The swiss army knife of lossless video/audio editing
Introduce template variable `FILES`
Mikael Finstad260107c96e3d
diff --git a/.gitignore b/.gitignoreindex 986f8277..00ae7409 100644--- a/.gitignore+++ b/.gitignore@@ -14,7 +14,7 @@ node_modules/out/icon-build/build-resources-/doc+/notes/ffmpeg/app*.log/main-ts-distdiff --git a/expressions.md b/expressions.mdindex 72647812..472fef21 100644--- a/expressions.md+++ b/expressions.md@@ -1,6 +1,6 @@# Expressions-LosslessCut has support for normal JavaScript expressions.+LosslessCut has support for JavaScript expressions in certain dialogs. This is a base JavaScript environment with [core JavaScript functionality](https://developer.mozilla.org/en-US/docs/Web/JavaScript) available for you to use.## Select segments by expressiondiff --git a/src/common/constants.ts b/src/common/constants.tsnew file mode 100644index 00000000..761eb0b8--- /dev/null+++ b/src/common/constants.ts@@ -0,0 +1,14 @@+export const homepageUrl = 'https://mifi.no/losslesscut/';+export const githubUrl = 'https://github.com/mifi/lossless-cut/';+export const getReleaseUrl = (version: string) => `https://github.com/mifi/lossless-cut/releases/tag/v${version}`;+export const compareReleasesUrl = (fromVersion: string, toVersion: string) => `https://github.com/mifi/lossless-cut/compare/v${fromVersion}...v${toVersion}`;+export const licensesUrl = 'https://losslesscut.mifi.no/licenses.txt';+export const thanksUrl = 'https://mifi.no/thanks';+export const issuesUrl = 'https://github.com/mifi/lossless-cut/issues';+export const discussionsUrl = 'https://github.com/mifi/lossless-cut/discussions';+export const usageUrl = 'https://mifi.no/losslesscut/usage';+export const faqUrl = 'https://mifi.no/losslesscut/faq';+export const troubleshootingUrl = 'https://mifi.no/losslesscut/troubleshooting';+export const exportedFileNameTemplateHelpUrl = 'https://github.com/mifi/lossless-cut/blob/master/docs.md#custom-exported-file-names';+export const jsExpressionHelpUrl = 'https://github.com/mifi/lossless-cut/blob/master/expressions.md';+export const supportEmail = '[email protected]';diff --git a/src/common/userTypes.ts b/src/common/userTypes.tsnew file mode 100644index 00000000..cb574404--- /dev/null+++ b/src/common/userTypes.ts@@ -0,0 +1,49 @@+// ⚠️ These types are a the contract with the user, through the documentation.+// ‼️ DO NOT change these types without considering the user impact!+// See https://github.com/mifi/lossless-cut/blob/master/expressions.md+// https://github.com/mifi/lossless-cut/blob/master/docs.md#custom-exported-file-names++/**+ * Properties of a source file made available to the user in the export file name template.+ * All times are expressed in milliseconds since the POSIX Epoch.+ */+export interface SourceFile {+ /** The file's name without the file system path. */+ name: string,+ /** The full filesystem path of the file. */+ path: string,+ /** File size in bytes. */+ size?: number | bigint | undefined, // File size in bytes+ /** The last time this file was accessed. */+ atime?: number | undefined,+ /** The last time this file was modified. */+ mtime?: number | undefined,+ /** The last time the file status was changed. */+ ctime?: number | undefined,+ /** The creation time of this file. */+ birthtime?: number | undefined,+}++/**+ * The global context made available to the user in the export file name template.+ */+export interface FileNameTemplateContext {+ FILENAME: string;+ FILES: SourceFile[];+ SEG_SUFFIX?: string | undefined;+ EXT: string;+ SEG_NUM_INT?: number | undefined;+ SEG_NUM?: string | undefined;+ SELECTED_SEG_NUM_INT?: number | undefined;+ SELECTED_SEG_NUM?: string | undefined;+ SEG_LABEL?: string | string[] | undefined;+ EPOCH_MS: number;+ CUT_FROM?: string | undefined;+ CUT_FROM_NUM?: number | undefined;+ CUT_TO?: string | undefined;+ CUT_TO_NUM?: number | undefined;+ CUT_DURATION?: string | undefined;+ SEG_TAGS?: Record<string, string> | undefined;+ FILE_EXPORT_COUNT?: number | undefined;+ EXPORT_COUNT?: number | undefined;+}diff --git a/src/main/aboutPanel.ts b/src/main/aboutPanel.tsindex f81df3df..f6a3d872 100644--- a/src/main/aboutPanel.ts+++ b/src/main/aboutPanel.ts@@ -4,7 +4,7 @@ import { AboutPanelOptionsOptions, app } from 'electron';import { appName, copyrightYear } from './common.js';import { isLinux } from './util.js';import isStoreBuild from './isStoreBuild.js';-import { githubLink, homepage } from './constants.js';+import { githubUrl, homepageUrl } from '../common/constants.js';// eslint-disable-next-line import/prefer-default-export@@ -12,7 +12,7 @@ export function getAboutPanelOptions() {const appVersion = app.getVersion();const aboutPanelLines = [- isStoreBuild ? homepage : githubLink,+ isStoreBuild ? homepageUrl : githubUrl,'',`Copyright © 2016-${copyrightYear} Mikael Finstad ❤️ 🇳🇴`,];diff --git a/src/main/constants.ts b/src/main/constants.tsdeleted file mode 100644index 23c2c9f6..00000000--- a/src/main/constants.ts+++ /dev/null@@ -1,4 +0,0 @@-export const homepage = 'https://mifi.no/losslesscut/';-export const githubLink = 'https://github.com/mifi/lossless-cut/';-export const getReleaseUrl = (version: string) => `https://github.com/mifi/lossless-cut/releases/tag/v${version}`;-export const licensesPage = 'https://losslesscut.mifi.no/licenses.txt';diff --git a/src/main/httpServer.ts b/src/main/httpServer.tsindex 543ac5a0..6e550523 100644--- a/src/main/httpServer.ts+++ b/src/main/httpServer.ts@@ -4,7 +4,7 @@ import http from 'node:http';import asyncHandler from 'express-async-handler';import assert from 'node:assert';-import { homepage } from './constants.js';+import { homepageUrl } from '../common/constants.js';import logger from './logger.js';@@ -22,7 +22,7 @@ export default ({ port, onKeyboardAction }: {const apiRouter = express.Router();- app.get('/', (_req, res) => res.send(`See ${homepage}`));+ app.get('/', (_req, res) => res.send(`See ${homepageUrl}`));app.use('/api', apiRouter);diff --git a/src/main/menu.ts b/src/main/menu.tsindex f4341d33..2c1b0563 100644--- a/src/main/menu.ts+++ b/src/main/menu.ts@@ -2,7 +2,7 @@import electron, { BrowserWindow, MenuItem, MenuItemConstructorOptions } from 'electron';import { t } from 'i18next';-import { homepage, getReleaseUrl, licensesPage } from './constants.js';+import { homepageUrl, getReleaseUrl, licensesUrl, thanksUrl, issuesUrl, usageUrl, faqUrl, troubleshootingUrl } from '../common/constants.js';import { logFilePath } from './logger.js';import { getConfigPath } from './configStore.js';@@ -437,15 +437,15 @@ export default ({ app, mainWindow, newVersion, isStoreBuild }: {submenu: [{label: esc(t('How to use')),- click() { electron.shell.openExternal('https://mifi.no/losslesscut/usage'); },+ click() { electron.shell.openExternal(usageUrl); },},{label: esc(t('FAQ')),- click() { electron.shell.openExternal('https://mifi.no/losslesscut/faq'); },+ click() { electron.shell.openExternal(faqUrl); },},{label: esc(t('Troubleshooting')),- click() { electron.shell.openExternal('https://mifi.no/losslesscut/troubleshooting'); },+ click() { electron.shell.openExternal(troubleshootingUrl); },},{label: esc(t('Keyboard & mouse shortcuts')),@@ -455,7 +455,7 @@ export default ({ app, mainWindow, newVersion, isStoreBuild }: {},{label: esc(t('Learn More')),- click() { electron.shell.openExternal(homepage); },+ click() { electron.shell.openExternal(homepageUrl); },},{ type: 'separator' },{@@ -464,11 +464,11 @@ export default ({ app, mainWindow, newVersion, isStoreBuild }: {},{label: esc(t('Feature request')),- click() { electron.shell.openExternal('https://github.com/mifi/lossless-cut/issues'); },+ click() { electron.shell.openExternal(issuesUrl); },},...(!isStoreBuild ? [{label: esc(`${t('Donate')} ❤️`),- click() { electron.shell.openExternal('https://mifi.no/thanks'); },+ click() { electron.shell.openExternal(thanksUrl); },}] : []),{ type: 'separator' },{@@ -482,7 +482,7 @@ export default ({ app, mainWindow, newVersion, isStoreBuild }: {{ type: 'separator' },{label: esc(t('Licenses')),- click() { electron.shell.openExternal(licensesPage); },+ click() { electron.shell.openExternal(licensesUrl); },},...(process.platform !== 'darwin' ? [{ role: 'about' as const, label: esc(t('About LosslessCut')) }] : []),],diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex d0d3fe68..efcd50d3 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -51,14 +51,14 @@ import { darkModeTransition } from './colors';import { getSegColor } from './util/colors';import {getStreamFps, isCuttingStart, isCuttingEnd,- readFileMeta, getDefaultOutFormat,+ readFileFfprobeMeta, getDefaultOutFormat,setCustomFfPath as ffmpegSetCustomFfPath,isIphoneHevc, isProblematicAvc1, tryMapChaptersToEdl,getDuration, getTimecodeFromStreams, createChaptersFromSegments,RefuseOverwriteError, extractSubtitleTrackToSegments,mapRecommendedDefaultFormat,getFfCommandLine,- FileMeta,+ FileFfprobeMeta,} from './ffmpeg';import { shouldCopyStreamByDefault, getAudioStreams, getRealVideoStreams, isAudioDefinitelyNotSupported, willPlayerProperlyHandleVideo, doesPlayerSupportHevcPlayback, getSubtitleStreams, enableVideoTrack, enableAudioTrack, canHtml5PlayerPlayStreams, isMatroska } from './util/streams';import { exportEdlFile, readEdlFile, loadLlcProject, askForEdlImport } from './edlStore';@@ -74,6 +74,7 @@ import {isAbortedError,shootConfetti,isMasBuild,+ readFileStats,} from './util';import getSwal, { errorToast, showPlaybackFailedMessage } from './swal';import { adjustRate } from './util/rate-calculator';@@ -85,9 +86,9 @@ import { generateCutFileNames as generateCutFileNamesRaw, generateCutMergedFileNimport { rightBarWidth, leftBarWidth, ffmpegExtractWindow, zoomMax } from './util/constants';import BigWaveform from './components/BigWaveform';-import { BatchFile, Chapter, CustomTagsByFile, EdlExportType, EdlFileType, EdlImportType, FfmpegCommandLog, FilesMeta, goToTimecodeDirectArgsSchema, openFilesActionArgsSchema, ParamsByStreamId, PlaybackMode, SegmentBase, SegmentColorIndex, SegmentTags, StateSegment, TunerType } from './types';+import { BatchFile, Chapter, CustomTagsByFile, EdlExportType, EdlFileType, EdlImportType, FfmpegCommandLog, FilesMeta, FileStats, goToTimecodeDirectArgsSchema, openFilesActionArgsSchema, ParamsByStreamId, PlaybackMode, SegmentBase, SegmentColorIndex, SegmentTags, StateSegment, TunerType } from './types';import { CaptureFormat, KeyboardAction, ApiActionRequest } from '../../common/types.js';-import { FFprobeChapter, FFprobeFormat, FFprobeStream } from '../../common/ffprobe.js';+import { FFprobeChapter, FFprobeStream } from '../../common/ffprobe.js';import useLoading from './hooks/useLoading';import useVideo from './hooks/useVideo';import useTimecode from './hooks/useTimecode';@@ -131,7 +132,7 @@ function App() {const [customTagsByFile, setCustomTagsByFile] = useState<CustomTagsByFile>({});const [paramsByStreamId, setParamsByStreamId] = useState<ParamsByStreamId>(new Map());const [detectedFps, setDetectedFps] = useState<number>();- const [mainFileMeta, setMainFileMeta] = useState<{ streams: FileMeta['streams'], formatData: FFprobeFormat, chapters: FFprobeChapter[] }>();+ const [mainFileMeta, setMainFileMeta] = useState<{ ffprobeMeta: FileFfprobeMeta, stats: FileStats }>();const [streamsSelectorShown, setStreamsSelectorShown] = useState(false);const [concatDialogOpen, setConcatDialogOpen] = useState(false);const [zoomUnrounded, setZoom] = useState(1);@@ -278,9 +279,9 @@ function App() {if (videoRef.current) videoRef.current.volume = playbackVolume;}, [playbackVolume, videoRef]);- const mainStreams = useMemo(() => mainFileMeta?.streams ?? [], [mainFileMeta?.streams]);- const mainFileFormatData = useMemo(() => mainFileMeta?.formatData, [mainFileMeta?.formatData]);- const mainFileChapters = useMemo(() => mainFileMeta?.chapters, [mainFileMeta?.chapters]);+ const mainStreams = useMemo(() => mainFileMeta?.ffprobeMeta.streams ?? [], [mainFileMeta?.ffprobeMeta.streams]);+ const mainFileFormat = useMemo(() => mainFileMeta?.ffprobeMeta.format, [mainFileMeta?.ffprobeMeta.format]);+ const mainFileChapters = useMemo(() => mainFileMeta?.ffprobeMeta.chapters, [mainFileMeta?.ffprobeMeta.chapters]);const subtitleStreams = useMemo(() => getSubtitleStreams(mainStreams), [mainStreams]);const videoStreams = useMemo(() => getRealVideoStreams(mainStreams), [mainStreams]);@@ -326,7 +327,7 @@ function App() {const {cutSegments, cutSegmentsHistory, createSegmentsFromKeyframes, shuffleSegments, detectBlackScenes, detectSilentScenes, detectSceneChanges, removeSegment, invertAllSegments, fillSegmentsGaps, combineOverlappingSegments, combineSelectedSegments, shiftAllSegmentTimes, alignSegmentTimesToKeyframes, updateSegOrder, updateSegOrders, reorderSegsByStartTime, addSegment, setCutStart, setCutEnd, labelSegment, splitCurrentSegment, focusSegmentAtCursor, selectSegmentsAtCursor, createNumSegments, createFixedDurationSegments, createFixedByteSizedSegments, createRandomSegments, getSegEstimatedSize, haveInvalidSegs, currentSegIndexSafe, currentCutSeg, inverseCutSegments, clearSegments, clearSegColorCounter, loadCutSegments, setCutTime, setCurrentSegIndex, labelSelectedSegments, deselectAllSegments, selectAllSegments, selectOnlyCurrentSegment, toggleCurrentSegmentSelected, invertSelectedSegments, removeSelectedSegments, selectSegmentsByLabel, selectSegmentsByExpr, selectAllMarkers, mutateSegmentsByExpr, toggleSegmentSelected, selectOnlySegment, selectedSegments, segmentsOrInverse, segmentsToExport, duplicateCurrentSegment, duplicateSegment, updateSegAtIndex, findSegmentsAtCursor, maybeCreateFullLengthSegment, currentCutSegOrWholeTimeline, segColorCounter,- } = useSegments({ filePath, workingRef, setWorking, setProgress, videoStream: activeVideoStream, fileDuration, getRelevantTime, maxLabelLength, checkFileOpened, invertCutSegments, segmentsToChaptersOnly, timecodePlaceholder, parseTimecode, appendFfmpegCommandLog, fileDurationNonZero, mainFileMeta, seekAbs, activeVideoStreamIndex, activeAudioStreamIndexes, handleError, showGenericDialog });+ } = useSegments({ filePath, workingRef, setWorking, setProgress, videoStream: activeVideoStream, fileDuration, getRelevantTime, maxLabelLength, checkFileOpened, invertCutSegments, segmentsToChaptersOnly, timecodePlaceholder, parseTimecode, appendFfmpegCommandLog, fileDurationNonZero, mainFileMeta: mainFileMeta?.ffprobeMeta, seekAbs, activeVideoStreamIndex, activeAudioStreamIndexes, handleError, showGenericDialog });const { getEdlFilePath, projectFileSavePath, getProjectFileSavePath } = useSegmentsAutoSave({ autoSaveProjectFile, storeProjectInWorkingDir, filePath, customOutDir, cutSegments });@@ -513,7 +514,7 @@ function App() {const allFilesMeta = useMemo(() => ({...externalFilesMeta,- ...(filePath && mainFileMeta != null ? { [filePath]: mainFileMeta } : {}),+ ...(filePath && mainFileMeta != null ? { [filePath]: mainFileMeta.ffprobeMeta } : {}),}), [externalFilesMeta, filePath, mainFileMeta]);// total number of streams for ALL files@@ -821,14 +822,14 @@ function App() {mainStreams,copyStreamIdsByFile,cutSegments: cutSegments.map((s) => ({ start: s.start, end: s.end })),- mainFileFormatData,+ mainFileFormat,rotation,shortestFlag,effectiveExportMode,};openSendReportDialog({ err, state });- }, [commonSettings, copyStreamIdsByFile, cutSegments, effectiveExportMode, externalFilesMeta, fileFormat, filePath, mainFileFormatData, mainStreams, rotation, shortestFlag]);+ }, [commonSettings, copyStreamIdsByFile, cutSegments, effectiveExportMode, externalFilesMeta, fileFormat, filePath, mainFileFormat, mainStreams, rotation, shortestFlag]);const openSendConcatReportDialogWithState = useCallback(async (err: unknown, reportState?: object) => {const state = { ...commonSettings, ...reportState };@@ -847,16 +848,16 @@ function App() {const generateCutFileNames = useCallback(async (template: string) => {invariant(fileFormat != null && outputDir != null && filePath != null);- return generateCutFileNamesRaw({ fileDuration, exportCount, currentFileExportCount, segmentsToExport, template, formatTimecode, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding });- }, [currentFileExportCount, exportCount, fileDuration, fileFormat, filePath, formatTimecode, isCustomFormatSelected, maxLabelLength, outputDir, outputFileNameMinZeroPadding, safeOutputFileName, segmentsToExport]);+ return generateCutFileNamesRaw({ fileDuration, exportCount, currentFileExportCount, segmentsToExport, template, formatTimecode, isCustomFormatSelected, fileFormat, sourceFile: { path: filePath, ...mainFileMeta }, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding });+ }, [currentFileExportCount, exportCount, fileDuration, fileFormat, filePath, formatTimecode, isCustomFormatSelected, mainFileMeta, maxLabelLength, outputDir, outputFileNameMinZeroPadding, safeOutputFileName, segmentsToExport]);const generateCutMergedFileNames = useCallback(async (template: string) => {invariant(fileFormat != null && outputDir != null && filePath != null);- return generateCutMergedFileNamesRaw({ template, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, exportCount, currentFileExportCount, segLabels: segmentsToExport.map((seg) => seg.name ?? '') });+ return generateCutMergedFileNamesRaw({ template, isCustomFormatSelected, fileFormat, sourceFile: { path: filePath }, outputDir, safeOutputFileName, maxLabelLength, exportCount, currentFileExportCount, segLabels: segmentsToExport.map((seg) => seg.name ?? '') });}, [currentFileExportCount, exportCount, fileFormat, filePath, isCustomFormatSelected, maxLabelLength, outputDir, safeOutputFileName, segmentsToExport]);const generateMergedFileNames = useCallback(async (params: GenerateMergedOutFileNamesParams) => (- generateMergedFileNamesRaw({ template: params.template, isCustomFormatSelected, fileFormat: params.fileFormat, filePaths: params.filePaths, outputDir: params.outputDir, safeOutputFileName, maxLabelLength, exportCount, epochMs: params.epochMs })+ generateMergedFileNamesRaw({ ...params, isCustomFormatSelected, safeOutputFileName, maxLabelLength, exportCount })), [exportCount, isCustomFormatSelected, maxLabelLength, safeOutputFileName]);const userConcatFiles = useCallback(async ({ paths, includeAllStreams, streams, fileFormat: outFormat, clearBatchFilesAfterConcat, generatedFileNames }: {@@ -1132,9 +1133,9 @@ function App() {if (!exportConfirmEnabled) notices.add(i18n.t('Export options are not shown. You can enable export options by clicking the icon right next to the export button.'));- invariant(mainFileFormatData != null);+ invariant(mainFileFormat != null);// https://github.com/mifi/lossless-cut/issues/329- if (isIphoneHevc(mainFileFormatData, mainStreams)) warnings.add(i18n.t('There is a known issue with cutting iPhone HEVC videos. The output file may not work in all players.'));+ if (isIphoneHevc(mainFileFormat, mainStreams)) warnings.add(i18n.t('There is a known issue with cutting iPhone HEVC videos. The output file may not work in all players.'));// https://github.com/mifi/lossless-cut/issues/280if (!ffmpegExperimental && isProblematicAvc1(fileFormat, mainStreams)) warnings.add(i18n.t('There is a known problem with this file type, and the output might not be playable. You can work around this problem by enabling the "Experimental flag" under Settings.'));@@ -1199,7 +1200,7 @@ function App() {setWorking(undefined);setProgress(undefined);}- }, [filePath, numStreamsToCopy, haveInvalidSegs, workingRef, setWorking, segmentsToChaptersOnly, cutFileTemplateOrDefault, generateCutFileNames, cutMultiple, outputDir, customOutDir, fileFormat, fileDuration, isRotationSet, effectiveRotation, copyFileStreams, allFilesMeta, keyframeCut, segmentsToExport, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMetadataOnMerge, preserveMovData, preserveChapters, movFastStart, avoidNegativeTs, customTagsByFile, paramsByStreamId, detectedFps, willMerge, enableOverwriteOutput, exportConfirmEnabled, mainFileFormatData, mainStreams, exportExtraStreams, areWeCutting, simpleMode, prefersReducedMotion, cleanupChoices, hideAllNotifications, segmentsOrInverse.selected, t, cutMergedFileTemplateOrDefault, segmentsToChapters, invertCutSegments, generateCutMergedFileNames, concatCutSegments, autoDeleteMergedSegments, tryDeleteFiles, nonCopiedExtraStreams, extractStreams, askForCleanupChoices, cleanupFiles, showOsNotification, openCutFinishedDialog, handleExportFailed]);+ }, [filePath, numStreamsToCopy, haveInvalidSegs, workingRef, setWorking, segmentsToChaptersOnly, cutFileTemplateOrDefault, generateCutFileNames, cutMultiple, outputDir, customOutDir, fileFormat, fileDuration, isRotationSet, effectiveRotation, copyFileStreams, allFilesMeta, keyframeCut, segmentsToExport, shortestFlag, ffmpegExperimental, preserveMetadata, preserveMetadataOnMerge, preserveMovData, preserveChapters, movFastStart, avoidNegativeTs, customTagsByFile, paramsByStreamId, detectedFps, willMerge, enableOverwriteOutput, exportConfirmEnabled, mainFileFormat, mainStreams, exportExtraStreams, areWeCutting, simpleMode, prefersReducedMotion, cleanupChoices, hideAllNotifications, segmentsOrInverse.selected, t, cutMergedFileTemplateOrDefault, segmentsToChapters, invertCutSegments, generateCutMergedFileNames, concatCutSegments, autoDeleteMergedSegments, tryDeleteFiles, nonCopiedExtraStreams, extractStreams, askForCleanupChoices, cleanupFiles, showOsNotification, openCutFinishedDialog, handleExportFailed]);const onExportPress = useCallback(async () => {if (!filePath) return;@@ -1388,22 +1389,23 @@ function App() {return;}- const fileMeta = await readFileMeta(fp);+ const ffprobeMeta = await readFileFfprobeMeta(fp);+ const fileStats = await readFileStats(fp);// console.log('file meta read', fileMeta);- const fileFormatNew = await getDefaultOutFormat({ filePath: fp, fileMeta });+ const fileFormatNew = await getDefaultOutFormat({ filePath: fp, fileMeta: ffprobeMeta });if (!fileFormatNew) throw new Error('Unable to determine file format');- const timecode = autoLoadTimecode ? getTimecodeFromStreams(fileMeta.streams) : undefined;+ const timecode = autoLoadTimecode ? getTimecodeFromStreams(ffprobeMeta.streams) : undefined;- const [firstVideoStream] = getRealVideoStreams(fileMeta.streams);- const [firstAudioStream] = getAudioStreams(fileMeta.streams);+ const [firstVideoStream] = getRealVideoStreams(ffprobeMeta.streams);+ const [firstAudioStream] = getAudioStreams(ffprobeMeta.streams);- const copyStreamIdsForPathNew = fromPairs(fileMeta.streams.map((stream) => [+ const copyStreamIdsForPathNew = fromPairs(ffprobeMeta.streams.map((stream) => [stream.index, shouldCopyStreamByDefault(stream),]));- const validDuration = isDurationValid(parseFloat(fileMeta.format.duration));+ const validDuration = isDurationValid(parseFloat(ffprobeMeta.format.duration));const hevcPlaybackSupported = enableNativeHevc && await hevcPlaybackSupportedPromise;@@ -1415,7 +1417,7 @@ function App() {const existingHtml5FriendlyFile = await findExistingHtml5FriendlyFile(fp, cod);- const needsAutoHtml5ify = !existingHtml5FriendlyFile && !willPlayerProperlyHandleVideo({ streams: fileMeta.streams, hevcPlaybackSupported, isMasBuild }) && validDuration;+ const needsAutoHtml5ify = !existingHtml5FriendlyFile && !willPlayerProperlyHandleVideo({ streams: ffprobeMeta.streams, hevcPlaybackSupported, isMasBuild }) && validDuration;console.log('loadMedia', { filePath: fp, customOutDir: cod, projectPath });@@ -1440,7 +1442,7 @@ function App() {if (projectPath) {await loadEdlFile({ path: projectPath, type: 'llc' });} else {- await tryFindAndLoadProjectFile({ chapters: fileMeta.chapters, cod });+ await tryFindAndLoadProjectFile({ chapters: ffprobeMeta.chapters, cod });}// throw new Error('test');@@ -1454,13 +1456,13 @@ function App() {if (timecode) setStartTimeOffset(timecode);setDetectedFps(getFps());- setMainFileMeta({ streams: fileMeta.streams, formatData: fileMeta.format, chapters: fileMeta.chapters });+ setMainFileMeta({ ffprobeMeta, stats: { size: fileStats.size, atime: fileStats.atimeMs, mtime: fileStats.mtimeMs, ctime: fileStats.ctimeMs, birthtime: fileStats.birthtimeMs } });setCopyStreamIdsForPath(fp, () => copyStreamIdsForPathNew);setDetectedFileFormat(fileFormatNew);if (outFormatLocked) {setFileFormat(outFormatLocked);} else {- const recommendedDefaultFormat = mapRecommendedDefaultFormat({ sourceFormat: fileFormatNew, streams: fileMeta.streams });+ const recommendedDefaultFormat = mapRecommendedDefaultFormat({ sourceFormat: fileFormatNew, streams: ffprobeMeta.streams });if (recommendedDefaultFormat.message) showNotification({ icon: 'info', text: recommendedDefaultFormat.message });setFileFormat(recommendedDefaultFormat.format);}@@ -1470,7 +1472,7 @@ function App() {showPreviewFileLoadedMessage(basename(existingHtml5FriendlyFile.path));} else if (needsAutoHtml5ify) {showUnsupportedFileMessage();- } else if (isAudioDefinitelyNotSupported(fileMeta.streams)) {+ } else if (isAudioDefinitelyNotSupported(ffprobeMeta.streams)) {showNotification({ icon: 'info', text: i18n.t('The audio track is not supported while previewing. You can convert to a supported format from the menu') });} else if (!validDuration) {getSwal().toast.fire({ icon: 'warning', timer: 10000, text: i18n.t('This file does not have a valid duration. This may cause issues. You can try to fix the file\'s duration from the File menu') });@@ -1677,9 +1679,9 @@ function App() {const addStreamSourceFile = useCallback(async (path: string) => {if (allFilesMeta[path]) return undefined; // Already added?- const fileMeta = await readFileMeta(path);+ const fileMeta = await readFileFfprobeMeta(path);// console.log('streams', fileMeta.streams);- setExternalFilesMeta((old) => ({ ...old, [path]: { streams: fileMeta.streams, formatData: fileMeta.format, chapters: fileMeta.chapters } }));+ setExternalFilesMeta((old) => ({ ...old, [path]: fileMeta }));setCopyStreamIdsForPath(path, () => fromPairs(fileMeta.streams.map(({ index }) => [index, true])));return fileMeta;}, [allFilesMeta, setCopyStreamIdsForPath]);@@ -2662,7 +2664,7 @@ function App() {{mainStreams && filePath != null && (<StreamsSelectormainFilePath={filePath}- mainFileFormatData={mainFileFormatData}+ mainFileFormat={mainFileFormat}mainFileChapters={mainFileChapters}allFilesMeta={allFilesMeta}externalFilesMeta={externalFilesMeta}diff --git a/src/renderer/src/StreamsSelector.tsx b/src/renderer/src/StreamsSelector.tsxindex fe3e80d2..56e1992d 100644--- a/src/renderer/src/StreamsSelector.tsx+++ b/src/renderer/src/StreamsSelector.tsx@@ -45,8 +45,8 @@ const EditFileDialog = memo(({ editingFile, allFilesMeta, customTagsByFile, setC}) => {const { t } = useTranslation();- const { formatData } = allFilesMeta[editingFile]!;- const existingTags = formatData.tags || {};+ const { format } = allFilesMeta[editingFile]!;+ const existingTags = format.tags || {};const customTags = customTagsByFile[editingFile] || {};const onTagsChange = useCallback((keyValues: Record<string, string>) => {@@ -361,9 +361,9 @@ const Stream = memo(({ filePath, stream, onToggle, toggleCopyStreamIds, copyStre);});-function FileHeading({ path, formatData, chapters, onTrashClick, onEditClick, toggleCopyAllStreams, onExtractAllStreamsPress, changeEnabledStreamsFilter }: {+function FileHeading({ path, format, chapters, onTrashClick, onEditClick, toggleCopyAllStreams, onExtractAllStreamsPress, changeEnabledStreamsFilter }: {path: string,- formatData: FFprobeFormat | undefined,+ format: FFprobeFormat | undefined,chapters?: FFprobeChapter[] | undefined,onTrashClick?: (() => void) | undefined,onEditClick?: (() => void) | undefined,@@ -385,7 +385,7 @@ function FileHeading({ path, formatData, chapters, onTrashClick, onEditClick, to<Button title={t('Chapters')}><FaBook style={{ verticalAlign: 'middle' }} /></Button></Json5Dialog>)}- <Json5Dialog title={t('File info')} json={formatData}>+ <Json5Dialog title={t('File info')} json={format}><Button title={t('File info')}><FaInfoCircle style={{ verticalAlign: 'middle' }} /></Button></Json5Dialog>{onEditClick && <Button title={t('Edit file metadata')} onClick={onEditClick}><FaEdit style={{ verticalAlign: 'middle' }} /></Button>}@@ -422,10 +422,10 @@ const fileStyle: CSSProperties = { marginBottom: '2em', padding: '.5em 0', overffunction StreamsSelector({- mainFilePath, mainFileFormatData, mainFileStreams, mainFileChapters, isCopyingStreamId, toggleCopyStreamId, setCopyStreamIdsForPath, onExtractStreamPress, onExtractAllStreamsPress, allFilesMeta, externalFilesMeta, setExternalFilesMeta, showAddStreamSourceDialog, shortestFlag, setShortestFlag, nonCopiedExtraStreams, customTagsByFile, setCustomTagsByFile, paramsByStreamId, updateStreamParams, formatTimecode, loadSubtitleTrackToSegments, toggleCopyStreamIds, changeEnabledStreamsFilter, toggleCopyAllStreamsForPath, onStreamSourceFileDrop,+ mainFilePath, mainFileFormat, mainFileStreams, mainFileChapters, isCopyingStreamId, toggleCopyStreamId, setCopyStreamIdsForPath, onExtractStreamPress, onExtractAllStreamsPress, allFilesMeta, externalFilesMeta, setExternalFilesMeta, showAddStreamSourceDialog, shortestFlag, setShortestFlag, nonCopiedExtraStreams, customTagsByFile, setCustomTagsByFile, paramsByStreamId, updateStreamParams, formatTimecode, loadSubtitleTrackToSegments, toggleCopyStreamIds, changeEnabledStreamsFilter, toggleCopyAllStreamsForPath, onStreamSourceFileDrop,}: {mainFilePath: string,- mainFileFormatData: FFprobeFormat | undefined,+ mainFileFormat: FFprobeFormat | undefined,mainFileStreams: FileStream[],mainFileChapters: FFprobeChapter[] | undefined,isCopyingStreamId: (path: string | undefined, streamId: number) => boolean,@@ -456,9 +456,9 @@ function StreamsSelector({const [editingTag, setEditingTag] = useState<string>();const { t } = useTranslation();- function getFormatDuration(formatData: FFprobeFormat | undefined) {- if (!formatData || !formatData.duration) return undefined;- const parsed = parseFloat(formatData.duration);+ function getFormatDuration(format: FFprobeFormat | undefined) {+ if (!format || !format.duration) return undefined;+ const parsed = parseFloat(format.duration);if (Number.isNaN(parsed)) return undefined;return parsed;}@@ -478,7 +478,7 @@ function StreamsSelector({<><div style={fileStyle} onDrop={onStreamSourceFileDrop}>{/* We only support editing main file metadata for now */}- <FileHeading path={mainFilePath} formatData={mainFileFormatData} chapters={mainFileChapters} onEditClick={() => setEditingFile(mainFilePath)} toggleCopyAllStreams={() => toggleCopyAllStreamsForPath(mainFilePath)} onExtractAllStreamsPress={onExtractAllStreamsPress} changeEnabledStreamsFilter={changeEnabledStreamsFilter} />+ <FileHeading path={mainFilePath} format={mainFileFormat} chapters={mainFileChapters} onEditClick={() => setEditingFile(mainFilePath)} toggleCopyAllStreams={() => toggleCopyAllStreamsForPath(mainFilePath)} onExtractAllStreamsPress={onExtractAllStreamsPress} changeEnabledStreamsFilter={changeEnabledStreamsFilter} /><table className={styles['table']}><Thead />@@ -492,7 +492,7 @@ function StreamsSelector({onToggle={(streamId) => toggleCopyStreamId(mainFilePath, streamId)}toggleCopyStreamIds={(filter: (a: FFprobeStream) => boolean) => toggleCopyStreamIds(mainFilePath, filter)}setEditingStream={setEditingStream}- fileDuration={getFormatDuration(mainFileFormatData)}+ fileDuration={getFormatDuration(mainFileFormat)}onExtractStreamPress={() => onExtractStreamPress(stream.index)}paramsByStreamId={paramsByStreamId}updateStreamParams={updateStreamParams}@@ -504,9 +504,9 @@ function StreamsSelector({</table></div>- {externalFilesEntries.map(([path, { streams: externalFileStreams, formatData }]) => (+ {externalFilesEntries.map(([path, { streams: externalFileStreams, format }]) => (<div key={path} style={fileStyle}>- <FileHeading path={path} formatData={formatData} onTrashClick={() => removeFile(path)} toggleCopyAllStreams={() => toggleCopyAllStreamsForPath(path)} />+ <FileHeading path={path} format={format} onTrashClick={() => removeFile(path)} toggleCopyAllStreams={() => toggleCopyAllStreamsForPath(path)} /><table className={styles['table']}><Thead />@@ -520,7 +520,7 @@ function StreamsSelector({onToggle={(streamId) => toggleCopyStreamId(path, streamId)}toggleCopyStreamIds={(filter: (a: FFprobeStream) => boolean) => toggleCopyStreamIds(path, filter)}setEditingStream={setEditingStream}- fileDuration={getFormatDuration(formatData)}+ fileDuration={getFormatDuration(format)}paramsByStreamId={paramsByStreamId}updateStreamParams={updateStreamParams}formatTimecode={formatTimecode}diff --git a/src/renderer/src/components/ConcatDialog.tsx b/src/renderer/src/components/ConcatDialog.tsxindex cc790a7c..38663ea7 100644--- a/src/renderer/src/components/ConcatDialog.tsx+++ b/src/renderer/src/components/ConcatDialog.tsx@@ -4,20 +4,22 @@ import { AiOutlineMergeCells } from 'react-icons/ai';import { FaQuestionCircle, FaExclamationTriangle, FaCog, FaCheck, FaNotEqual } from 'react-icons/fa';import i18n from 'i18next';import invariant from 'tiny-invariant';+import pMap from 'p-map';import Checkbox from './Checkbox';-import { readFileMeta, getDefaultOutFormat, mapRecommendedDefaultFormat } from '../ffmpeg';+import { readFileFfprobeMeta, getDefaultOutFormat, mapRecommendedDefaultFormat, FileFfprobeMeta } from '../ffmpeg';import OutputFormatSelect from './OutputFormatSelect';import useUserSettings from '../hooks/useUserSettings';import { isMov } from '../util/streams';-import { getOutDir } from '../util';-import { FFprobeChapter, FFprobeFormat, FFprobeStream } from '../../../common/ffprobe';+import { getOutDir, readFileStats } from '../util';+import { FFprobeStream } from '../../../common/ffprobe';import Button, { DialogButton } from './Button';import { defaultMergedFileTemplate, GeneratedOutFileNames, GenerateMergedOutFileNames } from '../util/outputNameTemplate';import { dangerColor, saveColor, warningColor } from '../colors';import * as Dialog from './Dialog';import FileNameTemplateEditor from './FileNameTemplateEditor';import HighlightedText from './HighlightedText';+import { FileStats } from '../types';const { basename } = window.require('path');@@ -54,55 +56,32 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate, generateMergconst { preserveMovData, setPreserveMovData, segmentsToChapters, setSegmentsToChapters, preserveMetadataOnMerge, setPreserveMetadataOnMerge, customOutDir, simpleMode, setMergedFileTemplate, outFormatLocked, changeOutDir } = useUserSettings();const [includeAllStreams, setIncludeAllStreams] = useState(false);- const [fileMeta, setFileMeta] = useState<{ format: FFprobeFormat, streams: FFprobeStream[], chapters: FFprobeChapter[] }>();- const [allFilesMetaCache, setAllFilesMetaCache] = useState<Record<string, {format: FFprobeFormat, streams: FFprobeStream[], chapters: FFprobeChapter[] }>>({});+ const [allFilesMeta, setAllFilesMeta] = useState<Record<string, { ffprobeMeta: FileFfprobeMeta, stats: FileStats }>>({});const [clearBatchFilesAfterConcat, setClearBatchFilesAfterConcat] = useState(false);const [enableReadFileMeta, setEnableReadFileMeta] = useState(false);const [uniqueSuffix, setUniqueSuffix] = useState(Date.now());- const firstPath = useMemo(() => {- if (paths.length === 0) return undefined;- return paths[0];- }, [paths]);+ const firstPath = useMemo(() => paths[0], [paths]);const outputDir = getOutDir(customOutDir, firstPath);const generateFileNames = useCallback(async (template: string) => {- invariant(firstPath != null && fileFormat != null && outputDir != null);+ invariant(fileFormat != null && outputDir != null);++ const sourceFiles = paths.map((path) => ({+ path,+ ...allFilesMeta[path],+ }));- return generateMergedFileNames({ template, filePaths: paths, fileFormat, outputDir, epochMs: uniqueSuffix });- }, [fileFormat, firstPath, generateMergedFileNames, outputDir, paths, uniqueSuffix]);+ return generateMergedFileNames({ template, sourceFiles, fileFormat, outputDir, epochMs: uniqueSuffix });+ }, [allFilesMeta, fileFormat, generateMergedFileNames, outputDir, paths, uniqueSuffix]);useEffect(() => {if (!isShown) {- setFileMeta(undefined);+ setAllFilesMeta({});}}, [isShown, setDetectedFileFormat, setFileFormat]);- useEffect(() => {- if (!isShown) return undefined;-- const abortController = new AbortController();-- (async () => {- invariant(firstPath != null);- const fileMetaNew = await readFileMeta(firstPath);- const fileFormatNew = await getDefaultOutFormat({ filePath: firstPath, fileMeta: fileMetaNew });- if (abortController.signal.aborted) return;-- setFileMeta(fileMetaNew);- setDetectedFileFormat(fileFormatNew);- if (outFormatLocked) {- setFileFormat(outFormatLocked);- } else {- setFileFormat(mapRecommendedDefaultFormat({ sourceFormat: fileFormatNew, streams: fileMetaNew.streams }).format);- }- setUniqueSuffix(Date.now());- })().catch(console.error);-- return () => abortController.abort();- }, [firstPath, isShown, outFormatLocked, setDetectedFileFormat, setFileFormat, setMergedFileTemplate, simpleMode]);-useEffect(() => {const abortController = new AbortController();@@ -118,16 +97,16 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate, generateMergreturn () => abortController.abort();}, [fileFormat, firstPath, generateFileNames, isShown, setMergedFileTemplate, simpleMode]);- const allFilesMeta = useMemo(() => {+ const matchingFilesMeta = useMemo(() => {if (paths.length === 0) return undefined;- const filtered = paths.flatMap((path) => (allFilesMetaCache[path] ? [[path, allFilesMetaCache[path]!] as const] : []));+ const filtered = paths.flatMap((path) => (allFilesMeta[path] ? [[path, allFilesMeta[path]] as const] : []));return filtered.length === paths.length ? filtered : undefined;- }, [allFilesMetaCache, paths]);+ }, [allFilesMeta, paths]);const problemsByFile = useMemo(() => {- if (!allFilesMeta) return {};- const allFilesMetaExceptFirstFile = allFilesMeta.slice(1);- const [, firstFileMeta] = allFilesMeta[0]!;+ if (!matchingFilesMeta) return {};+ const allFilesMetaExceptFirstFile = matchingFilesMeta.slice(1);+ const [, firstFileMeta] = matchingFilesMeta[0]!;const problems: Record<string, Problem[]> = {};function addProblem(path: string, error: Problem) {@@ -135,9 +114,9 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate, generateMergproblems[path]!.push(error);}- allFilesMetaExceptFirstFile.forEach(([path, { streams }]) => {+ allFilesMetaExceptFirstFile.forEach(([path, { ffprobeMeta: { streams } }]) => {streams.forEach((stream, i) => {- const referenceStream = firstFileMeta.streams[i];+ const referenceStream = firstFileMeta.ffprobeMeta.streams[i];if (!referenceStream) {addProblem(path, { type: 'extraneous', index: stream.index });return;@@ -153,41 +132,75 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate, generateMerg});});return problems;- }, [allFilesMeta]);+ }, [matchingFilesMeta]);useEffect(() => {- if (!isShown || !enableReadFileMeta) return undefined;+ if (!isShown) return undefined;const abortController = new AbortController();+ invariant(firstPath != null);+(async () => {- // eslint-disable-next-line no-restricted-syntax- for (const path of paths) {- if (abortController.signal.aborted) return;- if (!allFilesMetaCache[path]) {- // eslint-disable-next-line no-await-in-loop- const fileMetaNew = await readFileMeta(path);- setAllFilesMetaCache((existing) => ({ ...existing, [path]: fileMetaNew }));- }+ const pathsToFetchMetaFrom = enableReadFileMeta ? paths : [firstPath];++ const newMetaEntries = await pMap(pathsToFetchMetaFrom, async (path) => {+ abortController.signal.throwIfAborted();+ const stats = await readFileStats(path);+ return [+ path,+ {+ ffprobeMeta: await readFileFfprobeMeta(path),+ stats: {+ size: stats.size,+ atime: stats.atimeMs,+ mtime: stats.mtimeMs,+ ctime: stats.ctimeMs,+ birthtime: stats.birthtimeMs,+ },+ },+ ] as const;+ }, { concurrency: 1 });++ const firstFileMeta = newMetaEntries[0]?.[1];+ invariant(firstFileMeta);+ const fileFormatNew = await getDefaultOutFormat({ filePath: firstPath, fileMeta: firstFileMeta.ffprobeMeta });++ abortController.signal.throwIfAborted();++ // state mutations:++ setDetectedFileFormat(fileFormatNew);+ if (outFormatLocked) {+ setFileFormat(outFormatLocked);+ } else {+ setFileFormat(mapRecommendedDefaultFormat({ sourceFormat: fileFormatNew, streams: firstFileMeta.ffprobeMeta.streams }).format);}- })().catch(console.error);+ setAllFilesMeta((existing) => ({ ...existing, ...Object.fromEntries(newMetaEntries) }));+ setUniqueSuffix(Date.now());+ })().catch((err) => {+ if (err instanceof Error && err.name === 'AbortError') return;+ console.error(err);+ });return () => abortController.abort();- }, [allFilesMetaCache, enableReadFileMeta, isShown, paths]);+ }, [enableReadFileMeta, firstPath, isShown, outFormatLocked, paths, setDetectedFileFormat, setFileFormat]);const onConcatClick = useCallback(async () => {- invariant(fileFormat != null);invariant(firstPath != null);+ invariant(fileFormat != null);invariant(outputDir != null);+ const firstFileMeta = allFilesMeta[firstPath];+ invariant(firstFileMeta != null);- const generatedFileNames = await generateMergedFileNames({ template: mergedFileTemplate, filePaths: paths, fileFormat, outputDir, epochMs: uniqueSuffix });+ const generatedFileNames = await generateFileNames(mergedFileTemplate);- await onConcat({ paths, includeAllStreams, streams: fileMeta!.streams, fileFormat, clearBatchFilesAfterConcat, generatedFileNames });- }, [clearBatchFilesAfterConcat, fileFormat, fileMeta, firstPath, generateMergedFileNames, includeAllStreams, mergedFileTemplate, onConcat, outputDir, paths, uniqueSuffix]);+ await onConcat({ paths, includeAllStreams, streams: firstFileMeta.ffprobeMeta.streams, fileFormat, clearBatchFilesAfterConcat, generatedFileNames });+ }, [firstPath, fileFormat, outputDir, allFilesMeta, generateFileNames, mergedFileTemplate, onConcat, paths, includeAllStreams, clearBatchFilesAfterConcat]);const handleReadFileMetaCheckedChange = useCallback((checked: boolean) => {setEnableReadFileMeta(checked);- setAllFilesMetaCache({});+ setAllFilesMeta({});}, []);return (@@ -206,7 +219,7 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate, generateMerg<span>{basename(path)}</span>- {allFilesMetaCache[path] ? (+ {allFilesMeta[path] ? (problemsByFile[path] ? (<Dialog.Root><Dialog.Trigger asChild>@@ -264,7 +277,7 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate, generateMerg)}<div style={{ minHeight: '2.7em' }}>- {enableReadFileMeta && (!allFilesMeta || Object.values(problemsByFile).length > 0) && (+ {enableReadFileMeta && (!matchingFilesMeta || Object.values(problemsByFile).length > 0) && (<Alert text={t('A mismatch was detected in at least one file. You may proceed, but the resulting file might not be playable.')} />)}{!enableReadFileMeta && (diff --git a/src/renderer/src/components/FileNameTemplateEditor.tsx b/src/renderer/src/components/FileNameTemplateEditor.tsxindex 7570c701..731cde46 100644--- a/src/renderer/src/components/FileNameTemplateEditor.tsx+++ b/src/renderer/src/components/FileNameTemplateEditor.tsx@@ -15,6 +15,7 @@ import TextInput from './TextInput';import Button from './Button';import * as Dialog from './Dialog';import { dangerColor, warningColor } from '../colors';+import { exportedFileNameTemplateHelpUrl } from '../../../common/constants';const electron = window.require('electron');@@ -227,7 +228,7 @@ function FileNameTemplateEditor(opts: {<div style={{ fontSize: '.9em', color: 'var(--gray-11)', display: 'flex', gap: '.3em', flexWrap: 'wrap', alignItems: 'center', marginBottom: '.7em' }}>{`${i18n.t('Variables')}:`}- <IoIosHelpCircle fontSize="1.3em" color="var(--gray-12)" role="button" cursor="pointer" onClick={() => electron.shell.openExternal('https://github.com/mifi/lossless-cut/blob/master/docs.md#custom-exported-file-names')} />+ <IoIosHelpCircle fontSize="1.3em" color="var(--gray-12)" role="button" cursor="pointer" onClick={() => electron.shell.openExternal(exportedFileNameTemplateHelpUrl)} />{availableVariables.map((variable) => (<span key={variable} role="button" style={{ cursor: 'copy', marginRight: '.2em', textDecoration: 'underline', textDecorationStyle: 'dashed', fontSize: '.9em' }} onClick={() => onVariableClick(variable)}>{variable}</span>))}diff --git a/src/renderer/src/components/WhatsNew.tsx b/src/renderer/src/components/WhatsNew.tsxindex 635b64ee..1b4157df 100644--- a/src/renderer/src/components/WhatsNew.tsx+++ b/src/renderer/src/components/WhatsNew.tsx@@ -11,6 +11,7 @@ import versionsJson from '../versions.json';import Button from './Button';import styles from './WhatsNew.module.css';+import { compareReleasesUrl, getReleaseUrl } from '../../../common/constants';// see also generateVersions.mts@@ -53,8 +54,8 @@ export default function WhatsNew() {<div key={version} className={styles['version']}><div style={{ display: 'flex', flexWrap: 'wrap', gap: '1em' }}>{!(isMasBuild && matchingVersions.length === 1) && <h2>v{version}</h2>}- <Button onClick={() => shell.openExternal(`https://github.com/mifi/lossless-cut/releases/tag/v${version}`)}><FaFile style={{ verticalAlign: 'middle' }} /> {t('All release notes')}</Button>- <Button onClick={() => shell.openExternal(`https://github.com/mifi/lossless-cut/compare/v${prevVersion}...v${version}`)}><FaCode style={{ verticalAlign: 'middle' }} /> {t('All code changes')}</Button>+ <Button onClick={() => shell.openExternal(getReleaseUrl(version))}><FaFile style={{ verticalAlign: 'middle' }} /> {t('All release notes')}</Button>+ <Button onClick={() => shell.openExternal(compareReleasesUrl(prevVersion, version))}><FaCode style={{ verticalAlign: 'middle' }} /> {t('All code changes')}</Button></div>diff --git a/src/renderer/src/ffmpeg.ts b/src/renderer/src/ffmpeg.tsindex 8551ceb8..9c2b84f1 100644--- a/src/renderer/src/ffmpeg.ts+++ b/src/renderer/src/ffmpeg.ts@@ -344,7 +344,7 @@ export async function getDefaultOutFormat({ filePath, fileMeta: { format } }: {return mapInputToOutputFormat(assumedFormat);}-export async function readFileMeta(filePath: string) {+export async function readFileFfprobeMeta(filePath: string) {try {const { stdout } = await runFfprobe(['-of', 'json', '-show_chapters', '-show_format', '-show_entries', 'stream', '-i', filePath, '-hide_banner',@@ -378,8 +378,8 @@ export async function readFileMeta(filePath: string) {}}-export type FileMeta = Awaited<ReturnType<typeof readFileMeta>>;-export type FileStream = FileMeta['streams'][number];+export type FileFfprobeMeta = Awaited<ReturnType<typeof readFileFfprobeMeta>>;+export type FileStream = FileFfprobeMeta['streams'][number];async function renderThumbnail(filePath: string, timestamp: number, signal: AbortSignal) {const args = [diff --git a/src/renderer/src/hooks/useFfmpegOperations.ts b/src/renderer/src/hooks/useFfmpegOperations.tsindex 03dec41d..cc4e31ec 100644--- a/src/renderer/src/hooks/useFfmpegOperations.ts+++ b/src/renderer/src/hooks/useFfmpegOperations.ts@@ -6,7 +6,7 @@ import invariant from 'tiny-invariant';import i18n from 'i18next';import { getSuffixedOutPath, transferTimestamps, getOutFileExtension, getOutDir, deleteDispositionValue, getHtml5ifiedPath, unlinkWithRetry, getFrameDuration, isMac } from '../util';-import { isCuttingStart, isCuttingEnd, runFfmpegWithProgress, getFfCommandLine, getDuration, createChaptersFromSegments, readFileMeta, getExperimentalArgs, getVideoTimescaleArgs, logStdoutStderr, runFfmpegConcat, RefuseOverwriteError, runFfmpeg } from '../ffmpeg';+import { isCuttingStart, isCuttingEnd, runFfmpegWithProgress, getFfCommandLine, getDuration, createChaptersFromSegments, readFileFfprobeMeta, getExperimentalArgs, getVideoTimescaleArgs, logStdoutStderr, runFfmpegConcat, RefuseOverwriteError, runFfmpeg } from '../ffmpeg';import { getMapStreamsArgs, getStreamIdsToCopy } from '../util/streams';import { needsSmartCut, getCodecParams } from '../smartcut';import { getGuaranteedSegments, isDurationValid } from '../segments';@@ -649,7 +649,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treaawait cutEncodeSmartPartWrapper({ cutFrom: desiredCutFrom, cutTo: encodeCutToSafe, outPath: smartCutEncodedPartOutPath });// need to re-read streams because indexes may have changed. Using main file as source of streams and metadata- const { streams: streamsAfterCut } = await readFileMeta(losslessPartOutPath);+ const { streams: streamsAfterCut } = await readFileFfprobeMeta(losslessPartOutPath);await concatFiles({ paths: smartCutSegmentsToConcat, outDir: outputDir, outPath: finalOutPath, metadataFromPath: losslessPartOutPath, outFormat, includeAllStreams: true, streams: streamsAfterCut, ffmpegExperimental, preserveMovData, movFastStart, chapters, preserveMetadataOnMerge, videoTimebase, onProgress: onConcatProgress });return { path: finalOutPath, created: true };@@ -686,7 +686,7 @@ function useFfmpegOperations({ filePath, treatInputFileModifiedTimeAsStart, treaconst metadataFromPath = segmentPaths[0];invariant(metadataFromPath != null);// need to re-read streams because may have changed- const { streams } = await readFileMeta(metadataFromPath);+ const { streams } = await readFileFfprobeMeta(metadataFromPath);await concatFiles({ paths: segmentPaths, outDir, outPath: mergedOutFilePath, metadataFromPath, outFormat, includeAllStreams: true, streams, ffmpegExperimental, onProgress, preserveMovData, movFastStart, chapters, preserveMetadataOnMerge });}, [concatFiles, filePath, shouldSkipExistingFile]);diff --git a/src/renderer/src/hooks/useSegments.tsx b/src/renderer/src/hooks/useSegments.tsxindex 8f30af17..aaab4b77 100644--- a/src/renderer/src/hooks/useSegments.tsx+++ b/src/renderer/src/hooks/useSegments.tsx@@ -26,6 +26,7 @@ import Button, { DialogButton } from '../components/Button';import { ButtonRow } from '../components/Dialog';import * as Dialog from '../components/Dialog';import { UserFacingError } from '../../errors';+import { jsExpressionHelpUrl } from '../../../common/constants';const remote = window.require('@electron/remote');const { shell } = remote;@@ -52,7 +53,7 @@ function useSegments({ filePath, workingRef, setWorking, setProgress, videoStreaparseTimecode: ParseTimecode,appendFfmpegCommandLog: (args: string[]) => void,fileDurationNonZero: number,- mainFileMeta: { formatData: FFprobeFormat } | undefined,+ mainFileMeta: { format: FFprobeFormat } | undefined,seekAbs: (val: number | undefined) => void,activeVideoStreamIndex: number | undefined,activeAudioStreamIndexes: Set<number>,@@ -726,7 +727,7 @@ function useSegments({ filePath, workingRef, setWorking, setProgress, videoStreaconst createFixedByteSizedSegments = useCallback(async () => {if (!checkFileOpened() || !isDurationValid(fileDuration)) return;invariant(mainFileMeta != null);- const fileSize = getFileSize(mainFileMeta.formatData);+ const fileSize = getFileSize(mainFileMeta.format);invariant(fileSize != null);const segmentDuration = await createFixedByteSixedSegmentsDialog({ fileDuration, fileSize });if (segmentDuration == null) return;@@ -735,7 +736,7 @@ function useSegments({ filePath, workingRef, setWorking, setProgress, videoStreaconst getSegEstimatedSize = useCallback((segment: Pick<StateSegment, 'start' | 'end'>) => {if (mainFileMeta == null || !isDurationValid(fileDuration) || segment.end == null) return undefined;- const fileSize = getFileSize(mainFileMeta.formatData);+ const fileSize = getFileSize(mainFileMeta.format);if (fileSize == null) return undefined;const segDuration = segment.end - segment.start;return Math.round((segDuration / fileDuration) * fileSize);@@ -800,7 +801,7 @@ function useSegments({ filePath, workingRef, setWorking, setProgress, videoStrea{ name: i18n.t('Markers'), code: 'segment.end == null' },]}title={i18n.t('Select segments by expression')}- description={<Trans>Enter a JavaScript expression which will be evaluated for each segment. Segments for which the expression evaluates to "true" will be selected. <button type="button" className="link-button" onClick={() => shell.openExternal('https://github.com/mifi/lossless-cut/blob/master/expressions.md')}>View available syntax.</button></Trans>}+ description={<Trans>Enter a JavaScript expression which will be evaluated for each segment. Segments for which the expression evaluates to "true" will be selected. <button type="button" className="link-button" onClick={() => shell.openExternal(jsExpressionHelpUrl)}>View available syntax.</button></Trans>}variables={['segment.index', 'segment.label', 'segment.start', 'segment.end', 'segment.duration', 'segment.tags.*']}/>),@@ -870,7 +871,7 @@ function useSegments({ filePath, workingRef, setWorking, setProgress, videoStrea{ name: i18n.t('Convert markers to segments'), code: '{ ...(segment.end == null && { end: segment.start + 5 }) }' },]}title={i18n.t('Edit segments by expression')}- description={<Trans>Enter a JavaScript expression which will be evaluated for each selected segment. Returned properties will be edited. <button type="button" className="link-button" onClick={() => shell.openExternal('https://github.com/mifi/lossless-cut/blob/master/expressions.md')}>View available syntax.</button></Trans>}+ description={<Trans>Enter a JavaScript expression which will be evaluated for each selected segment. Returned properties will be edited. <button type="button" className="link-button" onClick={() => shell.openExternal(jsExpressionHelpUrl)}>View available syntax.</button></Trans>}variables={['segment.index', 'segment.label', 'segment.start', 'segment.end', 'segment.tags.*']}/>),diff --git a/src/renderer/src/reporting.tsx b/src/renderer/src/reporting.tsxindex f2b892b9..0e819a14 100644--- a/src/renderer/src/reporting.tsx+++ b/src/renderer/src/reporting.tsx@@ -4,6 +4,7 @@ import { Trans } from 'react-i18next';import CopyClipboardButton from './components/CopyClipboardButton';import { isStoreBuild, isMasBuild, isWindowsStoreBuild, isExecaError, appVersion, appPath } from './util';import getSwal from './swal';+import { discussionsUrl, githubUrl, issuesUrl, supportEmail } from '../../common/constants';const electron = window.require('electron');@@ -21,14 +22,14 @@ export function openSendReportDialog({ err, message, state }: {}) {const reportInstructions = isStoreBuild? (- <p><Trans>Please send an email to <span className="link-button" role="button" onClick={() => electron.shell.openExternal('mailto:[email protected]')}>[email protected]</span> where you describe what you were doing.</Trans></p>+ <p><Trans>Please send an email to <span className="link-button" role="button" onClick={() => electron.shell.openExternal(`mailto:${supportEmail}`)}>{supportEmail}</span> where you describe what you were doing.</Trans></p>) : (<Trans><p>- If you're having a problem or question about LosslessCut, please first check the links in the <b>Help</b> menu. If you cannot find any resolution, you may ask a question in <span className="link-button" role="button" onClick={() => electron.shell.openExternal('https://github.com/mifi/lossless-cut/discussions')}>GitHub discussions</span> or on <span className="link-button" role="button" onClick={() => electron.shell.openExternal('https://github.com/mifi/lossless-cut')}>Discord.</span>+ If you're having a problem or question about LosslessCut, please first check the links in the <b>Help</b> menu. If you cannot find any resolution, you may ask a question in <span className="link-button" role="button" onClick={() => electron.shell.openExternal(discussionsUrl)}>GitHub discussions</span> or on <span className="link-button" role="button" onClick={() => electron.shell.openExternal(githubUrl)}>Discord.</span></p><p>- If you believe that you found a bug in LosslessCut, you may <span className="link-button" role="button" onClick={() => electron.shell.openExternal('https://github.com/mifi/lossless-cut/issues')}>report a bug</span>.+ If you believe that you found a bug in LosslessCut, you may <span className="link-button" role="button" onClick={() => electron.shell.openExternal(issuesUrl)}>report a bug</span>.</p></Trans>);diff --git a/src/renderer/src/smartcut.ts b/src/renderer/src/smartcut.tsindex 52a5b45e..0407bc8f 100644--- a/src/renderer/src/smartcut.ts+++ b/src/renderer/src/smartcut.ts@@ -5,8 +5,7 @@ import { getRealVideoStreams, getVideoTimebase } from './util/streams';import { readKeyframesAroundTime, findNextKeyframe, findKeyframeAtExactTime } from './ffmpeg';import { FFprobeStream } from '../../common/ffprobe';import { UserFacingError } from '../errors';--const { stat } = window.require('fs-extra');+import { readFileSize } from './util';const mapVideoCodec = (codec: string) => ({ av1: 'libsvtav1' }[codec] ?? codec);@@ -63,9 +62,9 @@ export async function getCodecParams({ path, fileDuration, streams }: {let videoBitrate = parseInt(videoStream.bit_rate!, 10);if (Number.isNaN(videoBitrate)) {console.warn('Unable to detect input bitrate.');- const stats = await stat(path);+ const size = await readFileSize(path);if (fileDuration == null) throw new Error('Video duration is unknown, cannot estimate bitrate');- videoBitrate = (stats.size * 8) / fileDuration;+ videoBitrate = (size * 8) / fileDuration;console.warn('Estimated bitrate.', videoBitrate / 1e6, 'Mbit/s');}diff --git a/src/renderer/src/types.ts b/src/renderer/src/types.tsindex 2b7b8aa8..afaf8481 100644--- a/src/renderer/src/types.ts+++ b/src/renderer/src/types.ts@@ -130,7 +130,7 @@ export type ExportMode = 'segments_to_chapters' | 'merge' | 'merge+separate' | 'export type FilesMeta = Record<string, {streams: FileStream[];- formatData: FFprobeFormat;+ format: FFprobeFormat;chapters: FFprobeChapter[];}>@@ -143,9 +143,17 @@ export interface Chapter { start: number, end: number, name?: string | undefinedexport type LiteFFprobeStream = Pick<FFprobeStream, 'index' | 'codec_type' | 'codec_tag' | 'codec_name' | 'disposition' | 'tags' | 'sample_rate' | 'time_base'>;+export interface FileStats {+ size: number | bigint,+ atime: number,+ mtime: number,+ ctime: number,+ birthtime: number,+}+export type AllFilesMeta = Record<string, {streams: LiteFFprobeStream[];- formatData: FFprobeFormat;+ format: FFprobeFormat;chapters: FFprobeChapter[];}>diff --git a/src/renderer/src/util.ts b/src/renderer/src/util.tsindex a7df3066..53c92111 100644--- a/src/renderer/src/util.ts+++ b/src/renderer/src/util.ts@@ -332,7 +332,9 @@ export function escapeRegExp(str: string) {return str.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string}-export const readFileSize = async (path: string) => (await stat(path)).size;+export const readFileStats = async (path: string) => stat(path);++export const readFileSize = async (path: string) => (await readFileStats(path)).size;export const readFileSizes = (paths: string[]) => pMap(paths, async (path) => readFileSize(path), { concurrency: 5 });@@ -398,8 +400,8 @@ export function getImportProjectType(filePath: string) {return edlFormatForExtension[matchingExt];}-export function getFileSize(formatData: FFprobeFormat) {- const fileSize = parseInt(formatData.size, 10);+export function getFileSize(format: FFprobeFormat) {+ const fileSize = parseInt(format.size, 10);if (Number.isNaN(fileSize)) return undefined;return fileSize;}diff --git a/src/renderer/src/util/outputNameTemplate.ts b/src/renderer/src/util/outputNameTemplate.tsindex e06f5152..6a033830 100644--- a/src/renderer/src/util/outputNameTemplate.ts+++ b/src/renderer/src/util/outputNameTemplate.ts@@ -4,12 +4,15 @@ import pMap from 'p-map';import max from 'lodash/max';import invariant from 'tiny-invariant';+import type { FileNameTemplateContext } from '../../../common/userTypes.ts';+import { isMac, isWindows, hasDuplicates, filenamify, getOutFileExtension } from '../util';import isDev from '../isDev';import { getSegmentTags, formatSegNum, getGuaranteedSegments } from '../segments';-import { FormatTimecode, SegmentToExport } from '../types';+import { FileStats, FormatTimecode, SegmentToExport } from '../types';import safeishEval from '../worker/eval';import { UserFacingError } from '../../errors';+import { FileFfprobeMeta } from '../ffmpeg';export const segNumVariable = 'SEG_NUM';@@ -37,9 +40,11 @@ export interface GeneratedOutFileNames {export type GenerateOutFileNames = (template: string) => Promise<GeneratedOutFileNames>;+export interface SourceFile { path: string, ffprobeMeta?: FileFfprobeMeta | undefined, stats?: FileStats | undefined }+export interface GenerateMergedOutFileNamesParams {template: string;- filePaths: string[];+ sourceFiles: SourceFile[];fileFormat: string;outputDir: string;epochMs: number;@@ -137,8 +142,28 @@ export const defaultCutMergedFileTemplate = '${FILENAME}-cut-merged-${EPOCH_MS}$export const defaultMergedFileTemplate = '${FILENAME}-merged-${EPOCH_MS}${EXT}';-async function interpolateOutFileName(template: string, { epochMs, inputFileNameWithoutExt, ext, segSuffix, segNum, segNumPadded, selectedSegNum, selectedSegNumPadded, segLabels, cutFrom, cutFromStr, cutTo, cutToStr, cutDurationStr, tags, exportCount, currentFileExportCount }: {+async function interpolateOutFileName(template: string, {+ epochMs,+ sourceFiles,+ inputFileNameWithoutExt,+ ext,+ exportCount,+ currentFileExportCount,+ segLabels,+ segSuffix,+ segNum,+ segNumPadded,+ selectedSegNum,+ selectedSegNumPadded,+ cutFrom,+ cutFromStr,+ cutTo,+ cutToStr,+ cutDurationStr,+ tags,+}: {epochMs: number,+ sourceFiles: SourceFile[],inputFileNameWithoutExt: string,ext: string,exportCount: number,@@ -159,6 +184,15 @@ async function interpolateOutFileName(template: string, { epochMs, inputFileName}>) {const context = {FILENAME: inputFileNameWithoutExt,+ FILES: sourceFiles.map((sf) => ({+ path: sf.path,+ name: basename(sf.path),+ size: sf.stats?.size,+ atime: sf.stats?.atime,+ mtime: sf.stats?.mtime,+ ctime: sf.stats?.ctime,+ birthtime: sf.stats?.birthtime,+ })),[segSuffixVariable]: segSuffix,[extVariable]: ext,[segNumIntVariable]: segNum,@@ -179,7 +213,7 @@ async function interpolateOutFileName(template: string, { epochMs, inputFileName},FILE_EXPORT_COUNT: currentFileExportCount != null ? currentFileExportCount + 1 : undefined,EXPORT_COUNT: exportCount != null ? exportCount + 1 : undefined,- };+ } satisfies FileNameTemplateContext;const ret = (await safeishEval(`\`${template}\``, context));if (typeof ret !== 'string') throw new UserFacingError(i18n.t('Expression did not lead to a string'));@@ -240,14 +274,14 @@ async function generateWithFallback({ generate, desiredTemplate, defaultTemplatereturn { fileNames: originalFileNames, problems };}-export async function generateCutFileNames({ fileDuration, segmentsToExport: segmentsToExportIn, template: desiredTemplate, formatTimecode, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding, exportCount, currentFileExportCount }: {+export async function generateCutFileNames({ fileDuration, segmentsToExport: segmentsToExportIn, template: desiredTemplate, formatTimecode, isCustomFormatSelected, fileFormat, sourceFile, outputDir, safeOutputFileName, maxLabelLength, outputFileNameMinZeroPadding, exportCount, currentFileExportCount }: {fileDuration: number | undefined,segmentsToExport: SegmentToExport[],template: string,formatTimecode: FormatTimecode,isCustomFormatSelected: boolean,fileFormat: string,- filePath: string,+ sourceFile: SourceFile,outputDir: string,safeOutputFileName: boolean,maxLabelLength: number,@@ -277,7 +311,7 @@ export async function generateCutFileNames({ fileDuration, segmentsToExport: segreturn '';}- const { name: inputFileNameWithoutExt } = parsePath(filePath);+ const { name: inputFileNameWithoutExt } = parsePath(sourceFile.path);const cutDuration = end - start;@@ -288,8 +322,9 @@ export async function generateCutFileNames({ fileDuration, segmentsToExport: segselectedSegNum,selectedSegNumPadded,segSuffix: getSegSuffix(),+ sourceFiles: [sourceFile],inputFileNameWithoutExt,- ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),+ ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath: sourceFile.path }),segLabels: [sanitizeName(name)],cutFrom: start,cutFromStr: formatTimecode({ seconds: start, fileNameFriendly: true }),@@ -306,7 +341,7 @@ export async function generateCutFileNames({ fileDuration, segmentsToExport: seg},desiredTemplate,defaultTemplate: defaultCutFileTemplate,- filePath,+ filePath: sourceFile.path,outputDir,maxLabelLength,safeOutputFileName,@@ -315,11 +350,11 @@ export async function generateCutFileNames({ fileDuration, segmentsToExport: segexport type GenerateMergedOutFileNames = (params: GenerateMergedOutFileNamesParams) => Promise<GeneratedOutFileNames>;-export async function generateCutMergedFileNames({ template: desiredTemplate, isCustomFormatSelected, fileFormat, filePath, outputDir, safeOutputFileName, maxLabelLength, exportCount, currentFileExportCount, segLabels, epochMs = Date.now() }: {+export async function generateCutMergedFileNames({ template: desiredTemplate, isCustomFormatSelected, fileFormat, sourceFile, outputDir, safeOutputFileName, maxLabelLength, exportCount, currentFileExportCount, segLabels, epochMs = Date.now() }: {template: string,isCustomFormatSelected: boolean,fileFormat: string,- filePath: string,+ sourceFile: SourceFile,outputDir: string,safeOutputFileName: boolean,maxLabelLength: number,@@ -330,12 +365,13 @@ export async function generateCutMergedFileNames({ template: desiredTemplate, is}) {return generateWithFallback({generate: async ({ template, safeOutputFileName: safeOutputFileName2, sanitizeName }) => {- const { name: inputFileNameWithoutExt } = parsePath(filePath);+ const { name: inputFileNameWithoutExt } = parsePath(sourceFile.path);const fileName = await interpolateOutFileName(template, {epochMs,+ sourceFiles: [sourceFile],inputFileNameWithoutExt,- ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath }),+ ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath: sourceFile.path }),exportCount,currentFileExportCount,segLabels: segLabels.map((label) => sanitizeName(label)),@@ -345,44 +381,45 @@ export async function generateCutMergedFileNames({ template: desiredTemplate, is},desiredTemplate,defaultTemplate: defaultCutMergedFileTemplate,- filePath,+ filePath: sourceFile.path,outputDir,maxLabelLength,safeOutputFileName,});}-export async function generateMergedFileNames({ template: desiredTemplate, isCustomFormatSelected, fileFormat, filePaths, outputDir, safeOutputFileName, maxLabelLength, exportCount, epochMs }: {+export async function generateMergedFileNames({ template: desiredTemplate, isCustomFormatSelected, fileFormat, sourceFiles, outputDir, safeOutputFileName, maxLabelLength, exportCount, epochMs }: {template: string,isCustomFormatSelected: boolean,fileFormat: string,- filePaths: string[],+ sourceFiles: SourceFile[],outputDir: string,safeOutputFileName: boolean,maxLabelLength: number,exportCount: number,epochMs: number,}) {- const [firstPath] = filePaths;- invariant(firstPath != null);+ const [firstFile] = sourceFiles;+ invariant(firstFile != null);return generateWithFallback({generate: async ({ template, safeOutputFileName: safeOutputFileName2, sanitizeName }) => {- const { name: inputFileNameWithoutExt } = parsePath(firstPath);+ const { name: inputFileNameWithoutExt } = parsePath(firstFile.path);const fileName = await interpolateOutFileName(template, {epochMs,+ sourceFiles,inputFileNameWithoutExt,- ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath: firstPath }),+ ext: getOutFileExtension({ isCustomFormatSelected, outFormat: fileFormat, filePath: firstFile.path }),exportCount,- segLabels: filePaths.map((filePath) => sanitizeName(basename(filePath))),+ segLabels: sourceFiles.map((file) => sanitizeName(basename(file.path))),});return [maybeTruncatePath(fileName, safeOutputFileName2)];},desiredTemplate,defaultTemplate: defaultCutMergedFileTemplate,- filePath: firstPath,+ filePath: firstFile.path,outputDir,maxLabelLength,safeOutputFileName,