The swiss army knife of lossless video/audio editing
Address second review of metadata editor changes
Claudef833247edaca
diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 7cabe6ca..03684688 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -395,7 +395,7 @@"Input has {{numStreamsTotal}} tracks": "Input has {{numStreamsTotal}} tracks","Instead of video apparently starting at 0, you can offset by a specified value. This only applies to the preview inside LosslessCut and does not modify the file in any way. (Useful for viewing/cutting videos according to timecodes)": "Instead of video apparently starting at 0, you can offset by a specified value. This only applies to the preview inside LosslessCut and does not modify the file in any way. (Useful for viewing/cutting videos according to timecodes).","Invalid character(s) found in key": "Invalid character found in key",- "Invalid date, use ISO 8601 format, e.g. {{example}}": "Invalid date, use ISO 8601 format, e.g. {{example}}",+ "Invalid date, use e.g. {{example}} or {{now}}": "Invalid date, use e.g. {{example}} or {{now}}","Invalid duration": "Invalid duration","Invalid EDL data found": "Invalid EDL data found","Invalid input": "Invalid input",diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 9df368e7..20de4822 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -1789,7 +1789,7 @@ function App() {return fileMeta;}, [allFilesMeta, setCopyStreamIdsForPath]);- const hvc1NeededStreams = useMemo(() => mainCopiedStreams.filter((stream) => needsHvc1Tag({ stream, outFormat: fileFormat, customTag: filePath != null ? paramsByFile.get(filePath)?.paramsByStream.get(stream.index)?.tag : undefined })), [fileFormat, filePath, mainCopiedStreams, paramsByFile]);+ const hvc1NeededStreams = useMemo(() => copyFileStreams.flatMap(({ path, streamIds }) => (allFilesMeta[path]?.streams ?? []).filter((stream) => streamIds.includes(stream.index) && needsHvc1Tag({ stream, outFormat: fileFormat, customTag: paramsByFile.get(path)?.paramsByStream.get(stream.index)?.tag }))), [allFilesMeta, copyFileStreams, fileFormat, paramsByFile]);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() });diff --git a/src/renderer/src/SegmentList.tsx b/src/renderer/src/SegmentList.tsxindex 1d4feb43..b91fb670 100644--- a/src/renderer/src/SegmentList.tsx+++ b/src/renderer/src/SegmentList.tsx@@ -19,7 +19,7 @@ import useActionTitle from './hooks/useActionTitle';import { saveColor, controlsBackground, primaryTextColor, darkModeTransition } from './colors';import { useSegColors } from './contexts';import { getSegmentTags } from './segments';-import TagEditor from './components/TagEditor';+import TagEditor, { cancelTagEditOnEscape } from './components/TagEditor';import type { ContextMenuTemplate, DefiniteSegmentBase, FormatTimecode, GetFrameCount, InverseCutSegment, SegmentBase, SegmentColorIndex, SegmentTags, StateSegment } from './types';import type { UseSegments } from './hooks/useSegments';import * as Dialog from './components/Dialog';@@ -617,7 +617,7 @@ function SegmentList({<Dialog.Root open={editingSegmentTagsSegmentIndex != null} onOpenChange={(open) => !open && onSegmentTagsCloseComplete()}><Dialog.Portal><Dialog.Overlay />- <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={(e) => editingTag != null && e.preventDefault()}>+ <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={cancelTagEditOnEscape(editingTag, setEditingTag)}><Dialog.Title>{t('Edit segment tags')}</Dialog.Title><TagEditor customTags={editingSegmentTags} editingTag={editingTag} setEditingTag={setEditingTag} onTagsChange={onTagsChange} onTagReset={onTagReset} addTagTitle={t('Add segment tag')} />diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex 7de14932..7c79a6f8 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -18,8 +18,7 @@ import { getStreamFps } from './ffmpeg';import { getActiveDisposition, attachedPicDisposition, isGpsStream, isMov } from './util/streams';import { fileMetadataKeys, getCodecTagSuggestions, getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidCreationTime, isValidLanguageCode, needsHvc1Tag, streamMetadataKeys } from './util/metadata';import useUserSettings from './hooks/useUserSettings';-import TagEditor from './components/TagEditor';-import type { TagInfo } from './components/TagEditor';+import TagEditor, { cancelTagEditOnEscape, type TagInfo } from './components/TagEditor';import SuggestionTextField from './components/SuggestionTextField';import Warning from './components/Warning';import type { FFprobeChapter, FFprobeFormat, FFprobeStream } from '../../common/ffprobe';@@ -58,8 +57,9 @@ function useCommonTagInfo(): TagInfo {const { t } = useTranslation();return useMemo(() => ({creation_time: {- suggestions: [{ value: new Date().toISOString(), label: t('Now') }],- validate: (value) => (isValidCreationTime(value) ? undefined : t('Invalid date, use ISO 8601 format, e.g. {{example}}', { example: '2024-12-31T23:59:59Z' })),+ // resolved by ffmpeg at export time+ suggestions: [{ value: 'now', label: t('Now') }],+ validate: (value) => (isValidCreationTime(value) ? undefined : t('Invalid date, use e.g. {{example}} or {{now}}', { example: '2024-12-31T23:59:59Z', now: 'now' })),},comment: { multiline: true },description: { multiline: true },@@ -79,10 +79,10 @@ function ActionCallout({ color, style, text, actionText, onAction }: { color: 'a}// MP4/MOV only stores certain keys, unless "use_metadata_tags" is enabled-function MovMetadataNotice({ outFormat, metadata, nativeKeys }: { outFormat: string | undefined, metadata: Record<string, string> | undefined, nativeKeys: readonly string[] }) {+function MovMetadataNotice({ outFormat, metadata, isStream }: { outFormat: string | undefined, metadata: Record<string, string> | undefined, isStream: boolean }) {const { t } = useTranslation();const { preserveMovData, setPreserveMovData } = useUserSettings();- const nonNativeKeys = getNonNativeMovMetadataKeys(metadata, nativeKeys);+ const nonNativeKeys = getNonNativeMovMetadataKeys({ metadata, outFormat, isStream });if (!isMov(outFormat) || preserveMovData || nonNativeKeys.length === 0) return null;return (<ActionCallout@@ -275,7 +275,7 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParam<div style={{ marginTop: '.5em' }}>{enableMetadata && (<Tabs.Content value="metadata">- <MovMetadataNotice outFormat={outFormat} metadata={fileParams?.metadata} nativeKeys={fileMetadataKeys} />+ <MovMetadataNotice outFormat={outFormat} metadata={fileParams?.metadata} isStream={false} /><TagEditor existingTags={existingMetadata} customTags={fileParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} keySuggestions={fileMetadataKeys} canDeleteExisting /></Tabs.Content>)}@@ -348,7 +348,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<Dialog.Root open={editingStream != null} onOpenChange={(v) => v === false && setEditingStream(undefined)}><Dialog.Portal><Dialog.Overlay />- <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={(e) => editingKey != null && e.preventDefault()}>+ <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={cancelTagEditOnEscape(editingKey, setEditingKey)}><Dialog.Title>{t('Edit track {{trackNum}} metadata', { trackNum: editingStream && (editingStream.index + 1) })}</Dialog.Title><Tabs.Root defaultValue="metadata" style={{ minHeight: '20em' }}>@@ -365,7 +365,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<div style={{ marginTop: '.5em' }}><Tabs.Content value="metadata">- <MovMetadataNotice outFormat={outFormat} metadata={streamParams?.metadata} nativeKeys={streamMetadataKeys} />+ <MovMetadataNotice outFormat={outFormat} metadata={streamParams?.metadata} isStream /><TagEditor existingTags={existingMetadata} customTags={streamParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} keySuggestions={streamMetadataKeys} canDeleteExisting /></Tabs.Content>@@ -824,7 +824,7 @@ function StreamsSelector({<Dialog.Root defaultOpen onOpenChange={(v) => v === false && setEditingFile(undefined)}><Dialog.Portal><Dialog.Overlay />- <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={(e) => editingKey != null && e.preventDefault()}>+ <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={cancelTagEditOnEscape(editingKey, setEditingKey)}><Dialog.Title>{t('Edit file metadata')}</Dialog.Title><EditFileDialog editingFile={editingFile} editingKey={editingKey} setEditingKey={setEditingKey} allFilesMeta={allFilesMeta} paramsByFile={paramsByFile} setParamsByFile={setParamsByFile} enableMetadata={editingFile === mainFilePath} outFormat={outFormat} />diff --git a/src/renderer/src/components/TagEditor.tsx b/src/renderer/src/components/TagEditor.tsxindex 69afe3a2..e9c32c53 100644--- a/src/renderer/src/components/TagEditor.tsx+++ b/src/renderer/src/components/TagEditor.tsx@@ -29,6 +29,14 @@ export type TagInfo = Record<string, {validate?: (value: string) => string | undefined,}>;+// For the containing dialog's `onEscapeKeyDown`: Esc discards the unsaved edit instead of closing the dialog.+// Handled at the dialog level so that it also works when the input doesn't have focus (or is not mounted, e.g. another tab)+export const cancelTagEditOnEscape = (editingTag: string | undefined, setEditingTag: (v: string | undefined) => void) => (e: KeyboardEvent) => {+ if (editingTag == null) return;+ e.preventDefault();+ setEditingTag(undefined);+};+function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editingTag, setEditingTag, onTagsChange, onTagReset, addTagTitle, tagInfo, keySuggestions, canDeleteExisting }: {existingTags?: SegmentTags,customTags?: SegmentTags | undefined,@@ -46,7 +54,9 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editiconst addRef = useRef<HTMLInputElement>(null);const [editingTagVal, setEditingTagVal] = useState<string>();- const [newTagKey, setNewTagKey] = useState<string>();+ const [newTagKeyState, setNewTagKey] = useState<string>();+ // the edit can also be discarded from outside (see cancelTagEditOnEscape), so only use it while editing+ const newTagKey = editingTag != null ? newTagKeyState : undefined;const [newTagKeyInput, setNewTagKeyInput] = useState<string>('');const newTagKeyInputError = useMemo(() => !!newTagKeyInput && newTagKeyInput.includes('='), [newTagKeyInput]);@@ -98,17 +108,13 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi}}, [editingTag, editingTagVal, existingTags, effectiveTags, newTagKey, onResetClick, saveTag, setEditingTag]);- // Discard the unsaved edit (unlike reset, which also removes the custom value)+ // Ctrl/Cmd+Enter saves (needed for multiline)const onEditKeyDown = useCallback<KeyboardEventHandler>((e) => {- if (e.key === 'Escape') {- e.stopPropagation();- setEditingTag(undefined);- setNewTagKey(undefined);- } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { // for multiline+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {e.preventDefault();onEditClick();}- }, [onEditClick, setEditingTag]);+ }, [onEditClick]);const onDeleteExistingClick = useCallback((tag: string) => {onTagsChange({ [tag]: '' }); // empty string means delete metadata in ffmpegdiff --git a/src/renderer/src/util/metadata.test.ts b/src/renderer/src/util/metadata.test.tsindex 6ba9a061..d8ee5819 100644--- a/src/renderer/src/util/metadata.test.ts+++ b/src/renderer/src/util/metadata.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'vitest';-import { getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidLanguageCode, needsHvc1Tag, streamMetadataKeys } from './metadata';+import { getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidCreationTime, isValidLanguageCode, needsHvc1Tag } from './metadata';describe('getLanguageSuggestions', () => {@@ -11,6 +11,10 @@ describe('getLanguageSuggestions', () => {expect(suggestions.every(({ value }) => isValidLanguageCode(value))).toBe(true);});+ test('underscore ui language', () => {+ expect(getLanguageSuggestions('pt_BR')).toContainEqual({ value: 'ger', label: 'alemão (ger)' });+ });+test('invalid ui language falls back to codes', () => {expect(getLanguageSuggestions('!!')).toContainEqual({ value: 'eng', label: 'eng (eng)' });});@@ -33,6 +37,17 @@ test('needsHvc1Tag', () => {});test('getNonNativeMovMetadataKeys', () => {- expect(getNonNativeMovMetadataKeys({ title: 'a', custom: 'b', deleted: '' }, streamMetadataKeys)).toEqual(['custom']);- expect(getNonNativeMovMetadataKeys(undefined, streamMetadataKeys)).toEqual([]);+ expect(getNonNativeMovMetadataKeys({ metadata: { title: 'a', custom: 'b', deleted: '' }, outFormat: 'mov', isStream: true })).toEqual(['custom']);+ expect(getNonNativeMovMetadataKeys({ metadata: { title: 'a' }, outFormat: 'mp4', isStream: true })).toEqual(['title']);+ expect(getNonNativeMovMetadataKeys({ metadata: { title: 'a', lyrics: 'b', custom: 'c' }, outFormat: 'mp4', isStream: false })).toEqual(['custom']);+ expect(getNonNativeMovMetadataKeys({ metadata: undefined, outFormat: 'mp4', isStream: true })).toEqual([]);+});++test('isValidCreationTime', () => {+ expect(isValidCreationTime('now')).toBe(true);+ expect(isValidCreationTime(new Date().toISOString())).toBe(true);+ expect(isValidCreationTime('2024-12-31 23:59:59')).toBe(true);+ expect(isValidCreationTime('12:00:00')).toBe(true);+ expect(isValidCreationTime('12/31/2024')).toBe(false);+ expect(isValidCreationTime('1')).toBe(false);});diff --git a/src/renderer/src/util/metadata.ts b/src/renderer/src/util/metadata.tsindex 63088408..37962c23 100644--- a/src/renderer/src/util/metadata.ts+++ b/src/renderer/src/util/metadata.ts@@ -3,13 +3,19 @@ import type { Suggestion } from '../components/SuggestionTextField';import { isMov } from './streams';-// Common metadata keys (as named by ffmpeg) that the MP4/MOV muxer stores natively (without `-movflags use_metadata_tags`)+// Common metadata keys (as named by ffmpeg) to suggestexport const fileMetadataKeys = ['title', 'artist', 'album_artist', 'album', 'composer', 'genre', 'date', 'track', 'comment', 'description', 'copyright', 'creation_time'] as const;export const streamMetadataKeys = ['title', 'language', 'handler_name', 'creation_time'] as const;-export const getNonNativeMovMetadataKeys = (metadata: Record<string, string> | undefined, nativeKeys: readonly string[]) => (- Object.entries(metadata ?? {}).filter(([key, value]) => value !== '' && !nativeKeys.includes(key)).map(([key]) => key)-);+// Keys that the MP4/MOV muxer stores natively (without `-movflags use_metadata_tags`)+const movNativeFileKeys = new Set<string>([...fileMetadataKeys, 'grouping', 'lyrics', 'synopsis', 'show', 'episode_id', 'network', 'disc', 'encoder']);+// track title is only written in MOV mode+const getMovNativeStreamKeys = (outFormat: string | undefined) => new Set<string>(['language', 'handler_name', 'creation_time', ...(outFormat === 'mov' ? ['title'] : [])]);++export const getNonNativeMovMetadataKeys = ({ metadata, outFormat, isStream }: { metadata: Record<string, string> | undefined, outFormat: string | undefined, isStream: boolean }) => {+ const nativeKeys = isStream ? getMovNativeStreamKeys(outFormat) : movNativeFileKeys;+ return Object.entries(metadata ?? {}).filter(([key, value]) => value !== '' && !nativeKeys.has(key)).map(([key]) => key);+};// Common codec tags (FourCC) for use with `-tag` when outputting MP4/MOVconst codecTagsByCodec: Partial<Record<FFprobeStream['codec_name'], readonly string[]>> = {@@ -36,7 +42,8 @@ export const needsHvc1Tag = ({ stream, outFormat, customTag }: { stream: Pick<FFstream.codec_name === 'hevc' && isMov(outFormat) && customTag == null && stream.codec_tag_string !== 'hvc1');-export const isValidCreationTime = (value: string) => !Number.isNaN(Date.parse(value));+// Formats accepted by ffmpeg's av_parse_time: `now` or [YYYY-MM-DD|YYYYMMDD][T| ]HH:MM:SS[.m...][Z]+export const isValidCreationTime = (value: string) => /^(now|((\d{4}-\d{2}-\d{2}|\d{8})[Tt ])?(\d{2}:\d{2}:\d{2}|\d{6})(\.\d+)?[Zz]?)$/.test(value);// Common ISO 639-2/B codes (as used by Matroska and ffmpeg) mapped to BCP 47, for displaying localized namesconst languages: [iso6392: string, bcp47: string][] = [@@ -51,7 +58,8 @@ const languages: [iso6392: string, bcp47: string][] = [export function getLanguageSuggestions(uiLanguage: string): Suggestion[] {let displayNames: Intl.DisplayNames | undefined;try {- displayNames = new Intl.DisplayNames([uiLanguage, 'en'], { type: 'language' });+ // our locale codes use underscores (e.g. pt_BR), which Intl doesn't accept+ displayNames = new Intl.DisplayNames([uiLanguage.replaceAll('_', '-'), 'en'], { type: 'language' });} catch {// ignore, fall back to codes only}