/*
 * Copyright (c) 2010 Nicolas George
 * Copyright (c) 2011 Stefano Sabatini
 * Copyright (c) 2014 Andrey Utkin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * The Digicam video converter engine (CamPort web engine).
 *
 * DERIVATIVE WORK: derived from CamPort App/Converter.c, which is itself derived from
 * FFmpeg doc/examples/transcode.c (MIT, header above). Kept from Converter.c:
 *   - input open + best video/audio stream selection, decoder setup (err_recognition,
 *     H.264 SHOW_ALL in recovery mode), pkt_timebase;
 *   - prime_video(): decode up to the first admissible video frame to learn the real
 *     size / pix_fmt / SAR / field order, then replay the buffered pre-roll packets;
 *     sidecar display-aspect override (cv_set_display_aspect -> cvw_set_display_aspect);
 *   - timestamp_frame() audio overlap/quantization policy, backward-timestamp policy,
 *     H.264 intra-recovery admission, origin (start_time) subtraction, progress formula;
 *   - output geometry: height rounded to even, width = round(width * SAR) rounded to
 *     even (square pixels: JVC .MOD 720x480 SAR 32:27 -> 854x480, not squashed);
 *   - video filter: [idet,]yadif (same field policy) + scale=W:H + setsar=1 + format;
 *   - audio: anull + buffersink constraints (auto aresample/aformat) -> native AAC
 *     48 kHz stereo 160 kb/s, 1024-sample frames;
 *   - strict mode fails on damaged input (AVERROR_INVALIDDATA); partial mode
 *     (recover=1, = cv_convert_partial) skips damage and stops at the first unreadable
 *     packet.
 * Changed for the web:
 *   - no h264_videotoolbox encoder and no libavformat muxing. Filtered video frames are
 *     I420 (format=yuv420p instead of nv12) and are handed to JS (Module.onVideoFrame),
 *     which encodes them with WebCodecs VideoEncoder. AAC packets go to JS
 *     (Module.onAudioPacket); JS muxes both into MP4 with mp4-muxer.
 *   - the one-shot convert loop is split into cvw_open / cvw_step / cvw_close so a Web
 *     Worker can pump it and apply encoder backpressure between steps.
 *   - single-threaded (no pthreads in this wasm build): decoder/filter threads = 1.
 *   - no watermark, no creation-time metadata, no engine.log file (log lines go to JS).
 *   - all output timestamps are shifted by the AAC encoder priming (initial_padding),
 *     because mp4-muxer rejects negative timestamps and writes no edit list.
 */

#include <emscripten.h>
#include <math.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/channel_layout.h>
#include <libavutil/mem.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>

EM_JS(void, js_video_frame, (const uint8_t *y, int ys, const uint8_t *u, int us, const uint8_t *v, int vs,
                             int w, int h, double pts_us, double dur_us, int full_range), {
    if (Module.onVideoFrame) Module.onVideoFrame(y, ys, u, us, v, vs, w, h, pts_us, dur_us, full_range);
});
EM_JS(void, js_audio_packet, (const uint8_t *data, int size, double pts_us, double dur_us), {
    if (Module.onAudioPacket) Module.onAudioPacket(data, size, pts_us, dur_us);
});
EM_JS(void, js_log, (int level, const char *line), {
    if (Module.onLog) Module.onLog(level, UTF8ToString(line));
});

static int cancelled;
static float progress_value;
static int compact_output;
static int max_out_width; /* 0 = no cap (free web tier caps output width) */
static int forced_aspect_num, forced_aspect_den;
static int64_t origin_us;
static int recovery_mode;
static int is_open, finished, step_frames;
static char last_error[512];
static char info_json[4096];
static int64_t ts_shift_us; /* AAC priming, added to every output timestamp */

EMSCRIPTEN_KEEPALIVE void cvw_set_compact_output(int compact) { compact_output = compact != 0; }
/* Cap the square-pixel output width (height scales to keep the display aspect); 0 = off. */
EMSCRIPTEN_KEEPALIVE void cvw_set_max_width(int width) { max_out_width = width > 0 ? width : 0; }
/* Display aspect from a camcorder sidecar (MOD/TOD .MOI); 0/0 = use the stream's own. */
EMSCRIPTEN_KEEPALIVE void cvw_set_display_aspect(int num, int den) {
    forced_aspect_num = num > 0 && den > 0 ? num : 0;
    forced_aspect_den = num > 0 && den > 0 ? den : 0;
}
EMSCRIPTEN_KEEPALIVE void cvw_cancel(void) { cancelled = 1; }
EMSCRIPTEN_KEEPALIVE float cvw_progress(void) { return progress_value; }
EMSCRIPTEN_KEEPALIVE const char *cvw_last_error(void) { return last_error; }
EMSCRIPTEN_KEEPALIVE const char *cvw_info_json(void) { return info_json; }
EMSCRIPTEN_KEEPALIVE int cvw_is_input_damage(int code) { return code == AVERROR_INVALIDDATA; }

static void web_log(void *ctx, int level, const char *fmt, va_list args) {
    if (level > AV_LOG_INFO) return;
    char line[1024]; int prefix = 1;
    av_log_format_line2(ctx, level, fmt, args, line, sizeof(line), &prefix);
    if (level <= AV_LOG_ERROR) snprintf(last_error, sizeof(last_error), "%s", line);
    js_log(level, line);
}

