Decoding the Akai Fire MIDI implementation – part 3

This continues the journey of analysing how the Akai Fire is controlled over MIDI and deals with the OLED display.

The OLED is a challenge!

Looking at the OLED, it’s small at 128×64 pixels, with each pixel being taller than it is wide. But here’s the proof that you can write to the OLED!

As an embedded engineer, it’s much easier to keep your firmware simple and offload as much as you can to something that is easily changed. Burdening users with continual firmware updates that have the possibility to fail, or even brick the device, is something that you want to do only if you’re superconfident. Best would be to buy the technology from SEGGER, an unashamed plug for our emLoad product!

The OLED is small, so my spidey senses tell me that the host will be constructing what it wants to display. It will then sending that bitmap wrapped in a SysEx to the Fire because this is the only way to transport large amounts of data with MIDI. It also makes sense—why fix displays in your firmware where it’s difficult to modify when you can do everything on the PC where program changes are easy?

And that is exactly how it pans out.

Replaying messages

Having cracked the pad RGB SysEx, it’s time to tackle the other SysEx messages that I found. And this is where it comes down to observation and experimentation.

How do you figure out what a long SysEx message does? Easy. You capture it and you send it to its destination and see what happens! For the OLED, this is exactly what I did, capture the SysEx messages and replay them under my control and observe their effect.

Playing them back, you can sometimes see what they do and indeed, I can write to the OLED display by sending it specific messages that FL Studio sent in the past, and I can alter the entire display.

Mutating messages

Experimentation is straightforward as well. There are lots of zeros in the candidate message, and I equate zero with “no pixel” for the OLED. If I change one of the zero bytes to 7F, thinking “seven pixels set” what do I see? I see seven pixels set, but in some weird non-intuitive pattern. The pattern is not entirely random, but not entirely regular either. Well, save that for another day.

If I set most zero bytes to 7F, leaving a few zero bytes at the beginning as zero just in case they are important controls, and I get a mainly white display.

Stepping back in the message byte by byte, setting each to 7F in turn, I can get the entire display to turn white. Result! There are a few bytes at the start of the message, but that’s OK, I don’t need to understand what they mean, I just need to accept that they are there and always send them. (In fact, I do now understand what they mean!)

The warped pixel arrangement

Back to the pixel arrangement. To understand how things are mapped to the OLED, I send messages where each successive message has a single additional bit set. When the message is sent, I expect to see one pixel on the display change. Using a magnifying glass, I write down the mapping of pixels on display to bits in the SysEx message.

What I see is that strange pattern repeat itself over and over, regularly.

The display is divided into eight bands of 8×128 pixels.  Each band in this arrangement is written in a block of 8×7 pixels, where the bit position in the MIDI SysEx message bears no linear relationship with a pixel on display.

Mapping this 8×7 block to MIDI messages looks like this:

    MIDI Message bytes (msb always 0)                  Display positions
   7    6    5    4    3    2    1    0           0    1    2    3    4    5    6
+----+----+----+----+----+----+----+----+      +----+----+----+----+----+----+----+
|  - |  6 |  5 |  4 |  3 |  2 |  1 |  0 |   0  | 13 | 19 | 25 | 31 | 37 | 43 | 49 |
|  - | 13 | 12 | 11 | 10 |  9 |  8 |  7 |   1  |  0 | 20 | 26 | 32 | 38 | 44 | 50 |
|  - | 20 | 19 | 18 | 17 | 16 | 15 | 14 |   2  |  1 |  7 | 27 | 33 | 39 | 45 | 51 |
|  - | 27 | 26 | 25 | 24 | 23 | 22 | 21 |   3  |  2 |  8 | 14 | 34 | 40 | 46 | 52 |
|  - | 34 | 33 | 32 | 31 | 30 | 29 | 28 |   4  |  3 |  9 | 15 | 21 | 41 | 47 | 53 |
|  - | 41 | 40 | 39 | 38 | 37 | 36 | 35 |   5  |  4 | 10 | 16 | 22 | 28 | 48 | 54 |
|  - | 48 | 47 | 46 | 45 | 44 | 43 | 42 |   6  |  5 | 11 | 17 | 23 | 29 | 35 | 55 |
|  - | 55 | 54 | 53 | 52 | 51 | 50 | 49 |   7  |  6 | 12 | 18 | 24 | 30 | 36 | 42 |
+----+----+----+----+----+----+----+----+      +----+----+----+----+----+----+----+

