Remove all use of nframes_t.
[ardour.git] / libs / ardour / midi_buffer.cc
1 /*
2     Copyright (C) 2006-2007 Paul Davis
3         Author: Dave 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 " << src_offset << " .. " 
104                              << (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                 DEBUG_STR_DECL(a);
162                 DEBUG_STR_APPEND(a, string_compose ("midibuffer %1 push event @ %2 sz %3 ", this, time, size));
163                 for (size_t i=0; i < size; ++i) {
164                         DEBUG_STR_APPEND(a,hex);
165                         DEBUG_STR_APPEND(a,"0x");
166                         DEBUG_STR_APPEND(a,(int)data[i]);
167                         DEBUG_STR_APPEND(a,' ');
168                 }
169                 DEBUG_STR_APPEND(a,'\n');
170                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
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         if (_size + stamp_size + ev.size >= _capacity) {
206                 cerr << "MidiBuffer::push_back failed (buffer is full)" << endl;
207                 return false;
208         }
209
210         if (!Evoral::midi_event_is_valid(ev.buffer, ev.size)) {
211                 cerr << "WARNING: MidiBuffer ignoring illegal MIDI event" << endl;
212                 return false;
213         }
214
215         uint8_t* const write_loc = _data + _size;
216         *((TimeType*)write_loc) = ev.time;
217         memcpy(write_loc + stamp_size, ev.buffer, ev.size);
218
219         _size += stamp_size + ev.size;
220         _silent = false;
221
222         return true;
223 }
224
225
226 /** Reserve space for a new event in the buffer.
227  *
228  * This call is for copying MIDI directly into the buffer, the data location
229  * (of sufficient size to write \a size bytes) is returned, or 0 on failure.
230  * This call MUST be immediately followed by a write to the returned data
231  * location, or the buffer will be corrupted and very nasty things will happen.
232  */
233 uint8_t*
234 MidiBuffer::reserve(TimeType time, size_t size)
235 {
236         const size_t stamp_size = sizeof(TimeType);
237         if (_size + stamp_size + size >= _capacity) {
238                 return 0;
239         }
240
241         // write timestamp
242         uint8_t* write_loc = _data + _size;
243         *((TimeType*)write_loc) = time;
244
245         // move write_loc to begin of MIDI buffer data to write to
246         write_loc += stamp_size;
247
248         _size += stamp_size + size;
249         _silent = false;
250
251         return write_loc;
252 }
253
254
255 void
256 MidiBuffer::silence (framecnt_t /*nframes*/, framecnt_t /*offset*/)
257 {
258         /* XXX iterate over existing events, find all in range given by offset & nframes,
259            and delete them.
260         */
261
262         _size = 0;
263         _silent = true;
264 }
265
266 /** Merge \a other into this buffer.  Realtime safe. */
267 bool
268 MidiBuffer::merge_in_place(const MidiBuffer &other)
269 {
270         if (other.size() == 0) {
271                 return true;
272         }
273
274         if (_size == 0) {
275                 copy(other);
276                 return true;
277         }
278
279         if (_size + other.size() > _capacity) {
280                 cerr << "MidiBuffer::merge failed (no space)" << endl;
281                 return false;
282         }
283
284 #ifndef NDEBUG
285         size_t   test_orig_us_size   = _size;
286         size_t   test_orig_them_size = other._size;
287         TimeType test_time           = 0;
288         size_t   test_us_count       = 0;
289         size_t   test_them_count     = 0;
290         for (iterator i = begin(); i != end(); ++i) {
291                 assert(Evoral::midi_event_is_valid((*i).buffer(), (*i).size()));
292                 assert((*i).time() >= test_time);
293                 test_time = (*i).time();
294                 ++test_us_count;
295         }
296         test_time = 0;
297         for (const_iterator i = other.begin(); i != other.end(); ++i) {
298                 assert(Evoral::midi_event_is_valid((*i).buffer(), (*i).size()));
299                 assert((*i).time() >= test_time);
300                 test_time = (*i).time();
301                 ++test_them_count;
302         }
303 #endif
304
305         const_iterator them = other.begin();
306         iterator us = begin();
307
308         while (them != other.end()) {
309
310                 size_t sz = 0;
311                 ssize_t src = -1;
312
313                 /* gather up total size of events that are earlier than
314                    the event referenced by "us"
315                 */
316
317                 while (them != other.end() && (*them).time() <= (*us).time()) {
318                         if (src == -1) {
319                                 src = them.offset;
320                         }
321                         sz += sizeof (TimeType) + (*them).size();
322                         ++them;
323                 }
324
325 #if 0                
326                 if (us != end())
327                         cerr << "us @ " << (*us).time() << endl;
328                 if (them != other.end())
329                         cerr << "them @ " << (*them).time() << endl;
330 #endif
331
332                 if (sz) {
333                         assert(src >= 0);
334                         /* move existing */
335                         memmove (_data + us.offset + sz, _data + us.offset, _size - us.offset);
336                         /* increase _size */
337                         _size += sz;
338                         assert(_size <= _capacity);
339                         /* insert new stuff */
340                         memcpy  (_data + us.offset, other._data + src, sz);
341                         /* update iterator to our own events. this is a miserable hack */
342                         us.offset += sz;
343                 } else {
344
345                         /* advance past our own events to get to the correct insertion
346                            point for the next event(s) from "other"
347                         */
348
349                         while (us != end() && (*us).time() < (*them).time()) {
350                                 ++us;
351                         }
352                 }
353
354                 if (!(us != end())) {
355                         /* just append the rest of other */
356                         memcpy (_data + us.offset, other._data + them.offset, other._size - them.offset);
357                         _size += other._size - them.offset;
358                         break;
359                 }
360         }
361
362 #ifndef NDEBUG
363         assert(_size == test_orig_us_size + test_orig_them_size);
364         size_t test_final_count = 0;
365         test_time = 0;
366         for (iterator i = begin(); i != end(); ++i) {
367                 // cerr << "CHECK " << test_final_count << " / " << test_us_count + test_them_count << endl;
368                 assert(Evoral::midi_event_is_valid((*i).buffer(), (*i).size()));
369                 assert((*i).time() >= test_time);
370                 test_time = (*i).time();
371                 ++test_final_count;
372         }
373         assert(test_final_count = test_us_count + test_them_count);
374 #endif
375
376         return true;
377 }
378
379 /** Clear, and merge \a a and \a b into this buffer.
380  *
381  * \return true if complete merge was successful
382  */
383 bool
384 MidiBuffer::merge(const MidiBuffer& a, const MidiBuffer& b)
385 {
386         _size = 0;
387
388         if (this == &a) {
389             return merge_in_place(b);
390         } else if (this == &b) {
391             return merge_in_place(a);
392         }
393
394         const_iterator ai = a.begin();
395         const_iterator bi = b.begin();
396
397         resize(a.size() + b.size());
398         while (ai != a.end() && bi != b.end()) {
399                 if ((*ai).time() < (*bi).time()) {
400                         memcpy(_data + _size, (*ai).buffer(), (*ai).size());
401                         _size += (*ai).size();
402                         ++ai;
403                 } else {
404                         memcpy(_data + _size, (*bi).buffer(), (*bi).size());
405                         _size += (*bi).size();
406                         ++bi;
407                 }
408         }
409
410         while (ai != a.end()) {
411                 memcpy(_data + _size, (*ai).buffer(), (*ai).size());
412                 _size += (*ai).size();
413                 ++ai;
414         }
415
416         while (bi != b.end()) {
417                 memcpy(_data + _size, (*bi).buffer(), (*bi).size());
418                 _size += (*bi).size();
419                 ++bi;
420         }
421
422         return true;
423 }
424