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