The left-hand side shows the MIDI message bytes in transmission order, 0 through 7, and a reference bit number, 0 through 56. The most-significant bit of each MIDI byte must be zero by the MIDI specification.

The right-hand side shows how each of those reference bits controls a pixel on the display. No, there is no obvious logic to the mapping. For instance, follow column 1 of the display, from 7 to 12 going down, then see where 13 lies, and then 14. Bizarre.

With this understood, I put together a display function that plots a pixel using regular coordinates using the warped pixel mapping:

static const U8 _aBitMutate[8][7] = {
  { 13,  19,  25,  31,  37,  43,  49 },
  {  0,  20,  26,  32,  38,  44,  50 },
  {  1,   7,  27,  33,  39,  45,  51 },
  {  2,   8,  14,  34,  40,  46,  52 },
  {  3,   9,  15,  21,  41,  47,  53 },
  {  4,  10,  16,  22,  28,  48,  54 },
  {  5,  11,  17,  23,  29,  35,  55 },
  {  6,  12,  18,  24,  30,  36,  42 }
};

static void _PlotPixel(unsigned X, unsigned Y, unsigned C) {
  unsigned RemapBit;
  //
  if (X < 128 && Y < 64) {
    //
    // Unwind 128x64 arrangement into a 1024x8 arrangement of pixels.
    //
    X += 128 * (Y/8);
    Y %= 8;
    //
    // Remap by tiling 8x7 block of translated pixels.
    //
    RemapBit = _aBitMutate[Y][X % 7];
    if (C > 0) {
      _aTestBitmap2[4 + X/7*8 + RemapBit/7] |= 1u << (RemapBit % 7);
    } else {
      _aTestBitmap2[4 + X/7*8 + RemapBit/7] &= ~(1u << (RemapBit % 7));
    }
  }
}

The OLED “write display” SysEx

The SysEx that writes the OLED display is as follows:

F0 – System Exclusive
47 – Akai Manufacturer ID
7F – The All-Call address
43 – “Fire” product
0E – “Write OLED” command
hh – Bits 7-13 of payload length
ll – Bits 0-6 of payload length
00 – Start 8-pixel band of update
07 – End 8-pixel band of update (here, 8 bands of 8 pixels, i.e. the whole display)
00 – Start colum of update
7F – End column of update
xx – Bitmap data formatted as in _PlotPixel()
F7 – End of Exclusive

This is all wrapped up in some code that you can deploy using Embedded Studio and the SEGGER emPower-USB-Host board. But if you want to run it on another controller, or convert it to something else like Python, go for it!

Bonus material

Here’s two tidbits that I found playing with the Fire.

Bet you didn’t know that there’s a color-balance mode in the Fire?  Well, you do now! To access this:

  • Remove the USB cable
  • Hold down the four buttons at the bottom right of the device (pattern, play, stop, rec) and keep them pressed
  • Plug in the USB cable

You get this:

I guess you could really screw up your Fire if you wanted to, so be careful!

And what else can we uncover?  Same deal:

  • Remove the USB cable
  • Hold down the four buttons at the bottom left of the device (step, note, drum, perform) and keep them pressed
  • Plug in the USB cable

You are now in STM32 bootloader mode… I’m not familiar with the operation of the STM32 bootloader because I always debug using a J-Link and trace using a J-Trace. But for the curious, maybe you can figure out firmware replacement if you want to.  Perhaps you can crack open the case and see if it has a 10-pin Cortex connector for debug.

Unfinished business

There is some unfinished engineering here. I know, for instance, there are more MIDI messages that control the OLED operation, and I know what they do from seeing when they are sent. I also know how to make the single OLED message described above more flexible by changing its first set of parameters, but I don’t need to use that right now, so haven’t documented it.

