/*
 * ffw - the video engine of 20mb.net
 *
 * A small, single-threaded transcoder built on the FFmpeg libraries. It is
 * compiled to WebAssembly and driven from JavaScript: every job runs in a
 * fresh instance, and several instances run in parallel Web Workers.
 *
 * Why not the ffmpeg command line tool? Since FFmpeg 6.0 it requires threads,
 * and threads in a browser require SharedArrayBuffer, which requires the page
 * to be cross-origin isolated (COOP/COEP headers). Cross-origin isolation
 * blocks third-party ad iframes. Running independent single-threaded
 * instances side by side gives the same multi-core speed without it.
 *
 * Commands
 *   ffw probe <input> <output.json> [scan]
 *       Describe a file as JSON (format, streams, rotation, HDR, keyframes...).
 *       With "scan", every packet is read to get exact durations and sizes.
 *
 *   ffw run [options]
 *       Decode -> (constant frame rate selection) -> filter -> encode -> mux.
 *       -i PATH            input file            -fin FMT / -iopt K=V  input format/options
 *       -ss SEC            seek before decoding  -vsi N / -asi N       stream index (-1 = none)
 *       -cfr N/D           output frame rate; frames are picked on a fixed grid
 *       -slots A:B         grid slots [A, B) to output (B = -1: until the end)
 *       -vf GRAPH / -af GRAPH                    filter graphs
 *       -c:v ENC / -c:a ENC                      encoders ("none" disables)
 *       -vopt K=V / -aopt K=V                    encoder options
 *       -pass 1|2 -passlog PATH                  two-pass video encoding
 *       -vframes N                               maximum video frames
 *       -f FMT -fopt K=V -meta K=V -copymeta -o PATH   output
 *       -result PATH                             write a JSON summary
 *       -progress MS                             progress interval
 *
 *   ffw mux [options]
 *       Stream copy from one or more inputs into one output.
 *       [-fin FMT] [-iopt K=V] -i PATH ...  -map IN:v|IN:a|IN:INDEX ...
 *       -f FMT -fopt K=V -meta K=V -copymeta IN -o PATH
 *       -vtb N/D       time base for video streams (AVI: 1/fps)
 *
 * Copyright (c) 2026 20mb.net
 * SPDX-License-Identifier: MIT
 */

#include <inttypes.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <libavcodec/avcodec.h>
#include <libavfilter/avfilter.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavformat/avformat.h>
#include <libavutil/avstring.h>
#include <libavutil/bprint.h>
#include <libavutil/channel_layout.h>
#include <libavutil/crc.h>
#include <libavutil/display.h>
#include <libavutil/mathematics.h>
#include <libavutil/opt.h>
#include <libavutil/parseutils.h>
#include <libavutil/pixdesc.h>
#include <libavutil/time.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>

EM_JS(void, js_progress, (double in_t, double out_t, double frames, double bytes), {
    if (Module["onProgress"]) Module["onProgress"](in_t, out_t, frames, bytes);
});
EM_JS(void, js_log, (int level, const char *msg), {
    if (Module["onLog"]) Module["onLog"](level, UTF8ToString(msg));
});
static double now_ms(void) { return emscripten_get_now(); }
#else
static void js_progress(double in_t, double out_t, double frames, double bytes)
{
    fprintf(stderr, "[progress] in=%.3f out=%.3f frames=%.0f bytes=%.0f\n", in_t, out_t, frames, bytes);
}
static void js_log(int level, const char *msg) { (void)level; fputs(msg, stderr); }
static double now_ms(void) { return av_gettime_relative() / 1000.0; }
#endif

/* ------------------------------------------------------------------ logging */

static int g_log_level = AV_LOG_WARNING;

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

static void msg(int level, const char *fmt, ...)
{
    va_list vl;
    va_start(vl, fmt);
    av_vlog(NULL, level, fmt, vl);
    va_end(vl);
}

static int fail(int err, const char *what)
{
    msg(AV_LOG_ERROR, "%s: %s\n", what, av_err2str(err));
    return err;
}

static int parse_kv(AVDictionary **d, const char *kv)
{
    const char *eq = strchr(kv, '=');
    char *key;
    if (!eq || eq == kv) {
        msg(AV_LOG_ERROR, "expected KEY=VALUE, got '%s'\n", kv);
        return AVERROR(EINVAL);
    }
    key = av_strndup(kv, eq - kv);
    if (!key)
        return AVERROR(ENOMEM);
    return av_dict_set(d, key, eq + 1, AV_DICT_DONT_STRDUP_KEY);
}

static int read_text_file(const char *path, char **out)
{
    FILE *f = fopen(path, "rb");
    long n;
    char *buf;
    if (!f)
        return AVERROR(errno);
    fseek(f, 0, SEEK_END);
    n = ftell(f);
    fseek(f, 0, SEEK_SET);
    buf = av_malloc(n + 1);
    if (!buf) {
        fclose(f);
        return AVERROR(ENOMEM);
    }
    if (n > 0 && fread(buf, 1, n, f) != (size_t)n) {
        fclose(f);
        av_free(buf);
        return AVERROR(EIO);
    }
    buf[n] = 0;
    fclose(f);
    *out = buf;
    return 0;
}

static int write_text_file(const char *path, const char *text)
{
    FILE *f = fopen(path, "wb");
    size_t n = strlen(text);
    if (!f)
        return AVERROR(errno);
    if (fwrite(text, 1, n, f) != n) {
        fclose(f);
        return AVERROR(EIO);
    }
    fclose(f);
    return 0;
}

/* --------------------------------------------------------------------- json */

static void json_escape(AVBPrint *bp, const char *s)
{
    av_bprint_chars(bp, '"', 1);
    for (; s && *s; s++) {
        unsigned char ch = *s;
        switch (ch) {
        case '"':  av_bprintf(bp, "\\\""); break;
        case '\\': av_bprintf(bp, "\\\\"); break;
        case '\n': av_bprintf(bp, "\\n");  break;
        case '\r': av_bprintf(bp, "\\r");  break;
        case '\t': av_bprintf(bp, "\\t");  break;
        default:
            if (ch < 0x20) av_bprintf(bp, "\\u%04x", ch);
            else           av_bprint_chars(bp, ch, 1);
        }
    }
    av_bprint_chars(bp, '"', 1);
}

static void json_key(AVBPrint *bp, int *first, const char *key)
{
    if (!*first)
        av_bprint_chars(bp, ',', 1);
    *first = 0;
    json_escape(bp, key);
    av_bprint_chars(bp, ':', 1);
}

static void json_str(AVBPrint *bp, int *first, const char *key, const char *val)
{
    json_key(bp, first, key);
    if (val) json_escape(bp, val);
    else     av_bprintf(bp, "null");
}

static void json_int(AVBPrint *bp, int *first, const char *key, int64_t val)
{
    json_key(bp, first, key);
    av_bprintf(bp, "%" PRId64, val);
}

static void json_num(AVBPrint *bp, int *first, const char *key, double val)
{
    json_key(bp, first, key);
    if (isfinite(val)) av_bprintf(bp, "%.6f", val);
    else               av_bprintf(bp, "null");
}

static void json_q(AVBPrint *bp, int *first, const char *key, AVRational q)
{
    json_key(bp, first, key);
    av_bprintf(bp, "[%d,%d]", q.num, q.den);
}

static void json_tags(AVBPrint *bp, int *first, const char *key, const AVDictionary *d)
{
    const AVDictionaryEntry *t = NULL;
    int f2 = 1;
    json_key(bp, first, key);
    av_bprint_chars(bp, '{', 1);
    while ((t = av_dict_iterate(d, t)))
        json_str(bp, &f2, t->key, t->value);
    av_bprint_chars(bp, '}', 1);
}

/* ------------------------------------------------------------------- shared */

static double stream_rotation(const AVStream *st)
{
    const AVPacketSideData *sd = av_packet_side_data_get(st->codecpar->coded_side_data,
                                                         st->codecpar->nb_coded_side_data,
                                                         AV_PKT_DATA_DISPLAYMATRIX);
    double r;
    if (!sd || sd->size < 9 * 4)
        return 0;
    r = -av_display_rotation_get((const int32_t *)sd->data);
    if (isnan(r))
        return 0;
    r -= 360 * floor(r / 360 + 0.9 / 360);
    return r;
}

static int stream_has_side_data(const AVStream *st, enum AVPacketSideDataType type)
{
    return !!av_packet_side_data_get(st->codecpar->coded_side_data,
                                     st->codecpar->nb_coded_side_data, type);
}

static int open_input(AVFormatContext **pic, const char *path, const char *fmt, AVDictionary *opts_in)
{
    const AVInputFormat *ifmt = NULL;
    AVDictionary *opts = NULL;
    int ret;
    if (fmt && !(ifmt = av_find_input_format(fmt))) {
        msg(AV_LOG_ERROR, "unknown input format '%s'\n", fmt);
        return AVERROR(EINVAL);
    }
    av_dict_copy(&opts, opts_in, 0);
    if (!av_dict_get(opts, "probesize", NULL, 0))
        av_dict_set(&opts, "probesize", "20000000", 0);
    if (!av_dict_get(opts, "analyzeduration", NULL, 0))
        av_dict_set(&opts, "analyzeduration", "15000000", 0);
    ret = avformat_open_input(pic, path, ifmt, &opts);
    av_dict_free(&opts);
    if (ret < 0)
        return fail(ret, "cannot open input");
    ret = avformat_find_stream_info(*pic, NULL);
    if (ret < 0)
        msg(AV_LOG_WARNING, "could not read stream info: %s\n", av_err2str(ret));
    return 0;
}