static AVFormatContext *ifmt_ctx;
typedef struct FilteringContext {
    AVFilterContext *buffersink_ctx;
    AVFilterContext *buffersrc_ctx;
    AVFilterGraph *filter_graph;
    AVPacket *enc_pkt;
    AVFrame *filtered_frame;
} FilteringContext;
static FilteringContext *filter_ctx;

typedef struct StreamContext {
    AVCodecContext *dec_ctx;
    AVCodecContext *enc_ctx;    /* audio: native AAC encoder; video: NULL (WebCodecs) */
    int output_index;
    int h264_intra_recovery;
    int64_t next_pts;
    int64_t last_frame_pts;
    AVFrame *dec_frame;
    /* video output parameters (were enc_ctx fields for h264_videotoolbox) */
    int out_width, out_height;
    AVRational framerate;
    int64_t bit_rate;
    int full_range;
} StreamContext;
static StreamContext *stream_ctx;
static AVPacket **preroll;
static int preroll_count, preroll_cursor;
static AVPacket *packet;
static int video_index = -1, audio_index = -1;
static const char *field_policy = "none";

static int decode_damage(int ret, const AVCodecContext *dec) {
    return ret == AVERROR_INVALIDDATA || (ret == -1 && dec->codec_id == AV_CODEC_ID_DVVIDEO);
}
// SHOW_ALL also exposes unusable pre-roll. Admit only a clean intra boundary,
// then frames without decoder-reported missing references or concealment.
static int admit_recovery_frame(StreamContext *stream, AVFrame *frame) {
    if (!recovery_mode || stream->dec_ctx->codec_id != AV_CODEC_ID_H264) return 1;
    if (!(frame->flags & AV_FRAME_FLAG_CORRUPT)) {
        stream->h264_intra_recovery = 0;
        return 1;
    }
    if (frame->decode_error_flags) {
        stream->h264_intra_recovery = 0;
        av_log(NULL, AV_LOG_WARNING, "H264_PREROLL_SKIP pts=%lld errors=%d\n", (long long)frame->best_effort_timestamp, frame->decode_error_flags);
        return 0;
    }
    if (frame->pict_type == AV_PICTURE_TYPE_I) {
        stream->h264_intra_recovery = 1;
        av_log(NULL, AV_LOG_INFO, "H264_INTRA_RECOVERY pts=%lld\n", (long long)frame->best_effort_timestamp);
    }
    return stream->h264_intra_recovery;
}
static int prime_video(void) {
    int vi = video_index, ret = 0; int64_t bytes = 0;
    if (vi < 0) return AVERROR_STREAM_NOT_FOUND;
    AVCodecContext *dec = stream_ctx[vi].dec_ctx;
    AVFrame *frame = av_frame_alloc();
    const int max_preroll_packets = 4096;
    preroll = av_calloc(max_preroll_packets, sizeof(*preroll));
    if (!frame || !preroll) { av_frame_free(&frame); return AVERROR(ENOMEM); }
    int found = 0;
    while (!found && preroll_count < max_preroll_packets && bytes < 32*1024*1024) {
        if (cancelled) { ret=AVERROR_EXIT; break; }
        AVPacket *p = av_packet_alloc();
        if (!p) { ret=AVERROR(ENOMEM); break; }
        ret=av_read_frame(ifmt_ctx,p);
        if (ret < 0) { av_packet_free(&p); break; }
        preroll[preroll_count++]=p; bytes+=p->size;
        if (p->stream_index != vi) continue;
        if (!recovery_mode && (p->flags & AV_PKT_FLAG_CORRUPT)) { ret=AVERROR_INVALIDDATA; break; }
        ret=avcodec_send_packet(dec,p);
        if (recovery_mode && ret == AVERROR_INVALIDDATA) continue;
        if (ret < 0) break;
        ret=avcodec_receive_frame(dec,frame);
        if (ret == AVERROR(EAGAIN) || (recovery_mode && ret == AVERROR_INVALIDDATA)) continue;
        if (ret < 0) break;
        if (!admit_recovery_frame(&stream_ctx[vi], frame)) { av_frame_unref(frame); continue; }
        found=1;
    }
    if (!found && ret == AVERROR_EOF) {
        ret=avcodec_send_packet(dec,NULL);
        if (ret>=0) { ret=avcodec_receive_frame(dec,frame); found=ret>=0 && admit_recovery_frame(&stream_ctx[vi], frame); }
    }
    av_log(NULL, AV_LOG_INFO, "PREROLL packets=%d bytes=%lld found=%d recovery=%d\n", preroll_count, (long long)bytes, found, recovery_mode);
    if (found) {
        dec->width=frame->width; dec->height=frame->height; dec->pix_fmt=frame->format;
        if (dec->codec_id == AV_CODEC_ID_MJPEG) {
            dec->color_range = frame->color_range;
            dec->colorspace = frame->colorspace;
            dec->color_primaries = frame->color_primaries;
            dec->color_trc = frame->color_trc;
        }
        AVRational aspect=av_guess_sample_aspect_ratio(ifmt_ctx,ifmt_ctx->streams[vi],frame);
        dec->sample_aspect_ratio = aspect.num > 0 && aspect.den > 0 ? aspect : (AVRational){1, 1};
        if (forced_aspect_num > 0 && forced_aspect_den > 0 && frame->width > 0 && frame->height > 0) {
            av_reduce(&dec->sample_aspect_ratio.num, &dec->sample_aspect_ratio.den,
                      (int64_t)forced_aspect_num * frame->height, (int64_t)forced_aspect_den * frame->width, 1 << 30);
            av_log(NULL, AV_LOG_INFO, "SIDECAR_ASPECT dar=%d:%d sar=%d/%d\n", forced_aspect_num, forced_aspect_den, dec->sample_aspect_ratio.num, dec->sample_aspect_ratio.den);
        }
        if (frame->flags & AV_FRAME_FLAG_INTERLACED)
            dec->field_order=(frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST) ? AV_FIELD_TT : AV_FIELD_BB;
        av_log(NULL,AV_LOG_INFO,"FIRST_FRAME width=%d height=%d SAR=%d/%d order=%d\n",dec->width,dec->height,dec->sample_aspect_ratio.num,dec->sample_aspect_ratio.den,dec->field_order);
        avcodec_flush_buffers(dec); stream_ctx[vi].h264_intra_recovery=0; ret=0;
    } else if (ret>=0 || ret==AVERROR(EAGAIN) || ret==AVERROR_EOF) ret=AVERROR_INVALIDDATA;
    av_frame_free(&frame); return ret;
}
static int timestamp_frame(StreamContext *stream) {
    AVFrame *f=stream->dec_frame;
    int64_t pts=f->best_effort_timestamp;
    if (pts==AV_NOPTS_VALUE) pts=stream->next_pts;
    if (pts==AV_NOPTS_VALUE) pts=av_rescale_q(origin_us,AV_TIME_BASE_Q,stream->dec_ctx->pkt_timebase);
    int64_t step=stream->dec_ctx->codec_type==AVMEDIA_TYPE_AUDIO ?
        av_rescale_q(f->nb_samples,(AVRational){1,stream->dec_ctx->sample_rate},stream->dec_ctx->pkt_timebase) : f->duration;
    if (step<=0) {
        AVRational unit=stream->dec_ctx->codec_type==AVMEDIA_TYPE_AUDIO ?
            (AVRational){f->nb_samples,stream->dec_ctx->sample_rate} : av_inv_q(stream->framerate);
        step=av_rescale_q(1,unit,stream->dec_ctx->pkt_timebase);
    }
    // Same quantization tolerance as Converter.c (CLIP0006 note there).
    int64_t audio_tolerance = FFMAX(2, av_rescale_q_rnd(1, (AVRational){1,1000},
        stream->dec_ctx->pkt_timebase, AV_ROUND_UP));
    if (stream->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO && stream->next_pts != AV_NOPTS_VALUE && pts < stream->next_pts && pts >= stream->next_pts-audio_tolerance)
        av_log(NULL, AV_LOG_VERBOSE, "AUDIO_TIMESTAMP_QUANTIZATION ticks=%lld tolerance=%lld\n", (long long)(stream->next_pts-pts), (long long)audio_tolerance);
    if (stream->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO && stream->next_pts != AV_NOPTS_VALUE && pts < stream->next_pts-audio_tolerance) {
        av_log(NULL, AV_LOG_WARNING, "INPUT_AUDIO_OVERLAP pts=%lld expected=%lld\n", (long long)pts, (long long)stream->next_pts);
        if (!recovery_mode) return AVERROR_INVALIDDATA;
        pts=stream->next_pts;
    }
    stream->next_pts=pts+FFMAX(step,1);
    f->pts=pts;
    return 0;
}

