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