"""Stage and check the macOS libmpv set built by scripts/macos/build-libmpv.sh. Standard library only; runs on macOS with the Command Line Tools. stage --prefix P --dist D Copy libmpv.2.dylib and every non-system library it needs (breadth-first, as IINA's fix-install-names.sh does) from P/lib into the new folder D under their install names, set each id to @rpath/, point each dependency at @rpath/, leave exactly one LC_RPATH (@loader_path), ad-hoc sign. Nothing outside D is changed. gate --dist D --min-os 13.0 --arch arm64 [--forbid STRING ...] [--build-root PATH] The LGPL and portability gate (docs/macos/PLAN.md 6.4). Prints a report and exits 1 on any failure. """ import argparse import ctypes import os import re import shutil import subprocess import sys from pathlib import Path SYSTEM_PREFIXES = ("/usr/lib/", "/System/Library/Frameworks/") ALLOWED_NAME = re.compile( r"^lib(mpv\.2|avcodec\.\d+|avformat\.\d+|avutil\.\d+|avfilter\.\d+|avdevice\.\d+" r"|swresample\.\d+|swscale\.\d+|placebo\.\d+|ass\.\d+|freetype\.\d+|harfbuzz\.\d+" r"|fribidi\.\d+|dav1d\.\d+)\.dylib$" ) # Libraries that must never be linked, even from the system (GPL, JIT, or deliberately off). FORBIDDEN_DEPS = ("lua", "x264", "x265", "rubberband", "dvdnav", "dvdread", "cdio", "bluray", "archive", "mujs", "curl", "ssl", "crypto", "mbedtls", "gnutls", "fontconfig", "xvid", "postproc", "vidstab", "PrivateFrameworks", "/usr/local/", "/opt/") LOAD_CMDS = ("LC_LOAD_DYLIB", "LC_LOAD_WEAK_DYLIB", "LC_REEXPORT_DYLIB", "LC_LOAD_UPWARD_DYLIB", "LC_LAZY_LOAD_DYLIB") FFMPEG_LIBS = ("avutil", "avcodec", "avformat", "avfilter", "avdevice", "swresample", "swscale") LGPL21 = "LGPL version 2.1 or later" # Exact strings that may contain a forbidden fragment. mpv 0.42.0's `macos-bundle-path` option # defaults to these folders (osdep/mac/app_bridge.m); mpv adds them to PATH only when it is its # own mpv.app (AppHub.initMpv needs mpv's EventHelper, which is nil when NSApp is not mpv's # Application class, i.e. inside Wolvix). Inert data, not a link to Homebrew. ALLOWED_STRINGS = { "libmpv.2.dylib": {"/opt/homebrew/bin", "/opt/homebrew/sbin"}, } def c_strings_containing(data, fragment): """Every NUL-delimited string in data that contains fragment.""" out, start = [], 0 frag = fragment.encode() while True: i = data.find(frag, start) if i < 0: return out a = data.rfind(b"\0", 0, i) + 1 b = data.find(b"\0", i) out.append(data[a:b if b >= 0 else len(data)].decode("utf-8", "replace")) start = i + len(frag) def run(*cmd): return subprocess.run([str(c) for c in cmd], check=True, capture_output=True, text=True).stdout def load_commands(path): """Parse `otool -l` into a list of {field: value} dicts, one per load command.""" cmds, cur = [], None for line in run("/usr/bin/otool", "-l", path).splitlines(): s = line.strip() if s.startswith("Load command"): cur = {} cmds.append(cur) elif cur is not None: parts = s.split(None, 1) if len(parts) == 2 and parts[0] not in cur: cur[parts[0]] = re.sub(r" \(offset \d+\)$", "", parts[1]) return cmds def deps_of(cmds): return [c["name"] for c in cmds if c.get("cmd") in LOAD_CMDS] def ident_of(cmds): ids = [c["name"] for c in cmds if c.get("cmd") == "LC_ID_DYLIB"] return ids[0] if ids else None def rpaths_of(cmds): return [c["path"] for c in cmds if c.get("cmd") == "LC_RPATH"] def is_system(dep): return dep.startswith(SYSTEM_PREFIXES) # ------------------------------------------------------------------------------------- stage def stage(prefix, dist): lib = prefix / "lib" dist.mkdir(parents=True, exist_ok=False) queue, done = ["libmpv.2.dylib"], [] while queue: name = queue.pop(0) if name in done: continue src = lib / name if not src.exists(): sys.exit(f"stage: {src} does not exist") dst = dist / name shutil.copy2(src, dst) # follows symlinks: the real file under its soname os.chmod(dst, 0o755) done.append(name) for dep in deps_of(load_commands(dst)): if is_system(dep): continue base = os.path.basename(dep) if dep.startswith("@rpath/") or dep.startswith(str(lib) + "/"): queue.append(base) else: sys.exit(f"stage: {name} depends on {dep}, which is neither system nor ours") for name in done: p = dist / name cmds = load_commands(p) args = ["-id", f"@rpath/{name}"] for dep in deps_of(cmds): if not is_system(dep): new = "@rpath/" + os.path.basename(dep) if dep != new: args += ["-change", dep, new] run("/usr/bin/install_name_tool", *args, p) for r in rpaths_of(load_commands(p)): run("/usr/bin/install_name_tool", "-delete_rpath", r, p) run("/usr/bin/install_name_tool", "-add_rpath", "@loader_path", p) run("/usr/bin/codesign", "--force", "--sign", "-", "--timestamp=none", p) print(f"staged {name}") print(f"{len(done)} libraries in {dist}") # -------------------------------------------------------------------------------------- gate def ffmpeg_libs(dist): libs = {} for stem in FFMPEG_LIBS: found = sorted(dist.glob(f"lib{stem}.*.dylib")) if found: libs[stem] = ctypes.CDLL(str(found[0])) return libs def cstr(lib, fn, *args, argtypes=None): f = getattr(lib, fn) f.restype = ctypes.c_char_p if argtypes is not None: f.argtypes = argtypes v = f(*args) return v.decode() if v else None def gate(dist, min_os, arch, forbid, build_root): fails, notes = [], [] files = sorted(p for p in dist.iterdir() if p.is_file()) names = {p.name for p in files} if "libmpv.2.dylib" not in names: fails.append("libmpv.2.dylib missing") total = 0 print(f"{'file':28s} {'bytes':>10s} arch minos sdk") system_deps = set() for p in files: size = p.stat().st_size total += size if not ALLOWED_NAME.match(p.name): fails.append(f"{p.name}: not on the allow-list of library names") archs = run("/usr/bin/lipo", "-archs", p).split() if archs != [arch]: fails.append(f"{p.name}: architectures {archs}, want [{arch}]") cmds = load_commands(p) bv = [c for c in cmds if c.get("cmd") == "LC_BUILD_VERSION"] if any(c.get("cmd") == "LC_VERSION_MIN_MACOSX" for c in cmds): fails.append(f"{p.name}: has an old LC_VERSION_MIN_MACOSX command") minos = sdk = "?" if len(bv) != 1: fails.append(f"{p.name}: {len(bv)} LC_BUILD_VERSION commands, want 1") else: minos, sdk, plat = bv[0].get("minos"), bv[0].get("sdk"), bv[0].get("platform") if plat not in ("1", "MACOS", "macos"): fails.append(f"{p.name}: platform {plat}, want MACOS (1)") if minos != min_os: fails.append(f"{p.name}: minos {minos}, want {min_os}") print(f"{p.name:28s} {size:10d} {','.join(archs):6s} {minos:6s} {sdk}") ident = ident_of(cmds) if ident != f"@rpath/{p.name}": fails.append(f"{p.name}: install name {ident}, want @rpath/{p.name}") rp = rpaths_of(cmds) if rp != ["@loader_path"]: fails.append(f"{p.name}: LC_RPATH {rp}, want ['@loader_path']") weak = {c["name"] for c in cmds if c.get("cmd") == "LC_LOAD_WEAK_DYLIB"} for dep in deps_of(cmds): if dep.startswith("@rpath/"): if dep[len("@rpath/"):] not in names: fails.append(f"{p.name}: needs {dep}, which is not in the set") elif is_system(dep): system_deps.add(dep + (" (weak)" if dep in weak else "")) else: fails.append(f"{p.name}: dependency outside the set and the system: {dep}") low = dep.lower() for bad in FORBIDDEN_DEPS: if bad.lower() in low: fails.append(f"{p.name}: forbidden dependency {dep} (matches {bad!r})") data = p.read_bytes() allowed = ALLOWED_STRINGS.get(p.name, set()) for s in forbid: found = c_strings_containing(data, s) bad = [x for x in found if x not in allowed] ok = [x for x in found if x in allowed] if bad: fails.append(f"{p.name}: contains {s!r} in {bad}") if ok: notes.append(f"{p.name}: allow-listed strings containing {s!r}: {ok} " "(mpv's inert macos-bundle-path default)") if build_root: n = data.count(build_root.encode()) if n: notes.append(f"{p.name}: build folder path appears {n} time(s) (informational)") r = subprocess.run(["/usr/bin/codesign", "--verify", "--strict", str(p)], capture_output=True, text=True) if r.returncode != 0: fails.append(f"{p.name}: codesign --verify failed: {r.stderr.strip()}") print(f"{'total':28s} {total:10d} ({total / 1048576:.1f} MiB)") print() print("System libraries and frameworks linked:") for d in sorted(system_deps): print(f" {d}") print() # FFmpeg licence and configuration, read from the built libraries themselves. libs = ffmpeg_libs(dist) for stem in FFMPEG_LIBS: if stem not in libs: fails.append(f"lib{stem} missing from the set") print("FFmpeg libraries:") for stem, lib in libs.items(): vf = getattr(lib, f"{stem}_version") vf.restype = ctypes.c_uint v = vf() lic = cstr(lib, f"{stem}_license") print(f" lib{stem} {v >> 16}.{(v >> 8) & 0xFF}.{v & 0xFF}: {lic}") if lic != LGPL21: fails.append(f"lib{stem} licence is {lic!r}, want {LGPL21!r}") conf = cstr(lib, f"{stem}_configuration") or "" for bad in ("--enable-gpl", "--enable-nonfree", "--enable-version3"): if bad in conf: fails.append(f"lib{stem} configured with {bad}") for need in ("--disable-autodetect", "--enable-securetransport", "--enable-videotoolbox", "--enable-libdav1d"): if need not in conf: fails.append(f"lib{stem} configuration lacks {need}") if "avutil" in libs: conf = cstr(libs["avutil"], "avutil_configuration") or "" flags = [f for f in conf.split() if f.startswith("--") and not f.startswith( ("--prefix", "--extra-", "--pkg-config=", "--install-name-dir"))] print(" configure flags: " + " ".join(flags)) print(" ffmpeg version: " + (cstr(libs["avutil"], "av_version_info") or "?")) dav1d = sorted(dist.glob("libdav1d.*.dylib")) if dav1d: print(" dav1d version: " + (cstr(ctypes.CDLL(str(dav1d[0])), "dav1d_version") or "?")) else: fails.append("libdav1d missing from the set (software AV1 decoding)") print() # What the app needs from FFmpeg (IPTV playback, the watermark filter, test sources). if all(k in libs for k in ("avcodec", "avformat", "avfilter", "avdevice", "avutil")): avc, avf, afl, avd, avu = (libs[k] for k in ("avcodec", "avformat", "avfilter", "avdevice", "avutil")) avd.avdevice_register_all.restype = None avd.avdevice_register_all() avc.avcodec_find_decoder_by_name.restype = ctypes.c_void_p avc.avcodec_find_decoder_by_name.argtypes = [ctypes.c_char_p] avf.av_find_input_format.restype = ctypes.c_void_p avf.av_find_input_format.argtypes = [ctypes.c_char_p] afl.avfilter_get_by_name.restype = ctypes.c_void_p afl.avfilter_get_by_name.argtypes = [ctypes.c_char_p] avu.av_hwdevice_find_type_by_name.restype = ctypes.c_int avu.av_hwdevice_find_type_by_name.argtypes = [ctypes.c_char_p] avf.avio_enum_protocols.restype = ctypes.c_char_p avf.avio_enum_protocols.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_int] need = { "decoders": (avc.avcodec_find_decoder_by_name, "h264 hevc mpeg2video mpeg4 vp9 vc1 aac aac_latm ac3 eac3 mp3 mp2 " "opus vorbis flac pcm_s16le gif png mjpeg subrip ass webvtt mov_text " "dvbsub dvdsub libdav1d"), "demuxers": (avf.av_find_input_format, "hls mpegts mov matroska flv aac mp3 gif image2 rtsp lavfi"), "filters": (afl.avfilter_get_by_name, "movie overlay scale format aresample null anull testsrc2 sine"), } for kind, (fn, items) in need.items(): missing = [i for i in items.split() if not fn(i.encode())] print(f" {kind}: {'all present' if not missing else 'MISSING ' + ' '.join(missing)}") if missing: fails.append(f"FFmpeg {kind} missing: {' '.join(missing)}") for opt in ("dash",): print(f" optional demuxer {opt}: {'present' if avf.av_find_input_format(opt.encode()) else 'absent'}") # The decoder FFmpeg (and mpv, which keeps FFmpeg's order) picks for AV1 without # hardware decoding. FFmpeg's native "av1" decoder only drives hardware decoders, so # software AV1 needs libdav1d first. First fields: AVCodecDescriptor.id, AVCodec.name. avc.avcodec_descriptor_get_by_name.restype = ctypes.c_void_p avc.avcodec_descriptor_get_by_name.argtypes = [ctypes.c_char_p] avc.avcodec_find_decoder.restype = ctypes.c_void_p avc.avcodec_find_decoder.argtypes = [ctypes.c_int] desc = avc.avcodec_descriptor_get_by_name(b"av1") dec = avc.avcodec_find_decoder(ctypes.cast(desc, ctypes.POINTER(ctypes.c_int))[0]) if desc else None av1 = ctypes.cast(dec, ctypes.POINTER(ctypes.c_char_p))[0].decode() if dec else None print(f" default AV1 decoder: {av1}") if av1 != "libdav1d": fails.append(f"the default AV1 decoder is {av1}, want libdav1d") opaque = ctypes.c_void_p() protos = [] while True: name = avf.avio_enum_protocols(ctypes.byref(opaque), 0) if not name: break protos.append(name.decode()) print(f" input protocols: {' '.join(protos)}") # (FFmpeg 9 no longer has the old "hls:" protocol; HLS is the hls demuxer above.) missing = [x for x in "file http https tls tcp udp rtp crypto data rtmp".split() if x not in protos] if missing: fails.append(f"FFmpeg protocols missing: {' '.join(missing)}") vt = avu.av_hwdevice_find_type_by_name(b"videotoolbox") print(f" hwdevice videotoolbox: {'present' if vt > 0 else 'MISSING'}") if vt <= 0: fails.append("FFmpeg has no VideoToolbox hwdevice") print() for n in notes: print("note: " + n) if fails: print("GATE FAILED:") for f in fails: print(" - " + f) sys.exit(1) print("GATE PASSED") def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) s = sub.add_parser("stage") s.add_argument("--prefix", type=Path, required=True) s.add_argument("--dist", type=Path, required=True) g = sub.add_parser("gate") g.add_argument("--dist", type=Path, required=True) g.add_argument("--min-os", required=True) g.add_argument("--arch", required=True) g.add_argument("--forbid", action="append", default=[]) g.add_argument("--build-root", default="") a = ap.parse_args() if a.cmd == "stage": stage(a.prefix, a.dist) else: gate(a.dist, a.min_os, a.arch, a.forbid, a.build_root) if __name__ == "__main__": main()