// The live conversion: see hdff_convert_start in hdff.h. One thread per job
// reads the input (paced at read_rate), copies or decodes the picture, and
// writes an HLS EVENT playlist through libavformat's hls muxer, with the
// numbers of the Mac's segmented `playable` (mediaext/jobs/args.go).
#include "hdff_convert.h"

#include <math.h>
#include <string.h>

#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/avstring.h>
#include <libavutil/channel_layout.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/time.h>

// args.go's playableAudioBitrate.
#define AUDIO_BITRATE 160000
// What a paced read may run ahead of the clock, ffmpeg's readrate_initial_burst.
#define READ_BURST_US 500000
// The longest a paced read sleeps before it looks for a cancel again.
#define PACE_WAKE_US 100000

static int cancelled(const hdff_conv *c) { return atomic_load(&c->job->cancelled); }

static int interrupted(void *opaque) { return atomic_load(&((hdff_job *)opaque)->cancelled); }

int hdff_fail(hdff_conv *c, int code, const char *reason) {
    if (!c->reason[0]) {
        c->code = code;
        av_strlcpy(c->reason, reason, sizeof c->reason);
    }
    return code < 0 ? code : AVERROR_EXTERNAL;
}

// MARK: Muxing

static int write_packet(hdff_conv *c, AVPacket *pkt, AVRational tb) {
    AVStream *st = c->out->streams[pkt->stream_index];
    if (st == c->vout && pkt->pts != AV_NOPTS_VALUE) {
        double end = c->grid + (pkt->pts + pkt->duration) * av_q2d(tb);
        if (end > c->written) c->written = end;
    }
    av_packet_rescale_ts(pkt, tb, st->time_base);
    int ret = av_interleaved_write_frame(c->out, pkt);
    if (ret < 0) return hdff_fail(c, ret, "The converted video could not be written.");
    if (c->job->cb.progress && c->written >= c->reported + SEGMENT_SECONDS) {
        c->reported = c->written;
        c->job->cb.progress(c->job->cb.context, c->written);
    }
    return 0;
}

// Hands a packet whose timestamps are in `tb` to the muxer, or keeps it
// until the header is written.
static int mux(hdff_conv *c, AVPacket *pkt, AVRational tb) {
    if (c->header) return write_packet(c, pkt, tb);
    if (c->npending == PENDING_MAX) return hdff_fail(c, AVERROR(ENOSPC), "The video's first picture never came.");
    AVPacket *kept = av_packet_alloc();
    if (!kept) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    av_packet_move_ref(kept, pkt);
    av_packet_rescale_ts(kept, tb, AV_TIME_BASE_Q);
    c->pending[c->npending++] = kept;
    return 0;
}

int hdff_write_header(hdff_conv *c) {
    const char *playlist = c->job->playlist;
    const char *slash = strrchr(playlist, '/');
    int dirlen = (int)(slash - playlist);
    int fmp4 = c->plan == HDFF_PLAN_COPY_FMP4;
    char segments[2048], number[32];
    snprintf(segments, sizeof segments, "%.*s/seg%%05d.%s", dirlen, playlist, fmp4 ? "m4s" : "ts");
    AVDictionary *opts = NULL;
    av_dict_set(&opts, "hls_time", "2", 0);
    av_dict_set(&opts, "hls_list_size", "0", 0);
    av_dict_set(&opts, "hls_playlist_type", "event", 0);
    av_dict_set(&opts, "hls_flags", "temp_file+independent_segments", 0);
    av_dict_set(&opts, "hls_segment_type", fmp4 ? "fmp4" : "mpegts", 0);
    if (fmp4) av_dict_set(&opts, "hls_fmp4_init_filename", "init.mp4", 0);
    av_dict_set(&opts, "hls_segment_filename", segments, 0);
    if (c->grid > 0) {
        snprintf(number, sizeof number, "%d", c->grid / SEGMENT_SECONDS);
        av_dict_set(&opts, "start_number", number, 0);
        c->out->output_ts_offset = (int64_t)c->grid * AV_TIME_BASE;
    }
    int ret = avformat_write_header(c->out, &opts);
    av_dict_free(&opts);
    if (ret < 0) return hdff_fail(c, ret, "The playlist could not be started.");
    c->header = 1;
    for (int i = 0; i < c->npending && ret >= 0; i++) ret = write_packet(c, c->pending[i], AV_TIME_BASE_Q);
    for (int i = 0; i < c->npending; i++) av_packet_free(&c->pending[i]);
    c->npending = 0;
    return ret;
}