static int open_input_file(const char *filename)
{
    int ret;
    unsigned int i;

    ifmt_ctx = NULL;
    if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
        return ret;
    }
    if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
        return ret;
    }
    stream_ctx = av_calloc(ifmt_ctx->nb_streams, sizeof(*stream_ctx));
    if (!stream_ctx)
        return AVERROR(ENOMEM);

    video_index = av_find_best_stream(ifmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if (video_index < 0) return video_index;
    audio_index = av_find_best_stream(ifmt_ctx, AVMEDIA_TYPE_AUDIO, -1, video_index, NULL, 0);
    if (audio_index < 0 && audio_index != AVERROR_STREAM_NOT_FOUND) return audio_index;
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        stream_ctx[i].output_index = -1;
        stream_ctx[i].next_pts = AV_NOPTS_VALUE;
        stream_ctx[i].last_frame_pts = AV_NOPTS_VALUE;
        if ((int)i != video_index && (int)i != audio_index) continue;
        AVStream *stream = ifmt_ctx->streams[i];
        const AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
        AVCodecContext *codec_ctx;
        if (!dec) {
            av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream #%u (%s)\n", i, avcodec_get_name(stream->codecpar->codec_id));
            return AVERROR_DECODER_NOT_FOUND;
        }
        codec_ctx = avcodec_alloc_context3(dec);
        if (!codec_ctx) return AVERROR(ENOMEM);
        ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
        if (ret < 0) return ret;
        codec_ctx->pkt_timebase = stream->time_base;
        codec_ctx->thread_count = 1; /* Converter.c: 2; this wasm build has no threads */
        codec_ctx->err_recognition = recovery_mode ? 0 : AV_EF_CRCCHECK | AV_EF_EXPLODE;
        if (recovery_mode && codec_ctx->codec_id == AV_CODEC_ID_H264) codec_ctx->flags2 |= AV_CODEC_FLAG2_SHOW_ALL;
        if (!codec_ctx->sample_aspect_ratio.num || !codec_ctx->sample_aspect_ratio.den)
            codec_ctx->sample_aspect_ratio = (AVRational){1, 1};
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
            codec_ctx->framerate = av_guess_frame_rate(ifmt_ctx, stream, NULL);
        ret = avcodec_open2(codec_ctx, dec, NULL);
        if (ret < 0) {
            av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
            avcodec_free_context(&codec_ctx);
            return ret;
        }
        stream_ctx[i].dec_ctx = codec_ctx;
        stream_ctx[i].dec_frame = av_frame_alloc();
        if (!stream_ctx[i].dec_frame)
            return AVERROR(ENOMEM);
    }
    origin_us = ifmt_ctx->start_time == AV_NOPTS_VALUE ? 0 : ifmt_ctx->start_time;
    av_dump_format(ifmt_ctx, 0, filename, 0);
    return 0;
}

