Skip to content

The swiss army knife of lossless video/audio editing

improve extract frames

Mikael Finstad572a0caf1a5c
diff --git a/public/configStore.js b/public/configStore.js
index 358a2d91..6b750376 100644
--- a/public/configStore.js
+++ b/public/configStore.js
@@ -115,6 +115,7 @@ const defaults = {
mouseWheelZoomModifierKey: 'ctrl',
captureFrameMethod: 'videotag', // we don't default to ffmpeg because ffmpeg might choose a frame slightly off
captureFrameQuality: 0.95,
+ captureFrameFileNameFormat: 'timestamp',
};
// For portable app: https://github.com/mifi/lossless-cut/issues/645
diff --git a/src/App.jsx b/src/App.jsx
index eb735411..9a4dcedf 100644
--- a/src/App.jsx
+++ b/src/App.jsx
@@ -1432,7 +1432,7 @@ const App = memo(() => {
setWorking(i18n.t('Extracting frames'));
setCutProgress(0);
- const outPath = await captureFramesRange({ customOutDir, filePath, fromTime: start, toTime: end, captureFormat, quality: captureFrameQuality, filter: captureFramesResponse.filter, onProgress: setCutProgress });
+ const outPath = await captureFramesRange({ customOutDir, filePath, fps: detectedFps, fromTime: start, toTime: end, estimatedMaxNumFiles: captureFramesResponse.estimatedMaxNumFiles, captureFormat, quality: captureFrameQuality, filter: captureFramesResponse.filter, outputTimestamps: captureFrameFileNameFormat === 'timestamp', onProgress: setCutProgress });
if (!hideAllNotifications) openDirToast({ icon: 'success', filePath: outPath, text: i18n.t('Frames extracted to: {{path}}', { path: outputDir }) });
} catch (err) {
handleError(err);
@@ -1440,7 +1440,7 @@ const App = memo(() => {
setWorking();
setCutProgress();
}
- }, [apparentCutSegments, captureFormat, captureFrameQuality, customOutDir, detectedFps, filePath, getFrameCount, hideAllNotifications, outputDir, setWorking]);
+ }, [apparentCutSegments, captureFormat, captureFrameFileNameFormat, captureFrameQuality, customOutDir, detectedFps, filePath, getFrameCount, hideAllNotifications, outputDir, setWorking]);
const extractCurrentSegmentFramesAsImages = useCallback(() => extractSegmentFramesAsImages(currentSegIndexSafe), [currentSegIndexSafe, extractSegmentFramesAsImages]);
diff --git a/src/Settings.jsx b/src/Settings.jsx
index 1bef2139..ef237386 100644
--- a/src/Settings.jsx
+++ b/src/Settings.jsx
@@ -24,7 +24,7 @@ const Settings = memo(({
}) => {
const { t } = useTranslation();
- const { customOutDir, changeOutDir, keyframeCut, toggleKeyframeCut, timecodeFormat, setTimecodeFormat, invertCutSegments, setInvertCutSegments, askBeforeClose, setAskBeforeClose, enableAskForImportChapters, setEnableAskForImportChapters, enableAskForFileOpenAction, setEnableAskForFileOpenAction, autoSaveProjectFile, setAutoSaveProjectFile, invertTimelineScroll, setInvertTimelineScroll, language, setLanguage, ffmpegExperimental, setFfmpegExperimental, hideNotifications, setHideNotifications, autoLoadTimecode, setAutoLoadTimecode, enableTransferTimestamps, setEnableTransferTimestamps, enableAutoHtml5ify, setEnableAutoHtml5ify, customFfPath, setCustomFfPath, storeProjectInWorkingDir, setStoreProjectInWorkingDir, enableOverwriteOutput, setEnableOverwriteOutput, mouseWheelZoomModifierKey, setMouseWheelZoomModifierKey, captureFrameMethod, setCaptureFrameMethod, captureFrameQuality, setCaptureFrameQuality } = useUserSettings();
+ const { customOutDir, changeOutDir, keyframeCut, toggleKeyframeCut, timecodeFormat, setTimecodeFormat, invertCutSegments, setInvertCutSegments, askBeforeClose, setAskBeforeClose, enableAskForImportChapters, setEnableAskForImportChapters, enableAskForFileOpenAction, setEnableAskForFileOpenAction, autoSaveProjectFile, setAutoSaveProjectFile, invertTimelineScroll, setInvertTimelineScroll, language, setLanguage, ffmpegExperimental, setFfmpegExperimental, hideNotifications, setHideNotifications, autoLoadTimecode, setAutoLoadTimecode, enableTransferTimestamps, setEnableTransferTimestamps, enableAutoHtml5ify, setEnableAutoHtml5ify, customFfPath, setCustomFfPath, storeProjectInWorkingDir, setStoreProjectInWorkingDir, enableOverwriteOutput, setEnableOverwriteOutput, mouseWheelZoomModifierKey, setMouseWheelZoomModifierKey, captureFrameMethod, setCaptureFrameMethod, captureFrameQuality, setCaptureFrameQuality, captureFrameFileNameFormat, setCaptureFrameFileNameFormat } = useUserSettings();
const onLangChange = useCallback((e) => {
const { value } = e.target;
@@ -202,6 +202,15 @@ const Settings = memo(({
</Table.TextCell>
</Row>
+ <Row>
+ <KeyCell>{t('Extract video frames file name')}</KeyCell>
+ <Table.TextCell>
+ <Button iconBefore={captureFrameFileNameFormat === 'timestamp' ? TimeIcon : NumericalIcon} onClick={() => setCaptureFrameFileNameFormat((existing) => (existing === 'timestamp' ? 'index' : 'timestamp'))}>
+ {captureFrameFileNameFormat === 'timestamp' ? t('Frame timestamp') : t('File number')}
+ </Button>
+ </Table.TextCell>
+ </Row>
+
<Row>
<KeyCell>{t('In timecode show')}</KeyCell>
<Table.TextCell>
diff --git a/src/capture-frame.js b/src/capture-frame.js
index 4708ba48..ea6860b4 100644
--- a/src/capture-frame.js
+++ b/src/capture-frame.js
@@ -1,12 +1,14 @@
import dataUriToBuffer from 'data-uri-to-buffer';
+import pMap from 'p-map';
-import { getSuffixedOutPath, transferTimestamps } from './util';
+import { getSuffixedOutPath, getOutDir, transferTimestamps, getSuffixedFileName, getOutPath, escapeRegExp } from './util';
import { formatDuration } from './util/duration';
import { captureFrame as ffmpegCaptureFrame, captureFrames as ffmpegCaptureFrames } from './ffmpeg';
const fs = window.require('fs-extra');
const mime = window.require('mime-types');
+const { rename, readdir } = window.require('fs/promises');
function getFrameFromVideo(video, format, quality) {
const canvas = document.createElement('canvas');
@@ -20,16 +22,51 @@ function getFrameFromVideo(video, format, quality) {
return dataUriToBuffer(dataUri);
}
-export async function captureFramesRange({ customOutDir, filePath, fromTime, toTime, captureFormat, quality, filter, onProgress }) {
- const time = formatDuration({ seconds: fromTime, fileNameFriendly: true });
- const numDigits = 5;
- const getSuffix = (numPart) => `${time}-${numPart}.${captureFormat}`;
- const nameTemplateSuffix = getSuffix(`%0${numDigits}d`);
- const nameSuffix = getSuffix(`${'1'.padStart(numDigits, '0')}`); // mimic ffmpeg
- const outPathTemplate = getSuffixedOutPath({ customOutDir, filePath, nameSuffix: nameTemplateSuffix });
- const firstFileOutPath = getSuffixedOutPath({ customOutDir, filePath, nameSuffix });
- await ffmpegCaptureFrames({ from: fromTime, to: toTime, videoPath: filePath, outPathTemplate, quality, filter, onProgress });
- return firstFileOutPath;
+export async function captureFramesRange({ customOutDir, filePath, fps, fromTime, toTime, estimatedMaxNumFiles, captureFormat, quality, filter, onProgress, outputTimestamps }) {
+ const getSuffix = (prefix) => `${prefix}.${captureFormat}`;
+
+ if (!outputTimestamps) {
+ const numDigits = Math.floor(Math.log10(estimatedMaxNumFiles)) + 1;
+ const nameTemplateSuffix = getSuffix(`%0${numDigits}d`);
+ const nameSuffix = getSuffix(`${'1'.padStart(numDigits, '0')}`); // mimic ffmpeg output
+ const outPathTemplate = getSuffixedOutPath({ customOutDir, filePath, nameSuffix: nameTemplateSuffix });
+ const firstFileOutPath = getSuffixedOutPath({ customOutDir, filePath, nameSuffix });
+
+ await ffmpegCaptureFrames({ from: fromTime, to: toTime, videoPath: filePath, outPathTemplate, quality, filter, onProgress });
+
+ return firstFileOutPath;
+ }
+
+ // see https://github.com/mifi/lossless-cut/issues/1139
+ const tmpSuffix = 'llc-tmp-frame-capture-';
+ const outPathTemplate = getSuffixedOutPath({ customOutDir, filePath, nameSuffix: getSuffix(`${tmpSuffix}%d`) });
+ await ffmpegCaptureFrames({ from: fromTime, to: toTime, videoPath: filePath, outPathTemplate, quality, filter, framePts: true, onProgress });
+
+ const outDir = getOutDir(customOutDir, filePath);
+ const files = await readdir(outDir);
+
+ // https://github.com/mifi/lossless-cut/issues/1139
+ const matches = files.map((fileName) => {
+ const escapedRegexp = escapeRegExp(getSuffixedFileName(filePath, tmpSuffix));
+ const regexp = `^${escapedRegexp}(\\d+)`;
+ console.log(regexp);
+ const match = fileName.match(new RegExp(regexp));
+ if (!match) return undefined;
+ const frameNum = parseInt(match[1], 10);
+ if (Number.isNaN(frameNum) || frameNum < 0) return undefined;
+ return { fileName, frameNum };
+ }).filter((it) => it != null);
+
+ console.log('Renaming temp files...');
+ const outPaths = await pMap(matches, async ({ fileName, frameNum }) => {
+ const duration = formatDuration({ seconds: fromTime + (frameNum / fps), fileNameFriendly: true });
+ const renameFromPath = getOutPath({ customOutDir, filePath, fileName });
+ const renameToPath = getOutPath({ customOutDir, filePath, fileName: getSuffixedFileName(filePath, getSuffix(duration, captureFormat)) });
+ await rename(renameFromPath, renameToPath);
+ return renameToPath;
+ }, { concurrency: 1 });
+
+ return outPaths[0];
}
export async function captureFrameFromFfmpeg({ customOutDir, filePath, fromTime, captureFormat, enableTransferTimestamps, quality }) {
diff --git a/src/components/ConcatDialog.jsx b/src/components/ConcatDialog.jsx
index 9930ef5b..614a6042 100644
--- a/src/components/ConcatDialog.jsx
+++ b/src/components/ConcatDialog.jsx
@@ -12,7 +12,7 @@ import useFileFormatState from '../hooks/useFileFormatState';
import OutputFormatSelect from './OutputFormatSelect';
import useUserSettings from '../hooks/useUserSettings';
import { isMov } from '../util/streams';
-import { getOutFileExtension, getFileBaseName } from '../util';
+import { getOutFileExtension, getSuffixedFileName } from '../util';
const { basename } = window.require('path');
@@ -77,7 +77,7 @@ const ConcatDialog = memo(({
return;
}
const ext = getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath: firstPath });
- setOutFileName(`${getFileBaseName(firstPath)}-merged-${uniqueSuffix}${ext}`);
+ setOutFileName(getSuffixedFileName(firstPath, `merged-${uniqueSuffix}${ext}`));
}, [fileFormat, firstPath, isCustomFormatSelected, uniqueSuffix]);
const allFilesMeta = useMemo(() => {
diff --git a/src/dialogs.jsx b/src/dialogs.jsx
index 1c61aa38..c71c590a 100644
--- a/src/dialogs.jsx
+++ b/src/dialogs.jsx
@@ -552,6 +552,8 @@ export async function askExtractFramesAsImages({ segmentNumFrames, fps }) {
// we don't know estimatedMaxNumFiles here
}
+ estimatedMaxNumFiles += 1; // just to be sure
+
if (estimatedMaxNumFiles > 1000) {
const { isConfirmed } = await Swal.fire({
icon: 'warning',
@@ -562,7 +564,7 @@ export async function askExtractFramesAsImages({ segmentNumFrames, fps }) {
if (!isConfirmed) return undefined;
}
- return { filter };
+ return { filter, estimatedMaxNumFiles };
}
export async function createFixedDurationSegments(fileDuration) {
diff --git a/src/ffmpeg.js b/src/ffmpeg.js
index 35343507..b1e1f4be 100644
--- a/src/ffmpeg.js
+++ b/src/ffmpeg.js
@@ -745,7 +745,7 @@ export async function captureFrame({ timestamp, videoPath, outPath, quality }) {
]);
}
-export async function captureFrames({ from, to, videoPath, outPathTemplate, quality, filter, onProgress }) {
+export async function captureFrames({ from, to, videoPath, outPathTemplate, quality, filter, framePts, onProgress }) {
const ffmpegQuality = getFffmpegJpegQuality(quality);
const args = [
@@ -755,7 +755,7 @@ export async function captureFrames({ from, to, videoPath, outPathTemplate, qual
'-q:v', ffmpegQuality,
...(filter != null ? ['-vf', filter] : []),
// https://superuser.com/questions/1336285/use-ffmpeg-for-thumbnail-selections
- // '-frame_pts', '1', // if we set this, output file name frame numbers will not start at 0
+ ...(framePts ? ['-frame_pts', '1'] : []),
'-vsync', '0', // else we get a ton of duplicates (thumbnail filter)
'-y', outPathTemplate,
];
diff --git a/src/hooks/useUserSettingsRoot.js b/src/hooks/useUserSettingsRoot.js
index dc6bdb38..f336cf29 100644
--- a/src/hooks/useUserSettingsRoot.js
+++ b/src/hooks/useUserSettingsRoot.js
@@ -121,6 +121,8 @@ export default () => {
useEffect(() => safeSetConfig('captureFrameMethod', captureFrameMethod), [captureFrameMethod]);
const [captureFrameQuality, setCaptureFrameQuality] = useState(safeGetConfigInitial('captureFrameQuality'));
useEffect(() => safeSetConfig('captureFrameQuality', captureFrameQuality), [captureFrameQuality]);
+ const [captureFrameFileNameFormat, setCaptureFrameFileNameFormat] = useState(safeGetConfigInitial('captureFrameFileNameFormat'));
+ useEffect(() => safeSetConfig('captureFrameFileNameFormat', captureFrameFileNameFormat), [captureFrameFileNameFormat]);
const resetKeyBindings = useCallback(() => {
configStore.reset('keyBindings');
@@ -221,5 +223,7 @@ export default () => {
setCaptureFrameMethod,
captureFrameQuality,
setCaptureFrameQuality,
+ captureFrameFileNameFormat,
+ setCaptureFrameFileNameFormat,
};
};
diff --git a/src/util.js b/src/util.js
index b18d7dbb..7224b5a2 100644
--- a/src/util.js
+++ b/src/util.js
@@ -27,7 +27,7 @@ export function getOutDir(customOutDir, filePath) {
return undefined;
}
-export function getFileBaseName(filePath) {
+function getFileBaseName(filePath) {
if (!filePath) return undefined;
const parsed = parsePath(filePath);
return parsed.name;
@@ -38,9 +38,11 @@ export function getOutPath({ customOutDir, filePath, fileName }) {
return join(getOutDir(customOutDir, filePath), fileName);
}
+export const getSuffixedFileName = (filePath, nameSuffix) => `${getFileBaseName(filePath)}-${nameSuffix}`;
+
export function getSuffixedOutPath({ customOutDir, filePath, nameSuffix }) {
if (!filePath) return undefined;
- return getOutPath({ customOutDir, filePath, fileName: `${getFileBaseName(filePath)}-${nameSuffix}` });
+ return getOutPath({ customOutDir, filePath, fileName: getSuffixedFileName(filePath, nameSuffix) });
}
export async function havePermissionToReadFile(filePath) {
@@ -222,7 +224,7 @@ export const html5dummySuffix = 'dummy';
export async function findExistingHtml5FriendlyFile(fp, cod) {
// The order is the priority we will search:
const suffixes = ['slowest', 'slow-audio', 'slow', 'fast-audio-remux', 'fast-audio', 'fast', 'fastest-audio', 'fastest-audio-remux', html5dummySuffix];
- const prefix = `${getFileBaseName(fp)}-${html5ifiedPrefix}`;
+ const prefix = getSuffixedFileName(fp, html5ifiedPrefix);
const outDir = getOutDir(cod, fp);
const dirEntries = await readdir(outDir);
@@ -354,3 +356,8 @@ export function shuffleArray(arrayIn) {
return array;
}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
+export function escapeRegExp(string) {
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
+}