// DropBridgeCloud's AVI reader (shared with FilePaster): opens an AVI file
// with FFmpeg (LGPL build, see build.sh), decodes its video and sound, and hands the frames to
// JavaScript (safari/media/avi-worker.js), which encodes them to MP4 with
// Chrome's own encoder. Video comes out as I420 at the size JavaScript asks
// for, sound as 32-bit float, interleaved.
//
// Calls, in order: fp_open(path), fp_info(), fp_start(...), then fp_next()
// until it returns 0, then fp_close().
#include <emscripten.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/channel_layout.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>

static AVFormatContext *fmt;
static AVCodecContext *vdec, *adec;
static int vi = -1, ai = -1;
static struct SwsContext *sws;
static SwrContext *swr;
static AVPacket *pkt;
static AVFrame *frame;
static int eof, vdone, adone;
static int outW, outH, outRate, outCh;
static uint8_t *vbuf;
static float *abuf;
static int abufCap, abufFrames;
static double ts, fps, startTime;
static long frameCount;
// width, height (square pixels), fps, duration, hasAudio, sampleRate, channels
static double info[8];

static int open_decoder(int index, AVCodecContext **ctx) {
  AVStream *st = fmt->streams[index];
  const AVCodec *codec = avcodec_find_decoder(st->codecpar->codec_id);
  if (!codec) return -1;
  *ctx = avcodec_alloc_context3(codec);
  if (!*ctx || avcodec_parameters_to_context(*ctx, st->codecpar) < 0) return -1;
  (*ctx)->pkt_timebase = st->time_base;
  return avcodec_open2(*ctx, codec, NULL) < 0 ? -1 : 0;
}