What irritates me the most is that I know that each of the buttons (not the pads) and the bank LEDs can be fully controlled debecause the Fire has a built-in demo mode. That means the buttons are capable of more than just dull and high intensity levels. If you plug the Fire into a USB power outlet rather than a computer, you get to see that all buttons and LEDs have smooth dimming.

I tried a few things to see if this was exposed, but there wasn’t anything I could find that would set arbitrary levels on any of the controls. I tried using pad indexes from 0x40 up, additional SysEx messages with single color controls, and scanning SysEx command from 0x00 through 0xFF. Nothing. Some even crashed the Fire. But hey, you might be able to explore, poke about, and see if you can find some and, if you do, I would be very interested to hear about it!

Final thoughts

I wrapped all of this knowledge into an application that demonstrates my Fire reverse engineering journey so far. I’m now off to make my ideal step sequencer for myself using this knowledge, and I’ve ordered more Akai equipment to control. So life is good, and I hope this helps somebody else put their Fire to new uses!

Example System Exclusive files!

As promised, here is a Zip file that contains an assortment of animations and things that may help you with programming the Fire using MIDI.

Akai Fire Sysex Examples

The code

Here is the code ready to use on any device that has emUSB-Host running.

/*********************************************************************
*                   (c) SEGGER Microcontroller GmbH                  *
*                        The Embedded Experts                        *
*                           www.segger.com                           *
**********************************************************************

-------------------------- END-OF-HEADER -----------------------------

File    : USBH_MIDI_FireController.c
Purpose : This sample is designed to control the Akai Fire MIDI
          controller.

Additional information:
  Preparations:
    None.

  Expected behavior:
    Plug in ONLY an Akai Fire. It displays the SEGGER logo on the
    OLED and animates all the buttons and pads.
*/

/*********************************************************************
*
*       #include section
*
**********************************************************************
*/

#include "RTOS.h"
#include "BSP.h"
#include "USBH_Int.h"
#include "USBH_MIDI.h"
#include "SEGGER.h"
#include <stdlib.h>

/*********************************************************************
*
*       Local data definitions
*
**********************************************************************
*/
enum {
  TASK_PRIO_APP = 150,
  TASK_PRIO_FIRE,
  TASK_PRIO_USBH_MAIN,
  TASK_PRIO_USBH_ISR
};

typedef struct {
  USBH_DEVICE_EVENT Event;
  U8                DevIndex;
} PNP_EVENT;

typedef struct {
  USBH_MIDI_HANDLE hMIDI;
  OS_STACKPTR int  aStack[1500/sizeof(int)];
  U8               DevIndex;
  OS_TASK          Task;
} MIDI_DEVICE;

/*********************************************************************
*
*       Static const data
*
**********************************************************************
*/

static const U8 _aButtons[] = {
  0x23, 0x22, 0x21, 0x20, 0x1F, 0x28, 0x29, 0x2A, 0x2B, 0x2C,
  0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35
};

static const U8 _aBitMutate[8][7] = {
  { 13,  19,  25,  31,  37,  43,  49 },
  {  0,  20,  26,  32,  38,  44,  50 },
  {  1,   7,  27,  33,  39,  45,  51 },
  {  2,   8,  14,  34,  40,  46,  52 },
  {  3,   9,  15,  21,  41,  47,  53 },
  {  4,  10,  16,  22,  28,  48,  54 },
  {  5,  11,  17,  23,  29,  35,  55 },
  {  6,  12,  18,  24,  30,  36,  42 }
};

static const U32 _aColors[] = {
  0xFF0000,
  0xFFFF00,
  0x00FF00,
  0x00FFFF,
  0x0000F0,
  0xFF00FF
};

