Skip to content

The swiss army knife of lossless video/audio editing

Metadata editor: hvc1 export warning, creation_time, MP4 notice, Esc/multiline

Claude47f00c89ec72
diff --git a/locales/en/translation.json b/locales/en/translation.json
index d89f0dee..7cabe6ca 100644
--- a/locales/en/translation.json
+++ b/locales/en/translation.json
@@ -235,6 +235,7 @@
"EDL": "EDL",
"Elapsed: {{seconds}} seconds": "Elapsed: {{seconds}} seconds",
"empty": "empty",
+ "Enable": "Enable",
"Enable \"{{filterName}}\" bitstream filter.": "Enable \"{{filterName}}\" bitstream filter.",
"Enable experimental ffmpeg features flag?": "Enable experimental ffmpeg features flag",
"Enable FFmpeg `-hwaccel auto` flag. This can improve performance segment auto detection and FFmpeg-assisted playback speed.": "Enable FFmpeg `-hwaccel auto` flag. This can improve performance segment auto detection and FFmpeg-assisted playback speed.",
@@ -394,6 +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 duration": "Invalid duration",
"Invalid EDL data found": "Invalid EDL data found",
"Invalid input": "Invalid input",
@@ -502,6 +504,7 @@
"Mouse wheel frame seek modifier key": "Mouse wheel frame seek modifier key",
"Mouse wheel keyframe seek modifier key": "Mouse wheel keyframe seek modifier key",
"Mouse wheel zoom modifier key": "Mouse wheel zoom modifier key",
+ "MP4/MOV may not keep these keys unless \"{{option}}\" is enabled: {{keys}}": "MP4/MOV may not keep these keys unless \"{{option}}\" is enabled: {{keys}}",
"Mute preview": "Mute preview",
"Mute preview? (will not affect output)": "Mute preview (will not affect output)?",
"N/A": "N/A",
@@ -532,6 +535,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",
+ "Now": "Now",
"Offset": "Offset",
"OK": "OK",
"One frame back": "One frame back",
@@ -826,6 +830,7 @@
"Total seconds": "Total seconds",
"Track": "Track",
"Track {{num}} info": "Track {{num}} info",
+ "Track {{trackNumbers}} is HEVC without the \"{{tag}}\" codec tag, so it may not play on Apple devices (QuickTime, Safari, iOS). You can set the tag in the track editor.": "Track {{trackNumbers}} is HEVC without the \"{{tag}}\" codec tag, so it may not play on Apple devices (QuickTime, Safari, iOS). You can set the tag in the track editor.",
"Track has been extracted": "Track has been extracted",
"Tracks": "Tracks",
"Tracks with at least 720p video": "Tracks with at least 720p video",
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 4c8d481e..9df368e7 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -65,6 +65,7 @@ import {
getFfCommandLine,
} from './ffmpeg';
import { shouldCopyStreamByDefault, getAudioStreams, getRealVideoStreams, isAudioDefinitelyNotSupported, willPlayerProperlyHandleVideo, doesPlayerSupportHevcPlayback, getSubtitleStreams, enableVideoTrack, enableAudioTrack, canHtml5PlayerPlayStreams, isMatroska } from './util/streams';
+import { needsHvc1Tag } from './util/metadata';
import { exportEdlFile, readEdlFile, loadLlcProject, askForEdlImport } from './edlStore';
import { formatYouTube, getFrameCountRaw, formatTsvHuman } from './edlFormats';
import {
@@ -1788,6 +1789,8 @@ 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 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);
@@ -2788,7 +2791,7 @@ function App() {
{/* Dialogs */}
- <ExportConfirm areWeCutting={areWeCutting} segmentsOrInverse={segmentsOrInverse} segmentsToExport={segmentsToExport} willMerge={willMerge} visible={exportConfirmOpen} onClosePress={closeExportConfirm} onExportConfirm={onExportConfirm} renderOutFmt={renderOutFmt} outputDir={outputDir} numStreamsTotal={numStreamsTotal} numStreamsToCopy={numStreamsToCopy} onShowStreamsSelectorClick={handleShowStreamsSelectorClick} outFormat={fileFormat} cutFileTemplate={cutFileTemplateOrDefault} cutMergedFileTemplate={cutMergedFileTemplateOrDefault} generateCutFileNames={generateCutFileNames} generateCutMergedFileNames={generateCutMergedFileNames} currentSegIndexSafe={currentSegIndexSafe} mainCopiedThumbnailStreams={mainCopiedThumbnailStreams} needSmartCut={needSmartCut} isEncoding={isEncoding} encBitrate={encBitrate} setEncBitrate={setEncBitrate} toggleSettings={toggleSettings} outputPlaybackRate={outputPlaybackRate} lossyMode={lossyMode} neighbouringKeyFrames={neighbouringKeyFrames} findNearestKeyFrameTime={findNearestKeyFrameTime} />
+ <ExportConfirm areWeCutting={areWeCutting} segmentsOrInverse={segmentsOrInverse} segmentsToExport={segmentsToExport} willMerge={willMerge} visible={exportConfirmOpen} onClosePress={closeExportConfirm} onExportConfirm={onExportConfirm} renderOutFmt={renderOutFmt} outputDir={outputDir} numStreamsTotal={numStreamsTotal} numStreamsToCopy={numStreamsToCopy} onShowStreamsSelectorClick={handleShowStreamsSelectorClick} outFormat={fileFormat} cutFileTemplate={cutFileTemplateOrDefault} cutMergedFileTemplate={cutMergedFileTemplateOrDefault} generateCutFileNames={generateCutFileNames} generateCutMergedFileNames={generateCutMergedFileNames} currentSegIndexSafe={currentSegIndexSafe} mainCopiedThumbnailStreams={mainCopiedThumbnailStreams} hvc1NeededStreams={hvc1NeededStreams} needSmartCut={needSmartCut} isEncoding={isEncoding} encBitrate={encBitrate} setEncBitrate={setEncBitrate} toggleSettings={toggleSettings} outputPlaybackRate={outputPlaybackRate} lossyMode={lossyMode} neighbouringKeyFrames={neighbouringKeyFrames} findNearestKeyFrameTime={findNearestKeyFrameTime} />
<Dialog.Root open={streamsSelectorShown} onOpenChange={setStreamsSelectorShown}>
<Dialog.Portal>
diff --git a/src/renderer/src/SegmentList.tsx b/src/renderer/src/SegmentList.tsx
index 159e3a56..1d4feb43 100644
--- a/src/renderer/src/SegmentList.tsx
+++ b/src/renderer/src/SegmentList.tsx
@@ -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}>
+ <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={(e) => editingTag != null && e.preventDefault()}>
<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.tsx
index 67fef389..7de14932 100644
--- a/src/renderer/src/StreamsSelector.tsx
+++ b/src/renderer/src/StreamsSelector.tsx
@@ -15,8 +15,9 @@ import AutoExportToggler from './components/AutoExportToggler';
import Select from './components/Select';
import type { FileStream } from './ffmpeg';
import { getStreamFps } from './ffmpeg';
-import { getActiveDisposition, attachedPicDisposition, isGpsStream, getCodecTagSuggestions, isMov, isValidCodecTag } from './util/streams';
-import { getLanguageSuggestions, isValidLanguageCode } from './util/languages';
+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 SuggestionTextField from './components/SuggestionTextField';
@@ -37,10 +38,6 @@ interface EditingStream {
path: string;
}
-// Common metadata keys (as named by ffmpeg) to suggest when adding metadata
-const fileMetadataKeySuggestions = ['title', 'artist', 'album_artist', 'album', 'composer', 'genre', 'date', 'track', 'comment', 'description', 'copyright', 'creation_time'];
-const streamMetadataKeySuggestions = ['title', 'language', 'handler_name', 'comment', 'creation_time'];
-
const getStreamDispositionsObj = (stream: FFprobeStream) => ((stream && stream.disposition) || {});
const getStreamParams = ({ paramsByFile, filePath, streamId }: { paramsByFile: ParamsByFile, filePath: string, streamId: number }) => (
@@ -56,6 +53,48 @@ function getStreamEffectiveDisposition(paramsByFile: ParamsByFile, fileId: strin
}
+// Tag info shared by file and track metadata
+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' })),
+ },
+ comment: { multiline: true },
+ description: { multiline: true },
+ }), [t]);
+}
+
+function ActionCallout({ color, style, text, actionText, onAction }: { color: 'amber' | 'blue', style?: CSSProperties, text: string, actionText: string, onAction: () => void }) {
+ return (
+ <Callout.Root size="1" color={color} style={style}>
+ <Callout.Icon><FaInfoCircle /></Callout.Icon>
+ <Callout.Text>
+ {text}{' '}
+ <ThemesButton size="1" variant="soft" onClick={onAction}>{actionText}</ThemesButton>
+ </Callout.Text>
+ </Callout.Root>
+ );
+}
+
+// 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[] }) {
+ const { t } = useTranslation();
+ const { preserveMovData, setPreserveMovData } = useUserSettings();
+ const nonNativeKeys = getNonNativeMovMetadataKeys(metadata, nativeKeys);
+ if (!isMov(outFormat) || preserveMovData || nonNativeKeys.length === 0) return null;
+ return (
+ <ActionCallout
+ color="amber"
+ style={{ marginBottom: '1em' }}
+ text={t('MP4/MOV may not keep these keys unless "{{option}}" is enabled: {{keys}}', { option: t('Preserve all MP4/MOV metadata?'), keys: nonNativeKeys.join(', ') })}
+ actionText={t('Enable')}
+ onAction={() => setPreserveMovData(true)}
+ />
+ );
+}
+
function KeyValue({ name, value }: { name: ReactNode, value: ReactNode }) {
return (
<div style={{ display: 'flex', gap: '1em', marginBottom: '.3em', justifyContent: 'space-between' }}>
@@ -175,8 +214,9 @@ function OffsetEditor({ fileParams, updateFileParams }: {
}
// eslint-disable-next-line react/display-name
-const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParamsByFile, editingKey, setEditingKey, enableMetadata }: {
+const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParamsByFile, editingKey, setEditingKey, enableMetadata, outFormat }: {
editingFile: string,
+ outFormat: string | undefined,
allFilesMeta: FilesMeta,
paramsByFile: ParamsByFile,
setParamsByFile: Dispatch<SetStateAction<ParamsByFile>>,
@@ -217,11 +257,13 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParam
});
}, [updateFileParams]);
- const tagInfo = useMemo(() => ({
+ const commonTagInfo = useCommonTagInfo();
+ const tagInfo = useMemo<TagInfo>(() => ({
+ ...commonTagInfo,
encoder: {
description: t('This is hardcoded by FFmpeg and cannot be changed.'),
},
- }), [t]);
+ }), [commonTagInfo, t]);
return (
<Tabs.Root defaultValue={enableMetadata ? 'metadata' : 'offset'} style={{ minHeight: '20em' }}>
@@ -233,7 +275,8 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParam
<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} keySuggestions={fileMetadataKeySuggestions} canDeleteExisting />
+ <MovMetadataNotice outFormat={outFormat} metadata={fileParams?.metadata} nativeKeys={fileMetadataKeys} />
+ <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>
)}
@@ -285,18 +328,19 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat
});
}, [editingFile, editingStreamId, updateStreamParams]);
+ const commonTagInfo = useCommonTagInfo();
const tagInfo = useMemo<TagInfo>(() => ({
+ ...commonTagInfo,
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')),
},
- }), [i18n.language, t]);
+ }), [commonTagInfo, i18n.language, t]);
const codecTagSuggestions = useMemo(() => (isMov(outFormat) ? getCodecTagSuggestions(editingStream?.codec_name).map((value) => ({ value })) : []), [editingStream?.codec_name, outFormat]);
- // https://developer.apple.com/documentation/http-live-streaming/hls-authoring-specification-for-apple-devices
- const suggestHvc1 = editingStream?.codec_name === 'hevc' && isMov(outFormat) && streamParams?.tag == null && editingStream.codec_tag_string !== 'hvc1';
+ const suggestHvc1 = editingStream != null && needsHvc1Tag({ stream: editingStream, outFormat, customTag: streamParams?.tag });
const updateCurrentStreamParams = (setter: (a: StreamParams) => void) => updateStreamParams(editingFile, editingStreamId, setter);
@@ -304,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}>
+ <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={(e) => editingKey != null && e.preventDefault()}>
<Dialog.Title>{t('Edit track {{trackNum}} metadata', { trackNum: editingStream && (editingStream.index + 1) })}</Dialog.Title>
<Tabs.Root defaultValue="metadata" style={{ minHeight: '20em' }}>
@@ -321,7 +365,8 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat
<div style={{ marginTop: '.5em' }}>
<Tabs.Content value="metadata">
- <TagEditor existingTags={existingMetadata} customTags={streamParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} keySuggestions={streamMetadataKeySuggestions} canDeleteExisting />
+ <MovMetadataNotice outFormat={outFormat} metadata={streamParams?.metadata} nativeKeys={streamMetadataKeys} />
+ <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>
{editingStream != null && (
@@ -371,14 +416,14 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat
{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>
+ <ActionCallout
+ color="blue"
+ style={{ marginTop: '.5em' }}
+ text={t('Apple devices (QuickTime, Safari, iOS) require the "{{tag}}" codec tag to play HEVC in MP4/MOV.', { tag: 'hvc1' })}
+ actionText={t('Use "{{tag}}"', { tag: 'hvc1' })}
+ // eslint-disable-next-line no-param-reassign
+ onAction={() => updateCurrentStreamParams((params) => { params.tag = 'hvc1'; })}
+ />
)}
</>
)}
@@ -779,10 +824,10 @@ function StreamsSelector({
<Dialog.Root defaultOpen onOpenChange={(v) => v === false && setEditingFile(undefined)}>
<Dialog.Portal>
<Dialog.Overlay />
- <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined}>
+ <Dialog.Content style={{ width: '40em' }} aria-describedby={undefined} onEscapeKeyDown={(e) => editingKey != null && e.preventDefault()}>
<Dialog.Title>{t('Edit file metadata')}</Dialog.Title>
- <EditFileDialog editingFile={editingFile} editingKey={editingKey} setEditingKey={setEditingKey} allFilesMeta={allFilesMeta} paramsByFile={paramsByFile} setParamsByFile={setParamsByFile} enableMetadata={editingFile === mainFilePath} />
+ <EditFileDialog editingFile={editingFile} editingKey={editingKey} setEditingKey={setEditingKey} allFilesMeta={allFilesMeta} paramsByFile={paramsByFile} setParamsByFile={setParamsByFile} enableMetadata={editingFile === mainFilePath} outFormat={outFormat} />
<Dialog.ButtonRow>
<Dialog.Close asChild>
diff --git a/src/renderer/src/components/ExportConfirm.tsx b/src/renderer/src/components/ExportConfirm.tsx
index 07bb5755..550fe4c4 100644
--- a/src/renderer/src/components/ExportConfirm.tsx
+++ b/src/renderer/src/components/ExportConfirm.tsx
@@ -132,6 +132,7 @@ function ExportConfirm({
currentSegIndexSafe,
segmentsOrInverse,
mainCopiedThumbnailStreams,
+ hvc1NeededStreams,
needSmartCut,
isEncoding,
encBitrate,
@@ -161,6 +162,7 @@ function ExportConfirm({
currentSegIndexSafe: number,
segmentsOrInverse: UseSegments['segmentsOrInverse'],
mainCopiedThumbnailStreams: FFprobeStream[],
+ hvc1NeededStreams: FFprobeStream[],
needSmartCut: boolean,
isEncoding: boolean,
encBitrate: number | undefined,
@@ -233,6 +235,10 @@ function ExportConfirm({
generic.push({ text: t('Exporting whole file without cutting, because there are no segments to export.') });
}
+ if (hvc1NeededStreams.length > 0) {
+ generic.push({ warning: true, text: t('Track {{trackNumbers}} is HEVC without the "{{tag}}" codec tag, so it may not play on Apple devices (QuickTime, Safari, iOS). You can set the tag in the track editor.', { trackNumbers: hvc1NeededStreams.map((s) => s.index + 1).join(', '), tag: 'hvc1' }) });
+ }
+
if (areWeCutting) {
// https://github.com/mifi/lossless-cut/issues/1809
if (outFormat === 'flac') {
@@ -251,7 +257,7 @@ function ExportConfirm({
specific,
totalNum: generic.filter((n) => n.warning).length + Object.values(specific).filter((n) => n != null && n.warning).length,
};
- }, [effectiveExportMode, areWeCuttingProblematicStreams, mainCopiedThumbnailStreams, isMov, isIpod, movFastStart, t, preserveMovData, areWeCutting, needSmartCut, isEncoding, keyframeCut, enableOverwriteOutput, simpleMode, willMerge, avoidNegativeTs, outFormat, outputPlaybackRate, keyframesEnabled, haveSegmentWithProblematicKeyframe]);
+ }, [effectiveExportMode, areWeCuttingProblematicStreams, mainCopiedThumbnailStreams, isMov, isIpod, movFastStart, t, preserveMovData, areWeCutting, needSmartCut, isEncoding, keyframeCut, enableOverwriteOutput, simpleMode, willMerge, avoidNegativeTs, outFormat, outputPlaybackRate, keyframesEnabled, haveSegmentWithProblematicKeyframe, hvc1NeededStreams]);
const exportModeDescription = useMemo(() => ({
segments_to_chapters: t('Don\'t cut the file, but instead export an unmodified original which has chapters generated from segments'),
diff --git a/src/renderer/src/components/TagEditor.tsx b/src/renderer/src/components/TagEditor.tsx
index 0b4ce7de..69afe3a2 100644
--- a/src/renderer/src/components/TagEditor.tsx
+++ b/src/renderer/src/components/TagEditor.tsx
@@ -1,10 +1,10 @@
-import type { FormEventHandler } from 'react';
+import type { FormEventHandler, KeyboardEventHandler } from 'react';
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, FaClipboard, FaClipboardList, FaEdit, FaInfo, FaPlus, FaTrash, FaUndo } from 'react-icons/fa';
-import { IconButton, Tooltip, Button } from '@radix-ui/themes';
+import { IconButton, Tooltip, Button, TextArea } from '@radix-ui/themes';
import type { SegmentTags } from '../types';
import { segmentTagsSchema } from '../types';
@@ -24,6 +24,7 @@ export type TagInfo = Record<string, {
description?: string,
url?: string,
suggestions?: Suggestion[],
+ multiline?: boolean,
// returns an error message if invalid
validate?: (value: string) => string | undefined,
}>;
@@ -37,11 +38,11 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi
onTagReset: (tag: string) => void,
addTagTitle: string,
tagInfo?: TagInfo,
- keySuggestions?: string[],
+ keySuggestions?: readonly string[],
canDeleteExisting?: boolean,
}) {
const { t } = useTranslation();
- const editRef = useRef<HTMLInputElement>(null);
+ const editRef = useRef<HTMLInputElement & HTMLTextAreaElement>(null);
const addRef = useRef<HTMLInputElement>(null);
const [editingTagVal, setEditingTagVal] = useState<string>();
@@ -97,6 +98,18 @@ 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)
+ 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
+ e.preventDefault();
+ onEditClick();
+ }
+ }, [onEditClick, setEditingTag]);
+
const onDeleteExistingClick = useCallback((tag: string) => {
onTagsChange({ [tag]: '' }); // empty string means delete metadata in ffmpeg
setEditingTag(undefined);
@@ -177,7 +190,11 @@ 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}>
- <SuggestionTextField ref={editRef} placeholder={t('Enter value')} value={editingTagVal ?? ''} onValueChange={setEditingTagVal} suggestions={tagInfo?.[tag]?.suggestions ?? []} />
+ {tagInfo?.[tag]?.multiline || editingTagVal?.includes('\n') ? (
+ <TextArea ref={editRef} placeholder={t('Enter value')} value={editingTagVal ?? ''} onChange={(e) => setEditingTagVal(e.target.value)} onKeyDown={onEditKeyDown} resize="vertical" style={{ width: '20em' }} />
+ ) : (
+ <SuggestionTextField ref={editRef} placeholder={t('Enter value')} value={editingTagVal ?? ''} onValueChange={setEditingTagVal} onKeyDown={onEditKeyDown} suggestions={tagInfo?.[tag]?.suggestions ?? []} />
+ )}
</form>
) : (
renderValue({ isDeletedExisting, value, thisTagCustom })
diff --git a/src/renderer/src/util/languages.test.ts b/src/renderer/src/util/languages.test.ts
deleted file mode 100644
index 39b84152..00000000
--- a/src/renderer/src/util/languages.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-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.ts
deleted file mode 100644
index c74c8b06..00000000
--- a/src/renderer/src/util/languages.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-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/metadata.test.ts b/src/renderer/src/util/metadata.test.ts
new file mode 100644
index 00000000..6ba9a061
--- /dev/null
+++ b/src/renderer/src/util/metadata.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from 'vitest';
+
+import { getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidLanguageCode, needsHvc1Tag, streamMetadataKeys } from './metadata';
+
+
+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)' });
+ });
+});
+
+test('isValidCodecTag', () => {
+ expect(isValidCodecTag('hvc1')).toBe(true);
+ expect(isValidCodecTag('0x31637668')).toBe(true);
+ expect(isValidCodecTag('hvc1 ')).toBe(false);
+ expect(isValidCodecTag('hvc')).toBe(false);
+});
+
+test('needsHvc1Tag', () => {
+ const hev1 = { codec_name: 'hevc', codec_tag_string: 'hev1' };
+ expect(needsHvc1Tag({ stream: hev1, outFormat: 'mp4', customTag: undefined })).toBe(true);
+ expect(needsHvc1Tag({ stream: hev1, outFormat: 'mp4', customTag: 'hev1' })).toBe(false);
+ expect(needsHvc1Tag({ stream: hev1, outFormat: 'matroska', customTag: undefined })).toBe(false);
+ expect(needsHvc1Tag({ stream: { codec_name: 'hevc', codec_tag_string: 'hvc1' }, outFormat: 'mov', customTag: undefined })).toBe(false);
+ expect(needsHvc1Tag({ stream: { codec_name: 'h264', codec_tag_string: 'avc1' }, outFormat: 'mp4', customTag: undefined })).toBe(false);
+});
+
+test('getNonNativeMovMetadataKeys', () => {
+ expect(getNonNativeMovMetadataKeys({ title: 'a', custom: 'b', deleted: '' }, streamMetadataKeys)).toEqual(['custom']);
+ expect(getNonNativeMovMetadataKeys(undefined, streamMetadataKeys)).toEqual([]);
+});
diff --git a/src/renderer/src/util/metadata.ts b/src/renderer/src/util/metadata.ts
new file mode 100644
index 00000000..63088408
--- /dev/null
+++ b/src/renderer/src/util/metadata.ts
@@ -0,0 +1,63 @@
+import type { FFprobeStream } from '../../../common/ffprobe';
+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`)
+export 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)
+);
+
+// Common codec tags (FourCC) for use with `-tag` when outputting MP4/MOV
+const codecTagsByCodec: Partial<Record<FFprobeStream['codec_name'], readonly string[]>> = {
+ hevc: ['hvc1', 'hev1'],
+ h264: ['avc1', 'avc3'],
+ av1: ['av01'],
+ vp9: ['vp09'],
+ mpeg4: ['mp4v'],
+ aac: ['mp4a'],
+ ac3: ['ac-3'],
+ eac3: ['ec-3'],
+ opus: ['Opus'],
+ flac: ['fLaC'],
+};
+
+export const getCodecTagSuggestions = (codecName: string | undefined) => (codecName != null && codecTagsByCodec[codecName]) || [];
+
+// ffmpeg accepts a FourCC or a numeric tag like 0x31637668
+export const isValidCodecTag = (tag: string) => tag.length === 4 || /^0x[\da-f]+$/i.test(tag);
+
+// Apple devices (QuickTime, Safari, iOS) require hvc1 for HEVC in MP4/MOV, but ffmpeg defaults to hev1 (unless the source is already hvc1)
+// https://developer.apple.com/documentation/http-live-streaming/hls-authoring-specification-for-apple-devices
+export const needsHvc1Tag = ({ stream, outFormat, customTag }: { stream: Pick<FFprobeStream, 'codec_name' | 'codec_tag_string'>, outFormat: string | undefined, customTag: string | undefined }) => (
+ stream.codec_name === 'hevc' && isMov(outFormat) && customTag == null && stream.codec_tag_string !== 'hvc1'
+);
+
+export const isValidCreationTime = (value: string) => !Number.isNaN(Date.parse(value));
+
+// 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.test.ts b/src/renderer/src/util/streams.test.ts
index dd2c073b..9d9c5bca 100644
--- a/src/renderer/src/util/streams.test.ts
+++ b/src/renderer/src/util/streams.test.ts
@@ -1,6 +1,6 @@
import { test, expect } from 'vitest';
-import { getEffectiveAvoidNegativeTs, getKeyframeCutSeekCompensation, getMapStreamsArgs, getStreamIdsToCopy, isCopyingOnlyAudioStreams, isValidCodecTag } from './streams';
+import { getEffectiveAvoidNegativeTs, getKeyframeCutSeekCompensation, getMapStreamsArgs, getStreamIdsToCopy, isCopyingOnlyAudioStreams } from './streams';
import type { FFprobeStreamDisposition } from '../../../common/ffprobe';
import type { LiteFFprobeStream } from '../types';
@@ -232,10 +232,3 @@ test('getKeyframeCutSeekCompensation', () => {
// not cutting start
expect(getKeyframeCutSeekCompensation({ formatName: 'matroska,webm', streams: bFrames, cutFrom: 0 })).toBe(0);
});
-
-test('isValidCodecTag', () => {
- expect(isValidCodecTag('hvc1')).toBe(true);
- expect(isValidCodecTag('0x31637668')).toBe(true);
- expect(isValidCodecTag('hvc1 ')).toBe(false);
- expect(isValidCodecTag('hvc')).toBe(false);
-});
diff --git a/src/renderer/src/util/streams.ts b/src/renderer/src/util/streams.ts
index b618ae86..c3433847 100644
--- a/src/renderer/src/util/streams.ts
+++ b/src/renderer/src/util/streams.ts
@@ -105,25 +105,6 @@ 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` when outputting MP4/MOV
-const codecTagsByCodec: Record<string, string[]> = {
- hevc: ['hvc1', 'hev1'],
- h264: ['avc1', 'avc3'],
- av1: ['av01'],
- vp9: ['vp09'],
- mpeg4: ['mp4v'],
- aac: ['mp4a'],
- ac3: ['ac-3'],
- eac3: ['ec-3'],
- opus: ['Opus'],
- flac: ['fLaC'],
-};
-
-export const getCodecTagSuggestions = (codecName: string | undefined) => (codecName != null && codecTagsByCodec[codecName]) || [];
-
-// ffmpeg accepts a FourCC or a numeric tag like 0x31637668
-export const isValidCodecTag = (tag: string) => tag.length === 4 || /^0x[\da-f]+$/i.test(tag);
-
type GetVideoArgsFn = (a: { streamIndex: number, outputIndex: number }) => string[] | undefined;
function getPerStreamFlags({ stream, outputIndex, outFormat, manuallyCopyDisposition = false, getVideoArgs = () => undefined, needFlac }: {