The swiss army knife of lossless video/audio editing
Copy metadata from another track or file in the metadata editors
Claudedb94da16dfd3
diff --git a/locales/en/translation.json b/locales/en/translation.jsonindex 3fabf6b4..7525501c 100644--- a/locales/en/translation.json+++ b/locales/en/translation.json@@ -150,6 +150,7 @@"Convert to supported format": "Convert to supported format","Converting to supported format": "Converting to supported format","Copy": "Copy",+ "Copy from": "Copy from","Copy selected segments times to clipboard": "Copy selected segments times to clipboard","Copy to clipboard": "Copy to clipboard","Copy to YouTube description/comment:": "Copy to YouTube description/comment:",diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex e0e59a70..f722bd5e 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -16,7 +16,7 @@ import Select from './components/Select';import type { FileStream } from './ffmpeg';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 { fileMetadataKeys, getCodecTagSuggestions, getCopyableMetadata, getEffectiveMetadata, getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidCreationTime, isValidLanguageCode, needsHvc1Tag, streamMetadataKeys } from './util/metadata';import useUserSettings from './hooks/useUserSettings';import TagEditor, { cancelTagEditOnEscape, type TagInfo } from './components/TagEditor';import SuggestionTextField from './components/SuggestionTextField';@@ -30,6 +30,14 @@ import GpsMap from './components/GpsMap';import Switch from './components/Switch';+const getFileName = (path: string) => path.replace(/.*\/([^/]+)$/, '$1');++// for "Copy from": the source's metadata including the user's changes, without muxer-written keys+function getCopyFromSource(label: string, existing: Record<string, string> | undefined, custom: Record<string, string> | undefined) {+ const metadata = getCopyableMetadata(getEffectiveMetadata(existing, custom));+ return Object.keys(metadata).length > 0 ? { label, metadata } : undefined;+}+type UpdateStreamParams = (fileId: string, streamId: number, setter: (a: StreamParams) => void) => void;interface EditingStream {@@ -257,6 +265,10 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParam});}, [updateFileParams]);+ const copyFromSources = useMemo(() => Object.entries(allFilesMeta).flatMap(([path, { format: otherFormat }]) => (+ path !== editingFile ? getCopyFromSource(getFileName(path), otherFormat.tags, paramsByFile.get(path)?.metadata) ?? [] : []+ )), [allFilesMeta, editingFile, paramsByFile]);+const commonTagInfo = useCommonTagInfo();const tagInfo = useMemo<TagInfo>(() => ({...commonTagInfo,@@ -276,7 +288,7 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, paramsByFile, setParam{enableMetadata && (<Tabs.Content value="metadata"><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 />+ <TagEditor existingTags={existingMetadata} customTags={fileParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} keySuggestions={fileMetadataKeys} copyFromSources={copyFromSources} canDeleteExisting /></Tabs.Content>)}@@ -341,6 +353,17 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat});}, [editingFile, editingStreamId, updateStreamParams]);+ const copyFromSources = useMemo(() => {+ const multipleFiles = Object.keys(allFilesMeta).length > 1;+ return Object.entries(allFilesMeta).flatMap(([path, { streams: fileStreams }]) => fileStreams.flatMap((s) => {+ if (path === editingFile && s.index === editingStreamId) return [];+ const custom = getStreamParams({ paramsByFile, filePath: path, streamId: s.index })?.metadata;+ const title = custom?.['title'] ?? s.tags?.title;+ const label = `${multipleFiles ? `${getFileName(path)}: ` : ''}#${s.index + 1} ${s.codec_type}${title ? ` – ${title}` : ''}`;+ return getCopyFromSource(label, s.tags, custom) ?? [];+ }));+ }, [allFilesMeta, editingFile, editingStreamId, paramsByFile]);+const commonTagInfo = useCommonTagInfo();const tagInfo = useMemo<TagInfo>(() => ({...commonTagInfo,@@ -379,7 +402,7 @@ const EditStreamDialog = memo(({ editingStream: { streamId: editingStreamId, pat<div style={{ marginTop: '.5em' }}><Tabs.Content value="metadata"><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 onApplyToAll={otherStreamsOfSameType.length > 0 ? onApplyToAll : undefined} applyToAllTitle={t('Apply to all other tracks of this type')} />+ <TagEditor existingTags={existingMetadata} customTags={streamParams?.metadata} editingTag={editingKey} setEditingTag={setEditingKey} onTagsChange={onMetadataChange} onTagReset={onMetadataReset} addTagTitle={t('Add metadata')} tagInfo={tagInfo} keySuggestions={streamMetadataKeys} canDeleteExisting onApplyToAll={otherStreamsOfSameType.length > 0 ? onApplyToAll : undefined} applyToAllTitle={t('Apply to all other tracks of this type')} copyFromSources={copyFromSources} /></Tabs.Content>{editingStream != null && (@@ -655,7 +678,7 @@ function FileHeading({ path, format, onEditClick, toggleCopyAllStreams, chaptersreturn (<div style={{ display: 'flex', marginBottom: '.2em', borderBottom: '1px solid var(--gray-7)' }}>- <div title={path} style={{ wordBreak: 'break-all', marginRight: '1em', fontWeight: 'bold' }}>{path.replace(/.*\/([^/]+)$/, '$1')}</div>+ <div title={path} style={{ wordBreak: 'break-all', marginRight: '1em', fontWeight: 'bold' }}>{getFileName(path)}</div><div style={{ flexGrow: 1 }} />diff --git a/src/renderer/src/components/TagEditor.tsx b/src/renderer/src/components/TagEditor.tsxindex 279c8f90..9fb63d4f 100644--- a/src/renderer/src/components/TagEditor.tsx+++ b/src/renderer/src/components/TagEditor.tsx@@ -3,8 +3,8 @@ 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, FaClone, FaEdit, FaInfo, FaPlus, FaTrash, FaUndo } from 'react-icons/fa';-import { IconButton, Tooltip, Button, TextArea } from '@radix-ui/themes';+import { FaCheck, FaChevronDown, FaClipboard, FaClipboardList, FaClone, FaCopy, FaEdit, FaInfo, FaPlus, FaTrash, FaUndo } from 'react-icons/fa';+import { IconButton, Tooltip, Button, TextArea, DropdownMenu } from '@radix-ui/themes';import type { SegmentTags } from '../types';import { segmentTagsSchema } from '../types';@@ -37,7 +37,7 @@ export const cancelTagEditOnEscape = (editingTag: string | undefined, setEditingsetEditingTag(undefined);};-function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editingTag, setEditingTag, onTagsChange, onTagReset, addTagTitle, tagInfo, keySuggestions, canDeleteExisting, onApplyToAll, applyToAllTitle }: {+function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editingTag, setEditingTag, onTagsChange, onTagReset, addTagTitle, tagInfo, keySuggestions, canDeleteExisting, onApplyToAll, applyToAllTitle, copyFromSources = [] }: {existingTags?: SegmentTags,customTags?: SegmentTags | undefined,editingTag: string | undefined,@@ -50,6 +50,8 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editicanDeleteExisting?: boolean,onApplyToAll?: ((tag: string, value: string) => void) | undefined,applyToAllTitle?: string,+ // other tracks/files to copy metadata from+ copyFromSources?: { label: string, metadata: Record<string, string> }[],}) {const { t } = useTranslation();const editRef = useRef<HTMLInputElement & HTMLTextAreaElement>(null);@@ -252,7 +254,20 @@ function TagEditor({ existingTags = emptyObject, customTags = emptyObject, editi{({ onClick }) => <Button color="gray" size="1" onClick={onClick}><FaClipboardList />{t('Copy to clipboard')}</Button>}</CopyClipboardButton>- <Button color="gray" size="1" onClick={onPasteClick}><FaClipboard />{t('Paste')}</Button>+ <Button color="gray" size="1" onClick={onPasteClick} style={{ marginRight: '.3em' }}><FaClipboard />{t('Paste')}</Button>++ {copyFromSources.length > 0 && (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Button color="gray" size="1"><FaCopy />{t('Copy from')}<FaChevronDown /></Button>+ </DropdownMenu.Trigger>+ <DropdownMenu.Content size="1" style={{ maxHeight: '20em' }}>+ {copyFromSources.map(({ label, metadata }) => (+ <DropdownMenu.Item key={label} onSelect={() => onTagsChange(metadata)}>{label}</DropdownMenu.Item>+ ))}+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )}</div></>);diff --git a/src/renderer/src/util/metadata.test.ts b/src/renderer/src/util/metadata.test.tsindex d8ee5819..cb170797 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, isValidCreationTime, isValidLanguageCode, needsHvc1Tag } from './metadata';+import { getCopyableMetadata, getEffectiveMetadata, getLanguageSuggestions, getNonNativeMovMetadataKeys, isValidCodecTag, isValidCreationTime, isValidLanguageCode, needsHvc1Tag } from './metadata';describe('getLanguageSuggestions', () => {@@ -51,3 +51,20 @@ test('isValidCreationTime', () => {expect(isValidCreationTime('12/31/2024')).toBe(false);expect(isValidCreationTime('1')).toBe(false);});++test('getEffectiveMetadata', () => {+ expect(getEffectiveMetadata({ title: 'a', language: 'eng', comment: 'c' }, { title: 'b', comment: '' })).toEqual({ title: 'b', language: 'eng' });+ expect(getEffectiveMetadata(undefined, undefined)).toEqual({});+});++test('getCopyableMetadata', () => {+ expect(getCopyableMetadata({+ title: 'a',+ language: 'eng',+ DURATION: '00:01:00.000',+ 'BPS-eng': '128000',+ _STATISTICS_WRITING_APP: 'mkvmerge',+ encoder: 'Lavf',+ major_brand: 'isom',+ })).toEqual({ title: 'a', language: 'eng' });+});diff --git a/src/renderer/src/util/metadata.ts b/src/renderer/src/util/metadata.tsindex 37962c23..f9832439 100644--- a/src/renderer/src/util/metadata.ts+++ b/src/renderer/src/util/metadata.ts@@ -17,6 +17,18 @@ export const getNonNativeMovMetadataKeys = ({ metadata, outFormat, isStream }: {return Object.entries(metadata ?? {}).filter(([key, value]) => value !== '' && !nativeKeys.has(key)).map(([key]) => key);};+// Existing metadata with the user's changes applied ('' means deleted)+export const getEffectiveMetadata = (existing: Record<string, string> | undefined, custom: Record<string, string> | undefined) => (+ Object.fromEntries(Object.entries({ ...existing, ...custom }).filter(([, value]) => value !== ''))+);++// Keys that describe the source's own data (written by the muxer), so they shouldn't be copied to another track/file+const nonCopyableMetadataKeyRegex = /^(encoder|major_brand|minor_version|compatible_brands|(DURATION|NUMBER_OF_FRAMES|NUMBER_OF_BYTES|BPS|_STATISTICS_[A-Z_]+)(-\w+)?)$/i;++export const getCopyableMetadata = (metadata: Record<string, string>) => (+ Object.fromEntries(Object.entries(metadata).filter(([key]) => !nonCopyableMetadataKeyRegex.test(key)))+);+// Common codec tags (FourCC) for use with `-tag` when outputting MP4/MOVconst codecTagsByCodec: Partial<Record<FFprobeStream['codec_name'], readonly string[]>> = {hevc: ['hvc1', 'hev1'],