static const U8 _aSEGGERBitmap[] = {
  0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00,
  0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00,
  0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00,
  0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3e, 0x7f, 0xcf, 0xff, 0xc0, 0x3c, 0x00, 0xf0, 0x13, 0xe0, 0x27, 0x00, 0x31, 0xf1, 0xfc, 0x00,
  0x3c, 0x3f, 0x87, 0xff, 0x80, 0x18, 0x00, 0xe0, 0x03, 0xc0, 0x07, 0x00, 0x31, 0xf1, 0xfc, 0x00,
  0x3c, 0x1f, 0x87, 0xff, 0x0f, 0x18, 0xff, 0xc3, 0xc3, 0x87, 0x87, 0x1f, 0xf1, 0xf1, 0xfc, 0x00,
  0x3e, 0x1f, 0xc3, 0xff, 0x9f, 0x18, 0xff, 0xc7, 0xe3, 0x0f, 0xc7, 0x3f, 0xf1, 0xf1, 0xfc, 0x00,
  0x3f, 0x0f, 0xc1, 0xff, 0xfc, 0x18, 0xff, 0x87, 0x03, 0x1e, 0x07, 0x3f, 0xf1, 0xc1, 0xfc, 0x00,
  0x3f, 0x07, 0xe0, 0xff, 0xc0, 0x18, 0x01, 0x8f, 0x03, 0x1e, 0x07, 0x00, 0x70, 0x03, 0xfc, 0x00,
  0x3f, 0x83, 0xf0, 0xff, 0x80, 0x78, 0x01, 0x8f, 0xff, 0x1f, 0xff, 0x00, 0x70, 0x01, 0xfc, 0x00,
  0x3f, 0xc3, 0xf8, 0x7f, 0x07, 0xf8, 0xff, 0x87, 0xff, 0x0f, 0xff, 0x1f, 0xf1, 0xf1, 0xfc, 0x00,
  0x3f, 0xe1, 0xfc, 0x3f, 0x1f, 0x38, 0xff, 0xc7, 0xe7, 0x8f, 0xcf, 0x3f, 0xf1, 0xf1, 0xfc, 0x00,
  0x3f, 0xe0, 0xfc, 0x1f, 0x0e, 0x18, 0x7f, 0xc3, 0xc7, 0x87, 0x0f, 0x1f, 0xf1, 0xe1, 0xfc, 0x00,
  0x3f, 0xf0, 0x7e, 0x1f, 0x80, 0x38, 0x00, 0xe0, 0x07, 0xc0, 0x0f, 0x00, 0x30, 0x01, 0xfc, 0x00,
  0x3f, 0xf8, 0x7f, 0x0f, 0xc0, 0x7c, 0x01, 0xf8, 0x1f, 0xf0, 0x3f, 0x00, 0x38, 0x07, 0xfc, 0x00,
  0x3d, 0xfc, 0x3f, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3d, 0xfc, 0x1f, 0x83, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0xfe, 0x0f, 0xc1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x7f, 0x0f, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x3f, 0x87, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x3f, 0x83, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00,
  0x3c, 0x1f, 0xc1, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00,
  0x3c, 0x0f, 0xe1, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00,
  0x3c, 0x07, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x07, 0xf0, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x07, 0xf0, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x07, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x0f, 0xe1, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00,
  0x3c, 0x1f, 0xc1, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00,
  0x3c, 0x3f, 0x83, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00,
  0x3c, 0x3f, 0x87, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x7f, 0x0f, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0xfe, 0x0f, 0xc1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3d, 0xfc, 0x1f, 0x83, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3d, 0xfc, 0x3f, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xf8, 0x7f, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xf0, 0x7e, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xe0, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xe1, 0xfc, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xc3, 0xf8, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0x83, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0x07, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0x0f, 0xc1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3e, 0x1f, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x1f, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3c, 0x3f, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3e, 0x7f, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00,
  0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00,
  0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00,
  0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00,
};

/*********************************************************************
*
*       Static data
*
**********************************************************************
*/

static OS_STACKPTR int        _StackMain[1536/sizeof(int)];
static OS_TASK                _TCBMain;
static OS_STACKPTR int        _StackIsr[1276/sizeof(int)];
static OS_TASK                _TCBIsr;
static MIDI_DEVICE            _aDevice[32];
static OS_MAILBOX             _PnPMailbox;
static PNP_EVENT              _aPnPEvents[32];
static USBH_NOTIFICATION_HOOK _Hook;
static U8                     _aMidiBuffer[4];
static unsigned               _MidiIndex;
static U8                     _aUsbBuffer[1500];
static U8                     _aOLEDBitmap[1175];

