// What the driver's files share; Swift sees only hdff.h.
#ifndef HDFF_INTERNAL_H
#define HDFF_INTERNAL_H

#include "hdff.h"

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

/// Installs the driver's av_log callback, once per process.
void hdff_log_install(void);

/// Whether `input` is one the driver reads: an absolute file path or a
/// loopback preview URL (http://127.0.0.1:<port>/...).
int hdff_input_allowed(const char *input);

/// The options an input is opened with: the protocols it may use (file for a
/// path; http and tcp for a loopback URL, never a redirect elsewhere).
void hdff_input_options(const char *input, AVDictionary **opts);

/// The index of the first video stream that is not cover art, or a negative
/// AVERROR code.
int hdff_video_stream(const AVFormatContext *fmt);

/// Whether this device decodes the stream's codec in hardware. Under the
/// Debug build's test hook HDFF_TEST_FAIL_HW=1 every codec counts as
/// decodable and every hardware open fails before its first frame.
int hdff_hardware_decodes(const AVCodecParameters *par);

/// A video decoder opened hardware first. Until its first frame comes out,
/// a hardware decoder keeps the packets it was sent, so a failure then is
/// retried once in software from the same packets.
typedef struct hdff_decoder {
    AVCodecContext *ctx;
    const AVCodecParameters *par;
    AVRational time_base;
    /// The open is on VideoToolbox.
    int hardware;
    /// A frame has come out.
    int produced;
    /// The frame callback failed; its error is not the decoder's.
    int callback_failed;
    AVPacket **kept;
    int nkept;
} hdff_decoder;

/// Called with each decoded frame; a negative answer stops the decode.
typedef int (*hdff_frame_fn)(void *opaque, AVFrame *frame);

/// Opens a decoder for `par`, whose packets are in `time_base`: on
/// VideoToolbox when the device decodes the codec, else in software.
int hdff_decoder_open(hdff_decoder *d, const AVCodecParameters *par, AVRational time_base);

/// Sends one packet (NULL drains the decoder) and hands every frame that
/// comes out to `fn`. A packet the decoder refuses as invalid after its
/// first frame is skipped, as ffmpeg does. Answers 0 or a negative AVERROR
/// code.
int hdff_decoder_decode(hdff_decoder *d, const AVPacket *pkt, AVFrame *frame, hdff_frame_fn fn, void *opaque);

/// The decoder's name, such as "vp9" or "libdav1d".
const char *hdff_decoder_name(const hdff_decoder *d);

void hdff_decoder_close(hdff_decoder *d);

#endif
