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 2 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'),
consistent: i18n.t('True keyframe cut'),
},
inputValue: 'before',
inputValue: 'consistent',
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' | 'consistent';

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 'consistent': {
return findNextKeyframe(keyframes,time);
}
default: {
return undefined;
}
Expand Down
43 changes: 37 additions & 6 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, getDuration } from '../ffmpeg';
import { handleError, shuffleArray } from '../util';
import { errorToast } from '../swal';
import { showParametersDialog } from '../dialogs/parameters';
Expand Down Expand Up @@ -280,18 +280,49 @@ 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.

The error handling should provide more descriptive messages to help with debugging.

- 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);
const duration = await getDuration(filePath);

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 != 'consistent') {
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 == 'consistent') {
newSegment.start += frameTime * 0.3;
}
await align('start');
if (mode == 'consistent') {
newSegment.start -= frameTime * 0.7;
}
}
if (startOrEnd.includes('end')) {
await align('end');
if (mode == 'consistent' && 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);
}


Comment on lines +283 to +325
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

There are no unit tests covering the new 'consistent' keyframe alignment mode or the useSegments function. This lack of test coverage could lead to untested edge cases and potential issues in production.

  • Ensure that unit tests are added to cover the 'consistent' mode, including edge cases where keyframes might not be found within the expected range.
  • Consider adding tests for the useSegments function to ensure comprehensive coverage.
Analysis chain

The implementation of the new 'consistent' keyframe alignment mode is complex and involves several conditional checks and adjustments to segment times. Ensure thorough testing, especially edge cases where keyframes might not be found within the expected range.

Would you like assistance in writing additional unit tests for this new feature?

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the new 'consistent' mode is covered by unit tests.

# Test: Search for unit tests covering the 'consistent' mode. Expect: Tests that handle various scenarios including edge cases.
rg --type typescript $'describe.*(consistent)'

Length of output: 82



Script:

#!/bin/bash
# Description: Verify the new 'consistent' mode is covered by unit tests.

# Test: Search for unit tests covering the 'consistent' mode. Expect: Tests that handle various scenarios including edge cases.
rg --type ts $'describe.*(consistent)'

Length of output: 39



Script:

#!/bin/bash
# Description: Verify if there are any tests related to the `useSegments` function.

# Test: Search for test cases related to `useSegments`. Expect: Tests that might indirectly cover the 'consistent' mode.
rg --type ts 'useSegments'

Length of output: 880



Script:

#!/bin/bash
# Description: Verify if there are any test files in the repository.

# Test: Search for test files in the repository. Expect: Files that might contain tests for `useSegments`.
fd --type f --extension ts --exec rg 'test|describe|it'

Length of output: 80538

Comment on lines +291 to +325
Copy link

Choose a reason for hiding this comment

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

This block introduces complex logic for aligning segment times based on the new 'consistent' keyframe mode. Consider breaking down this large anonymous function into smaller, named functions to improve readability and maintainability.

+ async function adjustSegmentTime(segment, key, mode, frameTime, duration) {
+   const time = segment[key];
+   if (filePath == null) throw new Error('File path is required to find keyframes.');
+   let keyframe = await findKeyframeNearTime({ filePath, streamIndex: videoStream.index, time, mode });
+   if (keyframe == null) {
+     if (mode != 'consistent') {
+       throw new Error(`Cannot find any keyframe within 60 seconds of frame ${time}`);
+     }
+     keyframe = duration;
+   }
+   segment[key] = keyframe;
+   return segment;
+ }

-      await modifySelectedSegmentTimes(async (segment) => {
+      await modifySelectedSegmentTime(segment => adjustSegmentTime(segment, 'start', mode, frameTime, duration));
+      await modifySelectedSegmentTime(segment => adjustSegmentTime(segment, 'end', mode, frameTime, duration));

Committable suggestion was skipped due to low confidence.

return newSegment;
});
} catch (err) {
Expand Down