Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

true keyframe cut #1984

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/renderer/src/dialogs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,9 @@ export async function askForAlignSegments() {
nearest: i18n.t('Nearest keyframe'),
before: i18n.t('Previous keyframe'),
after: i18n.t('Next keyframe'),
keyframeCutFix: i18n.t('True keyframe cut'),
},
inputValue: 'before',
inputValue: 'keyframeCutFix',
text: i18n.t('Do you want to align segment times to the nearest, previous or next keyframe?'),
});

Expand Down
5 changes: 4 additions & 1 deletion src/renderer/src/ffmpeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export const findNextKeyframe = (keyframes: Keyframe[], time: number) => keyfram
const findPreviousKeyframe = (keyframes: Keyframe[], time: number) => keyframes.findLast((keyframe) => keyframe.time <= time);
const findNearestKeyframe = (keyframes: Keyframe[], time: number) => minBy(keyframes, (keyframe) => Math.abs(keyframe.time - time));

export type FindKeyframeMode = 'nearest' | 'before' | 'after';
export type FindKeyframeMode = 'nearest' | 'before' | 'after' | 'keyframeCutFix';

function findKeyframe(keyframes: Keyframe[], time: number, mode: FindKeyframeMode) {
switch (mode) {
Expand All @@ -119,6 +119,9 @@ function findKeyframe(keyframes: Keyframe[], time: number, mode: FindKeyframeMod
case 'after': {
return findNextKeyframe(keyframes, time);
}
case 'keyframeCutFix': {
return findNextKeyframe(keyframes,time);
}
default: {
return undefined;
}
Expand Down
43 changes: 36 additions & 7 deletions src/renderer/src/hooks/useSegments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import pMap from 'p-map';
import invariant from 'tiny-invariant';
import sortBy from 'lodash/sortBy';

import { detectSceneChanges as ffmpegDetectSceneChanges, readFrames, mapTimesToSegments, findKeyframeNearTime } from '../ffmpeg';
import { detectSceneChanges as ffmpegDetectSceneChanges, readFrames, mapTimesToSegments, findKeyframeNearTime, getStreamFps } from '../ffmpeg';
import { handleError, shuffleArray } from '../util';
import { errorToast } from '../swal';
import { showParametersDialog } from '../dialogs/parameters';
Expand Down Expand Up @@ -280,26 +280,55 @@ function useSegments({ filePath, workingRef, setWorking, setCutProgress, videoSt
if (response == null) return;
setWorking({ text: i18n.t('Aligning segments to keyframes') });
const { mode, startOrEnd } = response;

if (filePath == null) throw new Error();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve error handling message.

The error handling at line 284 should provide more descriptive messages to help with debugging, especially since this function deals with critical segment timing adjustments.

Consider adding a more descriptive error message:

- if (filePath == null) throw new Error();
+ if (filePath == null) throw new Error('File path is required for alignment.');
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (filePath == null) throw new Error();
if (filePath == null) throw new Error('File path is required for alignment.');

const frameTime = 1 / (getStreamFps(videoStream) || 1000);

await modifySelectedSegmentTimes(async (segment) => {
const newSegment = { ...segment };

async function align(key) {
async function align(key: string) {
const time = newSegment[key];
if (filePath == null) throw new Error();
const keyframe = await findKeyframeNearTime({ filePath, streamIndex: videoStream.index, time, mode });
if (keyframe == null) throw new Error(`Cannot find any keyframe within 60 seconds of frame ${time}`);
let keyframe = await findKeyframeNearTime({ filePath, streamIndex: videoStream.index, time, mode });
if (keyframe === null) {
if (mode !== 'keyframeCutFix') {
throw new Error(`Cannot find any keyframe within 60 seconds of frame ${time}`);
}
keyframe = duration;
}
newSegment[key] = keyframe;
}
if (startOrEnd.includes('start')) await align('start');
if (startOrEnd.includes('end')) await align('end');
if (startOrEnd.includes('start')) {
if (mode === 'keyframeCutFix') {
newSegment.start += frameTime * 0.3;
}
await align('start');
if (mode === 'keyframeCutFix') {
newSegment.start -= frameTime * 0.7;
}
}
if (startOrEnd.includes('end')) {
await align('end');
if (mode === 'keyframeCutFix' && newSegment.end !== duration) {
newSegment.end -= frameTime * 0.3;
}
}
if (startOrEnd.includes('start')) {
newSegment.start = Math.min(newSegment.start, newSegment.end - frameTime * 0.99); // don't know how ffmpeg interprets cuts between frames
} else {
newSegment.end = Math.max(newSegment.start + frameTime * 0.99, newSegment.end);
}


return newSegment;
});
} catch (err) {
handleError(err);
} finally {
setWorking(undefined);
}
}, [filePath, videoStream, modifySelectedSegmentTimes, setWorking, workingRef]);
}, [filePath, videoStream, modifySelectedSegmentTimes, setWorking, workingRef, duration]);

const updateSegOrder = useCallback((index, newOrder) => {
if (newOrder > cutSegments.length - 1 || newOrder < 0) return;
Expand Down