Replace a bunch of potential crashes with graceful handling of the situation.
[ardour.git] / libs / ardour / midi_ring_buffer.cc
1 /*
2     Copyright (C) 2006-2008 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include "pbd/compose.h"
20 #include "pbd/error.h"
21
22 #include "ardour/debug.h"
23 #include "ardour/midi_ring_buffer.h"
24 #include "ardour/midi_buffer.h"
25 #include "ardour/event_type_map.h"
26
27 using namespace std;
28 using namespace PBD;
29
30 namespace ARDOUR {
31
32 /** Read a block of MIDI events from this buffer into a MidiBuffer.
33  *
34  * Timestamps of events returned are relative to start (i.e. event with stamp 0
35  * occurred at start), with offset added.
36  */
37 template<typename T>
38 size_t
39 MidiRingBuffer<T>::read(MidiBuffer& dst, framepos_t start, framepos_t end, framecnt_t offset, bool stop_on_overflow_in_dst)
40 {
41         if (this->read_space() == 0) {
42                 return 0;
43         }
44
45         T                 ev_time;
46         uint32_t          ev_size;
47         size_t            count = 0;
48         const size_t      prefix_size = sizeof(T) + sizeof(Evoral::EventType) + sizeof(uint32_t);
49
50         while (this->read_space() >= prefix_size) {
51
52                 uint8_t peekbuf[prefix_size];
53
54                 /* this cannot fail, because we've already verified that there
55                    is prefix_space to read
56                 */
57                 assert (this->peek (peekbuf, prefix_size));
58
59                 ev_time = *((T*) peekbuf);
60                 ev_size = *((uint32_t*)(peekbuf + sizeof(T) + sizeof (Evoral::EventType)));
61
62                 if (ev_time >= end) {
63                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MRB event @ %1 past end @ %2\n", ev_time, end));
64                         break;
65                 } else if (ev_time < start) {
66                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MRB event @ %1 before start @ %2\n", ev_time, start));
67                         break;
68                 } else {
69                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MRB event @ %1 in range %2 .. %3\n", ev_time, start, end));
70                 }
71
72                 ev_time -= start;
73                 ev_time += offset;
74
75                 /* we're good to go ahead and read the data now but since we
76                  * have the prefix data already, just skip over that
77                  */
78                 this->increment_read_ptr (prefix_size);
79
80                 uint8_t status;
81                 assert (this->peek (&status, sizeof(uint8_t))); // If this failed, buffer is corrupt, all hope is lost
82
83                 // Ignore event if it doesn't match channel filter
84                 if (is_channel_event(status) && get_channel_mode() == FilterChannels) {
85                         const uint8_t channel = status & 0x0F;
86                         if (!(get_channel_mask() & (1L << channel))) {
87                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MRB skipping event (%3 bytes) due to channel mask (mask = %1 chn = %2)\n",
88                                                                                       get_channel_mask(), (int) channel, ev_size));
89                                 this->increment_read_ptr (ev_size); // Advance read pointer to next event
90                                 continue;
91                         }
92                 }
93
94                 /* lets see if we are going to be able to write this event into dst.
95                  */
96                 uint8_t* write_loc = dst.reserve (ev_time, ev_size);
97                 if (write_loc == 0) {
98                         if (stop_on_overflow_in_dst) {
99                                 DEBUG_TRACE (DEBUG::MidiDiskstreamIO, string_compose ("MidiRingBuffer: overflow in destination MIDI buffer, stopped after %1 events\n", count));
100                                 break;
101                         }
102                         error << "MRB: Unable to reserve space in buffer, event skipped" << endmsg;
103                         this->increment_read_ptr (ev_size); // Advance read pointer to next event
104                         continue;
105                 }
106
107                 // write MIDI buffer contents
108                 bool success = read_contents (ev_size, write_loc);
109
110 #ifndef NDEBUG
111                 if (DEBUG::MidiDiskstreamIO && PBD::debug_bits) {
112                         DEBUG_STR_DECL(a);
113                         DEBUG_STR_APPEND(a, string_compose ("wrote MidiEvent to Buffer (time=%1, start=%2 offset=%3)", ev_time, start, offset));
114                         for (size_t i=0; i < ev_size; ++i) {
115                                 DEBUG_STR_APPEND(a,hex);
116                                 DEBUG_STR_APPEND(a,"0x");
117                                 DEBUG_STR_APPEND(a,(int)write_loc[i]);
118                                 DEBUG_STR_APPEND(a,' ');
119                         }
120                         DEBUG_STR_APPEND(a,'\n');
121                         DEBUG_TRACE (DEBUG::MidiDiskstreamIO, DEBUG_STR(a).str());
122                 }
123 #endif
124
125                 if (success) {
126
127                         if (is_note_on(write_loc[0]) ) {
128                                 _tracker.add (write_loc[1], write_loc[0] & 0xf);
129                         } else if (is_note_off(write_loc[0])) {
130                                 _tracker.remove (write_loc[1], write_loc[0] & 0xf);
131                         }
132                         
133                         if (is_channel_event(status) && get_channel_mode() == ForceChannel) {
134                                 write_loc[0] = (write_loc[0] & 0xF0) | (get_channel_mask() & 0x0F);
135                         }
136                         ++count;
137                 } else {
138                         cerr << "WARNING: error reading event contents from MIDI ring" << endl;
139                 }
140         }
141
142         return count;
143 }
144
145 template<typename T>
146 void
147 MidiRingBuffer<T>::flush (framepos_t /*start*/, framepos_t end)
148 {
149         const size_t prefix_size = sizeof(T) + sizeof(Evoral::EventType) + sizeof(uint32_t);
150
151         while (this->read_space() >= prefix_size) {
152                 uint8_t  peekbuf[prefix_size];
153                 bool     success;
154                 uint32_t ev_size;
155                 T        ev_time;
156
157                 success = this->peek (peekbuf, prefix_size);
158                 /* this cannot fail, because we've already verified that there
159                    is prefix_space to read
160                 */
161                 assert (success);
162
163                 ev_time = *((T*) peekbuf);
164                 
165                 if (ev_time >= end) {
166                         break;
167                 }
168
169                 ev_size = *((uint32_t*)(peekbuf + sizeof(T) + sizeof (Evoral::EventType)));
170                 this->increment_read_ptr (prefix_size);
171                 this->increment_read_ptr (ev_size);
172         }
173 }
174
175 template<typename T>
176 void
177 MidiRingBuffer<T>::dump(ostream& str)
178 {
179         size_t rspace;
180
181         if ((rspace = this->read_space()) == 0) {
182                 str << "MRB::dump: empty\n";
183                 return;
184         }
185
186         T                 ev_time;
187         Evoral::EventType ev_type;
188         uint32_t          ev_size;
189
190         RingBufferNPT<uint8_t>::rw_vector vec;
191         RingBufferNPT<uint8_t>::get_read_vector (&vec);
192
193         if (vec.len[0] == 0) {
194                 return;
195         }
196
197         str << this << ": Dump size = " << vec.len[0] + vec.len[1]
198             << " r@ " << RingBufferNPT<uint8_t>::get_read_ptr()
199             << " w@" << RingBufferNPT<uint8_t>::get_write_ptr() << endl;
200
201
202         uint8_t *buf = new uint8_t[vec.len[0] + vec.len[1]];
203         memcpy (buf, vec.buf[0], vec.len[0]);
204
205         if (vec.len[1]) {
206                 memcpy (buf+vec.len[1], vec.buf[1], vec.len[1]);
207         }
208
209         uint8_t* data = buf;
210         const uint8_t* end = buf + vec.len[0] + vec.len[1];
211
212         while (data < end) {
213
214                 memcpy (&ev_time, data, sizeof (T));
215                 data += sizeof (T);
216                 str << "\ttime " << ev_time;
217
218                 if (data >= end) {
219                         str << "(incomplete)\n ";
220                         break;
221                 }
222
223                 memcpy (&ev_type, data, sizeof (ev_type));
224                 data += sizeof (ev_type);
225                 str << " type " << ev_type;
226
227                 if (data >= end) {
228                         str << "(incomplete)\n";
229                         break;
230                 }
231
232                 memcpy (&ev_size, data, sizeof (ev_size));
233                 data += sizeof (ev_size);
234                 str << " size " << ev_size;
235
236                 if (data >= end) {
237                         str << "(incomplete)\n";
238                         break;
239                 }
240
241                 for (uint32_t i = 0; i != ev_size && data < end; ++i) {
242                         str << ' ' << hex << (int) data[i] << dec;
243                 }
244
245                 data += ev_size;
246
247                 str << endl;
248         }
249
250         delete [] buf;
251 }
252
253 template<typename T>
254 void
255 MidiRingBuffer<T>::reset_tracker ()
256 {
257         _tracker.reset ();
258 }
259
260 template<typename T>
261 void
262 MidiRingBuffer<T>::loop_resolve (MidiBuffer& dst, framepos_t t)
263 {
264         _tracker.resolve_notes (dst, t);
265 }
266
267 template class MidiRingBuffer<framepos_t>;
268
269 }  // namespace ARDOUR