#!/usr/bin/env python3
"""Read the encoder delay and end padding that an MP3 stores in its Info/Xing + LAME tag.
Players that read this tag (gapless playback) cut exactly these samples; players that
ignore it play them as silence. Standard library only.
Usage: python3 lametag.py file.mp3 [file2.mp3 ...]
Exit code: 0 all files have a delay/padding field, 1 at least one has none, 2 a file could not be read."""
import sys

def skip_id3v2(b):
    if len(b) >= 10 and b[:3] == b"ID3":
        size = (b[6] & 0x7F) << 21 | (b[7] & 0x7F) << 14 | (b[8] & 0x7F) << 7 | (b[9] & 0x7F)
        return 10 + size + (10 if b[5] & 0x10 else 0)
    return 0

def first_frame(b, pos):
    # Find the first MPEG audio frame header (11 sync bits, layer III).
    while pos + 4 <= len(b):
        if b[pos] == 0xFF and (b[pos + 1] & 0xE0) == 0xE0 and (b[pos + 1] & 0x06) == 0x02:
            return pos
        pos += 1
    return -1

def read(path):
    with open(path, "rb") as f:
        b = f.read()
    if not b:
        return "empty file"
    if b[:4] == b"RIFF":
        return "a WAV (RIFF) file, not an MP3: WAV has no encoder delay"
    pos = first_frame(b, skip_id3v2(b))
    if pos < 0:
        return "no MP3 frame found (not an MP3 file?)"
    mpeg1 = (b[pos + 1] >> 3) & 0x03 == 0x03
    mono = (b[pos + 3] >> 6) == 0x03
    side = (32 if not mono else 17) if mpeg1 else (17 if not mono else 9)
    x = pos + 4 + side
    tag = b[x:x + 4]
    if tag not in (b"Xing", b"Info"):
        return "no Info/Xing tag: a player cannot know the delay, so it plays it"
    flags = int.from_bytes(b[x + 4:x + 8], "big")
    o = x + 8 + (4 if flags & 1 else 0) + (4 if flags & 2 else 0) + (100 if flags & 4 else 0) + (4 if flags & 8 else 0)
    frames = int.from_bytes(b[x + 8:x + 12], "big") if flags & 1 else None
    enc = b[o:o + 9]
    if len(b) < o + 24 or not enc.strip(b"\0"):
        return f"{tag.decode()} tag without a LAME extension: no delay/padding field"
    d = b[o + 21:o + 24]
    delay, padding = (d[0] << 4) | (d[1] >> 4), ((d[1] & 0x0F) << 8) | d[2]
    out = f"tag={tag.decode()} encoder={enc.decode('latin-1').strip()} delay={delay} padding={padding}"
    if frames is not None:
        spf = 1152 if mpeg1 else 576
        out += f" frames={frames} audio_samples={frames * spf - delay - padding}"
    return out

if len(sys.argv) < 2:
    sys.exit("usage: python3 lametag.py file.mp3 [file2.mp3 ...]")
code = 0
for p in sys.argv[1:]:
    try:
        r = read(p)
    except OSError as e:
        print(f"{p}: cannot read ({e.strerror})"); code = 2; continue
    print(f"{p}: {r}")
    if "delay=" not in r and code == 0:
        code = 1
sys.exit(code)