/*********************************************************************
*
*       Static Code
*
**********************************************************************
*/

/*********************************************************************
*
*       _MIDI_DeviceEvent()
*
*  Function description
*    Callback, called when a device is added or removed.
*    Called in the context of the USBH_Task.
*    The functionality in this routine should not block!
*/
static void _MIDI_DeviceEvent(void * pContext, U8 DevIndex, USBH_DEVICE_EVENT Event) {
  PNP_EVENT PnP;
  //
  (void)pContext;
  //
  PnP.Event    = Event;
  PnP.DevIndex = DevIndex;
  //
  OS_PutMail(&_PnPMailbox, &PnP);
}

/*********************************************************************
*
*       _FIRE_SYSEX_Begin()
*
*  Function description
*    Begin SysEx message construction.
*/
static void _FIRE_SYSEX_Begin(void) {
  _MidiIndex = 0;
  _aMidiBuffer[_MidiIndex++] = 0x04;  // Cable #0, begin SysEx
  _aMidiBuffer[_MidiIndex++] = 0xF0;
}

/*********************************************************************
*
*       _FIRE_SYSEX_Add()
*
*  Function description
*    Add a byte to the SysEx message.
*
*  Parameters
*    hMIDI - Handle to MIDI device instance.
*    Byte  - Byte to add.
*/
static void _FIRE_SYSEX_Add(USBH_MIDI_HANDLE hMIDI, U8 Byte) {
  _aMidiBuffer[_MidiIndex++] = Byte;
  if (_MidiIndex == 4) {
    USBH_MIDI_WrEvent(hMIDI, USBH_LoadU32BE(&_aMidiBuffer[0]));
    _MidiIndex = 1;
  }
}

/*********************************************************************
*
*       _FIRE_SYSEX_End()
*
*  Function description
*    End SysEx message construction.
*
*  Parameters
*    hMIDI - Handle to MIDI device instance.
*/
static void _FIRE_SYSEX_End(USBH_MIDI_HANDLE hMIDI) {
  if (_MidiIndex == 1) {
    _aMidiBuffer[0]            += 0x01;  // Turn 0x?4 to 0x?5
    _aMidiBuffer[_MidiIndex++]  = 0xF7;
    _aMidiBuffer[_MidiIndex++]  = 0x00;
    _aMidiBuffer[_MidiIndex]    = 0x00;
  } else if (_MidiIndex == 2) {
    _aMidiBuffer[0]            += 0x02;  // Turn 0x?4 to 0x?6
    _aMidiBuffer[_MidiIndex++]  = 0xF7;
    _aMidiBuffer[_MidiIndex]    = 0x00;
  } else {
    _aMidiBuffer[0]            += 0x03;  // Turn 0x?4 to 0x?7
    _aMidiBuffer[_MidiIndex]    = 0xF7;
  }
  USBH_MIDI_WrEvent(hMIDI, USBH_LoadU32BE(&_aMidiBuffer[0]));
}

/*********************************************************************
*
*       _FIRE_SetButtonColor()
*
*  Function description
*    Set Fire button color.
*
*  Parameters
*    hMIDI  - Handle to MIDI device instance.
*    Button - Controller that controls button.
*    Color  - Logical color to set for that button.
*/
static void _FIRE_SetButtonColor(USBH_MIDI_HANDLE hMIDI, unsigned Button, unsigned Color) {
  USBH_MIDI_WrEvent(hMIDI, 0x0BB00000uL + (Button<<8) + Color);
}

