"""Load a staged macOS libmpv the way the app will, and play a test source headless. env -i /bin/python -I libmpv_smoke.py <.../Contents/Frameworks/libmpv.2.dylib> Run by scripts/macos/build-libmpv.sh with an empty environment. The loader is the one planned in docs/macos/_work/libmpv-macos.md 5.3: python-mpv calls ctypes.util.find_library("mpv") at import, so that one lookup is pointed at the bundled file for the length of the import and then restored. Checks: the bundled file is the one loaded; versions; no Lua (no `osc` property); a lavfi test source (video and audio) plays with vo=null/ao=null; the app's fallback watermark graph (movie= + overlay, as in mpv_widget.py) applies while playing; a small AV1 clip decodes in software through libdav1d. Exit 0 on success. """ import base64 import ctypes.util import hashlib import os import signal import sys import time from pathlib import Path # A looping two-frame 1x1 GIF with a 0.1 s frame delay, shaped like the app's own animated # adverts (src/resources/wm_iptv_*.gif: two frames, NETSCAPE loop). _GIF_FRAME = (b"\x21\xf9\x04\x00\x0a\x00\x00\x00" # graphic control: 10 cs b"\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00" # image descriptor 1x1 b"\x02\x02\x44\x01\x00") # LZW data GIF_ANIM = (b"GIF89a\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00" b"\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00" # loop forever + _GIF_FRAME + _GIF_FRAME + b"\x3b") TEST_SOURCE = ("av://lavfi:testsrc2=size=320x240:rate=25[out0];" "sine=frequency=440:sample_rate=48000[out1]") # A 64x64 AV1 clip (Main profile, 8-bit 4:2:0, 20 frames at 10 fps, one solid colour) in IVF, # 690 bytes, made with libaom-av1 by FFmpeg on Linux (the Mac build has no AV1 encoder). AV1_IVF = base64.b64decode("".join(""" REtJRgAAIABBVjAxQABAAAoAAAABAAAAFAAAAAAAAAAiAAAAAAAAAAAAAAASAAoKAAAAAq//m18g CDISEADagAACgAAACgWF1OqVZqNOFQAAAAEAAAAAAAAAEgAyETADwIAAAAbbAAACgAAgAJkQFQAA AAIAAAAAAAAAEgAyETAEAQQAAAbcAAACgAAgAJTAFQAAAAMAAAAAAAAAEgAyETAGAgiAAAbdAAAC gAAgAJCAFAAAAAQAAAAAAAAAEgAyEDAIBA0QAAbeAAACgAAgAI0UAAAABQAAAAAAAAASADIQMAoI EaBABt+AAAKAACAAihQAAAAGAAAAAAAAABIAMhAwDBAWMIgG4IAAAsAAIACGFAAAAAcAAAAAAAAA EgAyEDAOIBrA0QbiAAACwAAgAIQUAAAACAAAAAAAAAASADIQMBAAn1EaBuOAAALAACAAhBQAAAAJ AAAAAAAAABIAMhAwEgEH4WMG5QAAAsAAIAB8FAAAAAoAAAAAAAAAEgAyEDAUAgjxrAbnAAACwAAg AHgUAAAACwAAAAAAAAASADIQMBYEDRH1BuiAAALAACAAeBQAAAAMAAAAAAAAABIAMhAwGAgRoH4G 6oAAAsAAIAB4FAAAAA0AAAAAAAAAEgAyEDAaEBYwjwbtAAACwAAgAHAUAAAADgAAAAAAAAASADIQ MBwgGsDRBu8AAALAACAAcBQAAAAPAAAAAAAAABIAMhAwHgCfURoG8YAAAsAAIABwFQAAABAAAAAA AAAAEgAyETAhwQfhYwb/gAACwAAgAJzwFAAAABEAAAAAAAAAEgAyEDAiAgfkLAb3AAACwAAgAHAU AAAAEgAAAAAAAAASADIQMCQEDPQ1BvqAAALAACAAcBQAAAATAAAAAAAAABIAMhAwJggRlD4G/4AA AsAAIABw """.split())) AV1_IVF_SHA256 = "5cb0e50c266762a974f38b6ceb4fe07ba582ac4ebec1733abc79ee797220cbc7" def prop_of(player, name): """Read an mpv property (python-mpv's player[name] reads options/ instead).""" return getattr(player, name.replace("-", "_")) def check_av1(mpv, work, fails): """Software AV1: mpv lists libdav1d and decodes the AV1 clip with it (hwdec off).""" print() print("AV1 (dav1d):") if hashlib.sha256(AV1_IVF).hexdigest() != AV1_IVF_SHA256: fails.append("the embedded AV1 clip is damaged") return clip = work / "av1-64x64.ivf" clip.write_bytes(AV1_IVF) logs = [] player = mpv.MPV(vo="null", ao="null", hwdec="no", loop_file="inf", loglevel="info", log_handler=lambda lvl, comp, msg: logs.append(f"[{lvl}] {comp}: {msg.rstrip()}")) try: drivers = [d.get("driver") for d in (prop_of(player, "decoder-list") or []) if d.get("codec") == "av1"] print(f" AV1 decoders in mpv, in order: {drivers}") if not drivers or drivers[0] != "libdav1d": fails.append(f"libdav1d is not mpv's first AV1 decoder ({drivers})") player.play(str(clip)) player.wait_until_playing(timeout=30) # IVF carries no frame rate for the container, so estimated-frame-number stays 0; count # distinct positions instead (the 2-second clip loops, so positions also wrap to 0). seen = set() for _ in range(8): time.sleep(0.2) pos = prop_of(player, "time-pos") if pos is not None: seen.add(round(pos, 1)) track = prop_of(player, "current-tracks/video") or {} # mpv 0.38 and later give the decoder's name in "decoder"; older ones only "decoder-desc", # FFmpeg's long name ("dav1d AV1 decoder by VideoLAN"). decoder, desc = track.get("decoder"), track.get("decoder-desc") or "" print(f" decoder = {decoder} ({desc})") params = prop_of(player, "video-params") or {} print(f" video-params: {params.get('w')}x{params.get('h')} {params.get('pixelformat')}") print(f" hwdec-current = {prop_of(player, 'hwdec-current')}") print(f" distinct time-pos values in 1.6 s: {len(seen)}") if decoder != "libdav1d" and not (decoder is None and "dav1d" in desc): fails.append(f"the AV1 clip was decoded by {decoder or desc}, not libdav1d") if (params.get("w"), params.get("h")) != (64, 64): fails.append(f"AV1 video-params {params}") if len(seen) < 3: fails.append(f"AV1 playback did not advance (time-pos values {sorted(seen)})") finally: player.terminate() errors = [line for line in logs if line.startswith(("[error]", "[fatal]"))] print(f" {len(logs)} log lines; errors and fatal lines: {len(errors)}") for line in errors: print(" " + line) if errors: fails.append(f"{len(errors)} error lines in the AV1 mpv log") def main(): dylib = Path(sys.argv[1]) work = Path(sys.argv[2]) work.mkdir(parents=True, exist_ok=False) signal.alarm(120) # never hang a headless run fails = [] print("environment variables:", sorted(os.environ)) # names only; expected (almost) none print("DYLD_* set:", [k for k in os.environ if k.startswith("DYLD_")]) real = ctypes.util.find_library ctypes.util.find_library = lambda name: str(dylib) if name == "mpv" else real(name) try: import mpv finally: ctypes.util.find_library = real loaded = Path(mpv.backend._name) print("python-mpv", mpv.__version__, "loaded", loaded) if loaded.resolve() != dylib.resolve(): fails.append(f"loaded {loaded}, not the bundled {dylib}") print("client API", ".".join(map(str, mpv.MPV_VERSION))) logs = [] player = mpv.MPV(vo="null", ao="null", loglevel="info", log_handler=lambda lvl, comp, msg: logs.append(f"[{lvl}] {comp}: {msg.rstrip()}")) for prop in ("mpv-version", "ffmpeg-version", "libass-version", "mpv-configuration"): print(f"{prop} = {prop_of(player, prop)}") conf = prop_of(player, "mpv-configuration") or "" if "-Dgpl=false" not in conf: fails.append("mpv-configuration lacks -Dgpl=false") if str(prop_of(player, "mpv-version")) not in ("mpv v0.42.0", "mpv 0.42.0"): fails.append(f"unexpected mpv-version {prop_of(player, 'mpv-version')}") try: prop_of(player, "osc") fails.append("the osc property exists: this build has Lua") except Exception as exc: # noqa: BLE001 print(f"osc property absent, as expected without Lua ({type(exc).__name__})") t0 = time.monotonic() player.play(TEST_SOURCE) player.wait_until_playing(timeout=30) print(f"playing after {time.monotonic() - t0:.2f} s") time.sleep(1.0) p1 = prop_of(player, "time-pos") time.sleep(1.0) p2 = prop_of(player, "time-pos") print(f"time-pos {p1} -> {p2}") if p1 is None or p2 is None or p2 <= p1: fails.append(f"playback did not advance ({p1} -> {p2})") for prop in ("video-codec", "video-params", "audio-codec-name", "audio-params", "container-fps", "frame-drop-count", "hwdec-current"): try: print(f"{prop} = {prop_of(player, prop)}") except Exception as exc: # noqa: BLE001 print(f"{prop} unavailable ({type(exc).__name__})") # The app's fallback watermark graph (mpv_widget.py, without ":loop=0"). The ":loop=0" form # blocks mpv's core in this headless setup (vo=null, lavfi source) on every libmpv tried, # including Linux's system mpv 0.37.0 / FFmpeg 6.1.1 with the app's own advert GIF, so it is # not a property of this build; Spike 2 checks it with a real stream and the render path. gif = work / "wm.gif" gif.write_bytes(GIF_ANIM) graph = f"movie='{gif}'[wm];[vid1][wm]overlay=W-w-10:10[vo]" player.command("set", "lavfi-complex", graph) time.sleep(1.0) p3 = prop_of(player, "time-pos") print(f"watermark graph applied: {prop_of(player, 'lavfi-complex') == graph}; time-pos now {p3}") if prop_of(player, "lavfi-complex") != graph: fails.append("lavfi-complex was not applied") if p3 is None or p3 <= p2: fails.append(f"playback stopped after the watermark graph ({p2} -> {p3})") errors = [line for line in logs if line.startswith(("[error]", "[fatal]"))] player.terminate() print() print(f"{len(logs)} log lines; errors and fatal lines: {len(errors)}") for line in errors: print(" " + line) warn = [line for line in logs if line.startswith("[warn]")] for line in warn[:20]: print(" " + line) if errors: fails.append(f"{len(errors)} error lines in the mpv log") check_av1(mpv, work, fails) if fails: print("SMOKE TEST FAILED:") for f in fails: print(" - " + f) sys.exit(1) print("SMOKE TEST PASSED") if __name__ == "__main__": main()