// The driver over libav*: see hdff.h. This file holds the log path, the
// input rules, the probe, the copy rule and the decode self-test;
// hdff_decode.c opens video decoders hardware first, and hdff_hls.c runs the
// live conversion with hdff_picture.c encoding its picture.
#include "hdff_internal.h"

#include <os/log.h>
#include <pthread.h>
#include <string.h>

#include <libavutil/avstring.h>
#include <libavutil/pixdesc.h>
#include <libavutil/time.h>

const char *hdff_version(void) { return av_version_info(); }

// MARK: The log path

static os_log_t ffmpeg_log;
static pthread_once_t log_once = PTHREAD_ONCE_INIT;

static int scheme_char(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '+' || c == '-' ||
           c == '.';
}

static int token_end(char c) {
    return c == '\0' || c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\'' || c == '"' || c == '<' ||
           c == '>' || c == '`';
}

// Copies `in` into `out` with everything after each "scheme://" up to the
// end of its token replaced by "<redacted>", and without a trailing newline.
static void redact(const char *in, char *out, size_t size) {
    static const char mark[] = "<redacted>";
    size_t o = 0;
    for (const char *p = in; *p && o + 1 < size;) {
        if (p[0] == ':' && p[1] == '/' && p[2] == '/' && p > in && scheme_char(p[-1])) {
            const char *end = p + 3;
            while (!token_end(*end)) end++;
            for (const char *q = "://"; *q && o + 1 < size; q++) out[o++] = *q;
            for (const char *q = mark; *q && o + 1 < size; q++) out[o++] = *q;
            p = end;
            continue;
        }
        out[o++] = *p++;
    }
    while (o > 0 && (out[o - 1] == '\n' || out[o - 1] == '\r')) o--;
    out[o] = '\0';
}

static void emit(int level, const char *line) {
    char out[2048];
    redact(line, out, sizeof out);
    if (!out[0]) return;
    os_log_with_type(ffmpeg_log, level <= AV_LOG_ERROR ? OS_LOG_TYPE_ERROR : OS_LOG_TYPE_DEFAULT, "%{public}s", out);
}

static void log_callback(void *avcl, int level, const char *fmt, va_list vl) {
    if (level > AV_LOG_WARNING) return;
    char line[1024];
    int print_prefix = 1;
    av_log_format_line2(avcl, level, fmt, vl, line, sizeof line, &print_prefix);
    emit(level, line);
}

static void log_setup(void) {
    ffmpeg_log = os_log_create("com.gethyperdrop.app", "ffmpeg");
    av_log_set_level(AV_LOG_WARNING);
    av_log_set_callback(log_callback);
}

void hdff_log_install(void) { pthread_once(&log_once, log_setup); }

void hdff_log_line(int level, const char *text) {
    hdff_log_install();
    if (level > AV_LOG_WARNING || !text) return;
    emit(level, text);
}

// MARK: Inputs

int hdff_input_allowed(const char *input) {
    static const char loopback[] = "http://127.0.0.1:";
    if (!input || !input[0]) return 0;
    if (input[0] == '/') return 1;
    if (strncmp(input, loopback, sizeof loopback - 1) != 0) return 0;
    const char *p = input + sizeof loopback - 1;
    long port = 0;
    int digits = 0;
    while (*p >= '0' && *p <= '9' && digits < 6) {
        port = port * 10 + (*p++ - '0');
        digits++;
    }
    return digits > 0 && port >= 1 && port <= 65535 && *p == '/';
}

void hdff_input_options(const char *input, AVDictionary **opts) {
    av_dict_set(opts, "protocol_whitelist", input[0] == '/' ? "file" : "http,tcp", 0);
}

int hdff_video_stream(const AVFormatContext *fmt) {
    for (unsigned i = 0; i < fmt->nb_streams; i++) {
        const AVStream *st = fmt->streams[i];
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
            return (int)i;
    }
    return AVERROR_STREAM_NOT_FOUND;
}

// MARK: The probe

static int probe_interrupted(void *opaque) { return av_gettime_relative() > *(const int64_t *)opaque; }

static void copy_name(char *dst, size_t size, const char *src) {
    if (src) av_strlcpy(dst, src, size);
    else dst[0] = '\0';
}

int hdff_probe(const char *input, double seconds, hdff_probe_t *out) {
    hdff_log_install();
    memset(out, 0, sizeof *out);
    out->profile = AV_PROFILE_UNKNOWN;
    if (!hdff_input_allowed(input)) return AVERROR(EINVAL);
    AVFormatContext *fmt = avformat_alloc_context();
    if (!fmt) return AVERROR(ENOMEM);
    int64_t deadline = av_gettime_relative() + (int64_t)(seconds * AV_TIME_BASE);
    fmt->interrupt_callback = (AVIOInterruptCB){probe_interrupted, &deadline};
    AVDictionary *opts = NULL;
    hdff_input_options(input, &opts);
    int ret = avformat_open_input(&fmt, input, NULL, &opts);
    av_dict_free(&opts);
    if (ret < 0) return ret;
    if ((ret = avformat_find_stream_info(fmt, NULL)) < 0) goto done;
    copy_name(out->container, sizeof out->container, fmt->iformat->name);
    out->untimed = (fmt->iformat->flags & AVFMT_NOTIMESTAMPS) != 0;
    if (fmt->duration != AV_NOPTS_VALUE && fmt->duration > 0) out->duration = fmt->duration / (double)AV_TIME_BASE;
    if (fmt->start_time != AV_NOPTS_VALUE) out->start_time = fmt->start_time / (double)AV_TIME_BASE;
    int video = hdff_video_stream(fmt);
    if (video >= 0) {
        const AVStream *st = fmt->streams[video];
        const AVCodecParameters *par = st->codecpar;
        copy_name(out->video_codec, sizeof out->video_codec, avcodec_get_name(par->codec_id));
        out->profile = par->profile;
        copy_name(out->pix_fmt, sizeof out->pix_fmt, av_get_pix_fmt_name(par->format));
        out->width = par->width;
        out->height = par->height;
        AVRational rate = st->avg_frame_rate.num > 0 ? st->avg_frame_rate : st->r_frame_rate;
        if (rate.num > 0 && rate.den > 0) out->frame_rate = av_q2d(rate);
        if (st->start_time != AV_NOPTS_VALUE) out->start_time = st->start_time * av_q2d(st->time_base);
        if (out->duration == 0 && st->duration != AV_NOPTS_VALUE && st->duration > 0)
            out->duration = st->duration * av_q2d(st->time_base);
        out->hardware_decodable = hdff_hardware_decodes(par);
    }
    for (unsigned i = 0; i < fmt->nb_streams; i++) {
        if (fmt->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) continue;
        copy_name(out->audio_codec, sizeof out->audio_codec, avcodec_get_name(fmt->streams[i]->codecpar->codec_id));
        break;
    }
    ret = 0;
done:
    avformat_close_input(&fmt);
    return ret;
}

// MARK: The copy rule

int hdff_video_plan(const char *codec, int profile, const char *pix_fmt) {
    if (!codec) return HDFF_PLAN_ENCODE;
    if (strcmp(codec, "hevc") == 0) {
        int main = profile == AV_PROFILE_HEVC_MAIN || profile == AV_PROFILE_HEVC_MAIN_10;
        int picture = pix_fmt && (strcmp(pix_fmt, "yuv420p") == 0 || strcmp(pix_fmt, "yuv420p10le") == 0);
        return main && picture ? HDFF_PLAN_COPY_FMP4 : HDFF_PLAN_ENCODE;
    }
    if (strcmp(codec, "h264") == 0 && pix_fmt && (strcmp(pix_fmt, "yuv420p") == 0 || strcmp(pix_fmt, "yuvj420p") == 0))
        return HDFF_PLAN_COPY_TS;
    return HDFF_PLAN_ENCODE;
}

// MARK: The decode self-test

// Stops the decode at its first frame, recording which decoder made it.
static int first_frame(void *opaque, AVFrame *frame) {
    *(int *)opaque = frame->format == AV_PIX_FMT_VIDEOTOOLBOX ? HDFF_DECODED_HARDWARE : HDFF_DECODED_SOFTWARE;
    return AVERROR_EXIT;
}

int hdff_selftest_decode(const char *path) {
    hdff_log_install();
    AVFormatContext *fmt = NULL;
    AVPacket *pkt = av_packet_alloc();
    AVFrame *frame = av_frame_alloc();
    hdff_decoder dec = {0};
    int answer = -1;
    int ret = pkt && frame ? 0 : AVERROR(ENOMEM);
    if (ret >= 0) ret = avformat_open_input(&fmt, path, NULL, NULL);
    if (ret >= 0) ret = avformat_find_stream_info(fmt, NULL);
    int index = ret >= 0 ? hdff_video_stream(fmt) : ret;
    if (index < 0) ret = index;
    if (ret >= 0) ret = hdff_decoder_open(&dec, fmt->streams[index]->codecpar, fmt->streams[index]->time_base);
    while (ret >= 0 && answer < 0) {
        int read = av_read_frame(fmt, pkt);
        if (read == AVERROR_EOF) {
            ret = hdff_decoder_decode(&dec, NULL, frame, first_frame, &answer);
            if (ret >= 0 && answer < 0) ret = AVERROR_EOF;
            break;
        }
        if (read < 0) {
            ret = read;
            break;
        }
        if (pkt->stream_index == index) ret = hdff_decoder_decode(&dec, pkt, frame, first_frame, &answer);
        av_packet_unref(pkt);
    }
    hdff_decoder_close(&dec);
    av_frame_free(&frame);
    av_packet_free(&pkt);
    avformat_close_input(&fmt);
    return answer >= 0 ? answer : (ret < 0 ? ret : AVERROR_BUG);
}