/*********************************************************************
*
*       _FIRE_SetPadColor()
*
*  Function description
*    Set Fire pad color.
*
*  Parameters
*    hMIDI - Handle to MIDI device instance.
*    R     - Row number (0...3).
*    C     - Column number (0...15).
*    Color - Color in RGB color format (00.RR.GG.BB).
*/
static void _FIRE_SetPadColor(USBH_MIDI_HANDLE hMIDI, unsigned R, unsigned C, U32 Color) {
  _FIRE_SYSEX_Begin();
  _FIRE_SYSEX_Add(hMIDI, 0x47);                  // AKAI
  _FIRE_SYSEX_Add(hMIDI, 0x7F);                  // All-Call
  _FIRE_SYSEX_Add(hMIDI, 0x43);                  // Fire
  _FIRE_SYSEX_Add(hMIDI, 0x65);                  // WRITE PADS
  _FIRE_SYSEX_Add(hMIDI, 0);                     // Payload length: 4 bytes
  _FIRE_SYSEX_Add(hMIDI, 4);
  _FIRE_SYSEX_Add(hMIDI, R*0x10 + C);            // Pad index
  _FIRE_SYSEX_Add(hMIDI, (Color >> 17) & 0x7F);  // Red
  _FIRE_SYSEX_Add(hMIDI, (Color >> 9)  & 0x7F);  // Green
  _FIRE_SYSEX_Add(hMIDI, (Color >> 1)  & 0x7F);  // Blue
  _FIRE_SYSEX_End(hMIDI);
}

/*********************************************************************
*
*       _Interpolate()
*
*  Function description
*    Interpolate color.
*
*  Parameters
*    Color0 - Start color.
*    Color1 - Finish color.
*    Shift  - Byte selection shift (0, 8, 16).
*    Step   - Step number (0...7) within interpolation sequence.
*/
static unsigned _Interpolate(unsigned Color0, unsigned Color1, unsigned Shift, unsigned Step) {
  unsigned C0;
  unsigned C1;
  //
  C0 = (Color0 >> Shift) & 0xFF;
  C1 = (Color1 >> Shift) & 0xFF;
  //
  return ((((C1 - C0) * Step / 8) + C0) & 0xFF) << Shift;
}

/*********************************************************************
*
*       _FIRE_DisplaySpectrum()
*
*  Function description
*    Display shifted spectrum on a single row.
*
*  Parameters
*    hMIDI  - Handle to MIDI device instance.
*    Row    - Row to update (0...3)
*    Step   - Spectrum step number.
*/
static void _FIRE_DisplaySpectrum(USBH_MIDI_HANDLE hMIDI, unsigned Row, unsigned Step) {
  unsigned Color1;
  unsigned Color2;
  unsigned Color;
  unsigned I;
  //
  _FIRE_SYSEX_Begin();
  _FIRE_SYSEX_Add(hMIDI, 0x47);                     // AKAI
  _FIRE_SYSEX_Add(hMIDI, 0x7F);                     // All-Call
  _FIRE_SYSEX_Add(hMIDI, 0x43);                     // Fire
  _FIRE_SYSEX_Add(hMIDI, 0x65);                     // WRITE PADS
  _FIRE_SYSEX_Add(hMIDI, 0);                        // Payload length: 64 bytes
  _FIRE_SYSEX_Add(hMIDI, 64);
  for (I = 0; I < 16; ++I) {
    Color1 = _aColors[(Step+I)   % 48 / 8];
    Color2 = _aColors[(Step+I+8) % 48 / 8];
    Color  = _Interpolate(Color1, Color2, 16, (Step + I) % 8) +
             _Interpolate(Color1, Color2,  8, (Step + I) % 8) +
             _Interpolate(Color1, Color2,  0, (Step + I) % 8);
    _FIRE_SYSEX_Add(hMIDI, Row+I);                  // Pad index
    _FIRE_SYSEX_Add(hMIDI, (Color >> 17) & 0x7F);   // Red
    _FIRE_SYSEX_Add(hMIDI, (Color >> 9)  & 0x7F);   // Green
    _FIRE_SYSEX_Add(hMIDI, (Color >> 1)  & 0x7F);   // Blue
  }
  _FIRE_SYSEX_End(hMIDI);
  USBH_MIDI_Send(hMIDI);
}

