Skip to content

Commit e391c67

Browse files
fix(cli): a cut-short MP4 says download it again, read from its header and ffprobe's specific line
1 parent 391e10f commit e391c67

2 files changed

Lines changed: 92 additions & 20 deletions

File tree

‎packages/cli/src/measure/media.test.ts‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { afterAll, beforeAll, describe, expect, it } from "vitest";
22
import { execFileSync, spawnSync } from "node:child_process";
3-
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { join } from "node:path";
66
import { selectFirstFrameAfterEach } from "../commands/snapshot.js";
@@ -128,15 +128,54 @@ describe("a file ffprobe cannot read", () => {
128128
expect(ffprobeReason(new Error("boom"), "x.mp4")).toBeUndefined();
129129
});
130130

131+
it("keeps the specific cause of a cut-short file over ffprobe's generic last line", () => {
132+
const err = {
133+
stderr: Buffer.from(
134+
"[mov,mp4,m4a,3gp,3g2,mj2 @ 0x12e808c00] moov atom not found\nhalf.mp4: Invalid data found when processing input\n",
135+
),
136+
};
137+
const reason = ffprobeReason(err, "half.mp4");
138+
expect(reason).toBe("moov atom not found");
139+
expect(unreadableFix(reason, true)).toMatch(/download it again/);
140+
// A web page named .mp4 gets the same two lines from ffprobe: only the header tells them apart.
141+
expect(unreadableFix(reason, false)).toMatch(/not a video/);
142+
});
143+
131144
it.each([
132-
["moov atom not found", /download it again/],
133-
["Invalid data found when processing input", /not a video/],
134-
["Permission denied", /permissions/],
135-
[undefined, /pass a video file/],
136-
])("answers %s", (reason, fix) => {
137-
expect(unreadableFix(reason)).toMatch(fix);
145+
["moov atom not found", true, /download it again/],
146+
["moov atom not found", false, /not a video/],
147+
["End of file", false, /download it again/],
148+
["Invalid data found when processing input", false, /not a video/],
149+
["Permission denied", false, /permissions/],
150+
[undefined, false, /pass a video file/],
151+
])("answers %s (MP4 header: %s)", (reason, mp4Header, fix) => {
152+
expect(unreadableFix(reason, mp4Header)).toMatch(fix);
138153
});
139154

