var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
import { AVMEDIA_TYPE_ATTACHMENT, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_VIDEO } from '../constants/constants.js';
import { Codec } from '../lib/codec.js';
import { avGetPixFmtName, avGetSampleFmtName } from '../lib/utilities.js';
import { Demuxer } from './demuxer.js';
/**
 * Map an `AVMediaType` to a readable stream type.
 *
 * @param codecType - The `AVMediaType` value
 *
 * @returns Readable stream type
 *
 * @internal
 */
function mediaTypeToString(codecType) {
    switch (codecType) {
        case AVMEDIA_TYPE_VIDEO:
            return 'video';
        case AVMEDIA_TYPE_AUDIO:
            return 'audio';
        case AVMEDIA_TYPE_SUBTITLE:
            return 'subtitle';
        case AVMEDIA_TYPE_DATA:
            return 'data';
        case AVMEDIA_TYPE_ATTACHMENT:
            return 'attachment';
        default:
            return 'unknown';
    }
}
/**
 * Build a {@link ProbeStream} from a low-level stream.
 *
 * @param stream - The low-level stream to summarize
 *
 * @returns Structured stream info
 *
 * @internal
 */
function buildProbeStream(stream) {
    const par = stream.codecpar;
    const type = mediaTypeToString(par.codecType);
    const codec = Codec.findDecoder(par.codecId);
    const metadata = stream.metadata?.getAll() ?? {};
    const info = {
        index: stream.index,
        type,
        codec: codec?.name ?? 'unknown',
        codecLongName: codec?.longName ?? '',
        codecId: par.codecId,
        bitrate: par.bitRate > 0n ? Number(par.bitRate) : 0,
        metadata,
        language: metadata.language,
        default: (stream.disposition & 0x0001) !== 0,
    };
    if (type === 'video') {
        info.width = par.width;
        info.height = par.height;
        info.pixelFormat = avGetPixFmtName(par.format) ?? undefined;
        const fr = stream.avgFrameRate;
        info.frameRate = fr && fr.den > 0 ? fr.num / fr.den : 0;
        const sar = par.sampleAspectRatio;
        if (sar && sar.num > 0 && sar.den > 0) {
            info.sampleAspectRatio = { num: sar.num, den: sar.den };
        }
    }
    else if (type === 'audio') {
        info.sampleRate = par.sampleRate;
        info.channels = par.channels;
        info.sampleFormat = avGetSampleFmtName(par.format) ?? undefined;
    }
    return info;
}
/**
 * Build the full {@link ProbeResult} from an open demuxer.
 *
 * @param demuxer - An open demuxer with stream info read
 *
 * @returns Structured probe result
 *
 * @internal
 */
function buildProbeResult(demuxer) {
    const streams = demuxer.streams.map(buildProbeStream);
    return {
        format: demuxer.formatName,
        formatLongName: demuxer.formatLongName,
        duration: demuxer.duration,
        startTime: demuxer.startTime,
        bitrate: Math.round(demuxer.bitRate * 1000),
        nbStreams: streams.length,
        streams,
        metadata: demuxer.metadata,
        video: streams.find((s) => s.type === 'video'),
        audio: streams.find((s) => s.type === 'audio'),
    };
}
/**
 * Probe a media source and return structured metadata.
 *
 * Opens the input, reads stream information, builds a typed summary, and closes
 * the input again. Equivalent to `ffprobe -show_format -show_streams`, but as a
 * plain object.
 *
 * @param input - Media source: a file path/URL or an in-memory buffer
 *
 * @param options - Optional format hint and demuxer options
 *
 * @returns Structured probe result
 *
 * @throws {FFmpegError} If the input cannot be opened or has no stream info
 *
 * @example
 * ```typescript
 * const info = await probe('input.mkv');
 * if (info.video) {
 *   console.log(`${info.video.codec} ${info.video.width}x${info.video.height} @ ${info.video.frameRate}fps`);
 * }
 * ```
 *
 * @see {@link probeSync} For the synchronous version
 * @see {@link Demuxer} For full streaming access
 */
// eslint-disable-next-line space-before-function-paren
export async function probe(input, options) {
    const env_1 = { stack: [], error: void 0, hasError: false };
    try {
        const demuxer = __addDisposableResource(env_1, await Demuxer.open(input, options), true);
        return buildProbeResult(demuxer);
    }
    catch (e_1) {
        env_1.error = e_1;
        env_1.hasError = true;
    }
    finally {
        const result_1 = __disposeResources(env_1);
        if (result_1)
            await result_1;
    }
}
/**
 * Probe a media source and return structured metadata synchronously.
 * Synchronous version of {@link probe}.
 *
 * @param input - Media source: a file path/URL or an in-memory buffer
 *
 * @param options - Optional format hint and demuxer options
 *
 * @returns Structured probe result
 *
 * @throws {FFmpegError} If the input cannot be opened or has no stream info
 *
 * @example
 * ```typescript
 * const info = probeSync('input.mkv');
 * console.log(info.duration, info.streams.length);
 * ```
 *
 * @see {@link probe} For the asynchronous version
 */
// eslint-disable-next-line space-before-function-paren
export function probeSync(input, options) {
    const env_2 = { stack: [], error: void 0, hasError: false };
    try {
        const demuxer = __addDisposableResource(env_2, Demuxer.openSync(input, options), false);
        return buildProbeResult(demuxer);
    }
    catch (e_2) {
        env_2.error = e_2;
        env_2.hasError = true;
    }
    finally {
        __disposeResources(env_2);
    }
}
//# sourceMappingURL=probe.js.map