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