static int64_t file_start_us(const AVFormatContext *ic)
{
    return ic->start_time == AV_NOPTS_VALUE ? 0 : ic->start_time;
}

/* ==================================================================== probe */

typedef struct ScanStream {
    int64_t packets, bytes;
    int64_t end_ts;          /* max pts + duration, stream time base */
    int64_t first_ts;
} ScanStream;

static int cmd_probe(int argc, char **argv)
{
    AVFormatContext *ic = NULL;
    AVBPrint bp;
    ScanStream *scan = NULL;
    double *kf = NULL, *sec_bytes = NULL;
    int nb_kf = 0, kf_cap = 0, nb_sec = 0;
    int scan_all = argc > 4 && !strcmp(argv[4], "scan");
    int first = 1, vbest, abest, ret;
    int64_t start_us;

    if (argc < 4) {
        msg(AV_LOG_ERROR, "usage: ffw probe INPUT OUTPUT.json [scan]\n");
        return AVERROR(EINVAL);
    }
    if ((ret = open_input(&ic, argv[2], NULL, NULL)) < 0)
        return ret;
    start_us = file_start_us(ic);

    vbest = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if (vbest >= 0 && (ic->streams[vbest]->disposition & AV_DISPOSITION_ATTACHED_PIC))
        vbest = -1;
    for (unsigned i = 0; vbest < 0 && i < ic->nb_streams; i++) {
        AVStream *st = ic->streams[i];
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
            vbest = i;
    }
    abest = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -1, vbest, NULL, 0);

    if (scan_all) {
        AVPacket *pkt = av_packet_alloc();
        scan = av_calloc(ic->nb_streams, sizeof(*scan));
        if (!pkt || !scan) { ret = AVERROR(ENOMEM); av_packet_free(&pkt); goto end; }
        for (unsigned i = 0; i < ic->nb_streams; i++)
            scan[i].end_ts = scan[i].first_ts = AV_NOPTS_VALUE;
        while (av_read_frame(ic, pkt) >= 0) {
            ScanStream *s = &scan[pkt->stream_index];
            AVStream *st = ic->streams[pkt->stream_index];
            int64_t ts = pkt->pts != AV_NOPTS_VALUE ? pkt->pts : pkt->dts;
            s->packets++;
            s->bytes += pkt->size;
            if (ts != AV_NOPTS_VALUE) {
                int64_t end = ts + FFMAX(pkt->duration, 0);
                if (s->end_ts == AV_NOPTS_VALUE || end > s->end_ts) s->end_ts = end;
                if (s->first_ts == AV_NOPTS_VALUE || ts < s->first_ts) s->first_ts = ts;
                if (pkt->stream_index == vbest) {
                    double t = ts * av_q2d(st->time_base) - start_us / 1e6;
                    int sec = (int)FFMAX(0, floor(t));
                    if ((pkt->flags & AV_PKT_FLAG_KEY) && nb_kf < 200000) {
                        if (nb_kf >= kf_cap) {
                            kf_cap = kf_cap ? kf_cap * 2 : 1024;
                            if (av_reallocp_array(&kf, kf_cap, sizeof(*kf)) < 0) { ret = AVERROR(ENOMEM); break; }
                        }
                        kf[nb_kf++] = t;
                    }
                    if (sec < 86400) {
                        if (sec >= nb_sec) {
                            int n = sec + 1;
                            if (av_reallocp_array(&sec_bytes, n, sizeof(*sec_bytes)) < 0) { ret = AVERROR(ENOMEM); break; }
                            for (int k = nb_sec; k < n; k++) sec_bytes[k] = 0;
                            nb_sec = n;
                        }
                        sec_bytes[sec] += pkt->size;
                    }
                }
            }
            av_packet_unref(pkt);
        }
        av_packet_free(&pkt);
    } else if (vbest >= 0) {
        /* Keyframes and sizes from the container index (MP4/MOV/AVI have it). */
        AVStream *st = ic->streams[vbest];
        int n = avformat_index_get_entries_count(st);
        for (int i = 0; i < n; i++) {
            const AVIndexEntry *e = avformat_index_get_entry(st, i);
            double t;
            int sec;
            if (!e || (e->flags & AVINDEX_DISCARD_FRAME))
                continue;
            t = e->timestamp * av_q2d(st->time_base) - start_us / 1e6;
            if ((e->flags & AVINDEX_KEYFRAME) && nb_kf < 200000) {
                if (nb_kf >= kf_cap) {
                    kf_cap = kf_cap ? kf_cap * 2 : 1024;
                    if (av_reallocp_array(&kf, kf_cap, sizeof(*kf)) < 0) { ret = AVERROR(ENOMEM); goto end; }
                }
                kf[nb_kf++] = t;
            }
            sec = (int)FFMAX(0, floor(t));
            if (e->size > 0 && sec < 86400) {
                if (sec >= nb_sec) {
                    int m = sec + 1;
                    if (av_reallocp_array(&sec_bytes, m, sizeof(*sec_bytes)) < 0) { ret = AVERROR(ENOMEM); goto end; }
                    for (int k = nb_sec; k < m; k++) sec_bytes[k] = 0;
                    nb_sec = m;
                }
                sec_bytes[sec] += e->size;
            }
        }
    }

    av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
    av_bprint_chars(&bp, '{', 1);
    json_str(&bp, &first, "format", ic->iformat->name);
    json_str(&bp, &first, "format_long", ic->iformat->long_name);
    json_num(&bp, &first, "duration", ic->duration != AV_NOPTS_VALUE ? ic->duration / 1e6 : NAN);
    json_num(&bp, &first, "start_time", start_us / 1e6);
    json_int(&bp, &first, "bit_rate", ic->bit_rate);
    json_int(&bp, &first, "size", ic->pb ? avio_size(ic->pb) : -1);
    json_int(&bp, &first, "video_index", vbest);
    json_int(&bp, &first, "audio_index", abest);
    json_int(&bp, &first, "scanned", scan_all);
    json_tags(&bp, &first, "tags", ic->metadata);

    json_key(&bp, &first, "streams");
    av_bprint_chars(&bp, '[', 1);
    for (unsigned i = 0; i < ic->nb_streams; i++) {
        AVStream *st = ic->streams[i];
        AVCodecParameters *par = st->codecpar;
        const AVCodecDescriptor *desc = avcodec_descriptor_get(par->codec_id);
        int f = 1;
        if (i) av_bprint_chars(&bp, ',', 1);
        av_bprint_chars(&bp, '{', 1);
        json_int(&bp, &f, "index", i);
        json_str(&bp, &f, "type", av_get_media_type_string(par->codec_type));
        json_str(&bp, &f, "codec", desc ? desc->name : "unknown");
        json_int(&bp, &f, "decodable", avcodec_find_decoder(par->codec_id) != NULL);
        json_str(&bp, &f, "profile", avcodec_profile_name(par->codec_id, par->profile));
        json_int(&bp, &f, "bit_rate", par->bit_rate);
        json_q(&bp, &f, "time_base", st->time_base);
        json_num(&bp, &f, "start_time", st->start_time != AV_NOPTS_VALUE ? st->start_time * av_q2d(st->time_base) - start_us / 1e6 : NAN);
        json_num(&bp, &f, "duration", st->duration != AV_NOPTS_VALUE ? st->duration * av_q2d(st->time_base) : NAN);
        json_int(&bp, &f, "nb_frames", st->nb_frames);
        json_int(&bp, &f, "default", !!(st->disposition & AV_DISPOSITION_DEFAULT));
        json_int(&bp, &f, "attached_pic", !!(st->disposition & AV_DISPOSITION_ATTACHED_PIC));
        if (scan) {
            ScanStream *s = &scan[i];
            json_int(&bp, &f, "scan_packets", s->packets);
            json_int(&bp, &f, "scan_bytes", s->bytes);
            json_num(&bp, &f, "scan_end", s->end_ts != AV_NOPTS_VALUE ? s->end_ts * av_q2d(st->time_base) - start_us / 1e6 : NAN);
            json_num(&bp, &f, "scan_start", s->first_ts != AV_NOPTS_VALUE ? s->first_ts * av_q2d(st->time_base) - start_us / 1e6 : NAN);
        }
        if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
            const AVPixFmtDescriptor *pd = av_pix_fmt_desc_get(par->format);
            json_int(&bp, &f, "width", par->width);
            json_int(&bp, &f, "height", par->height);
            json_q(&bp, &f, "sar", par->sample_aspect_ratio);
            json_str(&bp, &f, "pix_fmt", pd ? pd->name : NULL);
            json_int(&bp, &f, "bits", pd ? pd->comp[0].depth : 0);
            json_int(&bp, &f, "alpha", pd ? !!(pd->flags & AV_PIX_FMT_FLAG_ALPHA) : 0);
            json_str(&bp, &f, "color_range", av_color_range_name(par->color_range));
            json_str(&bp, &f, "color_space", av_color_space_name(par->color_space));
            json_str(&bp, &f, "color_transfer", av_color_transfer_name(par->color_trc));
            json_str(&bp, &f, "color_primaries", av_color_primaries_name(par->color_primaries));
            json_int(&bp, &f, "field_order", par->field_order);
            json_q(&bp, &f, "r_frame_rate", st->r_frame_rate);
            json_q(&bp, &f, "avg_frame_rate", st->avg_frame_rate);
            json_num(&bp, &f, "rotation", stream_rotation(st));
            json_int(&bp, &f, "dovi", stream_has_side_data(st, AV_PKT_DATA_DOVI_CONF));
            json_int(&bp, &f, "hdr_mastering", stream_has_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA));
        } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
            char layout[128] = "";
            av_channel_layout_describe(&par->ch_layout, layout, sizeof(layout));
            json_int(&bp, &f, "sample_rate", par->sample_rate);
            json_int(&bp, &f, "channels", par->ch_layout.nb_channels);
            json_str(&bp, &f, "layout", layout);
        }
        json_tags(&bp, &f, "tags", st->metadata);
        av_bprint_chars(&bp, '}', 1);
    }
    av_bprint_chars(&bp, ']', 1);

    json_key(&bp, &first, "keyframes");
    av_bprint_chars(&bp, '[', 1);
    for (int i = 0; i < nb_kf; i++)
        av_bprintf(&bp, i ? ",%.4f" : "%.4f", kf[i]);
    av_bprint_chars(&bp, ']', 1);

    json_key(&bp, &first, "video_bytes_per_second");
    av_bprint_chars(&bp, '[', 1);
    for (int i = 0; i < nb_sec; i++)
        av_bprintf(&bp, i ? ",%.0f" : "%.0f", sec_bytes[i]);
    av_bprint_chars(&bp, ']', 1);
    av_bprint_chars(&bp, '}', 1);

    if (!av_bprint_is_complete(&bp)) {
        ret = AVERROR(ENOMEM);
    } else {
        ret = write_text_file(argv[3], bp.str);
        if (ret < 0) fail(ret, "cannot write probe output");
    }
    av_bprint_finalize(&bp, NULL);

