new file
[ardour.git] / libs / ardour / midi_buffer.cc
1 /*
2     Copyright (C) 2006-2007 Paul Davis
3     Author: David Robillard
4
5     This program is free software; you can redistribute it and/or modify it
6     under the terms of the GNU General Public License as published by the Free
7     Software Foundation; either version 2 of the License, or (at your option)
8     any later version.
9
10     This program is distributed in the hope that it will be useful, but WITHOUT
11     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13     for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include <iostream>
21
22 #include "pbd/malign.h"
23 #include "pbd/compose.h"
24 #include "pbd/debug.h"
25
26 #include "ardour/debug.h"
27 #include "ardour/midi_buffer.h"
28
29 using namespace std;
30 using namespace ARDOUR;
31 using namespace PBD;
32
33 // FIXME: mirroring for MIDI buffers?
34 MidiBuffer::MidiBuffer(size_t capacity)
35         : Buffer(DataType::MIDI, capacity)
36         , _data(0)
37 {
38         if (capacity) {
39                 resize(_capacity);
40                 silence(_capacity);
41         }
42 }
43
44 MidiBuffer::~MidiBuffer()
45 {
46         free(_data);
47 }
48
49 void
50 MidiBuffer::resize(size_t size)
51 {
52         assert(size > 0);
53
54         if (size < _capacity) {
55                 return;
56         }
57
58         free(_data);
59
60         _size = 0;
61         _capacity = size;
62         cache_aligned_malloc ((void**) &_data, _capacity);
63
64         assert(_data);
65 }
66
67 void
68 MidiBuffer::copy(const MidiBuffer& copy)
69 {
70         assert(_capacity >= copy._size);
71         _size = copy._size;
72         memcpy(_data, copy._data, copy._size);
73 }
74
75
76 /** Read events from @a src starting at time @a offset into the START of this buffer, for
77  * time duration @a nframes.  Relative time, where 0 = start of buffer.
78  *
79  * Note that offset and nframes refer to sample time, NOT buffer offsets or event counts.
80  */
81 void
82 MidiBuffer::read_from (const Buffer& src, framecnt_t nframes, framecnt_t dst_offset, framecnt_t src_offset)
83 {
84         assert (src.type() == DataType::MIDI);
85         assert (&src != this);
86
87         const MidiBuffer& msrc = (const MidiBuffer&) src;
88
89         assert (_capacity >= msrc.size());
90
91         if (dst_offset == 0) {
92                 clear ();
93                 assert (_size == 0);
94         }
95
96         /* XXX use dst_offset somehow */
97
98         for (MidiBuffer::const_iterator i = msrc.begin(); i != msrc.end(); ++i) {
99                 const Evoral::MIDIEvent<TimeType> ev(*i, false);
100                 if (ev.time() >= src_offset && ev.time() < (nframes+src_offset)) {
101                         push_back (ev);
102                 } else {
103                         cerr << "MIDI event @ " <<  ev.time() << " skipped, not within range "
104                              << src_offset << " .. " << (nframes + src_offset) << endl;
105                 }
106         }
107
108         _silent = src.silent();
109 }
110
111 void
112 MidiBuffer::merge_from (const Buffer& src, framecnt_t /*nframes*/, framecnt_t /*dst_offset*/, framecnt_t /*src_offset*/)
113 {
114         const MidiBuffer* mbuf = dynamic_cast<const MidiBuffer*>(&src);
115         assert (mbuf);
116         assert (mbuf != this);
117
118         /* XXX use nframes, and possible offsets */
119         merge_in_place (*mbuf);
120 }
121
122 /** Push an event into the buffer.
123  *
124  * Note that the raw MIDI pointed to by ev will be COPIED and unmodified.
125  * That is, the caller still owns it, if it needs freeing it's Not My Problem(TM).
126  * Realtime safe.
127  * @return false if operation failed (not enough room)
128  */
129 bool
130 MidiBuffer::push_back(const Evoral::MIDIEvent<TimeType>& ev)
131 {
132         const size_t stamp_size = sizeof(TimeType);
133
134         if (_size + stamp_size + ev.size() >= _capacity) {
135                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
136                 return false;
137         }
138
139         if (!Evoral::midi_event_is_valid(ev.buffer(), ev.size())) {
140                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
141                 return false;
142         }
143
144         push_back(ev.time(), ev.size(), ev.buffer());
145
146         return true;
147 }
148
149
150 /** Push an event into the buffer.
151  * @return false if operation failed (not enough room)
152  */
153 bool
154 MidiBuffer::push_back(TimeType time, size_t size, const uint8_t* data)
155 {
156         const size_t stamp_size = sizeof(TimeType);
157
158 #ifndef NDEBUG
159         if (DEBUG::MidiIO & PBD::debug_bits) {
160                 DEBUG_STR_DECL(a);
161                 DEBUG_STR_APPEND(a, string_compose ("midibuffer %1 push event @ %2 sz %3 ", this, time, size));
162                 for (size_t i=0; i < size; ++i) {
163                         DEBUG_STR_APPEND(a,hex);
164                         DEBUG_STR_APPEND(a,"0x");
165                         DEBUG_STR_APPEND(a,(int)data[i]);
166                         DEBUG_STR_APPEND(a,' ');
167                 }
168                 DEBUG_STR_APPEND(a,'\n');
169                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
170         }
171 #endif
172
173         if (_size + stamp_size + size >= _capacity) {
174                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
175                 return false;
176         }
177
178         if (!Evoral::midi_event_is_valid(data, size)) {
179                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
180                 return false;
181         }
182
183         uint8_t* const write_loc = _data + _size;
184         *((TimeType*)write_loc) = time;
185         memcpy(write_loc + stamp_size, data, size);
186
187         _size += stamp_size + size;
188         _silent = false;
189
190         return true;
191 }
192
193 /** Reserve space for a new event in the buffer.
194  *
195  * This call is for copying MIDI directly into the buffer, the data location
196  * (of sufficient size to write \a size bytes) is returned, or 0 on failure.
197  * This call MUST be immediately followed by a write to the returned data
198  * location, or the buffer will be corrupted and very nasty things will happen.
199  */
200 uint8_t*
201 MidiBuffer::reserve(TimeType time, size_t size)
202 {
203         const size_t stamp_size = sizeof(TimeType);
204         if (_size + stamp_size + size >= _capacity) {
205                 return 0;
206         }
207
208         // write timestamp
209         uint8_t* write_loc = _data + _size;
210         *((TimeType*)write_loc) = time;
211
212         // move write_loc to begin of MIDI buffer data to write to
213         write_loc += stamp_size;
214
215         _size += stamp_size + size;
216         _silent = false;
217
218         return write_loc;
219 }
220
221
222 void
223 MidiBuffer::silence (framecnt_t /*nframes*/, framecnt_t /*offset*/)
224 {
225         /* XXX iterate over existing events, find all in range given by offset & nframes,
226            and delete them.
227         */
228
229         _size = 0;
230         _silent = true;
231 }
232
233 bool
234 MidiBuffer::second_simultaneous_midi_byte_is_first (uint8_t a, uint8_t b)
235 {
236         bool b_first = false;
237
238         /* two events at identical times. we need to determine
239            the order in which they should occur.
240            
241            the rule is:
242            
243            Controller messages
244            Program Change
245            Note Off
246            Note On
247            Note Pressure
248            Channel Pressure
249            Pitch Bend
250         */
251         
252         if ((a) >= 0xf0 || (b) >= 0xf0 || ((a & 0xf) != (b & 0xf))) {
253                 
254                 /* if either message is not a channel message, or if the channels are
255                  * different, we don't care about the type.
256                  */
257                 
258                 b_first = true;
259                 
260         } else {
261                 
262                 switch (b & 0xf0) {
263                 case MIDI_CMD_CONTROL:
264                         b_first = true;
265                         break;
266                         
267                 case MIDI_CMD_PGM_CHANGE:
268                         switch (a & 0xf0) {
269                         case MIDI_CMD_CONTROL:
270                                 break;
271                         case MIDI_CMD_PGM_CHANGE:
272                         case MIDI_CMD_NOTE_OFF:
273                         case MIDI_CMD_NOTE_ON:
274                         case MIDI_CMD_NOTE_PRESSURE:
275                         case MIDI_CMD_CHANNEL_PRESSURE:
276                         case MIDI_CMD_BENDER:
277                                 b_first = true;
278                         }
279                         break;
280                         
281                 case MIDI_CMD_NOTE_OFF:
282                         switch (a & 0xf0) {
283                         case MIDI_CMD_CONTROL:
284                         case MIDI_CMD_PGM_CHANGE:
285                                 break;
286                         case MIDI_CMD_NOTE_OFF:
287                         case MIDI_CMD_NOTE_ON:
288                         case MIDI_CMD_NOTE_PRESSURE:
289                         case MIDI_CMD_CHANNEL_PRESSURE:
290                         case MIDI_CMD_BENDER:
291                                 b_first = true;
292                         }
293                         break;
294                         
295                 case MIDI_CMD_NOTE_ON:
296                         switch (a & 0xf0) {
297                         case MIDI_CMD_CONTROL:
298                         case MIDI_CMD_PGM_CHANGE:
299                         case MIDI_CMD_NOTE_OFF:
300                                 break;
301                         case MIDI_CMD_NOTE_ON:
302                         case MIDI_CMD_NOTE_PRESSURE:
303                         case MIDI_CMD_CHANNEL_PRESSURE:
304                         case MIDI_CMD_BENDER:
305                                 b_first = true;
306                         }
307                         break;
308                 case MIDI_CMD_NOTE_PRESSURE:
309                         switch (a & 0xf0) {
310                         case MIDI_CMD_CONTROL:
311                         case MIDI_CMD_PGM_CHANGE:
312                         case MIDI_CMD_NOTE_OFF:
313                         case MIDI_CMD_NOTE_ON:
314                                 break;
315                         case MIDI_CMD_NOTE_PRESSURE:
316                         case MIDI_CMD_CHANNEL_PRESSURE:
317                         case MIDI_CMD_BENDER:
318                                 b_first = true;
319                         }
320                         break;
321                         
322                 case MIDI_CMD_CHANNEL_PRESSURE:
323                         switch (a & 0xf0) {
324                         case MIDI_CMD_CONTROL:
325                         case MIDI_CMD_PGM_CHANGE:
326                         case MIDI_CMD_NOTE_OFF:
327                         case MIDI_CMD_NOTE_ON:
328                         case MIDI_CMD_NOTE_PRESSURE:
329                                 break;
330                         case MIDI_CMD_CHANNEL_PRESSURE:
331                         case MIDI_CMD_BENDER:
332                                 b_first = true;
333                         }
334                         break;
335                 case MIDI_CMD_BENDER:
336                         switch (a & 0xf0) {
337                         case MIDI_CMD_CONTROL:
338                         case MIDI_CMD_PGM_CHANGE:
339                         case MIDI_CMD_NOTE_OFF:
340                         case MIDI_CMD_NOTE_ON:
341                         case MIDI_CMD_NOTE_PRESSURE:
342                         case MIDI_CMD_CHANNEL_PRESSURE:
343                                 break;
344                         case MIDI_CMD_BENDER:
345                                 b_first = true;
346                         }
347                         break;
348                 }
349         }
350         
351         return b_first;
352 }
353         
354 /** Merge \a other into this buffer.  Realtime safe. */
355 bool
356 MidiBuffer::merge_in_place (const MidiBuffer &other)
357 {
358         if (other.size() && size()) {
359                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("merge in place, sizes %1/%2\n", size(), other.size()));
360         }
361
362         if (other.size() == 0) {
363                 return true;
364         }
365
366         if (size() == 0) {
367                 copy (other);
368                 return true;
369         }
370
371         if (size() + other.size() > _capacity) {
372                 return false;
373         }
374
375         const_iterator them = other.begin();
376         iterator us = begin();
377
378         while (them != other.end()) {
379
380                 size_t bytes_to_merge;
381                 ssize_t merge_offset;
382
383                 /* gather up total size of events that are earlier than
384                    the event referenced by "us"
385                 */
386
387                 merge_offset = -1;
388                 bytes_to_merge = 0;
389
390                 while (them != other.end() && (*them).time() < (*us).time()) {
391                         if (merge_offset == -1) {
392                                 merge_offset = them.offset;
393                         }
394                         bytes_to_merge += sizeof (TimeType) + (*them).size();
395                         ++them;
396                 }
397
398                 /* "them" now points to either:
399                  *
400                  * 1) an event that has the same or later timestamp than the
401                  *        event pointed to by "us"
402                  *
403                  * OR
404                  *
405                  * 2) the end of the "other" buffer
406                  *
407                  * if "sz" is non-zero, there is data to be merged from "other"
408                  * into this buffer before we do anything else, corresponding
409                  * to the events from "other" that we skipped while advancing
410                  * "them". 
411                  */
412
413                 if (bytes_to_merge) {
414                         assert(merge_offset >= 0);
415                         /* move existing */
416                         memmove (_data + us.offset + bytes_to_merge, _data + us.offset, _size - us.offset);
417                         /* increase _size */
418                         _size += bytes_to_merge;
419                         assert (_size <= _capacity);
420                         /* insert new stuff */
421                         memcpy  (_data + us.offset, other._data + merge_offset, bytes_to_merge);
422                         /* update iterator to our own events. this is a miserable hack */
423                         us.offset += bytes_to_merge;
424                 } 
425
426                 /* if we're at the end of the other buffer, we're done */
427
428                 if (them == other.end()) {
429                         break;
430                 }
431
432                 /* if we have two messages messages with the same timestamp. we
433                  * must order them correctly.
434                  */
435
436                 if ((*us).time() == (*them).time()) {
437
438                         DEBUG_TRACE (DEBUG::MidiIO, 
439                                      string_compose ("simultaneous MIDI events discovered during merge, times %1/%2 status %3/%4\n",
440                                                      (*us).time(), (*them).time(),
441                                                      (int) *(_data + us.offset + sizeof (TimeType)),
442                                                      (int) *(other._data + them.offset + sizeof (TimeType))));
443                         
444                         uint8_t our_midi_status_byte = *(_data + us.offset + sizeof (TimeType));
445                         uint8_t their_midi_status_byte = *(other._data + them.offset + sizeof (TimeType));
446                         bool them_first = second_simultaneous_midi_byte_is_first (our_midi_status_byte, their_midi_status_byte);
447                         
448                         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("other message came first ? %1\n", them_first));
449                         
450                         if (!them_first) {
451                                 /* skip past our own event */
452                                 ++us;
453                         }
454                                 
455                         bytes_to_merge = sizeof (TimeType) + (*them).size();
456                         
457                         /* move our remaining events later in the buffer by
458                          * enough to fit the one message we're going to merge
459                          */
460
461                         memmove (_data + us.offset + bytes_to_merge, _data + us.offset, _size - us.offset);
462                         /* increase _size */
463                         _size += bytes_to_merge;
464                         assert(_size <= _capacity);
465                         /* insert new stuff */
466                         memcpy  (_data + us.offset, other._data + them.offset, bytes_to_merge);
467                         /* update iterator to our own events. this is a miserable hack */
468                         us.offset += bytes_to_merge;
469                         /* 'us' is now an iterator to the event right after the
470                            new ones that we merged
471                         */
472                         if (them_first) {
473                                 /* need to skip the event pointed to by 'us'
474                                    since its at the same time as 'them'
475                                    (still), and we'll enter 
476                                 */
477
478                                 if (us != end()) {
479                                         ++us;
480                                 }
481                         }
482
483                         /* we merged one event from the other buffer, so
484                          * advance the iterator there.
485                          */
486
487                         ++them;
488
489                 } else {
490                         
491                         /* advance past our own events to get to the correct insertion
492                            point for the next event(s) from "other"
493                         */
494                 
495                         while (us != end() && (*us).time() <= (*them).time()) {
496                                 ++us;
497                         }
498                 }
499
500                 /* check to see if we reached the end of this buffer while
501                  * looking for the insertion point.
502                  */
503
504                 if (us == end()) {
505
506                         /* just append the rest of other and we're done*/
507                         
508                         memcpy (_data + us.offset, other._data + them.offset, other._size - them.offset);
509                         _size += other._size - them.offset;
510                         assert(_size <= _capacity);
511                         break;
512                 } 
513         }
514
515         return true;
516 }
517