// The picture's encode in a live conversion: see hdff_convert.h. A decoded
// picture is dropped before the start, scaled (scale_vt keeps VideoToolbox
// frames on the GPU), held to 30 fps and encoded by h264_videotoolbox with
// the numbers of the Mac's segmented `playable` (mediaext/jobs/args.go).
#include "hdff_convert.h"

#include <math.h>

#include <VideoToolbox/VideoToolbox.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/hwcontext.h>

// args.go's segmentedMaxFrameRate and its playable bitrate: 0.1 bit per pixel
// per frame, 1 to 6 Mbit/s, at most 60 fps.
#define SEGMENTED_MAX_FRAME_RATE 30.0
#define BITS_PER_PIXEL_PER_FRAME 0.1
#define MIN_BITRATE 1000000
#define MAX_BITRATE 6000000
#define PLAYABLE_MAX_FRAME_RATE 60.0

// The display size: the coded size with non-square pixels made square.
static void display_size(const AVCodecParameters *par, AVRational sar, int *w, int *h) {
    *w = par->width;
    *h = par->height;
    if (sar.num > 0 && sar.den > 0 && sar.num != sar.den) {
        double wide = round(par->width * av_q2d(sar));
        if (wide > 0 && wide < INT32_MAX) *w = (int)wide;
    }
}

static int even_down(int n) { return FFMAX(2, n % 2 ? n - 1 : n); }

// args.go fitEven with no width cap: w x h scaled to fit max_h, on even numbers.
static void fit_even(int w, int h, int max_h, int *out_w, int *out_h) {
    if (w <= 0 || h <= 0) {
        *out_w = *out_h = 2;
        return;
    }
    if (max_h <= 0 || h <= max_h) {
        *out_w = even_down(w);
        *out_h = even_down(h);
        return;
    }
    double scale = (double)max_h / h;
    *out_w = even_down((int)round(w * scale));
    *out_h = even_down((int)round(h * scale));
}

// args.go segmentedVideoBitrate: the playable bitrate at the capped rate.
static int segmented_bitrate(int w, int h, int max_h, double fps) {
    if (h > max_h && h > 0) {
        w = w * max_h / h;
        h = max_h;
    }
    double raw = (double)w * h * FFMIN(fps, PLAYABLE_MAX_FRAME_RATE) * BITS_PER_PIXEL_PER_FRAME;
    return (int)FFMIN(FFMAX(raw, MIN_BITRATE), MAX_BITRATE);
}

static CFTypeRef session_property(VTCompressionSessionRef session, CFStringRef key) {
    CFTypeRef value = NULL;
    return VTSessionCopyProperty(session, key, NULL, &value) == noErr ? value : NULL;
}

