/* The static stand-in for libopenh264 the Linux ffmpeg links in place of
 * the library, so ffmpeg starts on a machine that has none. Nothing about
 * OpenH264 is resolved at start-up: the first WelsCreateSVCEncoder dlopens
 * the file HYPERDROP_OPENH264 names (an absolute path to Cisco's binary,
 * which the Media extension downloaded and verified), checks that its
 * major.minor version is the one the headers describe (ffmpeg allocates
 * the encoder's parameter structures itself, and their layout changes
 * between minor versions), and forwards. Any failure answers "cannot create
 * encoder", which ffmpeg reports as an ordinary error. */
#include <dlfcn.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <wels/codec_api.h>
#include <wels/codec_ver.h>

static int (*real_create)(ISVCEncoder **);
static void (*real_destroy)(ISVCEncoder *);
static pthread_once_t once = PTHREAD_ONCE_INIT;

static void load(void)
{
    const char *path = getenv("HYPERDROP_OPENH264");
    if (!path || path[0] != '/') {
        fprintf(stderr, "openh264: HYPERDROP_OPENH264 names no library\n");
        return;
    }
    void *h = dlopen(path, RTLD_NOW | RTLD_LOCAL);
    if (!h) {
        fprintf(stderr, "openh264: %s\n", dlerror());
        return;
    }
    OpenH264Version (*ver)(void) = (OpenH264Version (*)(void))dlsym(h, "WelsGetCodecVersion");
    if (!ver) {
        fprintf(stderr, "openh264: %s has no WelsGetCodecVersion\n", path);
        dlclose(h);
        return;
    }
    OpenH264Version v = ver();
    if (v.uMajor != OPENH264_MAJOR || v.uMinor != OPENH264_MINOR) {
        fprintf(stderr, "openh264: library is %u.%u, built for %d.%d\n",
                v.uMajor, v.uMinor, OPENH264_MAJOR, OPENH264_MINOR);
        dlclose(h);
        return;
    }
    real_create = (int (*)(ISVCEncoder **))dlsym(h, "WelsCreateSVCEncoder");
    real_destroy = (void (*)(ISVCEncoder *))dlsym(h, "WelsDestroySVCEncoder");
    if (!real_create || !real_destroy) {
        fprintf(stderr, "openh264: %s has no WelsCreateSVCEncoder or WelsDestroySVCEncoder\n", path);
        real_create = NULL;
        real_destroy = NULL;
        dlclose(h);
    }
}

int WelsCreateSVCEncoder(ISVCEncoder **enc)
{
    pthread_once(&once, load);
    if (!real_create) {
        *enc = NULL;
        return 1;
    }
    return real_create(enc);
}

void WelsDestroySVCEncoder(ISVCEncoder *enc)
{
    if (real_destroy && enc)
        real_destroy(enc);
}

OpenH264Version WelsGetCodecVersion(void)
{
    OpenH264Version v = { OPENH264_MAJOR, OPENH264_MINOR, OPENH264_REVISION, OPENH264_RESERVED };
    return v;
}

void WelsGetCodecVersionEx(OpenH264Version *v)
{
    *v = WelsGetCodecVersion();
}
