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 , _need_butler (false)
54 , _gui_feed_buffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
55 , _frames_written_to_ringbuffer (0)
56 , _frames_read_from_ringbuffer (0)
60 DiskReader::~DiskReader ()
62 DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 deleted\n", _name));
63 Glib::Threads::Mutex::Lock lm (state_lock);
65 for (uint32_t n = 0; n < DataType::num_types; ++n) {
67 _playlists[n]->release ();
72 RCUWriter<ChannelList> writer (channels);
73 boost::shared_ptr<ChannelList> c = writer.get_copy();
75 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
88 DiskReader::allocate_working_buffers()
90 /* with varifill buffer refilling, we compute the read size in bytes (to optimize
91 for disk i/o bandwidth) and then convert back into samples. These buffers
92 need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
95 _mixdown_buffer = new Sample[2*1048576];
96 _gain_buffer = new gain_t[2*1048576];
100 DiskReader::free_working_buffers()
102 delete [] _mixdown_buffer;
103 delete [] _gain_buffer;
109 DiskReader::default_chunk_frames()
115 DiskReader::set_name (string const & str)
118 for (uint32_t n = 0; n < DataType::num_types; ++n) {
120 _playlists[n]->set_name (str);
123 SessionObject::set_name(str);
130 DiskReader::set_roll_delay (ARDOUR::framecnt_t nframes)
132 _roll_delay = nframes;
136 DiskReader::set_state (const XMLNode& node, int version)
138 XMLProperty const * prop;
140 if (DiskIOProcessor::set_state (node, version)) {
144 if ((prop = node.property ("audio-playlist")) == 0) {
148 if (find_and_use_playlist (DataType::AUDIO, prop->value())) {
152 if ((prop = node.property ("midi-playlist")) == 0) {
156 if (find_and_use_playlist (DataType::MIDI, prop->value())) {
163 /* Processor interface */
166 DiskReader::configure_io (ChanCount in, ChanCount out)
168 Glib::Threads::Mutex::Lock lm (state_lock);
170 RCUWriter<ChannelList> writer (channels);
171 boost::shared_ptr<ChannelList> c = writer.get_copy();
173 uint32_t n_audio = in.n_audio();
175 if (n_audio > c->size()) {
176 add_channel_to (c, n_audio - c->size());
177 } else if (n_audio < c->size()) {
178 remove_channel_from (c, c->size() - n_audio);
181 if (in.n_midi() > 0 && !_midi_buf) {
182 const size_t size = _session.butler()->midi_diskstream_buffer_size();
183 _midi_buf = new MidiRingBuffer<framepos_t>(size);
184 midi_interpolation.add_channel_to (0,0);
187 Processor::configure_io (in, out);
193 DiskReader::can_support_io_configuration (const ChanCount& in, ChanCount& out)
195 if (in.n_midi() != 0 && in.n_midi() != 1) {
196 /* we only support zero or 1 MIDI stream */
201 /* currently no way to deliver different channels that we receive */
209 DiskReader::realtime_handle_transport_stopped ()
214 DiskReader::realtime_locate ()
219 DiskReader::set_loop (Location *location)
222 if (location->start() >= location->end()) {
223 error << string_compose(_("Location \"%1\" not valid for track loop (start >= end)"), location->name()) << endl;
228 loop_location = location;
230 LoopSet (location); /* EMIT SIGNAL */
235 DiskReader::buffer_load () const
237 /* Note: for MIDI it's not trivial to differentiate the following two cases:
239 1. The playback buffer is empty because the system has run out of time to fill it.
240 2. The playback buffer is empty because there is no more data on the playlist.
242 If we use a simple buffer load computation, we will report that the MIDI diskstream
243 cannot keep up when #2 happens, when in fact it can. Since MIDI data rates
244 are so low compared to audio, just use the audio value here.
247 boost::shared_ptr<ChannelList> c = channels.reader();
250 /* no channels, so no buffers, so completely full and ready to playback, sir! */
254 PBD::RingBufferNPT<Sample> * b = c->front()->buf;
255 return (float) ((double) b->read_space() / (double) b->bufsize());
259 DiskReader::adjust_buffering ()
261 boost::shared_ptr<ChannelList> c = channels.reader();
263 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
264 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
268 DiskReader::ChannelInfo::ChannelInfo (framecnt_t bufsize, framecnt_t speed_size, framecnt_t wrap_size)
272 speed_buffer = new Sample[speed_size];
273 wrap_buffer = new Sample[wrap_size];
275 buf = new RingBufferNPT<Sample> (bufsize);
277 /* touch the ringbuffer buffer, which will cause
278 them to be mapped into locked physical RAM if
279 we're running with mlockall(). this doesn't do
283 memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
287 DiskReader::ChannelInfo::resize (framecnt_t bufsize)
290 buf = new RingBufferNPT<Sample> (bufsize);
291 memset (buf->buffer(), 0, sizeof (Sample) * buf->bufsize());
294 DiskReader::ChannelInfo::~ChannelInfo ()
296 delete [] speed_buffer;
299 delete [] wrap_buffer;
307 DiskReader::set_block_size (pframes_t /*nframes*/)
309 if (_session.get_block_size() > speed_buffer_size) {
310 speed_buffer_size = _session.get_block_size();
311 boost::shared_ptr<ChannelList> c = channels.reader();
313 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
314 delete [] (*chan)->speed_buffer;
315 (*chan)->speed_buffer = new Sample[speed_buffer_size];
318 allocate_temporary_buffers ();
323 DiskReader::allocate_temporary_buffers ()
325 /* make sure the wrap buffer is at least large enough to deal
326 with the speeds up to 1.2, to allow for micro-variation
327 when slaving to MTC, Timecode etc.
330 double const sp = max (fabs (_actual_speed), 1.2);
331 framecnt_t required_wrap_size = (framecnt_t) ceil (_session.get_block_size() * sp) + 2;
333 if (required_wrap_size > wrap_buffer_size) {
335 boost::shared_ptr<ChannelList> c = channels.reader();
337 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
338 if ((*chan)->wrap_buffer) {
339 delete [] (*chan)->wrap_buffer;
341 (*chan)->wrap_buffer = new Sample[required_wrap_size];
344 wrap_buffer_size = required_wrap_size;
350 DiskReader::playlist_changed (const PropertyChange&)
352 playlist_modified ();
356 DiskReader::playlist_modified ()
358 if (!i_am_the_modifier && !overwrite_queued) {
359 // !!!! _session.request_overwrite_buffer (this);
360 overwrite_queued = true;
365 DiskReader::playlist_deleted (boost::weak_ptr<Playlist> wpl)
367 boost::shared_ptr<Playlist> pl (wpl.lock());
373 for (uint32_t n = 0; n < DataType::num_types; ++n) {
374 if (pl == _playlists[n]) {
376 /* this catches an ordering issue with session destruction. playlists
377 are destroyed before disk readers. we have to invalidate any handles
378 we have to the playlist.
380 _playlists[n].reset ();
386 boost::shared_ptr<AudioPlaylist>
387 DiskReader::audio_playlist () const
389 return boost::dynamic_pointer_cast<AudioPlaylist> (_playlists[DataType::AUDIO]);
392 boost::shared_ptr<MidiPlaylist>
393 DiskReader::midi_playlist () const
395 return boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
399 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
405 bool prior_playlist = false;
408 Glib::Threads::Mutex::Lock lm (state_lock);
410 if (playlist == _playlists[dt]) {
414 playlist_connections.drop_connections ();
416 if (_playlists[dt]) {
417 _playlists[dt]->release();
418 prior_playlist = true;
421 _playlists[dt] = playlist;
424 playlist->ContentsChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
425 playlist->LayeringChanged.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_modified, this));
426 playlist->DropReferences.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_deleted, this, boost::weak_ptr<Playlist>(playlist)));
427 playlist->RangesMoved.connect_same_thread (playlist_connections, boost::bind (&DiskReader::playlist_ranges_moved, this, _1, _2));
430 /* don't do this if we've already asked for it *or* if we are setting up
431 the diskstream for the very first time - the input changed handling will
432 take care of the buffer refill.
435 if (!overwrite_queued && prior_playlist) {
436 // !!! _session.request_overwrite_buffer (this);
437 overwrite_queued = true;
440 PlaylistChanged (dt); /* EMIT SIGNAL */
441 _session.set_dirty ();
447 DiskReader::find_and_use_playlist (DataType dt, const string& name)
449 boost::shared_ptr<Playlist> playlist;
451 if ((playlist = _session.playlists->by_name (name)) == 0) {
452 playlist = PlaylistFactory::create (dt, _session, name);
456 error << string_compose(_("DiskReader: \"%1\" isn't an playlist"), name) << endmsg;
460 return use_playlist (dt, playlist);
464 DiskReader::use_new_playlist (DataType dt)
467 boost::shared_ptr<Playlist> playlist = _playlists[dt];
470 newname = Playlist::bump_name (playlist->name(), _session);
472 newname = Playlist::bump_name (_name, _session);
475 playlist = boost::dynamic_pointer_cast<AudioPlaylist> (PlaylistFactory::create (dt, _session, newname, hidden()));
481 return use_playlist (dt, playlist);
485 DiskReader::use_copy_playlist (DataType dt)
487 assert (_playlists[dt]);
489 if (_playlists[dt] == 0) {
490 error << string_compose(_("DiskReader %1: there is no existing playlist to make a copy of!"), _name) << endmsg;
495 boost::shared_ptr<Playlist> playlist;
497 newname = Playlist::bump_name (_playlists[dt]->name(), _session);
499 if ((playlist = PlaylistFactory::create (_playlists[dt], newname)) == 0) {
503 playlist->reset_shares();
505 return use_playlist (dt, playlist);
509 /** Do some record stuff [not described in this comment!]
512 * - Setup playback_distance with the nframes, or nframes adjusted
513 * for current varispeed, if appropriate.
514 * - Setup current_buffer in each ChannelInfo to point to data
515 * that someone can read playback_distance worth of data from.
518 DiskReader::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
519 double speed, pframes_t nframes, bool result_required)
522 boost::shared_ptr<ChannelList> c = channels.reader();
523 ChannelList::iterator chan;
524 framecnt_t playback_distance = 0;
526 Glib::Threads::Mutex::Lock sm (state_lock, Glib::Threads::TRY_LOCK);
532 for (chan = c->begin(); chan != c->end(); ++chan) {
533 (*chan)->current_buffer = 0;
536 const bool need_disk_signal = result_required || _monitoring_choice == MonitorDisk || _monitoring_choice == MonitorCue;
538 if (need_disk_signal) {
540 /* we're doing playback */
542 framecnt_t necessary_samples;
544 if (_actual_speed != 1.0) {
545 necessary_samples = (framecnt_t) ceil ((nframes * fabs (_actual_speed))) + 2;
547 necessary_samples = nframes;
550 for (chan = c->begin(); chan != c->end(); ++chan) {
551 (*chan)->buf->get_read_vector (&(*chan)->read_vector);
556 /* Setup current_buffer in each ChannelInfo to point to data that someone
557 can read necessary_samples (== nframes at a transport speed of 1) worth of data
561 for (chan = c->begin(); chan != c->end(); ++chan, ++n) {
563 ChannelInfo* chaninfo (*chan);
565 if (necessary_samples <= (framecnt_t) chaninfo->read_vector.len[0]) {
566 /* There are enough samples in the first part of the ringbuffer */
567 chaninfo->current_buffer = chaninfo->read_vector.buf[0];
570 framecnt_t total = chaninfo->read_vector.len[0] + chaninfo->read_vector.len[1];
572 if (necessary_samples > total) {
573 cerr << _name << " Need " << necessary_samples << " total = " << total << endl;
574 cerr << "underrun for " << _name << endl;
575 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
576 DEBUG_THREAD_SELF, name(), total));
582 /* We have enough samples, but not in one lump. Coalesce the two parts
583 into one in wrap_buffer in our ChannelInfo, and specify that
584 as our current_buffer.
587 assert(wrap_buffer_size >= necessary_samples);
589 /* Copy buf[0] from buf */
590 memcpy ((char *) chaninfo->wrap_buffer,
591 chaninfo->read_vector.buf[0],
592 chaninfo->read_vector.len[0] * sizeof (Sample));
594 /* Copy buf[1] from buf */
595 memcpy (chaninfo->wrap_buffer + chaninfo->read_vector.len[0],
596 chaninfo->read_vector.buf[1],
597 (necessary_samples - chaninfo->read_vector.len[0])
600 chaninfo->current_buffer = chaninfo->wrap_buffer;
605 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
607 interpolation.set_speed (_target_speed);
610 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
611 ChannelInfo* chaninfo (*chan);
613 playback_distance = interpolation.interpolate (
614 channel, nframes, chaninfo->current_buffer, chaninfo->speed_buffer);
616 chaninfo->current_buffer = chaninfo->speed_buffer;
620 playback_distance = nframes;
623 _speed = _target_speed;
626 if (need_disk_signal) {
628 /* copy data over to buffer set */
630 size_t n_buffers = bufs.count().n_audio();
631 size_t n_chans = c->size();
632 gain_t scaling = 1.0f;
634 if (n_chans > n_buffers) {
635 scaling = ((float) n_buffers)/n_chans;
638 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
640 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
641 ChannelInfo* chaninfo (*chan);
644 if (scaling != 1.0f) {
645 buf.read_from_with_gain (chaninfo->current_buffer, nframes, scaling);
647 buf.read_from (chaninfo->current_buffer, nframes);
650 if (scaling != 1.0f) {
651 buf.accumulate_with_gain_from (chaninfo->current_buffer, nframes, scaling);
653 buf.accumulate_from (chaninfo->current_buffer, nframes);
658 /* extra buffers will already be silent, so leave them alone */
661 _need_butler = false;
663 if (_actual_speed < 0.0) {
664 playback_sample -= playback_distance;
666 playback_sample += playback_distance;
669 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
670 (*chan)->buf->increment_read_ptr (playback_distance);
675 if (c->front()->buf->write_space() >= c->front()->buf->bufsize() / 2) {
679 if ((framecnt_t) c->front()->buf->write_space() >= _chunk_frames) {
685 /* MIDI data handling */
687 if (_actual_speed != 1.0f && _target_speed > 0) {
689 interpolation.set_speed (_target_speed);
691 playback_distance = midi_interpolation.distance (nframes);
694 playback_distance = nframes;
697 if (need_disk_signal && !_session.declick_out_pending()) {
699 /* copy the diskstream data to all output buffers */
701 MidiBuffer& mbuf (bufs.get_midi (0));
702 get_playback (mbuf, playback_distance);
704 /* leave the audio count alone */
705 ChanCount cnt (DataType::MIDI, 1);
706 cnt.set (DataType::AUDIO, bufs.count().n_audio());
707 bufs.set_count (cnt);
710 if (_target_speed > 0 && _actual_speed != 1.0f) {
711 MidiBuffer& mbuf (bufs.get_midi (0));
712 for (MidiBuffer::iterator i = mbuf.begin(); i != mbuf.end(); ++i) {
713 MidiBuffer::TimeType *tme = i.timeptr();
714 *tme = (*tme) * nframes / playback_distance;
719 /* MIDI butler needed part */
721 uint32_t frames_read = g_atomic_int_get(const_cast<gint*>(&_frames_read_from_ringbuffer));
722 uint32_t frames_written = g_atomic_int_get(const_cast<gint*>(&_frames_written_to_ringbuffer));
725 cerr << name() << " MDS written: " << frames_written << " - read: " << frames_read <<
726 " = " << frames_written - frames_read
727 << " + " << playback_distance << " < " << midi_readahead << " = " << need_butler << ")" << endl;
730 /* frames_read will generally be less than frames_written, but
731 * immediately after an overwrite, we can end up having read some data
732 * before we've written any. we don't need to trip an assert() on this,
733 * but we do need to check so that the decision on whether or not we
734 * need the butler is done correctly.
739 * Doing heavy GUI operations[1] can stall also the butler.
740 * The RT-thread meanwhile will happily continue and
741 * ‘frames_read’ (from buffer to output) will become larger
742 * than ‘frames_written’ (from disk to buffer).
744 * The disk-stream is now behind..
746 * In those cases the butler needs to be summed to refill the buffer (done now)
747 * AND we need to skip (frames_read - frames_written). ie remove old events
748 * before playback_sample from the rinbuffer.
750 * [1] one way to do so is described at #6170.
751 * For me just popping up the context-menu on a MIDI-track header
752 * of a track with a large (think beethoven :) midi-region also did the
753 * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
755 * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
758 if (frames_read <= frames_written) {
759 if ((frames_written - frames_read) + playback_distance < midi_readahead) {
766 /* make sure bufs shows whatever data we had available */
769 cnt.set (DataType::MIDI, 1);
770 cnt.set (DataType::AUDIO, bufs.count().n_audio());
771 bufs.set_count (cnt);
775 DiskReader::calculate_playback_distance (pframes_t nframes)
777 frameoffset_t playback_distance = nframes;
779 if (_actual_speed != 1.0f && _actual_speed != -1.0f) {
780 interpolation.set_speed (_target_speed);
781 boost::shared_ptr<ChannelList> c = channels.reader();
783 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++channel) {
784 playback_distance = interpolation.interpolate (channel, nframes, NULL, NULL);
787 playback_distance = nframes;
790 if (_actual_speed < 0.0) {
791 return -playback_distance;
793 return playback_distance;
798 DiskReader::set_pending_overwrite (bool yn)
800 /* called from audio thread, so we can use the read ptr and playback sample as we wish */
802 _pending_overwrite = yn;
804 overwrite_frame = playback_sample;
806 boost::shared_ptr<ChannelList> c = channels.reader ();
808 overwrite_offset = c->front()->buf->get_read_ptr();
813 DiskReader::overwrite_existing_buffers ()
817 boost::shared_ptr<ChannelList> c = channels.reader();
819 overwrite_queued = false;
825 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
827 /* assume all are the same size */
828 framecnt_t size = c->front()->buf->bufsize();
830 std::auto_ptr<Sample> mixdown_buffer (new Sample[size]);
831 std::auto_ptr<float> gain_buffer (new float[size]);
833 /* reduce size so that we can fill the buffer correctly (ringbuffers
834 can only handle size-1, otherwise they appear to be empty)
841 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
843 start = overwrite_frame;
844 framecnt_t cnt = size;
846 /* to fill the buffer without resetting the playback sample, we need to
847 do it one or two chunks (normally two).
849 |----------------------------------------------------------------------|
853 |<- second chunk->||<----------------- first chunk ------------------>|
857 framecnt_t to_read = size - overwrite_offset;
859 if (audio_read ((*chan)->buf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
860 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
861 id(), size, playback_sample) << endmsg;
869 if (audio_read ((*chan)->buf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
870 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at frame %3"),
871 id(), size, playback_sample) << endmsg;
883 if (_midi_buf && _playlists[DataType::MIDI]) {
885 /* Clear the playback buffer contents. This is safe as long as the butler
886 thread is suspended, which it should be.
889 _midi_buf->reset_tracker ();
891 g_atomic_int_set (&_frames_read_from_ringbuffer, 0);
892 g_atomic_int_set (&_frames_written_to_ringbuffer, 0);
894 /* Resolve all currently active notes in the playlist. This is more
895 aggressive than it needs to be: ideally we would only resolve what is
896 absolutely necessary, but this seems difficult and/or impossible without
897 having the old data or knowing what change caused the overwrite.
899 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_frame);
901 midi_read (overwrite_frame, _chunk_frames, false);
903 file_frame = overwrite_frame; // it was adjusted by ::midi_read()
906 _pending_overwrite = false;
912 DiskReader::non_realtime_locate (framepos_t location)
914 /* now refill channel buffers */
916 if (speed() != 1.0f || speed() != -1.0f) {
917 seek ((framepos_t) (location * (double) speed()), true);
919 seek (location, true);
924 DiskReader::seek (framepos_t frame, bool complete_refill)
928 ChannelList::iterator chan;
929 boost::shared_ptr<ChannelList> c = channels.reader();
931 Glib::Threads::Mutex::Lock lm (state_lock);
933 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
934 (*chan)->buf->reset ();
937 if (g_atomic_int_get (&_frames_read_from_ringbuffer) == 0) {
938 /* we haven't read anything since the last seek,
939 so flush all note trackers to prevent
946 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
947 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
949 playback_sample = frame;
952 if (complete_refill) {
953 /* call _do_refill() to refill the entire buffer, using
954 the largest reads possible.
956 while ((ret = do_refill_with_alloc (false)) > 0) ;
958 /* call _do_refill() to refill just one chunk, and then
961 ret = do_refill_with_alloc (true);
969 DiskReader::can_internal_playback_seek (framecnt_t distance)
973 ChannelList::iterator chan;
974 boost::shared_ptr<ChannelList> c = channels.reader();
976 for (chan = c->begin(); chan != c->end(); ++chan) {
977 if ((*chan)->buf->read_space() < (size_t) distance) {
984 uint32_t frames_read = g_atomic_int_get(&_frames_read_from_ringbuffer);
985 uint32_t frames_written = g_atomic_int_get(&_frames_written_to_ringbuffer);
987 return ((frames_written - frames_read) < distance);
991 DiskReader::internal_playback_seek (framecnt_t distance)
993 ChannelList::iterator chan;
994 boost::shared_ptr<ChannelList> c = channels.reader();
996 for (chan = c->begin(); chan != c->end(); ++chan) {
997 (*chan)->buf->increment_read_ptr (::llabs(distance));
1000 playback_sample += distance;
1006 void swap_by_ptr (Sample *first, Sample *last)
1008 while (first < last) {
1009 Sample tmp = *first;
1015 /** Read some data for 1 channel from our playlist into a buffer.
1016 * @param buf Buffer to write to.
1017 * @param start Session frame to start reading from; updated to where we end up
1019 * @param cnt Count of samples to read.
1020 * @param reversed true if we are running backwards, otherwise false.
1023 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
1024 framepos_t& start, framecnt_t cnt,
1025 int channel, bool reversed)
1027 framecnt_t this_read = 0;
1028 bool reloop = false;
1029 framepos_t loop_end = 0;
1030 framepos_t loop_start = 0;
1031 framecnt_t offset = 0;
1034 /* XXX we don't currently play loops in reverse. not sure why */
1038 framecnt_t loop_length = 0;
1040 /* Make the use of a Location atomic for this read operation.
1042 Note: Locations don't get deleted, so all we care about
1043 when I say "atomic" is that we are always pointing to
1044 the same one and using a start/length values obtained
1048 if ((loc = loop_location) != 0) {
1049 loop_start = loc->start();
1050 loop_end = loc->end();
1051 loop_length = loop_end - loop_start;
1054 /* if we are looping, ensure that the first frame we read is at the correct
1055 position within the loop.
1058 if (loc && start >= loop_end) {
1059 start = loop_start + ((start - loop_start) % loop_length);
1068 /* We need this while loop in case we hit a loop boundary, in which case our read from
1069 the playlist must be split into more than one section.
1074 /* take any loop into account. we can't read past the end of the loop. */
1076 if (loc && (loop_end - start < cnt)) {
1077 this_read = loop_end - start;
1084 if (this_read == 0) {
1088 this_read = min(cnt,this_read);
1090 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
1091 error << string_compose(_("DiskReader %1: cannot read %2 from playlist at frame %3"), id(), this_read,
1098 swap_by_ptr (buf, buf + this_read - 1);
1102 /* if we read to the end of the loop, go back to the beginning */
1112 offset += this_read;
1119 DiskReader::_do_refill_with_alloc (bool partial_fill)
1121 /* We limit disk reads to at most 4MB chunks, which with floating point
1122 samples would be 1M samples. But we might use 16 or 14 bit samples,
1123 in which case 4MB is more samples than that. Therefore size this for
1124 the smallest sample value .. 4MB = 2M samples (16 bit).
1128 std::auto_ptr<Sample> mix_buf (new Sample[2*1048576]);
1129 std::auto_ptr<float> gain_buf (new float[2*1048576]);
1131 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_frames : 0));
1138 return refill_midi ();
1142 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1144 int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
1150 return refill_midi ();
1154 /** Get some more data from disk and put it in our channels' bufs,
1155 * if there is suitable space in them.
1157 * If fill_level is non-zero, then we will refill the buffer so that there is
1158 * still at least fill_level samples of space left to be filled. This is used
1159 * after locates so that we do not need to wait to fill the entire buffer.
1164 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, framecnt_t fill_level)
1166 if (_session.state_of_the_state() & Session::Loading) {
1172 RingBufferNPT<Sample>::rw_vector vector;
1173 bool const reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1174 framecnt_t total_space;
1175 framecnt_t zero_fill;
1177 ChannelList::iterator i;
1178 boost::shared_ptr<ChannelList> c = channels.reader();
1181 /* do not read from disk while session is marked as Loading, to avoid
1182 useless redundant I/O.
1189 assert(mixdown_buffer);
1190 assert(gain_buffer);
1197 c->front()->buf->get_write_vector (&vector);
1199 if ((total_space = vector.len[0] + vector.len[1]) == 0) {
1200 /* nowhere to write to */
1205 if (fill_level < total_space) {
1206 total_space -= fill_level;
1208 /* we can't do anything with it */
1213 /* if we're running close to normal speed and there isn't enough
1214 space to do disk_read_chunk_frames of I/O, then don't bother.
1216 at higher speeds, just do it because the sync between butler
1217 and audio thread may not be good enough.
1219 Note: it is a design assumption that disk_read_chunk_frames is smaller
1220 than the playback buffer size, so this check should never trip when
1221 the playback buffer is empty.
1224 if ((total_space < _chunk_frames) && fabs (_actual_speed) < 2.0f) {
1228 /* when slaved, don't try to get too close to the read pointer. this
1229 leaves space for the buffer reversal to have something useful to
1233 if (_slaved && total_space < (framecnt_t) (c->front()->buf->bufsize() / 2)) {
1239 if (file_frame == 0) {
1241 /* at start: nothing to do but fill with silence */
1243 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1245 ChannelInfo* chan (*i);
1246 chan->buf->get_write_vector (&vector);
1247 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1248 if (vector.len[1]) {
1249 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1251 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1256 if (file_frame < total_space) {
1258 /* too close to the start: read what we can,
1259 and then zero fill the rest
1262 zero_fill = total_space - file_frame;
1263 total_space = file_frame;
1272 if (file_frame == max_framepos) {
1274 /* at end: nothing to do but fill with silence */
1276 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1278 ChannelInfo* chan (*i);
1279 chan->buf->get_write_vector (&vector);
1280 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
1281 if (vector.len[1]) {
1282 memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
1284 chan->buf->increment_write_ptr (vector.len[0] + vector.len[1]);
1289 if (file_frame > max_framepos - total_space) {
1291 /* to close to the end: read what we can, and zero fill the rest */
1293 zero_fill = total_space - (max_framepos - file_frame);
1294 total_space = max_framepos - file_frame;
1301 framepos_t file_frame_tmp = 0;
1303 /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1305 const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1306 size_t total_bytes = total_space * bits_per_sample / 8;
1308 /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1310 size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1312 /* find nearest (lower) multiple of 16384 */
1314 byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1316 /* now back to samples */
1318 framecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1320 //cerr << name() << " will read " << byte_size_for_read << " out of total bytes " << total_bytes << " in buffer of "
1321 // << c->front()->buf->bufsize() * bits_per_sample / 8 << " bps = " << bits_per_sample << endl;
1322 // cerr << name () << " read samples = " << samples_to_read << " out of total space " << total_space << " in buffer of " << c->front()->buf->bufsize() << " samples\n";
1324 // uint64_t before = g_get_monotonic_time ();
1325 // uint64_t elapsed;
1327 for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1329 ChannelInfo* chan (*i);
1332 framecnt_t len1, len2;
1334 chan->buf->get_write_vector (&vector);
1336 if ((framecnt_t) vector.len[0] > samples_to_read) {
1338 /* we're not going to fill the first chunk, so certainly do not bother with the
1339 other part. it won't be connected with the part we do fill, as in:
1341 .... => writable space
1342 ++++ => readable space
1343 ^^^^ => 1 x disk_read_chunk_frames that would be filled
1345 |......|+++++++++++++|...............................|
1350 So, just pretend that the buf1 part isn't there.
1360 file_frame_tmp = file_frame;
1362 buf1 = vector.buf[0];
1363 len1 = vector.len[0];
1364 buf2 = vector.buf[1];
1365 len2 = vector.len[1];
1367 to_read = min (ts, len1);
1368 to_read = min (to_read, (framecnt_t) samples_to_read);
1370 assert (to_read >= 0);
1374 if (audio_read (buf1, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1379 chan->buf->increment_write_ptr (to_read);
1383 to_read = min (ts, len2);
1387 /* we read all of vector.len[0], but it wasn't the
1388 entire samples_to_read of data, so read some or
1389 all of vector.len[1] as well.
1392 if (audio_read (buf2, mixdown_buffer, gain_buffer, file_frame_tmp, to_read, chan_n, reversed)) {
1397 chan->buf->increment_write_ptr (to_read);
1401 /* XXX: do something */
1406 // elapsed = g_get_monotonic_time () - before;
1407 // cerr << "\tbandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1409 file_frame = file_frame_tmp;
1410 assert (file_frame >= 0);
1412 ret = ((total_space - samples_to_read) > _chunk_frames);
1414 c->front()->buf->get_write_vector (&vector);
1421 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<framepos_t> > const & movements_frames, bool from_undo)
1423 /* If we're coming from an undo, it will have handled
1424 automation undo (it must, since automation-follows-regions
1425 can lose automation data). Hence we can do nothing here.
1433 if (!_track || Config->get_automation_follows_regions () == false) {
1437 list< Evoral::RangeMove<double> > movements;
1439 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin();
1440 i != movements_frames.end();
1443 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1446 /* move panner automation */
1447 boost::shared_ptr<Pannable> pannable = _track->pannable();
1448 Evoral::ControlSet::Controls& c (pannable->controls());
1450 for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1451 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1455 boost::shared_ptr<AutomationList> alist = ac->alist();
1456 if (!alist->size()) {
1459 XMLNode & before = alist->get_state ();
1460 bool const things_moved = alist->move_ranges (movements);
1462 _session.add_command (new MementoCommand<AutomationList> (
1463 *alist.get(), &before, &alist->get_state ()));
1466 /* move processor automation */
1467 _track->foreach_processor (boost::bind (&Diskstream::move_processor_automation, this, _1, movements_frames));
1472 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<framepos_t> > const & movements_frames)
1474 boost::shared_ptr<Processor> processor (p.lock ());
1479 list< Evoral::RangeMove<double> > movements;
1480 for (list< Evoral::RangeMove<framepos_t> >::const_iterator i = movements_frames.begin(); i != movements_frames.end(); ++i) {
1481 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1484 set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1486 for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1487 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1491 XMLNode & before = al->get_state ();
1492 bool const things_moved = al->move_ranges (movements);
1494 _session.add_command (
1495 new MementoCommand<AutomationList> (
1496 *al.get(), &before, &al->get_state ()
1503 boost::shared_ptr<MidiBuffer>
1504 DiskReader::get_gui_feed_buffer () const
1506 boost::shared_ptr<MidiBuffer> b (new MidiBuffer (AudioEngine::instance()->raw_buffer_size (DataType::MIDI)));
1508 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex);
1509 b->copy (_gui_feed_buffer);
1514 DiskReader::reset_tracker ()
1516 _midi_buf->reset_tracker ();
1518 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1521 mp->reset_note_trackers ();
1526 DiskReader::resolve_tracker (Evoral::EventSink<framepos_t>& buffer, framepos_t time)
1528 _midi_buf->resolve_tracker(buffer, time);
1530 boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1533 mp->reset_note_trackers ();
1538 DiskReader::flush_playback (framepos_t start, framepos_t end)
1540 _midi_buf->flush (start, end);
1541 g_atomic_int_add (&_frames_read_from_ringbuffer, end - start);
1544 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1545 * so that an event at playback_sample has time = 0
1548 DiskReader::get_playback (MidiBuffer& dst, framecnt_t nframes)
1552 Location* loc = loop_location;
1554 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1555 "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1556 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), playback_sample, playback_sample + nframes,
1557 (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1559 //cerr << "======== PRE ========\n";
1560 //_midi_buf->dump (cerr);
1561 //cerr << "----------------\n";
1563 size_t events_read = 0;
1566 framepos_t effective_start;
1568 Evoral::Range<framepos_t> loop_range (loc->start(), loc->end() - 1);
1569 effective_start = loop_range.squish (playback_sample);
1571 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1573 if (effective_start == loc->start()) {
1574 /* We need to turn off notes that may extend
1575 beyond the loop end.
1578 _midi_buf->resolve_tracker (dst, 0);
1581 /* for split-cycles we need to offset the events */
1583 if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1585 /* end of loop is within the range we are reading, so
1586 split the read in two, and lie about the location
1590 framecnt_t first, second;
1592 first = loc->end() - effective_start;
1593 second = nframes - first;
1595 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1596 effective_start, loc->end(), first, second));
1599 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1600 effective_start, first));
1601 events_read = _midi_buf->read (dst, effective_start, first);
1605 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1606 loc->start(), second));
1607 events_read += _midi_buf->read (dst, loc->start(), second);
1611 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1612 effective_start, nframes));
1613 events_read = _midi_buf->read (dst, effective_start, effective_start + nframes);
1616 const size_t n_skipped = _midi_buf->skip_to (playback_sample);
1617 if (n_skipped > 0) {
1618 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1620 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", playback_sample, playback_sample + nframes, nframes));
1621 events_read = _midi_buf->read (dst, playback_sample, playback_sample + nframes);
1624 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1625 "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1626 _name, events_read, playback_sample, playback_sample + nframes,
1627 _midi_buf->read_space(), _midi_buf->write_space(),
1628 _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1630 g_atomic_int_add (&_frames_read_from_ringbuffer, nframes);
1632 //cerr << "======== POST ========\n";
1633 //_midi_buf->dump (cerr);
1634 //cerr << "----------------\n";
1637 /** Get the start, end, and length of a location "atomically".
1639 * Note: Locations don't get deleted, so all we care about when I say "atomic"
1640 * is that we are always pointing to the same one and using start/length values
1641 * obtained just once. Use this function to achieve this since location being
1642 * a parameter achieves this.
1645 get_location_times(const Location* location,
1651 *start = location->start();
1652 *end = location->end();
1653 *length = *end - *start;
1657 /** @a start is set to the new frame position (TIME) read up to */
1659 DiskReader::midi_read (framepos_t& start, framecnt_t dur, bool reversed)
1661 framecnt_t this_read = 0;
1662 framepos_t loop_end = 0;
1663 framepos_t loop_start = 0;
1664 framecnt_t loop_length = 0;
1665 Location* loc = loop_location;
1666 framepos_t effective_start = start;
1667 Evoral::Range<framepos_t>* loop_range (0);
1669 // MidiTrack* mt = dynamic_cast<MidiTrack*>(_track);
1670 // MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1671 MidiChannelFilter* filter = 0;
1673 frameoffset_t loop_offset = 0;
1675 if (!reversed && loc) {
1676 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1681 /* take any loop into account. we can't read past the end of the loop. */
1683 if (loc && !reversed) {
1686 loop_range = new Evoral::Range<framepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1689 /* if we are (seamlessly) looping, ensure that the first frame we read is at the correct
1690 position within the loop.
1693 effective_start = loop_range->squish (effective_start);
1695 if ((loop_end - effective_start) <= dur) {
1696 /* too close to end of loop to read "dur", so
1699 this_read = loop_end - effective_start;
1708 if (this_read == 0) {
1712 this_read = min (dur,this_read);
1714 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1716 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1717 error << string_compose(
1718 _("MidiDiskstream %1: cannot read %2 from playlist at frame %3"),
1719 id(), this_read, start) << endmsg;
1723 g_atomic_int_add (&_frames_written_to_ringbuffer, this_read);
1727 // Swap note ons with note offs here. etc?
1728 // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1729 // CC values etc. hard.
1733 /* adjust passed-by-reference argument (note: this is
1734 monotonic and does not reflect looping.
1738 /* similarly adjust effective_start, but this may be
1739 readjusted for seamless looping as we continue around
1742 effective_start += this_read;
1746 //offset += this_read;
1753 DiskReader::refill_midi ()
1756 size_t write_space = _midi_buf->write_space();
1757 bool reversed = (_visible_speed * _session.transport_speed()) < 0.0f;
1759 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS refill, write space = %1 file frame = %2\n",
1760 write_space, file_frame));
1762 /* no space to write */
1763 if (write_space == 0) {
1771 /* at end: nothing to do */
1772 if (file_frame == max_framepos) {
1776 uint32_t frames_read = g_atomic_int_get (&_frames_read_from_ringbuffer);
1777 uint32_t frames_written = g_atomic_int_get (&_frames_written_to_ringbuffer);
1779 if ((frames_read < frames_written) && (frames_written - frames_read) >= midi_readahead) {
1783 framecnt_t to_read = midi_readahead - ((framecnt_t)frames_written - (framecnt_t)frames_read);
1785 to_read = min (to_read, (framecnt_t) (max_framepos - file_frame));
1786 to_read = min (to_read, (framecnt_t) write_space);
1788 if (midi_read (file_frame, to_read, reversed)) {