// 0 = ready; -1 = can't open; -2 = no video the reader can read; -3 = the
// sound can't be read (the original is then kept, never sent without sound).
EMSCRIPTEN_KEEPALIVE int fp_open(const char *path) {
  av_log_set_level(AV_LOG_ERROR);
  if (avformat_open_input(&fmt, path, NULL, NULL) < 0) return -1;
  if (avformat_find_stream_info(fmt, NULL) < 0) return -1;
  vi = av_find_best_stream(fmt, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
  if (vi < 0 || open_decoder(vi, &vdec) < 0) return -2;
  ai = av_find_best_stream(fmt, AVMEDIA_TYPE_AUDIO, -1, vi, NULL, 0);
  if (ai == AVERROR_STREAM_NOT_FOUND) ai = -1;
  else if (ai < 0 || open_decoder(ai, &adec) < 0) return -3;

  AVStream *vs = fmt->streams[vi];
  AVRational rate = av_guess_frame_rate(fmt, vs, NULL);
  fps = rate.num > 0 && rate.den > 0 ? av_q2d(rate) : 0;
  AVRational sar = av_guess_sample_aspect_ratio(fmt, vs, NULL);
  int w = vdec->width, h = vdec->height;
  if (w <= 0 || h <= 0) return -2;
  double dw = sar.num > 0 && sar.den > 0 ? w * av_q2d(sar) : w;
  double duration = fmt->duration > 0 ? fmt->duration / (double)AV_TIME_BASE
                  : vs->duration > 0 ? vs->duration * av_q2d(vs->time_base) : 0;
  startTime = vs->start_time != AV_NOPTS_VALUE ? vs->start_time * av_q2d(vs->time_base) : 0;
  info[0] = dw; info[1] = h; info[2] = fps; info[3] = duration;
  info[4] = adec ? 1 : 0;
  info[5] = adec ? adec->sample_rate : 0;
  info[6] = adec ? adec->ch_layout.nb_channels : 0;
  pkt = av_packet_alloc();
  frame = av_frame_alloc();
  return pkt && frame ? 0 : -1;
}

EMSCRIPTEN_KEEPALIVE double *fp_info(void) { return info; }

// Output picture size (even numbers) and sound format.
EMSCRIPTEN_KEEPALIVE int fp_start(int w, int h, int rate, int channels) {
  outW = w; outH = h; outRate = rate; outCh = channels;
  vbuf = av_malloc((size_t)w * h * 3 / 2);
  return vbuf ? 0 : -1;
}

EMSCRIPTEN_KEEPALIVE uint8_t *fp_video(void) { return vbuf; }
EMSCRIPTEN_KEEPALIVE float *fp_audio(void) { return abuf; }
EMSCRIPTEN_KEEPALIVE int fp_audio_frames(void) { return abufFrames; }
EMSCRIPTEN_KEEPALIVE double fp_ts(void) { return ts; }

static int emit_video(void) {
  sws = sws_getCachedContext(sws, frame->width, frame->height, frame->format,
                             outW, outH, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  if (!sws) return -1;
  uint8_t *dst[4] = { vbuf, vbuf + outW * outH, vbuf + outW * outH + (outW / 2) * (outH / 2), NULL };
  int lines[4] = { outW, outW / 2, outW / 2, 0 };
  sws_scale(sws, (const uint8_t *const *)frame->data, frame->linesize, 0, frame->height, dst, lines);
  int64_t pts = frame->best_effort_timestamp;
  ts = pts != AV_NOPTS_VALUE ? pts * av_q2d(fmt->streams[vi]->time_base) - startTime
     : fps > 0 ? frameCount / fps : 0;
  frameCount++;
  av_frame_unref(frame);
  return 1;
}

// 2 when there is sound to take, 0 when the converter kept it for later.
static int emit_audio(void) {
  if (!swr) {
    AVChannelLayout in, out;
    if (frame->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
      av_channel_layout_default(&in, frame->ch_layout.nb_channels);
    else
      av_channel_layout_copy(&in, &frame->ch_layout);
    av_channel_layout_default(&out, outCh);
    if (swr_alloc_set_opts2(&swr, &out, AV_SAMPLE_FMT_FLT, outRate, &in, frame->format,
                            frame->sample_rate, 0, NULL) < 0 || swr_init(swr) < 0) return -1;
  }
  int need = swr_get_out_samples(swr, frame->nb_samples);
  if (need > abufCap) {
    av_free(abuf);
    abufCap = need + 4096;
    abuf = av_malloc((size_t)abufCap * outCh * sizeof(float));
    if (!abuf) return -1;
  }
  uint8_t *dst = (uint8_t *)abuf;
  abufFrames = swr_convert(swr, &dst, abufCap, (const uint8_t **)frame->extended_data, frame->nb_samples);
  av_frame_unref(frame);
  if (abufFrames < 0) return -1;
  return abufFrames > 0 ? 2 : 0;
}

// 1 = a video frame (fp_video, fp_ts); 2 = sound (fp_audio, fp_audio_frames);
// 0 = the end; below 0 = an error.
EMSCRIPTEN_KEEPALIVE int fp_next(void) {
  for (;;) {
    int r;
    if (vdec && !vdone) {
      r = avcodec_receive_frame(vdec, frame);
      if (r == 0) return emit_video();
      if (r == AVERROR_EOF) vdone = 1;
      else if (r != AVERROR(EAGAIN)) return -1;
    }
    if (adec && !adone) {
      r = avcodec_receive_frame(adec, frame);
      if (r == 0) { r = emit_audio(); if (r != 0) return r; continue; }
      if (r == AVERROR_EOF) adone = 1;
      else if (r != AVERROR(EAGAIN)) return -1;
    }
    if (eof) {
      if (vdone && (!adec || adone)) return 0;
      continue;
    }
    if (av_read_frame(fmt, pkt) < 0) {
      eof = 1;
      avcodec_send_packet(vdec, NULL);
      if (adec) avcodec_send_packet(adec, NULL);
      continue;
    }
    // A damaged packet is skipped, as players do.
    if (pkt->stream_index == vi) avcodec_send_packet(vdec, pkt);
    else if (adec && pkt->stream_index == ai) avcodec_send_packet(adec, pkt);
    av_packet_unref(pkt);
  }
}

EMSCRIPTEN_KEEPALIVE void fp_close(void) {
  avcodec_free_context(&vdec);
  avcodec_free_context(&adec);
  avformat_close_input(&fmt);
  sws_freeContext(sws); sws = NULL;
  swr_free(&swr);
  av_packet_free(&pkt);
  av_frame_free(&frame);
  av_freep(&vbuf);
  av_freep(&abuf);
  abufCap = abufFrames = 0;
  vi = ai = -1;
  eof = vdone = adone = 0;
  frameCount = 0;
}
