provide semantic ordering of simultaneous MIDI events; add operator== to MidiBuffer...
[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 = (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         /*cerr << "MidiBuffer: pushing event @ " << ev.time()
134                 << " size = " << ev.size() << endl;*/
135
136         if (_size + stamp_size + ev.size() >= _capacity) {
137                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
138                 return false;
139         }
140
141         if (!Evoral::midi_event_is_valid(ev.buffer(), ev.size())) {
142                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
143                 return false;
144         }
145
146         push_back(ev.time(), ev.size(), ev.buffer());
147
148         return true;
149 }
150
151
152 /** Push an event into the buffer.
153  * @return false if operation failed (not enough room)
154  */
155 bool
156 MidiBuffer::push_back(TimeType time, size_t size, const uint8_t* data)
157 {
158         const size_t stamp_size = sizeof(TimeType);
159
160 #ifndef NDEBUG
161         if (DEBUG::MidiIO & PBD::debug_bits) {
162                 DEBUG_STR_DECL(a);
163                 DEBUG_STR_APPEND(a, string_compose ("midibuffer %1 push event @ %2 sz %3 ", this, time, size));
164                 for (size_t i=0; i < size; ++i) {
165                         DEBUG_STR_APPEND(a,hex);
166                         DEBUG_STR_APPEND(a,"0x");
167                         DEBUG_STR_APPEND(a,(int)data[i]);
168                         DEBUG_STR_APPEND(a,' ');
169                 }
170                 DEBUG_STR_APPEND(a,'\n');
171                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
172         }
173 #endif
174
175         if (_size + stamp_size + size >= _capacity) {
176                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
177                 return false;
178         }
179
180         if (!Evoral::midi_event_is_valid(data, size)) {
181                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
182                 return false;
183         }
184
185         uint8_t* const write_loc = _data + _size;
186         *((TimeType*)write_loc) = time;
187         memcpy(write_loc + stamp_size, data, size);
188
189         _size += stamp_size + size;
190         _silent = false;
191
192         return true;
193 }
194
195
196 /** Push an event into the buffer.
197  *
198  * Note that the raw MIDI pointed to by ev will be COPIED and unmodified.
199  * That is, the caller still owns it, if it needs freeing it's Not My Problem(TM).
200  * Realtime safe.
201  * @return false if operation failed (not enough room)
202  */
203 bool
204 MidiBuffer::push_back(const jack_midi_event_t& ev)
205 {
206         const size_t stamp_size = sizeof(TimeType);
207         if (_size + stamp_size + ev.size >= _capacity) {
208                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
209                 return false;
210         }
211
212         if (!Evoral::midi_event_is_valid(ev.buffer, ev.size)) {
213                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
214                 return false;
215         }
216
217         uint8_t* const write_loc = _data + _size;
218         *((TimeType*)write_loc) = ev.time;
219         memcpy(write_loc + stamp_size, ev.buffer, ev.size);
220
221         _size += stamp_size + ev.size;
222         _silent = false;
223
224         return true;
225 }
226
227
228 /** Reserve space for a new event in the buffer.
229  *
230  * This call is for copying MIDI directly into the buffer, the data location
231  * (of sufficient size to write \a size bytes) is returned, or 0 on failure.
232  * This call MUST be immediately followed by a write to the returned data
233  * location, or the buffer will be corrupted and very nasty things will happen.
234  */
235 uint8_t*
236 MidiBuffer::reserve(TimeType time, size_t size)
237 {
238         const size_t stamp_size = sizeof(TimeType);
239         if (_size + stamp_size + size >= _capacity) {
240                 return 0;
241         }
242
243         // write timestamp
244         uint8_t* write_loc = _data + _size;
245         *((TimeType*)write_loc) = time;
246
247         // move write_loc to begin of MIDI buffer data to write to
248         write_loc += stamp_size;
249
250         _size += stamp_size + size;
251         _silent = false;
252
253         return write_loc;
254 }
255
256
257 void
258 MidiBuffer::silence (framecnt_t /*nframes*/, framecnt_t /*offset*/)
259 {
260         /* XXX iterate over existing events, find all in range given by offset & nframes,
261            and delete them.
262         */
263
264         _size = 0;
265         _silent = true;
266 }
267
268 bool
269 MidiBuffer::second_simultaneous_midi_byte_is_first (uint8_t a, uint8_t b)
270 {
271         bool b_first = false;
272
273         /* two events at identical times. we need to determine
274            the order in which they should occur.
275            
276            the rule is:
277            
278            Controller messages
279            Program Change
280            Note Off
281            Note On
282            Note Pressure
283            Channel Pressure
284            Pitch Bend
285         */
286         
287         if ((a) >= 0xf0 || (b) >= 0xf0 || ((a & 0xf) != (b & 0xf))) {
288                 
289                 /* if either message is not a channel message, or if the channels are
290                  * different, we don't care about the type.
291                  */
292                 
293                 b_first = true;
294                 
295         } else {
296                 
297                 switch (b & 0xf0) {
298                 case MIDI_CMD_CONTROL:
299                         b_first = true;
300                         break;
301                         
302                 case MIDI_CMD_PGM_CHANGE:
303                         switch (a & 0xf0) {
304                         case MIDI_CMD_CONTROL:
305                                 break;
306                         case MIDI_CMD_PGM_CHANGE:
307                         case MIDI_CMD_NOTE_OFF:
308                         case MIDI_CMD_NOTE_ON:
309                         case MIDI_CMD_NOTE_PRESSURE:
310                         case MIDI_CMD_CHANNEL_PRESSURE:
311                         case MIDI_CMD_BENDER:
312                                 b_first = true;
313                         }
314                         
315                 case MIDI_CMD_NOTE_OFF:
316                         switch (a & 0xf0) {
317                         case MIDI_CMD_CONTROL:
318                         case MIDI_CMD_PGM_CHANGE:
319                                 break;
320                         case MIDI_CMD_NOTE_OFF:
321                         case MIDI_CMD_NOTE_ON:
322                         case MIDI_CMD_NOTE_PRESSURE:
323                         case MIDI_CMD_CHANNEL_PRESSURE:
324                         case MIDI_CMD_BENDER:
325                                 b_first = true;
326                         }
327                         break;
328                         
329                 case MIDI_CMD_NOTE_ON:
330                         switch (a & 0xf0) {
331                         case MIDI_CMD_CONTROL:
332                         case MIDI_CMD_PGM_CHANGE:
333                         case MIDI_CMD_NOTE_OFF:
334                                 break;
335                         case MIDI_CMD_NOTE_ON:
336                         case MIDI_CMD_NOTE_PRESSURE:
337                         case MIDI_CMD_CHANNEL_PRESSURE:
338                         case MIDI_CMD_BENDER:
339                                 b_first = true;
340                         }
341                         break;
342                 case MIDI_CMD_NOTE_PRESSURE:
343                         switch (a & 0xf0) {
344                         case MIDI_CMD_CONTROL:
345                         case MIDI_CMD_PGM_CHANGE:
346                         case MIDI_CMD_NOTE_OFF:
347                         case MIDI_CMD_NOTE_ON:
348                                 break;
349                         case MIDI_CMD_NOTE_PRESSURE:
350                         case MIDI_CMD_CHANNEL_PRESSURE:
351                         case MIDI_CMD_BENDER:
352                                 b_first = true;
353                         }
354                         break;
355                         
356                 case MIDI_CMD_CHANNEL_PRESSURE:
357                         switch (a & 0xf0) {
358                         case MIDI_CMD_CONTROL:
359                         case MIDI_CMD_PGM_CHANGE:
360                         case MIDI_CMD_NOTE_OFF:
361                         case MIDI_CMD_NOTE_ON:
362                         case MIDI_CMD_NOTE_PRESSURE:
363                                 break;
364                         case MIDI_CMD_CHANNEL_PRESSURE:
365                         case MIDI_CMD_BENDER:
366                                 b_first = true;
367                         }
368                         break;
369                 case MIDI_CMD_BENDER:
370                         switch (a & 0xf0) {
371                         case MIDI_CMD_CONTROL:
372                         case MIDI_CMD_PGM_CHANGE:
373                         case MIDI_CMD_NOTE_OFF:
374                         case MIDI_CMD_NOTE_ON:
375                         case MIDI_CMD_NOTE_PRESSURE:
376                         case MIDI_CMD_CHANNEL_PRESSURE:
377                                 break;
378                         case MIDI_CMD_BENDER:
379                                 b_first = true;
380                         }
381                         break;
382                 }
383         }
384         
385         return b_first;
386 }
387         
388 /** Merge \a other into this buffer.  Realtime safe. */
389 bool
390 MidiBuffer::merge_in_place(const MidiBuffer &other)
391 {
392         if (other.size() || size()) {
393                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("merge in place, sizes %1/%2\n", size(), other.size()));
394         }
395
396         if (other.size() == 0) {
397                 return true;
398         }
399
400         if (_size == 0) {
401                 copy(other);
402                 return true;
403         }
404
405         if (_size + other.size() > _capacity) {
406                 cerr << "MidiBuffer::merge failed (no space)" << endl;
407                 return false;
408         }
409
410 #ifndef NDEBUG
411 #ifdef  TEST_MIDI_MERGE
412         size_t   test_orig_us_size   = _size;
413         size_t   test_orig_them_size = other._size;
414         TimeType test_time           = 0;
415         size_t   test_us_count       = 0;
416         size_t   test_them_count     = 0;
417         for (iterator i = begin(); i != end(); ++i) {
418                 assert(Evoral::midi_event_is_valid((*i).buffer(), (*i).size()));
419                 assert((*i).time() >= test_time);
420                 test_time = (*i).time();
421                 ++test_us_count;
422         }
423         test_time = 0;
424         for (const_iterator i = other.begin(); i != other.end(); ++i) {
425                 assert(Evoral::midi_event_is_valid((*i).buffer(), (*i).size()));
426                 assert((*i).time() >= test_time);
427                 test_time = (*i).time();
428                 ++test_them_count;
429         }
430 #endif
431 #endif
432
433         const_iterator them = other.begin();
434         iterator us = begin();
435
436         while (them != other.end()) {
437
438                 size_t sz;
439                 ssize_t src;
440
441                 /* gather up total size of events that are earlier than
442                    the event referenced by "us"
443                 */
444
445                 src = -1;
446                 sz = 0;
447
448                 while (them != other.end() && (*them).time() < (*us).time()) {
449                         if (src == -1) {
450                                 src = them.offset;
451                         }
452                         sz += sizeof (TimeType) + (*them).size();
453                         ++them;
454                 }
455
456                 if (sz) {
457                         assert(src >= 0);
458                         /* move existing */
459                         memmove (_data + us.offset + sz, _data + us.offset, _size - us.offset);
460                         /* increase _size */
461                         _size += sz;
462                         assert(_size <= _capacity);
463                         /* insert new stuff */
464                         memcpy  (_data + us.offset, other._data + src, sz);
465                         /* update iterator to our own events. this is a miserable hack */
466                         us.offset += sz;
467                 } else {
468
469                         /* advance past our own events to get to the correct insertion
470                            point for the next event(s) from "other"
471                         */
472
473                         while (us != end() && (*us).time() < (*them).time()) {
474                                 ++us;
475                         }
476                 }
477
478                 if (us == end()) { 
479
480                         /* just append the rest of other */
481
482                         memcpy (_data + us.offset, other._data + them.offset, other._size - them.offset);
483                         _size += other._size - them.offset;
484                         assert(_size <= _capacity);
485                         break;
486
487                 } else if (them != other.end()) {
488
489                         /* to get here implies that we've encountered two
490                          * messages with the same timestamp. we must order 
491                          * them correctly.
492                          */
493
494                         DEBUG_TRACE (DEBUG::MidiIO, 
495                                      string_compose ("simultaneous MIDI events discovered during merge, times %1/%2 status %3/%4\n",
496                                                      (*us).time(), (*them).time(),
497                                                      (int) *(_data + us.offset + sizeof (TimeType)),
498                                                      (int) *(other._data + them.offset + sizeof (TimeType))));
499
500                         assert ((*us).time() == (*them).time());
501                                                      
502                         uint8_t our_midi_status_byte = *(_data + us.offset + sizeof (TimeType));
503                         uint8_t their_midi_status_byte = *(other._data + them.offset + sizeof (TimeType));
504                         bool them_first = second_simultaneous_midi_byte_is_first (our_midi_status_byte, their_midi_status_byte);
505
506                         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("other message came first ? %1\n", them_first));
507                         
508                         if (!them_first) {
509                                 /* skip past our own event */
510                                 ++us;
511                         }
512                                 
513                         sz = sizeof (TimeType) + (*them).size();
514                         
515                         /* move our remaining events later in the buffer by
516                          * enough to fit the one message we're going to merge
517                          */
518
519                         memmove (_data + us.offset + sz, _data + us.offset, _size - us.offset);
520                         /* increase _size */
521                         _size += sz;
522                         assert(_size <= _capacity);
523                         /* insert new stuff */
524                         memcpy  (_data + us.offset, other._data + them.offset, sz);
525                         /* update iterator to our own events. this is a miserable hack */
526                         us.offset += sz;
527                         /* 'us' is now an iterator to the event right after the
528                            new ones that we merged
529                         */
530                         if (them_first) {
531                                 /* need to skip the event pointed to by 'us'
532                                    since its at the same time as 'them'
533                                    (still), and we'll enter 
534                                 */
535
536                                 if (us != end()) {
537                                         ++us;
538                                 }
539                         }
540
541                         /* we merged one event from the other buffer, so
542                          * advance the iterator there.
543                          */
544
545                         ++them;
546                 }
547         }
548
549 #ifndef NDEBUG
550 #ifdef  TEST_MIDI_MERGE
551         assert(_size == test_orig_us_size + test_orig_them_size);
552         size_t test_final_count = 0;
553         test_time = 0;
554         for (iterator i = begin(); i != end(); ++i) {
555                 cerr << "CHECK " << test_final_count << " / " << test_us_count + test_them_count << endl;
556                 assert(Evoral::midi_event_is_valid((*i).buffer(), (*i).size()));
557                 assert((*i).time() >= test_time);
558                 test_time = (*i).time();
559                 ++test_final_count;
560         }
561         assert(test_final_count = test_us_count + test_them_count);
562 #endif
563 #endif
564
565         return true;
566 }
567
568 /** Clear, and merge \a a and \a b into this buffer.
569  *
570  * \return true if complete merge was successful
571  */
572 bool
573 MidiBuffer::merge(const MidiBuffer& a, const MidiBuffer& b)
574 {
575         _size = 0;
576
577         if (this == &a) {
578             return merge_in_place(b);
579         } else if (this == &b) {
580             return merge_in_place(a);
581         }
582
583         const_iterator ai = a.begin();
584         const_iterator bi = b.begin();
585
586         resize(a.size() + b.size());
587         while (ai != a.end() && bi != b.end()) {
588                 if ((*ai).time() < (*bi).time()) {
589                         memcpy(_data + _size, (*ai).buffer(), (*ai).size());
590                         _size += (*ai).size();
591                         ++ai;
592                 } else {
593                         memcpy(_data + _size, (*bi).buffer(), (*bi).size());
594                         _size += (*bi).size();
595                         ++bi;
596                 }
597         }
598
599         while (ai != a.end()) {
600                 memcpy(_data + _size, (*ai).buffer(), (*ai).size());
601                 _size += (*ai).size();
602                 ++ai;
603         }
604
605         while (bi != b.end()) {
606                 memcpy(_data + _size, (*bi).buffer(), (*bi).size());
607                 _size += (*bi).size();
608                 ++bi;
609         }
610
611         return true;
612 }
613