#!/usr/bin/env python3
"""
mv2jpeg.py - extract the frames of WeatherStar XL product movies (.mv) as JPEG files.

The XL's /twc/product/*.mv files are QuickTime movies whose video track is Photo-JPEG ('jpeg'):
every frame is already a complete JPEG image. This script walks the QuickTime atoms, finds each
frame's bytes through the sample tables (stsd/stsc/stsz/stco/co64) and writes them out unchanged,
so there is no re-encoding and no quality loss. Pure Python 3, no extra packages.

Usage:
  python mv2jpeg.py FILE.mv [FILE.mv ...]           -> FILE_frames/FILE.0000.jpg, ...
  python mv2jpeg.py C:\\xl\\twc\\product              -> every .mv in the folder
  python mv2jpeg.py -o OUTDIR -r C:\\xl\\twc          -> recurse, all output under OUTDIR
Options:
  -o DIR   output folder (default: a <name>_frames folder next to each movie)
  -r       recurse into sub-folders when given a folder
  -q       quiet (only errors and the summary)
"""
import argparse
import os
import struct
import sys

CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"dinf", b"udta"}


def atoms(buf, start, end):
    """Yield (type, payload_start, payload_end) for the atoms in buf[start:end]."""
    p = start
    while p + 8 <= end:
        size, kind = struct.unpack(">I4s", buf[p:p + 8])
        hdr = 8
        if size == 1:                                   # 64-bit size
            if p + 16 > end:
                break
            size = struct.unpack(">Q", buf[p + 8:p + 16])[0]
            hdr = 16
        elif size == 0:                                 # runs to the end
            size = end - p
        if size < hdr or p + size > end:
            break
        yield kind, p + hdr, p + size
        p += size


def find_tracks(buf):
    """Return a list of dicts with the sample tables of each track in the movie."""
    tracks = []

    def walk(start, end, cur):
        for kind, a, b in atoms(buf, start, end):
            if kind == b"trak":
                t = {}
                walk(a, b, t)
                tracks.append(t)
            elif kind in CONTAINERS:
                walk(a, b, cur)
            elif kind == b"hdlr":
                cur["handler"] = buf[a + 8:a + 12]          # 'vide', 'soun', ...
            elif kind == b"mdhd":
                ver = buf[a]
                if ver == 1:
                    cur["timescale"], cur["duration"] = struct.unpack(">IQ", buf[a + 20:a + 32])
                else:
                    cur["timescale"], cur["duration"] = struct.unpack(">II", buf[a + 12:a + 20])
            elif kind == b"stsd":
                n = struct.unpack(">I", buf[a + 4:a + 8])[0]
                if n:
                    cur["codec"] = buf[a + 12:a + 16]
                    e = a + 8                               # visual sample entry: width/height at +32
                    if e + 36 <= b:
                        cur["width"], cur["height"] = struct.unpack(">HH", buf[e + 32:e + 36])
            elif kind == b"stsz":
                fixed, n = struct.unpack(">II", buf[a + 4:a + 12])
                cur["sizes"] = [fixed] * n if fixed else list(struct.unpack(">%dI" % n, buf[a + 12:a + 12 + 4 * n]))
            elif kind == b"stsc":
                n = struct.unpack(">I", buf[a + 4:a + 8])[0]
                cur["stsc"] = [struct.unpack(">III", buf[a + 8 + 12 * i:a + 20 + 12 * i]) for i in range(n)]
            elif kind == b"stco":
                n = struct.unpack(">I", buf[a + 4:a + 8])[0]
                cur["chunks"] = list(struct.unpack(">%dI" % n, buf[a + 8:a + 8 + 4 * n]))
            elif kind == b"co64":
                n = struct.unpack(">I", buf[a + 4:a + 8])[0]
                cur["chunks"] = list(struct.unpack(">%dQ" % n, buf[a + 8:a + 8 + 8 * n]))
            elif kind == b"stts":
                n = struct.unpack(">I", buf[a + 4:a + 8])[0]
                cur["stts"] = [struct.unpack(">II", buf[a + 8 + 8 * i:a + 16 + 8 * i]) for i in range(n)]

    walk(0, len(buf), {})
    return tracks