/* Replaces open_output_file(): same output geometry / rate / bitrate decisions, but the
   video "encoder" is described for JS instead of opened, and no muxer is created. */
static int open_outputs(void)
{
    int ret;
    for (unsigned i = 0; i < ifmt_ctx->nb_streams; i++) {
        StreamContext *s = &stream_ctx[i];
        if (!s->dec_ctx) continue;
        AVStream *in_stream = ifmt_ctx->streams[i];
        AVCodecContext *dec_ctx = s->dec_ctx;
        if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
            s->output_index = 0;
            s->out_height = (dec_ctx->height + 1) & ~1;
            s->out_width = ((int)lrint(dec_ctx->width * av_q2d(dec_ctx->sample_aspect_ratio)) + 1) & ~1;
            if (s->out_width <= 0 || s->out_width > 4096 || s->out_height > 4096) return AVERROR(EINVAL);
            if (max_out_width > 0 && s->out_width > max_out_width) {
                s->out_height = ((int)lrint((double)s->out_height * max_out_width / s->out_width) + 1) & ~1;
                s->out_width = max_out_width & ~1;
            }
            s->framerate = av_guess_frame_rate(ifmt_ctx, in_stream, NULL);
            if (s->framerate.num <= 0 || s->framerate.den <= 0)
                s->framerate = (AVRational){30,1};
            s->bit_rate = FFMAX(1500000, (int64_t)s->out_width * s->out_height * 4);
            s->full_range = 0;
            if (dec_ctx->codec_id == AV_CODEC_ID_MJPEG) {
                s->bit_rate = FFMAX(s->bit_rate, in_stream->codecpar->bit_rate);
                s->full_range = dec_ctx->color_range == AVCOL_RANGE_JPEG ||
                    dec_ctx->pix_fmt == AV_PIX_FMT_YUVJ420P || dec_ctx->pix_fmt == AV_PIX_FMT_YUVJ422P || dec_ctx->pix_fmt == AV_PIX_FMT_YUVJ444P;
            }
            if (compact_output) s->bit_rate = FFMAX(1500000, s->bit_rate * 2 / 3);
            av_log(NULL, AV_LOG_INFO, "ENCODER_QUALITY source_video_bps=%lld target_bps=%lld out=%dx%d rate=%d/%d\n",
                   (long long)in_stream->codecpar->bit_rate, (long long)s->bit_rate, s->out_width, s->out_height, s->framerate.num, s->framerate.den);
        } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            const AVCodec *encoder = avcodec_find_encoder(AV_CODEC_ID_AAC);
            if (!encoder) { av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n"); return AVERROR_INVALIDDATA; }
            AVCodecContext *enc_ctx = avcodec_alloc_context3(encoder);
            if (!enc_ctx) return AVERROR(ENOMEM);
            s->output_index = 1;
            enc_ctx->sample_rate = 48000;
            enc_ctx->bit_rate = 160000;
            av_channel_layout_default(&enc_ctx->ch_layout, 2);
            enc_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP; /* native aac: sample_fmts[0] */
            enc_ctx->time_base = (AVRational){1, enc_ctx->sample_rate};
            enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; /* MP4: AudioSpecificConfig in extradata */
            s->enc_ctx = enc_ctx;
            ret = avcodec_open2(enc_ctx, encoder, NULL);
            if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open aac encoder\n"); return ret; }
            ts_shift_us = av_rescale_q(enc_ctx->initial_padding, enc_ctx->time_base, (AVRational){1, 1000000});
        }
    }
    return 0;
}

EMSCRIPTEN_KEEPALIVE const uint8_t *cvw_audio_config(void) {
    return audio_index >= 0 && stream_ctx && stream_ctx[audio_index].enc_ctx ? stream_ctx[audio_index].enc_ctx->extradata : NULL;
}
EMSCRIPTEN_KEEPALIVE int cvw_audio_config_size(void) {
    return audio_index >= 0 && stream_ctx && stream_ctx[audio_index].enc_ctx ? stream_ctx[audio_index].enc_ctx->extradata_size : 0;
}

