#!/usr/bin/env python3
"""v0.7.13: the portable Linux viewer's VAAPI without a link to libva.

FFmpeg's VAAPI code calls libva directly, so a binary linked the usual way
would not start on a PC without libva. Instead, this writes va_shim.c: one
tiny x86-64 trampoline per libva function FFmpeg uses (found with nm in the
static FFmpeg libraries), jumping through a pointer that sft_va_load() fills
from the system's own libva.so.2 / libva-drm.so.2 with dlopen. The system's
libva also brings that distribution's driver path, so the GPU's driver is
found as on any other program. No libva: sft_va_load() says so and the
viewer simply does not try VAAPI (the trampolines are never reached).

    python3 gen_va_shim.py OUT.c libavcodec.a libavutil.a ...
"""
import subprocess, sys, re

out, libs = sys.argv[1], sys.argv[2:]
names = set()
for lib in libs:
    nm = subprocess.run(["nm", "-u", lib], capture_output=True, text=True).stdout
    for line in nm.splitlines():
        m = re.match(r"\s*U (va[A-Z]\w*)$", line)
        if m:
            names.add(m.group(1))
names = sorted(names)
if not names:
    sys.exit("no libva symbols - was FFmpeg built with VAAPI?")

c = ['/* generated by gen_va_shim.py - do not edit */',
     '#include <dlfcn.h>',
     '#include <stdio.h>',
     '#define N %d' % len(names),
     '__attribute__((visibility("hidden"))) void *sft_va_ptr[N];',
     'static const char *const sft_va_names[N] = {',
     *['    "%s",' % n for n in names],
     '};',
     '',
     '/* 1: every function FFmpeg needs was found in the system libva */',
     'int sft_va_load(void)',
     '{',
     '    static int state = -1;',
     '    if (state >= 0) return state;',
     '    void *va = dlopen("libva.so.2", RTLD_NOW | RTLD_GLOBAL);',
     '    void *drm = va ? dlopen("libva-drm.so.2", RTLD_NOW | RTLD_GLOBAL) : NULL;',
     '    state = 0;',
     '    if (!va || !drm) { fprintf(stderr, "decode: no libva on this system - VAAPI off\\n"); return 0; }',
     '    for (int i = 0; i < N; i++) {',
     '        void *p = dlsym(va, sft_va_names[i]);',
     '        if (!p) p = dlsym(drm, sft_va_names[i]);',
     '        if (!p) { fprintf(stderr, "decode: the system libva has no %s - VAAPI off\\n", sft_va_names[i]); return 0; }',
     '        sft_va_ptr[i] = p;',
     '    }',
     '    state = 1;',
     '    return 1;',
     '}',
     '',
     '__asm__(".text\\n"']
for i, n in enumerate(names):
    c.append('    ".globl %s\\n.type %s,@function\\n%s:\\n    jmp *sft_va_ptr+%d(%%rip)\\n"' % (n, n, n, 8 * i))
c.append(');')
open(out, "w").write("\n".join(c) + "\n")
print("%s: %d libva functions" % (out, len(names)))