/*********************************************************************
*
*       _FIRE_SendBitmap()
*
*  Function description
*    Send OLED bitmap to Fire.
*
*  Parameters
*    hMIDI     - Handle to MIDI device instance.
*    pBitmap   - Pointer to control bytes and bitmap.
*    BitmapLen - Length of bitmap payload.
*/
static void _FIRE_SendBitmap(USBH_MIDI_HANDLE hMIDI, const U8 *pBitmap, unsigned BitmapLen) {
  _FIRE_SYSEX_Begin();
  _FIRE_SYSEX_Add(hMIDI, 0x47);              // AKAI
  _FIRE_SYSEX_Add(hMIDI, 0x7F);              // All-Call
  _FIRE_SYSEX_Add(hMIDI, 0x43);              // Fire
  _FIRE_SYSEX_Add(hMIDI, 0x0E);              // WRITE OLED
  _FIRE_SYSEX_Add(hMIDI, BitmapLen >> 7);    // Payload length high
  _FIRE_SYSEX_Add(hMIDI, BitmapLen & 0x7F);  // Payload length low
  while (BitmapLen > 0) {
    _FIRE_SYSEX_Add(hMIDI, *pBitmap++);
    --BitmapLen;
  }
  _FIRE_SYSEX_End(hMIDI);
}

/*********************************************************************
*
*       _FIRE_PlotPixel()
*
*  Function description
*    Plot pixel on bitmap.
*
*  Parameters
*    X - X coordinate of pixel (0..127).
*    Y - Y coordinate of pixel (0..63).
*    C - Color, 0=black, nonzero=white.
*/
static void _FIRE_PlotPixel(unsigned X, unsigned Y, unsigned C) {
  unsigned RemapBit;
  //
  if (X < 128 && Y < 64) {
    //
    // Unwind 128x64 arrangement into a 1024x8 arrangement of pixels.
    //
    X += 128 * (Y/8);
    Y %= 8;
    //
    // Remap by tiling 7x8 block of translated pixels.
    //
    RemapBit = _aBitMutate[Y][X % 7];
    if (C > 0) {
      _aOLEDBitmap[4 + X/7*8 + RemapBit/7] |= 1u << (RemapBit % 7);
    } else {
      _aOLEDBitmap[4 + X/7*8 + RemapBit/7] &= ~(1u << (RemapBit % 7));
    }
  }
}

/*********************************************************************
*
*       _FIRE_DrawSEGGERLogo()
*
*  Function description
*    Draw SEGGER logo to display.
*
*  Parameters
*    YOrigin - Top Y coordinate for logo.
*/
static void _FIRE_DrawSEGGERLogo(MIDI_DEVICE *pInst, unsigned YOrigin) {
  unsigned y;
  unsigned x;
  //
  for (x = 0; x < 128; ++x) {
    for (y = 0; y < 64; ++y) {
      _FIRE_PlotPixel(x, y, 0);
    }
  }
  //
  for (y = 0; y < 56; ++y) {
    for (x = 0; x < 120; ++x) {
      if (_aSEGGERBitmap[(55-y)*128/8 + x/8] & (0x80 >> (x % 8))) {
        _FIRE_PlotPixel(x+4, YOrigin + y, 1);
      }
    }
  }
  _FIRE_SendBitmap(pInst->hMIDI, &_aOLEDBitmap[0], sizeof(_aOLEDBitmap));
}

/*********************************************************************
*
*       _FireTask()
*
*  Function description
*    Fire demo task.
*
*  Additional information
*    Animates the SEGGER logo onto the display, then a spectrum
*    across the pad matrix.
*/
static void _FireTask(void *pContext) {
  MIDI_DEVICE * pInst;
  unsigned      Step;
  unsigned      i;
  //
  pInst = (MIDI_DEVICE *)pContext;
  //
  USBH_MIDI_SetBuffer(pInst->hMIDI, &_aUsbBuffer[0], sizeof(_aUsbBuffer));
  //
  // All buttons and pads off.
  //
  for (i = 0; i < 64; ++i) {
    _FIRE_SetPadColor(pInst->hMIDI, i / 16, i % 16, 0x000000uL);
  }
  for (i = 0; i < SEGGER_COUNTOF(_aButtons); ++i) {
    _FIRE_SetButtonColor(pInst->hMIDI, _aButtons[i], 0);
  }
  _FIRE_SetButtonColor(pInst->hMIDI, 0x1B, 0x10);  // BANK selection LEDs all off
  USBH_MIDI_Send(pInst->hMIDI);
  //
  // Animate SEGGER logo onto display.
  //
  for (i = 64; i > 4; --i) {
    _FIRE_DrawSEGGERLogo(pInst, i);
    USBH_MIDI_Send(pInst->hMIDI);
    OS_Delay(10);
  }
  //
  // Animate buttons and pads.
  //
  Step = 0;
  for (;;) {
    _FIRE_SetButtonColor(pInst->hMIDI, _aButtons[Step     % SEGGER_COUNTOF(_aButtons)], 0);
    _FIRE_SetButtonColor(pInst->hMIDI, _aButtons[(Step+1) % SEGGER_COUNTOF(_aButtons)], 3);
    _FIRE_DisplaySpectrum(pInst->hMIDI,  0, Step);
    _FIRE_DisplaySpectrum(pInst->hMIDI, 16, Step-1);
    _FIRE_DisplaySpectrum(pInst->hMIDI, 32, Step-2);
    _FIRE_DisplaySpectrum(pInst->hMIDI, 48, Step-3);
    USBH_MIDI_Send(pInst->hMIDI);
    OS_Delay(50);
    ++Step;
  }
}

