Skip to content

ListenTo() panics for some message types

The existing function _channelMessage is correctly determining which bytes of the message to use to return the appropriate message type. However, it takes two data bytes as arguments. data2 is not populated for AfterTouch and ProgramChange messages. https://gitlab.com/gomidi/midi/-/blob/master/v2/listen.go?ref_type=heads#L8

_channelMessage is only used inside ListenTo, which always attempts to index into the message byte slice to pass both data1 and data2 bytes into _channelMessage. For AfterTouch or ProgramChange messages, this will always panic with panic: runtime error: index out of range [2] with length 2. https://gitlab.com/gomidi/midi/-/blob/master/v2/listen.go?ref_type=heads#L166

This can easily be fixed by making _channelMessage take the full byte slice and only attempt to index into data2 if we have already decoded the message type and determined it to be a message that uses data2.

This change will not affect any other parts of the code. I do not foresee any significant performance impact. I would be happy to open a PR that fixes this. We may also want to consider adding a test that will catch behavior like this in the future.