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