def sample_offsets(t):
    """File offset and size of every sample, from the chunk offsets + sample-to-chunk table."""
    sizes, chunks, stsc = t.get("sizes", []), t.get("chunks", []), t.get("stsc", [])
    out, s = [], 0
    for ci, base in enumerate(chunks, start=1):
        per = 0
        for first, spc, _desc in stsc:              # last entry whose first_chunk <= ci
            if first <= ci:
                per = spc
            else:
                break
        off = base
        for _ in range(per):
            if s >= len(sizes):
                return out
            out.append((off, sizes[s]))
            off += sizes[s]
            s += 1
    return out


def extract(path, outdir, quiet):
    with open(path, "rb") as f:
        buf = f.read()
    tracks = [t for t in find_tracks(buf) if t.get("handler") == b"vide"] or find_tracks(buf)
    if not tracks:
        print("%s: no QuickTime tracks found" % path, file=sys.stderr)
        return 0
    t = tracks[0]
    codec = t.get("codec", b"????")
    if codec not in (b"jpeg", b"mjpa", b"mjpb"):
        print("%s: video codec %r is not Photo-JPEG; frames can't be copied out as .jpg"
              % (path, codec.decode("latin1")), file=sys.stderr)
        return 0
    samples = sample_offsets(t)
    if not samples:
        print("%s: the movie holds no frames (an empty %d-byte placeholder)" % (path, len(buf)), file=sys.stderr)
        return 0
    name = os.path.splitext(os.path.basename(path))[0]
    os.makedirs(outdir, exist_ok=True)
    n = 0
    for i, (off, size) in enumerate(samples):
        data = buf[off:off + size]
        if codec == b"jpeg" and not data.startswith(b"\xff\xd8"):
            print("%s: frame %d does not start with a JPEG marker, skipped" % (path, i), file=sys.stderr)
            continue
        with open(os.path.join(outdir, "%s.%04d.jpg" % (name, i)), "wb") as o:
            o.write(data)
        n += 1
    if not quiet:
        fps = ""
        if t.get("timescale") and t.get("stts"):
            dur = t["stts"][0][1]
            if dur:
                fps = ", %.3f fps" % (t["timescale"] / dur)
        wh = " %dx%d" % (t["width"], t["height"]) if "width" in t else ""
        print("%s:%s %d frame(s)%s -> %s" % (path, wh, n, fps, outdir))
    return n


def main():
    ap = argparse.ArgumentParser(description="Extract the frames of XL product .mv movies as JPEG files.")
    ap.add_argument("inputs", nargs="+", help=".mv files or folders")
    ap.add_argument("-o", "--outdir", help="output folder (default: <name>_frames next to each movie)")
    ap.add_argument("-r", "--recursive", action="store_true", help="recurse into sub-folders")
    ap.add_argument("-q", "--quiet", action="store_true")
    a = ap.parse_args()

    movies = []
    for p in a.inputs:
        if os.path.isdir(p):
            for root, dirs, files in os.walk(p):
                movies += [os.path.join(root, f) for f in sorted(files) if f.lower().endswith(".mv")]
                if not a.recursive:
                    break
        else:
            movies.append(p)

    total = files = 0
    for m in movies:
        name = os.path.splitext(os.path.basename(m))[0]
        if a.outdir:
            rel = os.path.relpath(os.path.dirname(os.path.abspath(m)), os.path.abspath(a.inputs[0])) \
                if os.path.isdir(a.inputs[0]) else "."
            out = os.path.normpath(os.path.join(a.outdir, rel, name))
        else:
            out = os.path.join(os.path.dirname(m) or ".", name + "_frames")
        try:
            got = extract(m, out, a.quiet)
        except (OSError, struct.error) as e:
            print("%s: %s" % (m, e), file=sys.stderr)
            got = 0
        total += got
        files += 1 if got else 0
    print("%d movie(s), %d frame(s) written" % (files, total))
    return 0 if total else 1


if __name__ == "__main__":
    sys.exit(main())
