The swiss army knife of lossless video/audio editing
Implement Extract all frames as images
Mikael Finstad9bdc93275d7c
diff --git a/README.md b/README.mdindex b54d3e9b..f94457df 100644--- a/README.md+++ b/README.md@@ -35,7 +35,7 @@ The main feature is lossless trimming and cutting of video and audio files, whic- Batch view for fast multi-file workflow- Keyboard shortcut workflow- Lossless remux video/audio into any compatible output format-- Take full-resolution snapshots from videos in JPEG/PNG format+- Take full-resolution snapshots from videos in JPEG/PNG format, or export ranges of video frames to images- Manual input of cutpoint times- Apply a per-file timecode offset (and auto load timecode from file)- Edit file metadata, per-track metadata and per-track disposition@@ -73,6 +73,7 @@ The main feature is lossless trimming and cutting of video and audio files, whic- Great for rotating phone videos that come out the wrong way without actually re-encoding the video.- Loop a video / audio clip X times quickly without re-encoding- See [#284](https://github.com/mifi/lossless-cut/issues/284)+- Convert a video or parts of it into X image files (not lossless)### Export cut times as YouTube Chapters1. Export with Merge and "Create chapters from merged segments" enableddiff --git a/src/App.jsx b/src/App.jsxindex 9a436580..f2ae07df 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -49,7 +49,7 @@ import OutputFormatSelect from './components/OutputFormatSelect';import { loadMifiLink } from './mifi';import { controlsBackground } from './colors';-import { captureFrameFromTag, captureFrameFfmpeg } from './capture-frame';+import { captureFrameFromTag, captureFramesFfmpeg } from './capture-frame';import {getStreamFps, isCuttingStart, isCuttingEnd,readFileMeta, getSmarterOutFormat, renderThumbnails as ffmpegRenderThumbnails,@@ -69,7 +69,7 @@ import {} from './util';import { formatDuration } from './util/duration';import { adjustRate } from './util/rate-calculator';-import { askForOutDir, askForInputDir, askForImportChapters, createNumSegments as createNumSegmentsDialog, createFixedDurationSegments as createFixedDurationSegmentsDialog, promptTimeOffset, askForHtml5ifySpeed, askForFileOpenAction, confirmExtractAllStreamsDialog, showCleanupFilesDialog, showDiskFull, showCutFailedDialog, labelSegmentDialog, openYouTubeChaptersDialog, openAbout, showEditableJsonDialog, askForShiftSegments, selectSegmentsByLabelDialog } from './dialogs';+import { askForOutDir, askForInputDir, askForImportChapters, createNumSegments as createNumSegmentsDialog, createFixedDurationSegments as createFixedDurationSegmentsDialog, promptTimeOffset, askForHtml5ifySpeed, askForFileOpenAction, confirmExtractAllStreamsDialog, showCleanupFilesDialog, showDiskFull, showCutFailedDialog, labelSegmentDialog, openYouTubeChaptersDialog, openAbout, showEditableJsonDialog, askForShiftSegments, selectSegmentsByLabelDialog, confirmExtractFramesAsImages } from './dialogs';import { openSendReportDialog } from './reporting';import { fallbackLng } from './i18n';import { createSegment, getCleanCutSegments, getSegApparentStart, findSegmentsAtCursor, sortSegments, invertSegments, getSegmentTags, convertSegmentsToChapters, hasAnySegmentOverlap } from './segments';@@ -1375,8 +1375,8 @@ const App = memo(() => {try {const currentTime = getCurrentTime();const video = videoRef.current;- const outPath = previewFilePath- ? await captureFrameFfmpeg({ customOutDir, filePath, currentTime, captureFormat, enableTransferTimestamps })+ const outPath = usingPreviewFile+ ? await captureFramesFfmpeg({ customOutDir, filePath, fromTime: currentTime, captureFormat, enableTransferTimestamps, numFrames: 1 }): await captureFrameFromTag({ customOutDir, filePath, currentTime, captureFormat, video, enableTransferTimestamps });if (!hideAllNotifications) openDirToast({ dirPath: outputDir, text: `${i18n.t('Screenshot captured to:')} ${outPath}` });@@ -1384,7 +1384,27 @@ const App = memo(() => {console.error(err);errorToast(i18n.t('Failed to capture frame'));}- }, [filePath, getCurrentTime, previewFilePath, customOutDir, captureFormat, enableTransferTimestamps, hideAllNotifications, outputDir]);+ }, [filePath, getCurrentTime, usingPreviewFile, customOutDir, captureFormat, enableTransferTimestamps, hideAllNotifications, outputDir]);++ const extractSegmentFramesAsImages = useCallback(async (index) => {+ if (!filePath) return;+ const { start, end } = apparentCutSegments[index];+ const numFrames = getFrameCount(end - start);+ if (numFrames < 1) return;+ if (!(await confirmExtractFramesAsImages({ numFrames }))) return;++ try {+ setWorking(i18n.t('Extracting frames'));+ await captureFramesFfmpeg({ customOutDir, filePath, fromTime: start, captureFormat, enableTransferTimestamps, numFrames });+ if (!hideAllNotifications) openDirToast({ dirPath: outputDir, text: i18n.t('Frames extracted to: {{path}}', { path: outputDir }) });+ } catch (err) {+ handleError(err);+ } finally {+ setWorking();+ }+ }, [apparentCutSegments, captureFormat, customOutDir, enableTransferTimestamps, filePath, getFrameCount, hideAllNotifications, outputDir, setWorking]);++ const extractCurrentSegmentFramesAsImages = useCallback(() => extractSegmentFramesAsImages(currentSegIndexSafe), [currentSegIndexSafe, extractSegmentFramesAsImages]);const changePlaybackRate = useCallback((dir, rateMultiplier) => {if (canvasPlayerEnabled) {@@ -1848,6 +1868,7 @@ const App = memo(() => {addSegment,toggleHelp: () => { toggleHelp(); return false; },export: onExportPress,+ extractCurrentSegmentFramesAsImages,reorderSegsByStartTime,invertAllSegments,fillSegmentsGaps,@@ -1914,7 +1935,7 @@ const App = memo(() => {if (match) return bubble;return true; // bubble the event- }, [addSegment, askSetStartTimeOffset, batchFileJump, batchOpenSelectedFile, captureSnapshot, changePlaybackRate, cleanupFilesDialog, clearSegments, closeBatch, closeExportConfirm, concatCurrentBatch, concatDialogVisible, convertFormatBatch, createFixedDurationSegments, createNumSegments, currentSegIndexSafe, cutSegmentsHistory, deselectAllSegments, exportConfirmVisible, extractAllStreams, fillSegmentsGaps, goToTimecode, increaseRotation, invertAllSegments, jumpCutEnd, jumpCutStart, jumpSeg, jumpTimelineEnd, jumpTimelineStart, keyboardNormalSeekSpeed, keyboardSeekAccFactor, keyboardShortcutsVisible, onExportConfirm, onExportPress, onLabelSegmentPress, pause, play, removeCutSegment, removeSelectedSegments, reorderSegsByStartTime, seekClosestKeyframe, seekRel, seekRelPercent, selectAllSegments, selectOnlyCurrentSegment, setCutEnd, setCutStart, setPlaybackVolume, shortStep, shuffleSegments, splitCurrentSegment, timelineToggleComfortZoom, toggleCaptureFormat, toggleCurrentSegmentSelected, toggleHelp, toggleKeyboardShortcuts, toggleKeyframeCut, togglePlay, toggleSegmentsList, toggleStreamsSelector, toggleStripAudio, tryFixInvalidDuration, userHtml5ifyCurrentFile, zoomRel]);+ }, [addSegment, askSetStartTimeOffset, batchFileJump, batchOpenSelectedFile, captureSnapshot, changePlaybackRate, cleanupFilesDialog, clearSegments, closeBatch, closeExportConfirm, concatCurrentBatch, concatDialogVisible, convertFormatBatch, createFixedDurationSegments, createNumSegments, currentSegIndexSafe, cutSegmentsHistory, deselectAllSegments, exportConfirmVisible, extractAllStreams, extractCurrentSegmentFramesAsImages, fillSegmentsGaps, goToTimecode, increaseRotation, invertAllSegments, jumpCutEnd, jumpCutStart, jumpSeg, jumpTimelineEnd, jumpTimelineStart, keyboardNormalSeekSpeed, keyboardSeekAccFactor, keyboardShortcutsVisible, onExportConfirm, onExportPress, onLabelSegmentPress, pause, play, removeCutSegment, removeSelectedSegments, reorderSegsByStartTime, seekClosestKeyframe, seekRel, seekRelPercent, selectAllSegments, selectOnlyCurrentSegment, setCutEnd, setCutStart, setPlaybackVolume, shortStep, shuffleSegments, splitCurrentSegment, timelineToggleComfortZoom, toggleCaptureFormat, toggleCurrentSegmentSelected, toggleHelp, toggleKeyboardShortcuts, toggleKeyframeCut, togglePlay, toggleSegmentsList, toggleStreamsSelector, toggleStripAudio, tryFixInvalidDuration, userHtml5ifyCurrentFile, zoomRel]);useKeyboard({ keyBindings, onKeyPress });@@ -2343,6 +2364,7 @@ const App = memo(() => {onToggleSegmentSelected={toggleSegmentSelected}onDeselectAllSegments={deselectAllSegments}onSelectAllSegments={selectAllSegments}+ onExtractSegmentFramesAsImages={extractSegmentFramesAsImages}jumpSegStart={jumpSegStart}jumpSegEnd={jumpSegEnd}onViewSegmentTagsPress={onViewSegmentTagsPress}diff --git a/src/SegmentList.jsx b/src/SegmentList.jsxindex fda527ab..16d8eec9 100644--- a/src/SegmentList.jsx+++ b/src/SegmentList.jsx@@ -21,7 +21,7 @@ const buttonBaseStyle = {const neutralButtonColor = 'rgba(255, 255, 255, 0.2)';-const Segment = memo(({ seg, index, currentSegIndex, formatTimecode, getFrameCount, updateOrder, invertCutSegments, onClick, onRemovePress, onRemoveSelectedPress, onReorderPress, onLabelPress, enabled, onSelectSingleSegment, onToggleSegmentSelected, onDeselectAllSegments, onSelectSegmentsByLabel, onSelectAllSegments, jumpSegStart, jumpSegEnd, addSegment, onViewSegmentTagsPress }) => {+const Segment = memo(({ seg, index, currentSegIndex, formatTimecode, getFrameCount, updateOrder, invertCutSegments, onClick, onRemovePress, onRemoveSelectedPress, onReorderPress, onLabelPress, enabled, onSelectSingleSegment, onToggleSegmentSelected, onDeselectAllSegments, onSelectSegmentsByLabel, onSelectAllSegments, jumpSegStart, jumpSegEnd, addSegment, onViewSegmentTagsPress, onExtractSegmentFramesAsImages }) => {const { t } = useTranslation();const ref = useRef();@@ -55,8 +55,9 @@ const Segment = memo(({ seg, index, currentSegIndex, formatTimecode, getFrameCou{ type: 'separator' },{ label: t('Segment tags'), click: () => onViewSegmentTagsPress(index) },+ { label: t('Extract all frames as images'), click: () => onExtractSegmentFramesAsImages(index) },];- }, [invertCutSegments, t, jumpSegStart, jumpSegEnd, addSegment, onLabelPress, onRemovePress, onRemoveSelectedPress, onReorderPress, updateOrder, onSelectSingleSegment, seg, onSelectAllSegments, onDeselectAllSegments, onSelectSegmentsByLabel, onViewSegmentTagsPress, index]);+ }, [invertCutSegments, t, jumpSegStart, jumpSegEnd, addSegment, onLabelPress, onRemovePress, onRemoveSelectedPress, onReorderPress, updateOrder, onSelectSingleSegment, seg, onSelectAllSegments, onDeselectAllSegments, onSelectSegmentsByLabel, onViewSegmentTagsPress, index, onExtractSegmentFramesAsImages]);useContextMenu(ref, contextMenuTemplate);@@ -137,7 +138,7 @@ const SegmentList = memo(({currentSegIndex,updateSegOrder, updateSegOrders, addSegment, removeCutSegment, onRemoveSelectedPress,onLabelSegmentPress, currentCutSeg, segmentAtCursor, toggleSegmentsList, splitCurrentSegment,- selectedSegments, selectedSegmentsRaw, onSelectSingleSegment, onToggleSegmentSelected, onDeselectAllSegments, onSelectAllSegments, onSelectSegmentsByLabel,+ selectedSegments, selectedSegmentsRaw, onSelectSingleSegment, onToggleSegmentSelected, onDeselectAllSegments, onSelectAllSegments, onSelectSegmentsByLabel, onExtractSegmentFramesAsImages,jumpSegStart, jumpSegEnd, onViewSegmentTagsPress,}) => {const { t } = useTranslation();@@ -290,6 +291,7 @@ const SegmentList = memo(({onSelectAllSegments={onSelectAllSegments}onViewSegmentTagsPress={onViewSegmentTagsPress}onSelectSegmentsByLabel={onSelectSegmentsByLabel}+ onExtractSegmentFramesAsImages={onExtractSegmentFramesAsImages}/>);})}diff --git a/src/capture-frame.js b/src/capture-frame.jsindex aebb24b0..11784948 100644--- a/src/capture-frame.js+++ b/src/capture-frame.js@@ -20,13 +20,19 @@ function getFrameFromVideo(video, format) {return strongDataUri.decode(dataUri);}-export async function captureFrameFfmpeg({ customOutDir, filePath, currentTime, captureFormat, enableTransferTimestamps }) {- const time = formatDuration({ seconds: currentTime, fileNameFriendly: true });-- const outPath = getOutPath({ customOutDir, filePath, nameSuffix: `${time}.${captureFormat}` });- await ffmpegCaptureFrame({ timestamp: currentTime, videoPath: filePath, outPath });-- if (enableTransferTimestamps) await transferTimestamps(filePath, outPath, currentTime);+export async function captureFramesFfmpeg({ customOutDir, filePath, fromTime, captureFormat, enableTransferTimestamps, numFrames }) {+ const time = formatDuration({ seconds: fromTime, fileNameFriendly: true });+ let nameSuffix;+ if (numFrames > 1) {+ const numDigits = Math.floor(Math.log10(numFrames)) + 1;+ nameSuffix = `${time}-%0${numDigits}d.${captureFormat}`;+ } else {+ nameSuffix = `${time}.${captureFormat}`;+ }+ const outPath = getOutPath({ customOutDir, filePath, nameSuffix });+ await ffmpegCaptureFrame({ timestamp: fromTime, videoPath: filePath, outPath, numFrames });++ if (enableTransferTimestamps && numFrames === 1) await transferTimestamps(filePath, outPath, fromTime);return outPath;}diff --git a/src/components/KeyboardShortcuts.jsx b/src/components/KeyboardShortcuts.jsxindex c69c957f..7570c415 100644--- a/src/components/KeyboardShortcuts.jsx+++ b/src/components/KeyboardShortcuts.jsx@@ -366,6 +366,10 @@ const KeyboardShortcuts = memo(({name: t('Capture snapshot'),category: outputCategory,},+ extractCurrentSegmentFramesAsImages: {+ name: t('Extract all frames in segment as images'),+ category: outputCategory,+ },cleanupFilesDialog: {name: t('Delete source file'),category: outputCategory,diff --git a/src/dialogs.jsx b/src/dialogs.jsxindex a90b54d0..477fa065 100644--- a/src/dialogs.jsx+++ b/src/dialogs.jsx@@ -291,6 +291,15 @@ export async function confirmExtractAllStreamsDialog() {return !!value;}+export async function confirmExtractFramesAsImages({ numFrames }) {+ const { value } = await Swal.fire({+ text: i18n.t('Please confirm that you want to extract all {{numFrames}} frames as separate images', { numFrames }),+ showCancelButton: true,+ confirmButtonText: i18n.t('Extract all frames'),+ });+ return !!value;+}+const CleanupChoices = ({ cleanupChoicesInitial, onChange: onChangeProp }) => {const [choices, setChoices] = useState(cleanupChoicesInitial);diff --git a/src/ffmpeg.js b/src/ffmpeg.jsindex ab2d0473..d2098268 100644--- a/src/ffmpeg.js+++ b/src/ffmpeg.js@@ -541,18 +541,17 @@ export async function extractWaveform({ filePath, outPath }) {console.timeEnd('ffmpeg');}+const imageCaptureQuality = 3;+// See also capture-frame.js-export async function captureFrame({ timestamp, videoPath, outPath }) {- const args = [+export async function captureFrame({ timestamp, videoPath, outPath, numFrames }) {+ await runFfmpeg(['-ss', timestamp,'-i', videoPath,- '-vframes', '1',- '-q:v', '3',+ '-vframes', numFrames,+ '-q:v', imageCaptureQuality,'-y', outPath,- ];-- const ffmpegPath = getFfmpegPath();- await execa(ffmpegPath, args, { encoding: null });+ ]);}