The swiss army knife of lossless video/audio editing
implement SEG_LABEL array in cut+merge mode #2428
Mikael Finstad2504304748f2
diff --git a/docs.md b/docs.mdindex 35dacf76..9879880f 100644--- a/docs.md+++ b/docs.md@@ -67,11 +67,11 @@ The following variables are available in the template to customize the filenames| ✅ | `${EPOCH_MS}` | `number` | Number of milliseconds since epoch (e.g. `1680852771465`). Useful to generate a unique file name on every export to prevent accidental overwrite.| ✅ | `${EXPORT_COUNT}` | `number` | Number of exports done since last LosslessCut launch (starts at 1).| ✅ | `${FILE_EXPORT_COUNT}` | `number` | Number of exports done since last file was opened (starts at 1).+| ✅ | `${SEG_LABEL}` | `string` | The label of the segment (e.g. `Getting Lunch`). In cut+merge mode, this will be an `Array`, and you can use e.g. this code to combine all labels with a comma between: `${SEG_LABEL.filter(label => label).join(',')}`| | `${SEG_NUM}` | `string` | Segment index, padded string (e.g. `01`, `02` or `42`).| | `${SEG_NUM_INT}` | `number` | Segment index, as an integer (e.g. `1`, `2` or `42`). Can be used with numeric arithmetics, e.g. `${SEG_NUM_INT+100}`.| | `${SELECTED_SEG_NUM}` | `string` | Same as `SEG_NUM`, but it counts only selected segments.| | `${SELECTED_SEG_NUM_INT}` | `number` | Same as `SEG_NUM_INT`, but it counts only selected segments.-| | `${SEG_LABEL}` | `string` | The label of the segment (e.g. `Getting Lunch`).| | `${SEG_SUFFIX}` | `string` | If a label exists for this segment, the label will be used, prepended by `-`. Otherwise, the segment index prepended by `-seg` will be used (e.g. `-Getting_Lunch`, `-seg1`).| | `${CUT_FROM}` | `string` | The timestamp for the beginning of the segment in `hh.mm.ss.sss` format (e.g. `00.00.27.184`).| | `${CUT_TO}` | `string` | The timestamp for the ending of the segment in `hh.mm.ss.sss` format (e.g. `00.00.28.000`).diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex 89432faf..28f116bf 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -1037,8 +1037,8 @@ function App() {const generateMergedFileNames = useCallback(async (template: string) => {invariant(fileFormat != null && filePath != null);- return generateMergedFileNamesRaw({ template, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, exportCount, currentFileExportCount });- }, [currentFileExportCount, exportCount, fileFormat, filePath, isCustomFormatSelected, outputDir, safeOutputFileName]);+ return generateMergedFileNamesRaw({ template, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, exportCount, currentFileExportCount, segmentsToExport });+ }, [currentFileExportCount, exportCount, fileFormat, filePath, isCustomFormatSelected, maxLabelLength, outputDir, safeOutputFileName, segmentsToExport]);const closeExportConfirm = useCallback(() => setExportConfirmVisible(false), []);@@ -2744,7 +2744,7 @@ function App() {/></Sheet>- <ConcatDialog isShown={batchFiles.length > 0 && concatDialogVisible} onHide={() => setConcatDialogVisible(false)} paths={batchFilePaths} onConcat={userConcatFiles} setAlwaysConcatMultipleFiles={setAlwaysConcatMultipleFiles} alwaysConcatMultipleFiles={alwaysConcatMultipleFiles} exportCount={exportCount} />+ <ConcatDialog isShown={batchFiles.length > 0 && concatDialogVisible} onHide={() => setConcatDialogVisible(false)} paths={batchFilePaths} onConcat={userConcatFiles} setAlwaysConcatMultipleFiles={setAlwaysConcatMultipleFiles} alwaysConcatMultipleFiles={alwaysConcatMultipleFiles} exportCount={exportCount} maxLabelLength={maxLabelLength} /><KeyboardShortcuts isShown={keyboardShortcutsVisible} onHide={() => setKeyboardShortcutsVisible(false)} keyBindings={keyBindings} setKeyBindings={setKeyBindings} currentCutSeg={currentCutSeg} resetKeyBindings={resetKeyBindings} />diff --git a/src/renderer/src/components/ConcatDialog.tsx b/src/renderer/src/components/ConcatDialog.tsxindex 0ba2d7a8..3eafb21d 100644--- a/src/renderer/src/components/ConcatDialog.tsx+++ b/src/renderer/src/components/ConcatDialog.tsx@@ -33,7 +33,7 @@ function Alert({ text }: { text: string }) {);}-function ConcatDialog({ isShown, onHide, paths, onConcat, alwaysConcatMultipleFiles, setAlwaysConcatMultipleFiles, exportCount }: {+function ConcatDialog({ isShown, onHide, paths, onConcat, alwaysConcatMultipleFiles, setAlwaysConcatMultipleFiles, exportCount, maxLabelLength }: {isShown: boolean,onHide: () => void,paths: string[],@@ -41,6 +41,7 @@ function ConcatDialog({ isShown, onHide, paths, onConcat, alwaysConcatMultipleFialwaysConcatMultipleFiles: boolean,setAlwaysConcatMultipleFiles: (a: boolean) => void,exportCount: number,+ maxLabelLength: number,}) {const { t } = useTranslation();const { preserveMovData, setPreserveMovData, segmentsToChapters, setSegmentsToChapters, preserveMetadataOnMerge, setPreserveMetadataOnMerge, safeOutputFileName, customOutDir } = useUserSettings();@@ -99,7 +100,7 @@ function ConcatDialog({ isShown, onHide, paths, onConcat, alwaysConcatMultipleFi// todo allow user to edit template instead of this "hack"if (existingOutputName == null) {(async () => {- const generated = await generateMergedFileNames({ template: defaultMergedFileTemplate, isCustomFormatSelected, fileFormat, filePath: firstPath, outputDir, safeOutputFileName, epochMs: uniqueSuffix, exportCount });+ const generated = await generateMergedFileNames({ template: defaultMergedFileTemplate, isCustomFormatSelected, fileFormat, filePath: firstPath, outputDir, safeOutputFileName, maxLabelLength, epochMs: uniqueSuffix, exportCount });// todo show to user more errors?const [fileName] = generated.fileNames;invariant(fileName != null);@@ -112,7 +113,7 @@ function ConcatDialog({ isShown, onHide, paths, onConcat, alwaysConcatMultipleFi// make sure the last (optional) .* is replaced by .ext`return existingOutputName.replace(/(\.[^.]*)?$/, ext);});- }, [customOutDir, exportCount, fileFormat, firstPath, isCustomFormatSelected, safeOutputFileName, uniqueSuffix]);+ }, [customOutDir, exportCount, fileFormat, firstPath, isCustomFormatSelected, maxLabelLength, safeOutputFileName, uniqueSuffix]);const allFilesMeta = useMemo(() => {if (paths.length === 0) return undefined;diff --git a/src/renderer/src/components/FileNameTemplateEditor.tsx b/src/renderer/src/components/FileNameTemplateEditor.tsxindex afeb9c74..1e5c1d9c 100644--- a/src/renderer/src/components/FileNameTemplateEditor.tsx+++ b/src/renderer/src/components/FileNameTemplateEditor.tsx@@ -63,7 +63,7 @@ function FileNameTemplateEditor(opts: {const outSegs = await generateFileNames(debouncedText);// console.timeEnd('generateOutSegFileNames')if (abortController.signal.aborted) return;- setFileNames(outSegs.fileNames);+ setFileNames(outSegs.originalFileNames ?? outSegs.fileNames);setProblems(outSegs.problems);setValidText(outSegs.problems.error == null ? debouncedText : undefined);} catch (err) {@@ -77,8 +77,8 @@ function FileNameTemplateEditor(opts: {}, [debouncedText, generateFileNames, t]);const availableVariables = useMemo(() => (mergeMode- ? ['FILENAME', extVariable, 'EPOCH_MS', 'EXPORT_COUNT']- : ['FILENAME', 'CUT_FROM', 'CUT_TO', segNumVariable, segNumIntVariable, selectedSegNumVariable, selectedSegNumIntVariable, 'SEG_LABEL', segSuffixVariable, extVariable, segTagsExample, 'EPOCH_MS', 'EXPORT_COUNT', 'FILE_EXPORT_COUNT']+ ? ['FILENAME', extVariable, 'EPOCH_MS', 'EXPORT_COUNT', 'FILE_EXPORT_COUNT', 'SEG_LABEL']+ : ['FILENAME', extVariable, 'EPOCH_MS', 'EXPORT_COUNT', 'FILE_EXPORT_COUNT', 'SEG_LABEL', 'CUT_FROM', 'CUT_TO', segNumVariable, segNumIntVariable, selectedSegNumVariable, selectedSegNumIntVariable, segSuffixVariable, segTagsExample]), [mergeMode]);// eslint-disable-next-line no-template-curly-in-stringdiff --git a/src/renderer/src/util/outputNameTemplate.ts b/src/renderer/src/util/outputNameTemplate.tsindex a90bff14..b7d3542c 100644--- a/src/renderer/src/util/outputNameTemplate.ts+++ b/src/renderer/src/util/outputNameTemplate.ts@@ -114,19 +114,20 @@ export const defaultCutMergedFileTemplate = '${FILENAME}-cut-merged-${EPOCH_MS}$// eslint-disable-next-line no-template-curly-in-stringexport const defaultMergedFileTemplate = '${FILENAME}-merged-${EPOCH_MS}${EXT}';-async function interpolateOutFileName(template: string, { epochMs, inputFileNameWithoutExt, ext, segSuffix, segNum, segNumPadded, selectedSegNum, selectedSegNumPadded, segLabel, cutFrom, cutTo, tags, exportCount, currentFileExportCount }: {++async function interpolateOutFileName(template: string, { epochMs, inputFileNameWithoutExt, ext, segSuffix, segNum, segNumPadded, selectedSegNum, selectedSegNumPadded, segLabels, cutFrom, cutTo, tags, exportCount, currentFileExportCount }: {epochMs: number,inputFileNameWithoutExt: string,ext: string,exportCount: number,currentFileExportCount?: number | undefined,+ segLabels: string[],} & Partial<{segSuffix: string,segNum: number,segNumPadded: string,selectedSegNum: number,selectedSegNumPadded: string,- segLabel: string,cutFrom: string,cutTo: string,tags: Record<string, string>,@@ -139,7 +140,7 @@ async function interpolateOutFileName(template: string, { epochMs, inputFileName[segNumVariable]: segNumPadded,[selectedSegNumIntVariable]: selectedSegNum,[selectedSegNumVariable]: selectedSegNumPadded,- SEG_LABEL: segLabel,+ SEG_LABEL: segLabels.length === 1 ? segLabels[0] : segLabels,EPOCH_MS: epochMs,CUT_FROM: cutFrom,CUT_TO: cutTo,@@ -171,6 +172,34 @@ function maybeTruncatePath(fileName: string, truncate: boolean) {].join(pathSep);}+async function generateWithFallback({ generate, desiredTemplate, defaultTemplate, safeOutputFileName, filePath, outputDir, maxLabelLength }: {+ generate: (a: {+ template: string,+ sanitizeName: (name: string) => string,+ safeOutputFileName: boolean,+ }) => Promise<string[]>,+ desiredTemplate: string,+ defaultTemplate: string,+ safeOutputFileName: boolean,+ filePath: string,+ outputDir: string,+ maxLabelLength: number,+}) {+ // Fields that did not come from the source file's name must be sanitized, because they may contain characters that are not supported by the target operating/file system+ // however we disable this when the user has chosen to (safeOutputFileName === false)+ const sanitizeName = (name: string, safe: boolean) => (safe ? filenamify(name) : name).slice(0, Math.max(0, maxLabelLength));++ const originalFileNames = await generate({ template: desiredTemplate, sanitizeName: (name: string) => sanitizeName(name, safeOutputFileName), safeOutputFileName });++ const problems = getTemplateProblems({ fileNames: originalFileNames, filePath, outputDir, safeOutputFileName });+ if (problems.error != null) {+ const fileNames = await generate({ template: defaultTemplate, sanitizeName: (name: string) => sanitizeName(name, true), safeOutputFileName: true });+ return { fileNames, originalFileNames, problems };+ }++ return { fileNames: originalFileNames, problems };+}+export async function generateOutSegFileNames({ fileDuration, segmentsToExport: segmentsToExportIn, template: desiredTemplate, formatTimecode, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding, exportCount, currentFileExportCount }: {fileDuration: number | undefined,segmentsToExport: SegmentToExport[],@@ -188,101 +217,99 @@ export async function generateOutSegFileNames({ fileDuration, segmentsToExport:}) {const segmentsToExport = getGuaranteedSegments(segmentsToExportIn, fileDuration);- async function generate({ template, forceSafeOutputFileName }: { template: string, forceSafeOutputFileName: boolean }) {- const epochMs = Date.now();-- const maxOriginalIndex = max(segmentsToExport.map((s) => s.originalIndex)) ?? 0;-- return pMap(segmentsToExport, async (segment, i) => {- const { start, end, name = '' } = segment;- const selectedSegNum = i + 1;- const selectedSegNumPadded = formatSegNum(i, segmentsToExport.length, outputFileNameMinZeroPadding);- const segNum = segment.originalIndex + 1;- const segNumPadded = formatSegNum(segment.originalIndex, maxOriginalIndex + 1, outputFileNameMinZeroPadding);-- // Fields that did not come from the source file's name must be sanitized, because they may contain characters that are not supported by the target operating/file system- // however we disable this when the user has chosen to (safeOutputFileName === false)- const filenamifyOrNot = (fileName: string) => (safeOutputFileName || forceSafeOutputFileName ? filenamify(fileName) : fileName).slice(0, Math.max(0, maxLabelLength));-- function getSegSuffix() {- if (name) return `-${filenamifyOrNot(name)}`;- // https://github.com/mifi/lossless-cut/issues/583- if (segmentsToExport.length > 1) return `-seg${segNumPadded}`;- return '';- }-- const { name: inputFileNameWithoutExt } = parsePath(filePath);-- const segFileName = await interpolateOutFileName(template, {- epochMs,- segNum,- segNumPadded,- selectedSegNum,- selectedSegNumPadded,- segSuffix: getSegSuffix(),- inputFileNameWithoutExt,- ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),- segLabel: filenamifyOrNot(name),- cutFrom: formatTimecode({ seconds: start, fileNameFriendly: true }),- cutTo: formatTimecode({ seconds: end, fileNameFriendly: true }),- tags: Object.fromEntries(Object.entries(getSegmentTags(segment)).map(([tag, value]) => [tag, filenamifyOrNot(value)])),- exportCount,- currentFileExportCount,- });-- return maybeTruncatePath(segFileName, safeOutputFileName);- }, { concurrency: 5 });- }-- let fileNames = await generate({ template: desiredTemplate, forceSafeOutputFileName: false });-- const problems = getTemplateProblems({ fileNames, filePath, outputDir, safeOutputFileName });- if (problems.error != null) {- fileNames = await generate({ template: defaultOutSegTemplate, forceSafeOutputFileName: true });- }-- return { fileNames, problems };+ return generateWithFallback({+ generate: async ({ template, safeOutputFileName: safeOutputFileName2, sanitizeName }) => {+ const epochMs = Date.now();++ const maxOriginalIndex = max(segmentsToExport.map((s) => s.originalIndex)) ?? 0;++ return pMap(segmentsToExport, async (segment, i) => {+ const { start, end, name = '' } = segment;+ const selectedSegNum = i + 1;+ const selectedSegNumPadded = formatSegNum(i, segmentsToExport.length, outputFileNameMinZeroPadding);+ const segNum = segment.originalIndex + 1;+ const segNumPadded = formatSegNum(segment.originalIndex, maxOriginalIndex + 1, outputFileNameMinZeroPadding);++ function getSegSuffix() {+ if (name) return `-${sanitizeName(name)}`;+ // https://github.com/mifi/lossless-cut/issues/583+ if (segmentsToExport.length > 1) return `-seg${segNumPadded}`;+ return '';+ }++ const { name: inputFileNameWithoutExt } = parsePath(filePath);++ const segFileName = await interpolateOutFileName(template, {+ epochMs,+ segNum,+ segNumPadded,+ selectedSegNum,+ selectedSegNumPadded,+ segSuffix: getSegSuffix(),+ inputFileNameWithoutExt,+ ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),+ segLabels: [sanitizeName(name)],+ cutFrom: formatTimecode({ seconds: start, fileNameFriendly: true }),+ cutTo: formatTimecode({ seconds: end, fileNameFriendly: true }),+ tags: Object.fromEntries(Object.entries(getSegmentTags(segment)).map(([tag, value]) => [tag, sanitizeName(value)])),+ exportCount,+ currentFileExportCount,+ });++ return maybeTruncatePath(segFileName, safeOutputFileName2);+ }, { concurrency: 5 });+ },+ desiredTemplate,+ defaultTemplate: defaultOutSegTemplate,+ filePath,+ outputDir,+ maxLabelLength,+ safeOutputFileName,+ });}export type GenerateOutFileNames = (template: string) => Promise<{fileNames: string[],+ originalFileNames?: string[] | undefined,problems: {error: string | undefined;sameAsInputFileNameWarning: boolean;},}>;-export async function generateMergedFileNames({ template: desiredTemplate, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, epochMs = Date.now(), exportCount, currentFileExportCount }: {+export async function generateMergedFileNames({ template: desiredTemplate, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, epochMs = Date.now(), exportCount, currentFileExportCount, segmentsToExport }: {template: string,isCustomFormatSelected: boolean,fileFormat: string,filePath: string,outputDir: string,safeOutputFileName: boolean,+ maxLabelLength: number,epochMs?: number,exportCount: number,currentFileExportCount?: number,+ segmentsToExport?: SegmentToExport[],}) {- async function generate(template: string) {- const { name: inputFileNameWithoutExt } = parsePath(filePath);-- const fileName = await interpolateOutFileName(template, {- epochMs,- inputFileNameWithoutExt,- ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),- exportCount,- currentFileExportCount,- });-- return maybeTruncatePath(fileName, safeOutputFileName);- }-- let fileName = await generate(desiredTemplate);+ return generateWithFallback({+ generate: async ({ template, safeOutputFileName: safeOutputFileName2, sanitizeName }) => {+ const { name: inputFileNameWithoutExt } = parsePath(filePath);- const problems = getTemplateProblems({ fileNames: [fileName], filePath, outputDir, safeOutputFileName });- if (problems.error != null) {- fileName = await generate(defaultCutMergedFileTemplate);- }+ const fileName = await interpolateOutFileName(template, {+ epochMs,+ inputFileNameWithoutExt,+ ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),+ exportCount,+ currentFileExportCount,+ segLabels: segmentsToExport ? segmentsToExport.map((seg) => sanitizeName(seg.name ?? '')) : [],+ });- return { fileNames: [fileName], problems };+ return [maybeTruncatePath(fileName, safeOutputFileName2)];+ },+ desiredTemplate,+ defaultTemplate: defaultCutMergedFileTemplate,+ filePath,+ outputDir,+ maxLabelLength,+ safeOutputFileName,+ });}