openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
149 lines (148 loc) • 5.74 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { m as asSafeIntegerInRange, p as asPositiveSafeInteger } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { i as runFfprobe } from "./ffmpeg-exec-DAuj0BaS.mjs";
import fs from "node:fs/promises";
//#region src/media/media-probe.ts
function parseDurationMs(e) {
if (typeof e !== "number" && typeof e !== "string") return;
const t = typeof e === "number" ? e : Number(e.trim());
if (!Number.isFinite(t) || t <= 0) return;
return asPositiveSafeInteger(Math.round(t * 1e3));
}
function selectPlaybackStream(e, t) {
const n = e.filter((e) => {
if (e.codec_type !== t) return false;
const n = asOptionalRecord(e.disposition);
return t !== "video" || n?.attached_pic !== 1;
});
return n.find((e) => asOptionalRecord(e.disposition)?.default === 1) ?? n[0];
}
function parseFfprobeMediaMetadata(e, t) {
let n;
try {
n = JSON.parse(e);
} catch {
return null;
}
const r = asOptionalRecord(n);
if (!r) return null;
const i = asOptionalRecord(r.format);
const a = (Array.isArray(r.streams) ? r.streams : []).map(asOptionalRecord).filter((e) => Boolean(e));
const o = selectPlaybackStream(a, "audio");
const s = selectPlaybackStream(a, "video");
const c = (t === "video" ? [s, o] : [o]).map((e) => parseDurationMs(e?.duration)).filter((e) => e !== void 0);
const l = (c.length > 0 ? Math.max(...c) : void 0) ?? parseDurationMs(i?.duration);
const u = asPositiveSafeInteger(s?.width);
const d = asPositiveSafeInteger(s?.height);
const [f, p] = typeof s?.sample_aspect_ratio === "string" ? s.sample_aspect_ratio.split(":").map((e) => asPositiveSafeInteger(Number(e))) : [];
const m = f && p ? f / p : void 0;
const h = (Array.isArray(s?.side_data_list) ? s.side_data_list : []).map((e) => asSafeIntegerInRange(asOptionalRecord(e)?.rotation, {})).find((e) => e !== void 0);
const g = normalizeOptionalLowercaseString(o?.codec_name);
const _ = normalizeOptionalLowercaseString(s?.codec_name);
const v = normalizeOptionalLowercaseString(s?.pix_fmt);
const y = normalizeOptionalLowercaseString(s?.profile);
const b = asSafeIntegerInRange(o?.index, { min: 0 });
const x = asSafeIntegerInRange(s?.index, { min: 0 });
return {
...l ? { durationMs: l } : {},
...t === "video" && u && d ? {
width: u,
height: d
} : {},
...h !== void 0 ? { videoRotation: h } : {},
...m !== void 0 ? { videoSampleAspectRatio: m } : {},
...g ? { audioCodec: g } : {},
...b !== void 0 ? { audioStreamIndex: b } : {},
..._ ? { videoCodec: _ } : {},
...v ? { videoPixelFormat: v } : {},
...y ? { videoProfile: y } : {},
...x !== void 0 ? { videoStreamIndex: x } : {}
};
}
function isMissingFdProtocolError(e) {
const t = asOptionalRecord(e)?.stderr;
const n = typeof t === "string" ? t : e instanceof Error ? e.message : "";
return /(?:fd:.*protocol not found|protocol not found.*fd|unrecognized option ['"]?fd|option ['"]?fd\b.*not found)/is.test(n);
}
async function probeMediaSource(e, t, n = {}) {
const r = "stdinFileDescriptor" in e;
const runProbe = async (t) => await runFfprobe([
"-v",
"error",
"-protocol_whitelist",
t,
"-show_entries",
"format=duration:stream=index,codec_type,codec_name,profile,pix_fmt,duration,width,height,sample_aspect_ratio:stream_disposition=default,attached_pic:stream_side_data=rotation",
"-of",
"json",
...t === "fd" ? ["-fd", "0"] : [],
t === "fd" ? "fd:" : "pipe:0"
], {
...e,
...n
});
try {
return parseFfprobeMediaMetadata(await runProbe(r ? "fd" : "pipe"), t);
} catch (e) {
if (r && isMissingFdProtocolError(e)) try {
return parseFfprobeMediaMetadata(await runProbe("pipe"), t);
} catch {
return null;
}
return null;
}
}
/** Keep encoded playback facts separate from attachment display dimensions. */
function toMediaProbeResult(e) {
if (!e) return {};
const t = Math.abs(e.videoRotation ?? 0) % 180 === 90;
const n = e.width && (asPositiveSafeInteger(Math.round(e.width * (e.videoSampleAspectRatio ?? 1))) ?? e.width);
return {
...e.durationMs ? { durationMs: e.durationMs } : {},
...n && e.height ? {
width: t ? e.height : n,
height: t ? n : e.height
} : {}
};
}
/** Probes a bounded batch under one elapsed-time budget, unaffected by wall-clock steps. */
async function probeMediaFilesWithinBudget(e, t) {
const n = e.map(() => ({}));
const r = performance.now() + t.budgetMs;
const i = Math.min(e.length, t.maxProbes);
for (let a = 0; a < i; a += t.concurrency) {
const o = r - performance.now();
if (o <= 0) break;
const s = Math.min(a + t.concurrency, i);
const c = e.slice(a, s);
const l = await Promise.all(c.map(async ({ filePath: e, kind: t }) => {
try {
const n = await fs.open(e, "r");
try {
return toMediaProbeResult(await probeMediaSource({ stdinFileDescriptor: n.fd }, t, { timeoutMs: o }));
} finally {
await n.close().catch(() => {});
}
} catch {
return {};
}
}));
for (const [e, t] of l.entries()) n[a + e] = t;
}
return n;
}
/** Probes duration and first-stream codecs from an already validated local descriptor. */
async function probePlaybackMediaFileDescriptor(e, t) {
return await probeMediaSource({ stdinFileDescriptor: e }, t);
}
/** Probes a video buffer while preserving the existing public media-runtime API. */
async function probeVideoDimensions(e) {
const { width: t, height: n } = toMediaProbeResult(await probeMediaSource({ input: e }, "video"));
return t && n ? {
width: t,
height: n
} : void 0;
}
//#endregion
export { toMediaProbeResult as i, probePlaybackMediaFileDescriptor as n, probeVideoDimensions as r, probeMediaFilesWithinBudget as t };