The swiss army knife of lossless video/audio editing
implement delete tags and `-itsoffset`
Mikael Finstad260601db0a7a
diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 5ae6007c..9f64ec4b 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -186,6 +186,7 @@"Defaults to same format as input file. You can losslessly change the file format (container) of the file with this option. Not all formats support all codecs. Matroska/MP4/MOV support the most common codecs. Sometimes it's even impossible to export to the same output format as input.": "Defaults to same format as input file. You can losslessly change the file format (container) of the file with this option. Not all formats support all codecs. Matroska/MP4/MOV support the most common codecs. Sometimes it's even impossible to export to the same output format as input.","Delete": "Delete","Delete source file": "Delete source file",+ "deleted": "deleted","Depending on your specific file/player, you may have to try different options for best results.": "Depending on your specific file/player, you may have to try different options for best results.","Deselect all segments": "Deselect all segments","Detect black scenes": "Detect black scenes",@@ -483,6 +484,7 @@"Merged output file name:": "Merged output file name:","Merging": "Merging","Meta": "Meta",+ "Metadata": "Metadata","Millisecond fractions": "Millisecond fractions","Mini-waveform has been enabled. Click again to enable full-screen waveform": "Mini-waveform has been enabled. Click again to enable full-screen waveform","Minimize": "Minimize",@@ -525,6 +527,7 @@"Note that this is not supported in all video players.": "Note that this is not supported in all video players.","Note that this only applies when extracting multiple frames. When \"Frame number\" is selected, frame numbers are relative to the start of the segment (starting from 1).": "Note that this only applies when extracting multiple frames. When \"Frame number\" is selected, frame numbers are relative to the start of the segment (starting from 1).","Note: Keyframe cut is recommended for most common files": "Note: Keyframe cut is recommended for most common files",+ "Offset": "Offset","OK": "OK","One frame back": "One frame back","One frame forward": "One frame forward",@@ -698,9 +701,11 @@"Shift all segments on the timeline by this amount. Negative values will be shifted back, while positive value will be shifted forward in time.": "Shift all segments on the timeline by this amount. Negative values will be shifted back, while positive value will be shifted forward in time.","Shift all segments on timeline": "Shift all segments on timeline","Shift all start times": "Shift all start times",+ "Shift by seconds": "Shift by seconds","Shift end by": "Shift end by","Shift segments": "Shift segments","Shift start by": "Shift start by",+ "Shift the timestamps of all tracks in this file by a specified number of seconds, relative to other files. Positive values will delay the file's tracks, negative will advance it.": "Shift the timestamps of all tracks in this file by a specified number of seconds, relative to other files. Positive values will delay the file's tracks, negative will advance it.","Shift timestamps so that the first timestamp is 0. (LosslessCut default)": "Shift timestamps so that the first timestamp is 0 (LosslessCut default).","Shift timestamps to make them non-negative. Also note that this affects only leading negative timestamps, and not non-monotonic negative timestamps.": "Shift timestamps to make them non-negative. Also note that this affects only leading negative timestamps, and not non-monotonic negative timestamps.","Shortest": "Shortest",@@ -758,7 +763,6 @@"Success!": "Success!","System default": "System default","System language": "System language",- "Tags": "Tags","Template error: {{error}}": "Template error: {{error}}","Text chapters / YouTube": "Text chapters / YouTube","The audio track is not supported while previewing. You can convert to a supported format from the menu": "The audio track is not supported while previewing. You can convert to a supported format from the menu",@@ -784,6 +788,7 @@"This file does not have a valid duration. This may cause issues. You can try to fix the file's duration from the File menu": "This file does not have a valid duration. This may cause issues. You can try to fix the file's duration from the File menu","This file has embedded chapters. Do you want to import the chapters as cut-segments?": "This file has embedded chapters. Do you want to import the chapters as cut-segments?","This gives you an overview of the export and allows you to customise more parameters before exporting, like changing the output file name.": "This gives you an overview of the export and allows you to customise more parameters before exporting, like changing the output file name.",+ "This is hardcoded by FFmpeg and cannot be changed.": "This is hardcoded by FFmpeg and cannot be changed.","This is where working files and exported files are stored.": "This is where working files and exported files are stored.","This option allows you to shift all segment start times forward by one or more frames before cutting. This can be useful if the output video starts from the wrong (preceding) keyframe.": "This option allows you to shift all segment start times forward by one or more frames before cutting. This can be useful if the output video starts from the wrong (preceding) keyframe.","This option lets you losslessly change the speed at which media players will play back the exported file. For example if you double the FPS, the playback speed will double (and duration will halve), however all the frames will be intact and played back (but faster). Be careful not to set it too high, as the player might not be able to keep up (playback CPU usage will increase proportionally to the speed!)": "This option lets you losslessly change the speed at which media players will play back the exported file. For example if you double the FPS, the playback speed will double (and duration will halve), however all the frames will be intact and played back (but faster). Be careful not to set it too high, as the player might not be able to keep up (playback CPU usage will increase proportionally to the speed!)",diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 23cf9fd5..8c532c69 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -96,7 +96,7 @@ import { generateCutFileNames as generateCutFileNamesRaw, generateCutMergedFileNimport { rightBarWidth, leftBarWidth, ffmpegExtractWindow, zoomMax } from './util/constants';import BigWaveform from './components/BigWaveform';-import type { BatchFile, Chapter, CustomTagsByFile, EdlExportType, EdlFileType, EdlImportType, FfmpegCommandLog, FilesMeta, FileStats, ParamsByStreamId, PlaybackMode, SegmentBase, SegmentColorIndex, SegmentTags, StateSegment, TunerType } from './types';+import type { BatchFile, Chapter, EdlExportType, EdlFileType, EdlImportType, FfmpegCommandLog, FilesMeta, FileStats, ParamsByFile, PlaybackMode, SegmentBase, SegmentColorIndex, SegmentTags, StateSegment, TunerType } from './types';import { goToTimecodeDirectArgsSchema, openFilesActionArgsSchema } from './types';import type { CaptureFormat, KeyboardAction, ApiActionRequest } from '../../common/types.js';import type { FFprobeChapter, FFprobeStream } from '../../common/ffprobe.js';@@ -147,8 +147,7 @@ function App() {const [filePath, setFilePath] = useState<string>();const [fileDuration, setFileDuration] = useState<number>();const [externalFilesMeta, setExternalFilesMeta] = useState<FilesMeta>({});- const [customTagsByFile, setCustomTagsByFile] = useState<CustomTagsByFile>({});- const [paramsByStreamId, setParamsByStreamId] = useState<ParamsByStreamId>(new Map());+ const [paramsByFile, setParamsByFile] = useState<ParamsByFile>(new Map());const [detectedFps, setDetectedFps] = useState<number>();const [mainFileMeta, setMainFileMeta] = useState<{ ffprobeMeta: FileFfprobeMeta, stats: FileStats }>();const [streamsSelectorShown, setStreamsSelectorShown] = useState(false);@@ -660,8 +659,7 @@ function App() {setStartTimeOffset(0);setFilePath(undefined);setExternalFilesMeta({});- setCustomTagsByFile({});- setParamsByStreamId(new Map());+ setParamsByFile(new Map());setDetectedFps(undefined);setMainFileMeta(undefined);setCopyStreamIdsByFile({});@@ -1113,8 +1111,7 @@ function App() {preserveChapters,movFastStart,avoidNegativeTs,- customTagsByFile,- paramsByStreamId,+ paramsByFile,chapters: chaptersToAdd,detectedFps,});@@ -1240,7 +1237,7 @@ function App() {setWorking(undefined);setProgress(undefined);}- }, [filePath, numStreamsToCopy, haveInvalidSegs, workingRef, setWorking, segmentsToChaptersOnly, cutFileTemplateOrDefault, generateCutFileNames, cutMultiple, outputDir, customOutDir, fileFormat, fileDuration, isRotationSet, effectiveRotation, copyFileStreams, allFilesMeta, keyframeCut, segmentsToExport, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMetadataOnMerge, preserveMovData, preserveChapters, movFastStart, avoidNegativeTs, customTagsByFile, paramsByStreamId, detectedFps, willMerge, enableOverwriteOutput, exportConfirmEnabled, mainFileFormat, mainStreams, exportExtraStreams, areWeCutting, simpleMode, prefersReducedMotion, cleanupChoices, hideAllNotifications, segmentsOrInverse.selected, t, cutMergedFileTemplateOrDefault, segmentsToChapters, invertCutSegments, generateCutMergedFileNames, concatCutSegments, autoDeleteMergedSegments, tryDeleteFiles, nonCopiedExtraStreams, extractStreams, askForCleanupChoices, cleanupFiles, showOsNotification, openCutFinishedDialog, handleExportFailed]);+ }, [filePath, numStreamsToCopy, haveInvalidSegs, workingRef, setWorking, segmentsToChaptersOnly, cutFileTemplateOrDefault, generateCutFileNames, cutMultiple, outputDir, customOutDir, fileFormat, fileDuration, isRotationSet, effectiveRotation, copyFileStreams, allFilesMeta, keyframeCut, segmentsToExport, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMetadataOnMerge, preserveMovData, preserveChapters, movFastStart, avoidNegativeTs, paramsByFile, detectedFps, willMerge, enableOverwriteOutput, exportConfirmEnabled, mainFileFormat, mainStreams, exportExtraStreams, areWeCutting, simpleMode, prefersReducedMotion, cleanupChoices, hideAllNotifications, segmentsOrInverse.selected, t, cutMergedFileTemplateOrDefault, segmentsToChapters, invertCutSegments, generateCutMergedFileNames, concatCutSegments, autoDeleteMergedSegments, tryDeleteFiles, nonCopiedExtraStreams, extractStreams, askForCleanupChoices, cleanupFiles, showOsNotification, openCutFinishedDialog, handleExportFailed]);const onExportPress = useCallback(async () => {if (!filePath) return;@@ -1768,16 +1765,16 @@ function App() {return fileMeta;}, [allFilesMeta, setCopyStreamIdsForPath]);- const updateStreamParams = useCallback<Parameters<typeof StreamsSelector>[0]['updateStreamParams']>((fileId, streamId, setter) => setParamsByStreamId(produce((draft) => {- if (!draft.has(fileId)) draft.set(fileId, new Map());+ const updateStreamParams = useCallback<Parameters<typeof StreamsSelector>[0]['updateStreamParams']>((fileId, streamId, setter) => setParamsByFile(produce((draft) => {+ if (!draft.has(fileId)) draft.set(fileId, { metadata: {}, paramsByStream: new Map() });const fileMap = draft.get(fileId);invariant(fileMap != null);- if (!fileMap.has(streamId)) fileMap.set(streamId, {});+ if (!fileMap.paramsByStream.has(streamId)) fileMap.paramsByStream.set(streamId, { metadata: {} });- const params = fileMap.get(streamId);+ const params = fileMap.paramsByStream.get(streamId);invariant(params != null);setter(params);- })), [setParamsByStreamId]);+ })), [setParamsByFile]);const captureSnapshotAsCoverArt = useCallback(async () => {if (!filePath) return;@@ -2778,9 +2775,8 @@ function App() {shortestFlag={shortestFlag}setShortestFlag={setShortestFlag}nonCopiedExtraStreams={nonCopiedExtraStreams}- customTagsByFile={customTagsByFile}- setCustomTagsByFile={setCustomTagsByFile}- paramsByStreamId={paramsByStreamId}+ paramsByFile={paramsByFile}+ setParamsByFile={setParamsByFile}updateStreamParams={updateStreamParams}formatTimecode={formatTimecode}loadSubtitleTrackToSegments={loadSubtitleTrackToSegments}diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex 54650bfd..09f0eec5 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -6,7 +6,8 @@ import { GoFileBinary } from 'react-icons/go';import { MdSubtitles } from 'react-icons/md';import { useTranslation, Trans } from 'react-i18next';import prettyBytes from 'pretty-bytes';-import { Tabs } from '@radix-ui/themes';+import { Tabs, TextField } from '@radix-ui/themes';+import { produce } from 'immer';import * as DropdownMenu from './components/DropdownMenu';import * as Dialog from './components/Dialog';@@ -17,12 +18,11 @@ import { getStreamFps } from './ffmpeg';import { getActiveDisposition, attachedPicDisposition, isGpsStream } from './util/streams';import TagEditor from './components/TagEditor';import type { FFprobeChapter, FFprobeFormat, FFprobeStream } from '../../common/ffprobe';-import { contentDispositionOptionsSchema, deleteDispositionValue, dispositionOptions, type ContentDispositionOptions, type CustomTagsByFile, type FilesMeta, type FormatTimecode, type ParamsByStreamId, type StreamParams } from './types';+import { contentDispositionOptionsSchema, deleteDispositionValue, dispositionOptions, type ContentDispositionOptions, type FileParams, type FilesMeta, type FormatTimecode, type ParamsByFile, type StreamParams } from './types';import Button, { DialogButton } from './components/Button';import styles from './StreamsSelector.module.css';import Json5Dialog from './components/Json5Dialog';import GpsMap from './components/GpsMap';-import TextInput from './components/TextInput';import Switch from './components/Switch';@@ -33,44 +33,14 @@ interface EditingStream {path: string;}-// eslint-disable-next-line react/display-name-const EditFileDialog = memo(({ editingFile, allFilesMeta, customTagsByFile, setCustomTagsByFile, editingTag, setEditingTag }: {- editingFile: string,- allFilesMeta: FilesMeta,- customTagsByFile: CustomTagsByFile,- setCustomTagsByFile: Dispatch<SetStateAction<CustomTagsByFile>>,- editingTag: string | undefined,- setEditingTag: (tag: string | undefined) => void,-}) => {- const { t } = useTranslation();-- const { format } = allFilesMeta[editingFile]!;- const existingTags = format.tags || {};- const customTags = customTagsByFile[editingFile];-- const onTagsChange = useCallback((keyValues: Record<string, string>) => {- setCustomTagsByFile((old) => ({ ...old, [editingFile]: { ...old[editingFile], ...keyValues } }));- }, [editingFile, setCustomTagsByFile]);-- const onTagReset = useCallback((tag: string) => {- setCustomTagsByFile((old) => {- // eslint-disable-next-line @typescript-eslint/no-unused-vars- const { [tag]: deleted, ...rest } = old[editingFile] || {};- return { ...old, [editingFile]: rest };- });- }, [editingFile, setCustomTagsByFile]);-- return <TagEditor existingTags={existingTags} customTags={customTags} editingTag={editingTag} setEditingTag={setEditingTag} onTagsChange={onTagsChange} onTagReset={onTagReset} addTagTitle={t('Add metadata')} />;-});-const getStreamDispositionsObj = (stream: FFprobeStream) => ((stream && stream.disposition) || {});-const getStreamParams = ({ paramsByStreamId, filePath, streamId }: { paramsByStreamId: ParamsByStreamId, filePath: string, streamId: number }) => (- paramsByStreamId.get(filePath)?.get(streamId) ?? {}+const getStreamParams = ({ paramsByFile, filePath, streamId }: { paramsByFile: ParamsByFile, filePath: string, streamId: number }) => (+ paramsByFile.get(filePath)?.paramsByStream.get(streamId));-function getStreamEffectiveDisposition(paramsByStreamId: ParamsByStreamId, fileId: string, stream: FFprobeStream) {- const customDisposition = getStreamParams({ paramsByStreamId, filePath: fileId, streamId: stream.index }).disposition;+function getStreamEffectiveDisposition(paramsByFile: ParamsByFile, fileId: string, stream: FFprobeStream) {+ const customDisposition = getStreamParams({ paramsByFile, filePath: fileId, streamId: stream.index })?.disposition;const existingDispositionsObj = getStreamDispositionsObj(stream);if (customDisposition) return customDisposition;@@ -89,12 +59,12 @@ function KeyValue({ name, value }: { name: ReactNode, value: ReactNode }) {function AspectEditor({ stream, streamParams, updateStreamParams }: {stream: FFprobeStream,- streamParams: StreamParams,+ streamParams: StreamParams | undefined,updateStreamParams: (setter: (a: StreamParams) => void) => void,}) {const { t } = useTranslation();- const currentAr = streamParams.aspectRatio ?? { num: 0, den: 0 };+ const currentAr = streamParams?.aspectRatio ?? { num: 0, den: 0 };const updateAr = (field: 'num' | 'den', value: string) => {const parsed = parseInt(value, 10);@@ -114,20 +84,20 @@ function AspectEditor({ stream, streamParams, updateStreamParams }: {{' '}{t('Note that this is not supported in all video players.')}</div>- <KeyValue name={t('Width')} value={<TextInput type="number" min="0" style={{ width: '5em' }} placeholder="W" value={currentAr.num > 0 ? String(currentAr.num) : ''} onChange={(e) => updateAr('num', e.target.value)} />} />- <KeyValue name={t('Height')} value={<TextInput type="number" min="0" style={{ width: '5em' }} placeholder="H" value={currentAr.den > 0 ? String(currentAr.den) : ''} onChange={(e) => updateAr('den', e.target.value)} />} />+ <KeyValue name={t('Width')} value={<TextField.Root type="number" min="0" style={{ width: '5em' }} placeholder="W" value={currentAr.num > 0 ? String(currentAr.num) : ''} onChange={(e) => updateAr('num', e.target.value)} />} />+ <KeyValue name={t('Height')} value={<TextField.Root type="number" min="0" style={{ width: '5em' }} placeholder="H" value={currentAr.den > 0 ? String(currentAr.den) : ''} onChange={(e) => updateAr('den', e.target.value)} />} /></>);}function CropEditor({ stream, streamParams, updateStreamParams }: {stream: FFprobeStream,- streamParams: StreamParams,+ streamParams: StreamParams | undefined,updateStreamParams: (setter: (a: StreamParams) => void) => void,}) {const { t } = useTranslation();- const currentCrop = streamParams.crop ?? { left: 0, right: 0, top: 0, bottom: 0 };+ const currentCrop = streamParams?.crop ?? { left: 0, right: 0, top: 0, bottom: 0 };const updateCrop = (field: 'left' | 'right' | 'top' | 'bottom', value: string) => {const parsed = parseInt(value, 10);@@ -149,50 +119,160 @@ function CropEditor({ stream, streamParams, updateStreamParams }: {{' '}{t('Note that this is not supported in all video players.')}</div>- <KeyValue name={t('Left')} value={<TextInput type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.left)} onChange={(e) => updateCrop('left', e.target.value)} />} />- <KeyValue name={t('Right')} value={<TextInput type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.right)} onChange={(e) => updateCrop('right', e.target.value)} />} />- <KeyValue name={t('Top')} value={<TextInput type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.top)} onChange={(e) => updateCrop('top', e.target.value)} />} />- <KeyValue name={t('Bottom')} value={<TextInput type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.bottom)} onChange={(e) => updateCrop('bottom', e.target.value)} />} />+ <KeyValue name={t('Left')} value={<TextField.Root type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.left)} onChange={(e) => updateCrop('left', e.target.value)} />} />+ <KeyValue name={t('Right')} value={<TextField.Root type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.right)} onChange={(e) => updateCrop('right', e.target.value)} />} />+ <KeyValue name={t('Top')} value={<TextField.Root type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.top)} onChange={(e) => updateCrop('top', e.target.value)} />} />+ <KeyValue name={t('Bottom')} value={<TextField.Root type="number" min="0" step="2" style={{ width: '5em' }} value={String(currentCrop.bottom)} onChange={(e) => updateCrop('bottom', e.target.value)} />} />+ </>+ );+}++function OffsetEditor({ fileParams, updateFileParams }: {+ fileParams: FileParams | undefined,+ updateFileParams: (setter: (a: FileParams) => void) => void,+}) {+ const { t } = useTranslation();+ const [valid, setValid] = useState(true);++ const handleChange = useCallback<ChangeEventHandler<HTMLInputElement>>((e) => {+ if (e.target.value.trim() === '') {+ updateFileParams((params) => {+ // eslint-disable-next-line no-param-reassign+ params.offset = undefined;+ });+ setValid(true);+ return;+ }++ const offset = Number(e.target.value);+ if (Number.isNaN(offset)) {+ setValid(false);+ } else {+ setValid(true);+ updateFileParams((params) => {+ // eslint-disable-next-line no-param-reassign+ params.offset = offset;+ });+ }+ }, [updateFileParams]);++ return (+ <>+ <div style={{ fontSize: '.85em', color: 'var(--gray-11)', marginBottom: '.4em' }}>+ {t('Shift the timestamps of all tracks in this file by a specified number of seconds, relative to other files. Positive values will delay the file\'s tracks, negative will advance it.')}+ </div>+ <KeyValue name={t('Shift by seconds')} value={<TextField.Root variant="soft" color={valid ? undefined : 'red'} type="text" style={{ width: '5em' }} placeholder="0.0" defaultValue={fileParams?.offset ?? ''} onChange={handleChange} />} /></>);}// eslint-disable-next-line react/display-name-const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, path: editingFile }, setEditingStream, allFilesMeta, paramsByStreamId, updateStreamParams }: {+const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParamsByFile, editingKey, setEditingKey, enableMetadata }: {+ editingFile: string,+ allFilesMeta: FilesMeta,+ paramsByFile: ParamsByFile,+ setParamsByFile: Dispatch<SetStateAction<ParamsByFile>>,+ editingKey: string | undefined,+ setEditingKey: (key: string | undefined) => void,+ enableMetadata: boolean,+}) => {+ const { t } = useTranslation();++ const format = allFilesMeta[editingFile]?.format;+ const existingMetadata = useMemo(() => format?.tags ?? {}, [format?.tags]);+ const fileParams = paramsByFile.get(editingFile);++ const updateFileParams = useCallback((updater: (a: FileParams) => void) => {+ setParamsByFile(produce((draft) => {+ let params = draft.get(editingFile);+ if (params == null) {+ params = { metadata: {}, paramsByStream: new Map() };+ draft.set(editingFile, params);+ }+ updater(params);+ }));+ }, [editingFile, setParamsByFile]);++ const onMetadataChange = useCallback((keyValues: Record<string, string>) => {+ updateFileParams((params) => {+ // eslint-disable-next-line no-param-reassign+ params.metadata = { ...params.metadata, ...keyValues };+ });+ }, [updateFileParams]);++ const onMetadataReset = useCallback((key: string) => {+ updateFileParams((params) => {+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const { [key]: deleted, ...rest } = params.metadata;+ // eslint-disable-next-line no-param-reassign+ params.metadata = rest;+ });+ }, [updateFileParams]);++ const tagInfo = useMemo(() => ({+ encoder: {+ description: t('This is hardcoded by FFmpeg and cannot be changed.'),+ },+ }), [t]);++ return (+ <Tabs.Root defaultValue={enableMetadata ? 'metadata' : 'offset'} style={{ minHeight: '20em' }}>+ <Tabs.List>+ {enableMetadata && <Tabs.Trigger value="metadata">{t('Metadata')}</Tabs.Trigger>}+ <Tabs.Trigger value="offset">{t('Offset')}</Tabs.Trigger>+ </Tabs.List>++ <div style={{ marginTop: '.5em' }}>+ {enableMetadata && (+ <Tabs.Content value="metadata">+ <TagEditor existingTags={existingMetadata} customTags={fileParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} canDeleteExisting />+ </Tabs.Content>+ )}++ <Tabs.Content value="offset">+ <OffsetEditor fileParams={fileParams} updateFileParams={updateFileParams} />+ </Tabs.Content>+ </div>+ </Tabs.Root>+ );+});++// eslint-disable-next-line react/display-name+const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, path: editingFile }, setEditingStream, allFilesMeta, paramsByFile, updateStreamParams }: {editingStream: EditingStream,setEditingStream: Dispatch<SetStateAction<EditingStream | undefined>>,allFilesMeta: FilesMeta,- paramsByStreamId: ParamsByStreamId,+ paramsByFile: ParamsByFile,updateStreamParams: UpdateStreamParams,}) => {const { t } = useTranslation();- const [editingTag, setEditingTag] = useState<string>();+ const [editingKey, setEditingKey] = useState<string>();const { streams } = allFilesMeta[editingFile]!;const editingStream = useMemo(() => streams.find((s) => s.index === editingStreamId), [streams, editingStreamId]);- const existingTags = useMemo(() => editingStream?.tags ?? {}, [editingStream]);+ const existingMetadata = useMemo(() => editingStream?.tags ?? {}, [editingStream]);- const streamParams = useMemo(() => getStreamParams({ paramsByStreamId, filePath: editingFile, streamId: editingStreamId }) ?? {}, [editingFile, editingStreamId, paramsByStreamId]);- const customTags = useMemo(() => streamParams.customTags, [streamParams]);+ const streamParams = useMemo(() => getStreamParams({ paramsByFile, filePath: editingFile, streamId: editingStreamId }), [editingFile, editingStreamId, paramsByFile]);- const onTagsChange = useCallback((keyValues: Record<string, string>) => {+ const onMetadataChange = useCallback((keyValues: Record<string, string>) => {updateStreamParams(editingFile, editingStreamId, (params) => {// eslint-disable-next-line no-param-reassign- if (params.customTags == null) params.customTags = {};- const tags = params.customTags;+ if (params.metadata == null) params.metadata = {};+ const { metadata } = params;Object.entries(keyValues).forEach(([tag, value]) => {- tags[tag] = tag === 'language' ? value.toLowerCase() : value;+ metadata[tag] = tag === 'language' ? value.toLowerCase() : value;});});}, [editingFile, editingStreamId, updateStreamParams]);- const onTagReset = useCallback((tag: string) => {+ const onMetadataReset = useCallback((key: string) => {updateStreamParams(editingFile, editingStreamId, (params) => {- if (params.customTags == null) return;- // todo- // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-dynamic-delete- delete params.customTags[tag];+ if (params.metadata == null) return;+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const { [key]: deleted, ...rest } = params.metadata;+ // eslint-disable-next-line no-param-reassign+ params.metadata = rest;});}, [editingFile, editingStreamId, updateStreamParams]);@@ -212,9 +292,9 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<Dialog.Content style={{ width: '40em' }} aria-describedby={undefined}><Dialog.Title>{t('Edit track {{trackNum}} metadata', { trackNum: editingStream && (editingStream.index + 1) })}</Dialog.Title>- <Tabs.Root defaultValue="tags" style={{ minHeight: '20em' }}>+ <Tabs.Root defaultValue="metadata" style={{ minHeight: '20em' }}><Tabs.List>- <Tabs.Trigger value="tags">{t('Tags')}</Tabs.Trigger>+ <Tabs.Trigger value="metadata">{t('Metadata')}</Tabs.Trigger>{editingStream?.codec_type === 'video' && (<><Tabs.Trigger value="crop">{t('Crop')}</Tabs.Trigger>@@ -225,8 +305,8 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat</Tabs.List><div style={{ marginTop: '.5em' }}>- <Tabs.Content value="tags">- <TagEditor existingTags={existingTags} customTags={customTags} editingTag={editingTag} setEditingTag={setEditingTag} onTagsChange={onTagsChange} onTagReset={onTagReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} />+ <Tabs.Content value="metadata">+ <TagEditor existingTags={existingMetadata} customTags={streamParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} canDeleteExisting /></Tabs.Content>{editingStream != null && (@@ -245,7 +325,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<KeyValuename={t('Enable "{{filterName}}" bitstream filter.', { filterName: 'h264_mp4toannexb' })}// eslint-disable-next-line no-param-reassign- value={<Switch checked={!!streamParams.bsfH264Mp4toannexb} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfH264Mp4toannexb = checked === true; })} />}+ value={<Switch checked={!!streamParams?.bsfH264Mp4toannexb} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfH264Mp4toannexb = checked === true; })} />}/>)}@@ -254,13 +334,13 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<KeyValuename={t('Enable "{{filterName}}" bitstream filter.', { filterName: 'hevc_mp4toannexb' })}// eslint-disable-next-line no-param-reassign- value={<Switch checked={!!streamParams.bsfH264Mp4toannexb} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcMp4toannexb = checked === true; })} />}+ value={<Switch checked={!!streamParams?.bsfH264Mp4toannexb} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcMp4toannexb = checked === true; })} />}/><KeyValuename={t('Enable "{{filterName}}" bitstream filter.', { filterName: 'hevc_metadata=aud=insert' })}// eslint-disable-next-line no-param-reassign- value={<Switch checked={!!streamParams.bsfHevcAudInsert} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcAudInsert = checked === true; })} />}+ value={<Switch checked={!!streamParams?.bsfHevcAudInsert} onCheckedChange={(checked) => updateCurrentStreamParams((params) => { params.bsfHevcAudInsert = checked === true; })} />}/></>)}@@ -269,7 +349,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<KeyValuename={t('Codec tag')}// eslint-disable-next-line no-param-reassign- value={<TextInput placeholder={t('Default')} value={streamParams.tag ?? ''} onChange={(e) => updateCurrentStreamParams((params) => { params.tag = e.target.value.trim() === '' ? undefined : e.target.value; })} />}+ value={<TextField.Root placeholder={editingStream?.codec_tag_string ?? t('Default')} value={streamParams?.tag ?? ''} onChange={(e) => updateCurrentStreamParams((params) => { params.tag = e.target.value.trim() === '' ? undefined : e.target.value; })} />}/>)}</Tabs.Content>@@ -280,7 +360,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<Dialog.ButtonRow><Dialog.Close asChild>- <DialogButton primary>{t('Done')}</DialogButton>+ <DialogButton disabled={editingKey != null} primary>{t('Done')}</DialogButton></Dialog.Close></Dialog.ButtonRow>@@ -294,7 +374,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, patconst unchangedDispositionValue = 'llc_disposition_unchanged';// eslint-disable-next-line react/display-name-const Stream = memo(({ filePath, stream, onToggle, toggleCopyStreamIds, copyStream, fileDuration, setEditingStream, onExtractStreamPress, paramsByStreamId, updateStreamParams, formatTimecode, loadSubtitleTrackToSegments }: {+const Stream = memo(({ filePath, stream, onToggle, toggleCopyStreamIds, copyStream, fileDuration, setEditingStream, onExtractStreamPress, paramsByFile, updateStreamParams, formatTimecode, loadSubtitleTrackToSegments }: {filePath: string,stream: FileStream,onToggle: (a: number) => void,@@ -302,15 +382,15 @@ const Stream = memo(({ filePath, stream, onToggle, toggleCopyStreamIds, copyStrecopyStream: boolean, fileDuration: number | undefined,setEditingStream: (a: EditingStream) => void,onExtractStreamPress?: () => void,- paramsByStreamId: ParamsByStreamId,+ paramsByFile: ParamsByFile,updateStreamParams: UpdateStreamParams,formatTimecode: FormatTimecode,loadSubtitleTrackToSegments?: (index: number) => void,}) => {const { t } = useTranslation();- const effectiveDisposition = useMemo(() => getStreamEffectiveDisposition(paramsByStreamId, filePath, stream), [filePath, paramsByStreamId, stream]);- const effectiveLanguage = getStreamParams({ paramsByStreamId, filePath, streamId: stream.index }).customTags?.['language'] ?? stream.tags?.language;+ const effectiveDisposition = useMemo(() => getStreamEffectiveDisposition(paramsByFile, filePath, stream), [filePath, paramsByFile, stream]);+ const effectiveLanguage = getStreamParams({ paramsByFile, filePath, streamId: stream.index })?.metadata['language'] ?? stream.tags?.language;const bitrate = parseInt(stream.bit_rate!, 10);const streamDuration = parseInt(stream.duration, 10);@@ -472,13 +552,13 @@ const Stream = memo(({ filePath, stream, onToggle, toggleCopyStreamIds, copyStre);});-function FileHeading({ path, format, chapters, onTrashClick, onEditClick, toggleCopyAllStreams, onExtractAllStreamsPress, changeEnabledStreamsFilter }: {+function FileHeading({ path, format, onEditClick, toggleCopyAllStreams, chapters, onTrashClick, onExtractAllStreamsPress, changeEnabledStreamsFilter }: {path: string,format: FFprobeFormat | undefined,- chapters?: FFprobeChapter[] | undefined,- onTrashClick?: (() => void) | undefined,onEditClick?: (() => void) | undefined,toggleCopyAllStreams: () => void,+ chapters?: FFprobeChapter[] | undefined,+ onTrashClick?: (() => void) | undefined,onExtractAllStreamsPress?: () => Promise<void>,changeEnabledStreamsFilter?: (() => void) | undefined,}) {@@ -533,7 +613,7 @@ const fileStyle: CSSProperties = { marginBottom: '2em', padding: '.5em 0', overffunction StreamsSelector({- mainFilePath, mainFileFormat, mainFileStreams, mainFileChapters, isCopyingStreamId, toggleCopyStreamId, setCopyStreamIdsForPath, onExtractStreamPress, onExtractAllStreamsPress, allFilesMeta, externalFilesMeta, setExternalFilesMeta, showAddStreamSourceDialog, shortestFlag, setShortestFlag, nonCopiedExtraStreams, customTagsByFile, setCustomTagsByFile, paramsByStreamId, updateStreamParams, formatTimecode, loadSubtitleTrackToSegments, toggleCopyStreamIds, changeEnabledStreamsFilter, toggleCopyAllStreamsForPath, onStreamSourceFileDrop,+ mainFilePath, mainFileFormat, mainFileStreams, mainFileChapters, isCopyingStreamId, toggleCopyStreamId, setCopyStreamIdsForPath, onExtractStreamPress, onExtractAllStreamsPress, allFilesMeta, externalFilesMeta, setExternalFilesMeta, showAddStreamSourceDialog, shortestFlag, setShortestFlag, nonCopiedExtraStreams, paramsByFile, setParamsByFile, updateStreamParams, formatTimecode, loadSubtitleTrackToSegments, toggleCopyStreamIds, changeEnabledStreamsFilter, toggleCopyAllStreamsForPath, onStreamSourceFileDrop,}: {mainFilePath: string,mainFileFormat: FFprobeFormat | undefined,@@ -551,9 +631,8 @@ function StreamsSelector({shortestFlag: boolean,setShortestFlag: Dispatch<SetStateAction<boolean>>,nonCopiedExtraStreams: FFprobeStream[],- customTagsByFile: CustomTagsByFile,- setCustomTagsByFile: Dispatch<SetStateAction<CustomTagsByFile>>,- paramsByStreamId: ParamsByStreamId,+ paramsByFile: ParamsByFile,+ setParamsByFile: Dispatch<SetStateAction<ParamsByFile>>,updateStreamParams: UpdateStreamParams,formatTimecode: FormatTimecode,loadSubtitleTrackToSegments: (index: number) => void,@@ -564,7 +643,7 @@ function StreamsSelector({}) {const [editingFile, setEditingFile] = useState<string>();const [editingStream, setEditingStream] = useState<EditingStream>();- const [editingTag, setEditingTag] = useState<string>();+ const [editingKey, setEditingKey] = useState<string>();const { t } = useTranslation();function getFormatDuration(format: FFprobeFormat | undefined) {@@ -605,7 +684,7 @@ function StreamsSelector({setEditingStream={setEditingStream}fileDuration={getFormatDuration(mainFileFormat)}onExtractStreamPress={() => onExtractStreamPress(stream.index)}- paramsByStreamId={paramsByStreamId}+ paramsByFile={paramsByFile}updateStreamParams={updateStreamParams}formatTimecode={formatTimecode}loadSubtitleTrackToSegments={loadSubtitleTrackToSegments}@@ -617,7 +696,7 @@ function StreamsSelector({{externalFilesEntries.map(([path, { streams: externalFileStreams, format }]) => (<div key={path} style={fileStyle}>- <FileHeading path={path} format={format} onTrashClick={() => removeFile(path)} toggleCopyAllStreams={() => toggleCopyAllStreamsForPath(path)} />+ <FileHeading path={path} format={format} onEditClick={() => setEditingFile(path)} toggleCopyAllStreams={() => toggleCopyAllStreamsForPath(path)} onTrashClick={() => removeFile(path)} /><table className={styles['table']}><Thead />@@ -632,7 +711,7 @@ function StreamsSelector({toggleCopyStreamIds={(filter: (a: FFprobeStream) => boolean) => toggleCopyStreamIds(path, filter)}setEditingStream={setEditingStream}fileDuration={getFormatDuration(format)}- paramsByStreamId={paramsByStreamId}+ paramsByFile={paramsByFile}updateStreamParams={updateStreamParams}formatTimecode={formatTimecode}/>@@ -671,11 +750,11 @@ function StreamsSelector({<Dialog.Content style={{ width: '40em' }} aria-describedby={undefined}><Dialog.Title>{t('Edit file metadata')}</Dialog.Title>- <EditFileDialog editingFile={editingFile} editingTag={editingTag} setEditingTag={setEditingTag} allFilesMeta={allFilesMeta} customTagsByFile={customTagsByFile} setCustomTagsByFile={setCustomTagsByFile} />+ <EditFileDialog editingFile={editingFile} editingKey={editingKey} setEditingKey={setEditingKey} allFilesMeta={allFilesMeta} paramsByFile={paramsByFile} setParamsByFile={setParamsByFile} enableMetadata={editingFile === mainFilePath} /><Dialog.ButtonRow><Dialog.Close asChild>- <DialogButton primary>{t('Done')}</DialogButton>+ <DialogButton primary disabled={editingKey != null}>{t('Done')}</DialogButton></Dialog.Close></Dialog.ButtonRow>@@ -690,7 +769,7 @@ function StreamsSelector({editingStream={editingStream}setEditingStream={setEditingStream}allFilesMeta={allFilesMeta}- paramsByStreamId={paramsByStreamId}+ paramsByFile={paramsByFile}updateStreamParams={updateStreamParams}/>)}diff --git a/src/renderer/src/components/TagEditor.tsx b/src/renderer/src/components/TagEditor.tsxindex 7dd4d453..b950cc21 100644--- a/src/renderer/src/components/TagEditor.tsx+++ b/src/renderer/src/components/TagEditor.tsx@@ -3,15 +3,13 @@ import { memo, useRef, useState, useMemo, useCallback, useEffect } from 'react';import { useTranslation } from 'react-i18next';import invariant from 'tiny-invariant';import { motion } from 'motion/react';-import { FaCheck, FaEdit, FaInfo, FaPlus, FaTrash, FaUndo } from 'react-icons/fa';-import { IconButton, Tooltip } from '@radix-ui/themes';+import { FaCheck, FaClipboard, FaClipboardList, FaEdit, FaInfo, FaPlus, FaTrash, FaUndo } from 'react-icons/fa';+import { IconButton, Tooltip, Button, TextField } from '@radix-ui/themes';import type { SegmentTags } from '../types';import { segmentTagsSchema } from '../types';import CopyClipboardButton from './CopyClipboardButton';import { errorToast } from '../swal';-import TextInput from './TextInput';-import Button from './Button';import Warning from './Warning';import mainApi from '../mainApi';@@ -22,7 +20,7 @@ const activeColor = 'var(--gray-12)';const emptyObject = {};-function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editingTag, setEditingTag, onTagsChange, onTagReset, addTagTitle, tagInfo }: {+function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editingTag, setEditingTag, onTagsChange, onTagReset, addTagTitle, tagInfo, canDeleteExisting }: {existingTags?: SegmentTags,customTags?: SegmentTags | undefined,editingTag: string | undefined,@@ -31,6 +29,7 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editionTagReset: (tag: string) => void,addTagTitle: string,tagInfo?: Record<string, { description: string, url?: string }>,+ canDeleteExisting?: boolean,}) {const { t } = useTranslation();const ref = useRef<HTMLInputElement>(null);@@ -88,6 +87,11 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi}}, [editingTag, editingTagVal, existingTags, effectiveTags, newTagKey, onResetClick, saveTag, setEditingTag]);+ const onDeleteExistingClick = useCallback((tag: string) => {+ onTagsChange({ [tag]: '' }); // empty string means delete metadata in ffmpeg+ setEditingTag(undefined);+ }, [onTagsChange, setEditingTag]);+const onSubmit = useCallback<FormEventHandler<HTMLFormElement>>((e) => {e.preventDefault();onEditClick();@@ -118,15 +122,32 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editiconst canAdd = !newTagKey && (editingTag == null || effectiveTags[editingTag] == null);+ function renderValue({ isDeletedExisting, value, thisTagCustom }: {+ isDeletedExisting: boolean,+ value: string | undefined,+ thisTagCustom: boolean,+ }) {+ const emphasized = thisTagCustom || isDeletedExisting;+ const color = isDeletedExisting ? 'var(--red-10)' : (emphasized ? activeColor : 'var(--gray-11)');+ const displayValue = isDeletedExisting ? `<${t('deleted')}>` : (value ? String(value) : `<${t('empty')}>`);+ return (+ <span style={{ marginRight: '.5em', padding: '.3em 0', fontWeight: emphasized ? 'bold' : undefined, color }}>+ {displayValue}+ </span>+ );+ }+return (<><table style={{ marginBottom: '1em', width: '100%' }}><tbody>{Object.keys(effectiveTags).map((tag) => {const editingThis = tag === editingTag;- const Icon = editingThis ? FaCheck : FaEdit;const thisTagCustom = customTags[tag] != null;const thisTagNew = existingTags[tag] == null;+ const value = effectiveTags[tag];+ const isDeletedExisting = !!canDeleteExisting && !value && !thisTagNew;+ const editingOther = editingTag != null && !editingThis;return (<motion.tr@@ -139,25 +160,34 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi><td style={{ paddingRight: '1em', color: thisTagNew ? activeColor : 'var(--gray-11)' }}>{tag}</td>- <td style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>+ <td style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '.5em' }}>{editingThis ? (- <form style={{ display: 'inline' }} onSubmit={onSubmit}>- <TextInput ref={ref} placeholder={t('Enter value')} value={editingTagVal || ''} onChange={(e) => setEditingTagVal(e.target.value)} style={{ padding: '.4em' }} />+ <form style={{ marginRight: '.5em', display: 'inline' }} onSubmit={onSubmit}>+ <TextField.Root ref={ref} placeholder={t('Enter value')} value={editingTagVal ?? ''} onChange={(e) => setEditingTagVal(e.target.value)} /></form>) : (- <span style={{ padding: '.3em 0', color: thisTagCustom ? activeColor : 'var(--gray-11)', fontWeight: thisTagCustom ? 'bold' : undefined }}>{effectiveTags[tag] ? String(effectiveTags[tag]) : `<${t('empty')}>`}</span>+ renderValue({ isDeletedExisting, value, thisTagCustom }))}- <Button disabled={editingTag != null && !editingThis} title={t('Edit')} style={{ marginLeft: '.4em' }} onClick={() => onEditClick(tag)}><Icon style={{ fontSize: '.9em', padding: '.5em', verticalAlign: 'middle' }} /></Button>- {editingThis && (- <Button title={thisTagNew ? t('Delete') : t('Reset')} onClick={onResetClick}>- {thisTagNew ? <FaTrash style={{ fontSize: '.9em', padding: '.5em', verticalAlign: 'middle' }} /> : <FaUndo style={{ fontSize: '.9em', padding: '.5em', verticalAlign: 'middle' }} />}- </Button>- )}- {tagInfo?.[tag] && (++ {tagInfo?.[tag] && !editingThis && (<Tooltip content={tagInfo[tag].description}>- <IconButton size="1" style={{ marginLeft: '.5em', cursor: tagInfo[tag]?.url ? 'pointer' : undefined }} onClick={() => tagInfo[tag]?.url && shell.openExternal(tagInfo[tag].url)}><FaInfo /></IconButton>+ <IconButton size="1" variant="ghost" color="gray" style={{ cursor: tagInfo[tag]?.url ? 'pointer' : undefined }} onClick={() => tagInfo[tag]?.url && shell.openExternal(tagInfo[tag].url)}><FaInfo /></IconButton></Tooltip>)}++ <IconButton disabled={editingOther} size="1" variant="ghost" color={editingThis ? 'cyan' : 'gray'} title={t('Edit')} onClick={() => onEditClick(tag)}>{editingThis ? <FaCheck /> : <FaEdit />}</IconButton>++ {editingThis && thisTagNew && (+ <IconButton size="1" color="red" variant="ghost" title={t('Delete')} onClick={onResetClick}><FaTrash /></IconButton>+ )}++ {editingThis && !thisTagNew && (+ <IconButton size="1" color="red" variant="ghost" title={t('Reset')} onClick={onResetClick}><FaUndo /></IconButton>+ )}++ {canDeleteExisting && !isDeletedExisting && !editingThis && existingTags[tag] != null && (+ <IconButton disabled={editingOther} size="1" color="red" variant="ghost" title={t('Delete')} onClick={() => onDeleteExistingClick(tag)}><FaTrash /></IconButton>+ )}</td></motion.tr>);@@ -165,19 +195,19 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi</tbody></table>- <form onSubmit={onAddSubmit} style={{ opacity: canAdd ? undefined : 0.5, marginBottom: '1em' }}>- <TextInput ref={ref} disabled={!canAdd} value={newTagKeyInput} onChange={(e) => setNewTagKeyInput(e.target.value)} placeholder={addTagTitle} style={{ padding: '.4em', marginRight: '1em', verticalAlign: 'middle' }} />- <Button type="submit" disabled={!canAdd} title={addTagTitle} onClick={add}><FaPlus style={{ padding: '.6em', verticalAlign: 'middle' }} /></Button>+ <form onSubmit={onAddSubmit} style={{ opacity: canAdd ? undefined : 0.5, marginBottom: '1em', display: 'flex', alignItems: 'center' }}>+ <TextField.Root ref={ref} disabled={!canAdd} value={newTagKeyInput} onChange={(e) => setNewTagKeyInput(e.target.value)} placeholder={addTagTitle} style={{ marginRight: '1em' }} />+ <IconButton size="2" type="submit" disabled={!canAdd} title={addTagTitle} onClick={add}><FaPlus /></IconButton></form>{newTagKeyInputError && <Warning>{t('Invalid character(s) found in key')}</Warning>}- <div style={{ marginBottom: '1em' }}>+ <div style={{ marginBottom: '1em', display: 'flex', alignItems: 'center' }}><CopyClipboardButton text={JSON.stringify(effectiveTags, null, 2)} style={{ marginRight: '.3em', verticalAlign: 'middle' }}>- {({ onClick }) => <Button onClick={onClick} style={{ display: 'block' }}>{t('Copy to clipboard')}</Button>}+ {({ onClick }) => <Button color="gray" size="1" onClick={onClick}><FaClipboardList />{t('Copy to clipboard')}</Button>}</CopyClipboardButton>- <Button onClick={onPasteClick}>{t('Paste')}</Button>+ <Button color="gray" size="1" onClick={onPasteClick}><FaClipboard />{t('Paste')}</Button></div></>);diff --git a/src/renderer/src/hooks/useFfmpegOperations.ts b/src/renderer/src/hooks/useFfmpegOperations.tsindex 565f8a39..8366d5d2 100644--- a/src/renderer/src/hooks/useFfmpegOperations.ts+++ b/src/renderer/src/hooks/useFfmpegOperations.ts@@ -1,5 +1,4 @@import { useCallback } from 'react';-import flatMap from 'lodash/flatMap';import sum from 'lodash/sum';import pMap from 'p-map';import invariant from 'tiny-invariant';@@ -12,7 +11,7 @@ import { needsSmartCut, getCodecParams } from '../smartcut';import { getGuaranteedSegments, isDurationValid } from '../segments';import type { FFprobeStream } from '../../../common/ffprobe';import type { AvoidNegativeTs, FfmpegHwAccel, Html5ifyMode, PreserveMetadata } from '../../../common/types';-import { deleteDispositionValue, type AllFilesMeta, type Chapter, type CopyfileStreams, type CustomTagsByFile, type LiteFFprobeStream, type ParamsByStreamId, type SegmentToExport } from '../types';+import { deleteDispositionValue, type AllFilesMeta, type Chapter, type CopyfileStreams, type LiteFFprobeStream, type ParamsByFile, type SegmentToExport } from '../types';import type { LossyMode } from '../../../main';import { UserFacingError } from '../../errors';import mainApi from '../mainApi';@@ -53,7 +52,7 @@ function getMovFlags({ preserveMovData, movFastStart }: { preserveMovData: booleif (movFastStart) flags.push('+faststart');if (flags.length === 0) return [];- return flatMap(flags, (flag) => ['-movflags', flag]);+ return flags.flatMap((flag) => ['-movflags', flag]);}function getMatroskaFlags() {@@ -240,7 +239,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treaconst losslessCutSingle = useCallback(async ({keyframeCut: ssBeforeInput, avoidNegativeTs, copyFileStreams, cutFrom, cutTo, chaptersPath, onProgress, outPath,- fileDuration, rotation, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMovData, preserveChapters, movFastStart, customTagsByFile, paramsByStreamId, videoTimebase, detectedFps,+ fileDuration, rotation, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMovData, preserveChapters, movFastStart, paramsByFile, videoTimebase, detectedFps,}: {keyframeCut: boolean,avoidNegativeTs: AvoidNegativeTs | undefined,@@ -260,8 +259,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treapreserveMovData: boolean,preserveChapters: boolean,movFastStart: boolean,- customTagsByFile: CustomTagsByFile,- paramsByStreamId: ParamsByStreamId,+ paramsByFile: ParamsByFile,videoTimebase?: number | undefined,detectedFps?: number,}) => {@@ -277,7 +275,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trealet cutDuration = cutToWithAdjustment - cutFromWithAdjustment;if (detectedFps != null) cutDuration = Math.max(cutDuration, frameDuration); // ensure at least one frame duration- // Don't cut if no need: https://github.com/mifi/lossless-cut/issues/50+ // Don't cut if not needed: https://github.com/mifi/lossless-cut/issues/50const cutFromArgs = cuttingStart ? ['-ss', formatFfmpegNumber(cutFromWithAdjustment)] : [];const cutToArgs = cuttingEnd ? ['-t', formatFfmpegNumber(cutDuration)] : [];@@ -289,14 +287,22 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea// If cutting multiple files, `-ss` must be before `-i`, regardless of `ssBeforeInput` choice// and it seems that `-t` must be after `-i` #896const inputFilesArgs = copyFileStreamsFiltered.length > 1- ? flatMap(copyFileStreamsFiltered, ({ streamIds, path }) => {- // don't "cut"/seek cover art or images attached by users, see https://github.com/mifi/lossless-cut/issues/2884- const streamParams = streamIds.map((streamId) => paramsByStreamId.get(path)?.get(streamId));+ ? copyFileStreamsFiltered.flatMap(({ streamIds, path }) => {+ const fileParams = paramsByFile.get(path);+ // Don't cut/seek cover art or images attached by users - it will break them, see https://github.com/mifi/lossless-cut/issues/2884+ const streamParams = streamIds.map((streamId) => fileParams?.paramsByStream.get(streamId));if (streamIds.length === 1 && streamParams[0]?.disposition === 'attached_pic') {return ['-i', path];}- return [...cutFromArgs, '-i', path, ...cutToArgs];+ const itsOffsetArgs = fileParams?.offset ? ['-itsoffset', formatFfmpegNumber(fileParams.offset)] : [];++ return [+ ...cutFromArgs,+ ...itsOffsetArgs,+ '-i', path,+ ...cutToArgs,+ ];}): [...(ssBeforeInput ? cutFromArgs : []),@@ -330,17 +336,16 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treainvariant(filePath != null);- const customTagsArgs = [- // Main file metadata:- ...flatMap(Object.entries(customTagsByFile[filePath] || []), ([key, value]) => ['-metadata', `${key}=${value}`]),- ];+ const customFileMetadataArgs = Object.entries(paramsByFile.get(filePath)?.metadata ?? {}).flatMap(([key, value]) => [+ '-metadata', `${key}=${value}`,+ ]);const mapStreamsArgs = getMapStreamsArgs({ copyFileStreams: copyFileStreamsFiltered, allFilesMeta, outFormat, needFlac: areWeCutting });const customParamsArgs = (() => {const ret: string[] = [];- for (const [fileId, fileParams] of paramsByStreamId.entries()) {- for (const [streamId, streamParams] of fileParams.entries()) {+ for (const [fileId, { paramsByStream }] of paramsByFile.entries()) {+ for (const [streamId, streamParams] of paramsByStream.entries()) {const outputIndex = mapInputStreamIndexToOutputIndex(fileId, streamId);if (outputIndex != null) {const { disposition } = streamParams;@@ -401,10 +406,9 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trearet.push(`-tag:${outputIndex}`, streamParams.tag);}- // custom stream metadata tags- const { customTags } = streamParams;- if (customTags != null) {- for (const [tag, value] of Object.entries(customTags)) {+ // custom stream metadata+ if (streamParams.metadata != null) {+ for (const [tag, value] of Object.entries(streamParams.metadata)) {ret.push(`-metadata:s:${outputIndex}`, `${tag}=${value}`);}}@@ -453,7 +457,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea...getMovFlags({ preserveMovData, movFastStart }),...getMatroskaFlags(),- ...customTagsArgs,+ ...customFileMetadataArgs,...customParamsArgs,@@ -542,7 +546,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea}, [appendFfmpegCommandLog, filePath]);const cutMultiple = useCallback(async ({- outputDir, customOutDir, segments: segmentsIn, cutFileNames, fileDuration, rotation, detectedFps, onProgress: onTotalProgress, keyframeCut, copyFileStreams, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMetadataOnMerge, preserveMovData, preserveChapters, movFastStart, avoidNegativeTs, customTagsByFile, paramsByStreamId, chapters,+ outputDir, customOutDir, segments: segmentsIn, cutFileNames, fileDuration, rotation, detectedFps, onProgress: onTotalProgress, keyframeCut, copyFileStreams, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMetadataOnMerge, preserveMovData, preserveChapters, movFastStart, avoidNegativeTs, paramsByFile, chapters,}: {outputDir: string,customOutDir: string | undefined,@@ -564,12 +568,10 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treapreserveChapters: boolean,movFastStart: boolean,avoidNegativeTs: AvoidNegativeTs | undefined,- customTagsByFile: CustomTagsByFile,- paramsByStreamId: ParamsByStreamId,+ paramsByFile: ParamsByFile,chapters: Chapter[] | undefined,}) => {- console.log('customTagsByFile', customTagsByFile);- console.log('paramsByStreamId', paramsByStreamId);+ console.log('paramsByFile', paramsByFile);const segments = getGuaranteedSegments(segmentsIn, fileDuration);@@ -602,7 +604,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea// simple lossless cutinvariant(outFormat != null);await losslessCutSingle({- cutFrom: desiredCutFrom, cutTo, chaptersPath, outPath: finalOutPath, copyFileStreams, keyframeCut, avoidNegativeTs, fileDuration, rotation, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMovData, preserveChapters, movFastStart, customTagsByFile, paramsByStreamId, onProgress: (progress) => onSingleProgress(i, progress),+ cutFrom: desiredCutFrom, cutTo, chaptersPath, outPath: finalOutPath, copyFileStreams, keyframeCut, avoidNegativeTs, fileDuration, rotation, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMovData, preserveChapters, movFastStart, paramsByFile, onProgress: (progress) => onSingleProgress(i, progress),});return { path: finalOutPath, created: true };}@@ -674,7 +676,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, trea// for smart cut we need to use keyframe cut here, and no avoid_negative_tsawait losslessCutSingle({- cutFrom: losslessCutFrom, cutTo, chaptersPath, outPath: losslessPartOutPath, copyFileStreams: copyFileStreamsFiltered, keyframeCut: true, avoidNegativeTs: undefined, fileDuration, rotation, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMovData, preserveChapters, movFastStart, customTagsByFile, paramsByStreamId, videoTimebase, onProgress,+ cutFrom: losslessCutFrom, cutTo, chaptersPath, outPath: losslessPartOutPath, copyFileStreams: copyFileStreamsFiltered, keyframeCut: true, avoidNegativeTs: undefined, fileDuration, rotation, allFilesMeta, outFormat, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMovData, preserveChapters, movFastStart, paramsByFile, videoTimebase, onProgress,});// We don't need to concat, just return the single cut file (we may need smart cut in other segments though)diff --git a/src/renderer/src/types.ts b/src/renderer/src/types.tsindex 75843573..d4c0b9a9 100644--- a/src/renderer/src/types.ts+++ b/src/renderer/src/types.ts@@ -161,8 +161,6 @@ export type AllFilesMeta = Record<string, {chapters: FFprobeChapter[];}>-export type CustomTagsByFile = Record<string, Record<string, string>>;-export interface BsfCropParams {left: number;right: number;@@ -182,7 +180,7 @@ export const deleteDispositionValue = 'llc_disposition_remove' as const;export interface StreamParams {- customTags?: Record<string, string>,+ metadata: Record<string, string>,disposition?: ContentDispositionOptions | 'llc_disposition_remove' | undefined,bsfH264Mp4toannexb?: boolean,bsfHevcMp4toannexb?: boolean,@@ -191,7 +189,17 @@ export interface StreamParams {crop?: BsfCropParams | undefined,aspectRatio?: BsfAspectRatioParams | undefined,}-export type ParamsByStreamId = Map<string, Map<number, StreamParams>>;++export type ParamsByStream = Map<number, StreamParams>;++export interface FileParams {+ paramsByStream: ParamsByStream;++ metadata: Record<string, string>;+ offset?: number | undefined;+}++export type ParamsByFile = Map<string, FileParams>;export interface BatchFile {path: string,