]> sigrok.org Git - libsigrokdecode.git/blame - decoders/midi/pd.py
midi: Add missing copyright lines.
[libsigrokdecode.git] / decoders / midi / pd.py
CommitLineData
17f5df4f
UH
1##
2## This file is part of the libsigrokdecode project.
3##
08475857
UH
4## Copyright (C) 2013-2016 Uwe Hermann <uwe@hermann-uwe.de>
5## Copyright (C) 2016 Chris Dreher <chrisdreher@hotmail.com>
17f5df4f
UH
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
17f5df4f
UH
22import sigrokdecode as srd
23from .lists import *
24
25RX = 0
26TX = 1
27
28class Decoder(srd.Decoder):
12851357 29 api_version = 2
17f5df4f
UH
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']
da9bcbd9
BV
37 annotations = (
38 ('text-verbose', 'Human-readable text (verbose)'),
6aa03e3a
C
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,)),
da9bcbd9 45 )
17f5df4f 46
92b7b49f 47 def __init__(self):
17f5df4f 48 self.state = 'IDLE'
6aa03e3a
C
49 self.status_byte = 0
50 self.explicit_status_byte = False
51 self.cmd = []
17f5df4f
UH
52 self.ss = None
53 self.es = None
54 self.ss_block = None
55 self.es_block = None
56
8915b346 57 def start(self):
be465111 58 self.out_ann = self.register(srd.OUTPUT_ANN)
17f5df4f 59
17f5df4f
UH
60 def putx(self, data):
61 self.put(self.ss_block, self.es_block, self.out_ann, data)
62
b0fc934a
CD
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
6aa03e3a 69 def check_for_garbage_flush(self, is_flushed):
740a4a52
UH
70 if is_flushed:
71 if self.explicit_status_byte:
6aa03e3a
C
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):
17f5df4f
UH
87 # Note off: 8n kk vv
88 # n = channel, kk = note, vv = velocity
89 c = self.cmd
6aa03e3a
C
90 if len(c) < 2:
91 self.check_for_garbage_flush(is_flushed)
17f5df4f
UH
92 return
93 self.es_block = self.es
6aa03e3a
C
94 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
95 note, velocity = c[0], c[1]
b0fc934a
CD
96 note_name = self.get_note_name(chan, note)
97 self.putx([0, ['Channel %d: %s (note = %d \'%s\', velocity = %d)' % \
9cc1ddf9
C
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)]])
17f5df4f 103 self.cmd, self.state = [], 'IDLE'
6aa03e3a 104 self.soft_clear_status_byte()
17f5df4f 105
6aa03e3a 106 def handle_channel_msg_0x90(self, is_flushed):
17f5df4f
UH
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
6aa03e3a
C
111 if len(c) < 2:
112 self.check_for_garbage_flush(is_flushed)
17f5df4f 113 return
ee7de90f 114 self.es_block = self.es
6aa03e3a
C
115 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
116 note, velocity = c[0], c[1]
9cc1ddf9 117 s = status_bytes[0x80] if (velocity == 0) else status_bytes[msg]
b0fc934a
CD
118 note_name = self.get_note_name(chan, note)
119 self.putx([0, ['Channel %d: %s (note = %d \'%s\', velocity = %d)' % \
9cc1ddf9
C
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)]])
17f5df4f 125 self.cmd, self.state = [], 'IDLE'
6aa03e3a 126 self.soft_clear_status_byte()
17f5df4f 127
6aa03e3a 128 def handle_channel_msg_0xa0(self, is_flushed):
17f5df4f
UH
129 # Polyphonic key pressure / aftertouch: An kk vv
130 # n = channel, kk = polyphonic key pressure, vv = pressure value
b0fc934a 131 c = self.cmd
6aa03e3a
C
132 if len(c) < 2:
133 self.check_for_garbage_flush(is_flushed)
b0fc934a
CD
134 return
135 self.es_block = self.es
6aa03e3a
C
136 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
137 note, pressure = c[0], c[1]
b0fc934a 138 note_name = self.get_note_name(chan, note)
9cc1ddf9
C
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)]])
b0fc934a 145 self.cmd, self.state = [], 'IDLE'
6aa03e3a 146 self.soft_clear_status_byte()
17f5df4f
UH
147
148 def handle_controller_0x44(self):
149 # Legato footswitch: Bn 44 vv
150 # n = channel, vv = value (<= 0x3f: normal, > 0x3f: legato)
9cc1ddf9 151 c = self.cmd
6aa03e3a
C
152 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
153 vv = c[1]
9cc1ddf9
C
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])]])
17f5df4f
UH
164
165 def handle_controller_0x54(self):
166 # Portamento control (PTC): Bn 54 kk
167 # n = channel, kk = source note for pitch reference
9cc1ddf9 168 c = self.cmd
6aa03e3a
C
169 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
170 kk = c[1]
b0fc934a 171 kk_name = self.get_note_name(chan, kk)
9cc1ddf9
C
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)]])
17f5df4f
UH
181
182 def handle_controller_generic(self):
183 c = self.cmd
6aa03e3a
C
184 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
185 fn, param = c[0], c[1]
b0fc934a
CD
186 default_name = 'undefined'
187 ctrl_fn = control_functions.get(fn, default_name)
188 if ctrl_fn == default_name:
9cc1ddf9
C
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)]])
17f5df4f 196
b0fc934a
CD
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
6aa03e3a
C
201 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
202 mm, vv = c[0], c[1]
9cc1ddf9 203 mode_fn = control_functions.get(mm, ('undefined', 'undef', 'undef'))
b0fc934a 204 # Decode the value based on the mode number.
9cc1ddf9 205 vv_string = ('', '')
b0fc934a
CD
206 if mm == 122: # mode = local control?
207 if vv == 0:
9cc1ddf9 208 vv_string = ('off', 'off')
b0fc934a 209 elif vv == 127: # mode = poly mode on?
9cc1ddf9 210 vv_string = ('on', 'on')
b0fc934a 211 else:
9cc1ddf9
C
212 vv_string = ('(non-standard param value of 0x%02x)' % vv,
213 '0x%02x' % vv)
b0fc934a
CD
214 elif mm == 126: # mode = mono mode on?
215 if vv != 0:
9cc1ddf9 216 vv_string = ('(%d channels)' % vv, '(%d ch)' % vv)
b0fc934a 217 else:
9cc1ddf9
C
218 vv_string = ('(channels \'basic\' through 16)',
219 '(ch \'basic\' thru 16)')
b0fc934a 220 elif vv != 0: # All other channel mode messages expect vv == 0.
9cc1ddf9
C
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])]])
b0fc934a 229 self.cmd, self.state = [], 'IDLE'
6aa03e3a 230 self.soft_clear_status_byte()
b0fc934a 231
6aa03e3a 232 def handle_channel_msg_0xb0(self, is_flushed):
17f5df4f
UH
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
6aa03e3a
C
236 if len(c) < 2:
237 self.check_for_garbage_flush(is_flushed)
17f5df4f
UH
238 return
239 self.es_block = self.es
6aa03e3a 240 if c[0] in range(0x78, 0x7f + 1):
b0fc934a
CD
241 self.handle_channel_mode()
242 return
6aa03e3a 243 handle_ctrl = getattr(self, 'handle_controller_0x%02x' % c[0],
17f5df4f
UH
244 self.handle_controller_generic)
245 handle_ctrl()
246 self.cmd, self.state = [], 'IDLE'
6aa03e3a 247 self.soft_clear_status_byte()
17f5df4f 248
6aa03e3a 249 def handle_channel_msg_0xc0(self, is_flushed):
17f5df4f
UH
250 # Program change: Cn pp
251 # n = channel, pp = program number (0 - 127)
b0fc934a 252 c = self.cmd
6aa03e3a
C
253 if len(c) < 1:
254 self.check_for_garbage_flush(is_flushed)
b0fc934a
CD
255 return
256 self.es_block = self.es
6aa03e3a
C
257 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
258 pp = self.cmd[0] + 1
b0fc934a
CD
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)' % \
9cc1ddf9
C
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)]])
b0fc934a 272 self.cmd, self.state = [], 'IDLE'
6aa03e3a 273 self.soft_clear_status_byte()
17f5df4f 274
6aa03e3a 275 def handle_channel_msg_0xd0(self, is_flushed):
17f5df4f
UH
276 # Channel pressure / aftertouch: Dn vv
277 # n = channel, vv = pressure value
b0fc934a 278 c = self.cmd
6aa03e3a
C
279 if len(c) < 1:
280 self.check_for_garbage_flush(is_flushed)
b0fc934a
CD
281 return
282 self.es_block = self.es
6aa03e3a
C
283 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
284 vv = self.cmd[0]
9cc1ddf9
C
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)]])
b0fc934a 288 self.cmd, self.state = [], 'IDLE'
6aa03e3a 289 self.soft_clear_status_byte()
17f5df4f 290
6aa03e3a 291 def handle_channel_msg_0xe0(self, is_flushed):
17f5df4f
UH
292 # Pitch bend change: En ll mm
293 # n = channel, ll = pitch bend change LSB, mm = pitch bend change MSB
b0fc934a 294 c = self.cmd
6aa03e3a
C
295 if len(c) < 2:
296 self.check_for_garbage_flush(is_flushed)
b0fc934a
CD
297 return
298 self.es_block = self.es
6aa03e3a
C
299 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
300 ll, mm = self.cmd[0], self.cmd[1]
b0fc934a
CD
301 decimal = (mm << 7) + ll
302 self.putx([0, ['Channel %d: %s 0x%02x 0x%02x (%d)' % \
9cc1ddf9
C
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)]])
b0fc934a 308 self.cmd, self.state = [], 'IDLE'
6aa03e3a 309 self.soft_clear_status_byte()
17f5df4f 310
6aa03e3a 311 def handle_channel_msg_generic(self, is_flushed):
b0fc934a
CD
312 # TODO: It should not be possible to hit this code.
313 # It currently can not be unit tested.
6aa03e3a 314 msg_type = self.status_byte & 0xf0
b0fc934a 315 self.es_block = self.es
6aa03e3a 316 self.putx([2, ['Unknown channel message type: 0x%02x' % msg_type]])
b0fc934a 317 self.cmd, self.state = [], 'IDLE'
6aa03e3a 318 self.soft_clear_status_byte()
17f5df4f
UH
319
320 def handle_channel_msg(self, newbyte):
73c8d0fb 321 if newbyte is not None:
6aa03e3a
C
322 if newbyte >= 0x80:
323 self.set_status_byte(newbyte)
324 else:
325 self.cmd.append(newbyte)
326 msg_type = self.status_byte & 0xf0
17f5df4f
UH
327 handle_msg = getattr(self, 'handle_channel_msg_0x%02x' % msg_type,
328 self.handle_channel_msg_generic)
73c8d0fb 329 handle_msg(newbyte is None)
17f5df4f
UH
330
331 def handle_sysex_msg(self, newbyte):
b0fc934a 332 # SysEx message: 1 status byte, 1-3 manuf. bytes, x data bytes, EOX byte
6aa03e3a 333 #
f8a6ae16 334 # SysEx messages are variable length, can be terminated by EOX or
6aa03e3a 335 # by any non-SysReal status byte, and it clears self.status_byte.
f8a6ae16
UH
336 #
337 # Note: All System message codes don't utilize self.status_byte.
6aa03e3a 338 self.hard_clear_status_byte()
73c8d0fb 339 if newbyte != 0xf7 and newbyte is not None: # EOX
6aa03e3a 340 self.cmd.append(newbyte)
17f5df4f
UH
341 return
342 self.es_block = self.es
b0fc934a
CD
343 # Note: Unlike other methods, this code pops bytes out of self.cmd
344 # to isolate the data.
6aa03e3a 345 msg = self.cmd.pop(0)
b0fc934a 346 if len(self.cmd) < 1:
6aa03e3a 347 self.putx([2, ['%s: truncated manufacturer code (<1 bytes)' % \
9cc1ddf9
C
348 status_bytes[msg][0],
349 '%s: truncated manufacturer (<1 bytes)' % \
350 status_bytes[msg][1],
351 '%s: trunc. manu.' % status_bytes[msg][2]]])
b0fc934a
CD
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:
6aa03e3a 359 self.putx([2, ['%s: truncated manufacturer code (<3 bytes)' % \
9cc1ddf9
C
360 status_bytes[msg][0],
361 '%s: truncated manufacturer (<3 bytes)' % \
362 status_bytes[msg][1],
363 '%s: trunc. manu.' % status_bytes[msg][2]]])
b0fc934a
CD
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:
9cc1ddf9
C
371 manu_name = ('%s (0x%02x 0x%02x 0x%02x)' % \
372 (default_name, manu[0], manu[1], manu[2]),
373 default_name)
b0fc934a 374 else:
9cc1ddf9
C
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
b0fc934a 380 # TODO: Write methods to decode SysEx realtime & non-realtime payloads.
9cc1ddf9
C
381 payload0 = ''
382 payload1 = ''
b0fc934a 383 while len(self.cmd) > 0:
9cc1ddf9
C
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])]])
b0fc934a
CD
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
6aa03e3a 403 #
f8a6ae16 404 # Note: All System message codes don't utilize self.status_byte,
6aa03e3a 405 # and System Exclusive and System Common clear it.
b0fc934a
CD
406 c = self.cmd
407 if len(c) < 2:
73c8d0fb 408 if newbyte is None:
6aa03e3a 409 self.handle_garbage_msg(None)
b0fc934a 410 return
6aa03e3a
C
411 msg = c[0]
412 nn, dd = (c[1] & 0x70) >> 4, c[1] & 0x0f
9cc1ddf9 413 group = ('System Common', 'SysCom', 'SC')
b0fc934a
CD
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' % \
9cc1ddf9
C
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)]])
b0fc934a
CD
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' % \
9cc1ddf9
C
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])]])
17f5df4f
UH
437 self.cmd, self.state = [], 'IDLE'
438
439 def handle_syscommon_msg(self, newbyte):
b0fc934a
CD
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.
f8a6ae16
UH
447 #
448 # Note: All System message codes don't utilize self.status_byte.
6aa03e3a 449 self.hard_clear_status_byte()
73c8d0fb 450 if newbyte is not None:
6aa03e3a 451 self.cmd.append(newbyte)
b0fc934a 452 c = self.cmd
6aa03e3a 453 msg = c[0]
9cc1ddf9 454 group = ('System Common', 'SysCom', 'SC')
b0fc934a
CD
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:
73c8d0fb 463 if newbyte is None:
6aa03e3a 464 self.handle_garbage_msg(None)
b0fc934a 465 return
6aa03e3a 466 ll, mm = c[1], c[2]
b0fc934a
CD
467 decimal = (mm << 7) + ll
468 self.es_block = self.es
469 self.putx([0, ['%s: %s 0x%02x 0x%02x (%d)' % \
9cc1ddf9
C
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)]])
b0fc934a
CD
475 elif msg == 0xf3:
476 # Song select: F3 ss
477 # ss = song selection number
478 if len(c) < 2:
73c8d0fb 479 if newbyte is None:
6aa03e3a 480 self.handle_garbage_msg(None)
b0fc934a 481 return
6aa03e3a 482 ss = c[1]
b0fc934a 483 self.es_block = self.es
9cc1ddf9
C
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)]])
b0fc934a
CD
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
9cc1ddf9
C
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])]])
b0fc934a 497 self.cmd, self.state = [], 'IDLE'
17f5df4f
UH
498
499 def handle_sysrealtime_msg(self, newbyte):
500 # System realtime message: 0b11111ttt (t = message type)
6aa03e3a 501 #
f8a6ae16 502 # Important: These messages are handled differently from all others
6aa03e3a
C
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.
f8a6ae16
UH
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
9cc1ddf9 510 group = ('System Realtime', 'SysReal', 'SR')
6aa03e3a 511 self.putx([1, ['%s: %s' % (group[0], status_bytes[newbyte][0]),
9cc1ddf9
C
512 '%s: %s' % (group[1], status_bytes[newbyte][1]),
513 '%s: %s' % (group[2], status_bytes[newbyte][2])]])
f8a6ae16
UH
514 self.ss_block, self.es_block = old_ss_block, old_es_block
515 # Deliberately not resetting self.cmd or self.state.
6aa03e3a
C
516
517 def handle_garbage_msg(self, newbyte):
f8a6ae16 518 # Handle messages that are either not handled or are corrupt.
6aa03e3a 519 self.es_block = self.es
73c8d0fb 520 if newbyte is not None:
6aa03e3a
C
521 self.cmd.append(newbyte)
522 return
523 payload = '<empty>'
f8a6ae16
UH
524 max_bytes = 16 # Put a limit on the length on the hex dump.
525 for index in range(len(self.cmd)):
6aa03e3a 526 if index == max_bytes:
f8a6ae16 527 payload += ' ...'
6aa03e3a
C
528 break
529 if index == 0:
530 payload = '0x%02x' % self.cmd[index]
531 else:
f8a6ae16 532 payload += ' 0x%02x' % self.cmd[index]
6aa03e3a 533 self.putx([2, ['UNHANDLED DATA: %s' % payload,
f8a6ae16 534 'UNHANDLED', '???', '?']])
17f5df4f 535 self.cmd, self.state = [], 'IDLE'
6aa03e3a
C
536 self.hard_clear_status_byte()
537
538 def handle_state(self, state, newbyte):
539 # 'newbyte' can either be:
f8a6ae16
UH
540 # 1. Value between 0x00-0xff, deal with the byte normally.
541 # 2. Value of 'None' which means "flush any buffered data".
6aa03e3a
C
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):
f8a6ae16 554 # 'newbyte' must be a valid byte between 0x00 and 0xff.
6aa03e3a 555 #
f8a6ae16 556 # Try to determine the state based off of the 'newbyte' parameter.
6aa03e3a
C
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'
f8a6ae16 565 # Passing 0xf7 is an error; messages don't start with 0xf7.
6aa03e3a
C
566 if newbyte == 0xf7:
567 return 'BUFFER GARBAGE MSG'
f8a6ae16 568 # Next, base the state off of self.status_byte.
6aa03e3a
C
569 if self.status_byte < 0x80:
570 return 'BUFFER GARBAGE MSG'
571 return self.get_next_state(self.status_byte)
17f5df4f
UH
572
573 def decode(self, ss, es, data):
574 ptype, rxtx, pdata = data
6aa03e3a 575 state = 'IDLE'
17f5df4f
UH
576
577 # For now, ignore all UART packets except the actual data packets.
578 if ptype != 'DATA':
579 return
580
7cf698c5
UH
581 # We're only interested in the byte value (not individual bits).
582 pdata = pdata[0]
583
17f5df4f
UH
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.
f8a6ae16 589 #
6aa03e3a
C
590 # Aspects of the MIDI protocol that complicate decoding:
591 # - MIDI System Realtime messages can briefly interrupt other
f8a6ae16 592 # messages already in progress.
6aa03e3a
C
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
17f5df4f 598 # State machine.
6aa03e3a
C
599 if pdata >= 0x80 and pdata != 0xf7:
600 state = self.get_next_state(pdata)
601 if state != 'HANDLE SYSREALTIME MSG' and self.state != 'IDLE':
f8a6ae16 602 # Flush the previous data since a new message is starting.
6aa03e3a 603 self.handle_state(self.state, None)
f8a6ae16 604 # Cache ss and es -after- flushing previous data.
6aa03e3a 605 self.ss, self.es = ss, es
17f5df4f 606 # This is a status byte, remember the start sample.
f8a6ae16
UH
607 if state != 'HANDLE SYSREALTIME MSG':
608 self.ss_block = ss
6aa03e3a 609 elif self.state == 'IDLE' or self.state == 'BUFFER GARBAGE MSG':
f8a6ae16 610 # Deal with "running status" or that we're buffering garbage.
6aa03e3a 611 self.ss, self.es = ss, es
f8a6ae16
UH
612 if self.state == 'IDLE':
613 self.ss_block = ss
6aa03e3a
C
614 state = self.get_next_state(pdata)
615 else:
616 self.ss, self.es = ss, es
617 state = self.state
17f5df4f
UH
618
619 # Yes, this is intentionally _not_ an 'elif' here.
6aa03e3a
C
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)