Create sidechain ports when created from template (#0007680)
[ardour.git] / libs / ardour / disk_reader.cc
1 /*
2     Copyright (C) 2009-2016 Paul Davis
3
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.
8
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.
13
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.
17
18 */
19
20 #include <boost/smart_ptr/scoped_array.hpp>
21
22 #include "pbd/enumwriter.h"
23 #include "pbd/memento_command.h"
24
25 #include "ardour/audioengine.h"
26 #include "ardour/audioplaylist.h"
27 #include "ardour/audio_buffer.h"
28 #include "ardour/butler.h"
29 #include "ardour/debug.h"
30 #include "ardour/disk_reader.h"
31 #include "ardour/midi_ring_buffer.h"
32 #include "ardour/midi_playlist.h"
33 #include "ardour/midi_track.h"
34 #include "ardour/pannable.h"
35 #include "ardour/playlist.h"
36 #include "ardour/playlist_factory.h"
37 #include "ardour/session.h"
38 #include "ardour/session_playlists.h"
39
40 #include "pbd/i18n.h"
41
42 using namespace ARDOUR;
43 using namespace PBD;
44 using namespace std;
45
46 ARDOUR::samplecnt_t DiskReader::_chunk_samples = default_chunk_samples ();
47 PBD::Signal0<void> DiskReader::Underrun;
48 Sample* DiskReader::_mixdown_buffer = 0;
49 gain_t* DiskReader::_gain_buffer = 0;
50 samplecnt_t DiskReader::midi_readahead = 4096;
51 bool DiskReader::_no_disk_output = false;
52
53 DiskReader::DiskReader (Session& s, string const & str, DiskIOProcessor::Flag f)
54         : DiskIOProcessor (s, str, f)
55         , overwrite_sample (0)
56         , overwrite_offset (0)
57         , _pending_overwrite (false)
58         , overwrite_queued (false)
59         , _declick_gain (0)
60 {
61         file_sample[DataType::AUDIO] = 0;
62         file_sample[DataType::MIDI] = 0;
63 }
64
65 DiskReader::~DiskReader ()
66 {
67         DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskReader %1 @ %2 deleted\n", _name, this));
68
69         for (uint32_t n = 0; n < DataType::num_types; ++n) {
70                 if (_playlists[n]) {
71                         _playlists[n]->release ();
72                 }
73         }
74         delete _midi_buf;
75 }
76
77 void
78 DiskReader::ReaderChannelInfo::resize (samplecnt_t bufsize)
79 {
80         delete rbuf;
81         /* touch memory to lock it */
82         rbuf = new RingBufferNPT<Sample> (bufsize);
83         memset (rbuf->buffer(), 0, sizeof (Sample) * rbuf->bufsize());
84 }
85
86 int
87 DiskReader::add_channel_to (boost::shared_ptr<ChannelList> c, uint32_t how_many)
88 {
89         while (how_many--) {
90                 c->push_back (new ReaderChannelInfo (_session.butler()->audio_diskstream_playback_buffer_size()));
91                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: new reader channel, write space = %2 read = %3\n",
92                                                             name(),
93                                                             c->back()->rbuf->write_space(),
94                                                             c->back()->rbuf->read_space()));
95         }
96
97         return 0;
98 }
99
100 void
101 DiskReader::allocate_working_buffers()
102 {
103         /* with varifill buffer refilling, we compute the read size in bytes (to optimize
104            for disk i/o bandwidth) and then convert back into samples. These buffers
105            need to reflect the maximum size we could use, which is 4MB reads, or 2M samples
106            using 16 bit samples.
107         */
108         _mixdown_buffer       = new Sample[2*1048576];
109         _gain_buffer          = new gain_t[2*1048576];
110 }
111
112 void
113 DiskReader::free_working_buffers()
114 {
115         delete [] _mixdown_buffer;
116         delete [] _gain_buffer;
117         _mixdown_buffer       = 0;
118         _gain_buffer          = 0;
119 }
120
121 samplecnt_t
122 DiskReader::default_chunk_samples()
123 {
124         return 65536;
125 }
126
127 bool
128 DiskReader::set_name (string const & str)
129 {
130         string my_name = X_("player:");
131         my_name += str;
132
133         if (_name != my_name) {
134                 SessionObject::set_name (my_name);
135         }
136
137         return true;
138 }
139
140 XMLNode&
141 DiskReader::state ()
142 {
143         XMLNode& node (DiskIOProcessor::state ());
144         node.set_property(X_("type"), X_("diskreader"));
145         return node;
146 }
147
148 int
149 DiskReader::set_state (const XMLNode& node, int version)
150 {
151         if (DiskIOProcessor::set_state (node, version)) {
152                 return -1;
153         }
154
155         return 0;
156 }
157
158 void
159 DiskReader::realtime_handle_transport_stopped ()
160 {
161 }
162
163 void
164 DiskReader::realtime_locate ()
165 {
166 }
167
168 float
169 DiskReader::buffer_load () const
170 {
171         /* Note: for MIDI it's not trivial to differentiate the following two cases:
172
173            1.  The playback buffer is empty because the system has run out of time to fill it.
174            2.  The playback buffer is empty because there is no more data on the playlist.
175
176            If we use a simple buffer load computation, we will report that the MIDI diskstream
177            cannot keep up when #2 happens, when in fact it can.  Since MIDI data rates
178            are so low compared to audio, just use the audio value here.
179         */
180
181         boost::shared_ptr<ChannelList> c = channels.reader();
182
183         if (c->empty ()) {
184                 /* no channels, so no buffers, so completely full and ready to playback, sir! */
185                 return 1.0;
186         }
187
188         PBD::RingBufferNPT<Sample>* b = c->front()->rbuf;
189         return (float) ((double) b->read_space() / (double) b->bufsize());
190 }
191
192 void
193 DiskReader::adjust_buffering ()
194 {
195         boost::shared_ptr<ChannelList> c = channels.reader();
196
197         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
198                 (*chan)->resize (_session.butler()->audio_diskstream_playback_buffer_size());
199         }
200 }
201
202 void
203 DiskReader::playlist_changed (const PropertyChange&)
204 {
205         playlist_modified ();
206 }
207
208 void
209 DiskReader::playlist_modified ()
210 {
211         if (!i_am_the_modifier && !overwrite_queued) {
212                 _session.request_overwrite_buffer (_route);
213                 overwrite_queued = true;
214         }
215 }
216
217 int
218 DiskReader::use_playlist (DataType dt, boost::shared_ptr<Playlist> playlist)
219 {
220         bool prior_playlist = false;
221
222         if (_playlists[dt]) {
223                 prior_playlist = true;
224         }
225
226         if (DiskIOProcessor::use_playlist (dt, playlist)) {
227                 return -1;
228         }
229
230         /* don't do this if we've already asked for it *or* if we are setting up
231            the diskstream for the very first time - the input changed handling will
232            take care of the buffer refill.
233         */
234
235         if (!overwrite_queued && (prior_playlist || _session.loading())) {
236                 _session.request_overwrite_buffer (_route);
237                 overwrite_queued = true;
238         }
239
240         return 0;
241 }
242
243 void
244 DiskReader::run (BufferSet& bufs, samplepos_t start_sample, samplepos_t end_sample,
245                  double speed, pframes_t nframes, bool result_required)
246 {
247         uint32_t n;
248         boost::shared_ptr<ChannelList> c = channels.reader();
249         ChannelList::iterator chan;
250         sampleoffset_t disk_samples_to_consume;
251         MonitorState ms = _route->monitoring_state ();
252
253         if (_active) {
254                 if (!_pending_active) {
255                         _active = false;
256                         return;
257                 }
258         } else {
259                 if (_pending_active) {
260                         _active = true;
261                 } else {
262                         return;
263                 }
264         }
265
266         if ((speed == 0.0) && (ms == MonitoringDisk)) {
267                 /* no channels, or stopped. Don't accidentally pass any data
268                  * from disk into our outputs (e.g. via interpolation)
269                  */
270                 return;
271         }
272
273         BufferSet& scratch_bufs (_session.get_scratch_buffers (bufs.count()));
274         const bool still_locating = _session.global_locate_pending();
275
276         if (c->empty()) {
277                 /* do nothing with audio */
278                 goto midi;
279         }
280
281         assert (speed == -1 || speed == 0 || speed == 1);
282
283         if (speed < 0) {
284                 disk_samples_to_consume = -nframes;
285         } else if (speed > 0) {
286                 disk_samples_to_consume = nframes;
287         } else {
288                 disk_samples_to_consume = 0;
289         }
290
291         if (!result_required || ((ms & MonitoringDisk) == 0) || still_locating || _no_disk_output) {
292
293                 /* no need for actual disk data, just advance read pointer and return */
294
295                 if (!still_locating || _no_disk_output) {
296                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
297                                 (*chan)->rbuf->increment_read_ptr (disk_samples_to_consume);
298                         }
299                 }
300
301                 /* if monitoring disk but locating put silence in the buffers */
302
303                 if ((_no_disk_output || still_locating) && (ms == MonitoringDisk)) {
304                         bufs.silence (nframes, 0);
305                 }
306
307         } else {
308
309                 /* we need audio data from disk */
310
311                 size_t n_buffers = bufs.count().n_audio();
312                 size_t n_chans = c->size();
313                 gain_t scaling;
314
315                 if (n_chans > n_buffers) {
316                         scaling = ((float) n_buffers)/n_chans;
317                 } else {
318                         scaling = 1.0;
319                 }
320
321                 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
322
323                         ChannelInfo* chaninfo (*chan);
324                         AudioBuffer& output (bufs.get_audio (n%n_buffers));
325                         Sample* disk_signal = 0; /* assignment not really needed but it keeps the compiler quiet and helps track bugs */
326
327                         if (ms & MonitoringInput) {
328                                 /* put disk stream in scratch buffer, blend at end */
329                                 disk_signal = scratch_bufs.get_audio(n).data ();
330                         } else {
331                                 /* no input stream needed, just overwrite buffers */
332                                 disk_signal = output.data ();
333                         }
334
335                         if (speed > 0) {
336                                 if (start_sample < playback_sample) {
337                                         cerr << owner()->name() << " SS = " << start_sample << " PS = " << playback_sample << endl;
338                                         abort ();
339                                 }
340                         } else if (speed < 0) {
341                                 if (playback_sample < start_sample) {
342                                         cerr << owner()->name() << " SS = " << start_sample << " PS = " << playback_sample << " REVERSE" << endl;
343                                         abort ();
344                                 }
345                         }
346
347                         if ((speed > 0) && (start_sample != playback_sample)) {
348                                 stringstream str;
349                                 str << owner()->name() << " playback @ " << start_sample << " not aligned with " << playback_sample << " jump ahead " << (start_sample - playback_sample) << endl;
350                                 cerr << str.str();
351
352                                 if (can_internal_playback_seek (start_sample - playback_sample)) {
353                                         internal_playback_seek (start_sample - playback_sample);
354                                 } else {
355                                         cerr << owner()->name() << " playback not possible: ss = " << start_sample << " ps = " << playback_sample << endl;
356                                         goto midi;
357                                 }
358                         }
359
360                         chaninfo->rbuf->get_read_vector (&(*chan)->rw_vector);
361
362                         if (disk_samples_to_consume <= (samplecnt_t) chaninfo->rw_vector.len[0]) {
363
364                                 if (speed != 0.0) {
365                                         memcpy (disk_signal, chaninfo->rw_vector.buf[0], sizeof (Sample) * disk_samples_to_consume);
366                                 }
367
368                         } else {
369
370                                 const samplecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
371
372                                 if (disk_samples_to_consume <= total) {
373
374                                                 if (speed != 0.0) {
375                                                         memcpy (disk_signal,
376                                                         chaninfo->rw_vector.buf[0],
377                                                         chaninfo->rw_vector.len[0] * sizeof (Sample));
378                                                         memcpy (disk_signal + chaninfo->rw_vector.len[0],
379                                                         chaninfo->rw_vector.buf[1],
380                                                         (disk_samples_to_consume - chaninfo->rw_vector.len[0]) * sizeof (Sample));
381                                         }
382
383                                 } else {
384
385                                         cerr << _name << " Need " << disk_samples_to_consume << " total = " << total << endl;
386                                         cerr << "underrun for " << _name << endl;
387                                         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 underrun in %2, total space = %3\n",
388                                                                                     DEBUG_THREAD_SELF, name(), total));
389                                         Underrun ();
390                                         return;
391
392                                 }
393                         }
394
395                         if (scaling != 1.0f && speed != 0.0) {
396                                 apply_gain_to_buffer (disk_signal, disk_samples_to_consume, scaling);
397                         }
398
399                         chaninfo->rbuf->increment_read_ptr (disk_samples_to_consume);
400
401                         if (ms & MonitoringInput) {
402                                 /* mix the disk signal into the input signal (already in bufs) */
403                                 mix_buffers_no_gain (output.data(), disk_signal, disk_samples_to_consume);
404                         }
405                 }
406         }
407
408         /* MIDI data handling */
409
410   midi:
411         if (/*!_session.declick_out_pending() && */ bufs.count().n_midi()) {
412                 MidiBuffer* dst;
413
414                 if (_no_disk_output) {
415                         dst = &scratch_bufs.get_midi(0);
416                 } else {
417                         dst = &bufs.get_midi (0);
418                 }
419
420                 if ((ms & MonitoringDisk) && !still_locating) {
421                         get_midi_playback (*dst, start_sample, end_sample, ms, scratch_bufs, speed, disk_samples_to_consume);
422                 }
423         }
424
425         if (!still_locating) {
426
427                 bool butler_required = false;
428
429                 if (speed < 0.0) {
430                         playback_sample -= disk_samples_to_consume;
431                 } else {
432                         playback_sample += disk_samples_to_consume;
433                 }
434
435                 if (_playlists[DataType::AUDIO]) {
436                         if (!c->empty()) {
437                                 if (_slaved) {
438                                         if (c->front()->rbuf->write_space() >= c->front()->rbuf->bufsize() / 2) {
439                                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: slaved, write space = %2 of %3\n", name(), c->front()->rbuf->write_space(), c->front()->rbuf->bufsize()));
440                                                 butler_required = true;
441                                         }
442                                 } else {
443                                         if ((samplecnt_t) c->front()->rbuf->write_space() >= _chunk_samples) {
444                                                 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1: write space = %2 of %3\n", name(), c->front()->rbuf->write_space(),
445                                                                                             _chunk_samples));
446                                                 butler_required = true;
447                                         }
448                                 }
449                         }
450                 }
451
452                 if (_playlists[DataType::MIDI]) {
453                         /* MIDI butler needed part */
454
455                         uint32_t samples_read = g_atomic_int_get(const_cast<gint*>(&_samples_read_from_ringbuffer));
456                         uint32_t samples_written = g_atomic_int_get(const_cast<gint*>(&_samples_written_to_ringbuffer));
457
458                         /*
459                           cerr << name() << " MDS written: " << samples_written << " - read: " << samples_read <<
460                           " = " << samples_written - samples_read
461                           << " + " << disk_samples_to_consume << " < " << midi_readahead << " = " << need_butler << ")" << endl;
462                         */
463
464                         /* samples_read will generally be less than samples_written, but
465                          * immediately after an overwrite, we can end up having read some data
466                          * before we've written any. we don't need to trip an assert() on this,
467                          * but we do need to check so that the decision on whether or not we
468                          * need the butler is done correctly.
469                          */
470
471                         /* furthermore..
472                          *
473                          * Doing heavy GUI operations[1] can stall also the butler.
474                          * The RT-thread meanwhile will happily continue and
475                          * â€˜samples_read’ (from buffer to output) will become larger
476                          * than â€˜samples_written’ (from disk to buffer).
477                          *
478                          * The disk-stream is now behind..
479                          *
480                          * In those cases the butler needs to be summed to refill the buffer (done now)
481                          * AND we need to skip (samples_read - samples_written). ie remove old events
482                          * before playback_sample from the rinbuffer.
483                          *
484                          * [1] one way to do so is described at #6170.
485                          * For me just popping up the context-menu on a MIDI-track header
486                          * of a track with a large (think beethoven :) midi-region also did the
487                          * trick. The playhead stalls for 2 or 3 sec, until the context-menu shows.
488                          *
489                          * In both cases the root cause is that redrawing MIDI regions on the GUI is still very slow
490                          * and can stall
491                          */
492                         if (samples_read <= samples_written) {
493                                 if ((samples_written - samples_read) + disk_samples_to_consume < midi_readahead) {
494                                         butler_required = true;
495                                 }
496                         } else {
497                                 butler_required = true;
498                         }
499
500                 }
501
502                 _need_butler = butler_required;
503         }
504
505         // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 reader run, needs butler = %2\n", name(), _need_butler));
506 }
507
508 void
509 DiskReader::set_pending_overwrite (bool yn)
510 {
511         /* called from audio thread, so we can use the read ptr and playback sample as we wish */
512
513         _pending_overwrite = yn;
514
515         overwrite_sample = playback_sample;
516
517         boost::shared_ptr<ChannelList> c = channels.reader ();
518         if (!c->empty ()) {
519                 overwrite_offset = c->front()->rbuf->get_read_ptr();
520         }
521 }
522
523 int
524 DiskReader::overwrite_existing_buffers ()
525 {
526         int ret = -1;
527
528         boost::shared_ptr<ChannelList> c = channels.reader();
529
530         overwrite_queued = false;
531
532         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1 overwriting existing buffers at %2\n", overwrite_sample));
533
534         if (!c->empty ()) {
535
536                 /* AUDIO */
537
538                 const bool reversed = _session.transport_speed() < 0.0f;
539
540                 /* assume all are the same size */
541                 samplecnt_t size = c->front()->rbuf->bufsize();
542
543                 boost::scoped_array<Sample> mixdown_buffer (new Sample[size]);
544                 boost::scoped_array<float> gain_buffer (new float[size]);
545
546                 /* reduce size so that we can fill the buffer correctly (ringbuffers
547                    can only handle size-1, otherwise they appear to be empty)
548                 */
549                 size--;
550
551                 uint32_t n=0;
552                 samplepos_t start;
553
554                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
555
556                         start = overwrite_sample;
557                         samplecnt_t cnt = size;
558
559                         /* to fill the buffer without resetting the playback sample, we need to
560                            do it one or two chunks (normally two).
561
562                            |----------------------------------------------------------------------|
563
564                            ^
565                            overwrite_offset
566                            |<- second chunk->||<----------------- first chunk ------------------>|
567
568                         */
569
570                         samplecnt_t to_read = size - overwrite_offset;
571
572                         if (audio_read ((*chan)->rbuf->buffer() + overwrite_offset, mixdown_buffer.get(), gain_buffer.get(), start, to_read, n, reversed)) {
573                                 error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"),
574                                                         id(), size, playback_sample) << endmsg;
575                                 goto midi;
576                         }
577
578                         if (cnt > to_read) {
579
580                                 cnt -= to_read;
581
582                                 if (audio_read ((*chan)->rbuf->buffer(), mixdown_buffer.get(), gain_buffer.get(), start, cnt, n, reversed)) {
583                                         error << string_compose(_("DiskReader %1: when refilling, cannot read %2 from playlist at sample %3"),
584                                                                 id(), size, playback_sample) << endmsg;
585                                         goto midi;
586                                 }
587                         }
588                 }
589
590                 ret = 0;
591
592         }
593
594   midi:
595
596         if (_midi_buf && _playlists[DataType::MIDI]) {
597
598                 /* Clear the playback buffer contents.  This is safe as long as the butler
599                    thread is suspended, which it should be.
600                 */
601                 _midi_buf->reset ();
602                 _midi_buf->reset_tracker ();
603
604                 g_atomic_int_set (&_samples_read_from_ringbuffer, 0);
605                 g_atomic_int_set (&_samples_written_to_ringbuffer, 0);
606
607                 /* Resolve all currently active notes in the playlist.  This is more
608                    aggressive than it needs to be: ideally we would only resolve what is
609                    absolutely necessary, but this seems difficult and/or impossible without
610                    having the old data or knowing what change caused the overwrite.
611                 */
612                 midi_playlist()->resolve_note_trackers (*_midi_buf, overwrite_sample);
613
614                 midi_read (overwrite_sample, _chunk_samples, false);
615                 file_sample[DataType::MIDI] = overwrite_sample; // overwrite_sample was adjusted by ::midi_read() to the new position
616         }
617
618         _pending_overwrite = false;
619
620         return ret;
621 }
622
623 int
624 DiskReader::seek (samplepos_t sample, bool complete_refill)
625 {
626         uint32_t n;
627         int ret = -1;
628         ChannelList::iterator chan;
629         boost::shared_ptr<ChannelList> c = channels.reader();
630
631         //sample = std::max ((samplecnt_t)0, sample -_session.worst_output_latency ());
632
633         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
634                 (*chan)->rbuf->reset ();
635         }
636
637         if (g_atomic_int_get (&_samples_read_from_ringbuffer) == 0) {
638                 /* we haven't read anything since the last seek,
639                    so flush all note trackers to prevent
640                    wierdness
641                 */
642                 reset_tracker ();
643         }
644
645         _midi_buf->reset();
646         g_atomic_int_set(&_samples_read_from_ringbuffer, 0);
647         g_atomic_int_set(&_samples_written_to_ringbuffer, 0);
648
649         playback_sample = sample;
650         file_sample[DataType::AUDIO] = sample;
651         file_sample[DataType::MIDI] = sample;
652
653         if (complete_refill) {
654                 /* call _do_refill() to refill the entire buffer, using
655                    the largest reads possible.
656                 */
657                 while ((ret = do_refill_with_alloc (false)) > 0) ;
658         } else {
659                 /* call _do_refill() to refill just one chunk, and then
660                    return.
661                 */
662                 ret = do_refill_with_alloc (true);
663         }
664
665
666         return ret;
667 }
668
669 int
670 DiskReader::can_internal_playback_seek (samplecnt_t distance)
671 {
672         /* 1. Audio */
673
674         ChannelList::iterator chan;
675         boost::shared_ptr<ChannelList> c = channels.reader();
676
677         for (chan = c->begin(); chan != c->end(); ++chan) {
678                 if ((*chan)->rbuf->read_space() < (size_t) distance) {
679                         return false;
680                 }
681         }
682
683         /* 2. MIDI */
684
685         uint32_t samples_read    = g_atomic_int_get(&_samples_read_from_ringbuffer);
686         uint32_t samples_written = g_atomic_int_get(&_samples_written_to_ringbuffer);
687
688         return ((samples_written - samples_read) < distance);
689 }
690
691 int
692 DiskReader::internal_playback_seek (samplecnt_t distance)
693 {
694         ChannelList::iterator chan;
695         boost::shared_ptr<ChannelList> c = channels.reader();
696
697         for (chan = c->begin(); chan != c->end(); ++chan) {
698                 (*chan)->rbuf->increment_read_ptr (::llabs(distance));
699         }
700
701         playback_sample += distance;
702
703         return 0;
704 }
705
706 static
707 void swap_by_ptr (Sample *first, Sample *last)
708 {
709         while (first < last) {
710                 Sample tmp = *first;
711                 *first++ = *last;
712                 *last-- = tmp;
713         }
714 }
715
716 /** Read some data for 1 channel from our playlist into a buffer.
717  *  @param buf Buffer to write to.
718  *  @param start Session sample to start reading from; updated to where we end up
719  *         after the read.
720  *  @param cnt Count of samples to read.
721  *  @param reversed true if we are running backwards, otherwise false.
722  */
723 int
724 DiskReader::audio_read (Sample* buf, Sample* mixdown_buffer, float* gain_buffer,
725                         samplepos_t& start, samplecnt_t cnt,
726                         int channel, bool reversed)
727 {
728         samplecnt_t this_read = 0;
729         bool reloop = false;
730         samplepos_t loop_end = 0;
731         samplepos_t loop_start = 0;
732         samplecnt_t offset = 0;
733         Location *loc = 0;
734
735         if (!_playlists[DataType::AUDIO]) {
736                 memset (buf, 0, sizeof (Sample) * cnt);
737                 return 0;
738         }
739
740         /* XXX we don't currently play loops in reverse. not sure why */
741
742         if (!reversed) {
743
744                 samplecnt_t loop_length = 0;
745
746                 /* Make the use of a Location atomic for this read operation.
747
748                    Note: Locations don't get deleted, so all we care about
749                    when I say "atomic" is that we are always pointing to
750                    the same one and using a start/length values obtained
751                    just once.
752                 */
753
754                 if ((loc = _loop_location) != 0) {
755                         loop_start = loc->start();
756                         loop_end = loc->end();
757                         loop_length = loop_end - loop_start;
758                 }
759
760                 /* if we are looping, ensure that the first sample we read is at the correct
761                    position within the loop.
762                 */
763
764                 if (loc && start >= loop_end) {
765                         start = loop_start + ((start - loop_start) % loop_length);
766                 }
767
768         }
769
770         if (reversed) {
771                 start -= cnt;
772         }
773
774         /* We need this while loop in case we hit a loop boundary, in which case our read from
775            the playlist must be split into more than one section.
776         */
777
778         while (cnt) {
779
780                 /* take any loop into account. we can't read past the end of the loop. */
781
782                 if (loc && (loop_end - start < cnt)) {
783                         this_read = loop_end - start;
784                         reloop = true;
785                 } else {
786                         reloop = false;
787                         this_read = cnt;
788                 }
789
790                 if (this_read == 0) {
791                         break;
792                 }
793
794                 this_read = min(cnt,this_read);
795
796                 if (audio_playlist()->read (buf+offset, mixdown_buffer, gain_buffer, start, this_read, channel) != this_read) {
797                         error << string_compose(_("DiskReader %1: cannot read %2 from playlist at sample %3"), id(), this_read,
798                                          start) << endmsg;
799                         return -1;
800                 }
801
802                 if (reversed) {
803
804                         swap_by_ptr (buf, buf + this_read - 1);
805
806                 } else {
807
808                         /* if we read to the end of the loop, go back to the beginning */
809
810                         if (reloop) {
811                                 start = loop_start;
812                         } else {
813                                 start += this_read;
814                         }
815                 }
816
817                 cnt -= this_read;
818                 offset += this_read;
819         }
820
821         return 0;
822 }
823
824 int
825 DiskReader::_do_refill_with_alloc (bool partial_fill)
826 {
827         /* We limit disk reads to at most 4MB chunks, which with floating point
828            samples would be 1M samples. But we might use 16 or 14 bit samples,
829            in which case 4MB is more samples than that. Therefore size this for
830            the smallest sample value .. 4MB = 2M samples (16 bit).
831         */
832
833         {
834                 boost::scoped_array<Sample> mix_buf (new Sample[2*1048576]);
835                 boost::scoped_array<float>  gain_buf (new float[2*1048576]);
836
837                 int ret = refill_audio (mix_buf.get(), gain_buf.get(), (partial_fill ? _chunk_samples : 0));
838
839                 if (ret) {
840                         return ret;
841                 }
842         }
843
844         return refill_midi ();
845 }
846
847 int
848 DiskReader::refill (Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
849 {
850         int ret = refill_audio (mixdown_buffer, gain_buffer, fill_level);
851
852         if (ret) {
853                 return ret;
854         }
855
856         return refill_midi ();
857 }
858
859
860 /** Get some more data from disk and put it in our channels' bufs,
861  *  if there is suitable space in them.
862  *
863  * If fill_level is non-zero, then we will refill the buffer so that there is
864  * still at least fill_level samples of space left to be filled. This is used
865  * after locates so that we do not need to wait to fill the entire buffer.
866  *
867  */
868
869 int
870 DiskReader::refill_audio (Sample* mixdown_buffer, float* gain_buffer, samplecnt_t fill_level)
871 {
872         /* do not read from disk while session is marked as Loading, to avoid
873            useless redundant I/O.
874         */
875
876         if (_session.loading()) {
877                 return 0;
878         }
879
880         int32_t ret = 0;
881         samplecnt_t to_read;
882         RingBufferNPT<Sample>::rw_vector vector;
883         bool const reversed = _session.transport_speed() < 0.0f;
884         samplecnt_t total_space;
885         samplecnt_t zero_fill;
886         uint32_t chan_n;
887         ChannelList::iterator i;
888         boost::shared_ptr<ChannelList> c = channels.reader();
889         samplecnt_t ts;
890
891         if (c->empty()) {
892                 return 0;
893         }
894
895         assert(mixdown_buffer);
896         assert(gain_buffer);
897
898         vector.buf[0] = 0;
899         vector.len[0] = 0;
900         vector.buf[1] = 0;
901         vector.len[1] = 0;
902
903         c->front()->rbuf->get_write_vector (&vector);
904
905         if ((total_space = vector.len[0] + vector.len[1]) == 0) {
906                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: no space to refill\n", name()));
907                 /* nowhere to write to */
908                 return 0;
909         }
910
911         if (fill_level) {
912                 if (fill_level < total_space) {
913                         total_space -= fill_level;
914                 } else {
915                         /* we can't do anything with it */
916                         fill_level = 0;
917                 }
918         }
919
920         /* if we're running close to normal speed and there isn't enough
921            space to do disk_read_chunk_samples of I/O, then don't bother.
922
923            at higher speeds, just do it because the sync between butler
924            and audio thread may not be good enough.
925
926            Note: it is a design assumption that disk_read_chunk_samples is smaller
927            than the playback buffer size, so this check should never trip when
928            the playback buffer is empty.
929         */
930
931         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: space to refill %2 vs. chunk %3 (speed = %4)\n", name(), total_space, _chunk_samples, _session.transport_speed()));
932         if ((total_space < _chunk_samples) && fabs (_session.transport_speed()) < 2.0f) {
933                 return 0;
934         }
935
936         /* when slaved, don't try to get too close to the read pointer. this
937            leaves space for the buffer reversal to have something useful to
938            work with.
939         */
940
941         if (_slaved && total_space < (samplecnt_t) (c->front()->rbuf->bufsize() / 2)) {
942                 DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: not enough to refill while slaved\n", this));
943                 return 0;
944         }
945
946         samplepos_t ffa = file_sample[DataType::AUDIO];
947
948         if (reversed) {
949
950                 if (ffa == 0) {
951
952                         /* at start: nothing to do but fill with silence */
953
954                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
955
956                                 ChannelInfo* chan (*i);
957                                 chan->rbuf->get_write_vector (&vector);
958                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
959                                 if (vector.len[1]) {
960                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
961                                 }
962                                 chan->rbuf->increment_write_ptr (vector.len[0] + vector.len[1]);
963                         }
964                         return 0;
965                 }
966
967                 if (ffa < total_space) {
968
969                         /* too close to the start: read what we can,
970                            and then zero fill the rest
971                         */
972
973                         zero_fill = total_space - ffa;
974                         total_space = ffa;
975
976                 } else {
977
978                         zero_fill = 0;
979                 }
980
981         } else {
982
983                 if (ffa == max_samplepos) {
984
985                         /* at end: nothing to do but fill with silence */
986
987                         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
988
989                                 ChannelInfo* chan (*i);
990                                 chan->rbuf->get_write_vector (&vector);
991                                 memset (vector.buf[0], 0, sizeof(Sample) * vector.len[0]);
992                                 if (vector.len[1]) {
993                                         memset (vector.buf[1], 0, sizeof(Sample) * vector.len[1]);
994                                 }
995                                 chan->rbuf->increment_write_ptr (vector.len[0] + vector.len[1]);
996                         }
997                         return 0;
998                 }
999
1000                 if (ffa > max_samplepos - total_space) {
1001
1002                         /* to close to the end: read what we can, and zero fill the rest */
1003
1004                         zero_fill = total_space - (max_samplepos - ffa);
1005                         total_space = max_samplepos - ffa;
1006
1007                 } else {
1008                         zero_fill = 0;
1009                 }
1010         }
1011
1012         samplepos_t file_sample_tmp = 0;
1013
1014         /* total_space is in samples. We want to optimize read sizes in various sizes using bytes */
1015
1016         const size_t bits_per_sample = format_data_width (_session.config.get_native_file_data_format());
1017         size_t total_bytes = total_space * bits_per_sample / 8;
1018
1019         /* chunk size range is 256kB to 4MB. Bigger is faster in terms of MB/sec, but bigger chunk size always takes longer
1020          */
1021         size_t byte_size_for_read = max ((size_t) (256 * 1024), min ((size_t) (4 * 1048576), total_bytes));
1022
1023         /* find nearest (lower) multiple of 16384 */
1024
1025         byte_size_for_read = (byte_size_for_read / 16384) * 16384;
1026
1027         /* now back to samples */
1028
1029         samplecnt_t samples_to_read = byte_size_for_read / (bits_per_sample / 8);
1030
1031         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("%1: will refill %2 channels with %3 samples\n", name(), c->size(), total_space));
1032
1033         // uint64_t before = g_get_monotonic_time ();
1034         // uint64_t elapsed;
1035
1036         for (chan_n = 0, i = c->begin(); i != c->end(); ++i, ++chan_n) {
1037
1038                 ChannelInfo* chan (*i);
1039                 Sample* buf1;
1040                 Sample* buf2;
1041                 samplecnt_t len1, len2;
1042
1043                 chan->rbuf->get_write_vector (&vector);
1044
1045                 if ((samplecnt_t) vector.len[0] > samples_to_read) {
1046
1047                         /* we're not going to fill the first chunk, so certainly do not bother with the
1048                            other part. it won't be connected with the part we do fill, as in:
1049
1050                            .... => writable space
1051                            ++++ => readable space
1052                            ^^^^ => 1 x disk_read_chunk_samples that would be filled
1053
1054                            |......|+++++++++++++|...............................|
1055                            buf1                buf0
1056                                                 ^^^^^^^^^^^^^^^
1057
1058
1059                            So, just pretend that the buf1 part isn't there.
1060
1061                         */
1062
1063                         vector.buf[1] = 0;
1064                         vector.len[1] = 0;
1065
1066                 }
1067
1068                 ts = total_space;
1069                 file_sample_tmp = ffa;
1070
1071                 buf1 = vector.buf[0];
1072                 len1 = vector.len[0];
1073                 buf2 = vector.buf[1];
1074                 len2 = vector.len[1];
1075
1076                 to_read = min (ts, len1);
1077                 to_read = min (to_read, (samplecnt_t) samples_to_read);
1078
1079                 assert (to_read >= 0);
1080
1081                 if (to_read) {
1082
1083                         if (audio_read (buf1, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, chan_n, reversed)) {
1084                                 ret = -1;
1085                                 goto out;
1086                         }
1087                         chan->rbuf->increment_write_ptr (to_read);
1088                         ts -= to_read;
1089                 }
1090
1091                 to_read = min (ts, len2);
1092
1093                 if (to_read) {
1094
1095                         /* we read all of vector.len[0], but it wasn't the
1096                            entire samples_to_read of data, so read some or
1097                            all of vector.len[1] as well.
1098                         */
1099
1100                         if (audio_read (buf2, mixdown_buffer, gain_buffer, file_sample_tmp, to_read, chan_n, reversed)) {
1101                                 ret = -1;
1102                                 goto out;
1103                         }
1104
1105                         chan->rbuf->increment_write_ptr (to_read);
1106                 }
1107
1108                 if (zero_fill) {
1109                         /* XXX: do something */
1110                 }
1111
1112         }
1113
1114         // elapsed = g_get_monotonic_time () - before;
1115         // cerr << '\t' << name() << ": bandwidth = " << (byte_size_for_read / 1048576.0) / (elapsed/1000000.0) << "MB/sec\n";
1116
1117         file_sample[DataType::AUDIO] = file_sample_tmp;
1118         assert (file_sample[DataType::AUDIO] >= 0);
1119
1120         ret = ((total_space - samples_to_read) > _chunk_samples);
1121
1122         c->front()->rbuf->get_write_vector (&vector);
1123
1124   out:
1125         return ret;
1126 }
1127
1128 void
1129 DiskReader::playlist_ranges_moved (list< Evoral::RangeMove<samplepos_t> > const & movements_samples, bool from_undo)
1130 {
1131         /* If we're coming from an undo, it will have handled
1132            automation undo (it must, since automation-follows-regions
1133            can lose automation data).  Hence we can do nothing here.
1134         */
1135
1136         if (from_undo) {
1137                 return;
1138         }
1139
1140         if (!_route || Config->get_automation_follows_regions () == false) {
1141                 return;
1142         }
1143
1144         list< Evoral::RangeMove<double> > movements;
1145
1146         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin();
1147              i != movements_samples.end();
1148              ++i) {
1149
1150                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1151         }
1152
1153         /* move panner automation */
1154         boost::shared_ptr<Pannable> pannable = _route->pannable();
1155         Evoral::ControlSet::Controls& c (pannable->controls());
1156
1157         for (Evoral::ControlSet::Controls::iterator ci = c.begin(); ci != c.end(); ++ci) {
1158                 boost::shared_ptr<AutomationControl> ac = boost::dynamic_pointer_cast<AutomationControl>(ci->second);
1159                 if (!ac) {
1160                         continue;
1161                 }
1162                 boost::shared_ptr<AutomationList> alist = ac->alist();
1163                 if (!alist->size()) {
1164                         continue;
1165                 }
1166                 XMLNode & before = alist->get_state ();
1167                 bool const things_moved = alist->move_ranges (movements);
1168                 if (things_moved) {
1169                         _session.add_command (new MementoCommand<AutomationList> (
1170                                                       *alist.get(), &before, &alist->get_state ()));
1171                 }
1172         }
1173         /* move processor automation */
1174         _route->foreach_processor (boost::bind (&DiskReader::move_processor_automation, this, _1, movements_samples));
1175 }
1176
1177 void
1178 DiskReader::move_processor_automation (boost::weak_ptr<Processor> p, list< Evoral::RangeMove<samplepos_t> > const & movements_samples)
1179 {
1180         boost::shared_ptr<Processor> processor (p.lock ());
1181         if (!processor) {
1182                 return;
1183         }
1184
1185         list< Evoral::RangeMove<double> > movements;
1186         for (list< Evoral::RangeMove<samplepos_t> >::const_iterator i = movements_samples.begin(); i != movements_samples.end(); ++i) {
1187                 movements.push_back(Evoral::RangeMove<double>(i->from, i->length, i->to));
1188         }
1189
1190         set<Evoral::Parameter> const a = processor->what_can_be_automated ();
1191
1192         for (set<Evoral::Parameter>::const_iterator i = a.begin (); i != a.end (); ++i) {
1193                 boost::shared_ptr<AutomationList> al = processor->automation_control(*i)->alist();
1194                 if (!al->size()) {
1195                         continue;
1196                 }
1197                 XMLNode & before = al->get_state ();
1198                 bool const things_moved = al->move_ranges (movements);
1199                 if (things_moved) {
1200                         _session.add_command (
1201                                 new MementoCommand<AutomationList> (
1202                                         *al.get(), &before, &al->get_state ()
1203                                         )
1204                                 );
1205                 }
1206         }
1207 }
1208
1209 void
1210 DiskReader::reset_tracker ()
1211 {
1212         _midi_buf->reset_tracker ();
1213
1214         boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1215
1216         if (mp) {
1217                 mp->reset_note_trackers ();
1218         }
1219 }
1220
1221 void
1222 DiskReader::resolve_tracker (Evoral::EventSink<samplepos_t>& buffer, samplepos_t time)
1223 {
1224         _midi_buf->resolve_tracker(buffer, time);
1225
1226         boost::shared_ptr<MidiPlaylist> mp (midi_playlist());
1227
1228         if (mp) {
1229                 mp->reset_note_trackers ();
1230         }
1231 }
1232
1233 /** Writes playback events from playback_sample for nframes to dst, translating time stamps
1234  *  so that an event at playback_sample has time = 0
1235  */
1236 void
1237 DiskReader::get_midi_playback (MidiBuffer& dst, samplepos_t start_sample, samplepos_t end_sample, MonitorState ms, BufferSet& scratch_bufs, double speed, samplecnt_t disk_samples_to_consume)
1238 {
1239         MidiBuffer* target;
1240         samplepos_t nframes = end_sample - start_sample;
1241
1242         if ((ms & MonitoringInput) == 0) {
1243                 /* Route::process_output_buffers() clears the buffer as-needed */
1244                 target = &dst;
1245         } else {
1246                 target = &scratch_bufs.get_midi (0);
1247         }
1248
1249         if (ms & MonitoringDisk) {
1250                 /* disk data needed */
1251
1252                 Location* loc = _loop_location;
1253
1254                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1255                                      "%1 MDS pre-read read %8 offset = %9 @ %4..%5 from %2 write to %3, LOOPED ? %6 .. %7\n", _name,
1256                                      _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr(), start_sample, end_sample,
1257                                      (loc ? loc->start() : -1), (loc ? loc->end() : -1), nframes, Port::port_offset()));
1258
1259                 //cerr << "======== PRE ========\n";
1260                 //_midi_buf->dump (cerr);
1261                 //cerr << "----------------\n";
1262
1263                 size_t events_read = 0;
1264
1265                 if (loc) {
1266                         samplepos_t effective_start;
1267
1268                         Evoral::Range<samplepos_t> loop_range (loc->start(), loc->end() - 1);
1269                         effective_start = loop_range.squish (start_sample);
1270
1271                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("looped, effective start adjusted to %1\n", effective_start));
1272
1273                         if (effective_start == loc->start()) {
1274                                 /* We need to turn off notes that may extend
1275                                    beyond the loop end.
1276                                 */
1277
1278                                 _midi_buf->resolve_tracker (*target, 0);
1279                         }
1280
1281                         /* for split-cycles we need to offset the events */
1282
1283                         if (loc->end() >= effective_start && loc->end() < effective_start + nframes) {
1284
1285                                 /* end of loop is within the range we are reading, so
1286                                    split the read in two, and lie about the location
1287                                    for the 2nd read
1288                                 */
1289
1290                                 samplecnt_t first, second;
1291
1292                                 first = loc->end() - effective_start;
1293                                 second = nframes - first;
1294
1295                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read for eff %1 end %2: %3 and %4, cycle offset %5\n",
1296                                                                                       effective_start, loc->end(), first, second));
1297
1298                                 if (first) {
1299                                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #1, from %1 for %2\n",
1300                                                                                               effective_start, first));
1301                                         events_read = _midi_buf->read (*target, effective_start, first);
1302                                 }
1303
1304                                 if (second) {
1305                                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #2, from %1 for %2\n",
1306                                                                                               loc->start(), second));
1307                                         events_read += _midi_buf->read (*target, loc->start(), second);
1308                                 }
1309
1310                         } else {
1311                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("loop read #3, adjusted start as %1 for %2\n",
1312                                                                                       effective_start, nframes));
1313                                 events_read = _midi_buf->read (*target, effective_start, effective_start + nframes);
1314                         }
1315                 } else {
1316                         const size_t n_skipped = _midi_buf->skip_to (start_sample);
1317                         if (n_skipped > 0) {
1318                                 warning << string_compose(_("MidiDiskstream %1: skipped %2 events, possible underflow"), id(), n_skipped) << endmsg;
1319                         }
1320                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("playback buffer read, from %1 to %2 (%3)", start_sample, end_sample, nframes));
1321                         events_read = _midi_buf->read (*target, start_sample, end_sample, Port::port_offset ());
1322                 }
1323
1324                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose (
1325                                      "%1 MDS events read %2 range %3 .. %4 rspace %5 wspace %6 r@%7 w@%8\n",
1326                                      _name, events_read, playback_sample, playback_sample + nframes,
1327                                      _midi_buf->read_space(), _midi_buf->write_space(),
1328                                      _midi_buf->get_read_ptr(), _midi_buf->get_write_ptr()));
1329         }
1330
1331         g_atomic_int_add (&_samples_read_from_ringbuffer, nframes);
1332
1333         /* vari-speed */
1334         if (speed != 0.0 && fabsf (speed) != 1.0f) {
1335                 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1336                         MidiBuffer::TimeType *tme = i.timeptr();
1337                         // XXX need to subtract port offsets before scaling
1338                         // also we must only scale events read from disk
1339                         // and not existing input data in the buffer.
1340                         *tme = (*tme) * nframes / disk_samples_to_consume;
1341                 }
1342         }
1343
1344         if (ms & MonitoringInput) {
1345                 dst.merge_from (*target, nframes);
1346         }
1347
1348 #if 0
1349         if (!target->empty ()) {
1350                 cerr << "======== MIDI OUT ========\n";
1351                 for (MidiBuffer::iterator i = target->begin(); i != target->end(); ++i) {
1352                         const Evoral::Event<MidiBuffer::TimeType> ev (*i, false);
1353                         cerr << "MIDI EVENT (from disk) @ " << ev.time();
1354                         for (size_t xx = 0; xx < ev.size(); ++xx) {
1355                                 cerr << ' ' << hex << (int) ev.buffer()[xx];
1356                         }
1357                         cerr << dec << endl;
1358                 }
1359                 cerr << "----------------\n";
1360         }
1361 #endif
1362 #if 0
1363         cerr << "======== MIDI Disk Buffer ========\n";
1364         _midi_buf->dump (cerr);
1365         cerr << "----------------\n";
1366 #endif
1367 }
1368
1369 /** @a start is set to the new sample position (TIME) read up to */
1370 int
1371 DiskReader::midi_read (samplepos_t& start, samplecnt_t dur, bool reversed)
1372 {
1373         samplecnt_t this_read   = 0;
1374         samplepos_t loop_end    = 0;
1375         samplepos_t loop_start  = 0;
1376         samplecnt_t loop_length = 0;
1377         Location*  loc         = _loop_location;
1378         samplepos_t effective_start = start;
1379         Evoral::Range<samplepos_t>*  loop_range (0);
1380
1381         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS::midi_read @ %1 cnt %2\n", start, dur));
1382
1383         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
1384         MidiChannelFilter* filter = mt ? &mt->playback_filter() : 0;
1385         sampleoffset_t loop_offset = 0;
1386
1387         if (!reversed && loc) {
1388                 get_location_times (loc, &loop_start, &loop_end, &loop_length);
1389         }
1390
1391         while (dur) {
1392
1393                 /* take any loop into account. we can't read past the end of the loop. */
1394
1395                 if (loc && !reversed) {
1396
1397                         if (!loop_range) {
1398                                 loop_range = new Evoral::Range<samplepos_t> (loop_start, loop_end-1); // inclusive semantics require -1
1399                         }
1400
1401                         /* if we are (seamlessly) looping, ensure that the first sample we read is at the correct
1402                            position within the loop.
1403                         */
1404
1405                         effective_start = loop_range->squish (effective_start);
1406
1407                         if ((loop_end - effective_start) <= dur) {
1408                                 /* too close to end of loop to read "dur", so
1409                                    shorten it.
1410                                 */
1411                                 this_read = loop_end - effective_start;
1412                         } else {
1413                                 this_read = dur;
1414                         }
1415
1416                 } else {
1417                         this_read = dur;
1418                 }
1419
1420                 if (this_read == 0) {
1421                         break;
1422                 }
1423
1424                 this_read = min (dur,this_read);
1425
1426                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MDS ::read at %1 for %2 loffset %3\n", effective_start, this_read, loop_offset));
1427
1428                 if (midi_playlist()->read (*_midi_buf, effective_start, this_read, loop_range, 0, filter) != this_read) {
1429                         error << string_compose(
1430                                         _("MidiDiskstream %1: cannot read %2 from playlist at sample %3"),
1431                                         id(), this_read, start) << endmsg;
1432                         return -1;
1433                 }
1434
1435                 g_atomic_int_add (&_samples_written_to_ringbuffer, this_read);
1436
1437                 if (reversed) {
1438
1439                         // Swap note ons with note offs here.  etc?
1440                         // Fully reversing MIDI requires look-ahead (well, behind) to find previous
1441                         // CC values etc.  hard.
1442
1443                 } else {
1444
1445                         /* adjust passed-by-reference argument (note: this is
1446                            monotonic and does not reflect looping.
1447                         */
1448                         start += this_read;
1449
1450                         /* similarly adjust effective_start, but this may be
1451                            readjusted for seamless looping as we continue around
1452                            the loop.
1453                         */
1454                         effective_start += this_read;
1455                 }
1456
1457                 dur -= this_read;
1458         }
1459
1460         return 0;
1461 }
1462
1463 int
1464 DiskReader::refill_midi ()
1465 {
1466         if (!_playlists[DataType::MIDI]) {
1467                 return 0;
1468         }
1469
1470         const size_t  write_space = _midi_buf->write_space();
1471         const bool reversed    = _session.transport_speed() < 0.0f;
1472
1473         DEBUG_TRACE (DEBUG::DiskIO, string_compose ("MIDI refill, write space = %1 file sample = %2\n", write_space, file_sample[DataType::MIDI]));
1474
1475         /* no space to write */
1476         if (write_space == 0) {
1477                 return 0;
1478         }
1479
1480         if (reversed) {
1481                 return 0;
1482         }
1483
1484         /* at end: nothing to do */
1485
1486         samplepos_t ffm = file_sample[DataType::MIDI];
1487
1488         if (ffm == max_samplepos) {
1489                 return 0;
1490         }
1491
1492         int ret = 0;
1493         const uint32_t samples_read = g_atomic_int_get (&_samples_read_from_ringbuffer);
1494         const uint32_t samples_written = g_atomic_int_get (&_samples_written_to_ringbuffer);
1495
1496         if ((samples_read < samples_written) && (samples_written - samples_read) >= midi_readahead) {
1497                 return 0;
1498         }
1499
1500         samplecnt_t to_read = midi_readahead - ((samplecnt_t)samples_written - (samplecnt_t)samples_read);
1501
1502         to_read = min (to_read, (samplecnt_t) (max_samplepos - ffm));
1503         to_read = min (to_read, (samplecnt_t) write_space);
1504
1505         if (midi_read (ffm, to_read, reversed)) {
1506                 ret = -1;
1507         }
1508
1509         file_sample[DataType::MIDI] = ffm;
1510
1511         return ret;
1512 }
1513
1514 void
1515 DiskReader::set_no_disk_output (bool yn)
1516 {
1517         /* this MUST be called as part of the process call tree, before any
1518            disk readers are invoked. We use it when the session needs the
1519            transport (and thus effective read position for DiskReaders) to keep
1520            advancing as part of syncing up with a transport master, but we
1521            don't want any actual disk output yet because we are still not
1522            synced.
1523         */
1524         _no_disk_output = yn;
1525 }