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