main fix: when transport stops, clear per-region per-playlist note trackers even...
[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
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
194 /** Push an event into the buffer.
195  *
196  * Note that the raw MIDI pointed to by ev will be COPIED and unmodified.
197  * That is, the caller still owns it, if it needs freeing it's Not My Problem(TM).
198  * Realtime safe.
199  * @return false if operation failed (not enough room)
200  */
201 bool
202 MidiBuffer::push_back(const jack_midi_event_t& ev)
203 {
204         const size_t stamp_size = sizeof(TimeType);
205
206         if (_size + stamp_size + ev.size >= _capacity) {
207                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
208                 return false;
209         }
210
211         if (!Evoral::midi_event_is_valid(ev.buffer, ev.size)) {
212                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
213                 return false;
214         }
215
216 #ifndef NDEBUG
217         if (DEBUG::MidiIO & PBD::debug_bits) {
218                 DEBUG_STR_DECL(a);
219                 DEBUG_STR_APPEND(a, string_compose ("midibuffer %1 push jack event @ %2 sz %3 ", this, ev.time, ev.size));
220                 for (size_t i=0; i < ev.size; ++i) {
221                         DEBUG_STR_APPEND(a,hex);
222                         DEBUG_STR_APPEND(a,"0x");
223                         DEBUG_STR_APPEND(a,(int)ev.buffer[i]);
224                         DEBUG_STR_APPEND(a,' ');
225                 }
226                 DEBUG_STR_APPEND(a,'\n');
227                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
228         }
229 #endif
230
231         uint8_t* const write_loc = _data + _size;
232         *((TimeType*)write_loc) = ev.time;
233         memcpy(write_loc + stamp_size, ev.buffer, ev.size);
234
235         _size += stamp_size + ev.size;
236         _silent = false;
237
238         return true;
239 }
240
241
242 /** Reserve space for a new event in the buffer.
243  *
244  * This call is for copying MIDI directly into the buffer, the data location
245  * (of sufficient size to write \a size bytes) is returned, or 0 on failure.
246  * This call MUST be immediately followed by a write to the returned data
247  * location, or the buffer will be corrupted and very nasty things will happen.
248  */
249 uint8_t*
250 MidiBuffer::reserve(TimeType time, size_t size)
251 {
252         const size_t stamp_size = sizeof(TimeType);
253         if (_size + stamp_size + size >= _capacity) {
254                 return 0;
255         }
256
257         // write timestamp
258         uint8_t* write_loc = _data + _size;
259         *((TimeType*)write_loc) = time;
260
261         // move write_loc to begin of MIDI buffer data to write to
262         write_loc += stamp_size;
263
264         _size += stamp_size + size;
265         _silent = false;
266
267         return write_loc;
268 }
269
270
271 void
272 MidiBuffer::silence (framecnt_t /*nframes*/, framecnt_t /*offset*/)
273 {
274         /* XXX iterate over existing events, find all in range given by offset & nframes,
275            and delete them.
276         */
277
278         _size = 0;
279         _silent = true;
280 }
281
282 bool
283 MidiBuffer::second_simultaneous_midi_byte_is_first (uint8_t a, uint8_t b)
284 {
285         bool b_first = false;
286
287         /* two events at identical times. we need to determine
288            the order in which they should occur.
289            
290            the rule is:
291            
292            Controller messages
293            Program Change
294            Note Off
295            Note On
296            Note Pressure
297            Channel Pressure
298            Pitch Bend
299         */
300         
301         if ((a) >= 0xf0 || (b) >= 0xf0 || ((a & 0xf) != (b & 0xf))) {
302                 
303                 /* if either message is not a channel message, or if the channels are
304                  * different, we don't care about the type.
305                  */
306                 
307                 b_first = true;
308                 
309         } else {
310                 
311                 switch (b & 0xf0) {
312                 case MIDI_CMD_CONTROL:
313                         b_first = true;
314                         break;
315                         
316                 case MIDI_CMD_PGM_CHANGE:
317                         switch (a & 0xf0) {
318                         case MIDI_CMD_CONTROL:
319                                 break;
320                         case MIDI_CMD_PGM_CHANGE:
321                         case MIDI_CMD_NOTE_OFF:
322                         case MIDI_CMD_NOTE_ON:
323                         case MIDI_CMD_NOTE_PRESSURE:
324                         case MIDI_CMD_CHANNEL_PRESSURE:
325                         case MIDI_CMD_BENDER:
326                                 b_first = true;
327                         }
328                         
329                 case MIDI_CMD_NOTE_OFF:
330                         switch (a & 0xf0) {
331                         case MIDI_CMD_CONTROL:
332                         case MIDI_CMD_PGM_CHANGE:
333                                 break;
334                         case MIDI_CMD_NOTE_OFF:
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                         
343                 case MIDI_CMD_NOTE_ON:
344                         switch (a & 0xf0) {
345                         case MIDI_CMD_CONTROL:
346                         case MIDI_CMD_PGM_CHANGE:
347                         case MIDI_CMD_NOTE_OFF:
348                                 break;
349                         case MIDI_CMD_NOTE_ON:
350                         case MIDI_CMD_NOTE_PRESSURE:
351                         case MIDI_CMD_CHANNEL_PRESSURE:
352                         case MIDI_CMD_BENDER:
353                                 b_first = true;
354                         }
355                         break;
356                 case MIDI_CMD_NOTE_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                                 break;
363                         case MIDI_CMD_NOTE_PRESSURE:
364                         case MIDI_CMD_CHANNEL_PRESSURE:
365                         case MIDI_CMD_BENDER:
366                                 b_first = true;
367                         }
368                         break;
369                         
370                 case MIDI_CMD_CHANNEL_PRESSURE:
371                         switch (a & 0xf0) {
372                         case MIDI_CMD_CONTROL:
373                         case MIDI_CMD_PGM_CHANGE:
374                         case MIDI_CMD_NOTE_OFF:
375                         case MIDI_CMD_NOTE_ON:
376                         case MIDI_CMD_NOTE_PRESSURE:
377                                 break;
378                         case MIDI_CMD_CHANNEL_PRESSURE:
379                         case MIDI_CMD_BENDER:
380                                 b_first = true;
381                         }
382                         break;
383                 case MIDI_CMD_BENDER:
384                         switch (a & 0xf0) {
385                         case MIDI_CMD_CONTROL:
386                         case MIDI_CMD_PGM_CHANGE:
387                         case MIDI_CMD_NOTE_OFF:
388                         case MIDI_CMD_NOTE_ON:
389                         case MIDI_CMD_NOTE_PRESSURE:
390                         case MIDI_CMD_CHANNEL_PRESSURE:
391                                 break;
392                         case MIDI_CMD_BENDER:
393                                 b_first = true;
394                         }
395                         break;
396                 }
397         }
398         
399         return b_first;
400 }
401         
402 /** Merge \a other into this buffer.  Realtime safe. */
403 bool
404 MidiBuffer::merge_in_place (const MidiBuffer &other)
405 {
406         if (other.size() && size()) {
407                 DEBUG_TRACE (DEBUG::MidiIO, string_compose ("merge in place, sizes %1/%2\n", size(), other.size()));
408         }
409
410         if (other.size() == 0) {
411                 return true;
412         }
413
414         if (size() == 0) {
415                 copy (other);
416                 return true;
417         }
418
419         if (size() + other.size() > _capacity) {
420                 return false;
421         }
422
423         const_iterator them = other.begin();
424         iterator us = begin();
425
426         while (them != other.end()) {
427
428                 size_t bytes_to_merge;
429                 ssize_t merge_offset;
430
431                 /* gather up total size of events that are earlier than
432                    the event referenced by "us"
433                 */
434
435                 merge_offset = -1;
436                 bytes_to_merge = 0;
437
438                 while (them != other.end() && (*them).time() < (*us).time()) {
439                         if (merge_offset == -1) {
440                                 merge_offset = them.offset;
441                         }
442                         bytes_to_merge += sizeof (TimeType) + (*them).size();
443                         ++them;
444                 }
445
446                 /* "them" now points to either:
447                  *
448                  * 1) an event that has the same or later timestamp than the
449                  *        event pointed to by "us"
450                  *
451                  * OR
452                  *
453                  * 2) the end of the "other" buffer
454                  *
455                  * if "sz" is non-zero, there is data to be merged from "other"
456                  * into this buffer before we do anything else, corresponding
457                  * to the events from "other" that we skipped while advancing
458                  * "them". 
459                  */
460
461                 if (bytes_to_merge) {
462                         assert(merge_offset >= 0);
463                         /* move existing */
464                         memmove (_data + us.offset + bytes_to_merge, _data + us.offset, _size - us.offset);
465                         /* increase _size */
466                         _size += bytes_to_merge;
467                         assert (_size <= _capacity);
468                         /* insert new stuff */
469                         memcpy  (_data + us.offset, other._data + merge_offset, bytes_to_merge);
470                         /* update iterator to our own events. this is a miserable hack */
471                         us.offset += bytes_to_merge;
472                 } 
473
474                 /* if we're at the end of the other buffer, we're done */
475
476                 if (them == other.end()) {
477                         break;
478                 }
479
480                 /* if we have two messages messages with the same timestamp. we
481                  * must order them correctly.
482                  */
483
484                 if ((*us).time() == (*them).time()) {
485
486                         DEBUG_TRACE (DEBUG::MidiIO, 
487                                      string_compose ("simultaneous MIDI events discovered during merge, times %1/%2 status %3/%4\n",
488                                                      (*us).time(), (*them).time(),
489                                                      (int) *(_data + us.offset + sizeof (TimeType)),
490                                                      (int) *(other._data + them.offset + sizeof (TimeType))));
491                         
492                         uint8_t our_midi_status_byte = *(_data + us.offset + sizeof (TimeType));
493                         uint8_t their_midi_status_byte = *(other._data + them.offset + sizeof (TimeType));
494                         bool them_first = second_simultaneous_midi_byte_is_first (our_midi_status_byte, their_midi_status_byte);
495                         
496                         DEBUG_TRACE (DEBUG::MidiIO, string_compose ("other message came first ? %1\n", them_first));
497                         
498                         if (!them_first) {
499                                 /* skip past our own event */
500                                 ++us;
501                         }
502                                 
503                         bytes_to_merge = sizeof (TimeType) + (*them).size();
504                         
505                         /* move our remaining events later in the buffer by
506                          * enough to fit the one message we're going to merge
507                          */
508
509                         memmove (_data + us.offset + bytes_to_merge, _data + us.offset, _size - us.offset);
510                         /* increase _size */
511                         _size += bytes_to_merge;
512                         assert(_size <= _capacity);
513                         /* insert new stuff */
514                         memcpy  (_data + us.offset, other._data + them.offset, bytes_to_merge);
515                         /* update iterator to our own events. this is a miserable hack */
516                         us.offset += bytes_to_merge;
517                         /* 'us' is now an iterator to the event right after the
518                            new ones that we merged
519                         */
520                         if (them_first) {
521                                 /* need to skip the event pointed to by 'us'
522                                    since its at the same time as 'them'
523                                    (still), and we'll enter 
524                                 */
525
526                                 if (us != end()) {
527                                         ++us;
528                                 }
529                         }
530
531                         /* we merged one event from the other buffer, so
532                          * advance the iterator there.
533                          */
534
535                         ++them;
536
537                 } else {
538                         
539                         /* advance past our own events to get to the correct insertion
540                            point for the next event(s) from "other"
541                         */
542                 
543                         while (us != end() && (*us).time() <= (*them).time()) {
544                                 ++us;
545                         }
546                 }
547
548                 /* check to see if we reached the end of this buffer while
549                  * looking for the insertion point.
550                  */
551
552                 if (us == end()) {
553
554                         /* just append the rest of other and we're done*/
555                         
556                         memcpy (_data + us.offset, other._data + them.offset, other._size - them.offset);
557                         _size += other._size - them.offset;
558                         assert(_size <= _capacity);
559                         break;
560                 } 
561         }
562
563         return true;
564 }
565