155+
it.skipIf(!ffmpeg)(
156+
"tells a cut-short download to download again, not that it is no video",
157+
() => {
158+
const dir = mkdtempSync(join(tmpdir(), "hf-cut-"));
159+
const full = join(dir, "full.mp4");
160+
const half = join(dir, "half.mp4");
161+
execFileSync("ffmpeg", [
162+
...["-v", "error", "-f", "lavfi", "-i", "testsrc=size=640x360:rate=30:duration=4"],
163+
...["-pix_fmt", "yuv420p", full],
164+
]);
165+
const bytes = readFileSync(full);
166+
writeFileSync(half, bytes.subarray(0, bytes.length >> 1));
167+
try {
168+
probeVideo(half);
169+
expect.unreachable();
170+
} catch (err) {
171+
expect((err as Fix).message).toMatch(/moov atom not found/);
172+
expect((err as Fix).fix).toMatch(/download it again/);
173+
} finally {
174+
rmSync(dir, { recursive: true, force: true });
175+
}
176+
},
177+
);
178+
140179
it.skipIf(!ffmpeg)("puts the reason and its fix on the error", () => {
141180
const dir = mkdtempSync(join(tmpdir(), "hf-probe-"));
142181
const page = join(dir, "ref.mp4");

‎packages/cli/src/measure/media.ts‎

Lines changed: 46 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Decode with ffmpeg into raw arrays, so measuring and comparing need nothing but node and ffmpeg.
22
// Ported from the Studio's viral-clone media.mjs and tool.mjs.
33
import { execFileSync } from "node:child_process";
4-
import { existsSync, mkdirSync } from "node:fs";
4+
import { closeSync, existsSync, mkdirSync, openSync, readSync } from "node:fs";
55
import { dirname, join, resolve } from "node:path";
66
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
77

@@ -126,22 +126,55 @@ export function missingFileFix(path: string, argv: readonly string[] = process.a
126126
return "pass the video's path from the project folder";
127127
}
128128

129-
/** ffprobe's own last word on a file it could not read, without the path it repeats. */
129+
const CUT_SHORT = "the file is cut short, as an unfinished download is: download it again";
130+
const NOT_A_VIDEO =
131+
"this is not a video: check what was saved (a web page saved as .mp4 reads like this)";
132+
133+
/** ffprobe says "moov atom not found" for any file named .mp4; only an MP4's own header makes it cut short. */
134+
const UNREADABLE_CAUSES: readonly { pattern: RegExp; fix: (mp4Header: boolean) => string }[] = [
135+
{ pattern: /moov atom not found/i, fix: (mp4Header) => (mp4Header ? CUT_SHORT : NOT_A_VIDEO) },
136+
{ pattern: /end of file|partial file/i, fix: () => CUT_SHORT },
137+
{ pattern: /permission denied/i, fix: () => "the file cannot be read: check its permissions" },
138+
{ pattern: /invalid data found/i, fix: () => NOT_A_VIDEO },
139+
];
140+
141+
/** ffprobe's most specific line on a file it could not read, without the demuxer tag or the path it repeats. */
130142
export function ffprobeReason(err: unknown, path: string): string | undefined {
131143
const stderr = (err as { stderr?: Buffer | string } | null)?.stderr?.toString() ?? "";
132-
const line = stderr.trim().split(/\r?\n/).pop()?.replace(`${path}: `, "").trim();
144+
const lines = stderr
145+
.split(/\r?\n/)
146+
.map((line) =>
147+
line
148+
.replace(/^\[[^\]]*\]\s*/, "")
149+
.replace(`${path}: `, "")
150+
.trim(),
151+
)
152+
.filter(Boolean);
153+
const specific = UNREADABLE_CAUSES.map(({ pattern }) => lines.find((l) => pattern.test(l))).find(
154+
Boolean,
155+
);
156+
const line = specific ?? lines.at(-1);
133157
return line ? line.slice(0, 160) : undefined;
134158
}
135159

136-
/** The fix that goes with ffprobe's reason. */
137-
export function unreadableFix(reason: string | undefined): string {
138-
if (reason && /moov atom not found|end of file|partial file/i.test(reason))
139-
return "the file is cut short, as an unfinished download is: download it again";
140-
if (reason && /invalid data found/i.test(reason))
141-
return "this is not a video: check what was saved (a web page saved as .mp4 reads like this)";
142-
if (reason && /permission denied/i.test(reason))
143-
return "the file cannot be read: check its permissions";
144-
return "pass a video file (mp4, mov, webm)";
160+
/** The fix that goes with ffprobe's reason; `mp4Header` is whether the file starts with an MP4 `ftyp` box. */
161+
export function unreadableFix(reason: string | undefined, mp4Header = false): string {
162+
const cause = reason ? UNREADABLE_CAUSES.find(({ pattern }) => pattern.test(reason)) : undefined;
163+
return cause?.fix(mp4Header) ?? "pass a video file (mp4, mov, webm)";
164+
}
165+
166+
function startsWithMp4Header(path: string): boolean {
167+
let fd: number | undefined;
168+
try {
169+
fd = openSync(path, "r");
170+
const head = Buffer.alloc(8);
171+
readSync(fd, head, 0, 8, 0);
172+
return head.toString("latin1", 4, 8) === "ftyp";
173+
} catch {
174+
return false;
175+
} finally {
176+
if (fd !== undefined) closeSync(fd);
177+
}
145178
}
146179

147180
/** Size (as displayed, rotation applied), clock and sound of a video. */
@@ -161,7 +194,7 @@ export function probeVideo(path: string): VideoInfo {
161194
const reason = ffprobeReason(err, path);
162195
throw new Fix(
163196
`ffprobe cannot read ${path}${reason ? `: ${reason}` : ""}`,
164-
unreadableFix(reason),
197+
unreadableFix(reason, startsWithMp4Header(path)),
165198
);
166199
}
167200
const streams = json.streams ?? [];

0 commit comments

Comments
 (0)