// HyperDrop's C driver over the FFmpeg libraries, compiled into the app target
// and imported into Swift as the module FFmpegDriver (module.modulemap beside
// this file). Each library is its own framework under its upstream name, an
// unmodified FFmpeg and dav1d build (platforms/ios/ffmpeg/build.sh), so a stock
// build of the same versions and configure line replaces it; everything
// HyperDrop adds lives here, and this header names no libav* type.
//
// Every video decode is hardware first: VideoToolbox when
// VTIsHardwareDecodeSupported says this device decodes the codec, a software
// decoder otherwise (libdav1d for AV1; the native av1 decoder only ever drives
// VideoToolbox), and one software retry when the hardware open or decode fails
// before the first frame comes out.
//
// libav's log lines go through the driver's log path: only warnings and worse
// are kept, every "scheme://" token in them is redacted (a loopback preview
// URL carries its secret in its path), and what is left goes to the unified
// log under the subsystem com.gethyperdrop.app, category ffmpeg.
#ifndef HDFF_H
#define HDFF_H

#ifdef __cplusplus
extern "C" {
#endif

/// The FFmpeg release the linked framework was built from, such as "9.1".
const char *hdff_version(void);

/// hdff_selftest_decode's answers when a frame came out.
#define HDFF_DECODED_SOFTWARE 0
#define HDFF_DECODED_HARDWARE 1

/// Decodes the first frame of the best video stream in the file at `path`
/// through the hardware-first open. Answers HDFF_DECODED_HARDWARE or
/// HDFF_DECODED_SOFTWARE by which decoder produced the frame, or a negative
/// AVERROR code when none did.
int hdff_selftest_decode(const char *path);

/// Log levels for hdff_log_line, libav's own numbers.
#define HDFF_LOG_ERROR 16
#define HDFF_LOG_WARNING 24
#define HDFF_LOG_INFO 32

/// Sends one line through the driver's log path, as libav's own lines go:
/// dropped at HDFF_LOG_INFO and above, its scheme:// tokens redacted.
void hdff_log_line(int level, const char *text);

/// What hdff_probe read. Strings are empty when unknown; a missing stream
/// leaves its codec empty.
typedef struct hdff_probe_t {
    /// The demuxer's name list, such as "matroska,webm" or "mov,mp4,m4a,3gp,3g2,mj2".
    char container[64];
    /// The first video stream that is not cover art: libav's codec name
    /// ("h264", "hevc", "vp9", "av1", ...), its profile number (libav's
    /// AV_PROFILE_*, -99 when unknown) and pixel format ("yuv420p",
    /// "yuv420p10le", ...).
    char video_codec[32];
    int profile;
    char pix_fmt[32];
    /// Coded size in pixels.
    int width;
    int height;
    /// Frames per second, 0 when unknown.
    double frame_rate;
    /// Seconds; 0 when unknown.
    double duration;
    /// The first picture's timestamp in seconds (the container's first one
    /// when the file holds no video), 0 when unknown.
    double start_time;
    /// The first audio stream's codec name.
    char audio_codec[32];
    /// Whether VTIsHardwareDecodeSupported says this device decodes the video codec.
    int hardware_decodable;
    /// Whether the container stores no times (a bare H.264 or HEVC stream, as
    /// recorders export it): such a picture is encoded, never copied.
    int untimed;
} hdff_probe_t;

/// Probes an absolute file path or a loopback preview URL
/// (http://127.0.0.1:<port>/...). Answers 0 with *out filled, or a negative
/// AVERROR code. It gives up once `seconds` have passed since it started, so
/// it never outlives its caller's wait.
int hdff_probe(const char *input, double seconds, hdff_probe_t *out);

/// What a conversion does with the picture (hdff_video_plan).
#define HDFF_PLAN_ENCODE 0
#define HDFF_PLAN_COPY_TS 1
#define HDFF_PLAN_COPY_FMP4 2

/// The copy rule. H.264 follows the Mac's segmented `playable`
/// (mediaext/jobs/args.go copiesVideo): in 8-bit 4:2:0 (yuv420p, or yuvj420p)
/// it is copied into MPEG-TS segments. HEVC is copied into fragmented MP4
/// tagged hvc1 only where AVPlayer decodes it: the Main or Main 10 profile in
/// 4:2:0 at 8 or 10 bits (yuv420p, yuv420p10le); any other HEVC (Rext 4:2:2 or
/// 4:4:4, 12-bit, an unknown profile) is encoded, as is everything else.
/// `codec` and `pix_fmt` are libav's names and `profile` its number
/// (AV_PROFILE_*), as hdff_probe reports them.
int hdff_video_plan(const char *codec, int profile, const char *pix_fmt);

/// How a job ended (hdff_wait).
#define HDFF_DONE 0
#define HDFF_CANCELLED 1
#define HDFF_FAILED 2

/// A live conversion's input and output.
typedef struct hdff_options {
    /// An absolute file path or a loopback preview URL.
    const char *input;
    /// The absolute path of the playlist to write; its segments are written
    /// beside it. It must hold no '%': the HLS muxer reads one in a segment
    /// name as a template.
    const char *playlist;
    /// The source second to start at, snapped down to the 2 s segment grid.
    double start_seconds;
    /// The encoded picture's height cap (720, or 480 for a slow conversion).
    int max_height;
    /// Lets the H.264 encoder run in software. Without it, an encode on a
    /// device without a hardware H.264 encoder fails.
    int allow_software_encoder;
    /// Reads the input at this many times real time; 0 reads as fast as it can.
    double read_rate;
} hdff_options;

/// A job's reports, made on the job's own thread.
typedef struct hdff_callbacks {
    void *context;
    /// The source second the output reaches, after each segment's worth of
    /// output and once at the end.
    void (*progress)(void *context, double seconds_written);
    /// Once, when the first picture is decoded for an encode: the decoder's
    /// name ("vp9", "libdav1d", "h264", ...) and whether it is VideoToolbox.
    /// A copy decodes nothing and reports no decoder.
    void (*decoder)(void *context, const char *name, int hardware);
    /// Once, before a failed job ends: a negative AVERROR code (or -1) and
    /// a sentence that names no input.
    void (*failed)(void *context, int code, const char *reason);
} hdff_callbacks;

typedef struct hdff_job hdff_job;

/// Starts converting opt->input into an HLS EVENT playlist at opt->playlist on
/// a thread of its own, in the shape of the Mac's segmented `playable`: 2 s
/// segments, temp_file+independent_segments, `seg%05d.ts` (or `init.mp4` and
/// `seg%05d.m4s` for an HEVC copy), a start on the grid numbered and timed as
/// a run from 0 would be, an encode capped at 30 fps with a keyframe every
/// 2 s, and AAC sound copied (other sound encoded by aac_at at 160 kbit/s).
/// The options are copied. Answers NULL when the job cannot be made.
hdff_job *hdff_convert_start(const hdff_options *opt, hdff_callbacks cb);

/// Asks the job to stop; it ends with HDFF_CANCELLED within a second. Safe to
/// call more than once and from any thread, until hdff_free.
void hdff_cancel(hdff_job *job);

/// Waits for the job's thread to end and answers HDFF_DONE, HDFF_CANCELLED or
/// HDFF_FAILED. Every callback has returned by then. One thread waits.
int hdff_wait(hdff_job *job);

/// Releases a job hdff_wait has answered for.
void hdff_free(hdff_job *job);

#ifdef __cplusplus
}
#endif

#endif