// Whether a VideoToolbox H.264 session at w x h runs on a hardware encoder,
// by its own report or by the encoder list's entry for its encoder: the
// Simulator opens a session that asks for hardware on its software encoder.
static int hardware_h264_encoder(int w, int h) {
    CFMutableDictionaryRef spec =
        CFDictionaryCreateMutable(NULL, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(spec, kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder, kCFBooleanTrue);
    VTCompressionSessionRef session = NULL;
    OSStatus status =
        VTCompressionSessionCreate(NULL, w, h, kCMVideoCodecType_H264, spec, NULL, NULL, NULL, NULL, &session);
    CFRelease(spec);
    if (status != noErr || !session) return 0;
    int hardware = 0;
    CFTypeRef using = session_property(session, kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder);
    if (using) {
        hardware = CFGetTypeID(using) == CFBooleanGetTypeID() && CFBooleanGetValue(using);
        CFRelease(using);
    }
    CFTypeRef id = hardware ? NULL : session_property(session, kVTCompressionPropertyKey_EncoderID);
    CFArrayRef list = NULL;
    if (id && VTCopyVideoEncoderList(NULL, &list) == noErr && list) {
        for (CFIndex i = 0; i < CFArrayGetCount(list); i++) {
            CFDictionaryRef entry = CFArrayGetValueAtIndex(list, i);
            CFTypeRef entry_id = CFDictionaryGetValue(entry, kVTVideoEncoderList_EncoderID);
            if (!entry_id || !CFEqual(entry_id, id)) continue;
            CFTypeRef flag = CFDictionaryGetValue(entry, kVTVideoEncoderList_IsHardwareAccelerated);
            hardware = flag && CFGetTypeID(flag) == CFBooleanGetTypeID() && CFBooleanGetValue(flag);
            break;
        }
        CFRelease(list);
    }
    if (id) CFRelease(id);
    VTCompressionSessionInvalidate(session);
    CFRelease(session);
    return hardware;
}

// Plans the encode from the source: its size, rate and bitrate, then opens
// the decoder.
int hdff_picture_prepare(hdff_conv *c) {
    AVStream *st = c->in->streams[c->vin];
    const AVCodecParameters *par = st->codecpar;
    int w, h;
    display_size(par, av_guess_sample_aspect_ratio(c->in, st, NULL), &w, &h);
    fit_even(w, h, c->job->max_height, &c->out_w, &c->out_h);
    c->scales = c->out_w != par->width || c->out_h != par->height;
    c->source_rate = st->avg_frame_rate.num > 0 ? st->avg_frame_rate : st->r_frame_rate;
    double source = c->source_rate.num > 0 && c->source_rate.den > 0 ? av_q2d(c->source_rate) : 0;
    c->fps = FFMIN(source > 0 ? source : 30, SEGMENTED_MAX_FRAME_RATE);
    c->caps_rate = source > SEGMENTED_MAX_FRAME_RATE;
    c->bitrate = segmented_bitrate(w, h, c->job->max_height, c->fps);
    if (!c->job->allow_software_encoder && !hardware_h264_encoder(c->out_w, c->out_h))
        return hdff_fail(c, AVERROR(ENOSYS), "This device has no hardware H.264 encoder.");
    int ret = hdff_decoder_open(&c->dec, par, st->time_base);
    if (ret < 0) return hdff_fail(c, ret, "The video's picture cannot be decoded.");
    return 0;
}


// The picture's filters, built for the first decoded frame: VideoToolbox
// frames stay on the GPU and are scaled by scale_vt; software frames are
// scaled by scale and handed to the encoder as NV12. Above 30 fps, fps=30.
static int build_picture_filters(hdff_conv *c, const AVFrame *first) {
    AVStream *st = c->in->streams[c->vin];
    int hardware = first->format == AV_PIX_FMT_VIDEOTOOLBOX;
    AVFilterGraph *graph = c->vgraph = avfilter_graph_alloc();
    if (!graph) return AVERROR(ENOMEM);
    c->vsrc = avfilter_graph_alloc_filter(graph, avfilter_get_by_name("buffer"), "in");
    AVBufferSrcParameters *p = av_buffersrc_parameters_alloc();
    if (!c->vsrc || !p) {
        av_free(p);
        return AVERROR(ENOMEM);
    }
    p->format = first->format;
    p->width = first->width;
    p->height = first->height;
    p->time_base = st->time_base;
    p->sample_aspect_ratio = first->sample_aspect_ratio;
    p->frame_rate = c->source_rate;
    p->hw_frames_ctx = first->hw_frames_ctx;
    p->color_space = first->colorspace;
    p->color_range = first->color_range;
    int ret = av_buffersrc_parameters_set(c->vsrc, p);
    av_free(p);
    if (ret >= 0) ret = avfilter_init_str(c->vsrc, NULL);
    AVFilterContext *last = c->vsrc;
    char args[64];
    if (ret >= 0 && c->scales) {
        snprintf(args, sizeof args, "w=%d:h=%d", c->out_w, c->out_h);
        ret = hdff_add_filter(graph, &last, hardware ? "scale_vt" : "scale", args);
    }
    if (ret >= 0 && c->caps_rate) ret = hdff_add_filter(graph, &last, "fps", "fps=30");
    if (ret >= 0 && !hardware) ret = hdff_add_filter(graph, &last, "format", "pix_fmts=nv12");
    if (ret >= 0) ret = avfilter_graph_create_filter(&c->vsink, avfilter_get_by_name("buffersink"), "out", NULL, NULL, graph);
    if (ret >= 0) ret = avfilter_link(last, 0, c->vsink, 0);
    if (ret >= 0) ret = avfilter_graph_config(graph, NULL);
    return ret;
}

// h264_videotoolbox as the Mac runs it for a segmented encode: High profile,
// the bitrate as average and maximum with a buffer of twice it, and a GOP of
// 2 s at the capped rate.
static int open_picture_encoder(hdff_conv *c) {
    const AVCodec *codec = avcodec_find_encoder_by_name("h264_videotoolbox");
    if (!codec) return hdff_fail(c, AVERROR_ENCODER_NOT_FOUND, "The H.264 encoder is missing.");
    AVCodecContext *enc = c->venc = avcodec_alloc_context3(codec);
    if (!enc) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    enc->width = av_buffersink_get_w(c->vsink);
    enc->height = av_buffersink_get_h(c->vsink);
    enc->pix_fmt = av_buffersink_get_format(c->vsink);
    AVBufferRef *frames = av_buffersink_get_hw_frames_ctx(c->vsink);
    if (enc->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX && frames) {
        enc->hw_frames_ctx = av_buffer_ref(frames);
        enc->sw_pix_fmt = ((AVHWFramesContext *)frames->data)->sw_format;
    }
    enc->time_base = av_buffersink_get_time_base(c->vsink);
    enc->framerate = av_buffersink_get_frame_rate(c->vsink);
    if (enc->framerate.num <= 0) enc->framerate = av_d2q(c->fps, 1000);
    enc->sample_aspect_ratio = (AVRational){1, 1};
    enc->colorspace = av_buffersink_get_colorspace(c->vsink);
    enc->color_range = av_buffersink_get_color_range(c->vsink);
    enc->bit_rate = c->bitrate;
    enc->rc_max_rate = c->bitrate;
    enc->rc_buffer_size = c->bitrate * 2;
    enc->gop_size = (int)lround(SEGMENT_SECONDS * c->fps);
    if (c->out->oformat->flags & AVFMT_GLOBALHEADER) enc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    AVDictionary *opts = NULL;
    av_dict_set(&opts, "profile", "high", 0);
    av_dict_set(&opts, "allow_sw", c->job->allow_software_encoder ? "1" : "0", 0);
    int ret = avcodec_open2(enc, codec, &opts);
    av_dict_free(&opts);
    if (ret < 0) return hdff_fail(c, ret, "The H.264 encoder could not start.");
    if ((ret = avcodec_parameters_from_context(c->vout->codecpar, enc)) < 0) return hdff_fail(c, ret, "Out of memory.");
    c->vout->time_base = enc->time_base;
    c->vout->avg_frame_rate = enc->framerate;
    return 0;
}

// A filtered picture into the encoder, a keyframe forced every 2 s of
// output (the Mac's expr:gte(t,n_forced*2)).
static int encode_picture(hdff_conv *c, AVFrame *f) {
    int ret;
    if (!c->venc && (ret = open_picture_encoder(c)) < 0) return ret;
    if (!c->header && (ret = hdff_write_header(c)) < 0) return ret;
    f->pict_type = AV_PICTURE_TYPE_NONE;
    if (f->pts != AV_NOPTS_VALUE && f->pts * av_q2d(c->venc->time_base) >= c->forced * SEGMENT_SECONDS) {
        f->pict_type = AV_PICTURE_TYPE_I;
        c->forced++;
    }
    f->sample_aspect_ratio = (AVRational){1, 1};
    return hdff_encode(c, c->venc, c->vout, f);
}

static int pull_pictures(hdff_conv *c) {
    for (;;) {
        int ret = av_buffersink_get_frame(c->vsink, c->filtered);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return 0;
        if (ret < 0) return hdff_fail(c, ret, "The video's picture could not be scaled.");
        ret = encode_picture(c, c->filtered);
        av_frame_unref(c->filtered);
        if (ret < 0) return ret;
    }
}

// Each decoded picture: reported once, dropped before the start (an
// accurate seek), timed from the start, then filtered and encoded.
static int on_picture(void *opaque, AVFrame *frame) {
    hdff_conv *c = opaque;
    if (!c->decoder_reported) {
        c->decoder_reported = 1;
        if (c->job->cb.decoder)
            c->job->cb.decoder(c->job->cb.context, hdff_decoder_name(&c->dec), frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
    }
    AVStream *st = c->in->streams[c->vin];
    int64_t ts = frame->best_effort_timestamp != AV_NOPTS_VALUE ? frame->best_effort_timestamp : frame->pts;
    if (c->untimed) {
        AVRational rate = st->avg_frame_rate.num > 0 ? st->avg_frame_rate
                        : st->r_frame_rate.num > 0 ? st->r_frame_rate : (AVRational){25, 1};
        ts = c->untimed_next;
        c->untimed_next += av_rescale_q(1, av_inv_q(rate), st->time_base);
    }
    if (ts == AV_NOPTS_VALUE) return 0;
    ts -= av_rescale_q(c->base, AV_TIME_BASE_Q, st->time_base);
    if (ts < 0) return 0;
    frame->pts = ts;
    int ret;
    if (!c->vgraph && (ret = build_picture_filters(c, frame)) < 0)
        return hdff_fail(c, ret, "The video's picture could not be scaled.");
    if ((ret = av_buffersrc_add_frame_flags(c->vsrc, frame, AV_BUFFERSRC_FLAG_KEEP_REF)) < 0)
        return hdff_fail(c, ret, "The video's picture could not be scaled.");
    return pull_pictures(c);
}

int hdff_picture_decode(hdff_conv *c, const AVPacket *pkt) {
    int ret = hdff_decoder_decode(&c->dec, pkt, c->frame, on_picture, c);
    if (ret < 0 && !c->dec.callback_failed) return hdff_fail(c, ret, "The video's picture could not be decoded.");
    return ret;
}

int hdff_picture_finish(hdff_conv *c) {
    int ret = hdff_picture_decode(c, NULL);
    if (ret < 0) return ret;
    if (c->vgraph) {
        if ((ret = av_buffersrc_add_frame(c->vsrc, NULL)) < 0)
            return hdff_fail(c, ret, "The video's picture could not be scaled.");
        if ((ret = pull_pictures(c)) < 0) return ret;
    }
    if (!c->venc) return hdff_fail(c, AVERROR_INVALIDDATA, "No picture could be decoded from the video.");
    return hdff_encode(c, c->venc, c->vout, NULL);
}