end:
    av_free(scan);
    av_free(kf);
    av_free(sec_bytes);
    avformat_close_input(&ic);
    return ret < 0 ? ret : 0;
}

/* ====================================================================== run */

typedef struct PktQueue {
    AVPacket **pkts;
    int nb, cap;
} PktQueue;

typedef struct Pipe {
    enum AVMediaType type;
    int index;                      /* input stream index */
    AVStream *ist;
    AVCodecContext *dec;
    const char *filter_desc;

    AVFilterGraph *graph;
    AVFilterContext *src, *sink;
    int g_w, g_h, g_fmt, g_rate, g_sfmt, g_channels;

    const AVCodec *enc_codec;
    AVCodecContext *enc;
    AVDictionary *enc_opts;
    AVStream *ost;

    int dec_eof;                    /* decoder flushed */
    int done;                       /* no more output wanted */
    int64_t frames_out;             /* frames sent to the encoder */
    double last_in_t;               /* seconds, last decoded frame */
    double last_out_t;              /* seconds, last encoded frame */
    int64_t next_synth_pts;         /* for frames without timestamps */

    /* constant frame rate selection (video) */
    AVFrame *prev;
    int64_t prev_slot;
    int64_t next_slot;
    int64_t prev_dur_slots;
} Pipe;

typedef struct Run {
    /* options */
    const char *in_path, *in_fmt;
    AVDictionary *in_opts;
    double ss;
    int has_ss;
    int vsi, asi;                   /* -2 auto, -1 none */
    AVRational cfr;
    int64_t slot_start, slot_end;   /* slot_end < 0: until the end */
    const char *vf, *af;
    const char *venc, *aenc;
    AVDictionary *vopts, *aopts;
    int pass;
    const char *passlog;
    int64_t max_vframes;
    const char *out_fmt, *out_path, *result_path;
    AVDictionary *out_opts, *meta;
    int copy_meta;
    double progress_ms;

    /* state */
    AVFormatContext *ic, *oc;
    int64_t start_us;
    Pipe *v, *a;
    Pipe pipes[2];
    int nb_pipes;
    int header_written;
    PktQueue queue;
    double last_progress;
    AVFrame *frame, *filt;
    AVPacket *pkt, *enc_pkt;
    int64_t bytes_out;
    int decode_errors;
} Run;

static int is_null_output(const Run *r)
{
    return r->pass == 1 || !r->out_path || (r->out_fmt && !strcmp(r->out_fmt, "null"));
}

static void report_progress(Run *r, int force)
{
    double t = now_ms(), in_t = 0, out_t = 0, frames = 0;
    if (!force && r->progress_ms <= 0)
        return;
    if (!force && t - r->last_progress < r->progress_ms)
        return;
    r->last_progress = t;
    for (int i = 0; i < r->nb_pipes; i++) {
        in_t = FFMAX(in_t, r->pipes[i].last_in_t);
        out_t = FFMAX(out_t, r->pipes[i].last_out_t);
    }
    if (r->v)
        frames = (double)r->v->frames_out;
    if (r->oc && r->oc->pb && r->header_written)
        r->bytes_out = avio_tell(r->oc->pb);
    js_progress(in_t, out_t, frames, (double)r->bytes_out);
}

static int queue_push(PktQueue *q, AVPacket *pkt)
{
    AVPacket *copy;
    if (q->nb >= q->cap) {
        int cap = q->cap ? q->cap * 2 : 64;
        if (av_reallocp_array(&q->pkts, cap, sizeof(*q->pkts)) < 0)
            return AVERROR(ENOMEM);
        q->cap = cap;
    }
    copy = av_packet_clone(pkt);
    if (!copy)
        return AVERROR(ENOMEM);
    q->pkts[q->nb++] = copy;
    return 0;
}

static void queue_free(PktQueue *q)
{
    for (int i = 0; i < q->nb; i++)
        av_packet_free(&q->pkts[i]);
    av_freep(&q->pkts);
    q->nb = q->cap = 0;
}

static int write_header_if_ready(Run *r, int force)
{
    int ret;
    AVDictionary *opts = NULL;
    const AVDictionaryEntry *t;
    if (!r->oc || r->header_written)
        return 0;
    for (int i = 0; i < r->nb_pipes; i++)
        if (!r->pipes[i].ost && !force)
            return 0;
    if (!r->oc->nb_streams) {
        msg(AV_LOG_ERROR, "no stream produced any data\n");
        return AVERROR(EINVAL);
    }
    av_dict_copy(&opts, r->out_opts, 0);
    ret = avformat_write_header(r->oc, &opts);
    t = NULL;
    while ((t = av_dict_iterate(opts, t)))
        msg(AV_LOG_WARNING, "muxer option '%s' was not used\n", t->key);
    av_dict_free(&opts);
    if (ret < 0)
        return fail(ret, "cannot write header");
    r->header_written = 1;
    for (int i = 0; i < r->queue.nb; i++) {
        ret = av_interleaved_write_frame(r->oc, r->queue.pkts[i]);
        if (ret < 0)
            return fail(ret, "write error");
    }
    queue_free(&r->queue);
    return 0;
}

static int mux_packet(Run *r, Pipe *p, AVPacket *pkt)
{
    if (!r->oc || !p->ost) {
        av_packet_unref(pkt);
        return 0;
    }
    pkt->stream_index = p->ost->index;
    av_packet_rescale_ts(pkt, p->enc->time_base, p->ost->time_base);
    pkt->pos = -1;
    if (!r->header_written) {
        int ret = queue_push(&r->queue, pkt);
        av_packet_unref(pkt);
        return ret;
    }
    {
        int ret = av_interleaved_write_frame(r->oc, pkt);
        if (ret < 0)
            return fail(ret, "write error");
    }
    return 0;
}

