User guide5 min read

MIDI File Format Specification (.mid) & Metadata Extraction

Deep-dive technical specification into Standard MIDI Files (SMF Type 0/1), MThd magic repair, Variable-Length Delta Times, Event Streams, and KLyr XML decompression.

1. Standard MIDI File Structure (SMF)

A Standard MIDI File (.mid) consists of binary chunks starting with a 14-byte MThd header chunk followed by one or more MTrk track chunks. Each chunk begins with a 4-byte ASCII identifier and a 32-bit big-endian length header.

Automated Magic Header Repair Algorithm

2. Variable-Length Quantity (VLQ) & Event Parsing

Inside MTrk chunks, timestamps are encoded as Delta Times using Variable-Length Quantity (VLQ). Each byte's Most Significant Bit (MSB 0x80) indicates whether another byte follows. The remaining 7 bits are accumulated to build the integer value. The accumulated sum of delta times forms the absolute tick timeline for note synthesis.

MIDI Event Categories Parsed by System

  1. 1
    Channel Events (0x80 - 0xEF): Handles Note On (0x90), Note Off (0x80), Program Change (0xC0 - Instrument Swap), Pitch Bend, and Channel 10 (Index 9) Percussion Drum Kit notes.
  2. 2
    Tempo Meta Events (0x51): Stores Microseconds Per Quarter Note (MPQN). Calculated into BPM using: BPM = 60,000,000 / MPQN.
  3. 3
    Time Signature Meta Events (0x58): Defines measure numerator and denominator (e.g. 4/4, 3/4).
  4. 4
    Marker Text Events (0x06): Text events storing musical chord notation (e.g., C, Am, F#m, G7).

3. Embedded KLyr XML Metadata Extraction

Modern KAR/MIDI files often embed complete song info and syllable-level timing inside a Meta Text Event (Meta Type 0x01) starting with KLyrHdr header string. The extraction workflow functions as follows:

KLyr Decompression & Decoding Pipeline

  1. 1
    Scan Meta Event 0x01 for prefix header KLyrHdr1.
  2. 2
    Extract Base64 encoded payload and decode into binary Uint8Array buffer.
  3. 3

    Decompress compressed payload using zlib/pako inflation algorithm.

  4. 4

    Decode decompressed bytes using Windows-874 / TIS-620 charset into UTF-8 XML document.

  5. 5
    Parse XML <INFO> tags (Title, Key, Artist, Tempo) and <LYRIC><LINE><WORD> syllable timings.