The swiss army knife of lossless video/audio editing
Copy execa output before decoding it in the renderer
Claudef0a1f43b7854
diff --git a/src/renderer/src/ffmpeg.ts b/src/renderer/src/ffmpeg.tsindex 70009788..01e4255a 100644--- a/src/renderer/src/ffmpeg.ts+++ b/src/renderer/src/ffmpeg.ts@@ -31,23 +31,25 @@ export class RefuseOverwriteError extends Error {}}-export function safeCreateBlob(array: Uint8Array, options?: BlobPropertyBag) {- // if we don't do this when creating a Blob, we get:- // "Failed to construct 'Blob': The provided ArrayBufferView value must not be resizable."- // maybe when moving away from @electron/remote, it's not needed anymore?- // https://stackoverflow.com/a/25255750/6519037- const cloned = new Uint8Array(array);- return new Blob([cloned], options);-}+// execa's stdout/stderr (from main, via @electron/remote) are backed by a resizable ArrayBuffer,+// which Web APIs don't accept, e.g. "Failed to construct 'Blob': The provided ArrayBufferView value must not be resizable."+// (and since Electron 43 also TextDecoder), so we copy them first.+// maybe when moving away from @electron/remote, it's not needed anymore?+// https://stackoverflow.com/a/25255750/6519037+const copyResizable = (array: Uint8Array) => new Uint8Array(array);++export const safeCreateBlob = (array: Uint8Array, options?: BlobPropertyBag) => new Blob([copyResizable(array)], options);++export const decodeText = (array: Uint8Array) => new TextDecoder().decode(copyResizable(array));export function logStdoutStderr({ stdout, stderr }: { stdout: Uint8Array, stderr: Uint8Array }) {if (stdout.length > 0) {console.log('%cSTDOUT:', 'color: green; font-weight: bold');- console.log(new TextDecoder().decode(stdout));+ console.log(decodeText(stdout));}if (stderr.length > 0) {console.log('%cSTDERR:', 'color: blue; font-weight: bold');- console.log(new TextDecoder().decode(stderr));+ console.log(decodeText(stderr));}}@@ -82,7 +84,7 @@ export async function readFrames({ filePath, from, to, streamIndex }: {const intervalsArgs = from != null && to != null ? ['-read_intervals', `${from}%${to}`] : [];const { stdout } = await runFfprobe(['-v', 'error', ...intervalsArgs, '-show_packets', '-select_streams', String(streamIndex), '-show_entries', 'packet=pts_time,flags', '-of', 'json', filePath], { logCli: false });const createdAt = new Date();- const packetsFiltered: Frame[] = (JSON.parse(new TextDecoder().decode(stdout)).packets as { flags: string, pts_time: string }[])+ const packetsFiltered: Frame[] = (JSON.parse(decodeText(stdout)).packets as { flags: string, pts_time: string }[]).map((p) => ({keyframe: p.flags[0] === 'K',time: parseFloat(p.pts_time),@@ -336,7 +338,7 @@ export async function readFileFfprobeMeta(filePath: string) {let decoded: string | undefined;try {// https://github.com/mifi/lossless-cut/issues/1342- decoded = new TextDecoder().decode(stdout);+ decoded = decodeText(stdout);parsedJson = JSON.parse(decoded);} catch {console.log('ffprobe stdout:', decoded ?? stdout);@@ -390,7 +392,7 @@ export async function extractSubtitleTrack(filePath: string, streamId: number) {];const { stdout } = await runFfmpeg(args);- return new TextDecoder().decode(stdout);+ return decodeText(stdout);}export async function extractSubtitleTrackToSegments(filePath: string, streamId: number) {@@ -556,9 +558,9 @@ export async function runFfmpegStartupCheck() {// will throw if exit code != 0const { stderr: ffmpegStderr } = await runFfmpeg(['-f', 'lavfi', '-i', 'nullsrc=s=256x256:d=1', '-f', 'null', '-']);- console.log('FFmpeg startup check output:', new TextDecoder().decode(ffmpegStderr));+ console.log('FFmpeg startup check output:', decodeText(ffmpegStderr));const { stdout: ffprobeStout } = await runFfprobe(['-v', '0', '-of', 'json', '-show_program_version']);- return ffprobeVersionSchema.parse(JSON.parse(new TextDecoder().decode(ffprobeStout)));+ return ffprobeVersionSchema.parse(JSON.parse(decodeText(ffprobeStout)));}// https://superuser.com/questions/543589/information-about-ffmpeg-command-line-optionsdiff --git a/src/renderer/src/hooks/useFfmpegOperations.ts b/src/renderer/src/hooks/useFfmpegOperations.tsindex 7136eca1..a318efc5 100644--- a/src/renderer/src/hooks/useFfmpegOperations.ts+++ b/src/renderer/src/hooks/useFfmpegOperations.ts@@ -5,7 +5,7 @@ import invariant from 'tiny-invariant';import i18n from 'i18next';import { getSuffixedOutPath, transferTimestamps, getOutFileExtension, getOutDir, getHtml5ifiedPath, unlinkWithRetry, getFrameDuration, isMac, html5ifiedPrefix, html5dummySuffix, assertFileExists } from '../util';-import { isCuttingStart, isCuttingEnd, runFfmpegWithProgress, getFfCommandLine, getDuration, createChaptersFromSegments, readFileFfprobeMeta, getExperimentalArgs, getVideoTimescaleArgs, logStdoutStderr, runFfmpegConcat, RefuseOverwriteError, runFfmpeg } from '../ffmpeg';+import { isCuttingStart, isCuttingEnd, runFfmpegWithProgress, getFfCommandLine, getDuration, createChaptersFromSegments, readFileFfprobeMeta, getExperimentalArgs, getVideoTimescaleArgs, logStdoutStderr, runFfmpegConcat, RefuseOverwriteError, runFfmpeg, decodeText } from '../ffmpeg';import { getEffectiveAvoidNegativeTs, getKeyframeCutSeekCompensation, getMapStreamsArgs, getStreamIdsToCopy, isCopyingOnlyAudioStreams, isCropActive, isAspectRatioActive } from '../util/streams';import { needsSmartCut, getCodecParams } from '../smartcut';import { getGuaranteedSegments, isDurationValid } from '../segments';@@ -942,7 +942,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treaappendFfmpegCommandLog(ffmpegArgs);const { stdout } = await runFfmpegWithProgress({ ffmpegArgs, duration, onProgress });- console.log(new TextDecoder().decode(stdout));+ console.log(decodeText(stdout));invariant(outPath != null);await transferTimestamps({ inPath: filePathArg, outPath, duration, treatInputFileModifiedTimeAsStart, treatOutputFileModifiedTimeAsStart });@@ -1083,7 +1083,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treaappendFfmpegCommandLog(ffmpegArgs);const { stdout } = await runFfmpeg(ffmpegArgs);- console.log(new TextDecoder().decode(stdout));+ console.log(decodeText(stdout));return outPaths;}, [appendFfmpegCommandLog, enableOverwriteOutput, filePath]);@@ -1121,7 +1121,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treatry {appendFfmpegCommandLog(ffmpegArgs);const { stdout } = await runFfmpeg(ffmpegArgs);- console.log(new TextDecoder().decode(stdout));+ console.log(decodeText(stdout));} catch (err) {// Unfortunately ffmpeg will exit with code 1 even though it's a success// Note: This is kind of hacky: