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
Legacy karaoke song files downloaded from older repositories often contain missing or corrupted 4-byte magic headers (0x4D546864 in ASCII MThd). The parser checks the first 32-bit Uint32. If MThd magic is missing, it dynamically prepends or corrects the 4-byte MThd magic identifier in the DataView buffer before passing it to the decoder.
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
- 1Channel 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.
- 2Tempo Meta Events (0x51): Stores Microseconds Per Quarter Note (MPQN). Calculated into BPM using:
BPM = 60,000,000 / MPQN. - 3Time Signature Meta Events (0x58): Defines measure numerator and denominator (e.g. 4/4, 3/4).
- 4Marker 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
- 1Scan Meta Event 0x01 for prefix header
KLyrHdr1. - 2Extract Base64 encoded payload and decode into binary
Uint8Arraybuffer. - 3
Decompress compressed payload using zlib/pako inflation algorithm.
- 4
Decode decompressed bytes using Windows-874 / TIS-620 charset into UTF-8 XML document.
- 5Parse XML
<INFO>tags (Title, Key, Artist, Tempo) and<LYRIC><LINE><WORD>syllable timings.