]> sigrok.org Git - libsigrokdecode.git/blob - decoders/midi/pd.py
Add PD tags handling and some tags
[libsigrokdecode.git] / decoders / midi / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2013-2016 Uwe Hermann <uwe@hermann-uwe.de>
5 ## Copyright (C) 2016 Chris Dreher <chrisdreher@hotmail.com>
6 ##
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ##
20
21 import sigrokdecode as srd
22 from .lists import *
23
24 RX = 0
25 TX = 1
26
27 class Decoder(srd.Decoder):
28     api_version = 3
29     id = 'midi'
30     name = 'MIDI'
31     longname = 'Musical Instrument Digital Interface'
32     desc = 'Musical Instrument Digital Interface (MIDI) protocol.'
33     license = 'gplv2+'
34     inputs = ['uart']
35     outputs = ['midi']
36     tags = ['Logic', 'Bus', 'Audio']
37     annotations = (
38         ('text-verbose', 'Human-readable text (verbose)'),
39         ('text-sysreal-verbose', 'Human-readable SysReal text (verbose)'),
40         ('text-error', 'Human-readable Error text'),
41     )
42     annotation_rows = (
43         ('normal', 'Normal', (0, 2)),
44         ('sys-real', 'SysReal', (1,)),
45     )
46
47     def __init__(self):
48         self.reset()
49
50     def reset(self):
51         self.state = 'IDLE'
52         self.status_byte = 0
53         self.explicit_status_byte = False
54         self.cmd = []
55         self.ss = None
56         self.es = None
57         self.ss_block = None
58         self.es_block = None
59
60     def start(self):
61         self.out_ann = self.register(srd.OUTPUT_ANN)
62
63     def putx(self, data):
64         self.put(self.ss_block, self.es_block, self.out_ann, data)
65
66     def get_note_name(self, channel, note):
67         if channel != 10:
68             return chromatic_notes[note]
69         else:
70             return 'assuming ' + percussion_notes.get(note, 'undefined')
71
72     def check_for_garbage_flush(self, is_flushed):
73         if is_flushed:
74             if self.explicit_status_byte:
75                 self.cmd.insert(0, self.status_byte)
76             self.handle_garbage_msg(None)
77
78     def soft_clear_status_byte(self):
79         self.explicit_status_byte = False
80
81     def hard_clear_status_byte(self):
82         self.status_byte = 0
83         self.explicit_status_byte = False
84
85     def set_status_byte(self, newbyte):
86         self.status_byte = newbyte
87         self.explicit_status_byte = True
88
89     def handle_channel_msg_0x80(self, is_flushed):
90         # Note off: 8n kk vv
91         # n = channel, kk = note, vv = velocity
92         c = self.cmd
93         if len(c) < 2:
94             self.check_for_garbage_flush(is_flushed)
95             return
96         self.es_block = self.es
97         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
98         note, velocity = c[0], c[1]
99         note_name = self.get_note_name(chan, note)
100         self.putx([0, ['Channel %d: %s (note = %d \'%s\', velocity = %d)' % \
101                   (chan, status_bytes[msg][0], note, note_name, velocity),
102                   'ch %d: %s %d, velocity = %d' % \
103                   (chan, status_bytes[msg][1], note, velocity),
104                   '%d: %s %d, vel %d' % \
105                   (chan, status_bytes[msg][2], note, velocity)]])
106         self.cmd, self.state = [], 'IDLE'
107         self.soft_clear_status_byte()
108
109     def handle_channel_msg_0x90(self, is_flushed):
110         # Note on: 9n kk vv
111         # n = channel, kk = note, vv = velocity
112         # If velocity == 0 that actually means 'note off', though.
113         c = self.cmd
114         if len(c) < 2:
115             self.check_for_garbage_flush(is_flushed)
116             return
117         self.es_block = self.es
118         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
119         note, velocity = c[0], c[1]
120         s = status_bytes[0x80] if (velocity == 0) else status_bytes[msg]
121         note_name = self.get_note_name(chan, note)
122         self.putx([0, ['Channel %d: %s (note = %d \'%s\', velocity = %d)' % \
123                   (chan, s[0], note, note_name, velocity),
124                   'ch %d: %s %d, velocity = %d' % \
125                   (chan, s[1], note, velocity),
126                   '%d: %s %d, vel %d' % \
127                   (chan, s[2], note, velocity)]])
128         self.cmd, self.state = [], 'IDLE'
129         self.soft_clear_status_byte()
130
131     def handle_channel_msg_0xa0(self, is_flushed):
132         # Polyphonic key pressure / aftertouch: An kk vv
133         # n = channel, kk = polyphonic key pressure, vv = pressure value
134         c = self.cmd
135         if len(c) < 2:
136             self.check_for_garbage_flush(is_flushed)
137             return
138         self.es_block = self.es
139         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
140         note, pressure = c[0], c[1]
141         note_name = self.get_note_name(chan, note)
142         self.putx([0, ['Channel %d: %s of %d for note = %d \'%s\'' % \
143                   (chan, status_bytes[msg][0], pressure, note, note_name),
144                   'ch %d: %s %d for note %d' % \
145                   (chan, status_bytes[msg][1], pressure, note),
146                   '%d: %s %d, N %d' % \
147                   (chan, status_bytes[msg][2], pressure, note)]])
148         self.cmd, self.state = [], 'IDLE'
149         self.soft_clear_status_byte()
150
151     def handle_controller_0x44(self):
152         # Legato footswitch: Bn 44 vv
153         # n = channel, vv = value (<= 0x3f: normal, > 0x3f: legato)
154         c = self.cmd
155         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
156         vv = c[1]
157         t = ('normal', 'no') if vv <= 0x3f else ('legato', 'yes')
158         self.putx([0, ['Channel %d: %s \'%s\' = %s' % \
159                   (chan, status_bytes[msg][0],
160                   control_functions[0x44][0], t[0]),
161                   'ch %d: %s \'%s\' = %s' % \
162                   (chan, status_bytes[msg][1],
163                   control_functions[0x44][1], t[0]),
164                   '%d: %s \'%s\' = %s' % \
165                   (chan, status_bytes[msg][2],
166                   control_functions[0x44][2], t[1])]])
167
168     def handle_controller_0x54(self):
169         # Portamento control (PTC): Bn 54 kk
170         # n = channel, kk = source note for pitch reference
171         c = self.cmd
172         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
173         kk = c[1]
174         kk_name = self.get_note_name(chan, kk)
175         self.putx([0, ['Channel %d: %s \'%s\' (source note = %d / %s)' % \
176                   (chan, status_bytes[msg][0],
177                   control_functions[0x54][0], kk, kk_name),
178                   'ch %d: %s \'%s\' (source note = %d)' % \
179                   (chan, status_bytes[msg][1],
180                   control_functions[0x54][1], kk),
181                   '%d: %s \'%s\' (src N %d)' % \
182                   (chan, status_bytes[msg][2],
183                   control_functions[0x54][2], kk)]])
184
185     def handle_controller_generic(self):
186         c = self.cmd
187         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
188         fn, param = c[0], c[1]
189         default_name = 'undefined'
190         ctrl_fn = control_functions.get(fn, default_name)
191         if ctrl_fn == default_name:
192             ctrl_fn = ('undefined 0x%02x' % fn, 'undef 0x%02x' % fn, '0x%02x' % fn)
193         self.putx([0, ['Channel %d: %s \'%s\' (param = 0x%02x)' % \
194                   (chan, status_bytes[msg][0], ctrl_fn[0], param),
195                   'ch %d: %s \'%s\' (param = 0x%02x)' % \
196                   (chan, status_bytes[msg][1], ctrl_fn[1], param),
197                   '%d: %s \'%s\' is 0x%02x' % \
198                   (chan, status_bytes[msg][2], ctrl_fn[2], param)]])
199
200     def handle_channel_mode(self):
201         # Channel Mode: Bn mm vv
202         # n = channel, mm = mode number (120 - 127), vv = value
203         c = self.cmd
204         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
205         mm, vv = c[0], c[1]
206         mode_fn = control_functions.get(mm, ('undefined', 'undef', 'undef'))
207         # Decode the value based on the mode number.
208         vv_string = ('', '')
209         if mm == 122:           # mode = local control?
210             if vv == 0:
211                 vv_string = ('off', 'off')
212             elif vv == 127:     # mode = poly mode on?
213                 vv_string = ('on', 'on')
214             else:
215                 vv_string = ('(non-standard param value of 0x%02x)' % vv,
216                             '0x%02x' % vv)
217         elif mm == 126:         # mode = mono mode on?
218             if vv != 0:
219                 vv_string = ('(%d channels)' % vv, '(%d ch)' % vv)
220             else:
221                 vv_string = ('(channels \'basic\' through 16)',
222                             '(ch \'basic\' thru 16)')
223         elif vv != 0: # All other channel mode messages expect vv == 0.
224             vv_string = ('(non-standard param value of 0x%02x)' % vv,
225                         '0x%02x' % vv)
226         self.putx([0, ['Channel %d: %s \'%s\' %s' % \
227                       (chan, status_bytes[msg][0], mode_fn[0], vv_string[0]),
228                       'ch %d: %s \'%s\' %s' % \
229                       (chan, status_bytes[msg][1], mode_fn[1], vv_string[1]),
230                       '%d: %s \'%s\' %s' % \
231                       (chan, status_bytes[msg][2], mode_fn[2], vv_string[1])]])
232         self.cmd, self.state = [], 'IDLE'
233         self.soft_clear_status_byte()
234
235     def handle_channel_msg_0xb0(self, is_flushed):
236         # Control change (or channel mode messages): Bn cc vv
237         # n = channel, cc = control number (0 - 119), vv = control value
238         c = self.cmd
239         if len(c) < 2:
240             self.check_for_garbage_flush(is_flushed)
241             return
242         self.es_block = self.es
243         if c[0] in range(0x78, 0x7f + 1):
244             self.handle_channel_mode()
245             return
246         handle_ctrl = getattr(self, 'handle_controller_0x%02x' % c[0],
247                               self.handle_controller_generic)
248         handle_ctrl()
249         self.cmd, self.state = [], 'IDLE'
250         self.soft_clear_status_byte()
251
252     def handle_channel_msg_0xc0(self, is_flushed):
253         # Program change: Cn pp
254         # n = channel, pp = program number (0 - 127)
255         c = self.cmd
256         if len(c) < 1:
257             self.check_for_garbage_flush(is_flushed)
258             return
259         self.es_block = self.es
260         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
261         pp = self.cmd[0] + 1
262         change_type = 'instrument'
263         name = ''
264         if chan != 10:  # channel != percussion
265             name = gm_instruments.get(pp, 'undefined')
266         else:
267             change_type = 'drum kit'
268             name = drum_kit.get(pp, 'undefined')
269         self.putx([0, ['Channel %d: %s to %s %d (assuming %s)' % \
270             (chan, status_bytes[msg][0], change_type, pp, name),
271             'ch %d: %s to %s %d' % \
272             (chan, status_bytes[msg][1], change_type, pp),
273             '%d: %s %d' % \
274             (chan, status_bytes[msg][2], pp)]])
275         self.cmd, self.state = [], 'IDLE'
276         self.soft_clear_status_byte()
277
278     def handle_channel_msg_0xd0(self, is_flushed):
279         # Channel pressure / aftertouch: Dn vv
280         # n = channel, vv = pressure value
281         c = self.cmd
282         if len(c) < 1:
283             self.check_for_garbage_flush(is_flushed)
284             return
285         self.es_block = self.es
286         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
287         vv = self.cmd[0]
288         self.putx([0, ['Channel %d: %s %d' % (chan, status_bytes[msg][0], vv),
289                       'ch %d: %s %d' % (chan, status_bytes[msg][1], vv),
290                       '%d: %s %d' % (chan, status_bytes[msg][2], vv)]])
291         self.cmd, self.state = [], 'IDLE'
292         self.soft_clear_status_byte()
293
294     def handle_channel_msg_0xe0(self, is_flushed):
295         # Pitch bend change: En ll mm
296         # n = channel, ll = pitch bend change LSB, mm = pitch bend change MSB
297         c = self.cmd
298         if len(c) < 2:
299             self.check_for_garbage_flush(is_flushed)
300             return
301         self.es_block = self.es
302         msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
303         ll, mm = self.cmd[0], self.cmd[1]
304         decimal = (mm << 7) + ll
305         self.putx([0, ['Channel %d: %s 0x%02x 0x%02x (%d)' % \
306                       (chan, status_bytes[msg][0], ll, mm, decimal),
307                       'ch %d: %s 0x%02x 0x%02x (%d)' % \
308                       (chan, status_bytes[msg][1], ll, mm, decimal),
309                       '%d: %s (%d)' % \
310                       (chan, status_bytes[msg][2], decimal)]])
311         self.cmd, self.state = [], 'IDLE'
312         self.soft_clear_status_byte()
313
314     def handle_channel_msg_generic(self, is_flushed):
315         # TODO: It should not be possible to hit this code.
316         # It currently can not be unit tested.
317         msg_type = self.status_byte & 0xf0
318         self.es_block = self.es
319         self.putx([2, ['Unknown channel message type: 0x%02x' % msg_type]])
320         self.cmd, self.state = [], 'IDLE'
321         self.soft_clear_status_byte()
322
323     def handle_channel_msg(self, newbyte):
324         if newbyte is not None:
325             if newbyte >= 0x80:
326                 self.set_status_byte(newbyte)
327             else:
328                 self.cmd.append(newbyte)
329         msg_type = self.status_byte & 0xf0
330         handle_msg = getattr(self, 'handle_channel_msg_0x%02x' % msg_type,
331                              self.handle_channel_msg_generic)
332         handle_msg(newbyte is None)
333
334     def handle_sysex_msg(self, newbyte):
335         # SysEx message: 1 status byte, 1-3 manuf. bytes, x data bytes, EOX byte
336         #
337         # SysEx messages are variable length, can be terminated by EOX or
338         # by any non-SysReal status byte, and it clears self.status_byte.
339         #
340         # Note: All System message codes don't utilize self.status_byte.
341         self.hard_clear_status_byte()
342         if newbyte != 0xf7 and newbyte is not None: # EOX
343             self.cmd.append(newbyte)
344             return
345         self.es_block = self.es
346         # Note: Unlike other methods, this code pops bytes out of self.cmd
347         # to isolate the data.
348         msg = self.cmd.pop(0)
349         if len(self.cmd) < 1:
350             self.putx([2, ['%s: truncated manufacturer code (<1 bytes)' % \
351                           status_bytes[msg][0],
352                           '%s: truncated manufacturer (<1 bytes)' % \
353                           status_bytes[msg][1],
354                           '%s: trunc. manu.' % status_bytes[msg][2]]])
355             self.cmd, self.state = [], 'IDLE'
356             return
357         # Extract the manufacturer name (or SysEx realtime or non-realtime).
358         m1 = self.cmd.pop(0)
359         manu = (m1,)
360         if m1 == 0x00:  # If byte == 0, then 2 more manufacturer bytes follow.
361             if len(self.cmd) < 2:
362                 self.putx([2, ['%s: truncated manufacturer code (<3 bytes)' % \
363                           status_bytes[msg][0],
364                           '%s: truncated manufacturer (<3 bytes)' % \
365                           status_bytes[msg][1],
366                           '%s: trunc. manu.' % status_bytes[msg][2]]])
367                 self.cmd, self.state = [], 'IDLE'
368                 return
369             manu = (m1, self.cmd.pop(0), self.cmd.pop(0))
370         default_name = 'undefined'
371         manu_name = sysex_manufacturer_ids.get(manu, default_name)
372         if manu_name == default_name:
373             if len(manu) == 3:
374                 manu_name = ('%s (0x%02x 0x%02x 0x%02x)' % \
375                             (default_name, manu[0], manu[1], manu[2]),
376                             default_name)
377             else:
378                 manu_name = ('%s (0x%02x)' % (default_name, manu[0]),
379                             default_name)
380         else:
381             manu_name = (manu_name, manu_name)
382         # Extract the payload, display in 1 of 2 formats
383         # TODO: Write methods to decode SysEx realtime & non-realtime payloads.
384         payload0 = ''
385         payload1 = ''
386         while len(self.cmd) > 0:
387             byte = self.cmd.pop(0)
388             payload0 += '0x%02x ' % (byte)
389             payload1 += '%02x ' % (byte)
390         if payload0 == '':
391             payload0 = '<empty>'
392             payload1 = '<>'
393         payload = (payload0, payload1)
394         self.putx([0, ['%s: for \'%s\' with payload %s' % \
395                       (status_bytes[msg][0], manu_name[0], payload[0]),
396                       '%s: \'%s\', payload %s' % \
397                       (status_bytes[msg][1], manu_name[1], payload[1]),
398                       '%s: \'%s\', payload %s' % \
399                       (status_bytes[msg][2], manu_name[1], payload[1])]])
400         self.cmd, self.state = [], 'IDLE'
401
402     def handle_syscommon_midi_time_code_quarter_frame_msg(self, newbyte):
403         # MIDI time code quarter frame: F1 nd
404         # n = message type
405         # d = values
406         #
407         # Note: All System message codes don't utilize self.status_byte,
408         # and System Exclusive and System Common clear it.
409         c = self.cmd
410         if len(c) < 2:
411             if newbyte is None:
412                 self.handle_garbage_msg(None)
413             return
414         msg = c[0]
415         nn, dd = (c[1] & 0x70) >> 4, c[1] & 0x0f
416         group = ('System Common', 'SysCom', 'SC')
417         self.es_block = self.es
418         if nn != 7: # If message type does not contain SMPTE type.
419             self.putx([0, ['%s: %s of %s, value 0x%01x' % \
420                           (group[0], status_bytes[msg][0],
421                           quarter_frame_type[nn][0], dd),
422                           '%s: %s of %s, value 0x%01x' % \
423                           (group[1], status_bytes[msg][1],
424                           quarter_frame_type[nn][1], dd),
425                           '%s: %s of %s, value 0x%01x' % \
426                           (group[2], status_bytes[msg][2],
427                           quarter_frame_type[nn][1], dd)]])
428             self.cmd, self.state = [], 'IDLE'
429             return
430         tt = (dd & 0x6) >> 1
431         self.putx([0, ['%s: %s of %s, value 0x%01x for %s' % \
432                       (group[0], status_bytes[msg][0], \
433                       quarter_frame_type[nn][0], dd, smpte_type[tt]),
434                       '%s: %s of %s, value 0x%01x for %s' % \
435                       (group[1], status_bytes[msg][1], \
436                       quarter_frame_type[nn][1], dd, smpte_type[tt]),
437                       '%s: %s of %s, value 0x%01x for %s' % \
438                       (group[2], status_bytes[msg][2], \
439                       quarter_frame_type[nn][1], dd, smpte_type[tt])]])
440         self.cmd, self.state = [], 'IDLE'
441
442     def handle_syscommon_msg(self, newbyte):
443         # System common messages
444         #
445         # There are 5 simple formats (which are directly handled here) and
446         # 1 complex one called MIDI time code quarter frame.
447         #
448         # Note: While the MIDI lists 0xf7 as a "system common" message, it
449         # is actually only used with SysEx messages so it is processed there.
450         #
451         # Note: All System message codes don't utilize self.status_byte.
452         self.hard_clear_status_byte()
453         if newbyte is not None:
454             self.cmd.append(newbyte)
455         c = self.cmd
456         msg = c[0]
457         group = ('System Common', 'SysCom', 'SC')
458         if msg == 0xf1:
459             # MIDI time code quarter frame
460             self.handle_syscommon_midi_time_code_quarter_frame_msg(newbyte)
461             return
462         elif msg == 0xf2:
463             # Song position pointer: F2 ll mm
464             # ll = LSB position, mm = MSB position
465             if len(c) < 3:
466                 if newbyte is None:
467                     self.handle_garbage_msg(None)
468                 return
469             ll, mm = c[1], c[2]
470             decimal = (mm << 7) + ll
471             self.es_block = self.es
472             self.putx([0, ['%s: %s 0x%02x 0x%02x (%d)' % \
473                           (group[0], status_bytes[msg][0], ll, mm, decimal),
474                           '%s: %s 0x%02x 0x%02x (%d)' % \
475                           (group[1], status_bytes[msg][1], ll, mm, decimal),
476                           '%s: %s (%d)' % \
477                           (group[2], status_bytes[msg][2], decimal)]])
478         elif msg == 0xf3:
479             # Song select: F3 ss
480             # ss = song selection number
481             if len(c) < 2:
482                 if newbyte is None:
483                     self.handle_garbage_msg(None)
484                 return
485             ss = c[1]
486             self.es_block = self.es
487             self.putx([0, ['%s: %s number %d' % \
488                           (group[0], status_bytes[msg][0], ss),
489                           '%s: %s number %d' % \
490                           (group[1], status_bytes[msg][1], ss),
491                           '%s: %s # %d' % \
492                           (group[2], status_bytes[msg][2], ss)]])
493         elif msg == 0xf4 or msg == 0xf5 or msg == 0xf6:
494             # Undefined 0xf4, Undefined 0xf5, and Tune Request (respectively).
495             # All are only 1 byte long with no data bytes.
496             self.es_block = self.es
497             self.putx([0, ['%s: %s' % (group[0], status_bytes[msg][0]),
498                           '%s: %s' % (group[1], status_bytes[msg][1]),
499                           '%s: %s' % (group[2], status_bytes[msg][2])]])
500         self.cmd, self.state = [], 'IDLE'
501
502     def handle_sysrealtime_msg(self, newbyte):
503         # System realtime message: 0b11111ttt (t = message type)
504         #
505         # Important: These messages are handled differently from all others
506         # because they are allowed to temporarily interrupt other messages.
507         # The interrupted messages resume after the realtime message is done.
508         # Thus, they mostly leave 'self' the way it was found.
509         #
510         # Note: All System message codes don't utilize self.status_byte.
511         old_ss_block, old_es_block = self.ss_block, self.es_block
512         self.ss_block, self.es_block = self.ss, self.es
513         group = ('System Realtime', 'SysReal', 'SR')
514         self.putx([1, ['%s: %s' % (group[0], status_bytes[newbyte][0]),
515                       '%s: %s' % (group[1], status_bytes[newbyte][1]),
516                       '%s: %s' % (group[2], status_bytes[newbyte][2])]])
517         self.ss_block, self.es_block = old_ss_block, old_es_block
518         # Deliberately not resetting self.cmd or self.state.
519
520     def handle_garbage_msg(self, newbyte):
521         # Handle messages that are either not handled or are corrupt.
522         self.es_block = self.es
523         if newbyte is not None:
524             self.cmd.append(newbyte)
525             return
526         payload = '<empty>'
527         max_bytes = 16 # Put a limit on the length on the hex dump.
528         for index in range(len(self.cmd)):
529             if index == max_bytes:
530                 payload += ' ...'
531                 break
532             if index == 0:
533                 payload = '0x%02x' % self.cmd[index]
534             else:
535                 payload += ' 0x%02x' % self.cmd[index]
536         self.putx([2, ['UNHANDLED DATA: %s' % payload,
537                       'UNHANDLED', '???', '?']])
538         self.cmd, self.state = [], 'IDLE'
539         self.hard_clear_status_byte()
540
541     def handle_state(self, state, newbyte):
542         # 'newbyte' can either be:
543         # 1. Value between 0x00-0xff, deal with the byte normally.
544         # 2. Value of 'None' which means "flush any buffered data".
545         if state == 'HANDLE CHANNEL MSG':
546             self.handle_channel_msg(newbyte)
547         elif state == 'HANDLE SYSEX MSG':
548             self.handle_sysex_msg(newbyte)
549         elif state == 'HANDLE SYSCOMMON MSG':
550             self.handle_syscommon_msg(newbyte)
551         elif state == 'HANDLE SYSREALTIME MSG':
552             self.handle_sysrealtime_msg(newbyte)
553         elif state == 'BUFFER GARBAGE MSG':
554             self.handle_garbage_msg(newbyte)
555
556     def get_next_state(self, newbyte):
557         # 'newbyte' must be a valid byte between 0x00 and 0xff.
558         #
559         # Try to determine the state based off of the 'newbyte' parameter.
560         if newbyte in range(0x80, 0xef + 1):
561             return 'HANDLE CHANNEL MSG'
562         if newbyte == 0xf0:
563             return 'HANDLE SYSEX MSG'
564         if newbyte in range(0xf1, 0xf7):
565             return'HANDLE SYSCOMMON MSG'
566         if newbyte in range(0xf8, 0xff + 1):
567             return 'HANDLE SYSREALTIME MSG'
568         # Passing 0xf7 is an error; messages don't start with 0xf7.
569         if newbyte == 0xf7:
570             return 'BUFFER GARBAGE MSG'
571         # Next, base the state off of self.status_byte.
572         if self.status_byte < 0x80:
573             return 'BUFFER GARBAGE MSG'
574         return self.get_next_state(self.status_byte)
575
576     def decode(self, ss, es, data):
577         ptype, rxtx, pdata = data
578         state = 'IDLE'
579
580         # For now, ignore all UART packets except the actual data packets.
581         if ptype != 'DATA':
582             return
583
584         # We're only interested in the byte value (not individual bits).
585         pdata = pdata[0]
586
587         # Short MIDI overview:
588         #  - Status bytes are 0x80-0xff, data bytes are 0x00-0x7f.
589         #  - Most messages: 1 status byte, 1-2 data bytes.
590         #  - Real-time system messages: always 1 byte.
591         #  - SysEx messages: 1 status byte, n data bytes, EOX byte.
592         #
593         # Aspects of the MIDI protocol that complicate decoding:
594         #  - MIDI System Realtime messages can briefly interrupt other
595         #    messages already in progress.
596         #  - "Running Status" allows for omitting the status byte in most
597         #    scenarios if sequential messages have the same status byte.
598         #  - System Exclusive (SysEx) messages can be terminated by ANY
599         #    status byte (not limited to EOX byte).
600
601         # State machine.
602         if pdata >= 0x80 and pdata != 0xf7:
603             state = self.get_next_state(pdata)
604             if state != 'HANDLE SYSREALTIME MSG' and self.state != 'IDLE':
605                 # Flush the previous data since a new message is starting.
606                 self.handle_state(self.state, None)
607             # Cache ss and es -after- flushing previous data.
608             self.ss, self.es = ss, es
609             # This is a status byte, remember the start sample.
610             if state != 'HANDLE SYSREALTIME MSG':
611                 self.ss_block = ss
612         elif self.state == 'IDLE' or self.state == 'BUFFER GARBAGE MSG':
613             # Deal with "running status" or that we're buffering garbage.
614             self.ss, self.es = ss, es
615             if self.state == 'IDLE':
616                 self.ss_block = ss
617             state = self.get_next_state(pdata)
618         else:
619             self.ss, self.es = ss, es
620             state = self.state
621
622         # Yes, this is intentionally _not_ an 'elif' here.
623         if state != 'HANDLE SYSREALTIME MSG':
624             self.state = state
625         if state == 'BUFFER GARBAGE MSG':
626             self.status_byte = 0
627         self.handle_state(state, pdata)