Skip to content

The swiss army knife of lossless video/audio editing

Keep output file names unique when truncating long names

Claude41bc6040fa46
diff --git a/src/common/util.test.ts b/src/common/util.test.ts
index 17c206d9..0fd36841 100644
--- a/src/common/util.test.ts
+++ b/src/common/util.test.ts
@@ -1,7 +1,7 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { describe, expect, test } from 'vitest';
-import { getFixChannelLayoutFilter, hasCustomChannelLayout, truncateFileName } from './util.js';
+import { getFixChannelLayoutFilter, hasCustomChannelLayout, truncateFileName, truncateUtf8 } from './util.js';
describe('hasCustomChannelLayout', () => {
test('detects layouts that ffmpeg could not express natively', () => {
@@ -60,4 +60,16 @@ describe('truncateFileName', () => {
test('ignores a dot too early in the name to be an extension', () => {
expect(truncateFileName(`Dr. ${'a'.repeat(20)}`, 10)).toBe('Dr. aaaaaa');
});
+ test('counts UTF-8 bytes and does not split characters', () => {
+ expect(truncateFileName('日本語の動画.mp4', 13)).toBe('日本語.mp4'); // 3 bytes per character
+ expect(truncateFileName('😀😀😀.mkv', 13)).toBe('😀😀.mkv'); // 4 bytes per emoji
+ });
+});
+
+describe('truncateUtf8', () => {
+ test('truncates to whole characters', () => {
+ expect(truncateUtf8('abc', 5)).toBe('abc');
+ expect(truncateUtf8('😀😀', 5)).toBe('😀');
+ expect(truncateUtf8('åäö', 3)).toBe('å');
+ });
});
diff --git a/src/common/util.ts b/src/common/util.ts
index c20d0ba2..80f8f5a8 100644
--- a/src/common/util.ts
+++ b/src/common/util.ts
@@ -10,13 +10,37 @@ export const getHwaccelArgs = (hwaccel: FfmpegHwAccel) => (hwaccel !== 'none' ?
// I don't remember why 5 was chosen initially, but if we don't truncate, ffmpeg can sometimes give an error when too many decimal places are used in the time argument, see:
export const formatFfmpegNumber = (time: number) => time.toFixed(6);
-// Truncate a file name to `maxLength`, but keep its extension (if any)
-export function truncateFileName(name: string, maxLength: number) {
- if (name.length <= maxLength) return name;
+function getCharUtf8Length(char: string) {
+ const codePoint = char.codePointAt(0)!;
+ if (codePoint < 0x80) return 1;
+ if (codePoint < 0x800) return 2;
+ if (codePoint < 0x10000) return 3;
+ return 4;
+}
+
+// file systems limit file name length in bytes (e.g. ext4) or UTF-16 code units (NTFS); UTF-8 bytes is never less than either
+export const getUtf8Length = (str: string) => [...str].reduce((acc, char) => acc + getCharUtf8Length(char), 0);
+
+// Truncate to at most `maxBytes` UTF-8 bytes, without splitting a character
+export function truncateUtf8(str: string, maxBytes: number) {
+ if (getUtf8Length(str) <= maxBytes) return str;
+ let ret = '';
+ let bytes = 0;
+ for (const char of str) {
+ bytes += getCharUtf8Length(char);
+ if (bytes > maxBytes) break;
+ ret += char;
+ }
+ return ret;
+}
+
+// Truncate a file name to `maxBytes` UTF-8 bytes, but keep its extension (if any)
+export function truncateFileName(name: string, maxBytes: number) {
+ if (getUtf8Length(name) <= maxBytes) return name;
const extIndex = name.lastIndexOf('.');
- // only treat a short suffix as an extension, so that a dot early in the name doesn't make us exceed maxLength
+ // only treat a short suffix as an extension, so that a dot early in the name doesn't make us exceed the limit
const ext = extIndex > 0 && name.length - extIndex <= 10 ? name.slice(extIndex) : '';
- return name.slice(0, maxLength - ext.length) + ext;
+ return truncateUtf8(name.slice(0, name.length - ext.length), maxBytes - getUtf8Length(ext)) + ext;
}
export function parseRatio(str: string, char = '/') {
diff --git a/src/renderer/src/util/outputNameTemplate.ts b/src/renderer/src/util/outputNameTemplate.ts
index 63027f93..e44192c5 100644
--- a/src/renderer/src/util/outputNameTemplate.ts
+++ b/src/renderer/src/util/outputNameTemplate.ts
@@ -13,7 +13,7 @@ import type { FileStats, FormatTimecode, SegmentToExport } from '../types';
import safeishEval from '../worker/eval';
import { UserFacingError } from '../../errors';
import type { FileFfprobeMeta } from '../ffmpeg';
-import { truncateFileName } from '../../../common/util';
+import { getUtf8Length, truncateFileName, truncateUtf8 } from '../../../common/util';
export const segNumVariable = 'SEG_NUM';
@@ -221,18 +221,26 @@ async function interpolateOutFileName(template: string, {
return ret;
}
-function maybeTruncatePath(fileName: string, truncate: boolean) {
+function truncatePath(fileName: string) {
// Split the path by its separator, so we can check the actual file name (last path seg)
const pathSegs = fileName.split(pathSep);
if (pathSegs.length === 0) return '';
const [lastSeg] = pathSegs.slice(-1);
const rest = pathSegs.slice(0, -1);
- return [
- ...rest,
- // If sanitation is enabled, make sure filename (last seg of the path) is not too long
- truncate ? truncateFileName(lastSeg!, maxFileNameLength) : lastSeg,
- ].join(pathSep);
+ return [...rest, truncateFileName(lastSeg!, maxFileNameLength)].join(pathSep);
+}
+
+// If sanitation is enabled, make sure the file name (last seg of the path) is not too long.
+// First try to shorten the source file name (FILENAME), so that the parts that make each output name unique (cut times, segment number etc.) are kept
+async function interpolateTruncatedOutFileName(template: string, params: Parameters<typeof interpolateOutFileName>[1], truncate: boolean) {
+ const fileName = await interpolateOutFileName(template, params);
+ if (!truncate) return fileName;
+ const overflow = getUtf8Length(basename(fileName)) - maxFileNameLength;
+ if (overflow <= 0) return fileName;
+ const { inputFileNameWithoutExt } = params;
+ const shortenedFileName = await interpolateOutFileName(template, { ...params, inputFileNameWithoutExt: truncateUtf8(inputFileNameWithoutExt, getUtf8Length(inputFileNameWithoutExt) - overflow) });
+ return truncatePath(shortenedFileName);
}
async function generateWithFallback({ generate, desiredTemplate, defaultTemplate, safeOutputFileName, filePath, outputDir, maxLabelLength }: {
@@ -316,7 +324,7 @@ export async function generateCutFileNames({ fileDuration, segmentsToExport: seg
const cutDuration = end - start;
- const segFileName = await interpolateOutFileName(template, {
+ return interpolateTruncatedOutFileName(template, {
epochMs,
segNum,
segNumPadded,
@@ -335,9 +343,7 @@ export async function generateCutFileNames({ fileDuration, segmentsToExport: seg
tags: Object.fromEntries(Object.entries(getSegmentTags(segment)).map(([tag, value]) => [tag, sanitizeName(value)])),
exportCount,
currentFileExportCount,
- });
-
- return maybeTruncatePath(segFileName, safeOutputFileName2);
+ }, safeOutputFileName2);
}, { concurrency: 5 });
},
desiredTemplate,
@@ -368,7 +374,7 @@ export async function generateCutMergedFileNames({ template: desiredTemplate, is
generate: async ({ template, safeOutputFileName: safeOutputFileName2, sanitizeName }) => {
const { name: inputFileNameWithoutExt } = parsePath(sourceFile.path);
- const fileName = await interpolateOutFileName(template, {
+ return [await interpolateTruncatedOutFileName(template, {
epochMs,
sourceFiles: [sourceFile],
inputFileNameWithoutExt,
@@ -376,9 +382,7 @@ export async function generateCutMergedFileNames({ template: desiredTemplate, is
exportCount,
currentFileExportCount,
segLabels: segLabels.map((label) => sanitizeName(label)),
- });
-
- return [maybeTruncatePath(fileName, safeOutputFileName2)];
+ }, safeOutputFileName2)];
},
desiredTemplate,
defaultTemplate: defaultCutMergedFileTemplate,
@@ -407,16 +411,14 @@ export async function generateMergedFileNames({ template: desiredTemplate, isCus
generate: async ({ template, safeOutputFileName: safeOutputFileName2, sanitizeName }) => {
const { name: inputFileNameWithoutExt } = parsePath(firstFile.path);
- const fileName = await interpolateOutFileName(template, {
+ return [await interpolateTruncatedOutFileName(template, {
epochMs,
sourceFiles,
inputFileNameWithoutExt,
ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath: firstFile.path }),
exportCount,
segLabels: sourceFiles.map((file) => sanitizeName(basename(file.path))),
- });
-
- return [maybeTruncatePath(fileName, safeOutputFileName2)];
+ }, safeOutputFileName2)];
},
desiredTemplate,
defaultTemplate: defaultCutMergedFileTemplate,