int hdff_encode(hdff_conv *c, AVCodecContext *enc, AVStream *st, const AVFrame *frame) {
    int ret = avcodec_send_frame(enc, frame);
    if (ret < 0 && ret != AVERROR_EOF) return hdff_fail(c, ret, "The video could not be encoded.");
    for (;;) {
        ret = avcodec_receive_packet(enc, c->opkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return 0;
        if (ret < 0) return hdff_fail(c, ret, "The video could not be encoded.");
        c->opkt->stream_index = st->index;
        ret = mux(c, c->opkt, enc->time_base);
        av_packet_unref(c->opkt);
        if (ret < 0) return ret;
    }
}

int hdff_add_filter(AVFilterGraph *graph, AVFilterContext **last, const char *name, const char *args) {
    AVFilterContext *f = NULL;
    int ret = avfilter_graph_create_filter(&f, avfilter_get_by_name(name), name, args, NULL, graph);
    if (ret >= 0) ret = avfilter_link(*last, 0, f, 0);
    if (ret >= 0) *last = f;
    return ret;
}

// MARK: The sound

// The sound's encode: decoded, resampled to 16-bit at the source's rate (at
// most 48 kHz), mono or stereo, in aac_at's frame size, and encoded by
// aac_at at the Mac's playable bitrate.
static int open_sound(hdff_conv *c) {
    AVStream *st = c->in->streams[c->ain];
    const AVCodec *dc = avcodec_find_decoder(st->codecpar->codec_id);
    const AVCodec *ec = avcodec_find_encoder_by_name("aac_at");
    if (!dc || !ec) return hdff_fail(c, AVERROR_DECODER_NOT_FOUND, "The video's sound cannot be converted.");
    c->adec = avcodec_alloc_context3(dc);
    c->aenc = avcodec_alloc_context3(ec);
    if (!c->adec || !c->aenc) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    int ret = avcodec_parameters_to_context(c->adec, st->codecpar);
    c->adec->pkt_timebase = st->time_base;
    if (ret >= 0) ret = avcodec_open2(c->adec, dc, NULL);
    if (ret < 0 || c->adec->sample_rate <= 0 || c->adec->ch_layout.nb_channels <= 0)
        return hdff_fail(c, ret < 0 ? ret : AVERROR_INVALIDDATA, "The video's sound cannot be decoded.");
    AVCodecContext *enc = c->aenc;
    enc->sample_fmt = AV_SAMPLE_FMT_S16;
    enc->sample_rate = FFMIN(c->adec->sample_rate, 48000);
    av_channel_layout_default(&enc->ch_layout, c->adec->ch_layout.nb_channels == 1 ? 1 : 2);
    enc->bit_rate = AUDIO_BITRATE;
    enc->time_base = (AVRational){1, enc->sample_rate};
    if (c->out->oformat->flags & AVFMT_GLOBALHEADER) enc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    if ((ret = avcodec_open2(enc, ec, NULL)) < 0) return hdff_fail(c, ret, "The AAC encoder could not start.");

    char in_layout[128], out_layout[128], args[512], rate[16];
    av_channel_layout_describe(&c->adec->ch_layout, in_layout, sizeof in_layout);
    av_channel_layout_describe(&enc->ch_layout, out_layout, sizeof out_layout);
    snprintf(args, sizeof args, "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=%s", st->time_base.num,
             st->time_base.den, c->adec->sample_rate, av_get_sample_fmt_name(c->adec->sample_fmt), in_layout);
    snprintf(rate, sizeof rate, "%d", enc->sample_rate);
    AVFilterGraph *graph = c->agraph = avfilter_graph_alloc();
    if (!graph) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    ret = avfilter_graph_create_filter(&c->asrc, avfilter_get_by_name("abuffer"), "in", args, NULL, graph);
    AVFilterContext *last = c->asrc;
    if (ret >= 0) ret = hdff_add_filter(graph, &last, "aresample", NULL);
    if (ret >= 0) {
        c->asink = avfilter_graph_alloc_filter(graph, avfilter_get_by_name("abuffersink"), "out");
        ret = c->asink ? 0 : AVERROR(ENOMEM);
    }
    if (ret >= 0) ret = av_opt_set(c->asink, "sample_formats", "s16", AV_OPT_SEARCH_CHILDREN);
    if (ret >= 0) ret = av_opt_set(c->asink, "samplerates", rate, AV_OPT_SEARCH_CHILDREN);
    if (ret >= 0) ret = av_opt_set(c->asink, "channel_layouts", out_layout, AV_OPT_SEARCH_CHILDREN);
    if (ret >= 0) ret = avfilter_init_str(c->asink, NULL);
    if (ret >= 0) ret = avfilter_link(last, 0, c->asink, 0);
    if (ret >= 0) ret = avfilter_graph_config(graph, NULL);
    if (ret < 0) return hdff_fail(c, ret, "The video's sound cannot be resampled.");
    if (enc->frame_size > 0 && !(ec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
        av_buffersink_set_frame_size(c->asink, enc->frame_size);
    if ((ret = avcodec_parameters_from_context(c->aout->codecpar, enc)) < 0) return hdff_fail(c, ret, "Out of memory.");
    c->aout->time_base = enc->time_base;
    return 0;
}

static int pull_sound(hdff_conv *c) {
    AVRational tb = av_buffersink_get_time_base(c->asink);
    for (;;) {
        int ret = av_buffersink_get_frame(c->asink, c->filtered);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return 0;
        if (ret < 0) return hdff_fail(c, ret, "The video's sound cannot be resampled.");
        if (c->filtered->pts != AV_NOPTS_VALUE) c->filtered->pts = av_rescale_q(c->filtered->pts, tb, c->aenc->time_base);
        ret = hdff_encode(c, c->aenc, c->aout, c->filtered);
        av_frame_unref(c->filtered);
        if (ret < 0) return ret;
    }
}

// Decodes a sound packet (NULL drains) and filters and encodes its frames;
// frames before the start are dropped.
static int decode_sound(hdff_conv *c, const AVPacket *pkt) {
    AVStream *st = c->in->streams[c->ain];
    int ret = avcodec_send_packet(c->adec, pkt);
    if (ret == AVERROR_INVALIDDATA) return 0;
    if (ret < 0 && ret != AVERROR_EOF) return hdff_fail(c, ret, "The video's sound cannot be decoded.");
    for (;;) {
        ret = avcodec_receive_frame(c->adec, c->frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;
        if (ret == AVERROR_INVALIDDATA) continue;
        if (ret < 0) return hdff_fail(c, ret, "The video's sound cannot be decoded.");
        int64_t ts = c->frame->best_effort_timestamp;
        if (ts != AV_NOPTS_VALUE) ts -= av_rescale_q(c->base, AV_TIME_BASE_Q, st->time_base);
        if (ts != AV_NOPTS_VALUE && ts < 0) {
            av_frame_unref(c->frame);
            continue;
        }
        c->frame->pts = ts;
        ret = av_buffersrc_add_frame(c->asrc, c->frame);
        av_frame_unref(c->frame);
        if (ret < 0) return hdff_fail(c, ret, "The video's sound cannot be resampled.");
        if ((ret = pull_sound(c)) < 0) return ret;
    }
    if (!pkt) {
        if ((ret = av_buffersrc_add_frame(c->asrc, NULL)) < 0) return hdff_fail(c, ret, "The video's sound cannot be resampled.");
        if ((ret = pull_sound(c)) < 0) return ret;
        return hdff_encode(c, c->aenc, c->aout, NULL);
    }
    return 0;
}

// MARK: The run

// A decode timestamp for a copied picture packet that has only a
// presentation one (Matroska stores no other): the smallest of the last
// video_delay + 1 presentation times, as libavformat's muxer derives it.
static int64_t derive_dts(hdff_conv *c, const AVPacket *pkt, int delay) {
    int64_t *buf = c->pts_buffer;
    buf[0] = pkt->pts;
    for (int i = 1; i <= delay && buf[i] == AV_NOPTS_VALUE; i++) buf[i] = pkt->pts + (i - delay - 1) * pkt->duration;
    for (int i = 0; i < delay && buf[i] > buf[i + 1]; i++) FFSWAP(int64_t, buf[i], buf[i + 1]);
    return buf[0];
}

// A copied packet, timed from the start; a copied picture starts at its
// first keyframe.
static int copy_packet(hdff_conv *c, AVPacket *pkt, AVStream *out) {
    AVStream *st = c->in->streams[pkt->stream_index];
    if (out == c->vout && !c->copy_started) {
        if (!(pkt->flags & AV_PKT_FLAG_KEY)) return 0;
        c->copy_started = 1;
    }
    int64_t base = av_rescale_q(c->base, AV_TIME_BASE_Q, st->time_base);
    if (pkt->pts != AV_NOPTS_VALUE) pkt->pts -= base;
    if (pkt->dts != AV_NOPTS_VALUE) pkt->dts -= base;
    int delay = st->codecpar->video_delay;
    if (out == c->vout && pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY)
        pkt->dts = derive_dts(c, pkt, delay);
    pkt->stream_index = out->index;
    pkt->pos = -1;
    return mux(c, pkt, st->time_base);
}

// Holds the read back to read_rate times real time, as ffmpeg's -readrate
// does: the media read so far may run READ_BURST_US ahead of the clock. It
// sleeps the wall time the read is ahead by, waking at least every
// PACE_WAKE_US to see a cancel.
static void pace(hdff_conv *c, const AVPacket *pkt) {
    double rate = c->job->read_rate;
    int64_t ts = pkt->dts != AV_NOPTS_VALUE ? pkt->dts : pkt->pts;
    if (rate <= 0 || ts == AV_NOPTS_VALUE) return;
    int64_t us = av_rescale_q(ts, c->in->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q);
    if (!c->paced) {
        c->paced = 1;
        c->wall_start = av_gettime_relative();
        c->first_us = us;
        return;
    }
    while (!cancelled(c)) {
        int64_t allowed = (int64_t)((av_gettime_relative() - c->wall_start) * rate) + READ_BURST_US;
        int64_t ahead = us - c->first_us - allowed;
        if (ahead <= 0) return;
        int64_t sleep_us = (int64_t)(ahead / rate) + 1;
        av_usleep((unsigned)(sleep_us < PACE_WAKE_US ? sleep_us : PACE_WAKE_US));
    }
}

static int open_input(hdff_conv *c) {
    hdff_job *job = c->job;
    if (!(c->in = avformat_alloc_context())) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    c->in->interrupt_callback = (AVIOInterruptCB){interrupted, job};
    AVDictionary *opts = NULL;
    hdff_input_options(job->input, &opts);
    int ret = avformat_open_input(&c->in, job->input, NULL, &opts);
    av_dict_free(&opts);
    if (ret < 0) return hdff_fail(c, ret, "The video could not be opened.");
    if ((ret = avformat_find_stream_info(c->in, NULL)) < 0) return hdff_fail(c, ret, "The video's streams could not be read.");
    if ((c->vin = hdff_video_stream(c->in)) < 0) return hdff_fail(c, c->vin, "The file holds no video.");
    for (unsigned i = 0; i < c->in->nb_streams && c->ain < 0; i++)
        if (c->in->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) c->ain = (int)i;
    for (unsigned i = 0; i < c->in->nb_streams; i++)
        if ((int)i != c->vin && (int)i != c->ain) c->in->streams[i]->discard = AVDISCARD_ALL;
    const AVCodecParameters *par = c->in->streams[c->vin]->codecpar;
    const char *pix_fmt = av_get_pix_fmt_name(par->format);
    // A bare stream (a recorder's .264 or .265 export) stores no times, which
    // a copied packet needs, so its picture is encoded.
    c->untimed = (c->in->iformat->flags & AVFMT_NOTIMESTAMPS) != 0;
    c->plan = c->untimed
        ? HDFF_PLAN_ENCODE
        : hdff_video_plan(avcodec_get_name(par->codec_id), par->profile, pix_fmt ? pix_fmt : "");
    double start = job->start_seconds > 0 ? job->start_seconds : 0;
    if (c->in->duration > 0 && start >= c->in->duration / (double)AV_TIME_BASE)
        return hdff_fail(c, AVERROR(EINVAL), "The preview cannot start past the end of the video.");
    c->grid = SEGMENT_SECONDS * (int)floor(start / SEGMENT_SECONDS);
    c->base = (c->in->start_time != AV_NOPTS_VALUE ? c->in->start_time : 0) + (int64_t)c->grid * AV_TIME_BASE;
    if (c->grid > 0 && !c->untimed && avformat_seek_file(c->in, -1, INT64_MIN, c->base, c->base, 0) < 0)
        hdff_log_line(HDFF_LOG_WARNING, "live conversion: the seek to the start failed; reading from the beginning");
    return 0;
}

static int open_output(hdff_conv *c) {
    int ret = avformat_alloc_output_context2(&c->out, NULL, "hls", c->job->playlist);
    if (ret < 0) return hdff_fail(c, ret, "The playlist could not be made.");
    // ffmpeg's command line muxes with -muxdelay 0.7 unless told otherwise, so
    // the Mac's MPEG-TS segments carry its 1.4 s delay; these carry the same.
    c->out->max_delay = 700000;
    if (!(c->vout = avformat_new_stream(c->out, NULL))) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    AVStream *vst = c->in->streams[c->vin];
    if (c->plan == HDFF_PLAN_ENCODE) {
        if ((ret = hdff_picture_prepare(c)) < 0) return ret;
    } else {
        if ((ret = avcodec_parameters_copy(c->vout->codecpar, vst->codecpar)) < 0) return hdff_fail(c, ret, "Out of memory.");
        c->vout->codecpar->codec_tag = c->plan == HDFF_PLAN_COPY_FMP4 ? MKTAG('h', 'v', 'c', '1') : 0;
        c->vout->time_base = vst->time_base;
    }
    if (c->ain < 0) return 0;
    if (!(c->aout = avformat_new_stream(c->out, NULL))) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    AVStream *ast = c->in->streams[c->ain];
    if (ast->codecpar->codec_id != AV_CODEC_ID_AAC) return open_sound(c);
    if ((ret = avcodec_parameters_copy(c->aout->codecpar, ast->codecpar)) < 0) return hdff_fail(c, ret, "Out of memory.");
    c->aout->codecpar->codec_tag = 0;
    c->aout->time_base = ast->time_base;
    return 0;
}

static int handle_packet(hdff_conv *c, AVPacket *pkt) {
    if (pkt->stream_index == c->vin)
        return c->plan == HDFF_PLAN_ENCODE ? hdff_picture_decode(c, pkt) : copy_packet(c, pkt, c->vout);
    if (pkt->stream_index == c->ain) return c->adec ? decode_sound(c, pkt) : copy_packet(c, pkt, c->aout);
    return 0;
}

static int finish(hdff_conv *c) {
    int ret = 0;
    if (c->plan == HDFF_PLAN_ENCODE && (ret = hdff_picture_finish(c)) < 0) return ret;
    if (c->adec && (ret = decode_sound(c, NULL)) < 0) return ret;
    if (!c->header && (ret = hdff_write_header(c)) < 0) return ret;
    if ((ret = av_write_trailer(c->out)) < 0) return hdff_fail(c, ret, "The playlist could not be finished.");
    c->trailer = 1;
    if (c->job->cb.progress) c->job->cb.progress(c->job->cb.context, c->written);
    return 0;
}

static int run(hdff_conv *c) {
    int ret;
    c->pkt = av_packet_alloc();
    c->opkt = av_packet_alloc();
    c->frame = av_frame_alloc();
    c->filtered = av_frame_alloc();
    if (!c->pkt || !c->opkt || !c->frame || !c->filtered) return hdff_fail(c, AVERROR(ENOMEM), "Out of memory.");
    if ((ret = open_input(c)) < 0 || (ret = open_output(c)) < 0) return ret;
    // A copy's streams are known now; an encode's header waits for its encoder.
    if (c->plan != HDFF_PLAN_ENCODE && (ret = hdff_write_header(c)) < 0) return ret;
    while (!cancelled(c)) {
        ret = av_read_frame(c->in, c->pkt);
        if (ret == AVERROR_EOF) return finish(c);
        if (ret < 0) return cancelled(c) ? ret : hdff_fail(c, ret, "The video could not be read.");
        pace(c, c->pkt);
        ret = handle_packet(c, c->pkt);
        av_packet_unref(c->pkt);
        if (ret < 0) return ret;
    }
    return AVERROR_EXIT;
}

static void release(hdff_conv *c) {
    // The trailer also closes the segment and playlist files a stopped run holds.
    if (c->header && !c->trailer) av_write_trailer(c->out);
    avformat_free_context(c->out);
    for (int i = 0; i < c->npending; i++) av_packet_free(&c->pending[i]);
    hdff_decoder_close(&c->dec);
    avcodec_free_context(&c->venc);
    avcodec_free_context(&c->adec);
    avcodec_free_context(&c->aenc);
    avfilter_graph_free(&c->vgraph);
    avfilter_graph_free(&c->agraph);
    av_frame_free(&c->frame);
    av_frame_free(&c->filtered);
    av_packet_free(&c->pkt);
    av_packet_free(&c->opkt);
    avformat_close_input(&c->in);
}

static void *job_main(void *arg) {
    hdff_job *job = arg;
    hdff_conv *c = av_mallocz(sizeof *c);
    if (!c) {
        job->result = HDFF_FAILED;
        if (job->cb.failed) job->cb.failed(job->cb.context, AVERROR(ENOMEM), "Out of memory.");
        return NULL;
    }
    c->job = job;
    c->vin = c->ain = -1;
    for (int i = 0; i <= MAX_REORDER_DELAY; i++) c->pts_buffer[i] = AV_NOPTS_VALUE;
    int ret = run(c);
    release(c);
    if (atomic_load(&job->cancelled)) {
        job->result = HDFF_CANCELLED;
    } else if (ret < 0) {
        job->result = HDFF_FAILED;
        if (job->cb.failed) job->cb.failed(job->cb.context, c->code ? c->code : ret, c->reason[0] ? c->reason : "The conversion failed.");
    } else {
        job->result = HDFF_DONE;
    }
    av_free(c);
    return NULL;
}

hdff_job *hdff_convert_start(const hdff_options *opt, hdff_callbacks cb) {
    hdff_log_install();
    if (!opt || !hdff_input_allowed(opt->input) || !opt->playlist || opt->playlist[0] != '/' ||
        strchr(opt->playlist, '%') || opt->max_height <= 0)
        return NULL;
    hdff_job *job = av_mallocz(sizeof *job);
    if (!job) return NULL;
    job->input = av_strdup(opt->input);
    job->playlist = av_strdup(opt->playlist);
    job->start_seconds = opt->start_seconds;
    job->max_height = opt->max_height;
    job->allow_software_encoder = opt->allow_software_encoder;
    job->read_rate = opt->read_rate;
    job->cb = cb;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, 2 << 20);
    int started = job->input && job->playlist && pthread_create(&job->thread, &attr, job_main, job) == 0;
    pthread_attr_destroy(&attr);
    if (!started) {
        hdff_free(job);
        return NULL;
    }
    return job;
}

void hdff_cancel(hdff_job *job) {
    if (job) atomic_store(&job->cancelled, 1);
}

int hdff_wait(hdff_job *job) {
    if (!job->joined) {
        pthread_join(job->thread, NULL);
        job->joined = 1;
    }
    return job->result;
}

void hdff_free(hdff_job *job) {
    if (!job) return;
    av_free(job->input);
    av_free(job->playlist);
    av_free(job);
}
