* Fixed crash on closing MIDI automation tracks, because ARDOUR::Parameter::operator...
[ardour.git] / libs / ardour / ardour / midi_ring_buffer.h
1 /*
2     Copyright (C) 2006 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 #ifndef __ardour_midi_ring_buffer_h__
20 #define __ardour_midi_ring_buffer_h__
21
22 #include <iostream>
23 #include <algorithm>
24 #include <ardour/types.h>
25 #include <ardour/buffer.h>
26
27 namespace ARDOUR {
28
29
30 /* FIXME: this is probably too much inlined code */
31
32
33 /** A RingBuffer.
34  * Read/Write realtime safe.
35  * Single-reader Single-writer thread safe.
36  *
37  * This is Raul::RingBuffer, lifted for MIDIRingBuffer to inherit from as it works
38  * a bit differently than PBD::Ringbuffer.  This could/should be replaced with
39  * the PBD ringbuffer to decrease code size, but this code is tested and known to
40  * work, so here it sits for now...
41  *
42  * Ignore this class, use MidiRingBuffer.
43  */
44 template <typename T>
45 class MidiRingBufferBase {
46 public:
47
48         /** @param size Size in bytes.
49          */
50         MidiRingBufferBase(size_t size)
51                 : _size(size)
52                 , _buf(new T[size])
53         {
54                 reset();
55                 assert(read_space() == 0);
56                 assert(write_space() == size - 1);
57         }
58         
59         virtual ~MidiRingBufferBase() {
60                 delete[] _buf;
61         }
62
63         /** Reset(empty) the ringbuffer.
64          * NOT thread safe.
65          */
66         void reset() {
67                 g_atomic_int_set(&_write_ptr, 0);
68                 g_atomic_int_set(&_read_ptr, 0);
69         }
70
71         size_t write_space() const {
72                 
73                 const size_t w = g_atomic_int_get(&_write_ptr);
74                 const size_t r = g_atomic_int_get(&_read_ptr);
75                 
76                 if (w > r) {
77                         return ((r - w + _size) % _size) - 1;
78                 } else if (w < r) {
79                         return (r - w) - 1;
80                 } else {
81                         return _size - 1;
82                 }
83         }
84         
85         size_t read_space() const {
86                 
87                 const size_t w = g_atomic_int_get(&_write_ptr);
88                 const size_t r = g_atomic_int_get(&_read_ptr);
89                 
90                 if (w > r) {
91                         return w - r;
92                 } else {
93                         return (w - r + _size) % _size;
94                 }
95         }
96
97         size_t capacity() const { return _size; }
98
99         size_t peek(size_t size, T* dst);
100         bool   full_peek(size_t size, T* dst);
101
102         size_t read(size_t size, T* dst);
103         bool   full_read(size_t size, T* dst);
104
105         bool   skip(size_t size);
106         
107         void   write(size_t size, const T* src);
108
109 protected:
110         mutable int _write_ptr;
111         mutable int _read_ptr;
112         
113         size_t _size; ///< Size (capacity) in bytes
114         T*     _buf;  ///< size, event, size, event...
115 };
116
117
118 /** Peek at the ringbuffer (read w/o advancing read pointer).
119  *
120  * Note that a full read may not be done if the data wraps around.
121  * Caller must check return value and call again if necessary, or use the 
122  * full_peek method which does this automatically.
123  */
124 template<typename T>
125 size_t
126 MidiRingBufferBase<T>::peek(size_t size, T* dst)
127 {
128         const size_t priv_read_ptr = g_atomic_int_get(&_read_ptr);
129
130         const size_t read_size = (priv_read_ptr + size < _size)
131                         ? size
132                         : _size - priv_read_ptr;
133         
134         memcpy(dst, &_buf[priv_read_ptr], read_size);
135
136         return read_size;
137 }
138
139
140 template<typename T>
141 bool
142 MidiRingBufferBase<T>::full_peek(size_t size, T* dst)
143 {
144         if (read_space() < size) {
145                 return false;
146         }
147
148         const size_t read_size = peek(size, dst);
149         
150         if (read_size < size) {
151                 peek(size - read_size, dst + read_size);
152         }
153
154         return true;
155 }
156
157
158 /** Read from the ringbuffer.
159  *
160  * Note that a full read may not be done if the data wraps around.
161  * Caller must check return value and call again if necessary, or use the 
162  * full_read method which does this automatically.
163  */
164 template<typename T>
165 size_t
166 MidiRingBufferBase<T>::read(size_t size, T* dst)
167 {
168         const size_t priv_read_ptr = g_atomic_int_get(&_read_ptr);
169
170         const size_t read_size = (priv_read_ptr + size < _size)
171                         ? size
172                         : _size - priv_read_ptr;
173         
174         memcpy(dst, &_buf[priv_read_ptr], read_size);
175
176         g_atomic_int_set(&_read_ptr, (priv_read_ptr + read_size) % _size);
177
178         return read_size;
179 }
180
181
182 template<typename T>
183 bool
184 MidiRingBufferBase<T>::full_read(size_t size, T* dst)
185 {
186         if (read_space() < size) {
187                 return false;
188         }
189
190         const size_t read_size = read(size, dst);
191         
192         if (read_size < size) {
193                 read(size - read_size, dst + read_size);
194         }
195
196         return true;
197 }
198
199
200 template<typename T>
201 bool
202 MidiRingBufferBase<T>::skip(size_t size)
203 {
204         if (read_space() < size) {
205                 std::cerr << "WARNING: Attempt to skip past end of MIDI ring buffer" << std::endl;
206                 return false;
207         }
208         
209         const size_t priv_read_ptr = g_atomic_int_get(&_read_ptr);
210         g_atomic_int_set(&_read_ptr, (priv_read_ptr + size) % _size);
211
212         return true;
213 }
214
215
216
217 template<typename T>
218 inline void
219 MidiRingBufferBase<T>::write(size_t size, const T* src)
220 {
221         const size_t priv_write_ptr = g_atomic_int_get(&_write_ptr);
222         
223         if (priv_write_ptr + size <= _size) {
224                 memcpy(&_buf[priv_write_ptr], src, size);
225                 g_atomic_int_set(&_write_ptr, (priv_write_ptr + size) % _size);
226         } else {
227                 const size_t this_size = _size - priv_write_ptr;
228                 assert(this_size < size);
229                 assert(priv_write_ptr + this_size <= _size);
230                 memcpy(&_buf[priv_write_ptr], src, this_size);
231                 memcpy(&_buf[0], src+this_size, size - this_size);
232                 g_atomic_int_set(&_write_ptr, size - this_size);
233         }
234 }
235
236
237 /* ******************************************************************** */
238         
239
240 /** A MIDI RingBuffer.
241  *
242  * This is timestamps and MIDI packed sequentially into a single buffer, similarly
243  * to LV2 MIDI.  The buffer looks like this:
244  *
245  * [timestamp][size][size bytes of raw MIDI][timestamp][size][etc..]
246  */
247 class MidiRingBuffer : public MidiRingBufferBase<Byte> {
248 public:
249         /** @param size Size in bytes.
250          */
251         MidiRingBuffer(size_t size)
252                 : MidiRingBufferBase<Byte>(size), _channel_mask(0x0000FFFF)
253         {}
254
255         size_t write(double time, size_t size, const Byte* buf);
256         bool   read(double* time, size_t* size, Byte* buf);
257
258         bool   read_prefix(double* time, size_t* size);
259         bool   read_contents(size_t size, Byte* buf);
260
261         size_t read(MidiBuffer& dst, nframes_t start, nframes_t end, nframes_t offset=0);
262         
263         /** Set the channel filtering mode.
264          * @param mask If mode is FilterChannels, each bit represents a midi channel:
265          *     bit 0 = channel 0, bit 1 = channel 1 etc. the read and write methods will only
266          *     process events whose channel bit is 1.
267          *     If mode is ForceChannel, mask is simply a channel number which all events will
268          *     be forced to while reading.
269          */
270         void set_channel_mode(ChannelMode mode, uint16_t mask) {
271                 g_atomic_int_set(&_channel_mask, ((uint16_t)mode << 16) | mask);
272         }
273
274         ChannelMode get_channel_mode() const {
275                 return static_cast<ChannelMode>((g_atomic_int_get(&_channel_mask) & 0xFFFF0000) >> 16);
276         }
277         
278         uint16_t get_channel_mask() const {
279                 return static_cast<ChannelMode>((g_atomic_int_get(&_channel_mask) & 0x0000FFFF));
280         }
281         
282 protected:
283         inline bool is_channel_event(Byte event_type_byte) {
284                 // mask out channel information
285                 event_type_byte &= 0xF0;
286                 // midi channel events range from 0x80 to 0xE0
287                 return (0x80 <= event_type_byte) && (event_type_byte <= 0xE0);
288         }
289         
290 private:
291         volatile uint32_t _channel_mask; // 16 bits mode, 16 bits mask
292 };
293
294
295 inline bool
296 MidiRingBuffer::read(double* time, size_t* size, Byte* buf)
297 {
298         bool success = MidiRingBufferBase<Byte>::full_read(sizeof(double), (Byte*)time);
299         
300         if (success) {
301                 success = MidiRingBufferBase<Byte>::full_read(sizeof(size_t), (Byte*)size);
302         }
303         if (success) {
304                 success = MidiRingBufferBase<Byte>::full_read(*size, buf);
305         }
306         
307         return success;
308 }
309
310
311 /** Read the time and size of an event.  This call MUST be immediately proceeded
312  * by a call to read_contents (or the read pointer will be garabage).
313  */
314 inline bool
315 MidiRingBuffer::read_prefix(double* time, size_t* size)
316 {
317         bool success = MidiRingBufferBase<Byte>::full_read(sizeof(double), (Byte*)time);
318         if (success) {
319                 success = MidiRingBufferBase<Byte>::full_read(sizeof(size_t), (Byte*)size);
320         }
321
322         return success;
323 }
324
325
326 /** Read the contenst of an event.  This call MUST be immediately preceeded
327  * by a call to read_prefix (or the returned even will be garabage).
328  */
329 inline bool
330 MidiRingBuffer::read_contents(size_t size, Byte* buf)
331 {
332         return MidiRingBufferBase<Byte>::full_read(size, buf);
333 }
334
335
336 inline size_t
337 MidiRingBuffer::write(double time, size_t size, const Byte* buf)
338 {
339         /*fprintf(stderr, "MRB %p write (t = %f) ", this, time);
340         for (size_t i = 0; i < size; ++i)
341                 fprintf(stderr, "%X", (char)buf[i]);
342         fprintf(stderr, "\n");*/
343         
344         assert(size > 0);
345         
346         // Don't write event if it doesn't match channel filter
347         if (is_channel_event(buf[0]) && get_channel_mode() == FilterChannels) {
348                 Byte channel = buf[0] & 0x0F;
349                 if ( !(get_channel_mask() & (1L << channel)) ) {
350                         return 0;
351                 }
352         }
353
354         if (write_space() < (sizeof(double) + sizeof(size_t) + size)) {
355                 return 0;
356         } else {
357                 MidiRingBufferBase<Byte>::write(sizeof(double), (Byte*)&time);
358                 MidiRingBufferBase<Byte>::write(sizeof(size_t), (Byte*)&size);
359                 if (is_channel_event(buf[0]) && get_channel_mode() == ForceChannel) {
360                         assert(size == 2 || size == 3);
361                         Byte tmp_buf[3];
362                         // Force event to channel
363                         tmp_buf[0] = (buf[0] & 0xF0) | (get_channel_mask() & 0x0F);
364                         tmp_buf[1] = buf[1];
365                         if (size == 3) {
366                                 tmp_buf[2] = buf[2];
367                         }
368                         MidiRingBufferBase<Byte>::write(size, tmp_buf);
369                 } else {
370                         MidiRingBufferBase<Byte>::write(size, buf);
371                 }
372                 return size;
373         }
374
375 }
376
377
378 /** Read a block of MIDI events from buffer.
379  *
380  * Timestamps of events returned are relative to start (ie event with stamp 0
381  * occurred at start), with offset added.
382  */
383 inline size_t
384 MidiRingBuffer::read(MidiBuffer& dst, nframes_t start, nframes_t end, nframes_t offset)
385 {
386         if (read_space() == 0)
387                 return 0;
388
389         double   ev_time;
390         uint32_t ev_size;
391
392         size_t count = 0;
393
394         //printf("---- MRB read %u .. %u + %u\n", start, end, offset);
395
396         while (read_space() > sizeof(double) + sizeof(size_t)) {
397         
398                 full_peek(sizeof(double), (Byte*)&ev_time);
399         
400                 if (ev_time > end) {
401                         break;
402                 }
403                 
404                 bool success = MidiRingBufferBase<Byte>::full_read(sizeof(double), (Byte*)&ev_time);
405                 if (success) {
406                         success = MidiRingBufferBase<Byte>::full_read(sizeof(size_t), (Byte*)&ev_size);
407                 }
408
409                 if (!success) {
410                         std::cerr << "MRB: READ ERROR (time/size)" << std::endl;
411                         continue;
412                 }
413                 
414                 Byte status;
415                 success = full_peek(sizeof(Byte), &status);
416                 assert(success); // If this failed, buffer is corrupt, all hope is lost
417                 
418                 // Ignore event if it doesn't match channel filter
419                 if (is_channel_event(status) && get_channel_mode() == FilterChannels) {
420                         const Byte channel = status & 0x0F;
421                         if ( !(get_channel_mask() & (1L << channel)) ) {
422                                 skip(ev_size); // Advance read pointer to next event
423                                 continue;
424                         }
425                 }
426
427                 if (ev_time >= start) {
428
429                         /*std::cerr << "MRB " << this << " - Reading event, time = "
430                                 << ev_time << " - " << start << " => " << ev_time - start
431                                 << ", size = " << ev_size << std::endl;*/
432                         
433                         ev_time -= start;
434                         
435                         Byte* write_loc = dst.reserve(ev_time, ev_size);
436                         if (write_loc == NULL) {
437                                 std::cerr << "MRB: Unable to reserve space in buffer, event skipped";
438                                 continue;
439                         }
440                         
441                         success = MidiRingBufferBase<Byte>::full_read(ev_size, write_loc);
442                 
443                         if (success) {
444                                 if (is_channel_event(status) && get_channel_mode() == ForceChannel) {
445                                         write_loc[0] = (write_loc[0] & 0xF0) | (get_channel_mask() & 0x0F);
446                                 }
447                                 ++count;
448                                 //printf("MRB - read event at time %lf\n", ev_time);
449                         } else {
450                                 std::cerr << "MRB: READ ERROR (data)" << std::endl;
451                         }
452                         
453                 } else {
454                         printf("MRB (start %u) - Skipping event at (too early) time %f\n", start, ev_time);
455                 }
456         }
457         
458         //printf("(R) read space: %zu\n", read_space());
459
460         return count;
461 }
462
463
464 } // namespace ARDOUR
465
466 #endif // __ardour_midi_ring_buffer_h__
467