Skip to content

Commit

Permalink
allow custom smart cut bitrate
Browse files Browse the repository at this point in the history
closes #1997 #1824
see #126
  • Loading branch information
mifi committed May 16, 2024
1 parent b5028dc commit 096db54
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 9 deletions.
5 changes: 3 additions & 2 deletions src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ function App() {
const [editingSegmentTagsSegmentIndex, setEditingSegmentTagsSegmentIndex] = useState<number>();
const [editingSegmentTags, setEditingSegmentTags] = useState<SegmentTags>();
const [mediaSourceQuality, setMediaSourceQuality] = useState(0);
const [smartCutBitrate, setSmartCutBitrate] = useState<number | undefined>();

const incrementMediaSourceQuality = useCallback(() => setMediaSourceQuality((v) => (v + 1) % mediaSourceQualities.length), []);

Expand Down Expand Up @@ -836,7 +837,7 @@ function App() {

const {
concatFiles, html5ifyDummy, cutMultiple, autoConcatCutSegments, html5ify, fixInvalidDuration,
} = useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treatOutputFileModifiedTimeAsStart, needSmartCut, enableOverwriteOutput, outputPlaybackRate, cutFromAdjustmentFrames, appendLastCommandsLog });
} = useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treatOutputFileModifiedTimeAsStart, needSmartCut, enableOverwriteOutput, outputPlaybackRate, cutFromAdjustmentFrames, appendLastCommandsLog, smartCutCustomBitrate: smartCutBitrate });