static int init_filter(FilteringContext* fctx, AVCodecContext *dec_ctx,
        AVCodecContext *enc_ctx, const char *filter_spec)
{
    char args[512];
    int ret = 0;
    const AVFilter *buffersrc = NULL;
    const AVFilter *buffersink = NULL;
    AVFilterContext *buffersrc_ctx = NULL;
    AVFilterContext *buffersink_ctx = NULL;
    AVFilterInOut *outputs = avfilter_inout_alloc();
    AVFilterInOut *inputs  = avfilter_inout_alloc();
    AVFilterGraph *filter_graph = avfilter_graph_alloc();

    if (filter_graph) filter_graph->nb_threads = 1;
    if (!outputs || !inputs || !filter_graph) { ret = AVERROR(ENOMEM); goto end; }

    if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
        buffersrc = avfilter_get_by_name("buffer");
        buffersink = avfilter_get_by_name("buffersink");
        if (!buffersrc || !buffersink) { ret = AVERROR_UNKNOWN; goto end; }
        snprintf(args, sizeof(args),
                "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
                dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
                dec_ctx->pkt_timebase.num, dec_ctx->pkt_timebase.den,
                dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
        ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in", args, NULL, filter_graph);
        if (ret < 0) goto end;
        ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out", NULL, NULL, filter_graph);
        if (ret < 0) goto end;
        enum AVPixelFormat out_fmt = AV_PIX_FMT_YUV420P; /* Converter.c: NV12 for VideoToolbox */
        ret = av_opt_set_bin(buffersink_ctx, "pix_fmts", (uint8_t*)&out_fmt, sizeof(out_fmt), AV_OPT_SEARCH_CHILDREN);
        if (ret < 0) goto end;
    } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
        char buf[64];
        buffersrc = avfilter_get_by_name("abuffer");
        buffersink = avfilter_get_by_name("abuffersink");
        if (!buffersrc || !buffersink) { ret = AVERROR_UNKNOWN; goto end; }
        if (dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
            av_channel_layout_default(&dec_ctx->ch_layout, dec_ctx->ch_layout.nb_channels);
        av_channel_layout_describe(&dec_ctx->ch_layout, buf, sizeof(buf));
        snprintf(args, sizeof(args),
                "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=%s",
                dec_ctx->pkt_timebase.num, dec_ctx->pkt_timebase.den, dec_ctx->sample_rate,
                av_get_sample_fmt_name(dec_ctx->sample_fmt), buf);
        ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in", args, NULL, filter_graph);
        if (ret < 0) goto end;
        ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out", NULL, NULL, filter_graph);
        if (ret < 0) goto end;
        ret = av_opt_set_bin(buffersink_ctx, "sample_fmts", (uint8_t*)&enc_ctx->sample_fmt, sizeof(enc_ctx->sample_fmt), AV_OPT_SEARCH_CHILDREN);
        if (ret < 0) goto end;
        av_channel_layout_describe(&enc_ctx->ch_layout, buf, sizeof(buf));
        ret = av_opt_set(buffersink_ctx, "ch_layouts", buf, AV_OPT_SEARCH_CHILDREN);
        if (ret < 0) goto end;
        ret = av_opt_set_bin(buffersink_ctx, "sample_rates", (uint8_t*)&enc_ctx->sample_rate, sizeof(enc_ctx->sample_rate), AV_OPT_SEARCH_CHILDREN);
        if (ret < 0) goto end;
    } else {
        ret = AVERROR_UNKNOWN;
        goto end;
    }

    outputs->name       = av_strdup("in");
    outputs->filter_ctx = buffersrc_ctx;
    outputs->pad_idx    = 0;
    outputs->next       = NULL;
    inputs->name       = av_strdup("out");
    inputs->filter_ctx = buffersink_ctx;
    inputs->pad_idx    = 0;
    inputs->next       = NULL;
    if (!outputs->name || !inputs->name) { ret = AVERROR(ENOMEM); goto end; }

    if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec, &inputs, &outputs, NULL)) < 0)
        goto end;
    if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
        goto end;

    fctx->buffersrc_ctx = buffersrc_ctx;
    fctx->buffersink_ctx = buffersink_ctx;
    fctx->filter_graph = filter_graph;
end:
    if (ret < 0) avfilter_graph_free(&filter_graph);
    avfilter_inout_free(&inputs);
    avfilter_inout_free(&outputs);
    return ret;
}

