π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix video timestamps and retry native codec failures
Anand Baburajan27c9222b3adc
diff --git a/web/apps/space/src/components/PostComposer.tsx b/web/apps/space/src/components/PostComposer.tsxindex b6df8e0592..4206c3bbd7 100644--- a/web/apps/space/src/components/PostComposer.tsx+++ b/web/apps/space/src/components/PostComposer.tsx@@ -43,6 +43,7 @@ interface DraftPhoto {originalPhoto?: SpaceViewerPhoto;edit?: SpacePostPhotoEdit;videoEdit?: SpacePostVideoEdit;+ videoStartTime?: number;}let nextDraftPhotoID = 0;@@ -141,8 +142,10 @@ const SpacePostComposer: React.FC<{signal.throwIfAborted();let photo: SpaceViewerPhoto;let videoEdit: SpacePostVideoEdit | undefined;+ let videoStartTime: number | undefined;if (isSpaceVideoFile(draft.file)) {const info = await spaceVideoInfo(draft.file, signal);+ videoStartTime = info.startTime;videoEdit = initialSpaceVideoEdit(info.duration);const cover = await spaceVideoCover(draft.file,@@ -159,8 +162,8 @@ const SpacePostComposer: React.FC<{video: {url,durationMs: info.duration * 1000,- start: videoEdit.start,- end: videoEdit.end,+ start: videoStartTime + videoEdit.start,+ end: videoStartTime + videoEdit.end,muted: videoEdit.muted,},};@@ -198,6 +201,7 @@ const SpacePostComposer: React.FC<{photo,originalPhoto: photo,videoEdit,+ videoStartTime,}: item,),@@ -338,8 +342,8 @@ const SpacePostComposer: React.FC<{if (photo.video && videoEdit)photo.video = {...photo.video,- start: videoEdit.start,- end: videoEdit.end,+ start: draft.videoStartTime! + videoEdit.start,+ end: draft.videoStartTime! + videoEdit.end,muted: videoEdit.muted,};return { ...draft, edit: result.edit, videoEdit, photo };@@ -471,6 +475,7 @@ const SpacePostComposer: React.FC<{? {file: draft.file,sourceURL: draft.originalPhoto!.video!.url!,+ startTime: draft.videoStartTime!,duration:draft.originalPhoto!.video!.durationMs /1000,diff --git a/web/apps/space/src/components/PostPhotoEditor.tsx b/web/apps/space/src/components/PostPhotoEditor.tsxindex 08a36fcec5..002013d920 100644--- a/web/apps/space/src/components/PostPhotoEditor.tsx+++ b/web/apps/space/src/components/PostPhotoEditor.tsx@@ -42,6 +42,7 @@ export interface SpaceEditablePostPhoto {video?: {file: File;sourceURL: string;+ startTime: number;duration: number;edit: SpacePostVideoEdit;};@@ -357,6 +358,7 @@ export const SpacePostPhotoEditor: React.FC<{key={photo.id}file={photo.video.file}sourceURL={photo.video.sourceURL}+ startTime={photo.video.startTime}duration={photo.video.duration}edit={videoEdits[photo.id] ?? photo.video.edit}onChange={(next) =>diff --git a/web/apps/space/src/components/PostVideoEditor.tsx b/web/apps/space/src/components/PostVideoEditor.tsxindex 0f1b431bb4..f4956f1a43 100644--- a/web/apps/space/src/components/PostVideoEditor.tsx+++ b/web/apps/space/src/components/PostVideoEditor.tsx@@ -45,10 +45,11 @@ type DragMode = VideoTrimHandle | "cover";export const SpacePostVideoEditor: React.FC<{file: File;sourceURL: string;+ startTime: number;duration: number;edit: SpacePostVideoEdit;onChange: (edit: SpacePostVideoEdit) => void;-}> = ({ file, sourceURL, duration, edit, onChange }) => {+}> = ({ file, sourceURL, startTime, duration, edit, onChange }) => {const [mode, setMode] = React.useState<"trim" | "cover">("trim");const [frames, setFrames] = React.useState<string[]>([]);const [playing, setPlaying] = React.useState(false);@@ -84,13 +85,14 @@ export const SpacePostVideoEditor: React.FC<{videoRef.current!,() => latest.current.edit,() => setPreviewError("Couldn't play this video preview."),+ startTime,);playback.current = controller;return () => {controller.dispose();playback.current = undefined;};- }, []);+ }, [startTime]);const seek = React.useCallback((time: number) => {playback.current?.seek(time);diff --git a/web/apps/space/src/components/video-trim/playback.ts b/web/apps/space/src/components/video-trim/playback.tsindex 2d5bbdd423..c76535981a 100644--- a/web/apps/space/src/components/video-trim/playback.ts+++ b/web/apps/space/src/components/video-trim/playback.ts@@ -4,6 +4,7 @@ export const createVideoTrimPlayback = (video: HTMLVideoElement,getRange: () => { start: number; end: number },onError: () => void,+ startTime = 0,) => {let pendingSeek: number | undefined;let frame: number | undefined;@@ -42,15 +43,16 @@ export const createVideoTrimPlayback = (const seek = (time: number) => {pause();restartOnPlay = true;- pendingSeek = time;+ pendingSeek = startTime + time;applySeek();};const checkRange = () => {if (video.paused || video.seeking) return;const { start, end } = getRange();- if (video.currentTime >= end) seek(start);- else if (video.currentTime < start) video.currentTime = start;+ if (video.currentTime >= startTime + end) seek(start);+ else if (video.currentTime < startTime + start)+ video.currentTime = startTime + start;};const checkFrame = () => {@@ -94,7 +96,9 @@ export const createVideoTrimPlayback = (pause();return;}- const { start, end } = getRange();+ const range = getRange();+ const start = startTime + range.start;+ const end = startTime + range.end;const time =restartOnPlay ||video.currentTime < start ||diff --git a/web/apps/space/src/utils/post-video.ts b/web/apps/space/src/utils/post-video.tsindex 44c4efcd47..34fd49b09c 100644--- a/web/apps/space/src/utils/post-video.ts+++ b/web/apps/space/src/utils/post-video.ts@@ -13,6 +13,7 @@ export interface SpaceVideoInfo {duration: number;width: number;height: number;+ startTime: number;}export const maxSpaceVideoDuration = 10;diff --git a/web/apps/space/src/utils/video-encoding/software.ts b/web/apps/space/src/utils/video-encoding/software.tsindex 3a3ea2df0b..59b1e49368 100644--- a/web/apps/space/src/utils/video-encoding/software.ts+++ b/web/apps/space/src/utils/video-encoding/software.ts@@ -29,7 +29,7 @@ export const extractSoftwareVideoFrames = ("-read_intervals",`${time}%${time + 1}`,"-show_entries",- "packet=pts_time:format=start_time",+ "packet=pts_time","-of","json","-o",@@ -43,17 +43,13 @@ export const extractSoftwareVideoFrames = (throw new Error("Expected video timestamps.");const probe = z.object({- format: z.object({- start_time: z.coerce.number().optional(),- }),packets: z.array(z.object({ pts_time: z.coerce.number() })).nonempty(),}).parse(JSON.parse(json));- const start = probe.format.start_time ?? 0;const frameTime = probe.packets- .map((packet) => packet.pts_time - start)+ .map((packet) => packet.pts_time).reduce((closest, timestamp) =>Math.abs(timestamp - time) < Math.abs(closest - time)? timestamp@@ -62,6 +58,8 @@ export const extractSoftwareVideoFrames = (const bytes = await execute(ffmpeg,[+ "-seek_timestamp",+ "1","-ss",String(Math.max(0, frameTime - 0.000001)),"-i",@@ -115,6 +113,8 @@ export const transcodeSoftwareVideo = (execute(ffmpeg,[+ "-seek_timestamp",+ "1","-ss",String(edit.start),"-i",diff --git a/web/apps/space/src/utils/video-encoding/web.ts b/web/apps/space/src/utils/video-encoding/web.tsindex 892d437c47..7e737f1021 100644--- a/web/apps/space/src/utils/video-encoding/web.ts+++ b/web/apps/space/src/utils/video-encoding/web.ts@@ -33,14 +33,18 @@ export const determineVideoInfoWeb = (blob: Blob, signal?: AbortSignal) =>async (input) => {const track = await input.getPrimaryVideoTrack();if (!track) throw new Error("This file has no readable video.");- const [duration, width, height] = await Promise.all([- track.computeDuration(),- track.getDisplayWidth(),- track.getDisplayHeight(),- ]);+ const [endTimestamp, firstTimestamp, width, height] =+ await Promise.all([+ track.computeDuration(),+ track.getFirstTimestamp(),+ track.getDisplayWidth(),+ track.getDisplayHeight(),+ ]);+ const startTime = Math.max(0, firstTimestamp);+ const duration = endTimestamp - startTime;if (!Number.isFinite(duration) || duration <= 0)throw new Error("This video has no readable duration.");- return { duration, width, height };+ return { duration, width, height, startTime };},signal,);@@ -58,46 +62,64 @@ export const extractVideoFramesWeb = (const track = await input.getPrimaryVideoTrack();if (!track)throw new Error("This browser can't preview this video.");- if (!(await track.canDecode())) {- if (!canUseSoftwareVideo())+ const [firstTimestamp, endTimestamp] = await Promise.all([+ track.getFirstTimestamp(),+ track.computeDuration(),+ ]);+ const start = Math.max(0, firstTimestamp);+ const timestamps = times.map((time) =>+ Math.max(start, Math.min(start + time, endTimestamp - 0.001)),+ );+ try {+ if (!(await track.canDecode()))throw new Error("This browser can't preview this video.");+ const [width, height] = await Promise.all([+ track.getDisplayWidth(),+ track.getDisplayHeight(),+ ]);+ const scale = Math.min(+ 1,+ maxDimension / Math.max(width, height),+ );+ const sink = new CanvasSink(track, {+ width: Math.max(1, Math.round(width * scale)),+ height: Math.max(1, Math.round(height * scale)),+ fit: "contain",+ });+ const frames: HTMLCanvasElement[] = [];+ for await (const frame of sink.canvasesAtTimestamps(+ timestamps,+ )) {+ signal.throwIfAborted();+ if (!frame)+ throw new Error(+ "Couldn't read a video frame. Please try again.",+ );+ frames.push(frame.canvas as HTMLCanvasElement);+ }+ return frames;+ } catch (error) {+ signal.throwIfAborted();+ if (+ !canUseSoftwareVideo() ||+ (error instanceof Error &&+ (error.name === "AbortError" ||+ error.name === "TimeoutError"))+ )+ throw error;+ const hdr = await track.hasHighDynamicRange();+ input.dispose();const { extractSoftwareVideoFrames } =await import("./software");+ signal.throwIfAborted();return extractSoftwareVideoFrames(blob,- times,+ timestamps,maxDimension,- await track.hasHighDynamicRange(),+ hdr,signal,);}- const [width, height, firstTimestamp, duration] = await Promise.all(- [- track.getDisplayWidth(),- track.getDisplayHeight(),- track.getFirstTimestamp(),- track.computeDuration(),- ],- );- const scale = Math.min(1, maxDimension / Math.max(width, height));- const sink = new CanvasSink(track, {- width: Math.max(1, Math.round(width * scale)),- height: Math.max(1, Math.round(height * scale)),- fit: "contain",- });- const timestamps = times.map((time) =>- Math.max(firstTimestamp, Math.min(time, duration - 0.001)),- );- const frames: HTMLCanvasElement[] = [];- for await (const frame of sink.canvasesAtTimestamps(timestamps)) {- signal.throwIfAborted();- if (!frame)- throw new Error(- "Couldn't read a video frame. Please try again.",- );- frames.push(frame.canvas as HTMLCanvasElement);- }- return frames;},signal,);@@ -114,174 +136,192 @@ export const transcodeVideoWeb = (const videoTrack = await input.getPrimaryVideoTrack();if (!videoTrack)throw new Error("This file has no readable video.");+ const start = Math.max(0, await videoTrack.getFirstTimestamp());+ const trim = { start: start + edit.start, end: start + edit.end };const softwareExport = async () => {+ const hdr = await videoTrack.hasHighDynamicRange();+ input.dispose();const { transcodeSoftwareVideo } = await import("./software");+ signal.throwIfAborted();return transcodeSoftwareVideo(blob,- edit,- await videoTrack.hasHighDynamicRange(),+ { ...edit, ...trim },+ hdr,signal,);};- if (!(await videoTrack.canDecode())) {- if (canUseSoftwareVideo()) return softwareExport();- throw new Error("This browser can't decode this video.");- }- let audio: ConversionAudioOptions = edit.muted- ? { discard: true }- : { codec: "aac" };- const audioTrack = edit.muted- ? null- : await input.getPrimaryAudioTrack();- if (audioTrack && (await audioTrack.getCodec()) !== "aac") {- const quality = new Quality({ bitrate: 128_000 });- audio = { codec: "aac", quality };- if (- !(await canEncodeAudio("aac", {- numberOfChannels:- await audioTrack.getNumberOfChannels(),- sampleRate: await audioTrack.getSampleRate(),- quality,- }))- ) {- const { registerAacEncoder } =- await import("@mediabunny/aac-encoder");- signal.throwIfAborted();- registerAacEncoder();- }- }- let output = new Output({- format: new Mp4OutputFormat({ fastStart: "in-memory" }),- target: new BufferTarget(),- });- let conversion: Conversion | undefined;- let encodedInput: Input | undefined;- const cancel = () => {- void (conversion ? conversion.cancel() : output.cancel());- encodedInput?.dispose();- };- signal.addEventListener("abort", cancel, { once: true });try {- signal.throwIfAborted();- conversion = await Conversion.init({- input,- output,- tracks: "primary",- trim: { start: edit.start, end: edit.end },- copy: { boundaryPolicy: "shrink" },- tags: {},- showWarnings: false,- video: async (track): Promise<ConversionVideoOptions> => {- const [width, height, hdr] = await Promise.all([- track.getDisplayWidth(),- track.getDisplayHeight(),- track.hasHighDynamicRange(),- ]);- const scale = Math.min(- 1,- 1920 / Math.max(width, height),- 1080 / Math.min(width, height),- );- const outputWidth = Math.max(- 2,- Math.floor((width * scale) / 2) * 2,- );- const outputHeight = Math.max(- 2,- Math.floor((height * scale) / 2) * 2,- );- let context: CanvasRenderingContext2D | null = null;- if (hdr) {- const canvas = document.createElement("canvas");- canvas.width = outputWidth;- canvas.height = outputHeight;- context = canvas.getContext("2d", {- colorSpace: "srgb",- });- if (!context)- throw new Error(- "Couldn't prepare the video frames.",- );- }- const colorContext = context;- return {- codec: "avc",- width: outputWidth,- height: outputHeight,- fit: "contain",- frameRate: 30,- quality: new Quality({ bitrate: 4_000_000 }),- keyFrameInterval: 2,- allowTransformationMetadata: false,- process: colorContext- ? (sample) => {- sample.draw(- colorContext,- 0,- 0,- outputWidth,- outputHeight,- );- return colorContext.canvas;- }- : undefined,- };- },- audio,- });- signal.throwIfAborted();- if (- !conversion.isValid ||- conversion.discardedTracks.some(- (track) => track.reason !== "discarded_by_user",- )- ) {- if (canUseSoftwareVideo()) {- await conversion.cancel();- return await softwareExport();+ if (!(await videoTrack.canDecode())) {+ throw new Error("This browser can't decode this video.");+ }+ let audio: ConversionAudioOptions = edit.muted+ ? { discard: true }+ : { codec: "aac" };+ const audioTrack = edit.muted+ ? null+ : await input.getPrimaryAudioTrack();+ if (audioTrack && (await audioTrack.getCodec()) !== "aac") {+ const quality = new Quality({ bitrate: 128_000 });+ audio = { codec: "aac", quality };+ if (+ !(await canEncodeAudio("aac", {+ numberOfChannels:+ await audioTrack.getNumberOfChannels(),+ sampleRate: await audioTrack.getSampleRate(),+ quality,+ }))+ ) {+ const { registerAacEncoder } =+ await import("@mediabunny/aac-encoder");+ signal.throwIfAborted();+ registerAacEncoder();}- throw new Error(- "This browser can't export this video's format. Try another video or browser.",- );}- await conversion.execute();- signal.throwIfAborted();- if (!output.target.buffer)- throw new Error("Couldn't export this video.");- encodedInput = new Input({- formats: ALL_FORMATS,- source: new BufferSource(output.target.buffer),- });- output = new Output({+ let output = new Output({format: new Mp4OutputFormat({ fastStart: "in-memory" }),target: new BufferTarget(),});- conversion = await Conversion.init({- input: encodedInput,- output,- tracks: "primary",- trim: { start: 0, end: edit.end - edit.start },- copy: { mode: "forced", boundaryPolicy: "shrink" },- tags: {},- showWarnings: false,- });- signal.throwIfAborted();- if (!conversion.isValid || conversion.discardedTracks.length)- throw new Error("Couldn't trim the exported video.");- for (const track of output.tracks) delete track.metadata.name;- await conversion.execute();- signal.throwIfAborted();- if (!output.target.buffer)- throw new Error("Couldn't export this video.");- return new Uint8Array(output.target.buffer);- } finally {- signal.removeEventListener("abort", cancel);- if (output.state !== "finalized") {- if (conversion?.state !== "canceled")- await conversion?.cancel();- await output.cancel();+ let conversion: Conversion | undefined;+ let encodedInput: Input | undefined;+ const cancel = () => {+ void (conversion ? conversion.cancel() : output.cancel());+ encodedInput?.dispose();+ };+ signal.addEventListener("abort", cancel, { once: true });+ try {+ signal.throwIfAborted();+ conversion = await Conversion.init({+ input,+ output,+ tracks: "primary",+ trim,+ copy: { boundaryPolicy: "shrink" },+ tags: {},+ showWarnings: false,+ video: async (+ track,+ ): Promise<ConversionVideoOptions> => {+ const [width, height, hdr] = await Promise.all([+ track.getDisplayWidth(),+ track.getDisplayHeight(),+ track.hasHighDynamicRange(),+ ]);+ const scale = Math.min(+ 1,+ 1920 / Math.max(width, height),+ 1080 / Math.min(width, height),+ );+ const outputWidth = Math.max(+ 2,+ Math.floor((width * scale) / 2) * 2,+ );+ const outputHeight = Math.max(+ 2,+ Math.floor((height * scale) / 2) * 2,+ );+ let context: CanvasRenderingContext2D | null = null;+ if (hdr) {+ const canvas = document.createElement("canvas");+ canvas.width = outputWidth;+ canvas.height = outputHeight;+ context = canvas.getContext("2d", {+ colorSpace: "srgb",+ });+ if (!context)+ throw new Error(+ "Couldn't prepare the video frames.",+ );+ }+ const colorContext = context;+ return {+ codec: "avc",+ width: outputWidth,+ height: outputHeight,+ fit: "contain",+ frameRate: 30,+ quality: new Quality({ bitrate: 4_000_000 }),+ keyFrameInterval: 2,+ allowTransformationMetadata: false,+ process: colorContext+ ? (sample) => {+ sample.draw(+ colorContext,+ 0,+ 0,+ outputWidth,+ outputHeight,+ );+ return colorContext.canvas;+ }+ : undefined,+ };+ },+ audio,+ });+ signal.throwIfAborted();+ if (+ !conversion.isValid ||+ conversion.discardedTracks.some(+ (track) => track.reason !== "discarded_by_user",+ )+ ) {+ throw new Error(+ "This browser can't export this video's format. Try another video or browser.",+ );+ }+ await conversion.execute();+ signal.throwIfAborted();+ if (!output.target.buffer)+ throw new Error("Couldn't export this video.");+ encodedInput = new Input({+ formats: ALL_FORMATS,+ source: new BufferSource(output.target.buffer),+ });+ output = new Output({+ format: new Mp4OutputFormat({ fastStart: "in-memory" }),+ target: new BufferTarget(),+ });+ conversion = await Conversion.init({+ input: encodedInput,+ output,+ tracks: "primary",+ trim: { start: 0, end: edit.end - edit.start },+ copy: { mode: "forced", boundaryPolicy: "shrink" },+ tags: {},+ showWarnings: false,+ });+ signal.throwIfAborted();+ if (+ !conversion.isValid ||+ conversion.discardedTracks.length+ )+ throw new Error("Couldn't trim the exported video.");+ for (const track of output.tracks)+ delete track.metadata.name;+ await conversion.execute();+ signal.throwIfAborted();+ if (!output.target.buffer)+ throw new Error("Couldn't export this video.");+ return new Uint8Array(output.target.buffer);+ } finally {+ signal.removeEventListener("abort", cancel);+ if (output.state !== "finalized") {+ if (conversion?.state !== "canceled")+ await conversion?.cancel();+ await output.cancel();+ }+ encodedInput?.dispose();}- encodedInput?.dispose();+ } catch (error) {+ signal.throwIfAborted();+ if (+ !canUseSoftwareVideo() ||+ (error instanceof Error &&+ (error.name === "AbortError" ||+ error.name === "TimeoutError"))+ )+ throw error;+ return softwareExport();}},signal,diff --git a/web/apps/space/tests/video-export.test.ts b/web/apps/space/tests/video-export.test.tsindex 8515ffd691..5a397bc29e 100644--- a/web/apps/space/tests/video-export.test.ts+++ b/web/apps/space/tests/video-export.test.ts@@ -280,6 +280,7 @@ test("rejects a file without video and releases the input", async () => {});test("canceling an active export closes the codecs and allows the next job to run", async () => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });mocks.execute.mockImplementationOnce(() => new Promise(() => undefined));const run = await exporter();const controller = new AbortController();@@ -294,6 +295,7 @@ test("canceling an active export closes the codecs and allows the next job to ruexpect(mocks.conversions[0]!.cancel).toHaveBeenCalledOnce();expect(mocks.outputs[0]!.cancel).toHaveBeenCalled();expect(mocks.inputs[0]!.dispose).toHaveBeenCalled();+ expect(mocks.softwareExport).not.toHaveBeenCalled();});test("canceling a queued export returns promptly without canceling the active export", async () => {@@ -324,6 +326,7 @@ test("canceling a queued export returns promptly without canceling the active ex});test("a stalled conversion times out and releases the queue", async () => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });vi.useFakeTimers();mocks.execute.mockImplementationOnce(() => new Promise(() => undefined));const run = await exporter();@@ -335,6 +338,7 @@ test("a stalled conversion times out and releases the queue", async () => {await timedOut;expect(await run(file(), edit)).toEqual(new Uint8Array([1, 2, 3]));expect(mocks.conversions[0]!.cancel).toHaveBeenCalledOnce();+ expect(mocks.softwareExport).not.toHaveBeenCalled();});test("a conversion failure releases its resources and permits retry", async () => {@@ -344,6 +348,7 @@ test("a conversion failure releases its resources and permits retry", async () =expect(mocks.outputs[0]!.cancel).toHaveBeenCalled();expect(mocks.inputs[0]!.dispose).toHaveBeenCalled();await expect(run(file(), edit)).resolves.toBeDefined();+ expect(mocks.softwareExport).not.toHaveBeenCalled();});test("reads oriented metadata without requiring a video decoder", async () => {@@ -354,6 +359,7 @@ test("reads oriented metadata without requiring a video decoder", async () => {duration: 10.833333,width: 1080,height: 1920,+ startTime: 0,});expect(mocks.track.canDecode).not.toHaveBeenCalled();expect(mocks.inputs[0]!.dispose).toHaveBeenCalled();@@ -542,3 +548,203 @@ test("muted and silent videos do not load an AAC encoder", async () => {expect(mocks.canEncodeAudio).not.toHaveBeenCalled();expect(mocks.registerAacEncoder).not.toHaveBeenCalled();});++test.each([5, -0.1])(+ "metadata, covers, and native trim share a zero-based timeline with first timestamp %s",+ async (firstTimestamp) => {+ mocks.track.getFirstTimestamp.mockResolvedValue(firstTimestamp);+ mocks.track.computeDuration.mockResolvedValue(15);+ const {+ determineVideoInfoWeb,+ extractVideoFramesWeb,+ transcodeVideoWeb,+ } = await import("../src/utils/video-encoding/web");+ const start = Math.max(0, firstTimestamp);+ expect(await determineVideoInfoWeb(file())).toMatchObject({+ startTime: start,+ duration: 15 - start,+ });+ await extractVideoFramesWeb(file(), [0, 1, 20], 160);+ expect(mocks.frames.mock.calls[0]![0]).toEqual([+ start,+ start + 1,+ 14.999,+ ]);+ await transcodeVideoWeb(file(), edit);+ expect(mocks.init.mock.calls[0]![0]).toMatchObject({+ trim: { start: start + edit.start, end: start + edit.end },+ });+ expect(mocks.init.mock.calls[1]![0]).toMatchObject({+ trim: { start: 0, end: edit.end - edit.start },+ });+ },+);++test("software processing receives the same absolute timestamps as native processing", async () => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });+ mocks.track.getFirstTimestamp.mockResolvedValue(5);+ mocks.track.computeDuration.mockResolvedValue(15);+ mocks.track.canDecode.mockResolvedValue(false);+ const { extractVideoFramesWeb, transcodeVideoWeb } =+ await import("../src/utils/video-encoding/web");+ const source = file();+ await extractVideoFramesWeb(source, [0, 1, 20], 160);+ expect(mocks.softwareFrames).toHaveBeenCalledWith(+ source,+ [5, 6, 14.999],+ 160,+ false,+ expect.any(AbortSignal),+ );+ await transcodeVideoWeb(source, edit);+ expect(mocks.softwareExport).toHaveBeenCalledWith(+ source,+ { ...edit, start: 6.125, end: 14.875 },+ false,+ expect.any(AbortSignal),+ );+});++test.each(["init", "encode", "remux"])(+ "a native %s failure releases resources before one software export",+ async (stage) => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });+ const failure = new Error("Hardware codec failed");+ if (stage === "init") mocks.init.mockRejectedValueOnce(failure);+ else if (stage === "encode")+ mocks.execute.mockRejectedValueOnce(failure);+ else+ mocks.execute+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(failure);+ mocks.softwareExport.mockImplementationOnce(() => {+ expect(+ mocks.outputs.every((output) =>+ ["canceled", "finalized"].includes(output.state),+ ),+ ).toBe(true);+ expect(+ mocks.inputs.every(+ (input) => input.dispose.mock.calls.length > 0,+ ),+ ).toBe(true);+ return Promise.resolve(new Uint8Array([4, 5, 6]));+ });+ expect(await (await exporter())(file(), edit)).toEqual(+ new Uint8Array([4, 5, 6]),+ );+ expect(mocks.softwareExport).toHaveBeenCalledOnce();+ },+);++test("a failed software retry is reported without starting another retry", async () => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });+ mocks.execute.mockRejectedValueOnce(new Error("Native failed"));+ mocks.softwareExport.mockRejectedValueOnce(new Error("Software failed"));+ await expect((await exporter())(file(), edit)).rejects.toThrow(+ "Software failed",+ );+ expect(mocks.softwareExport).toHaveBeenCalledOnce();+});++test.each(["throw", "empty"])(+ "a native frame %s failure discards partial results and retries the entire batch",+ async (failure) => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });+ mocks.frames.mockImplementationOnce(function* () {+ yield { canvas: { width: 90, height: 160 } };+ if (failure === "throw") throw new Error("Decoder failed");+ yield null;+ });+ const softwareFrames = [+ { width: 80, height: 120 },+ { width: 80, height: 120 },+ ];+ mocks.softwareFrames.mockImplementationOnce(() => {+ expect(mocks.inputs[0]!.dispose).toHaveBeenCalled();+ return Promise.resolve(softwareFrames);+ });+ const { extractVideoFramesWeb } =+ await import("../src/utils/video-encoding/web");+ const source = file();+ expect(await extractVideoFramesWeb(source, [0, 1], 160)).toBe(+ softwareFrames,+ );+ expect(mocks.softwareFrames).toHaveBeenCalledExactlyOnceWith(+ source,+ [0, 1],+ 160,+ false,+ expect.any(AbortSignal),+ );+ },+);++test("iPhone never retries a native frame failure with full FFmpeg", async () => {+ mocks.frames.mockImplementationOnce(() => {+ throw new Error("Decoder failed");+ });+ const { extractVideoFramesWeb } =+ await import("../src/utils/video-encoding/web");+ await expect(extractVideoFramesWeb(file(), [0], 160)).rejects.toThrow(+ "Decoder failed",+ );+ expect(mocks.softwareFrames).not.toHaveBeenCalled();+});++test.each(["AbortError", "TimeoutError"])(+ "%s from native codecs does not start a software retry",+ async (name) => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });+ mocks.init.mockRejectedValueOnce(new DOMException("Stopped", name));+ mocks.frames.mockImplementationOnce(() => {+ throw new DOMException("Stopped", name);+ });+ const { extractVideoFramesWeb, transcodeVideoWeb } =+ await import("../src/utils/video-encoding/web");+ await expect(transcodeVideoWeb(file(), edit)).rejects.toMatchObject({+ name,+ });+ await expect(+ extractVideoFramesWeb(file(), [0], 160),+ ).rejects.toMatchObject({ name });+ expect(mocks.softwareExport).not.toHaveBeenCalled();+ expect(mocks.softwareFrames).not.toHaveBeenCalled();+ },+);++test.each(["cancel", "timeout"])(+ "a frame %s disposes the native input without retrying in software",+ async (action) => {+ vi.stubGlobal("navigator", { userAgent: "Firefox/144.0" });+ if (action === "timeout") vi.useFakeTimers();+ mocks.frames.mockImplementationOnce(async function* () {+ await new Promise((_, reject) => {+ mocks.inputs[0]!.dispose.mockImplementation(() =>+ reject(new Error("Decoder disposed")),+ );+ });+ yield null;+ });+ const { extractVideoFramesWeb } =+ await import("../src/utils/video-encoding/web");+ const controller = new AbortController();+ const pending = extractVideoFramesWeb(+ file(),+ [0],+ 160,+ controller.signal,+ );+ const rejected = expect(pending).rejects.toMatchObject({+ name: action === "cancel" ? "AbortError" : "TimeoutError",+ });+ if (action === "timeout") await vi.advanceTimersByTimeAsync(60_000);+ else {+ await vi.waitFor(() => expect(mocks.frames).toHaveBeenCalled());+ controller.abort();+ }+ await rejected;+ expect(mocks.softwareFrames).not.toHaveBeenCalled();+ expect(mocks.inputs[0]!.dispose).toHaveBeenCalled();+ },+);diff --git a/web/apps/space/tests/video-software.test.ts b/web/apps/space/tests/video-software.test.tsindex fee689347e..b0a7339052 100644--- a/web/apps/space/tests/video-software.test.ts+++ b/web/apps/space/tests/video-software.test.ts@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({terminate: vi.fn(),closeBitmap: vi.fn(),rejectPending: undefined as ((error: Error) => void) | undefined,+ packetTimes: [0],}));vi.mock("ente-base/log-web", () => ({ logToDisk: vi.fn() }));@@ -22,8 +23,9 @@ vi.mock("@ffmpeg/ffmpeg", () => ({Promise.resolve(path.endsWith("json")? JSON.stringify({- format: { start_time: 0 },- packets: [{ pts_time: 0 }],+ packets: mocks.packetTimes.map((pts_time) => ({+ pts_time,+ })),}): new Uint8Array([1, 2, 3]),),@@ -39,6 +41,7 @@ vi.mock("@ffmpeg/ffmpeg", () => ({beforeEach(() => {vi.clearAllMocks();mocks.rejectPending = undefined;+ mocks.packetTimes = [0];mocks.load.mockResolvedValue(true);mocks.exec.mockResolvedValue(0);vi.stubGlobal("document", {@@ -101,7 +104,9 @@ test.each([false, true])(),).resolves.toEqual(new Uint8Array([1, 2, 3]));const args = mocks.exec.mock.calls[0]![0] as string[];- expect(args.slice(0, 6)).toEqual([+ expect(args.slice(0, 8)).toEqual([+ "-seek_timestamp",+ "1","-ss","1.125","-i",@@ -160,3 +165,25 @@ test("a canceled request does not load FFmpeg, and a failed load releases the woexpect(mocks.terminate).toHaveBeenCalledOnce();expect(mocks.mount).not.toHaveBeenCalled();});++test("software cover seeking uses absolute packet timestamps for offset videos", async () => {+ mocks.packetTimes = [5, 6, 7];+ const { extractSoftwareVideoFrames } =+ await import("../src/utils/video-encoding/software");+ await extractSoftwareVideoFrames(+ file,+ [6],+ 160,+ false,+ new AbortController().signal,+ );+ const args = mocks.exec.mock.calls[0]![0] as string[];+ expect(args.slice(0, 6)).toEqual([+ "-seek_timestamp",+ "1",+ "-ss",+ "5.999999",+ "-i",+ "/input/video",+ ]);+});diff --git a/web/apps/space/tests/video-trim-playback.test.ts b/web/apps/space/tests/video-trim-playback.test.tsindex b21d40a373..10ce0149a9 100644--- a/web/apps/space/tests/video-trim-playback.test.ts+++ b/web/apps/space/tests/video-trim-playback.test.ts@@ -216,3 +216,26 @@ test("closing or pausing a loading preview cancels its timeout", async () => {await vi.advanceTimersByTimeAsync(30_000);expect(onError).not.toHaveBeenCalled();});++test("offset videos preview zero-based editor times on the source timeline", () => {+ playback.dispose();+ range = { start: 0.5, end: 2 };+ playback = createVideoTrimPlayback(+ video as unknown as HTMLVideoElement,+ () => range,+ onError,+ 5,+ );+ playback.seek(1);+ expect(video.currentTime).toBe(6);+ playback.toggle();+ expect(video.currentTime).toBe(5.5);+ video.currentTime = 6.25;+ playback.toggle();+ playback.toggle();+ expect(video.currentTime).toBe(6.25);+ video.currentTime = 7.01;+ renderFrame();+ expect(video.paused).toBe(true);+ expect(video.currentTime).toBe(5.5);+});