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