const html5ifyAndLoad = useCallback(async (cod: string | undefined, fp: string, speed: Html5ifyMode, hv: boolean, ha: boolean) => {
const usesDummyVideo = speed === 'fastest';
Expand Down Expand Up @@ -2733,7 +2734,7 @@ function App() {
/>
</div>

<ExportConfirm areWeCutting={areWeCutting} nonFilteredSegmentsOrInverse={nonFilteredSegmentsOrInverse} selectedSegments={selectedSegmentsOrInverse} segmentsToExport={segmentsToExport} willMerge={willMerge} visible={exportConfirmVisible} onClosePress={closeExportConfirm} onExportConfirm={onExportConfirm} renderOutFmt={renderOutFmt} outputDir={outputDir} numStreamsTotal={numStreamsTotal} numStreamsToCopy={numStreamsToCopy} onShowStreamsSelectorClick={handleShowStreamsSelectorClick} outFormat={fileFormat} setOutSegTemplate={setOutSegTemplate} outSegTemplate={outSegTemplateOrDefault} generateOutSegFileNames={generateOutSegFileNames} currentSegIndexSafe={currentSegIndexSafe} mainCopiedThumbnailStreams={mainCopiedThumbnailStreams} needSmartCut={needSmartCut} mergedOutFileName={mergedOutFileName} setMergedOutFileName={setMergedOutFileName} />
<ExportConfirm areWeCutting={areWeCutting} nonFilteredSegmentsOrInverse={nonFilteredSegmentsOrInverse} selectedSegments={selectedSegmentsOrInverse} segmentsToExport={segmentsToExport} willMerge={willMerge} visible={exportConfirmVisible} onClosePress={closeExportConfirm} onExportConfirm={onExportConfirm} renderOutFmt={renderOutFmt} outputDir={outputDir} numStreamsTotal={numStreamsTotal} numStreamsToCopy={numStreamsToCopy} onShowStreamsSelectorClick={handleShowStreamsSelectorClick} outFormat={fileFormat} setOutSegTemplate={setOutSegTemplate} outSegTemplate={outSegTemplateOrDefault} generateOutSegFileNames={generateOutSegFileNames} currentSegIndexSafe={currentSegIndexSafe} mainCopiedThumbnailStreams={mainCopiedThumbnailStreams} needSmartCut={needSmartCut} mergedOutFileName={mergedOutFileName} setMergedOutFileName={setMergedOutFileName} smartCutBitrate={smartCutBitrate} setSmartCutBitrate={setSmartCutBitrate} />

<Sheet visible={streamsSelectorShown} onClosePress={() => setStreamsSelectorShown(false)} maxWidth={1000}>
{mainStreams && filePath != null && (
Expand Down
37 changes: 36 additions & 1 deletion src/renderer/src/components/ExportConfirm.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CSSProperties, memo, useCallback, useMemo } from 'react';
import { CSSProperties, Dispatch, SetStateAction, memo, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { WarningSignIcon, CrossIcon } from 'evergreen-ui';
import { FaRegCheckCircle } from 'react-icons/fa';
Expand Down Expand Up @@ -28,6 +28,7 @@ import { InverseCutSegment, SegmentToExport } from '../types';
import { GenerateOutSegFileNames } from '../util/outputNameTemplate';
import { FFprobeStream } from '../../../../ffprobe';
import { AvoidNegativeTs } from '../../../../types';
import TextInput from './TextInput';


const boxStyle: CSSProperties = { margin: '15px 15px 50px 15px', borderRadius: 10, padding: '10px 20px', minHeight: 500, position: 'relative' };
Expand Down Expand Up @@ -61,6 +62,8 @@ const ExportConfirm = memo(({
needSmartCut,
mergedOutFileName,
setMergedOutFileName,
smartCutBitrate,
setSmartCutBitrate,
} : {
areWeCutting: boolean,
selectedSegments: InverseCutSegment[],
Expand All @@ -84,6 +87,8 @@ const ExportConfirm = memo(({
needSmartCut: boolean,
mergedOutFileName: string | undefined,
setMergedOutFileName: (a: string) => void,
smartCutBitrate: number | undefined,
setSmartCutBitrate: Dispatch<SetStateAction<number | undefined>>,
}) => {
const { t } = useTranslation();

Expand Down Expand Up @@ -165,6 +170,16 @@ const ExportConfirm = memo(({

const canEditTemplate = !willMerge || !autoDeleteMergedSegments;

const handleSmartCutBitrateToggle = useCallback((checked: boolean) => {
setSmartCutBitrate(() => (checked ? undefined : 10000));
}, [setSmartCutBitrate]);

const handleSmartCutBitrateChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const v = parseInt(e.target.value, 10);
if (Number.isNaN(v) || v <= 0) return;
setSmartCutBitrate(v);
}, [setSmartCutBitrate]);

// https://stackoverflow.com/questions/33454533/cant-scroll-to-top-of-flex-item-that-is-overflowing-container
return (
<AnimatePresence>
Expand Down Expand Up @@ -347,6 +362,26 @@ const ExportConfirm = memo(({
</td>
</tr>

{needSmartCut && (
<tr>
<td>
{t('Smart cut auto detect bitrate')}
</td>
<td>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
{smartCutBitrate != null && (
<>
<TextInput value={smartCutBitrate} onChange={handleSmartCutBitrateChange} style={{ width: '4em', flexGrow: 0, marginRight: '.3em' }} />
<span style={{ marginRight: '.3em' }}>{t('kbit/s')}</span>
</>
)}
<span><Switch checked={smartCutBitrate == null} onCheckedChange={handleSmartCutBitrateToggle} /></span>
</div>
</td>
<td />
</tr>
)}

{!needSmartCut && (
<tr>
<td>
Expand Down
13 changes: 7 additions & 6 deletions src/renderer/src/hooks/useFfmpegOperations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async function tryDeleteFiles(paths: string[]) {
return pMap(paths, (path) => unlinkWithRetry(path).catch((err) => console.error('Failed to delete', path, err)), { concurrency: 5 });
}

function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treatOutputFileModifiedTimeAsStart, needSmartCut, enableOverwriteOutput, outputPlaybackRate, cutFromAdjustmentFrames, appendLastCommandsLog }: {
function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treatOutputFileModifiedTimeAsStart, needSmartCut, enableOverwriteOutput, outputPlaybackRate, cutFromAdjustmentFrames, appendLastCommandsLog, smartCutCustomBitrate }: {
filePath: string | undefined,
treatInputFileModifiedTimeAsStart: boolean | null | undefined,
treatOutputFileModifiedTimeAsStart: boolean | null | undefined,
Expand All @@ -69,6 +69,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea
outputPlaybackRate: number,
cutFromAdjustmentFrames: number,
appendLastCommandsLog: (a: string) => void,
smartCutCustomBitrate: number | undefined,
}) {
const appendFfmpegCommandLog = useCallback((args: string[]) => appendLastCommandsLog(getFfCommandLine('ffmpeg', args)), [appendLastCommandsLog]);

Expand Down Expand Up @@ -412,7 +413,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea
return match ? [match] : [];
});

const { losslessCutFrom, segmentNeedsSmartCut, videoCodec, videoBitrate, videoStreamIndex, videoTimebase } = await getSmartCutParams({ path: filePath, videoDuration, desiredCutFrom, streams: streamsToCopyFromMainFile });
const { losslessCutFrom, segmentNeedsSmartCut, videoCodec, videoBitrate: detectedVideoBitrate, videoStreamIndex, videoTimebase } = await getSmartCutParams({ path: filePath, videoDuration, desiredCutFrom, streams: streamsToCopyFromMainFile });

if (segmentNeedsSmartCut && !detectedFps) throw new Error('Smart cut is not possible when FPS is unknown');

Expand All @@ -430,10 +431,10 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea
// eslint-disable-next-line no-shadow
async function cutEncodeSmartPartWrapper({ cutFrom, cutTo, outPath }) {
if (await shouldSkipExistingFile(outPath)) return;
if (videoCodec == null || videoBitrate == null || videoTimebase == null) throw new Error();
if (videoCodec == null || detectedVideoBitrate == null || videoTimebase == null) throw new Error();
invariant(filePath != null);
invariant(outFormat != null);
const args = await cutEncodeSmartPart({ filePath, cutFrom, cutTo, outPath, outFormat, videoCodec, videoBitrate, videoStreamIndex, videoTimebase, allFilesMeta, copyFileStreams: copyFileStreamsFiltered, ffmpegExperimental });
const args = await cutEncodeSmartPart({ filePath, cutFrom, cutTo, outPath, outFormat, videoCodec, videoBitrate: smartCutCustomBitrate != null ? smartCutCustomBitrate * 1000 : detectedVideoBitrate, videoStreamIndex, videoTimebase, allFilesMeta, copyFileStreams: copyFileStreamsFiltered, ffmpegExperimental });
appendFfmpegCommandLog(args);
}

Expand Down Expand Up @@ -497,7 +498,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea
} finally {
if (chaptersPath) await tryDeleteFiles([chaptersPath]);
}
}, [needSmartCut, filePath, losslessCutSingle, shouldSkipExistingFile, concatFiles]);
}, [needSmartCut, filePath, losslessCutSingle, shouldSkipExistingFile, smartCutCustomBitrate, appendFfmpegCommandLog, concatFiles]);

const autoConcatCutSegments = useCallback(async ({ customOutDir, outFormat, segmentPaths, ffmpegExperimental, onProgress, preserveMovData, movFastStart, autoDeleteMergedSegments, chapterNames, preserveMetadataOnMerge, mergedOutFilePath }) => {
const outDir = getOutDir(customOutDir, filePath);
Expand Down Expand Up @@ -576,7 +577,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea
await transferTimestamps({ inPath: filePath, outPath, treatOutputFileModifiedTimeAsStart });

return outPath;
}, [filePath, treatOutputFileModifiedTimeAsStart]);
}, [appendFfmpegCommandLog, filePath, treatOutputFileModifiedTimeAsStart]);

return {
cutMultiple, concatFiles, html5ify, html5ifyDummy, fixInvalidDuration, autoConcatCutSegments,
Expand Down

0 comments on commit 096db54

Please sign in to comment.