static int receive_packets(Run *r, Pipe *p)
{
    int ret;
    for (;;) {
        ret = avcodec_receive_packet(p->enc, r->enc_pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return 0;
        if (ret < 0)
            return fail(ret, "encoding failed");
        if (r->enc_pkt->pts != AV_NOPTS_VALUE) {
            double t = (r->enc_pkt->pts + FFMAX(r->enc_pkt->duration, 0)) * av_q2d(p->enc->time_base);
            p->last_out_t = FFMAX(p->last_out_t, t);
        }
        ret = mux_packet(r, p, r->enc_pkt);
        if (ret < 0)
            return ret;
    }
}

/* Send one filtered frame (or NULL to flush) to the encoder. */
static int encode_frame(Run *r, Pipe *p, AVFrame *f)
{
    int ret;
    if (!p->enc)
        return 0;
    if (f) {
        if (p->type == AVMEDIA_TYPE_VIDEO && r->max_vframes > 0 && p->frames_out >= r->max_vframes)
            return 0;
        f->pict_type = AV_PICTURE_TYPE_NONE;
        p->frames_out++;
    }
    ret = avcodec_send_frame(p->enc, f);
    if (ret < 0 && ret != AVERROR_EOF)
        return fail(ret, "cannot send frame to encoder");
    return receive_packets(r, p);
}


static int open_encoder(Run *r, Pipe *p)
{
    AVCodecContext *e;
    AVDictionary *opts = NULL;
    const AVDictionaryEntry *t;
    int ret;

    e = avcodec_alloc_context3(p->enc_codec);
    if (!e)
        return AVERROR(ENOMEM);
    if (p->type == AVMEDIA_TYPE_VIDEO) {
        AVRational fr = av_buffersink_get_frame_rate(p->sink);
        e->width = av_buffersink_get_w(p->sink);
        e->height = av_buffersink_get_h(p->sink);
        e->pix_fmt = av_buffersink_get_format(p->sink);
        e->sample_aspect_ratio = av_buffersink_get_sample_aspect_ratio(p->sink);
        e->time_base = av_buffersink_get_time_base(p->sink);
        e->color_range = av_buffersink_get_color_range(p->sink);
        e->colorspace = av_buffersink_get_colorspace(p->sink);
        if (fr.num > 0 && fr.den > 0)
            e->framerate = fr;
        if (r->pass) {
            e->flags |= r->pass == 1 ? AV_CODEC_FLAG_PASS1 : AV_CODEC_FLAG_PASS2;
            if (!r->passlog) {
                msg(AV_LOG_ERROR, "-pass needs -passlog\n");
                avcodec_free_context(&e);
                return AVERROR(EINVAL);
            }
            if (!strcmp(p->enc_codec->name, "libx264")) {
                av_dict_set(&opts, "stats", r->passlog, 0);
            } else if (r->pass == 2) {
                char *stats = NULL;
                ret = read_text_file(r->passlog, &stats);
                if (ret < 0) {
                    avcodec_free_context(&e);
                    return fail(ret, "cannot read the first-pass log");
                }
                e->stats_in = stats;
            }
        }
    } else {
        e->sample_rate = av_buffersink_get_sample_rate(p->sink);
        e->sample_fmt = av_buffersink_get_format(p->sink);
        ret = av_buffersink_get_ch_layout(p->sink, &e->ch_layout);
        if (ret < 0) {
            avcodec_free_context(&e);
            return ret;
        }
        e->time_base = (AVRational){ 1, e->sample_rate };
    }
    if (r->oc && (r->oc->oformat->flags & AVFMT_GLOBALHEADER))
        e->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    e->thread_count = 1;

    av_dict_copy(&opts, p->enc_opts, 0);
    ret = avcodec_open2(e, p->enc_codec, &opts);
    if (ret < 0) {
        av_dict_free(&opts);
        avcodec_free_context(&e);
        return fail(ret, "cannot open encoder");
    }
    t = NULL;
    while ((t = av_dict_iterate(opts, t))) {
        if (strcmp(t->key, "stats")) {
            msg(AV_LOG_ERROR, "encoder option '%s' is unknown to %s\n", t->key, p->enc_codec->name);
            av_dict_free(&opts);
            avcodec_free_context(&e);
            return AVERROR_OPTION_NOT_FOUND;
        }
    }
    av_dict_free(&opts);
    p->enc = e;

    if (p->type == AVMEDIA_TYPE_AUDIO && e->frame_size > 0 &&
        !(p->enc_codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
        av_buffersink_set_frame_size(p->sink, e->frame_size);

    if (r->oc) {
        const AVDictionaryEntry *lang = av_dict_get(p->ist->metadata, "language", NULL, 0);
        p->ost = avformat_new_stream(r->oc, NULL);
        if (!p->ost)
            return AVERROR(ENOMEM);
        ret = avcodec_parameters_from_context(p->ost->codecpar, e);
        if (ret < 0)
            return ret;
        p->ost->time_base = e->time_base;
        if (p->type == AVMEDIA_TYPE_VIDEO && e->framerate.num)
            p->ost->avg_frame_rate = e->framerate;
        if (lang && strcmp(lang->value, "und"))
            av_dict_set(&p->ost->metadata, "language", lang->value, 0);
        return write_header_if_ready(r, 0);
    }
    return 0;
}

static int set_sink_constraints(Pipe *p)
{
    const void *cfg;
    int n, ret;
    if (!p->enc_codec)
        return 0;
    if (p->type == AVMEDIA_TYPE_VIDEO) {
        if (p->enc) /* reconfiguration: keep the encoder's format */
            return av_opt_set_array(p->sink, "pixel_formats", AV_OPT_SEARCH_CHILDREN, 0, 1,
                                    AV_OPT_TYPE_PIXEL_FMT, &p->enc->pix_fmt);
        ret = avcodec_get_supported_config(NULL, p->enc_codec, AV_CODEC_CONFIG_PIX_FORMAT, 0, &cfg, &n);
        if (ret >= 0 && cfg && n > 0)
            return av_opt_set_array(p->sink, "pixel_formats", AV_OPT_SEARCH_CHILDREN, 0, n,
                                    AV_OPT_TYPE_PIXEL_FMT, cfg);
        return 0;
    }
    if (p->enc) {
        ret = av_opt_set_array(p->sink, "sample_formats", AV_OPT_SEARCH_CHILDREN, 0, 1,
                               AV_OPT_TYPE_SAMPLE_FMT, &p->enc->sample_fmt);
        if (ret >= 0)
            ret = av_opt_set_array(p->sink, "samplerates", AV_OPT_SEARCH_CHILDREN, 0, 1,
                                   AV_OPT_TYPE_INT, &p->enc->sample_rate);
        if (ret >= 0)
            ret = av_opt_set_array(p->sink, "channel_layouts", AV_OPT_SEARCH_CHILDREN, 0, 1,
                                   AV_OPT_TYPE_CHLAYOUT, &p->enc->ch_layout);
        return ret;
    }
    ret = avcodec_get_supported_config(NULL, p->enc_codec, AV_CODEC_CONFIG_SAMPLE_FORMAT, 0, &cfg, &n);
    if (ret >= 0 && cfg && n > 0) {
        ret = av_opt_set_array(p->sink, "sample_formats", AV_OPT_SEARCH_CHILDREN, 0, n,
                               AV_OPT_TYPE_SAMPLE_FMT, cfg);
        if (ret < 0) return ret;
    }
    ret = avcodec_get_supported_config(NULL, p->enc_codec, AV_CODEC_CONFIG_SAMPLE_RATE, 0, &cfg, &n);
    if (ret >= 0 && cfg && n > 0) {
        ret = av_opt_set_array(p->sink, "samplerates", AV_OPT_SEARCH_CHILDREN, 0, n,
                               AV_OPT_TYPE_INT, cfg);
        if (ret < 0) return ret;
    }
    ret = avcodec_get_supported_config(NULL, p->enc_codec, AV_CODEC_CONFIG_CHANNEL_LAYOUT, 0, &cfg, &n);
    if (ret >= 0 && cfg && n > 0) {
        ret = av_opt_set_array(p->sink, "channel_layouts", AV_OPT_SEARCH_CHILDREN, 0, n,
                               AV_OPT_TYPE_CHLAYOUT, cfg);
        if (ret < 0) return ret;
    }
    return 0;
}

static int drain_sink(Run *r, Pipe *p);

/* Build the filter graph for frames shaped like f. */
static int configure_graph(Run *r, Pipe *p, const AVFrame *f)
{
    AVFilterInOut *outputs = NULL, *inputs = NULL;
    char args[512];
    int ret;
    const char *desc;

    if (p->graph) {
        /* Parameters changed mid-stream: drain the old graph first. */
        ret = av_buffersrc_add_frame(p->src, NULL);
        if (ret >= 0)
            ret = drain_sink(r, p);
        avfilter_graph_free(&p->graph);
        if (ret < 0 && ret != AVERROR_EOF)
            return ret;
        p->done = 0;
    }
    p->graph = avfilter_graph_alloc();
    if (!p->graph)
        return AVERROR(ENOMEM);
    p->graph->nb_threads = 1;

    if (p->type == AVMEDIA_TYPE_VIDEO) {
        AVRational tb = r->cfr.num ? av_inv_q(r->cfr) : p->ist->time_base;
        AVRational sar = f->sample_aspect_ratio.num ? f->sample_aspect_ratio : p->ist->codecpar->sample_aspect_ratio;
        AVRational fr = r->cfr.num ? r->cfr : p->ist->avg_frame_rate;
        if (!sar.num || !sar.den)
            sar = (AVRational){ 1, 1 };
        snprintf(args, sizeof(args),
                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d:colorspace=%d:range=%d",
                 f->width, f->height, f->format, tb.num, tb.den, sar.num, sar.den,
                 f->colorspace, f->color_range);
        if (fr.num > 0 && fr.den > 0)
            av_strlcatf(args, sizeof(args), ":frame_rate=%d/%d", fr.num, fr.den);
        ret = avfilter_graph_create_filter(&p->src, avfilter_get_by_name("buffer"), "in", args, NULL, p->graph);
        if (ret < 0)
            return fail(ret, "cannot create video source");
        p->sink = avfilter_graph_alloc_filter(p->graph, avfilter_get_by_name("buffersink"), "out");
        p->g_w = f->width; p->g_h = f->height; p->g_fmt = f->format;
    } else {
        char layout[128];
        AVChannelLayout cl = { 0 };
        if (f->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
            av_channel_layout_default(&cl, f->ch_layout.nb_channels);
        else
            av_channel_layout_copy(&cl, &f->ch_layout);
        av_channel_layout_describe(&cl, layout, sizeof(layout));
        av_channel_layout_uninit(&cl);
        snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=%s",
                 p->ist->time_base.num, p->ist->time_base.den, f->sample_rate,
                 av_get_sample_fmt_name(f->format), layout);
        ret = avfilter_graph_create_filter(&p->src, avfilter_get_by_name("abuffer"), "in", args, NULL, p->graph);
        if (ret < 0)
            return fail(ret, "cannot create audio source");
        p->sink = avfilter_graph_alloc_filter(p->graph, avfilter_get_by_name("abuffersink"), "out");
        p->g_rate = f->sample_rate; p->g_sfmt = f->format; p->g_channels = f->ch_layout.nb_channels;
    }
    if (!p->sink)
        return AVERROR(ENOMEM);
    ret = set_sink_constraints(p);
    if (ret < 0)
        return fail(ret, "cannot constrain output format");
    ret = avfilter_init_dict(p->sink, NULL);
    if (ret < 0)
        return fail(ret, "cannot init sink");

    outputs = avfilter_inout_alloc();
    inputs = avfilter_inout_alloc();
    if (!outputs || !inputs) {
        ret = AVERROR(ENOMEM);
        goto end;
    }
    outputs->name = av_strdup("in");
    outputs->filter_ctx = p->src;
    outputs->pad_idx = 0;
    inputs->name = av_strdup("out");
    inputs->filter_ctx = p->sink;
    inputs->pad_idx = 0;
    desc = p->filter_desc && *p->filter_desc ? p->filter_desc
                                             : (p->type == AVMEDIA_TYPE_VIDEO ? "null" : "anull");
    ret = avfilter_graph_parse_ptr(p->graph, desc, &inputs, &outputs, NULL);
    if (ret < 0) {
        fail(ret, "invalid filter graph");
        goto end;
    }
    ret = avfilter_graph_config(p->graph, NULL);
    if (ret < 0) {
        fail(ret, "cannot configure filter graph");
        goto end;
    }
    if (!p->enc && p->enc_codec)
        ret = open_encoder(r, p);
    else if (p->enc && p->type == AVMEDIA_TYPE_AUDIO && p->enc->frame_size > 0 &&
             !(p->enc_codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
        av_buffersink_set_frame_size(p->sink, p->enc->frame_size);
end:
    avfilter_inout_free(&inputs);
    avfilter_inout_free(&outputs);
    return ret;
}

static int drain_sink(Run *r, Pipe *p)
{
    int ret;
    for (;;) {
        ret = av_buffersink_get_frame(p->sink, r->filt);
        if (ret == AVERROR(EAGAIN))
            return 0;
        if (ret == AVERROR_EOF) {
            return ret;
        }
        if (ret < 0)
            return fail(ret, "filtering failed");
        if (!p->done) {
            ret = encode_frame(r, p, r->filt);
            av_frame_unref(r->filt);
            if (ret < 0)
                return ret;
            if (p->type == AVMEDIA_TYPE_VIDEO && r->max_vframes > 0 && p->frames_out >= r->max_vframes) {
                p->done = 1;
                ret = encode_frame(r, p, NULL);
                if (ret < 0)
                    return ret;
            }
        } else {
            av_frame_unref(r->filt);
        }
    }
}

/* Push a frame (with its final timestamp) through the filters and encoder. */
static int filter_frame(Run *r, Pipe *p, AVFrame *f)
{
    int ret;
    if (p->done)
        return 0;
    if (!p->graph ||
        (p->type == AVMEDIA_TYPE_VIDEO && (f->width != p->g_w || f->height != p->g_h || f->format != p->g_fmt)) ||
        (p->type == AVMEDIA_TYPE_AUDIO && (f->sample_rate != p->g_rate || f->format != p->g_sfmt ||
                                           f->ch_layout.nb_channels != p->g_channels))) {
        ret = configure_graph(r, p, f);
        if (ret < 0)
            return ret;
    }
    ret = av_buffersrc_add_frame_flags(p->src, f, AV_BUFFERSRC_FLAG_KEEP_REF);
    if (ret < 0)
        return fail(ret, "cannot feed filter graph");
    ret = drain_sink(r, p);
    if (ret == AVERROR_EOF) {
        /* The graph ended (e.g. trim reached its end): finish this stream. */
        if (!p->done) {
            p->done = 1;
            ret = encode_frame(r, p, NULL);
            return ret < 0 ? ret : 0;
        }
        return 0;
    }
    return ret;
}

/* End a stream early (its last wanted frame was sent): drain the frames still
 * inside the filters (a deinterlacer holds one back), then the encoder. */
static int close_pipe(Run *r, Pipe *p)
{
    int ret = 0, ret2;
    if (p->done)
        return 0;
    if (p->graph) {
        ret = av_buffersrc_add_frame(p->src, NULL);
        if (ret >= 0) {
            ret = drain_sink(r, p);
            if (ret == AVERROR_EOF)
                ret = 0;
        }
    }
    if (p->done) /* the frame limit was reached while draining */
        return ret;
    p->done = 1;
    ret2 = encode_frame(r, p, NULL);
    return ret < 0 ? ret : ret2;
}

static int emit_slot(Run *r, Pipe *p, AVFrame *src, int64_t slot)
{
    int ret;
    AVFrame *f = av_frame_clone(src);
    if (!f)
        return AVERROR(ENOMEM);
    f->pts = slot - r->slot_start;
    f->duration = 1;
    ret = filter_frame(r, p, f);
    av_frame_free(&f);
    return ret;
}

/* Constant frame rate selection: for every slot s of the output grid, output
 * the latest decoded frame whose own slot is <= s. Independent chunks of the
 * same video therefore pick exactly the frames one long encode would pick. */
static int cfr_frame(Run *r, Pipe *p, AVFrame *f, double t)
{
    int64_t slot = llrint(t * av_q2d(r->cfr));
    int ret;
    if (p->done)
        return 0;
    if (p->prev && slot <= p->prev_slot && t < p->last_in_t - 1.0) {
        /* timestamps went backwards a lot (broken file): ignore the frame */
        return 0;
    }
    if (p->next_slot < 0)
        p->next_slot = r->slot_start;
    while (p->next_slot < slot && (r->slot_end < 0 || p->next_slot < r->slot_end)) {
        ret = emit_slot(r, p, p->prev ? p->prev : f, p->next_slot);
        if (ret < 0)
            return ret;
        p->next_slot++;
        if (p->done)
            return 0;
    }
    if (!p->prev && !(p->prev = av_frame_alloc()))
        return AVERROR(ENOMEM);
    av_frame_unref(p->prev);
    ret = av_frame_ref(p->prev, f);
    if (ret < 0)
        return ret;
    p->prev_slot = slot;
    p->prev_dur_slots = 1;
    if (f->duration > 0) {
        int64_t d = llrint(f->duration * av_q2d(p->ist->time_base) * av_q2d(r->cfr));
        p->prev_dur_slots = FFMAX(1, d);
    }
    if (r->slot_end >= 0 && p->next_slot >= r->slot_end)
        return close_pipe(r, p);
    return 0;
}

static int cfr_flush(Run *r, Pipe *p)
{
    int64_t end;
    int ret;
    if (!p->prev || p->done)
        return 0;
    end = r->slot_end >= 0 ? r->slot_end : p->prev_slot + p->prev_dur_slots;
    if (p->next_slot < 0)
        p->next_slot = r->slot_start;
    while (p->next_slot < end && !p->done) {
        ret = emit_slot(r, p, p->prev, p->next_slot);
        if (ret < 0)
            return ret;
        p->next_slot++;
    }
    return 0;
}

static int handle_decoded(Run *r, Pipe *p, AVFrame *f)
{
    int64_t ts = f->best_effort_timestamp;
    AVRational tb = p->ist->time_base;
    int64_t offset = av_rescale_q(r->start_us, AV_TIME_BASE_Q, tb);
    double t;

    if (ts == AV_NOPTS_VALUE)
        ts = f->pts;
    if (ts == AV_NOPTS_VALUE)
        ts = p->next_synth_pts;
    if (f->duration > 0)
        p->next_synth_pts = ts + f->duration;
    else
        p->next_synth_pts = ts + 1;
    t = ts * av_q2d(tb) - r->start_us / 1e6;
    p->last_in_t = FFMAX(p->last_in_t, t);

    if (p->type == AVMEDIA_TYPE_VIDEO && r->cfr.num)
        return cfr_frame(r, p, f, t);

    if (p->type == AVMEDIA_TYPE_VIDEO && r->has_ss && t < r->ss - 0.0005)
        return 0; /* before the seek point */
    f->pts = ts - offset;
    if (p->type == AVMEDIA_TYPE_VIDEO && r->has_ss)
        f->pts -= av_rescale_q(llrint(r->ss * 1e6), AV_TIME_BASE_Q, tb);
    return filter_frame(r, p, f);
}

static int decode_packet(Run *r, Pipe *p, AVPacket *pkt)
{
    int ret = avcodec_send_packet(p->dec, pkt);
    if (ret < 0 && ret != AVERROR_EOF) {
        if (ret == AVERROR(EAGAIN))
            msg(AV_LOG_WARNING, "decoder is full\n");
        else if (++r->decode_errors < 50)
            msg(AV_LOG_WARNING, "decoding error (skipped): %s\n", av_err2str(ret));
        if (pkt)
            return 0;
    }
    for (;;) {
        ret = avcodec_receive_frame(p->dec, r->frame);
        if (ret == AVERROR(EAGAIN))
            return 0;
        if (ret == AVERROR_EOF) {
            p->dec_eof = 1;
            return 0;
        }
        if (ret < 0) {
            if (++r->decode_errors < 50)
                msg(AV_LOG_WARNING, "decoding error (skipped): %s\n", av_err2str(ret));
            if (r->decode_errors > 2000)
                return fail(ret, "too many decoding errors");
            continue;
        }
        ret = handle_decoded(r, p, r->frame);
        av_frame_unref(r->frame);
        if (ret < 0)
            return ret;
        if (p->done)
            return 0;
    }
}

static int finish_pipe(Run *r, Pipe *p)
{
    int ret = 0;
    if (!p->dec_eof && !p->done) {
        ret = decode_packet(r, p, NULL);
        if (ret < 0)
            return ret;
    }
    if (p->type == AVMEDIA_TYPE_VIDEO && r->cfr.num && !p->done) {
        ret = cfr_flush(r, p);
        if (ret < 0)
            return ret;
    }
    if (p->graph && !p->done) {
        ret = av_buffersrc_add_frame(p->src, NULL);
        if (ret < 0)
            return fail(ret, "cannot flush filters");
        ret = drain_sink(r, p);
        if (ret < 0 && ret != AVERROR_EOF)
            return ret;
    }
    if (p->enc && !p->done) {
        p->done = 1;
        ret = encode_frame(r, p, NULL);
    }
    p->done = 1;
    return ret < 0 ? ret : 0;
}

static int open_decoder(Pipe *p)
{
    const AVCodec *dec = avcodec_find_decoder(p->ist->codecpar->codec_id);
    AVDictionary *opts = NULL;
    int ret;
    if (!dec) {
        msg(AV_LOG_ERROR, "no decoder for %s\n", avcodec_get_name(p->ist->codecpar->codec_id));
        return AVERROR_DECODER_NOT_FOUND;
    }
    p->dec = avcodec_alloc_context3(dec);
    if (!p->dec)
        return AVERROR(ENOMEM);
    ret = avcodec_parameters_to_context(p->dec, p->ist->codecpar);
    if (ret < 0)
        return ret;
    p->dec->pkt_timebase = p->ist->time_base;
    p->dec->thread_count = 1;
    p->dec->thread_type = 0;
    if (p->type == AVMEDIA_TYPE_VIDEO)
        p->dec->framerate = av_guess_frame_rate(NULL, p->ist, NULL);
    av_dict_set(&opts, "threads", "1", 0);
    ret = avcodec_open2(p->dec, dec, &opts);
    av_dict_free(&opts);
    if (ret < 0)
        return fail(ret, "cannot open decoder");
    return 0;
}

static int write_result(Run *r)
{
    AVBPrint bp;
    int first = 1, ret;
    if (!r->result_path)
        return 0;
    av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
    av_bprint_chars(&bp, '{', 1);
    json_int(&bp, &first, "video_frames", r->v ? r->v->frames_out : 0);
    json_num(&bp, &first, "video_end", r->v ? r->v->last_out_t : 0);
    json_int(&bp, &first, "audio_frames", r->a ? r->a->frames_out : 0);
    json_num(&bp, &first, "audio_end", r->a ? r->a->last_out_t : 0);
    json_num(&bp, &first, "input_end", FFMAX(r->v ? r->v->last_in_t : 0, r->a ? r->a->last_in_t : 0));
    json_int(&bp, &first, "bytes", r->bytes_out);
    json_int(&bp, &first, "decode_errors", r->decode_errors);
    if (r->v && r->v->enc) {
        AVCodecContext *e = r->v->enc;
        json_int(&bp, &first, "width", e->width);
        json_int(&bp, &first, "height", e->height);
        json_int(&bp, &first, "extradata_crc",
                 e->extradata_size ? av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, e->extradata, e->extradata_size) : 0);
    }
    av_bprint_chars(&bp, '}', 1);
    ret = write_text_file(r->result_path, bp.str);
    av_bprint_finalize(&bp, NULL);
    return ret;
}

static void run_free(Run *r)
{
    for (int i = 0; i < r->nb_pipes; i++) {
        Pipe *p = &r->pipes[i];
        avcodec_free_context(&p->dec);
        avcodec_free_context(&p->enc);
        avfilter_graph_free(&p->graph);
        av_frame_free(&p->prev);
    }
    if (r->oc) {
        if (r->oc->pb && !(r->oc->oformat->flags & AVFMT_NOFILE))
            avio_closep(&r->oc->pb);
        avformat_free_context(r->oc);
        r->oc = NULL;
    }
    avformat_close_input(&r->ic);
    queue_free(&r->queue);
    av_frame_free(&r->frame);
    av_frame_free(&r->filt);
    av_packet_free(&r->pkt);
    av_packet_free(&r->enc_pkt);
    av_dict_free(&r->in_opts);
    av_dict_free(&r->vopts);
    av_dict_free(&r->aopts);
    av_dict_free(&r->out_opts);
    av_dict_free(&r->meta);
}

static int parse_run_args(Run *r, int argc, char **argv)
{
    r->vsi = r->asi = -2;
    r->slot_end = -1;
    r->progress_ms = 250;
    for (int i = 2; i < argc; i++) {
        const char *o = argv[i];
        const char *v = i + 1 < argc ? argv[i + 1] : NULL;
        int ret = 0;
#define NEED() do { if (!v) { msg(AV_LOG_ERROR, "option %s needs a value\n", o); return AVERROR(EINVAL); } i++; } while (0)
        if      (!strcmp(o, "-i"))        { NEED(); r->in_path = v; }
        else if (!strcmp(o, "-fin"))      { NEED(); r->in_fmt = v; }
        else if (!strcmp(o, "-iopt"))     { NEED(); ret = parse_kv(&r->in_opts, v); }
        else if (!strcmp(o, "-ss"))       { NEED(); r->ss = strtod(v, NULL); r->has_ss = r->ss > 0; }
        else if (!strcmp(o, "-vsi"))      { NEED(); r->vsi = atoi(v); }
        else if (!strcmp(o, "-asi"))      { NEED(); r->asi = atoi(v); }
        else if (!strcmp(o, "-vn"))       { r->vsi = -1; }
        else if (!strcmp(o, "-an"))       { r->asi = -1; }
        else if (!strcmp(o, "-cfr"))      { NEED(); ret = av_parse_ratio(&r->cfr, v, 1000000, 0, NULL); }
        else if (!strcmp(o, "-slots"))    { NEED(); if (sscanf(v, "%" SCNd64 ":%" SCNd64, &r->slot_start, &r->slot_end) != 2) ret = AVERROR(EINVAL); }
        else if (!strcmp(o, "-vf"))       { NEED(); r->vf = v; }
        else if (!strcmp(o, "-af"))       { NEED(); r->af = v; }
        else if (!strcmp(o, "-c:v"))      { NEED(); r->venc = v; }
        else if (!strcmp(o, "-c:a"))      { NEED(); r->aenc = v; }
        else if (!strcmp(o, "-vopt"))     { NEED(); ret = parse_kv(&r->vopts, v); }
        else if (!strcmp(o, "-aopt"))     { NEED(); ret = parse_kv(&r->aopts, v); }
        else if (!strcmp(o, "-pass"))     { NEED(); r->pass = atoi(v); }
        else if (!strcmp(o, "-passlog"))  { NEED(); r->passlog = v; }
        else if (!strcmp(o, "-vframes"))  { NEED(); r->max_vframes = strtoll(v, NULL, 10); }
        else if (!strcmp(o, "-f"))        { NEED(); r->out_fmt = v; }
        else if (!strcmp(o, "-fopt"))     { NEED(); ret = parse_kv(&r->out_opts, v); }
        else if (!strcmp(o, "-meta"))     { NEED(); ret = parse_kv(&r->meta, v); }
        else if (!strcmp(o, "-copymeta")) { r->copy_meta = 1; }
        else if (!strcmp(o, "-o"))        { NEED(); r->out_path = v; }
        else if (!strcmp(o, "-result"))   { NEED(); r->result_path = v; }
        else if (!strcmp(o, "-progress")) { NEED(); r->progress_ms = strtod(v, NULL); }
        else if (!strcmp(o, "-loglevel")) { NEED(); g_log_level = atoi(v); }
        else { msg(AV_LOG_ERROR, "unknown option %s\n", o); return AVERROR(EINVAL); }
#undef NEED
        if (ret < 0)
            return ret;
    }
    if (!r->in_path) {
        msg(AV_LOG_ERROR, "missing -i\n");
        return AVERROR(EINVAL);
    }
    if (r->cfr.num < 0 || r->cfr.den <= 0)
        r->cfr = (AVRational){ 0, 1 };
    return 0;
}

static int is_location_tag(const char *key)
{
    return av_stristr(key, "location") || av_stristr(key, "gps") || av_stristr(key, "xyz");
}

static int cmd_run(int argc, char **argv)
{
    Run run = { 0 }, *r = &run;
    AVPacket *pkt;
    int ret, vsi, asi;

    if ((ret = parse_run_args(r, argc, argv)) < 0)
        goto end;
    r->frame = av_frame_alloc();
    r->filt = av_frame_alloc();
    r->pkt = av_packet_alloc();
    r->enc_pkt = av_packet_alloc();
    if (!r->frame || !r->filt || !r->pkt || !r->enc_pkt) {
        ret = AVERROR(ENOMEM);
        goto end;
    }
    if ((ret = open_input(&r->ic, r->in_path, r->in_fmt, r->in_opts)) < 0)
        goto end;
    r->start_us = file_start_us(r->ic);

    /* stream selection */
    vsi = r->vsi;
    if (vsi == -2) {
        vsi = av_find_best_stream(r->ic, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
        if (vsi >= 0 && (r->ic->streams[vsi]->disposition & AV_DISPOSITION_ATTACHED_PIC))
            vsi = -1;
    }
    asi = r->asi;
    if (asi == -2)
        asi = av_find_best_stream(r->ic, AVMEDIA_TYPE_AUDIO, -1, vsi, NULL, 0);
    if (r->venc && !strcmp(r->venc, "none")) vsi = -1;
    if (r->aenc && !strcmp(r->aenc, "none")) asi = -1;
    if (r->pass == 1) asi = -1;
    if (vsi >= (int)r->ic->nb_streams || asi >= (int)r->ic->nb_streams) {
        ret = AVERROR(EINVAL);
        goto end;
    }

    for (int k = 0; k < 2; k++) {
        int idx = k == 0 ? vsi : asi;
        const char *enc_name = k == 0 ? r->venc : r->aenc;
        Pipe *p;
        if (idx < 0)
            continue;
        if (!enc_name) {
            msg(AV_LOG_ERROR, "missing %s encoder\n", k == 0 ? "-c:v" : "-c:a");
            ret = AVERROR(EINVAL);
            goto end;
        }
        p = &r->pipes[r->nb_pipes++];
        p->type = k == 0 ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
        p->index = idx;
        p->ist = r->ic->streams[idx];
        p->filter_desc = k == 0 ? r->vf : r->af;
        p->enc_opts = k == 0 ? r->vopts : r->aopts;
        p->next_slot = -1;
        p->enc_codec = avcodec_find_encoder_by_name(enc_name);
        if (!p->enc_codec) {
            msg(AV_LOG_ERROR, "unknown encoder %s\n", enc_name);
            ret = AVERROR_ENCODER_NOT_FOUND;
            goto end;
        }
        if ((ret = open_decoder(p)) < 0)
            goto end;
        if (k == 0) r->v = p; else r->a = p;
    }
    if (!r->nb_pipes) {
        msg(AV_LOG_ERROR, "nothing to do: no usable video or audio stream\n");
        ret = AVERROR_STREAM_NOT_FOUND;
        goto end;
    }
    for (unsigned i = 0; i < r->ic->nb_streams; i++) {
        if ((int)i != vsi && (int)i != asi)
            r->ic->streams[i]->discard = AVDISCARD_ALL;
    }

    /* output */
    if (!is_null_output(r)) {
        ret = avformat_alloc_output_context2(&r->oc, NULL, r->out_fmt, r->out_path);
        if (ret < 0 || !r->oc) {
            fail(ret, "cannot create output");
            goto end;
        }
        if (!(r->oc->oformat->flags & AVFMT_NOFILE)) {
            ret = avio_open(&r->oc->pb, r->out_path, AVIO_FLAG_WRITE);
            if (ret < 0) {
                fail(ret, "cannot open output file");
                goto end;
            }
        }
        if (r->copy_meta) {
            const AVDictionaryEntry *t = NULL;
            while ((t = av_dict_iterate(r->ic->metadata, t)))
                if (!is_location_tag(t->key))
                    av_dict_set(&r->oc->metadata, t->key, t->value, 0);
        }
        av_dict_copy(&r->oc->metadata, r->meta, 0);
    }

    /* seek */
    {
        double seek_t = -1;
        if (r->cfr.num && r->slot_start > 0)
            seek_t = (r->slot_start - 1) / av_q2d(r->cfr);
        else if (r->has_ss)
            seek_t = r->ss;
        if (seek_t > 0) {
            int64_t ts = llrint(seek_t * AV_TIME_BASE) + r->start_us;
            ret = avformat_seek_file(r->ic, -1, INT64_MIN, ts, ts, 0);
            if (ret < 0) {
                msg(AV_LOG_WARNING, "seeking failed, decoding from the start: %s\n", av_err2str(ret));
                avformat_seek_file(r->ic, -1, INT64_MIN, r->start_us, r->start_us, 0);
            }
        }
    }

    /* main loop */
    pkt = r->pkt;
    for (;;) {
        int all_done = 1;
        Pipe *p = NULL;
        for (int i = 0; i < r->nb_pipes; i++)
            if (!r->pipes[i].done)
                all_done = 0;
        if (all_done)
            break;
        ret = av_read_frame(r->ic, pkt);
        if (ret == AVERROR(EAGAIN))
            continue;
        if (ret < 0) {
            if (ret != AVERROR_EOF)
                msg(AV_LOG_WARNING, "read error, treating as end of file: %s\n", av_err2str(ret));
            break;
        }
        for (int i = 0; i < r->nb_pipes; i++)
            if (r->pipes[i].index == pkt->stream_index)
                p = &r->pipes[i];
        if (p && !p->done) {
            ret = decode_packet(r, p, pkt);
            if (ret < 0) {
                av_packet_unref(pkt);
                goto end;
            }
        }
        av_packet_unref(pkt);
        report_progress(r, 0);
    }
    for (int i = 0; i < r->nb_pipes; i++) {
        ret = finish_pipe(r, &r->pipes[i]);
        if (ret < 0)
            goto end;
    }
    if (r->oc) {
        ret = write_header_if_ready(r, 1);
        if (ret < 0)
            goto end;
        ret = av_write_trailer(r->oc);
        if (ret < 0) {
            fail(ret, "cannot finish output");
            goto end;
        }
        if (r->oc->pb)
            r->bytes_out = avio_size(r->oc->pb);
    }
    if (r->pass == 1 && r->v && r->v->enc && r->v->enc->stats_out &&
        strcmp(r->v->enc_codec->name, "libx264")) {
        ret = write_text_file(r->passlog, r->v->enc->stats_out);
        if (ret < 0) {
            fail(ret, "cannot write the first-pass log");
            goto end;
        }
    }
    if (r->v && r->v->frames_out == 0 && r->v->enc_codec) {
        msg(AV_LOG_ERROR, "no video frames were produced\n");
        ret = AVERROR_INVALIDDATA;
        goto end;
    }
    report_progress(r, 1);
    ret = write_result(r);
end:
    run_free(r);
    return ret < 0 ? ret : 0;
}

/* ====================================================================== mux */

#define MAX_INPUTS 8
#define MAX_MAPS 8

typedef struct MuxIn {
    const char *path, *fmt;
    AVDictionary *opts;
    AVFormatContext *ic;
    AVPacket *pending;
    int has_pending, eof, started;
    int64_t offset_us;
} MuxIn;

typedef struct MuxMap {
    int in;
    int stream;
    AVStream *ost;
} MuxMap;

static int cmd_mux(int argc, char **argv)
{
    MuxIn ins[MAX_INPUTS] = { 0 };
    MuxMap maps[MAX_MAPS] = { 0 };
    int nb_in = 0, nb_maps = 0, copy_meta_from = -1, ret = 0, header = 0;
    const char *next_fmt = NULL, *out_fmt = NULL, *out_path = NULL;
    AVDictionary *next_opts = NULL, *out_opts = NULL, *meta = NULL;
    const char *map_specs[MAX_MAPS];
    AVFormatContext *oc = NULL;
    AVRational vtb = { 0, 0 };
    int64_t bytes = 0;

    for (int i = 2; i < argc; i++) {
        const char *o = argv[i];
        const char *v = i + 1 < argc ? argv[i + 1] : NULL;
#define NEED() do { if (!v) { msg(AV_LOG_ERROR, "option %s needs a value\n", o); ret = AVERROR(EINVAL); goto end; } i++; } while (0)
        if (!strcmp(o, "-fin"))       { NEED(); next_fmt = v; }
        else if (!strcmp(o, "-iopt")) { NEED(); if ((ret = parse_kv(&next_opts, v)) < 0) goto end; }
        else if (!strcmp(o, "-i")) {
            NEED();
            if (nb_in >= MAX_INPUTS) { ret = AVERROR(EINVAL); goto end; }
            ins[nb_in].path = v;
            ins[nb_in].fmt = next_fmt;
            ins[nb_in].opts = next_opts;
            next_opts = NULL;
            next_fmt = NULL;
            nb_in++;
        }
        else if (!strcmp(o, "-map"))      { NEED(); if (nb_maps >= MAX_MAPS) { ret = AVERROR(EINVAL); goto end; } map_specs[nb_maps++] = v; }
        else if (!strcmp(o, "-f"))        { NEED(); out_fmt = v; }
        else if (!strcmp(o, "-fopt"))     { NEED(); if ((ret = parse_kv(&out_opts, v)) < 0) goto end; }
        else if (!strcmp(o, "-meta"))     { NEED(); if ((ret = parse_kv(&meta, v)) < 0) goto end; }
        else if (!strcmp(o, "-copymeta")) { NEED(); copy_meta_from = atoi(v); }
        else if (!strcmp(o, "-vtb")) {
            NEED();
            if (av_parse_ratio(&vtb, v, 1000000, 0, NULL) < 0 || vtb.num <= 0 || vtb.den <= 0) {
                msg(AV_LOG_ERROR, "bad -vtb %s\n", v);
                ret = AVERROR(EINVAL);
                goto end;
            }
        }
        else if (!strcmp(o, "-o"))        { NEED(); out_path = v; }
        else if (!strcmp(o, "-loglevel")) { NEED(); g_log_level = atoi(v); }
        else { msg(AV_LOG_ERROR, "unknown option %s\n", o); ret = AVERROR(EINVAL); goto end; }
#undef NEED
    }
    if (!nb_in || !out_path || !nb_maps) {
        msg(AV_LOG_ERROR, "mux needs -i, -map and -o\n");
        ret = AVERROR(EINVAL);
        goto end;
    }
    for (int i = 0; i < nb_in; i++) {
        if ((ret = open_input(&ins[i].ic, ins[i].path, ins[i].fmt, ins[i].opts)) < 0)
            goto end;
        ins[i].pending = av_packet_alloc();
        if (!ins[i].pending) { ret = AVERROR(ENOMEM); goto end; }
        ins[i].offset_us = ins[i].ic->start_time != AV_NOPTS_VALUE && ins[i].ic->start_time > 0
                         ? -ins[i].ic->start_time : 0;
    }

    ret = avformat_alloc_output_context2(&oc, NULL, out_fmt, out_path);
    if (ret < 0 || !oc) {
        fail(ret, "cannot create output");
        goto end;
    }
    for (int m = 0; m < nb_maps; m++) {
        const char *spec = map_specs[m];
        char *colon = strchr(spec, ':');
        int in = atoi(spec), st = -1;
        AVFormatContext *ic;
        AVStream *ist;
        AVCodecParameters *par;
        if (!colon || in < 0 || in >= nb_in) {
            msg(AV_LOG_ERROR, "bad -map %s\n", spec);
            ret = AVERROR(EINVAL);
            goto end;
        }
        ic = ins[in].ic;
        if (colon[1] == 'v')
            st = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
        else if (colon[1] == 'a')
            st = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
        else
            st = atoi(colon + 1);
        if (st < 0 || st >= (int)ic->nb_streams) {
            msg(AV_LOG_ERROR, "-map %s matches no stream\n", spec);
            ret = AVERROR_STREAM_NOT_FOUND;
            goto end;
        }
        ist = ic->streams[st];
        maps[m].in = in;
        maps[m].stream = st;
        maps[m].ost = avformat_new_stream(oc, NULL);
        if (!maps[m].ost) { ret = AVERROR(ENOMEM); goto end; }
        par = maps[m].ost->codecpar;
        ret = avcodec_parameters_copy(par, ist->codecpar);
        if (ret < 0)
            goto end;
        /* keep the input codec tag only if the output format accepts it */
        {
            unsigned tag = ist->codecpar->codec_tag;
            unsigned tag2;
            par->codec_tag = 0;
            if (!oc->oformat->codec_tag ||
                av_codec_get_id(oc->oformat->codec_tag, tag) == par->codec_id ||
                !av_codec_get_tag2(oc->oformat->codec_tag, par->codec_id, &tag2))
                par->codec_tag = tag;
        }
        maps[m].ost->time_base = ist->time_base;
        /* AVI stores no timestamps: its time base is the frame rate, and the
         * muxer writes an empty chunk for every tick without a frame. -vtb
         * gives video the real frame duration instead of the intermediate
         * file's finer time base (1/600 wrote 24 empty chunks per frame). */
        if (vtb.num && par->codec_type == AVMEDIA_TYPE_VIDEO)
            maps[m].ost->time_base = vtb;
        maps[m].ost->avg_frame_rate = ist->avg_frame_rate;
        maps[m].ost->r_frame_rate = ist->r_frame_rate;
        maps[m].ost->disposition = ist->disposition & ~AV_DISPOSITION_ATTACHED_PIC;
        {
            const AVDictionaryEntry *lang = av_dict_get(ist->metadata, "language", NULL, 0);
            if (lang && strcmp(lang->value, "und"))
                av_dict_set(&maps[m].ost->metadata, "language", lang->value, 0);
        }
    }
    if (copy_meta_from >= 0 && copy_meta_from < nb_in) {
        const AVDictionaryEntry *t = NULL;
        while ((t = av_dict_iterate(ins[copy_meta_from].ic->metadata, t)))
            if (!is_location_tag(t->key))
                av_dict_set(&oc->metadata, t->key, t->value, 0);
    }
    av_dict_copy(&oc->metadata, meta, 0);
    if (!(oc->oformat->flags & AVFMT_NOFILE)) {
        ret = avio_open(&oc->pb, out_path, AVIO_FLAG_WRITE);
        if (ret < 0) {
            fail(ret, "cannot open output file");
            goto end;
        }
    }
    {
        AVDictionary *opts = NULL;
        av_dict_copy(&opts, out_opts, 0);
        ret = avformat_write_header(oc, &opts);
        av_dict_free(&opts);
        if (ret < 0) {
            fail(ret, "cannot write header");
            goto end;
        }
        header = 1;
    }

    /* Merge packets from all inputs in timestamp order. */
    for (;;) {
        int best = -1;
        int64_t best_ts = INT64_MAX;
        for (int i = 0; i < nb_in; i++) {
            MuxIn *in = &ins[i];
            while (!in->has_pending && !in->eof) {
                int mapped = 0;
                ret = av_read_frame(in->ic, in->pending);
                if (ret < 0) {
                    in->eof = 1;
                    break;
                }
                for (int m = 0; m < nb_maps; m++)
                    if (maps[m].in == i && maps[m].stream == in->pending->stream_index)
                        mapped = 1;
                if (mapped)
                    in->has_pending = 1;
                else
                    av_packet_unref(in->pending);
            }
            if (in->has_pending) {
                AVStream *st = in->ic->streams[in->pending->stream_index];
                int64_t ts = in->pending->dts != AV_NOPTS_VALUE ? in->pending->dts : in->pending->pts;
                int64_t us = ts == AV_NOPTS_VALUE ? INT64_MIN : av_rescale_q(ts, st->time_base, AV_TIME_BASE_Q);
                /* AVI (-vtb): an input whose first packet is before zero (MP3
                 * encoder delay: -23 ms, even when start_time reads 0 because
                 * the skipped samples are counted in) would make the muxer
                 * shift every stream later. AVI pads gaps only after the first
                 * frame, so frame 0 would stay at 0 and every later frame
                 * would land one grid step late. Start such an input at zero
                 * instead; the encoder delay then plays first, as in any MP3
                 * AVI. */
                if (vtb.num && !in->started && us != INT64_MIN) {
                    in->started = 1;
                    if (us + in->offset_us < 0)
                        in->offset_us = -us;
                }
                if (best < 0 || us < best_ts) {
                    best = i;
                    best_ts = us;
                }
            }
        }
        if (best < 0)
            break;
        {
            MuxIn *in = &ins[best];
            AVPacket *p = in->pending;
            AVStream *ist = in->ic->streams[p->stream_index];
            MuxMap *mm = NULL;
            int64_t off;
            for (int m = 0; m < nb_maps; m++)
                if (maps[m].in == best && maps[m].stream == p->stream_index)
                    mm = &maps[m];
            off = av_rescale_q(in->offset_us, AV_TIME_BASE_Q, ist->time_base);
            if (p->pts != AV_NOPTS_VALUE) p->pts += off;
            if (p->dts != AV_NOPTS_VALUE) p->dts += off;
            av_packet_rescale_ts(p, ist->time_base, mm->ost->time_base);
            p->stream_index = mm->ost->index;
            p->pos = -1;
            ret = av_interleaved_write_frame(oc, p);
            in->has_pending = 0;
            if (ret < 0) {
                fail(ret, "write error");
                goto end;
            }
        }
    }
    ret = av_write_trailer(oc);
    if (ret < 0) {
        fail(ret, "cannot finish output");
        goto end;
    }
    if (oc->pb)
        bytes = avio_size(oc->pb);
    js_progress(0, 0, 0, (double)bytes);
    ret = 0;
end:
    for (int i = 0; i < nb_in; i++) {
        avformat_close_input(&ins[i].ic);
        av_packet_free(&ins[i].pending);
        av_dict_free(&ins[i].opts);
    }
    if (oc) {
        if (oc->pb && !(oc->oformat->flags & AVFMT_NOFILE))
            avio_closep(&oc->pb);
        avformat_free_context(oc);
    }
    (void)header;
    av_dict_free(&next_opts);
    av_dict_free(&out_opts);
    av_dict_free(&meta);
    return ret < 0 ? ret : 0;
}

/* ===================================================================== main */

int main(int argc, char **argv)
{
    int ret;
    av_log_set_callback(log_callback);
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
    if (argc < 2) {
        msg(AV_LOG_ERROR, "usage: ffw probe|run|mux ...\n");
        return 2;
    }
    if (!strcmp(argv[1], "probe"))
        ret = cmd_probe(argc, argv);
    else if (!strcmp(argv[1], "run"))
        ret = cmd_run(argc, argv);
    else if (!strcmp(argv[1], "mux"))
        ret = cmd_mux(argc, argv);
    else if (!strcmp(argv[1], "version")) {
        printf("{\"ffmpeg\":\"%s\",\"avcodec\":\"%s\"}\n", av_version_info(), LIBAVCODEC_IDENT);
        ret = 0;
    } else {
        msg(AV_LOG_ERROR, "unknown command %s\n", argv[1]);
        ret = AVERROR(EINVAL);
    }
    return ret < 0 ? 1 : 0;
}