/*********************************************************************
*
*       Public code
*
**********************************************************************
*/

/*********************************************************************
*
*       MainTask
*/
#ifdef __cplusplus
extern "C" {     /* Make sure we have C-declarations in C++ programs */
#endif
void MainTask(void);
#ifdef __cplusplus
}
#endif
void MainTask(void) {
  PNP_EVENT Event;
  //
  USBH_Init();
  USBH_MIDI_Init();
  USBH_MIDI_AddNotification(&_Hook, _MIDI_DeviceEvent, NULL);
  //
  OS_CREATEMB(&_PnPMailbox, sizeof(PNP_EVENT), SEGGER_COUNTOF(_aPnPEvents), &_aPnPEvents);
  //                                                                                          // Tasks using emUSB-Host API should always have a lower priority than emUSB-Host main and ISR tasks.
  OS_SetPriority(OS_GetTaskID(), TASK_PRIO_APP);                                          // This task has the lowest prio for real-time application.
  OS_CREATETASK(&_TCBMain, "USBH_Task", USBH_Task,    TASK_PRIO_USBH_MAIN, _StackMain);   // Start USBH main task
  OS_CREATETASK(&_TCBIsr , "USBH_ISR",  USBH_ISRTask, TASK_PRIO_USBH_ISR,  _StackIsr);    // Start USBH ISR task
  //
  _aOLEDBitmap[0] = 0x00;
  _aOLEDBitmap[1] = 0x07;
  _aOLEDBitmap[2] = 0x00;
  _aOLEDBitmap[3] = 0x7f;
  //
  for (;;) {
    BSP_ToggleLED(1);
    //
    OS_GetMail(&_PnPMailbox, &Event);
    if (Event.Event == USBH_DEVICE_EVENT_ADD) {
      _aDevice[Event.DevIndex].hMIDI = USBH_MIDI_Open(Event.DevIndex);
      OS_CreateTaskEx(&_aDevice[Event.DevIndex].Task,
                      "Fire",
                      TASK_PRIO_FIRE,
                      _FireTask,
                      &_aDevice[Event.DevIndex].aStack[0],
                      sizeof(_aDevice[Event.DevIndex].aStack)
                      CTPARA_TIMESLICE,
                      &_aDevice[Event.DevIndex]);
      USBH_Logf_Application("**** MIDI device %d added and started", Event.DevIndex);
    } else {
      if (_aDevice[Event.DevIndex].hMIDI != USBH_MIDI_INVALID_HANDLE) {
        //
        // Wait for receiver task to terminate itself.
        //
        while (OS_TASK_IsTask(&_aDevice[Event.DevIndex].Task)) {
          OS_Delay(10);
        }
        //
        (void)USBH_MIDI_Close(_aDevice[Event.DevIndex].hMIDI);
        _aDevice[Event.DevIndex].hMIDI = USBH_MIDI_INVALID_HANDLE;
      }
      USBH_Logf_Application("**** MIDI device %d stopped and removed", Event.DevIndex);
    }
  }
}

/*************************** End of file ****************************/