2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2013-2016 Uwe Hermann <uwe@hermann-uwe.de>
5 ## Copyright (C) 2016 Chris Dreher <chrisdreher@hotmail.com>
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.
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.
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/>.
21 import sigrokdecode as srd
27 class Decoder(srd.Decoder):
31 longname = 'Musical Instrument Digital Interface'
32 desc = 'Musical Instrument Digital Interface (MIDI) protocol.'
36 tags = ['Audio', 'PC']
38 ('text-verbose', 'Text (verbose)'),
39 ('text-sysreal-verbose', 'SysReal text (verbose)'),
40 ('text-error', 'Error text'),
43 ('normal', 'Normal', (0, 2)),
44 ('sys-real', 'SysReal', (1,)),
53 self.explicit_status_byte = False
61 self.out_ann = self.register(srd.OUTPUT_ANN)
64 self.put(self.ss_block, self.es_block, self.out_ann, data)
66 def get_note_name(self, channel, note):
68 return chromatic_notes[note]
70 return 'assuming ' + percussion_notes.get(note, 'undefined')
72 def check_for_garbage_flush(self, is_flushed):
74 if self.explicit_status_byte:
75 self.cmd.insert(0, self.status_byte)
76 self.handle_garbage_msg(None)
78 def soft_clear_status_byte(self):
79 self.explicit_status_byte = False
81 def hard_clear_status_byte(self):
83 self.explicit_status_byte = False
85 def set_status_byte(self, newbyte):
86 self.status_byte = newbyte
87 self.explicit_status_byte = True
89 def handle_channel_msg_0x80(self, is_flushed):
91 # n = channel, kk = note, vv = velocity
94 self.check_for_garbage_flush(is_flushed)
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()
109 def handle_channel_msg_0x90(self, is_flushed):
111 # n = channel, kk = note, vv = velocity
112 # If velocity == 0 that actually means 'note off', though.
115 self.check_for_garbage_flush(is_flushed)
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()
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
136 self.check_for_garbage_flush(is_flushed)
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()
151 def handle_controller_0x44(self):
152 # Legato footswitch: Bn 44 vv
153 # n = channel, vv = value (<= 0x3f: normal, > 0x3f: legato)
155 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 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])]])
168 def handle_controller_0x54(self):
169 # Portamento control (PTC): Bn 54 kk
170 # n = channel, kk = source note for pitch reference
172 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 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)]])
185 def handle_controller_generic(self):
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)]])
200 def handle_channel_mode(self):
201 # Channel Mode: Bn mm vv
202 # n = channel, mm = mode number (120 - 127), vv = value
204 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
206 mode_fn = control_functions.get(mm, ('undefined', 'undef', 'undef'))
207 # Decode the value based on the mode number.
209 if mm == 122: # mode = local control?
211 vv_string = ('off', 'off')
212 elif vv == 127: # mode = poly mode on?
213 vv_string = ('on', 'on')
215 vv_string = ('(non-standard param value of 0x%02x)' % vv,
217 elif mm == 126: # mode = mono mode on?
219 vv_string = ('(%d channels)' % vv, '(%d ch)' % vv)
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,
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()
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
240 self.check_for_garbage_flush(is_flushed)
242 self.es_block = self.es
243 if c[0] in range(0x78, 0x7f + 1):
244 self.handle_channel_mode()
246 handle_ctrl = getattr(self, 'handle_controller_0x%02x' % c[0],
247 self.handle_controller_generic)
249 self.cmd, self.state = [], 'IDLE'
250 self.soft_clear_status_byte()
252 def handle_channel_msg_0xc0(self, is_flushed):
253 # Program change: Cn pp
254 # n = channel, pp = program number (0 - 127)
257 self.check_for_garbage_flush(is_flushed)
259 self.es_block = self.es
260 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
262 change_type = 'instrument'
264 if chan != 10: # channel != percussion
265 name = gm_instruments.get(pp, 'undefined')
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),
274 (chan, status_bytes[msg][2], pp)]])
275 self.cmd, self.state = [], 'IDLE'
276 self.soft_clear_status_byte()
278 def handle_channel_msg_0xd0(self, is_flushed):
279 # Channel pressure / aftertouch: Dn vv
280 # n = channel, vv = pressure value
283 self.check_for_garbage_flush(is_flushed)
285 self.es_block = self.es
286 msg, chan = self.status_byte & 0xf0, (self.status_byte & 0x0f) + 1
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()
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
299 self.check_for_garbage_flush(is_flushed)
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),
310 (chan, status_bytes[msg][2], decimal)]])
311 self.cmd, self.state = [], 'IDLE'
312 self.soft_clear_status_byte()
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()
323 def handle_channel_msg(self, newbyte):
324 if newbyte is not None:
326 self.set_status_byte(newbyte)
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)
334 def handle_sysex_msg(self, newbyte):
335 # SysEx message: 1 status byte, 1-3 manuf. bytes, x data bytes, EOX byte
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.
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)
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'
357 # Extract the manufacturer name (or SysEx realtime or non-realtime).
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'
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:
374 manu_name = ('%s (0x%02x 0x%02x 0x%02x)' % \
375 (default_name, manu[0], manu[1], manu[2]),
378 manu_name = ('%s (0x%02x)' % (default_name, manu[0]),
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.
386 while len(self.cmd) > 0:
387 byte = self.cmd.pop(0)
388 payload0 += '0x%02x ' % (byte)
389 payload1 += '%02x ' % (byte)
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'
402 def handle_syscommon_midi_time_code_quarter_frame_msg(self, newbyte):
403 # MIDI time code quarter frame: F1 nd
407 # Note: All System message codes don't utilize self.status_byte,
408 # and System Exclusive and System Common clear it.
412 self.handle_garbage_msg(None)
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'
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'
442 def handle_syscommon_msg(self, newbyte):
443 # System common messages
445 # There are 5 simple formats (which are directly handled here) and
446 # 1 complex one called MIDI time code quarter frame.
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.
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)
457 group = ('System Common', 'SysCom', 'SC')
459 # MIDI time code quarter frame
460 self.handle_syscommon_midi_time_code_quarter_frame_msg(newbyte)
463 # Song position pointer: F2 ll mm
464 # ll = LSB position, mm = MSB position
467 self.handle_garbage_msg(None)
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),
477 (group[2], status_bytes[msg][2], decimal)]])
480 # ss = song selection number
483 self.handle_garbage_msg(None)
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),
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'
502 def handle_sysrealtime_msg(self, newbyte):
503 # System realtime message: 0b11111ttt (t = message type)
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.
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.
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)
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:
533 payload = '0x%02x' % self.cmd[index]
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()
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)
556 def get_next_state(self, newbyte):
557 # 'newbyte' must be a valid byte between 0x00 and 0xff.
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'
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.
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)
576 def decode(self, ss, es, data):
577 ptype, rxtx, pdata = data
580 # For now, ignore all UART packets except the actual data packets.
584 # We're only interested in the byte value (not individual bits).
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.
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).
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':
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':
617 state = self.get_next_state(pdata)
619 self.ss, self.es = ss, es
622 # Yes, this is intentionally _not_ an 'elif' here.
623 if state != 'HANDLE SYSREALTIME MSG':
625 if state == 'BUFFER GARBAGE MSG':
627 self.handle_state(state, pdata)