mido developer on retainer: Type 1 MIDI tracks[1] iterated without reading tempo map from tracks[0] — hardcoded 120 BPM converts delta ticks to wrong timestamps; Chopin at 90 BPM plays 33% too fast; 50 lab stations out of sync by 60 s — tick2second fix — 3 weeks — mido developer on monthly retainer

mido 1.3.2 • Python 3.9; mid = mido.MidiFile('piece.mid'); iterating mid.tracks[1] for note events; elapsed_ticks += msg.time; elapsed_seconds = elapsed_ticks / mid.ticks_per_beat * (60.0 / 120.0) • Westfield Mido Ltd. (music learning lab, 50 student stations; software plays MIDI files synchronously across all stations via UDP broadcast; students follow a conductor track on-screen timed to the music; Type 1 MIDI files from a classical repertoire (Chopin, Bach, Mozart); developer iterates mid.tracks[1] (piano notes) only; hardcodes tempo 500,000 μs/beat = 120 BPM; Chopin Nocturne Op. 9 No. 2 is at 90 BPM: 666,667 μs/beat stored in a set_tempo meta message in mid.tracks[0]; each tick computed at 500,000/480 = 1,041.7 μs instead of 666,667/480 = 1,388.9 μs; playback 33% too fast; 4-minute piece ends at 3:00; system controller wall-clock drifts from students by 60 s over the piece; 32/50 stations failed sync test during pilot week; fix: read set_tempo events from mid.tracks[0]; mido.tick2second(tick, ticks_per_beat, tempo) with per-section tempo; station sync drift 60s→0.3s; 1.5h retainer engagement

Westfield Mido Ltd. built the software for a 50-station music learning lab at a conservatory. Each student station ran a Python application that received a MIDI file over the local network, parsed the note events, and displayed a scrolling staff notation view synchronized to live playback through the station’s audio interface. A central controller broadcast timing pulses via UDP so all 50 stations would start and advance together. The developer used mido to parse the MIDI files: mido.MidiFile to read the file, then a loop over mid.tracks[1] to extract note-on and note-off messages, summing the delta msg.time values to get absolute tick positions, and converting ticks to seconds with the formula seconds = ticks / ticks_per_beat * (60.0 / 120.0) — using 120 BPM as a fixed default. During initial testing with MIDI files prepared specifically for the lab at 120 BPM, synchronization worked correctly across all 50 stations. When the system was handed to the faculty for a pilot week using the conservatory’s existing MIDI repertoire — including Chopin nocturnes at 90 BPM, Bach inventions at 100 BPM, and Mozart sonatas at 140 BPM — 32 of 50 stations failed the synchronization check. The on-screen notation advanced too quickly or too slowly relative to the audio, and by the end of a 4-minute piece the display was up to 60 seconds out of step. A mido retainer developer was engaged to diagnose the synchronization failures.

The developer identified the root cause in under 30 minutes. MIDI stores timing as delta ticks — the number of clock pulses since the previous event — where the resolution (ticks per beat, or PPQ) is stored in the file header as mid.ticks_per_beat. Converting ticks to seconds requires knowing both PPQ and the current tempo in microseconds per beat. The default MIDI tempo is 500,000 μs/beat (120 BPM), but the actual tempo is encoded as set_tempo meta messages inside the MIDI tracks. In a Type 1 MIDI file, the convention — followed by every MIDI editor and DAW — is to place all conductor events (tempo changes, time signature changes, key signature changes) in mid.tracks[0] and instrument note events in mid.tracks[1] onwards. The developer’s code iterated only mid.tracks[1] and never read mid.tracks[0], so the set_tempo event at 666,667 μs/beat (90 BPM) for the Chopin nocturne was invisible to the timing computation. The hardcoded 120 BPM made every tick 500,000/666,667 = 0.75× as long as it actually was; every computed timestamp was 0.75× the correct value; the entire piece played back at 1/0.75 = 1.33× speed. For a 4-minute piece, the display finished at 3:00 — 60 seconds early. The fix had two parts: (1) parse set_tempo meta messages from mid.tracks[0] to build a tempo map; (2) replace the hardcoded formula with mido.tick2second(tick, mid.ticks_per_beat, current_tempo) where current_tempo is updated from the tempo map at each tempo event boundary. After the fix, the Chopin nocturne synchronized correctly across all 50 stations with a maximum inter-station drift of 0.3 seconds over 4 minutes, well within the 0.5-second perceptual threshold for audible desynchronization.

The annotated tempo-map parser and tick-to-second conversion, with the buggy and fixed implementations:

# Westfield Mido Ltd. — mido 1.3.2 Type 1 MIDI tempo map omission
# mido 1.3.2; Python 3.9
# Pipeline: Type 1 MIDI file → note event schedule in seconds → 50-station UDP sync
# Problem: iterating mid.tracks[1] only; hardcoded 120 BPM for tick→second conversion
#          Type 1 MIDI stores set_tempo events in tracks[0]; never read
#          90 BPM Chopin plays 33% too fast; 60s sync drift over 4 minutes
# Fix: read set_tempo from tracks[0]; mido.tick2second() per-section tempo

import mido
import dataclasses
from typing import List, Tuple


DEFAULT_TEMPO = 500_000  # μs/beat = 120 BPM (MIDI default)


@dataclasses.dataclass
class NoteEvent:
    """Scheduled note event: pitch, velocity, start and end in seconds."""
    pitch: int
    velocity: int
    start_sec: float
    end_sec: float


# ── BUGGY parser ────────────────────────────────────────────────────────────

def parse_midi_buggy(filepath: str) -> List[NoteEvent]:
    """
    BUG: iterates mid.tracks[1] only; converts ticks with hardcoded 120 BPM.
    For Type 1 MIDI: set_tempo events live in tracks[0] (conductor track).
    For 90 BPM MIDI: 120/90 = 1.33× speed; 4-min piece ends at 3:00.
    """
    mid = mido.MidiFile(filepath)
    tpb = mid.ticks_per_beat   # e.g. 480 PPQ
    tempo = DEFAULT_TEMPO       # BUG: hardcoded 120 BPM, ignores tracks[0]

    events: List[NoteEvent] = []
    pending: dict = {}          # pitch → start_tick
    abs_ticks = 0

    for msg in mid.tracks[1]:   # BUG: only instrument track; never reads tracks[0]
        abs_ticks += msg.time
        if msg.type == 'note_on' and msg.velocity > 0:
            # BUG: mido.tick2second uses hardcoded DEFAULT_TEMPO (120 BPM)
            start_sec = mido.tick2second(abs_ticks, tpb, DEFAULT_TEMPO)
            pending[msg.note] = (abs_ticks, start_sec)
        elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
            if msg.note in pending:
                _, start_sec = pending.pop(msg.note)
                end_sec = mido.tick2second(abs_ticks, tpb, DEFAULT_TEMPO)
                events.append(NoteEvent(msg.note, 80, start_sec, end_sec))

    return events


# ── Tempo map builder (reads from tracks[0]) ────────────────────────────────

def build_tempo_map(mid: mido.MidiFile) -> List[Tuple[int, int]]:
    """
    Read set_tempo meta messages from the conductor track (tracks[0] for Type 1).
    Returns: list of (abs_tick, tempo_us_per_beat) sorted by abs_tick.
    For Type 0 MIDI, tempo events appear inline in the single track.
    """
    tempo_map: List[Tuple[int, int]] = [(0, DEFAULT_TEMPO)]
    abs_ticks = 0
    track = mid.tracks[0] if mid.type == 1 else mid.tracks[0]
    for msg in track:
        abs_ticks += msg.time
        if msg.type == 'set_tempo':
            tempo_map.append((abs_ticks, msg.tempo))
    return tempo_map


def ticks_to_seconds(abs_ticks: int, tpb: int,
                     tempo_map: List[Tuple[int, int]]) -> float:
    """
    Convert absolute tick position to seconds using the full tempo map.
    Accumulates time section by section, using the correct tempo per region.
    """
    total_seconds = 0.0
    prev_tick = 0

    for i, (change_tick, tempo) in enumerate(tempo_map):
        if abs_ticks <= change_tick:
            break
        # Next change tick (or infinity if this is the last section)
        next_change = tempo_map[i + 1][0] if i + 1 < len(tempo_map) else abs_ticks

        ticks_in_section = min(abs_ticks, next_change) - max(prev_tick, change_tick)
        if ticks_in_section > 0:
            total_seconds += mido.tick2second(ticks_in_section, tpb, tempo)

        prev_tick = change_tick
        if abs_ticks <= next_change:
            break
    else:
        # Handle the last section up to abs_ticks
        last_tick, last_tempo = tempo_map[-1]
        remaining = abs_ticks - last_tick
        if remaining > 0:
            total_seconds += mido.tick2second(remaining, tpb, last_tempo)

    return total_seconds


# ── FIXED parser ─────────────────────────────────────────────────────────────

def parse_midi_fixed(filepath: str) -> List[NoteEvent]:
    """
    FIX: reads set_tempo events from tracks[0]; builds tempo map.
    ticks_to_seconds() uses correct per-section tempo via tempo map.
    Works correctly for 90 BPM Chopin, 100 BPM Bach, 140 BPM Mozart.
    Station sync drift: 60s → 0.3s over 4 minutes.
    """
    mid = mido.MidiFile(filepath)
    tpb = mid.ticks_per_beat
    tempo_map = build_tempo_map(mid)   # FIX: read actual tempo from tracks[0]

    events: List[NoteEvent] = []
    pending: dict = {}
    abs_ticks = 0

    # For Type 1 MIDI, merge tracks[1:] for note events only
    note_track = mid.tracks[1] if len(mid.tracks) > 1 else mid.tracks[0]

    for msg in note_track:
        abs_ticks += msg.time
        if msg.type == 'note_on' and msg.velocity > 0:
            start_sec = ticks_to_seconds(abs_ticks, tpb, tempo_map)  # FIX
            pending[msg.note] = (abs_ticks, start_sec)
        elif msg.type == 'note_off' or (msg.type == 'note_on' and msg.velocity == 0):
            if msg.note in pending:
                _, start_sec = pending.pop(msg.note)
                end_sec = ticks_to_seconds(abs_ticks, tpb, tempo_map)  # FIX
                events.append(NoteEvent(msg.note, 80, start_sec, end_sec))

    return events


# ── Timing validation ────────────────────────────────────────────────────────

def validate_tempo_conversion():
    """
    Manual timing check for a known scenario:
    ticks_per_beat=480; set_tempo=666667 (90 BPM); note at tick 480×4=1920 (4 beats).
    Expected: 4 beats × (60/90) s/beat = 2.667 seconds.
    Buggy (120 BPM hardcode): 4 beats × (60/120) = 2.000 seconds (wrong).
    """
    tpb = 480
    actual_tempo = 666_667   # 90 BPM
    note_tick = tpb * 4      # 4 beats after start

    # Buggy: hardcoded 120 BPM
    buggy_sec = mido.tick2second(note_tick, tpb, DEFAULT_TEMPO)

    # Fixed: correct 90 BPM tempo map
    tempo_map = [(0, actual_tempo)]
    fixed_sec = ticks_to_seconds(note_tick, tpb, tempo_map)

    expected_sec = 4.0 * (60.0 / 90.0)  # = 2.667 s

    print("Timing validation: note at beat 4, actual tempo 90 BPM")
    print(f"  Expected:   {expected_sec:.3f} s")
    print(f"  Buggy (120 BPM hardcode): {buggy_sec:.3f} s "
          f"(error: {buggy_sec - expected_sec:+.3f} s)")
    print(f"  Fixed (tempo map):        {fixed_sec:.3f} s "
          f"(error: {fixed_sec - expected_sec:+.3f} s)")
    print()
    print("Root cause: Type 1 MIDI set_tempo in tracks[0]; tracks[1] has notes only")
    print("  Hardcoded 120 BPM ignores actual 90 BPM; each tick 0.75× too short")
    print("  4-minute Chopin piece plays back in 3:00; 50 stations out of sync 60s")
    print()
    print("Fix: build_tempo_map() reads set_tempo from tracks[0]")
    print("  ticks_to_seconds() uses correct per-section tempo")
    print("  Station sync drift: 60s → 0.3s over 4 minutes; 1.5h")


validate_tempo_conversion()

How MIDI Type 0, Type 1, and Type 2 file formats differ in where they store tempo events, and the correct mido pattern for tempo-aware tick–to–second conversion

MIDI defines three file types that differ in how tracks are organized. Type 0 stores all events (notes, tempo changes, time signatures) in a single track (mid.tracks[0]); there is no separate conductor track. Type 1 stores events in multiple parallel tracks intended to play simultaneously: by convention, tracks[0] is the conductor track containing tempo and time-signature events, and tracks[1] onwards contain instrument events. Type 2 stores multiple independent patterns intended to play sequentially, each with its own tempo map. For mido, reading the MIDI header tells you which type you’re dealing with via mid.type. The critical difference for tick-to-second conversion: in a Type 0 file, you must read tempo events inline as you iterate tracks[0]; in a Type 1 file, you must read tracks[0] for tempo events before parsing note events from tracks[1] and beyond. The mido.tick2second(tick, ticks_per_beat, tempo) function converts a single-section tick count at a known tempo — it does not accept a tempo map. The responsibility for handling tempo changes falls on the calling code: build the tempo map from set_tempo events, then accumulate sections. The alternative for simple use cases is mido.MidiFile.play(), which yields messages at correctly timed intervals using real time.sleep() calls, handling tempo events automatically without exposing the tick arithmetic. For synchronization across multiple networked systems — as in the Westfield lab — play() is not suitable because each station needs to compute an absolute event schedule in advance rather than following a sleep-based playback clock. The tempo-map parser plus ticks_to_seconds() is the correct approach for schedule-first systems. The retainer engagement was 1.5h: 0.25h triage (32/50 stations fail sync on 90 BPM Chopin; pass on 120 BPM test file; hardcoded tempo identified); 0.5h root cause (Type 1 MIDI format confirmed; set_tempo event in tracks[0] at 666,667 μs/beat confirmed; tick-to-second formula confirmed wrong by manual calculation); 0.5h fix (build_tempo_map() added; ticks_to_seconds() replaces hardcoded formula; 90 BPM and 140 BPM test cases both pass); 0.25h validation (50-station sync drift 0.3s over 4 minutes; regression test for all three tempo cases merged to CI). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →