// Video decoders opened hardware first: see hdff_internal.h.
#include "hdff_internal.h"

#include <stdlib.h>
#include <string.h>

#include <VideoToolbox/VideoToolbox.h>
#include <libavutil/hwcontext.h>

// How many packets a hardware decoder may take without a frame before it
// counts as failed and the decode moves to software.
#define KEEP_MAX 256

// The VideoToolbox codec type for a stream, or 0 when VideoToolbox has none.
static CMVideoCodecType videotoolbox_codec(const AVCodecParameters *par) {
    switch (par->codec_id) {
    case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
    case AV_CODEC_ID_HEVC: return kCMVideoCodecType_HEVC;
    case AV_CODEC_ID_VP9: return kCMVideoCodecType_VP9;
    case AV_CODEC_ID_AV1: return kCMVideoCodecType_AV1;
    case AV_CODEC_ID_MPEG1VIDEO: return kCMVideoCodecType_MPEG1Video;
    case AV_CODEC_ID_MPEG2VIDEO: return kCMVideoCodecType_MPEG2Video;
    case AV_CODEC_ID_MPEG4: return kCMVideoCodecType_MPEG4Video;
    case AV_CODEC_ID_PRORES:
        switch (par->profile) {
        case AV_PROFILE_PRORES_PROXY: return kCMVideoCodecType_AppleProRes422Proxy;
        case AV_PROFILE_PRORES_LT: return kCMVideoCodecType_AppleProRes422LT;
        case AV_PROFILE_PRORES_HQ: return kCMVideoCodecType_AppleProRes422HQ;
        case AV_PROFILE_PRORES_4444: return kCMVideoCodecType_AppleProRes4444;
        case AV_PROFILE_PRORES_XQ: return kCMVideoCodecType_AppleProRes4444XQ;
        default: return kCMVideoCodecType_AppleProRes422;
        }
    default: return 0;
    }
}

// The Debug build's test hook: HDFF_TEST_FAIL_HW=1 in the environment.
static int hardware_fails_for_test(void) {
#ifdef DEBUG
    const char *hook = getenv("HDFF_TEST_FAIL_HW");
    return hook && strcmp(hook, "1") == 0;
#else
    return 0;
#endif
}

int hdff_hardware_decodes(const AVCodecParameters *par) {
    if (hardware_fails_for_test()) return 1;
    CMVideoCodecType type = videotoolbox_codec(par);
    return type != 0 && VTIsHardwareDecodeSupported(type);
}

// The decoder for an open: the native one, driven by its VideoToolbox
// hwaccel, for hardware; for software, libdav1d for AV1 (the native av1
// decoder only drives hardware) and the native one for everything else.
static const AVCodec *video_decoder(enum AVCodecID id, int hardware) {
    if (id == AV_CODEC_ID_AV1) return avcodec_find_decoder_by_name(hardware ? "av1" : "libdav1d");
    return avcodec_find_decoder(id);
}

// get_format for a hardware open: VideoToolbox, with frames VideoToolbox
// hands out as 8-bit NV12 whatever the source's depth, which is what the
// H.264 encoder takes; or no format at all, so a stream VideoToolbox refuses
// fails the decode instead of going on in software unnoticed.
static enum AVPixelFormat videotoolbox_format(AVCodecContext *ctx, const enum AVPixelFormat *formats) {
    if (hardware_fails_for_test()) return AV_PIX_FMT_NONE;
    for (const enum AVPixelFormat *f = formats; *f != AV_PIX_FMT_NONE; f++) {
        if (*f != AV_PIX_FMT_VIDEOTOOLBOX) continue;
        AVBufferRef *frames = NULL;
        if (avcodec_get_hw_frames_parameters(ctx, ctx->hw_device_ctx, AV_PIX_FMT_VIDEOTOOLBOX, &frames) < 0)
            return AV_PIX_FMT_NONE;
        ((AVHWFramesContext *)frames->data)->sw_format = AV_PIX_FMT_NV12;
        if (av_hwframe_ctx_init(frames) < 0) {
            av_buffer_unref(&frames);
            return AV_PIX_FMT_NONE;
        }
        av_buffer_unref(&ctx->hw_frames_ctx);
        ctx->hw_frames_ctx = frames;
        return AV_PIX_FMT_VIDEOTOOLBOX;
    }
    return AV_PIX_FMT_NONE;
}

static int open_context(hdff_decoder *d, int hardware) {
    const AVCodec *codec = video_decoder(d->par->codec_id, hardware);
    if (!codec) return AVERROR_DECODER_NOT_FOUND;
    AVCodecContext *ctx = avcodec_alloc_context3(codec);
    if (!ctx) return AVERROR(ENOMEM);
    int ret = avcodec_parameters_to_context(ctx, d->par);
    ctx->pkt_timebase = d->time_base;
    // VideoToolbox does a hardware decode's work, and one thread reports its
    // failure on the packet that caused it; software decodes on every core.
    ctx->thread_count = hardware ? 1 : 0;
    if (ret >= 0 && hardware) {
        ret = av_hwdevice_ctx_create(&ctx->hw_device_ctx, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, NULL, NULL, 0);
        ctx->get_format = videotoolbox_format;
    }
    if (ret >= 0) ret = avcodec_open2(ctx, codec, NULL);
    if (ret < 0) {
        avcodec_free_context(&ctx);
        return ret;
    }
    d->ctx = ctx;
    d->hardware = hardware;
    return 0;
}

int hdff_decoder_open(hdff_decoder *d, const AVCodecParameters *par, AVRational time_base) {
    memset(d, 0, sizeof *d);
    d->par = par;
    d->time_base = time_base;
    if (hdff_hardware_decodes(par) && open_context(d, 1) >= 0) return 0;
    return open_context(d, 0);
}

static void drop_kept(hdff_decoder *d) {
    for (int i = 0; i < d->nkept; i++) av_packet_free(&d->kept[i]);
    av_freep(&d->kept);
    d->nkept = 0;
}

static int keep(hdff_decoder *d, const AVPacket *pkt) {
    if (d->nkept == KEEP_MAX) return AVERROR(ENOSPC);
    if (!d->kept && !(d->kept = av_calloc(KEEP_MAX, sizeof *d->kept))) return AVERROR(ENOMEM);
    if (!(d->kept[d->nkept] = av_packet_clone(pkt))) return AVERROR(ENOMEM);
    d->nkept++;
    return 0;
}

// Takes every frame the decoder holds out and hands it to fn: answers how
// many came out, or a negative code.
static int drain(hdff_decoder *d, AVFrame *frame, hdff_frame_fn fn, void *opaque) {
    int n = 0;
    for (;;) {
        int ret = avcodec_receive_frame(d->ctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return n;
        if (ret == AVERROR_INVALIDDATA && d->produced) continue;
        if (ret < 0) return ret;
        if (!d->produced) {
            d->produced = 1;
            drop_kept(d);
        }
        n++;
        ret = fn(opaque, frame);
        av_frame_unref(frame);
        if (ret < 0) {
            d->callback_failed = 1;
            return ret;
        }
    }
}

static int feed(hdff_decoder *d, const AVPacket *pkt, AVFrame *frame, hdff_frame_fn fn, void *opaque) {
    int ret;
    // EAGAIN means the decoder holds output: it is taken out and the same
    // packet sent again. Both sides refusing at once breaks the API's contract.
    while ((ret = avcodec_send_packet(d->ctx, pkt)) == AVERROR(EAGAIN)) {
        int got = drain(d, frame, fn, opaque);
        if (got < 0) return got;
        if (got == 0) return AVERROR_BUG;
    }
    if (ret == AVERROR_EOF) ret = 0;
    if (ret == AVERROR_INVALIDDATA && d->produced) ret = 0;
    if (ret < 0) return ret;
    ret = drain(d, frame, fn, opaque);
    return ret < 0 ? ret : 0;
}

// Reopens the decoder in software and sends it the packets the hardware one
// was sent, then `extra` when it was not among them, then the drain when
// the decode is draining.
static int retry_in_software(hdff_decoder *d, const AVPacket *extra, int draining, AVFrame *frame,
                             hdff_frame_fn fn, void *opaque) {
    AVPacket **kept = d->kept;
    int nkept = d->nkept;
    d->kept = NULL;
    d->nkept = 0;
    avcodec_free_context(&d->ctx);
    int ret = open_context(d, 0);
    for (int i = 0; i < nkept && ret >= 0; i++) ret = feed(d, kept[i], frame, fn, opaque);
    if (ret >= 0 && extra) ret = feed(d, extra, frame, fn, opaque);
    if (ret >= 0 && draining) ret = feed(d, NULL, frame, fn, opaque);
    for (int i = 0; i < nkept; i++) av_packet_free(&kept[i]);
    av_free(kept);
    return ret;
}

int hdff_decoder_decode(hdff_decoder *d, const AVPacket *pkt, AVFrame *frame, hdff_frame_fn fn, void *opaque) {
    int waiting = d->hardware && !d->produced;
    if (waiting && pkt && keep(d, pkt) < 0) return retry_in_software(d, pkt, 0, frame, fn, opaque);
    int ret = feed(d, pkt, frame, fn, opaque);
    if (ret >= 0 || !waiting || d->produced || d->callback_failed) return ret;
    return retry_in_software(d, NULL, pkt == NULL, frame, fn, opaque);
}

const char *hdff_decoder_name(const hdff_decoder *d) { return d->ctx ? d->ctx->codec->name : ""; }

void hdff_decoder_close(hdff_decoder *d) {
    drop_kept(d);
    avcodec_free_context(&d->ctx);
}
