The swiss army knife of lossless video/audio editing
Add codec tag and language suggestions to the track metadata editor
Claudeb8a167e8df98
diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 656f6e66..e91a5ac7 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -52,6 +52,7 @@"Always open this dialog when opening multiple files": "Always open this dialog when opening multiple files","An error has occurred.": "An error has occurred.","API action name: {{action}}": "API action name: {{action}}",+ "Apple devices (QuickTime, Safari, iOS) require the \"{{tag}}\" codec tag to play HEVC in MP4/MOV.": "Apple devices (QuickTime, Safari, iOS) require the \"{{tag}}\" codec tag to play HEVC in MP4/MOV.","Apply change": "Apply change","Apply filter": "Apply filter","Are you sure you want to close the current file?": "Are you sure you want to close the current file?",@@ -130,6 +131,7 @@"Close sidebar": "Close sidebar","Codec": "Codec","Codec tag": "Codec tag",+ "Codec tag should be 4 characters": "Codec tag should be 4 characters","Combination is already bound to \"{{alreadyBoundKey}}\". Do you want to replace the existing binding?": "Combination is already bound to \"{{alreadyBoundKey}}\". Do you want to replace the existing binding?","Combination is invalid": "Combination is invalid","Combine overlapping segments": "Combine overlapping segments",@@ -439,6 +441,7 @@"Label segment": "Label segment","Label selected segments": "Label selected segments","Language": "Language",+ "Language should be a 3-letter ISO 639-2 code": "Language should be a 3-letter ISO 639-2 code","Last ffmpeg commands": "Last ffmpeg commands","Learn more": "Learn more","Learn More": "Learn More",@@ -850,6 +853,7 @@"Undo": "Undo","Unprocessable streams were exported as separate files.": "Unprocessable streams were exported as separate files.","Unsupported file": "Unsupported file",+ "Use \"{{tag}}\"": "Use \"{{tag}}\"","Use + and - for relative seek": "Use + and - for relative seek","Use this for all files until LosslessCut is restarted?": "Use this for all files until LosslessCut is restarted","User interface": "User interface",diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 901dfb83..4c8d481e 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -2824,6 +2824,7 @@ function App() {changeEnabledStreamsFilter={changeEnabledStreamsFilter}toggleCopyAllStreamsForPath={toggleCopyAllStreamsForPath}onStreamSourceFileDrop={handleStreamSourceFileDrop}+ outFormat={fileFormat}/>)}diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex 30c6eca8..74879931 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -6,7 +6,7 @@ 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, TextField } from '@radix-ui/themes';+import { Button as ThemesButton, Callout, Tabs, TextField } from '@radix-ui/themes';import { produce } from 'immer';import * as DropdownMenu from './components/DropdownMenu';@@ -15,8 +15,12 @@ import AutoExportToggler from './components/AutoExportToggler';import Select from './components/Select';import type { FileStream } from './ffmpeg';import { getStreamFps } from './ffmpeg';-import { getActiveDisposition, attachedPicDisposition, isGpsStream } from './util/streams';+import { getActiveDisposition, attachedPicDisposition, isGpsStream, getCodecTagSuggestions, isMov, isValidCodecTag } from './util/streams';+import { getLanguageSuggestions, isValidLanguageCode } from './util/languages';import TagEditor from './components/TagEditor';+import type { TagInfo } from './components/TagEditor';+import SuggestionTextField from './components/SuggestionTextField';+import Warning from './components/Warning';import type { FFprobeChapter, FFprobeFormat, FFprobeStream } from '../../common/ffprobe';import { contentDispositionOptionsSchema, deleteDispositionValue, dispositionOptions, type ContentDispositionOptions, type FileParams, type FilesMeta, type FormatTimecode, type ParamsByFile, type StreamParams } from './types';import Button, { DialogButton } from './components/Button';@@ -238,14 +242,15 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParam});// eslint-disable-next-line react/display-name-const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, path: editingFile }, setEditingStream, allFilesMeta, paramsByFile, updateStreamParams }: {+const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, path: editingFile }, setEditingStream, allFilesMeta, paramsByFile, updateStreamParams, outFormat }: {editingStream: EditingStream,setEditingStream: Dispatch<SetStateAction<EditingStream | undefined>>,allFilesMeta: FilesMeta,paramsByFile: ParamsByFile,updateStreamParams: UpdateStreamParams,+ outFormat: string | undefined,}) => {- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const [editingKey, setEditingKey] = useState<string>();const { streams } = allFilesMeta[editingFile]!;@@ -276,12 +281,19 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat});}, [editingFile, editingStreamId, updateStreamParams]);- const tagInfo = useMemo(() => ({+ const tagInfo = useMemo<TagInfo>(() => ({language: {description: t('The language tag (ISO 639-2 code). For example "eng" for English. This is used by some players to select the appropriate audio/subtitle track based on the user\'s language preferences.'),url: 'https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes',+ suggestions: getLanguageSuggestions(i18n.language),+ validate: (value) => (isValidLanguageCode(value.toLowerCase()) ? undefined : t('Language should be a 3-letter ISO 639-2 code')),},- }), [t]);+ }), [i18n.language, t]);++ const codecTagSuggestions = useMemo(() => getCodecTagSuggestions(editingStream?.codec_name).map((value) => ({ value })), [editingStream?.codec_name]);+ const effectiveCodecTag = streamParams?.tag ?? editingStream?.codec_tag_string;+ // https://developer.apple.com/documentation/http-live-streaming/hls-authoring-specification-for-apple-devices+ const suggestHvc1 = editingStream?.codec_name === 'hevc' && isMov(outFormat) && effectiveCodecTag !== 'hvc1';const updateCurrentStreamParams = (setter: (a: StreamParams) => void) => updateStreamParams(editingFile, editingStreamId, setter);@@ -346,11 +358,26 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat)}{(editingStream.codec_type === 'video' || editingStream.codec_type === 'audio') && (- <KeyValue- name={t('Codec tag')}- // eslint-disable-next-line no-param-reassign- 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; })} />}- />+ <>+ <KeyValue+ name={t('Codec tag')}+ // eslint-disable-next-line no-param-reassign+ value={<SuggestionTextField placeholder={editingStream?.codec_tag_string ?? t('Default')} value={streamParams?.tag ?? ''} suggestions={codecTagSuggestions} onValueChange={(value) => updateCurrentStreamParams((params) => { params.tag = value.trim() === '' ? undefined : value; })} />}+ />++ {streamParams?.tag != null && !isValidCodecTag(streamParams.tag) && <Warning>{t('Codec tag should be 4 characters')}</Warning>}++ {suggestHvc1 && (+ <Callout.Root size="1" color="blue" style={{ marginTop: '.5em' }}>+ <Callout.Icon><FaInfoCircle /></Callout.Icon>+ <Callout.Text>+ {t('Apple devices (QuickTime, Safari, iOS) require the "{{tag}}" codec tag to play HEVC in MP4/MOV.', { tag: 'hvc1' })}{' '}+ {/* eslint-disable-next-line no-param-reassign */}+ <ThemesButton size="1" variant="soft" onClick={() => updateCurrentStreamParams((params) => { params.tag = 'hvc1'; })}>{t('Use "{{tag}}"', { tag: 'hvc1' })}</ThemesButton>+ </Callout.Text>+ </Callout.Root>+ )}+ </>)}</Tabs.Content></>@@ -614,7 +641,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, paramsByFile, setParamsByFile, 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, outFormat,}: {mainFilePath: string,mainFileFormat: FFprobeFormat | undefined,@@ -641,6 +668,7 @@ function StreamsSelector({changeEnabledStreamsFilter: () => void,toggleCopyAllStreamsForPath: (path: string) => void,onStreamSourceFileDrop: DragEventHandler<HTMLDivElement>,+ outFormat: string | undefined,}) {const [editingFile, setEditingFile] = useState<string>();const [editingStream, setEditingStream] = useState<EditingStream>();@@ -772,6 +800,7 @@ function StreamsSelector({allFilesMeta={allFilesMeta}paramsByFile={paramsByFile}updateStreamParams={updateStreamParams}+ outFormat={outFormat}/>)}</>diff --git a/src/renderer/src/components/SuggestionTextField.tsx b/src/renderer/src/components/SuggestionTextField.tsxnew file mode 100644index 00000000..66f974db--- /dev/null+++ b/src/renderer/src/components/SuggestionTextField.tsx@@ -0,0 +1,35 @@+import type { ComponentProps } from 'react';+import { DropdownMenu, IconButton, TextField } from '@radix-ui/themes';+import { FaChevronDown } from 'react-icons/fa';+++export interface Suggestion {+ value: string,+ label?: string,+}++// A text field with a dropdown of suggested values (Radix Themes has no combobox)+export default function SuggestionTextField({ suggestions, onValueChange, ...props }: Omit<ComponentProps<typeof TextField.Root>, 'onChange'> & {+ suggestions: Suggestion[],+ onValueChange: (value: string) => void,+}) {+ return (+ // eslint-disable-next-line react/jsx-props-no-spreading+ <TextField.Root {...props} onChange={(e) => onValueChange(e.target.value)}>+ {suggestions.length > 0 && (+ <TextField.Slot side="right">+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <IconButton type="button" size="1" variant="ghost" color="gray"><FaChevronDown /></IconButton>+ </DropdownMenu.Trigger>+ <DropdownMenu.Content size="1" style={{ maxHeight: '20em' }}>+ {suggestions.map(({ value, label }) => (+ <DropdownMenu.Item key={value} onSelect={() => onValueChange(value)}>{label ?? value}</DropdownMenu.Item>+ ))}+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ </TextField.Slot>+ )}+ </TextField.Root>+ );+}diff --git a/src/renderer/src/components/TagEditor.tsx b/src/renderer/src/components/TagEditor.tsxindex 2742ddda..311402c4 100644--- a/src/renderer/src/components/TagEditor.tsx+++ b/src/renderer/src/components/TagEditor.tsx@@ -12,12 +12,22 @@ import CopyClipboardButton from './CopyClipboardButton';import { errorToast } from '../swal';import Warning from './Warning';import mainApi from '../mainApi';+import type { Suggestion } from './SuggestionTextField';+import SuggestionTextField from './SuggestionTextField';const activeColor = 'var(--gray-12)';const emptyObject = {};+export type TagInfo = Record<string, {+ description?: string,+ url?: string,+ suggestions?: Suggestion[],+ // returns an error message if invalid+ validate?: (value: string) => string | undefined,+}>;+function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editingTag, setEditingTag, onTagsChange, onTagReset, addTagTitle, tagInfo, canDeleteExisting }: {existingTags?: SegmentTags,customTags?: SegmentTags | undefined,@@ -26,7 +36,7 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editionTagsChange: (keyValues: Record<string, string>) => void,onTagReset: (tag: string) => void,addTagTitle: string,- tagInfo?: Record<string, { description: string, url?: string }>,+ tagInfo?: TagInfo,canDeleteExisting?: boolean,}) {const { t } = useTranslation();@@ -118,6 +128,8 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editiref.current?.focus();}, [editingTag]);+ const editingTagError = editingTag != null && editingTagVal ? tagInfo?.[editingTag]?.validate?.(editingTagVal) : undefined;+const canAdd = !newTagKey && (editingTag == null || effectiveTags[editingTag] == null);function renderValue({ isDeletedExisting, value, thisTagCustom }: {@@ -161,13 +173,13 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi<td style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '.5em' }}>{editingThis ? (<form style={{ marginRight: '.5em', display: 'inline' }} onSubmit={onSubmit}>- <TextField.Root ref={ref} placeholder={t('Enter value')} value={editingTagVal ?? ''} onChange={(e) => setEditingTagVal(e.target.value)} />+ <SuggestionTextField ref={ref} placeholder={t('Enter value')} value={editingTagVal ?? ''} onValueChange={setEditingTagVal} suggestions={tagInfo?.[tag]?.suggestions ?? []} /></form>) : (renderValue({ isDeletedExisting, value, thisTagCustom }))}- {tagInfo?.[tag] && !editingThis && (+ {tagInfo?.[tag]?.description && !editingThis && (<Tooltip content={tagInfo[tag].description}><IconButton size="1" variant="ghost" color="gray" style={{ cursor: tagInfo[tag]?.url ? 'pointer' : undefined }} onClick={() => tagInfo[tag]?.url && mainApi.openExternal(tagInfo[tag].url)}><FaInfo /></IconButton></Tooltip>@@ -193,6 +205,8 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi</tbody></table>+ {editingTagError && <Warning style={{ marginBottom: '1em' }}>{editingTagError}</Warning>}+<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>diff --git a/src/renderer/src/util/languages.test.ts b/src/renderer/src/util/languages.test.tsnew file mode 100644index 00000000..39b84152--- /dev/null+++ b/src/renderer/src/util/languages.test.ts@@ -0,0 +1,17 @@+import { describe, expect, test } from 'vitest';++import { getLanguageSuggestions, isValidLanguageCode } from './languages';+++describe('getLanguageSuggestions', () => {+ test('localized labels with codes', () => {+ const suggestions = getLanguageSuggestions('en');+ expect(suggestions).toContainEqual({ value: 'ger', label: 'German (ger)' });+ expect(getLanguageSuggestions('de')).toContainEqual({ value: 'ger', label: 'Deutsch (ger)' });+ expect(suggestions.every(({ value }) => isValidLanguageCode(value))).toBe(true);+ });++ test('invalid ui language falls back to codes', () => {+ expect(getLanguageSuggestions('!!')).toContainEqual({ value: 'eng', label: 'eng (eng)' });+ });+});diff --git a/src/renderer/src/util/languages.ts b/src/renderer/src/util/languages.tsnew file mode 100644index 00000000..c74c8b06--- /dev/null+++ b/src/renderer/src/util/languages.ts@@ -0,0 +1,26 @@+import type { Suggestion } from '../components/SuggestionTextField';+++// Common ISO 639-2/B codes (as used by Matroska and ffmpeg) mapped to BCP 47, for displaying localized names+const languages: [iso6392: string, bcp47: string][] = [+ ['ara', 'ar'], ['ben', 'bn'], ['bul', 'bg'], ['chi', 'zh'], ['cze', 'cs'], ['dan', 'da'], ['dut', 'nl'], ['eng', 'en'],+ ['fil', 'fil'], ['fin', 'fi'], ['fre', 'fr'], ['ger', 'de'], ['gre', 'el'], ['heb', 'he'], ['hin', 'hi'], ['hrv', 'hr'],+ ['hun', 'hu'], ['ice', 'is'], ['ind', 'id'], ['ita', 'it'], ['jpn', 'ja'], ['kor', 'ko'], ['may', 'ms'], ['nor', 'no'],+ ['per', 'fa'], ['pol', 'pl'], ['por', 'pt'], ['rum', 'ro'], ['rus', 'ru'], ['slo', 'sk'], ['slv', 'sl'], ['spa', 'es'],+ ['srp', 'sr'], ['swe', 'sv'], ['tam', 'ta'], ['tel', 'te'], ['tha', 'th'], ['tur', 'tr'], ['ukr', 'uk'], ['urd', 'ur'],+ ['vie', 'vi'], ['und', 'und'],+];++export function getLanguageSuggestions(uiLanguage: string): Suggestion[] {+ let displayNames: Intl.DisplayNames | undefined;+ try {+ displayNames = new Intl.DisplayNames([uiLanguage, 'en'], { type: 'language' });+ } catch {+ // ignore, fall back to codes only+ }+ return languages+ .map(([value, bcp47]) => ({ value, label: `${displayNames?.of(bcp47) ?? value} (${value})` }))+ .sort((a, b) => a.label.localeCompare(b.label));+}++export const isValidLanguageCode = (code: string) => /^[a-z]{3}$/.test(code);diff --git a/src/renderer/src/util/streams.ts b/src/renderer/src/util/streams.tsindex c3433847..ae9be678 100644--- a/src/renderer/src/util/streams.ts+++ b/src/renderer/src/util/streams.ts@@ -105,6 +105,24 @@ export const isMov = (format: string | undefined) => format != null && ['ismv',export const isMatroska = (format: string | undefined) => format != null && ['matroska', 'webm'].includes(format);+// Common codec tags (FourCC) for use with `-tag`. Mostly relevant for MP4/MOV output+const codecTagsByCodec: Record<string, string[]> = {+ hevc: ['hvc1', 'hev1', 'dvh1', 'dvhe'],+ h264: ['avc1', 'avc3'],+ av1: ['av01'],+ vp9: ['vp09'],+ mpeg4: ['mp4v', 'XVID', 'DIVX'],+ aac: ['mp4a'],+ ac3: ['ac-3'],+ eac3: ['ec-3'],+ opus: ['Opus'],+ flac: ['fLaC'],+};++export const getCodecTagSuggestions = (codecName: string | undefined) => (codecName != null && codecTagsByCodec[codecName]) || [];++export const isValidCodecTag = (tag: string) => tag.length === 4;+type GetVideoArgsFn = (a: { streamIndex: number, outputIndex: number }) => string[] | undefined;function getPerStreamFlags({ stream, outputIndex, outFormat, manuallyCopyDisposition = false, getVideoArgs = () => undefined, needFlac }: {