static int init_filters(void)
{
    const char *filter_spec;
    char video_filter[512];
    int ret;
    filter_ctx = av_calloc(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
    if (!filter_ctx)
        return AVERROR(ENOMEM);
    for (unsigned i = 0; i < ifmt_ctx->nb_streams; i++) {
        if (!stream_ctx[i].dec_ctx)
            continue;
        if (ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            enum AVFieldOrder order = stream_ctx[i].dec_ctx->field_order;
            const char *deinterlace = order == AV_FIELD_PROGRESSIVE ? "" :
                order == AV_FIELD_UNKNOWN ? "idet,yadif=mode=send_frame:parity=auto:deint=interlaced," :
                "yadif=mode=send_frame:parity=auto:deint=all,";
            field_policy = order == AV_FIELD_PROGRESSIVE ? "none (progressive)" :
                order == AV_FIELD_UNKNOWN ? "idet + yadif on frames detected as interlaced" :
                "yadif on every frame (stream is flagged interlaced)";
            av_log(NULL, AV_LOG_INFO, "FIELD_POLICY stream=%u order=%d filter=%s\n", i, order, deinterlace);
            snprintf(video_filter, sizeof(video_filter), "%sscale=%d:%d,setsar=1,format=yuv420p", deinterlace, stream_ctx[i].out_width, stream_ctx[i].out_height);
            filter_spec = video_filter;
        }
        else
            filter_spec = "anull";
        ret = init_filter(&filter_ctx[i], stream_ctx[i].dec_ctx, stream_ctx[i].enc_ctx, filter_spec);
        if (ret)
            return ret;
        if (stream_ctx[i].enc_ctx && stream_ctx[i].enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)
            av_buffersink_set_frame_size(filter_ctx[i].buffersink_ctx, stream_ctx[i].enc_ctx->frame_size);
        filter_ctx[i].enc_pkt = av_packet_alloc();
        filter_ctx[i].filtered_frame = av_frame_alloc();
        if (!filter_ctx[i].enc_pkt || !filter_ctx[i].filtered_frame)
            return AVERROR(ENOMEM);
    }
    return 0;
}

/* Replaces encode_write_frame(): video -> JS (WebCodecs); audio -> AAC -> JS (mp4-muxer). */
static int emit_frame(unsigned int stream_index, int flush)
{
    StreamContext *stream = &stream_ctx[stream_index];
    FilteringContext *filter = &filter_ctx[stream_index];
    AVFrame *f = flush ? NULL : filter->filtered_frame;
    int ret;

    if (stream->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
        if (!f) return 0; /* JS flushes its VideoEncoder */
        int64_t pts_us = f->pts == AV_NOPTS_VALUE ? 0 : av_rescale_q(f->pts, f->time_base, (AVRational){1, 1000000});
        double dur_us = 1e6 * stream->framerate.den / stream->framerate.num;
        js_video_frame(f->data[0], f->linesize[0], f->data[1], f->linesize[1], f->data[2], f->linesize[2],
                       f->width, f->height, (double)(pts_us + ts_shift_us), dur_us, stream->full_range);
        step_frames++;
        return 0;
    }

    AVPacket *enc_pkt = filter->enc_pkt;
    av_packet_unref(enc_pkt);
    if (f && f->pts != AV_NOPTS_VALUE)
        f->pts = av_rescale_q(f->pts, f->time_base, stream->enc_ctx->time_base);
    ret = avcodec_send_frame(stream->enc_ctx, f);
    if (ret < 0)
        return ret;
    while (ret >= 0) {
        ret = avcodec_receive_packet(stream->enc_ctx, enc_pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return 0;
        if (ret < 0) return ret;
        int64_t pts_us = av_rescale_q(enc_pkt->pts, stream->enc_ctx->time_base, (AVRational){1, 1000000}) + ts_shift_us;
        int64_t dur_us = av_rescale_q(enc_pkt->duration, stream->enc_ctx->time_base, (AVRational){1, 1000000});
        if (pts_us >= 0) js_audio_packet(enc_pkt->data, enc_pkt->size, (double)pts_us, (double)dur_us);
        av_packet_unref(enc_pkt);
    }
    return ret;
}

static int filter_emit_frame(AVFrame *frame, unsigned int stream_index)
{
    FilteringContext *filter = &filter_ctx[stream_index];
    int ret = av_buffersrc_add_frame_flags(filter->buffersrc_ctx, frame, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
        return ret;
    }
    while (1) {
        ret = av_buffersink_get_frame(filter->buffersink_ctx, filter->filtered_frame);
        if (ret < 0) {
            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                ret = 0;
            break;
        }
        filter->filtered_frame->time_base = av_buffersink_get_time_base(filter->buffersink_ctx);
        filter->filtered_frame->pict_type = AV_PICTURE_TYPE_NONE;
        ret = emit_frame(stream_index, 0);
        av_frame_unref(filter->filtered_frame);
        if (ret < 0)
            break;
    }
    return ret;
}

static void update_progress(StreamContext *stream) {
    if (stream->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO && ifmt_ctx->duration > 0)
        progress_value = fminf(0.99f, fmaxf(0, (float)(stream->dec_frame->pts * av_q2d(stream->dec_ctx->pkt_timebase) / (ifmt_ctx->duration / (double)AV_TIME_BASE))));
}

/* Body of one decoded frame in Converter.c's read loop / flush loop. Returns <0 on error,
   0 when the frame was consumed or skipped. */
static int handle_decoded(StreamContext *stream, unsigned int stream_index, int flushing) {
    int ret;
    if (!admit_recovery_frame(stream, stream->dec_frame)) { av_frame_unref(stream->dec_frame); return 0; }
    ret=timestamp_frame(stream); if (ret<0) return ret;
    if (stream->last_frame_pts != AV_NOPTS_VALUE && stream->dec_frame->pts <= stream->last_frame_pts) {
        if (!flushing) av_log(NULL, AV_LOG_WARNING, "INPUT_TIMESTAMP_BACKWARD stream=%u\n", stream_index);
        if (!recovery_mode) return AVERROR_INVALIDDATA;
        av_frame_unref(stream->dec_frame); return 0;
    }
    stream->last_frame_pts=stream->dec_frame->pts;
    if (stream->dec_frame->pts != AV_NOPTS_VALUE) {
        stream->dec_frame->pts -= av_rescale_q(origin_us, AV_TIME_BASE_Q, stream->dec_ctx->pkt_timebase);
        update_progress(stream);
    }
    return filter_emit_frame(stream->dec_frame, stream_index);
}

static int flush_all(void) {
    int ret = 0;
    for (unsigned i = 0; i < ifmt_ctx->nb_streams; i++) {
        if (!filter_ctx[i].filter_graph) continue;
        StreamContext *stream = &stream_ctx[i];
        ret = avcodec_send_packet(stream->dec_ctx, NULL);
        if (recovery_mode && decode_damage(ret, stream->dec_ctx)) goto flush_filters;
        if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing decoding failed\n"); return ret; }
        while (ret >= 0) {
            ret = avcodec_receive_frame(stream->dec_ctx, stream->dec_frame);
            if (ret == AVERROR_EOF || (recovery_mode && decode_damage(ret, stream->dec_ctx)))
                break;
            else if (ret < 0)
                return ret;
            ret = handle_decoded(stream, i, 1);
            if (ret < 0) return ret;
        }
flush_filters:
        ret = filter_emit_frame(NULL, i);
        if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n"); return ret; }
        if (stream->enc_ctx && (stream->enc_ctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {
            ret = emit_frame(i, 1);
            if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n"); return ret; }
        }
    }
    return 0;
}

static const char *field_order_name(enum AVFieldOrder o) {
    switch (o) {
    case AV_FIELD_PROGRESSIVE: return "progressive";
    case AV_FIELD_TT: return "tt"; case AV_FIELD_BB: return "bb";
    case AV_FIELD_TB: return "tb"; case AV_FIELD_BT: return "bt";
    default: return "unknown";
    }
}

static void build_info(void) {
    StreamContext *v = &stream_ctx[video_index];
    AVStream *vs = ifmt_ctx->streams[video_index];
    AVRational stream_sar = vs->codecpar->sample_aspect_ratio;
    int dar_n = 0, dar_d = 0;
    av_reduce(&dar_n, &dar_d, (int64_t)v->dec_ctx->width * v->dec_ctx->sample_aspect_ratio.num,
              (int64_t)v->dec_ctx->height * v->dec_ctx->sample_aspect_ratio.den, 1 << 20);
    char audio[512] = "null";
    if (audio_index >= 0) {
        AVCodecContext *a = stream_ctx[audio_index].dec_ctx;
        snprintf(audio, sizeof(audio),
                 "{\"codec\":\"%s\",\"codecLong\":\"%s\",\"sampleRate\":%d,\"channels\":%d,\"sampleFmt\":\"%s\",\"bitRate\":%lld}",
                 avcodec_get_name(a->codec_id), a->codec && a->codec->long_name ? a->codec->long_name : "",
                 a->sample_rate, a->ch_layout.nb_channels, av_get_sample_fmt_name(a->sample_fmt) ? av_get_sample_fmt_name(a->sample_fmt) : "",
                 (long long)ifmt_ctx->streams[audio_index]->codecpar->bit_rate);
    }
    snprintf(info_json, sizeof(info_json),
        "{\"container\":\"%s\",\"containerLong\":\"%s\",\"duration\":%.3f,\"recovery\":%d,"
        "\"video\":{\"codec\":\"%s\",\"codecLong\":\"%s\",\"width\":%d,\"height\":%d,\"pixFmt\":\"%s\","
        "\"streamSar\":\"%d:%d\",\"sar\":\"%d:%d\",\"displayAspect\":\"%d:%d\",\"sidecarAspect\":\"%d:%d\","
        "\"fps\":%.4f,\"fpsRational\":\"%d/%d\",\"fieldOrder\":\"%s\",\"deinterlace\":\"%s\",\"bitRate\":%lld,"
        "\"outWidth\":%d,\"outHeight\":%d,\"targetBitRate\":%lld,\"fullRange\":%d},"
        "\"audio\":%s,\"audioOut\":%s}",
        ifmt_ctx->iformat->name, ifmt_ctx->iformat->long_name ? ifmt_ctx->iformat->long_name : "",
        ifmt_ctx->duration > 0 ? ifmt_ctx->duration / (double)AV_TIME_BASE : 0.0, recovery_mode,
        avcodec_get_name(v->dec_ctx->codec_id), v->dec_ctx->codec && v->dec_ctx->codec->long_name ? v->dec_ctx->codec->long_name : "",
        v->dec_ctx->width, v->dec_ctx->height,
        av_get_pix_fmt_name(v->dec_ctx->pix_fmt) ? av_get_pix_fmt_name(v->dec_ctx->pix_fmt) : "",
        stream_sar.num, stream_sar.den, v->dec_ctx->sample_aspect_ratio.num, v->dec_ctx->sample_aspect_ratio.den,
        dar_n, dar_d, forced_aspect_num, forced_aspect_den,
        /* 0/0 framerate (unknown) would print "nan" and break the JSON */
        v->framerate.num > 0 && v->framerate.den > 0 ? av_q2d(v->framerate) : 0.0, v->framerate.num, v->framerate.den,
        field_order_name(v->dec_ctx->field_order), field_policy, (long long)vs->codecpar->bit_rate,
        v->out_width, v->out_height, (long long)v->bit_rate, v->full_range,
        audio, audio_index >= 0 ? "{\"codec\":\"aac\",\"sampleRate\":48000,\"channels\":2,\"bitRate\":160000}" : "null");
}

EMSCRIPTEN_KEEPALIVE void cvw_close(void) {
    for (int n=0;n<preroll_count;++n) av_packet_free(&preroll[n]);
    av_freep(&preroll); preroll_count = preroll_cursor = 0;
    av_packet_free(&packet);
    for (unsigned i = 0; ifmt_ctx && stream_ctx && i < ifmt_ctx->nb_streams; i++) {
        avcodec_free_context(&stream_ctx[i].dec_ctx);
        avcodec_free_context(&stream_ctx[i].enc_ctx);
        if (filter_ctx && filter_ctx[i].filter_graph) {
            avfilter_graph_free(&filter_ctx[i].filter_graph);
            av_packet_free(&filter_ctx[i].enc_pkt);
            av_frame_free(&filter_ctx[i].filtered_frame);
        }
        av_frame_free(&stream_ctx[i].dec_frame);
    }
    av_freep(&filter_ctx);
    av_freep(&stream_ctx);
    avformat_close_input(&ifmt_ctx);
    is_open = 0; finished = 0;
    video_index = audio_index = -1;
}

/* Opens input, primes video, prepares filters + AAC encoder. recover=1 mirrors
   cv_convert_partial. Returns 0 or a negative AVERROR; info via cvw_info_json(). */
EMSCRIPTEN_KEEPALIVE int cvw_open(const char *input, int recover) {
    int ret;
    if (is_open) cvw_close();
    recovery_mode = recover;
    cancelled = 0; progress_value = 0; finished = 0; ts_shift_us = 0;
    last_error[0] = 0; info_json[0] = 0; field_policy = "none";
    av_log_set_callback(web_log);
    av_log_set_level(AV_LOG_INFO);
    is_open = 1;
    if ((ret = open_input_file(input)) < 0) goto fail;
    if ((ret = prime_video()) < 0) goto fail;
    if ((ret = open_outputs()) < 0) goto fail;
    if ((ret = init_filters()) < 0) goto fail;
    if (!(packet = av_packet_alloc())) { ret = AVERROR(ENOMEM); goto fail; }
    build_info();
    return 0;
fail:
    if (!last_error[0] || ret != AVERROR_INVALIDDATA) {
        char e[128]; av_strerror(ret, e, sizeof(e));
        if (!last_error[0]) snprintf(last_error, sizeof(last_error), "%s", e);
    }
    if (ifmt_ctx && stream_ctx && video_index >= 0 && stream_ctx[video_index].dec_ctx) build_info();
    cvw_close();
    return ret;
}

/* Pumps demux -> decode -> filter (-> AAC) until max_frames video frames were handed to
   JS. Returns 1 = more to do, 0 = finished (flushed), <0 = AVERROR (call cvw_close). */
EMSCRIPTEN_KEEPALIVE int cvw_step(int max_frames) {
    int ret;
    if (!is_open) return AVERROR(EINVAL);
    if (finished) return 0;
    step_frames = 0;
    while (step_frames < max_frames) {
        if (cancelled) return AVERROR_EXIT;
        if (preroll_cursor < preroll_count) {
            av_packet_move_ref(packet,preroll[preroll_cursor++]); ret=0;
        } else ret = av_read_frame(ifmt_ctx, packet);
        if (ret == AVERROR_EOF || (recovery_mode && ret == AVERROR_INVALIDDATA)) {
            ret = flush_all();
            if (ret < 0) goto fail;
            finished = 1; progress_value = 1;
            return 0;
        }
        if (ret < 0) goto fail;
        unsigned stream_index = packet->stream_index;
        if (stream_ctx[stream_index].output_index < 0) { av_packet_unref(packet); continue; }
        if (!recovery_mode && (packet->flags & AV_PKT_FLAG_CORRUPT)) { ret=AVERROR_INVALIDDATA; goto fail; }
        if (filter_ctx[stream_index].filter_graph) {
            StreamContext *stream = &stream_ctx[stream_index];
            ret = avcodec_send_packet(stream->dec_ctx, packet);
            if (recovery_mode && decode_damage(ret, stream->dec_ctx)) { av_packet_unref(packet); continue; }
            if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); goto fail; }
            while (ret >= 0) {
                ret = avcodec_receive_frame(stream->dec_ctx, stream->dec_frame);
                if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
                    break;
                else if (recovery_mode && decode_damage(ret, stream->dec_ctx)) break;
                else if (ret < 0) goto fail;
                ret = handle_decoded(stream, stream_index, 0);
                if (ret < 0) goto fail;
            }
        }
        av_packet_unref(packet);
    }
    return 1;
fail:
    av_packet_unref(packet);
    {
        char e[128]; av_strerror(ret, e, sizeof(e));
        if (!last_error[0]) snprintf(last_error, sizeof(last_error), "%s", e);
    }
    return ret;
}
