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