Skip to content

The swiss army knife of lossless video/audio editing

Enable 8 lint rules whose findings oxlint autofixes safely

Claude2ef4d5520d28
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 864ae14a..3993594b 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -35,26 +35,20 @@
"no-implicit-coercion": "off", // (25)
"unicorn/consistent-function-scoping": "off", // (23)
"promise/prefer-await-to-then": "off", // (13)
- "vitest/prefer-expect-resolves": "off", // (7)
"jsx-a11y/prefer-tag-over-role": "off", // (60)
"react/hooks": "off", // (32)
"react/memo-dependencies": "off", // (20)
"unicorn/prefer-number-coercion": "off", // (95)
"unicorn-js/prefer-minimal-ternary": "off", // (19)
"unicorn-js/prefer-simple-condition-first": "off", // (17)
- "unicorn-js/no-asterisk-prefix-in-documentation-comments": "off", // (152)
"unicorn-js/prefer-combined-guards": "off", // (19)
"unicorn-js/prefer-early-return": "off", // (26)
"unicorn-js/no-negated-array-predicate": "off", // (7)
- "unicorn-js/single-line-block-comment-style": "off", // (37)
"unicorn/max-nested-calls": "off", // (22)
"unicorn-js/no-declarations-before-early-exit": "off", // (15)
- "unicorn/consistent-assert": "off", // (56)
"unicorn-js/no-top-level-assignment-in-function": "off", // (25)
"unicorn-js/prefer-continue": "off", // (6)
- "unicorn-js/prefer-split-limit": "off", // (7)
"unicorn-js/no-unnecessary-array-flat-map": "off", // (20)
- "unicorn-js/consistent-conditional-object-spread": "off", // (6)
"unicorn-js/prefer-await": "off", // (14)
"unicorn-js/no-computed-property-existence-check": "off", // (15)
"unicorn-js/no-useless-concat": "off", // (11)
@@ -70,11 +64,9 @@
"typescript/unbound-method": "off", // (8)
"typescript/no-duplicate-type-constituents": "off", // (11)
"typescript/no-floating-promises": "off", // (116)
- "typescript/no-unnecessary-type-assertion": "off", // (7)
"typescript/no-unnecessary-type-conversion": "off", // (9)
"typescript/prefer-optional-chain": "off", // (17)
"typescript/no-redundant-type-constituents": "off", // (8)
- "typescript/prefer-regexp-exec": "off", // (20)
"typescript/require-await": "off", // (19)
"typescript/no-misused-promises": "off", // (121)
"typescript/no-unnecessary-boolean-literal-compare": "off", // (7)
diff --git a/docs/generated/types.md b/docs/generated/types.md
index d1e5f691..8c625cf4 100644
--- a/docs/generated/types.md
+++ b/docs/generated/types.md
@@ -8,19 +8,33 @@
* All times are expressed in milliseconds since the POSIX Epoch.
*/
interface SourceFile {
- /** The file's name without the file system path. */
+ /**
+ * The file's name without the file system path.
+ */
name: string;
- /** The full filesystem path of the file. */
+ /**
+ * The full filesystem path of the file.
+ */
path: string;
- /** File size in bytes. */
+ /**
+ * File size in bytes.
+ */
size?: number | bigint | undefined;
- /** The last time this file was accessed. */
+ /**
+ * The last time this file was accessed.
+ */
atime?: number | undefined;
- /** The last time this file was modified. */
+ /**
+ * The last time this file was modified.
+ */
mtime?: number | undefined;
- /** The last time the file status was changed. */
+ /**
+ * The last time the file status was changed.
+ */
ctime?: number | undefined;
- /** The creation time of this file. */
+ /**
+ * The creation time of this file.
+ */
birthtime?: number | undefined;
}
```
@@ -61,17 +75,29 @@ interface FileNameTemplateContext {
* See https://losslesscut.app/docs/expressions
*/
interface Segment {
- /** Index of the segment in the segment list, starting with 0 */
+ /**
+ * Index of the segment in the segment list, starting with 0
+ */
index: number;
- /** Name of the segment */
+ /**
+ * Name of the segment
+ */
label: string;
- /** Segment start time in seconds */
+ /**
+ * Segment start time in seconds
+ */
start: number;
- /** Segment end time in seconds, or undefined for markers */
+ /**
+ * Segment end time in seconds, or undefined for markers
+ */
end?: number | undefined;
- /** Duration in seconds (effectively `end` minus `start` or 0 for markers) */
+ /**
+ * Duration in seconds (effectively `end` minus `start` or 0 for markers)
+ */
duration: number;
- /** Tags associated with this segment */
+ /**
+ * Tags associated with this segment
+ */
tags: Record<string, string>;
}
```
diff --git a/script/afterPack.ts b/script/afterPack.ts
index 4f3f5b18..bcebe03a 100644
--- a/script/afterPack.ts
+++ b/script/afterPack.ts
@@ -11,14 +11,14 @@ export default async function afterPack({ appOutDir, arch, electronPlatformName,
const resourcesDir = packager.getResourcesDir(appOutDir);
for (const name of ['ffmpeg', 'ffprobe']) {
const path = join(resourcesDir, electronPlatformName === 'win32' ? `${name}.exe` : name);
- assert(existsSync(path), `${path} is missing. Did you run download-ffmpeg for ${electronPlatformName}-${Arch[arch]}?`);
+ assert.ok(existsSync(path), `${path} is missing. Did you run download-ffmpeg for ${electronPlatformName}-${Arch[arch]}?`);
// If the binary can run on this machine, check that it does (e.g. not a broken download or missing libraries).
// Mac App Store builds have electronPlatformName 'mas', so they're not run (the dmg builds use the same binaries)
if (electronPlatformName === process.platform && Arch[arch] === process.arch) {
// Like the app does on Linux (see src/main/ffmpeg.ts)
const { stdout } = await execa(path, ['-hide_banner', '-version'], { env: { LD_LIBRARY_PATH: resourcesDir } });
- console.log(stdout.split('\n')[0]);
+ console.log(stdout.split('\n', 1)[0]);
}
}
}
diff --git a/script/checkReleaseAssets.ts b/script/checkReleaseAssets.ts
index dbc5fdf8..4c428feb 100644
--- a/script/checkReleaseAssets.ts
+++ b/script/checkReleaseAssets.ts
@@ -5,7 +5,7 @@ import assert from 'node:assert';
const tag = process.argv[2];
const token = process.env['GH_TOKEN'] || undefined;
-assert(tag != null, 'Usage: node script/checkReleaseAssets.ts <tag>');
+assert.ok(tag != null, 'Usage: node script/checkReleaseAssets.ts <tag>');
const repo = process.env['GITHUB_REPOSITORY'] ?? 'mifi/lossless-cut';
// Sizes usually change by a few percent between releases. A failure on a draft can be checked and ignored if the size change is expected
@@ -15,13 +15,13 @@ interface Release { tag_name: string, assets: { name: string, size: number }[] }
async function get<T>(path: string) {
const response = await fetch(`https://api.github.com/repos/${repo}/${path}`, { headers: { accept: 'application/vnd.github+json', ...(token != null && { authorization: `Bearer ${token}` }) } });
- assert(response.ok, `GET ${path} failed: ${response.status}`);
+ assert.ok(response.ok, `GET ${path} failed: ${response.status}`);
return await response.json() as T;
}
// The "release by tag" endpoint only returns published releases, so look in the list (drafts come first)
const release = (await get<Release[]>('releases?per_page=100')).find((r) => r.tag_name === tag);
-assert(release != null, `No release found for ${tag}`);
+assert.ok(release != null, `No release found for ${tag}`);
const previous = await get<Release>('releases/latest');
const formatMb = (bytes: number) => `${(bytes / 1e6).toFixed(0)} MB`;
// Nothing to compare with when re-running after the release was published
diff --git a/script/downloadFfmpeg.ts b/script/downloadFfmpeg.ts
index 5857fb1f..a10c7ff2 100644
--- a/script/downloadFfmpeg.ts
+++ b/script/downloadFfmpeg.ts
@@ -15,14 +15,14 @@ const windowsLinuxRelease = '9.0-2'; // https://github.com/mifi/ffmpeg-builds/re
const target = process.argv[2];
const btbnTargets: Record<string, string> = { 'linux-x64': 'linux64', 'linux-arm64': 'linuxarm64', 'win32-x64': 'win64', 'win32-arm64': 'winarm64' };
const macArchs: Record<string, string> = { 'darwin-x64': 'X64', 'darwin-arm64': 'ARM64' };
-assert(target != null && (Object.hasOwn(btbnTargets, target) || Object.hasOwn(macArchs, target)), `Usage: downloadFfmpeg.ts ${[...Object.keys(macArchs), ...Object.keys(btbnTargets)].join('|')}`);
+assert.ok(target != null && (Object.hasOwn(btbnTargets, target) || Object.hasOwn(macArchs, target)), `Usage: downloadFfmpeg.ts ${[...Object.keys(macArchs), ...Object.keys(btbnTargets)].join('|')}`);
const dir = join('ffmpeg', target);
async function download(url: string, path: string) {
console.log('Downloading', url);
const response = await fetch(url);
- assert(response.ok && response.body != null, `Failed to download ${url}: ${response.status}`);
+ assert.ok(response.ok && response.body != null, `Failed to download ${url}: ${response.status}`);
await pipeline(Readable.fromWeb(response.body), createWriteStream(path));
}
@@ -41,7 +41,7 @@ if (macArch != null) {
} else {
// the electron-builder config bundles everything in `lib`
binDir = join(dir, 'lib');
- const branch = windowsLinuxRelease.split('-')[0];
+ const branch = windowsLinuxRelease.split('-', 1)[0];
const isWindows = target.startsWith('win32');
const name = `ffmpeg-n${branch}-latest-${btbnTargets[target]}-gpl-shared-${branch}`;
const archiveName = `${name}${isWindows ? '.zip' : '.tar.xz'}`;
@@ -67,7 +67,7 @@ if (macArch != null) {
if (target === `${process.platform}-${process.arch}`) {
for (const name of ['ffmpeg', 'ffprobe']) {
const { stdout } = await execa(join(binDir, process.platform === 'win32' ? `${name}.exe` : name), ['-hide_banner', '-version']);
- console.log(stdout.split('\n')[0]);
+ console.log(stdout.split('\n', 1)[0]);
}
}
console.log('Done', binDir);
diff --git a/script/e2e.ts b/script/e2e.ts
index 777aec4b..723e6a89 100644
--- a/script/e2e.ts
+++ b/script/e2e.ts
@@ -7,10 +7,10 @@ import timers from 'node:timers/promises';
const losslessCutExePath = process.argv[2];
-assert(losslessCutExePath);
+assert.ok(losslessCutExePath);
const screenshotDevice = process.argv[3];
const screenshotOutPath = process.argv[4];
-assert(screenshotOutPath);
+assert.ok(screenshotOutPath);
const port = 8081;
@@ -38,7 +38,7 @@ async function captureScreenshot(outPath: string) {
console.log(stderr);
}
- assert(screenshotDevice);
+ assert.ok(screenshotDevice);
await execa('ffmpeg', [
...(platform === 'darwin' ? ['-r', '30', '-pix_fmt', 'uyvy422', '-f', 'avfoundation'] : []),
@@ -55,7 +55,7 @@ try {
retry: { backoffLimit: 5000, limit: 10 },
hooks: { beforeRequest: [() => { console.log('attempt'); }] },
}).text();
- assert(resp.length > 0);
+ assert.ok(resp.length > 0);
console.log('Waiting for UI to settle');
diff --git a/script/featureMedia.ts b/script/featureMedia.ts
index 18a374f5..e8da8935 100644
--- a/script/featureMedia.ts
+++ b/script/featureMedia.ts
@@ -21,16 +21,16 @@ import type { Caption, Rect, Zoom } from './featureMedia/socialVideo.ts';
// eslint-disable-next-line unicorn-js/no-unreadable-object-destructuring -- TODO fix (new rule in @mifi/lint-config)
const { values: { clips = 'dist/feature-media-clips', music: musicArg = defaultMusic, scale: scaleArg = '1' }, positionals: [scenarioName] } = parseArgs({ allowPositionals: true, options: { clips: { type: 'string' }, music: { type: 'string' }, scale: { type: 'string' } } });
const scenario = scenarioName != null ? scenarios[scenarioName] : undefined;
-assert(scenario != null, `Usage: node script/featureMedia.ts <scenario> [--clips dir] [--music track from music.ts, audio file or none] [--scale 2]. Scenarios: ${Object.keys(scenarios).join(', ')}`);
+assert.ok(scenario != null, `Usage: node script/featureMedia.ts <scenario> [--clips dir] [--music track from music.ts, audio file or none] [--scale 2]. Scenarios: ${Object.keys(scenarios).join(', ')}`);
const display = process.env['DISPLAY'];
-assert(process.platform === 'linux' && display != null, 'Run under Xvfb on Linux, see the top of this file');
+assert.ok(process.platform === 'linux' && display != null, 'Run under Xvfb on Linux, see the top of this file');
// The window size, in the coordinates scenarios use. With --scale 2 the app is drawn at twice the pixels (like on a HiDPI screen), e.g. for sharp screenshots
const width = 1024;
const height = 640;
const scale = Number(scaleArg);
// eslint-disable-next-line unicorn-js/prefer-number-is-safe-integer -- TODO fix (new rule in @mifi/lint-config)
-assert(Number.isInteger(scale) && scale > 0, `--scale must be a whole number, got ${scaleArg}`);
+assert.ok(Number.isInteger(scale) && scale > 0, `--scale must be a whole number, got ${scaleArg}`);
const screenWidth = width * scale;
const screenHeight = height * scale;
const port = 8099;
@@ -41,7 +41,7 @@ await new Promise<void>((resolvePromise, reject) => {
});
// Scenarios click at fixed positions, so the screen must be the size of the window
const { stdout: screenSize } = await execa('xdotool', ['getdisplaygeometry']);
-assert(screenSize === `${screenWidth} ${screenHeight}`, `The screen is ${screenSize}, run Xvfb with -screen 0 ${screenWidth}x${screenHeight}x24`);
+assert.ok(screenSize === `${screenWidth} ${screenHeight}`, `The screen is ${screenSize}, run Xvfb with -screen 0 ${screenWidth}x${screenHeight}x24`);
const ffmpeg = 'ffmpeg/linux-x64/lib/ffmpeg';
const ffprobe = 'ffmpeg/linux-x64/lib/ffprobe';
const outDir = 'dist/feature-media';
@@ -59,7 +59,7 @@ async function writeVia(path: string, write: (partPath: string) => Promise<unkno
async function download(url: string, path: string) {
const response = await fetch(url);
- assert(response.ok && response.body != null, `Failed to download ${url}: ${response.status}`);
+ assert.ok(response.ok && response.body != null, `Failed to download ${url}: ${response.status}`);
await writeVia(path, async (partPath) => pipeline(Readable.fromWeb(response.body!), createWriteStream(partPath)));
}
@@ -79,7 +79,7 @@ if (musicTrack != null) {
await ffmpegDownload(['-i', musicTrack.url, '-c', 'copy', '-f', 'mp3'], music);
}
}
-assert(music == null || await exists(music), `--music must be one of ${Object.keys(musicTracks).join(', ')}, an audio file or none, got ${musicArg}`);
+assert.ok(music == null || await exists(music), `--music must be one of ${Object.keys(musicTracks).join(', ')}, an audio file or none, got ${musicArg}`);
// Get the clips, from the folder or else make them from their sources (see clips.ts) or download them
const clipsUrl = process.env['FEATURE_MEDIA_CLIPS_URL'] ?? 'https://static.mifi.no/losslesscut';
@@ -117,7 +117,7 @@ async function post(path: string, body?: unknown) {
// Actions wait until they're done (e.g. a scene detection), but don't hang forever on one that opens a dialog
signal: AbortSignal.timeout(60_000),
});
- assert(response.ok, `${path} failed: ${response.status} ${await response.text()}`);
+ assert.ok(response.ok, `${path} failed: ${response.status} ${await response.text()}`);
}
const grab = ['-f', 'x11grab', '-draw_mouse', '0', '-framerate', '30', '-video_size', `${screenWidth}x${screenHeight}`, '-i', `${display}+0,0`];
@@ -128,7 +128,7 @@ try {
for (let i = 0; ; i += 1) {
// eslint-disable-next-line unicorn-js/prefer-then-catch -- TODO fix (new rule in @mifi/lint-config)
if (await fetch(`http://127.0.0.1:${port}/`).then(() => true, () => false)) break;
- assert(i < 60 && app.exitCode == null, `LosslessCut did not start, see ${appLog}`);
+ assert.ok(i < 60 && app.exitCode == null, `LosslessCut did not start, see ${appLog}`);
await timers.setTimeout(500);
}
await timers.setTimeout(3000);
@@ -199,7 +199,7 @@ try {
recorder.kill('SIGINT');
}
const { exitCode } = await recorder;
- assert(exitCode === 0 || exitCode === 255, `Recording failed with exit code ${exitCode}`);
+ assert.ok(exitCode === 0 || exitCode === 255, `Recording failed with exit code ${exitCode}`);
// Not needed for the encoding below
app.kill();
// A high quality master (web versions are made from it elsewhere), with the index at the start for streaming
diff --git a/script/featureMedia/socialVideo.ts b/script/featureMedia/socialVideo.ts
index 7635b34f..80ff12ea 100644
--- a/script/featureMedia/socialVideo.ts
+++ b/script/featureMedia/socialVideo.ts
@@ -96,12 +96,16 @@ export async function renderSocialVideo({ ffmpeg, rawVideo, videoStart, duration
ffmpeg: string,
rawVideo: string,
videoStart: number,
- /** Of the video after videoStart */
+ /**
+ Of the video after videoStart
+ */
duration: number,
captions: Caption[],
zooms: Zoom[],
description: string,
- /** An audio file, or undefined for no music */
+ /**
+ An audio file, or undefined for no music
+ */
music: string | undefined,
windowWidth: number,
windowHeight: number,
diff --git a/script/featureMedia/types.ts b/script/featureMedia/types.ts
index 0a1b6202..c561f608 100644
--- a/script/featureMedia/types.ts
+++ b/script/featureMedia/types.ts
@@ -1,34 +1,58 @@
import type { Rect } from './socialVideo.ts';
export interface ScenarioContext {
- /** Opens clips from the clips folder (several go to the batch list) */
+ /**
+ Opens clips from the clips folder (several go to the batch list)
+ */
open: (...clips: string[]) => Promise<void>,
- /** Runs a keyboard action (see the Keyboard & mouse shortcuts dialog for names), optionally with arguments */
+ /**
+ Runs a keyboard action (see the Keyboard & mouse shortcuts dialog for names), optionally with arguments
+ */
action: (name: string, args?: unknown) => Promise<void>,
- /** Runs an action that opens a dialog with a text field, types the text (if any) and confirms */
+ /**
+ Runs an action that opens a dialog with a text field, types the text (if any) and confirms
+ */
actionWithDialog: (name: string, text?: string) => Promise<void>,
- /** Presses keys with xdotool, e.g. 'Return' to confirm a dialog that an action opened (start the action without awaiting it) */
+ /**
+ Presses keys with xdotool, e.g. 'Return' to confirm a dialog that an action opened (start the action without awaiting it)
+ */
key: (keys: string) => Promise<void>,
- /** Types text with xdotool */
+ /**
+ Types text with xdotool
+ */
type: (text: string) => Promise<void>,
- /** Clicks at a position in the 1024×640 window (find it in a screenshot) */
+ /**
+ Clicks at a position in the 1024×640 window (find it in a screenshot)
+ */
click: (x: number, y: number) => Promise<void>,
- /** Saves a screenshot as <scenario>-<name>.png, optionally of only a part of the window (as for click) */
+ /**
+ Saves a screenshot as <scenario>-<name>.png, optionally of only a part of the window (as for click)
+ */
shot: (name: string, crop?: Rect) => Promise<void>,
wait: (ms: number) => Promise<void>,
- /** Starts the video here instead of at the beginning, e.g. after opening the file */
+ /**
+ Starts the video here instead of at the beginning, e.g. after opening the file
+ */
startVideo: () => void,
- /** Shows a caption in the social media versions from now until the next one (or none with no text) */
+ /**
+ Shows a caption in the social media versions from now until the next one (or none with no text)
+ */
caption: (text?: string) => void,
- /** Zooms the social media versions in on a part of the window (as for click), or back out with no rect */
+ /**
+ Zooms the social media versions in on a part of the window (as for click), or back out with no rect
+ */
zoom: (rect?: Rect) => void,
}
export interface Scenario {
description: string,
- /** File names of the clips it needs, from the clips folder or downloaded */
+ /**
+ File names of the clips it needs, from the clips folder or downloaded
+ */
clips: string[],
- /** Settings to start with (see src/main/configStore.ts), e.g. to show an export mode */
+ /**
+ Settings to start with (see src/main/configStore.ts), e.g. to show an export mode
+ */
config?: Record<string, unknown>,
run: (ctx: ScenarioContext) => Promise<void>,
}
diff --git a/script/getCommits.ts b/script/getCommits.ts
index 863ca3ba..eb8650db 100644
--- a/script/getCommits.ts
+++ b/script/getCommits.ts
@@ -5,7 +5,7 @@ import { DateTime } from 'luxon';
// Find the most recent tag that starts with `v` (if any)
const ps1 = await execa('git', ['describe', '--tags', '--abbrev=0', '--match', 'v*']);
const tag = ps1.stdout.trim();
-assert(tag, 'Tag not found');
+assert.ok(tag, 'Tag not found');
// Use record separator (RS) and field separator (FS) to split commits and fields reliably
const RS = '\u{1E}';
@@ -14,7 +14,7 @@ const format = `%H${FS}%cI${FS}%an <%ae>${FS}%B${RS}`;
const args = tag ? ['log', `${tag}..HEAD`, `--pretty=format:${format}`] : ['log', `--pretty=format:${format}`];
const ps2 = await execa('git', args);
-assert(ps2.stdout);
+assert.ok(ps2.stdout);
const commits = ps2.stdout
.split(RS)
@@ -22,7 +22,7 @@ const commits = ps2.stdout
.filter(Boolean)
.map((s) => {
const [hash, date, author, ...bodyParts] = s.split(FS);
- assert(date);
+ assert.ok(date);
const body = bodyParts.join(FS).trim();
return { hash: hash?.trim(), date: date?.trim(), author: author?.trim(), message: body };
});
diff --git a/script/releaseImage.ts b/script/releaseImage.ts
index 34e711ff..76969efd 100644
--- a/script/releaseImage.ts
+++ b/script/releaseImage.ts
@@ -11,7 +11,7 @@ const { values: { bg, position, caption, square, out }, positionals: [version, .
options: { bg: { type: 'string' }, position: { type: 'string' }, caption: { type: 'string' }, square: { type: 'boolean' }, out: { type: 'string' } },
});
const usage = 'Usage: node script/releaseImage.ts <version> [--bg photo.jpg] [--position top|bottom|left|right|center] [--caption "photo caption"] [--square] [--out file.png] [up to 3 "highlights"]';
-assert(version != null && highlights.length <= 3, usage);
+assert.ok(version != null && highlights.length <= 3, usage);
// 16:9 for X/Bluesky/Mastodon/Discord, or square for Instagram
const width = square ? 1080 : 1600;
diff --git a/script/storeRelease.ts b/script/storeRelease.ts
index 5605a943..15594ed2 100644
--- a/script/storeRelease.ts
+++ b/script/storeRelease.ts
@@ -47,11 +47,11 @@ const args = yargs(hideBin(process.argv))
const [store] = args._.map(String);
const write = args.submit || args.prepare;
-assert(!args.prepare || store === 'mas', '--prepare is only supported for mas');
+assert.ok(!args.prepare || store === 'mas', '--prepare is only supported for mas');
function requireEnv(name: string) {
const value = process.env[name];
- assert(value, `Missing environment variable ${name}`);
+ assert.ok(value, `Missing environment variable ${name}`);
return value;
}
@@ -59,7 +59,7 @@ const log = (...rest: unknown[]) => console.log(...rest);
const plan = (msg: string) => log(write ? `→ ${msg}` : `[dry run] would: ${msg}`);
// stops a real run, but lets a dry run go on to show the rest of its plan
const blocker = (msg: string) => {
- assert(!write, msg);
+ assert.ok(!write, msg);
log(`[dry run] BLOCKED, --submit would stop here: ${msg}`);
};
@@ -68,7 +68,7 @@ async function fetchJson(url: string, init: RequestInit & { hint?: string } = {}
const response = await fetch(url, rest);
const text = await response.text();
if (!response.ok) {
- throw new Error(`${rest.method ?? 'GET'} ${url.split('?')[0]}: HTTP ${response.status}\n${text}${hint && response.status === 403 ? `\n${hint}` : ''}`);
+ throw new Error(`${rest.method ?? 'GET'} ${url.split('?', 1)[0]}: HTTP ${response.status}\n${text}${hint && response.status === 403 ? `\n${hint}` : ''}`);
}
return text ? JSON.parse(text) : undefined;
}
@@ -80,8 +80,8 @@ async function readNotes(version: string, maxLength: number) {
return '';
}
const notes = (await readFile(path, 'utf8')).trim();
- assert(notes.length > 0, `${path} is empty`);
- assert(notes.length <= maxLength, `${path} is ${notes.length} characters, the max is ${maxLength}`);
+ assert.ok(notes.length > 0, `${path} is empty`);
+ assert.ok(notes.length <= maxLength, `${path} is ${notes.length} characters, the max is ${maxLength}`);
log(`What's New (${path}, ${notes.length}/${maxLength} characters):\n\n${notes}\n`);
return notes;
}
@@ -173,8 +173,8 @@ async function mas(version: string) {
if (write) {
for (let i = 0; build?.attributes['processingState'] !== 'VALID'; i += 1) {
- assert(build == null || build.attributes['processingState'] === 'PROCESSING', `Build ${version} is ${build?.attributes['processingState']}`);
- assert(i < 60, `Build ${version} didn't finish processing in time`);
+ assert.ok(build == null || build.attributes['processingState'] === 'PROCESSING', `Build ${version} is ${build?.attributes['processingState']}`);
+ assert.ok(i < 60, `Build ${version} didn't finish processing in time`);
log('Waiting for the build to be uploaded/processed…');
// eslint-disable-next-line no-await-in-loop
await sleep(60_000);
@@ -207,7 +207,7 @@ async function mas(version: string) {
const localizations = (await asc<AscResource[]>('GET', `/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations`))!;
const enUs = localizations.find((l) => l.attributes['locale'] === 'en-US');
- assert(enUs, 'No en-US localization');
+ assert.ok(enUs, 'No en-US localization');
const otherLocales = localizations.filter((l) => l !== enUs).map((l) => l.attributes['locale']);
if (otherLocales.length > 0) log(`Note: only en-US What's New is set, other locales: ${otherLocales.join(', ')}`);
if (enUs.attributes['whatsNew'] === notes) {
@@ -284,7 +284,7 @@ function logMsSubmission(label: string, submission: { id: string, friendlyName:
async function getMsApp() {
const app = await ms('GET', '');
log(`App: ${app.primaryName} (${app.id})`);
- assert(app.lastPublishedApplicationSubmission, 'No published submission');
+ assert.ok(app.lastPublishedApplicationSubmission, 'No published submission');
const published = await ms('GET', `/submissions/${app.lastPublishedApplicationSubmission.id}`);
const { packageRollout } = published.packageDeliveryOptions;
logMsSubmission('Last published', published, `, rollout ${packageRollout.isPackageRollout ? `${packageRollout.packageRolloutPercentage}% ${packageRollout.packageRolloutStatus}` : 'off'}`);
@@ -321,7 +321,7 @@ async function msstore(version: string) {
for (const { url } of packages) {
// eslint-disable-next-line no-await-in-loop
const response = await fetch(url, { method: 'HEAD' });
- assert(response.ok, `${url}: HTTP ${response.status}`);
+ assert.ok(response.ok, `${url}: HTTP ${response.status}`);
log(`${url} (${(Number(response.headers.get('content-length')) / 1e6).toFixed(0)} MB)`);
}
@@ -335,7 +335,7 @@ async function msstore(version: string) {
log(`Downloading ${fileName}…`);
// eslint-disable-next-line no-await-in-loop
const response = await fetch(url);
- assert(response.ok, `${url}: HTTP ${response.status}`);
+ assert.ok(response.ok, `${url}: HTTP ${response.status}`);
// eslint-disable-next-line no-await-in-loop
await writeFile(join(dir, fileName), Buffer.from(await response.arrayBuffer()));
}
@@ -345,7 +345,7 @@ async function msstore(version: string) {
const submission = await ms('POST', '/submissions');
log(`Created submission ${submission.id}`);
- assert(submission.listings['en-us'], `No en-us listing, found: ${Object.keys(submission.listings).join(', ')}`);
+ assert.ok(submission.listings['en-us'], `No en-us listing, found: ${Object.keys(submission.listings).join(', ')}`);
submission.listings['en-us'].baseListing.releaseNotes = notes;
submission.applicationPackages = [
// like Partner Center does when uploading new packages for the same architectures
@@ -363,12 +363,12 @@ async function msstore(version: string) {
headers: { 'x-ms-blob-type': 'BlockBlob', 'x-ms-version': '2021-12-02' },
body: await openAsBlob(zipPath),
});
- assert(upload.ok, `Upload failed: HTTP ${upload.status} ${await upload.text()}`);
+ assert.ok(upload.ok, `Upload failed: HTTP ${upload.status} ${await upload.text()}`);
await ms('POST', `/submissions/${submission.id}/commit`);
let status: { status: string, statusDetails: unknown };
for (let i = 0; ; i += 1) {
- assert(i < 60, 'Commit didn\'t finish in time, check the submission in Partner Center');
+ assert.ok(i < 60, 'Commit didn\'t finish in time, check the submission in Partner Center');
// eslint-disable-next-line no-await-in-loop
await sleep(10_000);
// eslint-disable-next-line no-await-in-loop
@@ -376,7 +376,7 @@ async function msstore(version: string) {
log(status.status);
if (!['PendingCommit', 'CommitStarted'].includes(status.status)) break;
}
- assert(status.status !== 'CommitFailed', `Commit failed: ${JSON.stringify(status.statusDetails, null, 2)}`);
+ assert.ok(status.status !== 'CommitFailed', `Commit failed: ${JSON.stringify(status.statusDetails, null, 2)}`);
log(`Submitted for certification: https://partner.microsoft.com/en-us/dashboard/products/${msStoreAppId}/submissions/${submission.id}`);
} finally {
await rm(dir, { recursive: true, force: true });
@@ -387,12 +387,12 @@ async function msstoreRollout(percentArg: string) {
const { published } = await getMsApp();
const { packageRolloutStatus, packageRolloutPercentage } = published.packageDeliveryOptions.packageRollout;
if (packageRolloutStatus !== 'PackageRolloutInProgress') {
- assert(percentArg === 'next', 'The last published submission has no gradual rollout in progress (did you click "Publish now"?)');
+ assert.ok(percentArg === 'next', 'The last published submission has no gradual rollout in progress (did you click "Publish now"?)');
log('No rollout in progress, nothing to do');
return;
}
const percent = percentArg === 'next' ? (msStoreRolloutSteps.find((step) => step > packageRolloutPercentage) ?? 100) : Number(percentArg);
- assert(percent > 0 && percent <= 100, 'Percent must be in (0, 100]');
+ assert.ok(percent > 0 && percent <= 100, 'Percent must be in (0, 100]');
const action = percent === 100 ? 'finalizepackagerollout' : `updatepackagerolloutpercentage?percentage=${percent}`;
plan(percent === 100 ? 'finalize the rollout (100%)' : `set rollout to ${percent}%`);
if (!args.submit) return;
@@ -401,7 +401,7 @@ async function msstoreRollout(percentArg: string) {
const version = String(args['version']);
-assert(store === 'msstore-rollout' || /^\d+\.\d+\.\d+$/.test(version), `Invalid version ${version}`);
+assert.ok(store === 'msstore-rollout' || /^\d+\.\d+\.\d+$/.test(version), `Invalid version ${version}`);
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- TODO fix (new rule in @mifi/lint-config)
switch (store) {
case 'mas': { await mas(version); break; }
diff --git a/script/uploadArtifacts.ts b/script/uploadArtifacts.ts
index 97189efd..bdd14800 100644
--- a/script/uploadArtifacts.ts
+++ b/script/uploadArtifacts.ts
@@ -11,7 +11,7 @@ const args = yargs(hideBin(process.argv))
})
.parseSync();
-assert(args._.length > 0, 'Please provide one or more files');
+assert.ok(args._.length > 0, 'Please provide one or more files');
const client = new DefaultArtifactClient();
diff --git a/src/common/ffprobe.ts b/src/common/ffprobe.ts
index 4b0bca3a..e415e80b 100644
--- a/src/common/ffprobe.ts
+++ b/src/common/ffprobe.ts
@@ -8,279 +8,279 @@
// ffprobe -v quiet -print_format json -show_format -show_streams -show_chapters -show_error my_file.mp4
/**
- * @typedef FFprobeDisposition
- * @property {number} default 1 if the default track
- * @property {number} dub 1 if a dub track
- * @property {number} original 1 if the original track
- * @property {number} comment 1 if a comment track
- * @property {number} lyrics 1 if a lyrics track
- * @property {number} karaoke 1 if a karaoke track
- * @property {number} forced 1 if a forced track
- * @property {number} hearing_impaired 1 if a track for the hearing impaired
- * @property {number} visual_impaired 1 if a track for the visually impaired
- * @property {number} clean_effects 1 if a clean effects track (meaning not entirely understood)
- * @property {number} attached_pic 1 if an attached picture track
- * @property {number} timed_thumbnails 1 if a timed thumbnails track (perhaps like the preview thumbnails you get when scrolling over a YouTube video's seek bar)
- * @property {number} captions 1 if a captions track
- * @property {number} descriptions 1 if a descriptions track
- * @property {number} metadata 1 if a metadata track
- * @property {number} dependent 1 if a dependent track (unclear meaning)
- * @property {number} still_image 1 if a still image track
- */
+@typedef FFprobeDisposition
+@property {number} default 1 if the default track
+@property {number} dub 1 if a dub track
+@property {number} original 1 if the original track
+@property {number} comment 1 if a comment track
+@property {number} lyrics 1 if a lyrics track
+@property {number} karaoke 1 if a karaoke track
+@property {number} forced 1 if a forced track
+@property {number} hearing_impaired 1 if a track for the hearing impaired
+@property {number} visual_impaired 1 if a track for the visually impaired
+@property {number} clean_effects 1 if a clean effects track (meaning not entirely understood)
+@property {number} attached_pic 1 if an attached picture track
+@property {number} timed_thumbnails 1 if a timed thumbnails track (perhaps like the preview thumbnails you get when scrolling over a YouTube video's seek bar)
+@property {number} captions 1 if a captions track
+@property {number} descriptions 1 if a descriptions track
+@property {number} metadata 1 if a metadata track
+@property {number} dependent 1 if a dependent track (unclear meaning)
+@property {number} still_image 1 if a still image track
+*/
/**
- * @typedef FFprobeStreamTags
- * @property {string} [language] The track's language code (usually represented using a 3 letter language code, e.g.: "eng")
- * @property {string} [handler_name] The name of the handler which produced the track
- * @property {string} [vendor_id] The ID of the vendor which produced the track
- * @property {string} [encoder] The name of the encoder responsible for creating the stream
- * @property {string} [creation_time] The date (often ISO-formatted, but it may use other formats) when the media was created
- * @property {string} [comment] The comment attached to the stream
- */
+@typedef FFprobeStreamTags
+@property {string} [language] The track's language code (usually represented using a 3 letter language code, e.g.: "eng")
+@property {string} [handler_name] The name of the handler which produced the track
+@property {string} [vendor_id] The ID of the vendor which produced the track
+@property {string} [encoder] The name of the encoder responsible for creating the stream
+@property {string} [creation_time] The date (often ISO-formatted, but it may use other formats) when the media was created
+@property {string} [comment] The comment attached to the stream
+*/
/**
- * @typedef FFprobeStream
- * @property {number} index The stream index
- * @property {string} codec_name The codec's name
- * @property {string} codec_long_name The codec's long (detailed) name
- * @property {string} profile The codec profile
- * @property {'video'|'audio'|'subtitle'} codec_type The type of codec (video, audio, subtitle, etc)
- * @property {string} codec_tag_string The codec tag (technical name)
- * @property {string} codec_tag The codec tag ID
- * @property {string} [sample_fmt] The audio sample format (not present if codec_type is not "audio")
- * @property {string} [sample_rate] A string representation of an integer showing the audio sample rate (not present if codec_type is not "audio")
- * @property {number} [channels] The audio track's channel count (not present if codec_type is not "audio")
- * @property {string} [channel_layout] The audio track's channel layout (e.g. "stereo") (not present if codec_type is not "audio")
- * @property {number} [bits_per_sample] Bits per audio sample (might not be accurate, may just be 0) (not present if codec_type is not "audio")
- * @property {number} [width] The video stream width (also available for images) (not present if codec_type is not "video")
- * @property {number} [height] The stream height (also available for images) (not present if codec_type is not "video")
- * @property {number} [coded_width] The stream's coded width (shouldn't vary from "width") (not present if codec_type is not "video")
- * @property {number} [coded_height] The stream's coded height (shouldn't vary from "height") (not present if codec_type is not "video")
- * @property {number} [closed_captions] Set to 1 if closed captions are present in stream... I think (not present if codec_type is not "video")
- * @property {number} [has_b_frames] Set to 1 if the stream has b-frames... I think (not present if codec_type is not "video")
- * @property {string} [sample_aspect_ratio] The sample aspect ratio (you probably want "display_aspect_ratio") (not present if codec_type is not "video")
- * @property {string} [display_aspect_ratio] The display (real) aspect ratio (e.g. "16:9") (not present if codec_type is not "video")
- * @property {string} [pix_fmt] The pixel format used (not present if codec_type is not "video")
- * @property {number} [level] Unknown (not present if codec_type is not "video")
- * @property {string} [color_range] The color range used (e.g. "tv") (not present if codec_type is not "video")
- * @property {string} [color_space] The color space used (not present if codec_type is not "video")
- * @property {string} [color_transfer] The color transfer used (not present if codec_type is not "video")
- * @property {string} [color_primaries] The color primaries used (not present if codec_type is not "video")
- * @property {string} [chroma_location] The chroma location (not present if codec_type is not "video")
- * @property {number} [refs] Unknown (not present if codec_type is not "video")
- * @property {'true'|'false'} [is_avc] Whether the stream is AVC (not present if codec_type is not "video")
- * @property {string} [nal_length_size] Unknown string representing a number (not present if codec_type is not "video")
- * @property {string} r_frame_rate Odd formatting of the frame rate, possibly "real frame rate"? (e.g. "30/1")
- * @property {string} avg_frame_rate Odd formatting of the average frame rate (e.g. "30/1")
- * @property {string} time_base The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
- * @property {number} start_pts Unknown
- * @property {string} start_time A string representation of a floating point integer showing the start time in seconds
- * @property {number} duration_ts The stream's duration in integer timestamp format (defined by time_base)
- * @property {string} duration A string representation of a floating point integer showing the stream duration in seconds
- * @property {string} [bit_rate] The string representation of an integer showing the stream bit rate (not present on lossless formats such as FLAC)
- * @property {string} [bits_per_raw_sample] A string representation of an integer showing the bits per raw sample (not present if codec_type is not "video")
- * @property {string} nb_frames A string representation of an integer showing the total number of frames in the stream
- * @property {FFprobeDisposition} disposition The stream's disposition
- * @property {FFprobeStreamTags} [tags] The stream's tags
- */
+@typedef FFprobeStream
+@property {number} index The stream index
+@property {string} codec_name The codec's name
+@property {string} codec_long_name The codec's long (detailed) name
+@property {string} profile The codec profile
+@property {'video'|'audio'|'subtitle'} codec_type The type of codec (video, audio, subtitle, etc)
+@property {string} codec_tag_string The codec tag (technical name)
+@property {string} codec_tag The codec tag ID
+@property {string} [sample_fmt] The audio sample format (not present if codec_type is not "audio")
+@property {string} [sample_rate] A string representation of an integer showing the audio sample rate (not present if codec_type is not "audio")
+@property {number} [channels] The audio track's channel count (not present if codec_type is not "audio")
+@property {string} [channel_layout] The audio track's channel layout (e.g. "stereo") (not present if codec_type is not "audio")
+@property {number} [bits_per_sample] Bits per audio sample (might not be accurate, may just be 0) (not present if codec_type is not "audio")
+@property {number} [width] The video stream width (also available for images) (not present if codec_type is not "video")
+@property {number} [height] The stream height (also available for images) (not present if codec_type is not "video")
+@property {number} [coded_width] The stream's coded width (shouldn't vary from "width") (not present if codec_type is not "video")
+@property {number} [coded_height] The stream's coded height (shouldn't vary from "height") (not present if codec_type is not "video")
+@property {number} [closed_captions] Set to 1 if closed captions are present in stream... I think (not present if codec_type is not "video")
+@property {number} [has_b_frames] Set to 1 if the stream has b-frames... I think (not present if codec_type is not "video")
+@property {string} [sample_aspect_ratio] The sample aspect ratio (you probably want "display_aspect_ratio") (not present if codec_type is not "video")
+@property {string} [display_aspect_ratio] The display (real) aspect ratio (e.g. "16:9") (not present if codec_type is not "video")
+@property {string} [pix_fmt] The pixel format used (not present if codec_type is not "video")
+@property {number} [level] Unknown (not present if codec_type is not "video")
+@property {string} [color_range] The color range used (e.g. "tv") (not present if codec_type is not "video")
+@property {string} [color_space] The color space used (not present if codec_type is not "video")
+@property {string} [color_transfer] The color transfer used (not present if codec_type is not "video")
+@property {string} [color_primaries] The color primaries used (not present if codec_type is not "video")
+@property {string} [chroma_location] The chroma location (not present if codec_type is not "video")
+@property {number} [refs] Unknown (not present if codec_type is not "video")
+@property {'true'|'false'} [is_avc] Whether the stream is AVC (not present if codec_type is not "video")
+@property {string} [nal_length_size] Unknown string representing a number (not present if codec_type is not "video")
+@property {string} r_frame_rate Odd formatting of the frame rate, possibly "real frame rate"? (e.g. "30/1")
+@property {string} avg_frame_rate Odd formatting of the average frame rate (e.g. "30/1")
+@property {string} time_base The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
+@property {number} start_pts Unknown
+@property {string} start_time A string representation of a floating point integer showing the start time in seconds
+@property {number} duration_ts The stream's duration in integer timestamp format (defined by time_base)
+@property {string} duration A string representation of a floating point integer showing the stream duration in seconds
+@property {string} [bit_rate] The string representation of an integer showing the stream bit rate (not present on lossless formats such as FLAC)
+@property {string} [bits_per_raw_sample] A string representation of an integer showing the bits per raw sample (not present if codec_type is not "video")
+@property {string} nb_frames A string representation of an integer showing the total number of frames in the stream
+@property {FFprobeDisposition} disposition The stream's disposition
+@property {FFprobeStreamTags} [tags] The stream's tags
+*/
/**
- * @typedef FFprobeChapterTags
- * @property {string} title The chapter title
- */
+@typedef FFprobeChapterTags
+@property {string} title The chapter title
+*/
/**
- * @typedef FFprobeChapter
- * @property {number} id The chapter ID
- * @property {string} time_base The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
- * @property {number} start When the chapter starts in integer timestamp format (defined by time_base)
- * @property {string} start_time The string representation of a floating point integer showing when the chapter starts in seconds
- * @property {number} end When the chapter end in integer timestamp format (defined by time_base)
- * @property {string} end_time The string representation of a floating point integer showing when the chapter ends in seconds
- * @property {FFprobeChapterTags} tags The chapter's tags
- */
+@typedef FFprobeChapter
+@property {number} id The chapter ID
+@property {string} time_base The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
+@property {number} start When the chapter starts in integer timestamp format (defined by time_base)
+@property {string} start_time The string representation of a floating point integer showing when the chapter starts in seconds
+@property {number} end When the chapter end in integer timestamp format (defined by time_base)
+@property {string} end_time The string representation of a floating point integer showing when the chapter ends in seconds
+@property {FFprobeChapterTags} tags The chapter's tags
+*/
/**
- * @typedef FFprobeFormatTags
- * @property {string} major_brand Not clear, probably the media type brand, but not sure
- * @property {string} minor_version The brand version perhaps, but not sure
- * @property {string} compatible_brands The brands that are compatible with the referenced brands perhaps, but not sure
- * @property {string} [title] The media's title (song metadata uses an all uppercase version)
- * @property {string} [artist] The media artist (song metadata uses an all uppercase version)
- * @property {string} [date] The media's creation date, seems to be in YYYYMMDD format (song metadata uses an all uppercase version)
- * @property {string} [encoder] The name of the encoder responsible for encoding the media
- * @property {string} [comment] The comment attached to the file
- * @property {string} [description] The description attached to the file
- * @property {string} [creation_time] The ISO-formatted date (although it may use other formats) when the media was created
- * @property {string} [ALBUM] The album (only present in audio files)
- * @property {string} [album_artist] The album arist (only present in audio files)
- * @property {string} [ALBUMARTISTSORT] The album artist name used for sorting probably (only present in audio files)
- * @property {string} [ARTIST] The song artist (only present in audio files)
- * @property {string} [DATE] The date when the song was created (no particular format, often the year) (only present in audio files)
- * @property {string} [disc] The string representation of an integer showing the song's disc number (only present in audio files)
- * @property {string} [DISCTOTAL] The string representation of an integer showing the total number of discs comprising the album the song is in (only present in audio files)
- * @property {string} [ISRC] The song's International Standard Recording Code
- * @property {string} [GENRE] The song's genre (only present in audio files)
- * @property {string} [TITLE] The song's title (only present in audio files)
- * @property {string} [track] The string representation of an integer showing the song's track number (only present in audio files)
- * @property {string} [TRACKTOTAL] The string representation of an integer showing the total number of tracks in the album the song is in (only present in audio files)
- * @property {string} [YEAR] The string representation of an integer showing the year the song was created (only present in audio files)
- * @property {string} [BPM] The string representation of an integer showing the song's BPM (only present in audio files)
- * @property {string} [PUBLISHER] The song's publisher (only present in audio files)
- */
+@typedef FFprobeFormatTags
+@property {string} major_brand Not clear, probably the media type brand, but not sure
+@property {string} minor_version The brand version perhaps, but not sure
+@property {string} compatible_brands The brands that are compatible with the referenced brands perhaps, but not sure
+@property {string} [title] The media's title (song metadata uses an all uppercase version)
+@property {string} [artist] The media artist (song metadata uses an all uppercase version)
+@property {string} [date] The media's creation date, seems to be in YYYYMMDD format (song metadata uses an all uppercase version)
+@property {string} [encoder] The name of the encoder responsible for encoding the media
+@property {string} [comment] The comment attached to the file
+@property {string} [description] The description attached to the file
+@property {string} [creation_time] The ISO-formatted date (although it may use other formats) when the media was created
+@property {string} [ALBUM] The album (only present in audio files)
+@property {string} [album_artist] The album arist (only present in audio files)
+@property {string} [ALBUMARTISTSORT] The album artist name used for sorting probably (only present in audio files)
+@property {string} [ARTIST] The song artist (only present in audio files)
+@property {string} [DATE] The date when the song was created (no particular format, often the year) (only present in audio files)
+@property {string} [disc] The string representation of an integer showing the song's disc number (only present in audio files)
+@property {string} [DISCTOTAL] The string representation of an integer showing the total number of discs comprising the album the song is in (only present in audio files)
+@property {string} [ISRC] The song's International Standard Recording Code
+@property {string} [GENRE] The song's genre (only present in audio files)
+@property {string} [TITLE] The song's title (only present in audio files)
+@property {string} [track] The string representation of an integer showing the song's track number (only present in audio files)
+@property {string} [TRACKTOTAL] The string representation of an integer showing the total number of tracks in the album the song is in (only present in audio files)
+@property {string} [YEAR] The string representation of an integer showing the year the song was created (only present in audio files)
+@property {string} [BPM] The string representation of an integer showing the song's BPM (only present in audio files)
+@property {string} [PUBLISHER] The song's publisher (only present in audio files)
+*/
/**
- * @typedef FFprobeFormat
- * @property {string} filename The path of the probed file (as specified in the input file argument)
- * @property {number} nb_streams The total number of streams present
- * @property {number} nb_programs The total number of programs present
- * @property {string} format_name The name of the format (a comma separated list of applicable file extensions for the format)
- * @property {string} format_long_name The long (detailed) name of the format
- * @property {string} start_time The string representation of a floating point integer showing the file's starting time
- * @property {string} duration The string representation of a floating point integer showing the file's duration in seconds (seems to be a non-accurate, rounded version of the real duration)
- * @property {string} size The string representation of a long integer showing the file's size in bytes
- * @property {string} bit_rate The string representation of a long integer showing the file's stated bitrate (may vary between streams, probably applies to just video if a video file)
- * @property {number} probe_score A score of how confident FFprobe is of the format, 0 to 100. https://stackoverflow.com/questions/25257986/what-does-probe-score-mean-in-ffprobe-output
- * @property {FFprobeFormatTags} [tags] The format's tags
- */
+@typedef FFprobeFormat
+@property {string} filename The path of the probed file (as specified in the input file argument)
+@property {number} nb_streams The total number of streams present
+@property {number} nb_programs The total number of programs present
+@property {string} format_name The name of the format (a comma separated list of applicable file extensions for the format)
+@property {string} format_long_name The long (detailed) name of the format
+@property {string} start_time The string representation of a floating point integer showing the file's starting time
+@property {string} duration The string representation of a floating point integer showing the file's duration in seconds (seems to be a non-accurate, rounded version of the real duration)
+@property {string} size The string representation of a long integer showing the file's size in bytes
+@property {string} bit_rate The string representation of a long integer showing the file's stated bitrate (may vary between streams, probably applies to just video if a video file)
+@property {number} probe_score A score of how confident FFprobe is of the format, 0 to 100. https://stackoverflow.com/questions/25257986/what-does-probe-score-mean-in-ffprobe-output
+@property {FFprobeFormatTags} [tags] The format's tags
+*/
/**
- * @typedef FFprobeProbeError
- * @property {number} code The error code
- * @property {string} string The error message
- */
+@typedef FFprobeProbeError
+@property {number} code The error code
+@property {string} string The error message
+*/
/**
- * @typedef FFprobeProbeResult
- * @property {Array<FFprobeStream>} [streams] The probed file's streams (-show_streams flag required)
- * @property {Array<FFprobeChapter>} [chapters] The probed file's chapters (-show_chapters flag required)
- * @property {FFprobeFormat} [format] The probed file's format data (-show_format flag required)
- * @property {FFprobeProbeError} [error] The error that occurred when trying to probe the file (-show_error flag required)
- */
+@typedef FFprobeProbeResult
+@property {Array<FFprobeStream>} [streams] The probed file's streams (-show_streams flag required)
+@property {Array<FFprobeChapter>} [chapters] The probed file's chapters (-show_chapters flag required)
+@property {FFprobeFormat} [format] The probed file's format data (-show_format flag required)
+@property {FFprobeProbeError} [error] The error that occurred when trying to probe the file (-show_error flag required)
+*/
/**
- * The "disposition" field on an FFprobe response stream object
- */
+The "disposition" field on an FFprobe response stream object
+*/
export interface FFprobeStreamDisposition {
/**
- * 1 if the default track
- */
+ 1 if the default track
+ */
default: 1 | 0,
/**
- * 1 if a dub track
- */
+ 1 if a dub track
+ */
dub: 1 | 0,
/**
- * 1 if the original track
- */
+ 1 if the original track
+ */
original: 1 | 0,
/**
- * 1 if a comment track
- */
+ 1 if a comment track
+ */
comment: 1 | 0,
/**
- * 1 if a lyrics track
- */
+ 1 if a lyrics track
+ */
lyrics: 1 | 0,
/**
- * 1 if a karaoke track
- */
+ 1 if a karaoke track
+ */
karaoke: 1 | 0,
/**
- * 1 if a forced track
- */
+ 1 if a forced track
+ */
forced: 1 | 0,
/**
- * 1 if a track for the hearing impaired
- */
+ 1 if a track for the hearing impaired
+ */
hearing_impaired: 1 | 0,
/**
- * 1 if a track for the visually impaired
- */
+ 1 if a track for the visually impaired
+ */
visual_impaired: 1 | 0,
/**
- * 1 if a clean effects track
- */
+ 1 if a clean effects track
+ */
clean_effects: 1 | 0,
/**
- * 1 if an attached picture track
- */
+ 1 if an attached picture track
+ */
attached_pic: 1 | 0,
/**
- * 1 if a timed thumbnails track (perhaps like the preview thumbnails you get when scrolling over a YouTube video's seek bar)
- */
+ 1 if a timed thumbnails track (perhaps like the preview thumbnails you get when scrolling over a YouTube video's seek bar)
+ */
timed_thumbnails: 1 | 0,
/**
- * 1 if a captions track
- */
+ 1 if a captions track
+ */
captions: 1 | 0,
/**
- * 1 if a descriptions track
- */
+ 1 if a descriptions track
+ */
descriptions: 1 | 0,
/**
- * 1 if a metadata track
- */
+ 1 if a metadata track
+ */
metadata: 1 | 0,
/**
- * 1 if a dependent track (unclear meaning)
- */
+ 1 if a dependent track (unclear meaning)
+ */
dependent: 1 | 0,
/**
- * 1 if a still image track
- */
+ 1 if a still image track
+ */
still_image: 1 | 0
}
/**
- * The "tags" field on an FFprobe response stream object
- */
+The "tags" field on an FFprobe response stream object
+*/
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export type FFprobeStreamTags = {
/**
- * The track's language (usually represented using a 3 letter language code, e.g.: "eng")
- */
+ The track's language (usually represented using a 3 letter language code, e.g.: "eng")
+ */
language?: string,
/**
- * The name of the handler which produced the track
- */
+ The name of the handler which produced the track
+ */
handler_name?: string,
/**
- * The ID of the vendor which produced the track
- */
+ The ID of the vendor which produced the track
+ */
vendor_id?: string,
/**
- * The name of the encoder responsible for creating the stream
- */
+ The name of the encoder responsible for creating the stream
+ */
encoder?: string,
/**
- * The date (often ISO-formatted, but it may use other formats) when the media was created
- */
+ The date (often ISO-formatted, but it may use other formats) when the media was created
+ */
creation_time?: string,
/**
- * The comment attached to the stream
- */
+ The comment attached to the stream
+ */
comment?: string
rotate?: string,
@@ -290,496 +290,496 @@ export type FFprobeStreamTags = {
} & Record<string, string>;
/**
- * An FFprobe response stream object
- */
+An FFprobe response stream object
+*/
export interface FFprobeStream {
/**
- * The stream index
- */
+ The stream index
+ */
index: number,
/**
- * The codec's name
- */
+ The codec's name
+ */
codec_name: string,
/**
- * The codec's long (detailed) name
- */
+ The codec's long (detailed) name
+ */
codec_long_name: string,
/**
- * The codec profile
- */
+ The codec profile
+ */
profile: string,
/**
- * The type of codec (video, audio, subtitle, etc.)
- */
+ The type of codec (video, audio, subtitle, etc.)
+ */
codec_type: 'video' | 'audio' | 'subtitle' | 'attachment' | 'data',
/**
- * The codec tag (technical name)
- */
+ The codec tag (technical name)
+ */
codec_tag_string: string,
/**
- * The codec tag ID
- */
+ The codec tag ID
+ */
codec_tag: string,
/**
- * The audio sample format (not present if codec_type is not "audio")
- */
+ The audio sample format (not present if codec_type is not "audio")
+ */
sample_fmt?: string,
/**
- * A string representation of an integer showing the audio sample rate (not present if codec_type is not "audio")
- */
+ A string representation of an integer showing the audio sample rate (not present if codec_type is not "audio")
+ */
sample_rate?: string,
/**
- * The audio track's channel count (not present if codec_type is not "audio")
- */
+ The audio track's channel count (not present if codec_type is not "audio")
+ */
channels?: number,
/**
- * The audio track's channel layout (e.g. "stereo") (not present if codec_type is not "audio")
- */
+ The audio track's channel layout (e.g. "stereo") (not present if codec_type is not "audio")
+ */
channel_layout?: string,
/**
- * Bits per audio sample (might not be accurate, may just be 0) (not present if codec_type is not "audio")
- */
+ Bits per audio sample (might not be accurate, may just be 0) (not present if codec_type is not "audio")
+ */
bits_per_sample?: number,
/**
- * The video stream width (also available for images) (not present if codec_type is not "video")
- */
+ The video stream width (also available for images) (not present if codec_type is not "video")
+ */
width?: number,
/**
- * The stream height (also available for images) (not present if codec_type is not "video")
- */
+ The stream height (also available for images) (not present if codec_type is not "video")
+ */
height?: number,
/**
- * The stream's coded width (shouldn't vary from "width") (not present if codec_type is not "video")
- */
+ The stream's coded width (shouldn't vary from "width") (not present if codec_type is not "video")
+ */
coded_width?: number,
/**
- * The stream's coded height (shouldn't vary from "height") (not present if codec_type is not "video")
- */
+ The stream's coded height (shouldn't vary from "height") (not present if codec_type is not "video")
+ */
coded_height?: number,
/**
- * Set to 1 if closed captions are present in stream... I think (not present if codec_type is not "video")
- */
+ Set to 1 if closed captions are present in stream... I think (not present if codec_type is not "video")
+ */
closed_captions?: 1 | 0 | number,
/**
- * Set to 1 if the stream has b-frames... I think (not present if codec_type is not "video")
- */
+ Set to 1 if the stream has b-frames... I think (not present if codec_type is not "video")
+ */
has_b_frames?: 1 | 0 | number,
/**
- * The sample aspect ratio (you probably want "display_aspect_ratio") (not present if codec_type is not "video")
- */
+ The sample aspect ratio (you probably want "display_aspect_ratio") (not present if codec_type is not "video")
+ */
sample_aspect_ratio?: string,
/**
- * The display (real) aspect ratio (e.g. "16:9") (not present if codec_type is not "video")
- */
+ The display (real) aspect ratio (e.g. "16:9") (not present if codec_type is not "video")
+ */
display_aspect_ratio?: string,
/**
- * The pixel format used (not present if codec_type is not "video")
- */
+ The pixel format used (not present if codec_type is not "video")
+ */
pix_fmt?: string,
/**
- * Unknown (not present if codec_type is not "video")
- */
+ Unknown (not present if codec_type is not "video")
+ */
level?: number,
/**
- * The color range used (e.g. "tv") (not present if codec_type is not "video")
- */
+ The color range used (e.g. "tv") (not present if codec_type is not "video")
+ */
color_range?: string,
/**
- * The color space used (not present if codec_type is not "video")
- */
+ The color space used (not present if codec_type is not "video")
+ */
color_space?: string,
/**
- * The color transfer used (not present if codec_type is not "video")
- */
+ The color transfer used (not present if codec_type is not "video")
+ */
color_transfer?: string,
/**
- * The color primaries used (not present if codec_type is not "video")
- */
+ The color primaries used (not present if codec_type is not "video")
+ */
color_primaries?: string,
/**
- * The chroma location (not present if codec_type is not "video")
- */
+ The chroma location (not present if codec_type is not "video")
+ */
chroma_location?: string,
/**
- * Unknown (not present if codec_type is not "video")
- */
+ Unknown (not present if codec_type is not "video")
+ */
refs?: number,
/**
- * Whether the stream is AVC (not present if codec_type is not "video")
- */
+ Whether the stream is AVC (not present if codec_type is not "video")
+ */
is_avc?: 'true' | 'false',
/**
- * Unknown string representing a number (not present if codec_type is not "video")
- */
+ Unknown string representing a number (not present if codec_type is not "video")
+ */
nal_length_size?: string,
/**
- * Odd formatting of the frame rate, possibly "real frame rate"? (e.g. "30/1")
- */
+ Odd formatting of the frame rate, possibly "real frame rate"? (e.g. "30/1")
+ */
r_frame_rate: string,
/**
- * Odd formatting of the average frame rate (e.g. "30/1")
- */
+ Odd formatting of the average frame rate (e.g. "30/1")
+ */
avg_frame_rate: string,
/**
- * The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
- */
+ The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
+ */
time_base: string,
/**
- * Unknown
- */
+ Unknown
+ */
start_pts: number,
/**
- * A string representation of a floating point integer showing the start time in seconds
- */
+ A string representation of a floating point integer showing the start time in seconds
+ */
start_time: string,
/**
- * The stream's duration in integer timestamp format (defined by time_base)
- */
+ The stream's duration in integer timestamp format (defined by time_base)
+ */
duration_ts: number,
/**
- * A string representation of a floating point integer showing the stream duration in seconds
- */
+ A string representation of a floating point integer showing the stream duration in seconds
+ */
duration: string,
/**
- * The string representation of an integer showing the stream bit rate (not present on lossless formats such as FLAC)
- */
+ The string representation of an integer showing the stream bit rate (not present on lossless formats such as FLAC)
+ */
bit_rate?: string,
/**
- * A string representation of an integer showing the bits per raw sample (not present if codec_type is not "video")
- */
+ A string representation of an integer showing the bits per raw sample (not present if codec_type is not "video")
+ */
bits_per_raw_sample?: string,
/**
- * A string representation of an integer showing the total number of frames in the stream
- */
+ A string representation of an integer showing the total number of frames in the stream
+ */
nb_frames: string,
/**
- * The stream's disposition
- */
+ The stream's disposition
+ */
disposition: FFprobeStreamDisposition,
/**
- * The stream's tags
- */
+ The stream's tags
+ */
tags?: FFprobeStreamTags
}
/**
- * The "tags" field on an FFprobe response chapter object
- */
+The "tags" field on an FFprobe response chapter object
+*/
export interface FFprobeChapterTags {
/**
- * The chapter title
- */
+ The chapter title
+ */
title: string
}
/**
- * An FFprobe response chapter object
- */
+An FFprobe response chapter object
+*/
export interface FFprobeChapter {
/**
- * The chapter ID
- */
+ The chapter ID
+ */
id: number,
/**
- * The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
- */
+ The division equation to use for converting integer representations of timestamps into seconds (e.g. "1/30000" turns 80632552 into 2687.751733 seconds)
+ */
time_base: string,
/**
- * When the chapter starts in integer timestamp format (defined by time_base)
- */
+ When the chapter starts in integer timestamp format (defined by time_base)
+ */
start: number,
/**
- * The string representation of a floating point integer showing when the chapter starts in seconds
- */
+ The string representation of a floating point integer showing when the chapter starts in seconds
+ */
start_time: string,
/**
- * When the chapter end in integer timestamp format (defined by time_base)
- */
+ When the chapter end in integer timestamp format (defined by time_base)
+ */
end: number,
/**
- * The string representation of a floating point integer showing when the chapter ends in seconds
- */
+ The string representation of a floating point integer showing when the chapter ends in seconds
+ */
end_time: string,
/**
- * The chapter's tags
- */
+ The chapter's tags
+ */
tags?: FFprobeChapterTags
}
/**
- * The "tags" field on an FFprobe response format object
- */
+The "tags" field on an FFprobe response format object
+*/
export type FFprobeFormatTags = {
/**
- * Not clear, probably the media type brand, but not sure
- */
+ Not clear, probably the media type brand, but not sure
+ */
major_brand: string,
/**
- * The brand version perhaps, but not sure
- */
+ The brand version perhaps, but not sure
+ */
minor_version: string,
/**
- * The brands that are compatible with the referenced brands perhaps, but not sure
- */
+ The brands that are compatible with the referenced brands perhaps, but not sure
+ */
compatible_brands: string,
/**
- * The media's title (song metadata uses an all uppercase version)
- */
+ The media's title (song metadata uses an all uppercase version)
+ */
title?: string,
/**
- * The media artist (song metadata uses an all uppercase version)
- */
+ The media artist (song metadata uses an all uppercase version)
+ */
artist?: string,
/**
- * The media's creation date, seems to be in YYYYMMDD format (song metadata uses an all uppercase version)
- */
+ The media's creation date, seems to be in YYYYMMDD format (song metadata uses an all uppercase version)
+ */
date?: string,
/**
- * The name of the encoder responsible for encoding the media
- */
+ The name of the encoder responsible for encoding the media
+ */
encoder?: string,
/**
- * The comment attached to the file
- */
+ The comment attached to the file
+ */
comment?: string,
/**
- * The description attached to the file
- */
+ The description attached to the file
+ */
description?: string,
/**
- * The ISO-formatted date (although it may use other formats) when the media was created
- */
+ The ISO-formatted date (although it may use other formats) when the media was created
+ */
creation_time?: string,
/**
- * The album (only present in audio files)
- */
+ The album (only present in audio files)
+ */
ALBUM?: string,
/**
- * The album arist (only present in audio files)
- */
+ The album arist (only present in audio files)
+ */
album_artist?: string,
/**
- * The album artist name used for sorting probably (only present in audio files)
- */
+ The album artist name used for sorting probably (only present in audio files)
+ */
ALBUMARTISTSORT?: string,
/**
- * The song artist (only present in audio files)
- */
+ The song artist (only present in audio files)
+ */
ARTIST?: string,
/**
- * The date when the song was created (no particular format, often the year) (only present in audio files)
- */
+ The date when the song was created (no particular format, often the year) (only present in audio files)
+ */
DATE?: string,
/**
- * The string representation of an integer showing the song's disc number (only present in audio files)
- */
+ The string representation of an integer showing the song's disc number (only present in audio files)
+ */
disc?: string,
/**
- * The string representation of an integer showing the total number of discs comprising the album the song is in (only present in audio files)
- */
+ The string representation of an integer showing the total number of discs comprising the album the song is in (only present in audio files)
+ */
DISCTOTAL?: string,
/**
- * The song's International Standard Recording Code
- */
+ The song's International Standard Recording Code
+ */
ISRC?: string,
/**
- * The song's genre (only present in audio files)
- */
+ The song's genre (only present in audio files)
+ */
GENRE?: string,
/**
- * The song's title (only present in audio files)
- */
+ The song's title (only present in audio files)
+ */
TITLE?: string,
/**
- * The string representation of an integer showing the song's track number (only present in audio files)
- */
+ The string representation of an integer showing the song's track number (only present in audio files)
+ */
track?: string,
/**
- * The string representation of an integer showing the total number of tracks in the album the song is in (only present in audio files)
- */
+ The string representation of an integer showing the total number of tracks in the album the song is in (only present in audio files)
+ */
TRACKTOTAL?: string,
/**
- * The string representation of an integer showing the year the song was created (only present in audio files)
- */
+ The string representation of an integer showing the year the song was created (only present in audio files)
+ */
YEAR?: string,
/**
- * The string representation of an integer showing the song's BPM (only present in audio files)
- */
+ The string representation of an integer showing the song's BPM (only present in audio files)
+ */
BPM?: string,
/**
- * The song's publisher (only present in audio files)
- */
+ The song's publisher (only present in audio files)
+ */
PUBLISHER?: string
} & Record<string, string>;
/**
- * An FFprobe response format object
- */
+An FFprobe response format object
+*/
export interface FFprobeFormat {
/**
- * The path of the probed file (as specified in the input file argument)
- */
+ The path of the probed file (as specified in the input file argument)
+ */
filename: string,
/**
- * The total number of streams present
- */
+ The total number of streams present
+ */
nb_streams: number,
/**
- * The total number of programs present
- */
+ The total number of programs present
+ */
nb_programs: number,
/**
- * The name of the format (a comma separated list of applicable file extensions for the format)
- */
+ The name of the format (a comma separated list of applicable file extensions for the format)
+ */
format_name: string,
/**
- * The long (detailed) name of the format
- */
+ The long (detailed) name of the format
+ */
format_long_name: string,
/**
- * The string representation of a floating point integer showing the file's starting time
- */
+ The string representation of a floating point integer showing the file's starting time
+ */
start_time: string,
/**
- * The string representation of a floating point integer showing the file's duration in seconds (seems to be a non-accurate, rounded version of the real duration)
- */
+ The string representation of a floating point integer showing the file's duration in seconds (seems to be a non-accurate, rounded version of the real duration)
+ */
duration: string,
/**
- * The string representation of a long integer showing the file's size in bytes
- */
+ The string representation of a long integer showing the file's size in bytes
+ */
size: string,
/**
- * The string representation of a long integer showing the file's stated bitrate (may vary between streams, probably applies to just video if a video file)
- */
+ The string representation of a long integer showing the file's stated bitrate (may vary between streams, probably applies to just video if a video file)
+ */
bit_rate: string,
/**
- * A score of how confident FFprobe is of the format, 0 to 100. https://stackoverflow.com/questions/25257986/what-does-probe-score-mean-in-ffprobe-output
- */
+ A score of how confident FFprobe is of the format, 0 to 100. https://stackoverflow.com/questions/25257986/what-does-probe-score-mean-in-ffprobe-output
+ */
probe_score: number,
/**
- * The format's tags
- */
+ The format's tags
+ */
tags?: FFprobeFormatTags
}
/**
- * An FFprobe error object
- */
+An FFprobe error object
+*/
export interface FFprobeProbeError {
/**
- * The error code
- */
+ The error code
+ */
code: number,
/**
- * The error message
- */
+ The error message
+ */
string: string
}
/**
- * An FFprobe probe result object
- */
+An FFprobe probe result object
+*/
export interface FFprobeProbeResult {
/**
- * The probed file's streams (-show_streams flag required)
- */
+ The probed file's streams (-show_streams flag required)
+ */
streams?: FFprobeStream[],
/**
- * The probed file's chapters (-show_chapters flag required)
- */
+ The probed file's chapters (-show_chapters flag required)
+ */
chapters?: FFprobeChapter[],
/**
- * The probed file's format data (-show_format flag required)
- */
+ The probed file's format data (-show_format flag required)
+ */
format?: FFprobeFormat,
/**
- * The error that occurred when trying to probe the file (-show_error flag required)
- */
+ The error that occurred when trying to probe the file (-show_error flag required)
+ */
error?: FFprobeProbeError
}
diff --git a/src/common/types.ts b/src/common/types.ts
index 08a5abea..54d8bae0 100644
--- a/src/common/types.ts
+++ b/src/common/types.ts
@@ -16,9 +16,9 @@ export const ffmpegHwAccelSchema = z.enum(['none', 'auto', 'vdpau', 'dxva2', 'd3
export type FfmpegHwAccel = z.infer<typeof ffmpegHwAccelSchema>;
/**
- * The parts of an audio stream's ffprobe data needed to decide whether its channel layout
- * has to be fixed up before ffmpeg can resample or downmix it. See `getFixChannelLayoutFilter`.
- */
+The parts of an audio stream's ffprobe data needed to decide whether its channel layout
+has to be fixed up before ffmpeg can resample or downmix it. See `getFixChannelLayoutFilter`.
+*/
export interface AudioChannelInfo {
channels?: number | undefined,
channelLayout?: string | undefined,
@@ -82,11 +82,17 @@ export const configSchema = z.object({
autoLoadTimecode: z.boolean(),
segmentsToChapters: z.boolean(),
simpleMode: z.boolean(),
- /** todo: rename to cutFileTemplate */
+ /**
+ todo: rename to cutFileTemplate
+ */
outSegTemplate: z.string().or(z.undefined()),
- /** todo: rename to cutMergedFileTemplate */
+ /**
+ todo: rename to cutMergedFileTemplate
+ */
mergedFileTemplate: z.string().or(z.undefined()),
- /** todo: rename to mergedFileTemplate */
+ /**
+ todo: rename to mergedFileTemplate
+ */
mergedFilesTemplate: z.string().or(z.undefined()),
keyboardSeekAccFactor: z.number(),
keyboardNormalSeekSpeed: z.number(),
diff --git a/src/common/userTypes.ts b/src/common/userTypes.ts
index bb954a3c..55211356 100644
--- a/src/common/userTypes.ts
+++ b/src/common/userTypes.ts
@@ -5,30 +5,44 @@
// https://losslesscut.app/docs/file-name-template
/**
- * 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.
- */
+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. */
+ /**
+ The file's name without the file system path.
+ */
name: string,
- /** The full filesystem path of the file. */
+ /**
+ The full filesystem path of the file.
+ */
path: string,
- /** File size in bytes. */
+ /**
+ File size in bytes.
+ */
size?: number | bigint | undefined, // File size in bytes
- /** The last time this file was accessed. */
+ /**
+ The last time this file was accessed.
+ */
atime?: number | undefined,
- /** The last time this file was modified. */
+ /**
+ The last time this file was modified.
+ */
mtime?: number | undefined,
- /** The last time the file status was changed. */
+ /**
+ The last time the file status was changed.
+ */
ctime?: number | undefined,
- /** The creation time of this file. */
+ /**
+ The creation time of this file.
+ */
birthtime?: number | undefined,
}
/**
- * The global context made available to the user in the export file name template.
- * See docs/file-name-template.md documentation for details.
- */
+The global context made available to the user in the export file name template.
+See docs/file-name-template.md documentation for details.
+*/
export interface FileNameTemplateContext {
FILENAME: string;
FILES: SourceFile[];
@@ -51,19 +65,31 @@ export interface FileNameTemplateContext {
}
/**
- * See https://losslesscut.app/docs/expressions
- */
+See https://losslesscut.app/docs/expressions
+*/
export interface Segment {
- /** Index of the segment in the segment list, starting with 0 */
+ /**
+ Index of the segment in the segment list, starting with 0
+ */
index: number,
- /** Name of the segment */
+ /**
+ Name of the segment
+ */
label: string,
- /** Segment start time in seconds */
+ /**
+ Segment start time in seconds
+ */
start: number,
- /** Segment end time in seconds, or undefined for markers */
+ /**
+ Segment end time in seconds, or undefined for markers
+ */
end?: number | undefined,
- /** Duration in seconds (effectively `end` minus `start` or 0 for markers) */
+ /**
+ Duration in seconds (effectively `end` minus `start` or 0 for markers)
+ */
duration: number,
- /** Tags associated with this segment */
+ /**
+ Tags associated with this segment
+ */
tags: Record<string, string>,
}
diff --git a/src/main/configStore.ts b/src/main/configStore.ts
index 0ead7a7b..b52b45ef 100644
--- a/src/main/configStore.ts
+++ b/src/main/configStore.ts
@@ -221,7 +221,7 @@ async function tryCreateStore({ customStoragePath }: { customStoragePath: string
try {
store = new Store({
defaults,
- ...(customStoragePath != null ? { cwd: customStoragePath } : {}),
+ ...(customStoragePath != null && { cwd: customStoragePath }),
});
return;
} catch (err) {
@@ -295,7 +295,7 @@ export async function init({ customConfigDir }: { customConfigDir: string | unde
const newBindings = keyBindings.map(({ keys: keysOrig, keysStr, action }) => {
try {
- assert(keysOrig.length > 0 && keysOrig.every((k) => k.length > 0), 'Invalid keys');
+ assert.ok(keysOrig.length > 0 && keysOrig.every((k) => k.length > 0), 'Invalid keys');
const map: Record<string, string> = {
/* eslint-disable @stylistic/quote-props */
@@ -410,7 +410,7 @@ export async function init({ customConfigDir }: { customConfigDir: string | unde
return [k];
}).map((k) => {
const mapped = map[k.toLowerCase()];
- assert(mapped != null, `Unknown key: ${k}`);
+ assert.ok(mapped != null, `Unknown key: ${k}`);
return mapped;
});
diff --git a/src/main/ffmpeg.ts b/src/main/ffmpeg.ts
index 20cd9c19..0f9320a7 100644
--- a/src/main/ffmpeg.ts
+++ b/src/main/ffmpeg.ts
@@ -79,8 +79,8 @@ export async function checkFfExists(cmd: FfCommand) {
const getFfprobePath = () => getFfPath('ffprobe');
/**
- * ⚠️ Do not use directly when running ffmpeg, because we need to add certain options before running, like `LD_LIBRARY_PATH` on linux
- */
+⚠️ Do not use directly when running ffmpeg, because we need to add certain options before running, like `LD_LIBRARY_PATH` on linux
+*/
export const getFfmpegPath = () => getFfPath('ffmpeg');
export function abortFfmpegs() {
@@ -176,7 +176,7 @@ export async function runFfmpegConcat({ ffmpegArgs, concatTxt, totalDuration, on
handleProgress(process, totalDuration, onProgress);
- assert(process.stdin != null);
+ assert.ok(process.stdin != null);
stringToStream(concatTxt).pipe(process.stdin);
return process;
@@ -188,7 +188,7 @@ export async function runFfmpegWithProgress({ ffmpegArgs, duration, onProgress }
onProgress: (a: number) => void,
}) {
const process = runFfmpegProcess(ffmpegArgs);
- assert(process.stderr != null);
+ assert.ok(process.stderr != null);
handleProgress(process, duration, onProgress);
return process;
}
@@ -262,8 +262,8 @@ export async function renderWaveformPng({ filePath, start, duration, resample, c
try {
ps1 = runFfmpegProcess(args1, { buffer: false, ...(timeout != null && { timeout }) }, { logCli: false });
ps2 = runFfmpegProcess(args2, timeout != null ? { timeout } : undefined, { logCli: false });
- assert(ps1.stdout != null);
- assert(ps2.stdin != null);
+ assert.ok(ps1.stdout != null);
+ assert.ok(ps2.stdin != null);
ps1.stdout.pipe(ps2.stdin);
const { stdout } = await ps2;
@@ -323,14 +323,14 @@ export async function detectSceneChanges({ filePath, streamId, minChange, onProg
handleProgress(process, to - from, onProgress);
- assert(process.stdout != null);
+ assert.ok(process.stdout != null);
const rl = readline.createInterface({ input: process.stdout });
let lastTime: number | undefined;
rl.on('line', (line) => {
// eslint-disable-next-line unicorn/better-regex
- const match = line.match(/^frame:\d+\s+pts:\d+\s+pts_time:([\d.]+)/);
+ const match = /^frame:\d+\s+pts:\d+\s+pts_time:([\d.]+)/.exec(line);
if (!match) return;
const time = parseFloat(match[1]!);
if (!Number.isNaN(time)) {
diff --git a/src/main/ffmpegUtil.ts b/src/main/ffmpegUtil.ts
index 3bbd8bcf..c0b236c2 100644
--- a/src/main/ffmpegUtil.ts
+++ b/src/main/ffmpegUtil.ts
@@ -1,8 +1,8 @@
/**
- * Convert 0-1 quality to ffmpeg jpeg quality scale
- * @param quality 0-1 where 1 is best quality
- * @returns ffmpeg jpeg quality value
- */
+Convert 0-1 quality to ffmpeg jpeg quality scale
+@param quality 0-1 where 1 is best quality
+@returns ffmpeg jpeg quality value
+*/
export function getFfmpegJpegQuality(quality: number) {
// Normal range for JPEG is 2-31 with 31 being the worst quality.
const qMin = 2;
diff --git a/src/main/httpServer.ts b/src/main/httpServer.ts
index 51a4e892..5b16f12d 100644
--- a/src/main/httpServer.ts
+++ b/src/main/httpServer.ts
@@ -43,14 +43,14 @@ export default ({ port, onKeyboardAction, onAwaitAppEvent }: {
// eslint-disable-next-line prefer-destructuring
const action = req.params['action'];
const parameters = req.body as unknown;
- assert(action != null);
+ assert.ok(action != null);
await onKeyboardAction(action, [parameters]);
res.end();
});
apiRouter.post('/await-event/:eventName', express.json(), async (req, res) => {
const { eventName } = req.params;
- assert(eventName != null);
+ assert.ok(eventName != null);
const abortController = new AbortController();
abortController.signal.addEventListener('abort', () => logger.info('await-event aborted', eventName));
req.on('close', () => abortController.abort());
diff --git a/src/main/index.ts b/src/main/index.ts
index 05550b7c..c158003a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -205,7 +205,7 @@ function createWindow() {
mainWindow.on('close', (e) => {
if (!askBeforeClose) return;
- assert(mainWindow);
+ assert.ok(mainWindow);
const choice = electron.dialog.showMessageBoxSync(mainWindow, {
type: 'question',
buttons: ['Yes', 'No'],
@@ -240,7 +240,7 @@ async function openExternal(url: string) {
}
function updateMenu() {
- assert(mainWindow);
+ assert.ok(mainWindow);
menu({ app, mainWindow, newVersion, isStoreBuild, openExternal });
}
@@ -521,7 +521,7 @@ app.addListener('remote-require', (event: { returnValue: RemoteApiLegacy }, _web
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ipcMain.handle('__electron_rpc__', async (_event, method: keyof RemoteApi, args: any[]) => {
const fn = remoteApi[method];
- assert(fn, `Unknown API method: ${method}`);
+ assert.ok(fn, `Unknown API method: ${method}`);
// @ts-expect-error don't know how to type
return fn(...args);
});
diff --git a/src/main/progress.ts b/src/main/progress.ts
index c5ed24b9..e25b894d 100644
--- a/src/main/progress.ts
+++ b/src/main/progress.ts
@@ -3,9 +3,9 @@ export function parseFfmpegProgressLine({ line, customMatcher, duration: duratio
customMatcher?: ((a: string) => void) | undefined,
duration: number | undefined,
}) {
- let match = line.match(/frame=\s*\S+\s+fps=\s*\S+\s+q=\s*\S+\s+(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/);
+ let match = /frame=\s*\S+\s+fps=\s*\S+\s+q=\s*\S+\s+(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/.exec(line);
// Audio only looks like this: "size= 233422kB time=01:45:50.68 bitrate= 301.1kbits/s speed= 353x "
- match ??= line.match(/(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/);
+ match ??= /(?:size|Lsize)=\s*\S+\s+time=\s*(\S+)\s+/.exec(line);
if (!match) {
customMatcher?.(line);
return undefined;
@@ -17,7 +17,7 @@ export function parseFfmpegProgressLine({ line, customMatcher, duration: duratio
const timeStr = match[1];
// console.log(timeStr);
- const match2 = timeStr!.match(/^(-?)(\d+):(\d+):(\d+)\.(\d+)$/);
+ const match2 = /^(-?)(\d+):(\d+):(\d+)\.(\d+)$/.exec(timeStr!);
if (!match2) throw new Error(`Invalid time from ffmpeg progress ${timeStr}`);
const sign = match2[1];
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index d5fb5123..c2ec13f3 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -538,7 +538,7 @@ function App() {
const allFilesMeta = useMemo(() => ({
...externalFilesMeta,
- ...(filePath && mainFileMeta != null ? { [filePath]: mainFileMeta.ffprobeMeta } : {}),
+ ...(filePath && mainFileMeta != null && { [filePath]: mainFileMeta.ffprobeMeta }),
}), [externalFilesMeta, filePath, mainFileMeta]);
// total number of streams for ALL files
@@ -1989,7 +1989,7 @@ function App() {
const { canceled, filePaths } = await showOpenDialog({
properties: ['openFile'],
title: t('Include more tracks from other file'),
- ...(filePath != null ? { defaultPath: dirname(filePath) } : {}),
+ ...(filePath != null && { defaultPath: dirname(filePath) }),
});
const [firstFilePath] = filePaths;
if (canceled || firstFilePath == null) return;
diff --git a/src/renderer/src/Timeline.tsx b/src/renderer/src/Timeline.tsx
index de4c8fab..81a21d03 100644
--- a/src/renderer/src/Timeline.tsx
+++ b/src/renderer/src/Timeline.tsx
@@ -181,12 +181,12 @@ function Timeline({
// https://github.com/mifi/lossless-cut/issues/676
const pos = calculateTimelinePos(relevantTime, fileDurationNonZero);
// eslint-disable-next-line react-hooks/refs
- if (pos != null && timelineScrollerRef.current) return pos * zoom * timelineScrollerRef.current!.offsetWidth;
+ if (pos != null && timelineScrollerRef.current) return pos * zoom * timelineScrollerRef.current.offsetWidth;
return undefined;
}, [fileDurationNonZero, relevantTime, zoom]);
const calcZoomWindowStartTime = useCallback(() => (timelineScrollerRef.current
- ? (timelineScrollerRef.current.scrollLeft / (timelineScrollerRef.current!.offsetWidth * zoom)) * fileDurationNonZero
+ ? (timelineScrollerRef.current.scrollLeft / (timelineScrollerRef.current.offsetWidth * zoom)) * fileDurationNonZero
: 0), [fileDurationNonZero, zoom]);
// const zoomWindowStartTime = calcZoomWindowStartTime(duration, zoom);
diff --git a/src/renderer/src/components/AlertDialog.tsx b/src/renderer/src/components/AlertDialog.tsx
index 09750945..d24c14ac 100644
--- a/src/renderer/src/components/AlertDialog.tsx
+++ b/src/renderer/src/components/AlertDialog.tsx
@@ -15,7 +15,7 @@ export const Title = withClass(AlertDialog.Title, styles['AlertDialogTitle']!);
export const Description = withClass(AlertDialog.Description, styles['AlertDialogDescription']!);
-export const Portal = (props: AlertDialog.AlertDialogPortalProps) => <AlertDialog.Portal container={document.getElementById('app-root')!} {...props} />;
+export const Portal = (props: AlertDialog.AlertDialogPortalProps) => <AlertDialog.Portal container={document.getElementById('app-root')} {...props} />;
export function CancelButton() {
const { t } = useTranslation();
diff --git a/src/renderer/src/components/ConcatDialog.tsx b/src/renderer/src/components/ConcatDialog.tsx
index 05ebb331..ed6598d0 100644
--- a/src/renderer/src/components/ConcatDialog.tsx
+++ b/src/renderer/src/components/ConcatDialog.tsx
@@ -141,7 +141,7 @@ function ConcatDialog({ isShown, onHide, paths, mergedFileTemplate: storedMerged
function addProblem(path: string, error: Problem) {
problems[path] ??= [];
- problems[path]!.push(error);
+ problems[path].push(error);
}
allFilesMetaExceptFirstFile.forEach(([path, { ffprobeMeta: { streams } }]) => {
diff --git a/src/renderer/src/components/Dialog.tsx b/src/renderer/src/components/Dialog.tsx
index 6de21b4b..e69a215d 100644
--- a/src/renderer/src/components/Dialog.tsx
+++ b/src/renderer/src/components/Dialog.tsx
@@ -16,7 +16,7 @@ export const Description = withClass(Dialog.Description, styles['DialogDescripti
export const Title = withClass(Dialog.Title, styles['DialogTitle']!);
-export const Portal = (props: Dialog.DialogPortalProps) => <Dialog.Portal container={document.getElementById('app-root')!} {...props} />;
+export const Portal = (props: Dialog.DialogPortalProps) => <Dialog.Portal container={document.getElementById('app-root')} {...props} />;
export const CloseButton = () => (
<Dialog.Close asChild>
diff --git a/src/renderer/src/components/DropdownMenu.tsx b/src/renderer/src/components/DropdownMenu.tsx
index 8c5a266a..5d0c7972 100644
--- a/src/renderer/src/components/DropdownMenu.tsx
+++ b/src/renderer/src/components/DropdownMenu.tsx
@@ -13,4 +13,4 @@ export const Arrow = withClass(DropdownMenu.Arrow, styles['DropdownMenuArrow']!)
export const Separator = withClass(DropdownMenu.Separator, styles['DropdownMenuSeparator']!);
-export const Portal = (props: DropdownMenu.DropdownMenuPortalProps) => <DropdownMenu.Portal container={document.getElementById('app-root')!} {...props} />;
+export const Portal = (props: DropdownMenu.DropdownMenuPortalProps) => <DropdownMenu.Portal container={document.getElementById('app-root')} {...props} />;
diff --git a/src/renderer/src/components/ErrorDialog.tsx b/src/renderer/src/components/ErrorDialog.tsx
index 791edbbe..74a37cd2 100644
--- a/src/renderer/src/components/ErrorDialog.tsx
+++ b/src/renderer/src/components/ErrorDialog.tsx
@@ -12,8 +12,8 @@ export interface GenericError {
}
/**
- * We need to be able to show errors from anywhere in the app, also while dialogs are open. Also originating from keyboard actions
- */
+We need to be able to show errors from anywhere in the app, also while dialogs are open. Also originating from keyboard actions
+*/
export default function ErrorDialog({ error, onOpenChange }: {
error: GenericError | undefined,
onOpenChange: (open: boolean) => void,
diff --git a/src/renderer/src/dialogs/index.tsx b/src/renderer/src/dialogs/index.tsx
index 9054f972..7dff7a06 100644
--- a/src/renderer/src/dialogs/index.tsx
+++ b/src/renderer/src/dialogs/index.tsx
@@ -40,7 +40,7 @@ export const showOpenDialog = async ({
...props
}: Omit<Parameters<typeof dialog.showOpenDialog>[0], 'title'> & { title: string }) => {
const effectiveDefaultPath = defaultPath || await getLastDialogDir();
- const result = await dialog.showOpenDialog({ ...props, title, ...(effectiveDefaultPath != null && { defaultPath: effectiveDefaultPath }), ...(filters != null ? { filters } : {}) });
+ const result = await dialog.showOpenDialog({ ...props, title, ...(effectiveDefaultPath != null && { defaultPath: effectiveDefaultPath }), ...(filters != null && { filters }) });
const [firstPath] = result.filePaths;
if (!result.canceled && firstPath != null) {
try {
@@ -265,7 +265,7 @@ export async function askForSegmentDuration({ totalDuration, inputPlaceholder, p
async function askForSegmentsRandomDurationRange() {
function parse(str: string) {
// eslint-disable-next-line unicorn/better-regex
- const match = str.replaceAll(/\s/g, '').match(/^duration([\d.]+)to([\d.]+),gap([-\d.]+)to([-\d.]+)$/i);
+ const match = /^duration([\d.]+)to([\d.]+),gap([-\d.]+)to([-\d.]+)$/i.exec(str.replaceAll(/\s/g, ''));
if (!match) return undefined;
const values = match.slice(1);
const parsed = values.map((val) => parseFloat(val));
@@ -350,7 +350,7 @@ export interface CleanupChoicesType {
export type CleanupChoice = keyof CleanupChoicesType;
function parseBytesHuman(str: string) {
- const match = str.replaceAll(/\s/g, '').match(/^(\d+)([gkmt]?)b$/i);
+ const match = /^(\d+)([gkmt]?)b$/i.exec(str.replaceAll(/\s/g, ''));
if (!match) return undefined;
const size = parseInt(match[1]!, 10);
const unit = match[2]!.toLowerCase();
@@ -617,7 +617,7 @@ export async function checkAppPath() {
let payload: string | undefined;
if (isWindowsStoreBuild || (isDev && forceCheckMs)) {
const appPathOrMock = isDev ? String.raw`C:\Program Files\WindowsApps\37672NoveltyStudio.MediaConverter_9.0.6.0_x64__vjhnv588cyf84` : appPath;
- const pathMatch = appPathOrMock.replaceAll('\\', '/').match(/Windows ?Apps\/([^/]+)/); // find the first component after WindowsApps
+ const pathMatch = /Windows ?Apps\/([^/]+)/.exec(appPathOrMock.replaceAll('\\', '/')); // find the first component after WindowsApps
// example pathMatch: 37672NoveltyStudio.MediaConverter_9.0.6.0_x64__vjhnv588cyf84
if (!pathMatch) {
console.warn('Unknown path match', appPathOrMock);
diff --git a/src/renderer/src/edl.test.ts b/src/renderer/src/edl.test.ts
index 8a17d7ed..399655a4 100644
--- a/src/renderer/src/edl.test.ts
+++ b/src/renderer/src/edl.test.ts
@@ -6,9 +6,9 @@ import { parseEdlCmx3600 } from './edlFormats';
it('parseEdlCmx3600', async () => {
const fps = 30;
- expect(await parseEdlCmx3600(await readFixture('edl/12_16 TL01 MUSIC.edl'), fps)).toMatchSnapshot();
- expect(await parseEdlCmx3600(await readFixture('edl/070816_EG101_HEISTS_ROUGH_CUT_SOURCES_PART 1.edl'), fps)).toMatchSnapshot();
- expect(await parseEdlCmx3600(await readFixture('edl/cmx3600_5994.edl'), fps)).toMatchSnapshot();
- expect(await parseEdlCmx3600(await readFixture('edl/cmx3600.edl'), fps)).toMatchSnapshot();
- expect(await parseEdlCmx3600(await readFixture('edl/pull001_201109_exr.edl'), fps)).toMatchSnapshot();
+ await expect(parseEdlCmx3600(await readFixture('edl/12_16 TL01 MUSIC.edl'), fps)).resolves.toMatchSnapshot();
+ await expect(parseEdlCmx3600(await readFixture('edl/070816_EG101_HEISTS_ROUGH_CUT_SOURCES_PART 1.edl'), fps)).resolves.toMatchSnapshot();
+ await expect(parseEdlCmx3600(await readFixture('edl/cmx3600_5994.edl'), fps)).resolves.toMatchSnapshot();
+ await expect(parseEdlCmx3600(await readFixture('edl/cmx3600.edl'), fps)).resolves.toMatchSnapshot();
+ await expect(parseEdlCmx3600(await readFixture('edl/pull001_201109_exr.edl'), fps)).resolves.toMatchSnapshot();
});
diff --git a/src/renderer/src/edlFormats.test.ts b/src/renderer/src/edlFormats.test.ts
index 42e29704..f5150fd5 100644
--- a/src/renderer/src/edlFormats.test.ts
+++ b/src/renderer/src/edlFormats.test.ts
@@ -136,7 +136,7 @@ it('parseMplayerEdl', async () => {
const str = await readFixture('mplayer.edl');
- expect(await parseMplayerEdl(str)).toStrictEqual([
+ await expect(parseMplayerEdl(str)).resolves.toStrictEqual([
{ start: 0,
end: 5.3,
name: 'Cut',
@@ -171,7 +171,7 @@ it('parseMplayerEdl', async () => {
it('parseMplayerEdl, starting at 0', async () => {
const str2 = ' 0 1.1 0\n';
- expect(await parseMplayerEdl(str2)).toStrictEqual([{
+ await expect(parseMplayerEdl(str2)).resolves.toStrictEqual([{
start: 1.1,
end: undefined,
name: 'Cut',
diff --git a/src/renderer/src/edlFormats.ts b/src/renderer/src/edlFormats.ts
index 7e964442..d13a5470 100644
--- a/src/renderer/src/edlFormats.ts
+++ b/src/renderer/src/edlFormats.ts
@@ -24,7 +24,7 @@ export function getFrameCountRaw(detectedFps: number | undefined, sec: number) {
}
function parseTime(str: string) {
- const timeMatch = str.match(/^\D*(?:(?:(\d+):)?(\d{1,2}):)?(\d+)(?:\.(\d{1,3}))?:?/);
+ const timeMatch = /^\D*(?:(?:(\d+):)?(\d{1,2}):)?(\d+)(?:\.(\d{1,3}))?:?/.exec(str);
if (!timeMatch) return undefined;
const rest = str.slice(timeMatch[0].length);
@@ -170,7 +170,7 @@ export async function parseCutlist(clStr: string) {
export async function parseMplayerEdl(text: string) {
const allRows = text.split('\n').flatMap((line) => {
- const match = line.match(/^\s*(\S+)\s+(\S+)\s+([0-3])\s*$/);
+ const match = /^\s*(\S+)\s+(\S+)\s+([0-3])\s*$/.exec(line);
if (!match) return [];
const start = parseFloat(match[1]!);
const end = parseFloat(match[2]!);
@@ -203,7 +203,7 @@ export async function parseEdlCmx3600(text: string, fps: number) {
const cmx = parseCmx3600(text);
const parseTimecode = (t: string) => {
- const match = t.match(/^(\d+)[:;](\d+)[:;](\d+)[:;](\d+)$/);
+ const match = /^(\d+)[:;](\d+)[:;](\d+)[:;](\d+)$/.exec(t);
invariant(match, `Invalid EDL line: ${t}`);
const hours = parseInt(match[1]!, 10);
const minutes = parseInt(match[2]!, 10);
@@ -254,7 +254,7 @@ export function parsePbf(buf: Buffer) {
const text = buf.toString('utf16le');
return text.split('\n').flatMap((line) => {
- const match = line.match(/^\d+=(\d+)\*([^*]+)*([^*]+)?/);
+ const match = /^\d+=(\d+)\*([^*]+)*([^*]+)?/.exec(line);
if (match) return [{ start: parseInt(match[1]!, 10) / 1000, name: match[2] }];
return [];
});
@@ -300,9 +300,9 @@ export function parseFcpXml(xmlStr: string) {
// e.g. "1001/30000s" or "10s"
function getTime(str: string | undefined) {
if (str == null) throw new Error('Missing attribute');
- const match = str.match(/^(\d+)\/(\d+)s$/);
+ const match = /^(\d+)\/(\d+)s$/.exec(str);
if (match) return parseInt(match[1]!, 10) / parseInt(match[2]!, 10);
- const secMatch = str.match(/^(\d+(?:\.\d+)?)s$/);
+ const secMatch = /^(\d+(?:\.\d+)?)s$/.exec(str);
if (secMatch) return parseFloat(secMatch[1]!);
throw new Error('Invalid attribute');
}
@@ -325,7 +325,7 @@ export function parseYouTube(str: string) {
const { time, rest } = timeParsed;
- const nameMatch = rest.match(/^[\s-]+([^\n]*)$/);
+ const nameMatch = /^[\s-]+([^\n]*)$/.exec(rest);
if (!nameMatch) return undefined;
const [, name] = nameMatch;
@@ -404,7 +404,7 @@ export function parseDvAnalyzerSummaryTxt(txt: string) {
// eslint-disable-next-line eslint-js/no-restricted-syntax
for (const line of lines) {
if (headerFound) {
- const match = line.match(/^(\d{2}):(\d{2}):(\d{2}).(\d{3})\s+(\S+)\s+-\s+(\S+)\s+(\S+\s+\S+)\s+-\s+(\S+\s+\S+)/);
+ const match = /^(\d{2}):(\d{2}):(\d{2}).(\d{3})\s+(\S+)\s+-\s+(\S+)\s+(\S+\s+\S+)\s+-\s+(\S+\s+\S+)/.exec(line);
if (!match) break;
const h = parseInt(match[1]!, 10);
const m = parseInt(match[2]!, 10);
@@ -453,7 +453,7 @@ export function parseSrt(text: string) {
if (line === '') {
flush();
} else if (subtitleIndexAt != null && subtitleIndexAt > 0) {
- const match = line.match(/^(\d+:\d+:\d+[,.]\d+\s+)-->(\s+\d+:\d+:\d+[,.]\d+)$/);
+ const match = /^(\d+:\d+:\d+[,.]\d+\s+)-->(\s+\d+:\d+:\d+[,.]\d+)$/.exec(line);
if (match) {
const fixComma = (v: string | undefined) => v!.replaceAll(',', '.');
start = parseTime(fixComma(match[1]))?.time;
@@ -491,7 +491,7 @@ export function parseDjiGps1(lines: string[]) {
const firstLine = lines[0];
if (firstLine == null) return undefined;
- const gpsMatch = firstLine.match(/^\s*([^,]+),\s*SS\s+([^,]+),\s*ISO\s+([^,]+),\s*EV\s+([^,]+)(?:,\s*DZOOM\s+([^,]+))?,\s*GPS\s+\(([^,]+),\s*([^,]+),\s*([^,]+)\),\s*D\s+([^m]+)m,\s*H\s+([^m]+)m,\s*H\.S\s+([^m]+)m\/s,\s*V\.S\s+([^m]+)m\/s\s*$/);
+ const gpsMatch = /^\s*([^,]+),\s*SS\s+([^,]+),\s*ISO\s+([^,]+),\s*EV\s+([^,]+)(?:,\s*DZOOM\s+([^,]+))?,\s*GPS\s+\(([^,]+),\s*([^,]+),\s*([^,]+)\),\s*D\s+([^m]+)m,\s*H\s+([^m]+)m,\s*H\.S\s+([^m]+)m\/s,\s*V\.S\s+([^m]+)m\/s\s*$/.exec(firstLine);
if (!gpsMatch) return undefined;
return {
f: gpsMatch[1]!,
@@ -512,7 +512,7 @@ export function parseDjiGps1(lines: string[]) {
export function parseDjiGps2(lines: string[]) {
const { font } = new XMLParser().parse(lines.join('\n')) as { font: unknown };
invariant(typeof font === 'string');
- const line = font.split('\n')[2];
+ const line = font.split('\n', 3)[2];
invariant(line != null);
const records: Record<string, string> = {};
const pairsMatch = line.match(/([^\s:[]+\s*:\s*[^\s\]]+)+/g);
diff --git a/src/renderer/src/edlStore.ts b/src/renderer/src/edlStore.ts
index cd4bb4ec..51643c92 100644
--- a/src/renderer/src/edlStore.ts
+++ b/src/renderer/src/edlStore.ts
@@ -221,7 +221,7 @@ export async function exportEdlFile({ type, cutSegments, customOutDir, filePath,
const defaultPath = getOutPath({ filePath, customOutDir, fileName: `${basename(filePath)}.${ext}` });
- const { canceled, filePath: savePath } = await dialog.showSaveDialog({ defaultPath, title: i18n.t('Export project'), ...(filters != null ? { filters } : {}) });
+ const { canceled, filePath: savePath } = await dialog.showSaveDialog({ defaultPath, title: i18n.t('Export project'), ...(filters != null && { filters }) });
if (canceled || !savePath) return;
console.log('Saving', type, savePath);
// eslint-disable-next-line unicorn-js/prefer-switch
diff --git a/src/renderer/src/ffmpeg.ts b/src/renderer/src/ffmpeg.ts
index 068ae169..f2a93d64 100644
--- a/src/renderer/src/ffmpeg.ts
+++ b/src/renderer/src/ffmpeg.ts
@@ -209,10 +209,10 @@ export function tryMapChaptersToEdl(chapters: FFprobeChapter[]) {
}
/**
- * Some of the detected input formats are not the same as the muxer name used for encoding.
- * Therefore we have to map between detected input format and encode format
- * See also ffmpeg -formats
- */
+Some of the detected input formats are not the same as the muxer name used for encoding.
+Therefore we have to map between detected input format and encode format
+See also ffmpeg -formats
+*/
function mapInputToOutputFormat(requestedFormat: string | undefined) {
// see file aac raw adts.aac
if (requestedFormat === 'aac') return 'adts';
@@ -463,7 +463,7 @@ export function isProblematicAvc1(outFormat: string | undefined, streams: FFprob
}
function parseFfprobeFps(stream: FFprobeStream) {
- const match = typeof stream.avg_frame_rate === 'string' && stream.avg_frame_rate.match(/^(\d+)\/(\d+)$/);
+ const match = typeof stream.avg_frame_rate === 'string' && /^(\d+)\/(\d+)$/.exec(stream.avg_frame_rate);
if (!match) return undefined;
const num = parseInt(match[1]!, 10);
const den = parseInt(match[2]!, 10);
diff --git a/src/renderer/src/hooks/normalizeWheel.ts b/src/renderer/src/hooks/normalizeWheel.ts
index 036c4f6a..4d8f69a4 100644
--- a/src/renderer/src/hooks/normalizeWheel.ts
+++ b/src/renderer/src/hooks/normalizeWheel.ts
@@ -3,16 +3,16 @@
import type { WheelEvent } from 'react';
/**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- *
- * @providesModule normalizeWheel
- * @typechecks
- */
+Copyright (c) 2015, Facebook, Inc.
+All rights reserved.
+
+This source code is licensed under the BSD-style license found in the
+LICENSE file in the root directory of this source tree. An additional grant
+of patent rights can be found in the PATENTS file in the same directory.
+
+@providesModule normalizeWheel
+@typechecks
+*/
// Reasonable defaults
const PIXEL_STEP = 10;
@@ -20,105 +20,105 @@ const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
/**
- * Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
- * complicated, thus this doc is long and (hopefully) detailed enough to answer
- * your questions.
- *
- * If you need to react to the mouse wheel in a predictable way, this code is
- * like your bestest friend. * hugs *
- *
- * As of today, there are 4 DOM event types you can listen to:
- *
- * 'wheel' -- Chrome(31+), FF(17+), IE(9+)
- * 'mousewheel' -- Chrome, IE(6+), Opera, Safari
- * 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
- * 'DOMMouseScroll' -- FF(0.9.7+) since 2003
- *
- * So what to do? The is the best:
- *
- * normalizeWheel.getEventType();
- *
- * In your event callback, use this code to get sane interpretation of the
- * deltas. This code will return an object with properties:
- *
- * spinX -- normalized spin speed (use for zoom) - x plane
- * spinY -- " - y plane
- * pixelX -- normalized distance (to pixels) - x plane
- * pixelY -- " - y plane
- *
- * Wheel values are provided by the browser assuming you are using the wheel to
- * scroll a web page by a number of lines or pixels (or pages). Values can vary
- * significantly on different platforms and browsers, forgetting that you can
- * scroll at different speeds. Some devices (like trackpads) emit more events
- * at smaller increments with fine granularity, and some emit massive jumps with
- * linear speed or acceleration.
- *
- * This code does its best to normalize the deltas for you:
- *
- * - spin is trying to normalize how far the wheel was spun (or trackpad
- * dragged). This is super useful for zoom support where you want to
- * throw away the chunky scroll steps on the PC and make those equal to
- * the slow and smooth tiny steps on the Mac. Key data: This code tries to
- * resolve a single slow step on a wheel to 1.
- *
- * - pixel is normalizing the desired scroll delta in pixel units. You'll
- * get the crazy differences between browsers, but at least it'll be in
- * pixels!
- *
- * - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
- * should translate to positive value zooming IN, negative zooming OUT.
- * This matches the newer 'wheel' event.
- *
- * Why are there spinX, spinY (or pixels)?
- *
- * - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
- * with a mouse. It results in side-scrolling in the browser by default.
- *
- * - spinY is what you expect -- it's the classic axis of a mouse wheel.
- *
- * - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
- * probably is by browsers in conjunction with fancy 3D controllers .. but
- * you know.
- *
- * Implementation info:
- *
- * Examples of 'wheel' event if you scroll slowly (down) by one step with an
- * average mouse:
- *
- * OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
- * OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
- * OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
- * Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
- * Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
- *
- * On the trackpad:
- *
- * OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
- * OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
- *
- * On other/older browsers.. it's more complicated as there can be multiple and
- * also missing delta values.
- *
- * The 'wheel' event is more standard:
- *
- * https://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
- *
- * The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
- * deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
- * backward compatibility with older events. Those other values help us
- * better normalize spin speed. Example of what the browsers provide:
- *
- * | event.wheelDelta | event.detail
- * ------------------+------------------+--------------
- * Safari v5/OS X | -120 | 0
- * Safari v5/Win7 | -120 | 0
- * Chrome v17/OS X | -120 | 0
- * Chrome v17/Win7 | -120 | 0
- * IE9/Win7 | -120 | undefined
- * Firefox v4/OS X | undefined | 1
- * Firefox v4/Win7 | undefined | 3
- *
- */
+Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
+complicated, thus this doc is long and (hopefully) detailed enough to answer
+your questions.
+
+If you need to react to the mouse wheel in a predictable way, this code is
+like your bestest friend. * hugs *
+
+As of today, there are 4 DOM event types you can listen to:
+
+ 'wheel' -- Chrome(31+), FF(17+), IE(9+)
+ 'mousewheel' -- Chrome, IE(6+), Opera, Safari
+ 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
+ 'DOMMouseScroll' -- FF(0.9.7+) since 2003
+
+So what to do? The is the best:
+
+ normalizeWheel.getEventType();
+
+In your event callback, use this code to get sane interpretation of the
+deltas. This code will return an object with properties:
+
+ spinX -- normalized spin speed (use for zoom) - x plane
+ spinY -- " - y plane
+ pixelX -- normalized distance (to pixels) - x plane
+ pixelY -- " - y plane
+
+Wheel values are provided by the browser assuming you are using the wheel to
+scroll a web page by a number of lines or pixels (or pages). Values can vary
+significantly on different platforms and browsers, forgetting that you can
+scroll at different speeds. Some devices (like trackpads) emit more events
+at smaller increments with fine granularity, and some emit massive jumps with
+linear speed or acceleration.
+
+This code does its best to normalize the deltas for you:
+
+ - spin is trying to normalize how far the wheel was spun (or trackpad
+ dragged). This is super useful for zoom support where you want to
+ throw away the chunky scroll steps on the PC and make those equal to
+ the slow and smooth tiny steps on the Mac. Key data: This code tries to
+ resolve a single slow step on a wheel to 1.
+
+ - pixel is normalizing the desired scroll delta in pixel units. You'll
+ get the crazy differences between browsers, but at least it'll be in
+ pixels!
+
+ - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
+ should translate to positive value zooming IN, negative zooming OUT.
+ This matches the newer 'wheel' event.
+
+Why are there spinX, spinY (or pixels)?
+
+ - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
+ with a mouse. It results in side-scrolling in the browser by default.
+
+ - spinY is what you expect -- it's the classic axis of a mouse wheel.
+
+ - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
+ probably is by browsers in conjunction with fancy 3D controllers .. but
+ you know.
+
+Implementation info:
+
+Examples of 'wheel' event if you scroll slowly (down) by one step with an
+average mouse:
+
+ OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
+ OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
+ OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
+ Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
+ Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
+
+On the trackpad:
+
+ OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
+ OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
+
+On other/older browsers.. it's more complicated as there can be multiple and
+also missing delta values.
+
+The 'wheel' event is more standard:
+
+https://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
+
+The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
+deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
+backward compatibility with older events. Those other values help us
+better normalize spin speed. Example of what the browsers provide:
+
+ | event.wheelDelta | event.detail
+ ------------------+------------------+--------------
+ Safari v5/OS X | -120 | 0
+ Safari v5/Win7 | -120 | 0
+ Chrome v17/OS X | -120 | 0
+ Chrome v17/Win7 | -120 | 0
+ IE9/Win7 | -120 | undefined
+ Firefox v4/OS X | undefined | 1
+ Firefox v4/Win7 | undefined | 3
+
+*/
// eslint-disable-next-line unicorn-js/prefer-smaller-scope -- TODO fix (new rule in @mifi/lint-config)
type LegacyWheelEvent = WheelEvent & { axis?: number, HORIZONTAL_AXIS?: number };
diff --git a/src/renderer/src/hooks/useErrorHandling.ts b/src/renderer/src/hooks/useErrorHandling.ts
index 6346423f..758c6665 100644
--- a/src/renderer/src/hooks/useErrorHandling.ts
+++ b/src/renderer/src/hooks/useErrorHandling.ts
@@ -15,8 +15,8 @@ export default function useErrorHandling() {
}, []);
/**
- * Run an operation with error handling
- */
+ Run an operation with error handling
+ */
async function withErrorHandling(operation: () => Promise<void>, errorMsg?: string) {
try {
await operation();
diff --git a/src/renderer/src/hooks/useFrameCapture.ts b/src/renderer/src/hooks/useFrameCapture.ts
index 1171574b..2d01b2ad 100644
--- a/src/renderer/src/hooks/useFrameCapture.ts
+++ b/src/renderer/src/hooks/useFrameCapture.ts
@@ -75,7 +75,7 @@ export default ({ appendFfmpegCommandLog, formatTimecode, treatInputFileModified
const matches = files.flatMap((fileName) => {
const escapedRegexp = escapeRegExp(getSuffixedFileName(filePath, tmpSuffix));
const regexp = `^${escapedRegexp}(\\d+)`;
- const match = fileName.match(new RegExp(regexp));
+ const match = new RegExp(regexp).exec(fileName);
if (!match) return [];
const frameNum = parseInt(match[1]!, 10);
if (Number.isNaN(frameNum) || frameNum < 0) return [];
diff --git a/src/renderer/src/segments.ts b/src/renderer/src/segments.ts
index ad6b4050..cb549c4f 100644
--- a/src/renderer/src/segments.ts
+++ b/src/renderer/src/segments.ts
@@ -177,7 +177,7 @@ export function invertSegments(
ret.push({
start: 0,
end: firstSeg.start,
- ...(firstSeg.segId != null ? { segId: `start-${firstSeg.segId}` } : {}),
+ ...(firstSeg.segId != null && { segId: `start-${firstSeg.segId}` }),
});
}
}
diff --git a/src/renderer/src/util.ts b/src/renderer/src/util.ts
index a9f260df..0a18fb22 100644
--- a/src/renderer/src/util.ts
+++ b/src/renderer/src/util.ts
@@ -132,7 +132,7 @@ export async function fsOperationWithRetry<T>(operation: () => Promise<T>, { sig
// mimic fs.rm `maxRetries` https://nodejs.org/api/fs.html#fspromisesrmpath-options
shouldRetry: (err) => err instanceof Error && 'code' in err && typeof err.code === 'string' && ['EBUSY', 'EMFILE', 'ENFILE', 'EPERM'].includes(err.code),
...opts,
- } as Options);
+ });
}
// example error: index-18074aaf.js:166 Failed to delete C:\Users\USERNAME\Desktop\RC\New folder\2023-12-27 21-45-22 (GMT p5)-merged-1703933052361-00.01.04.915-00.01.07.424-seg1.mp4 Error: EPERM: operation not permitted, unlink 'C:\Users\USERNAME\Desktop\RC\New folder\2023-12-27 21-45-22 (GMT p5)-merged-1703933052361-00.01.04.915-00.01.07.424-seg1.mp4'
diff --git a/src/renderer/src/util/constants.ts b/src/renderer/src/util/constants.ts
index a9b670f4..3ec8b166 100644
--- a/src/renderer/src/util/constants.ts
+++ b/src/renderer/src/util/constants.ts
@@ -1,7 +1,9 @@
// anything more than this will probably cause the UI to become unusably slow
export const maxSegmentsAllowed = 2000;
-/** Size of the window to extract keyframes/waveforms */
+/**
+Size of the window to extract keyframes/waveforms
+*/
export const ffmpegExtractWindow = 60;
export const zoomMax = 2 ** 14;
diff --git a/src/renderer/src/util/duration.ts b/src/renderer/src/util/duration.ts
index 4ee4b5a5..198eed77 100644
--- a/src/renderer/src/util/duration.ts
+++ b/src/renderer/src/util/duration.ts
@@ -56,7 +56,7 @@ export const isExactTimecodeMatch = (str: string, parseTimecode: ParseTimecode,
// See also parseYoutube
export function parseDuration(str: string, fps?: number) {
// eslint-disable-next-line unicorn/better-regex
- const match = str.replaceAll(/\s/g, '').match(durationRegex);
+ const match = durationRegex.exec(str.replaceAll(/\s/g, ''));
if (!match) return undefined;
@@ -72,7 +72,7 @@ export function parseDuration(str: string, fps?: number) {
if (fps == null) {
time = ((hour * 60) + min) * 60 + parseFloat(secWithFraction);
} else {
- const [secStr, framesStr] = secWithFraction.split('.');
+ const [secStr, framesStr] = secWithFraction.split('.', 2);
const wholeSeconds = ((hour * 60) + min) * 60 + parseInt(secStr!, 10);
const frames = framesStr != null ? parseInt(framesStr, 10) : 0;
// inverse of formatDuration (which floors the frame remainder), needed for non-integer fps like 29.97
diff --git a/src/renderer/src/util/metadata.ts b/src/renderer/src/util/metadata.ts
index 19f62908..d745ce0b 100644
--- a/src/renderer/src/util/metadata.ts
+++ b/src/renderer/src/util/metadata.ts
@@ -35,7 +35,7 @@ const nonCopyableMetadataKeys = new Set<string>([...muxerWrittenMetadataKeys, ..
const isDefaultHandlerName = (value: string) => /handler|core media|iso media|dji\./i.test(value);
const isCopyableMetadata = (key: string, value: string) => {
- const baseKey = key.toLowerCase().split('-')[0]!;
+ const baseKey = key.toLowerCase().split('-', 1)[0]!;
if (baseKey === 'handler_name') return !isDefaultHandlerName(value);
return !nonCopyableMetadataKeys.has(baseKey) && !baseKey.startsWith('_statistics_');
};
diff --git a/src/renderer/src/util/rate-calculator.ts b/src/renderer/src/util/rate-calculator.ts
index 04ff80b2..90be7ebb 100644
--- a/src/renderer/src/util/rate-calculator.ts
+++ b/src/renderer/src/util/rate-calculator.ts
@@ -1,21 +1,21 @@
import clamp from 'lodash/clamp';
/**
- * @constant {number}
- * @default
- * The default playback rate multiplier is used to adjust the current playback
- * rate when no additional modifiers are applied. This is set to ∛2 so that striking
- * the fast forward key (`l`) three times speeds playback up to twice the speed.
- */
+@constant {number}
+@default
+The default playback rate multiplier is used to adjust the current playback
+rate when no additional modifiers are applied. This is set to ∛2 so that striking
+the fast forward key (`l`) three times speeds playback up to twice the speed.
+*/
export const DEFAULT_PLAYBACK_RATE = (2 ** (1 / 3));
/**
- * Adjusts the current playback rate up or down
- * @param {number} playbackRate current playback rate
- * @param {number} direction positive for forward, negative for reverse
- * @param {number} [multiplier] rate multiplier, defaults to {@link DEFAULT_PLAYBACK_RATE}
- * @returns a new playback rate
- */
+Adjusts the current playback rate up or down
+@param {number} playbackRate current playback rate
+@param {number} direction positive for forward, negative for reverse
+@param {number} [multiplier] rate multiplier, defaults to {@link DEFAULT_PLAYBACK_RATE}
+@returns a new playback rate
+*/
export function adjustRate(playbackRate: number, direction: number, multiplier?: number) {
const m = multiplier || DEFAULT_PLAYBACK_RATE;
const factor = direction > 0 ? m : (1 / m);
diff --git a/src/renderer/src/util/streams.ts b/src/renderer/src/util/streams.ts
index 2b9e349d..6fde49d8 100644
--- a/src/renderer/src/util/streams.ts
+++ b/src/renderer/src/util/streams.ts
@@ -285,7 +285,9 @@ export function isStreamThumbnail(stream: Pick<FFprobeStream, 'codec_type' | 'di
return stream && stream.codec_type === 'video' && stream.disposition?.[attachedPicDisposition] === 1;
}
-/** Resolves every stream that is going to be copied to the output. Unknown streams resolve to `undefined`. */
+/**
+Resolves every stream that is going to be copied to the output. Unknown streams resolve to `undefined`.
+*/
const getCopiedStreams = ({ allFilesMeta, copyFileStreams }: {
allFilesMeta: AllFilesStreamMeta,
copyFileStreams: CopyfileStreams,
@@ -299,15 +301,15 @@ function isCopyingThumbnailStream({ allFilesMeta, copyFileStreams }: {
}
/**
- * Whether every stream being copied is audio (cover art is allowed, as it is a single keyframe anyway).
- *
- * Used to decide whether it is safe to pass `-copyinkf` to ffmpeg. When cutting with `-ss` *after* `-i`
- * (keyframe cut mode off), ffmpeg's stream copy discards packets until it sees one flagged as a keyframe.
- * Audio packets are normally all keyframes, but some audio-only MP4/M4A files carry a sync sample table
- * (`stss`) that only flags a packet every few seconds. The cut then starts seconds late (and with `-ss`
- * before `-i`, seconds early). `-copyinkf` makes ffmpeg keep the leading non-keyframe packets, which is
- * harmless for audio, but would produce broken frames for video, so we only do it for audio-only exports.
- */
+Whether every stream being copied is audio (cover art is allowed, as it is a single keyframe anyway).
+
+Used to decide whether it is safe to pass `-copyinkf` to ffmpeg. When cutting with `-ss` *after* `-i`
+(keyframe cut mode off), ffmpeg's stream copy discards packets until it sees one flagged as a keyframe.
+Audio packets are normally all keyframes, but some audio-only MP4/M4A files carry a sync sample table
+(`stss`) that only flags a packet every few seconds. The cut then starts seconds late (and with `-ss`
+before `-i`, seconds early). `-copyinkf` makes ffmpeg keep the leading non-keyframe packets, which is
+harmless for audio, but would produce broken frames for video, so we only do it for audio-only exports.
+*/
export function isCopyingOnlyAudioStreams({ allFilesMeta, copyFileStreams }: {
allFilesMeta: AllFilesStreamMeta,
copyFileStreams: CopyfileStreams,
@@ -317,16 +319,16 @@ export function isCopyingOnlyAudioStreams({ allFilesMeta, copyFileStreams }: {
}
/**
- * An attached_pic (cover art) packet has no position on the timeline - the demuxer emits it at
- * pts 0. When seeking before the input (`-ss` before `-i`), ffmpeg applies the seek offset to it
- * anyway, dragging it to -(cut from), and it reaches the muxer first. `make_zero` and
- * `make_non_negative` then derive their file-wide correction from that packet and shift every
- * other stream back by +(cut from), undoing the rebase to zero that the audio/video already got.
- * The mov muxer records that as an empty edit, so the muxed duration ends up being the segment's
- * end time in the source instead of its length (ffprobe hides this, but e.g. VLC reports it).
- * `auto` doesn't use the attached pic as its reference, so it cuts correctly and keeps the cover art.
- * See https://github.com/mifi/lossless-cut/issues/3009
- */
+An attached_pic (cover art) packet has no position on the timeline - the demuxer emits it at
+pts 0. When seeking before the input (`-ss` before `-i`), ffmpeg applies the seek offset to it
+anyway, dragging it to -(cut from), and it reaches the muxer first. `make_zero` and
+`make_non_negative` then derive their file-wide correction from that packet and shift every
+other stream back by +(cut from), undoing the rebase to zero that the audio/video already got.
+The mov muxer records that as an empty edit, so the muxed duration ends up being the segment's
+end time in the source instead of its length (ffprobe hides this, but e.g. VLC reports it).
+`auto` doesn't use the attached pic as its reference, so it cuts correctly and keeps the cover art.
+See https://github.com/mifi/lossless-cut/issues/3009
+*/
export function getEffectiveAvoidNegativeTs({ avoidNegativeTs, allFilesMeta, copyFileStreams }: {
avoidNegativeTs: AvoidNegativeTs | undefined,
allFilesMeta: AllFilesStreamMeta,
@@ -338,11 +340,11 @@ export function getEffectiveAvoidNegativeTs({ avoidNegativeTs, allFilesMeta, cop
}
/**
- * For input formats without AVFMT_SEEK_TO_PTS (e.g. Matroska/WebM), when any stream has B-frames, ffmpeg seeks
- * 3/23s earlier than the input `-ss` (`dts_heuristic` in fftools/ffmpeg_demux.c). With `-ss` before `-i`, a keyframe cut
- * starting on (or up to ~0.13s after) a keyframe then starts from the *previous* keyframe. Returns how much to add to the
- * input `-ss` (and pass as `-itsoffset`) to undo that. See https://github.com/mifi/lossless-cut/issues/1216
- */
+For input formats without AVFMT_SEEK_TO_PTS (e.g. Matroska/WebM), when any stream has B-frames, ffmpeg seeks
+3/23s earlier than the input `-ss` (`dts_heuristic` in fftools/ffmpeg_demux.c). With `-ss` before `-i`, a keyframe cut
+starting on (or up to ~0.13s after) a keyframe then starts from the *previous* keyframe. Returns how much to add to the
+input `-ss` (and pass as `-itsoffset`) to undo that. See https://github.com/mifi/lossless-cut/issues/1216
+*/
export function getKeyframeCutSeekCompensation({ formatName, streams, cutFrom }: {
formatName: string | undefined,
streams: Pick<FFprobeStream, 'has_b_frames'>[],
diff --git a/website/src/lib/docs.ts b/website/src/lib/docs.ts
index 79e1ced8..cd7bdcaf 100644
--- a/website/src/lib/docs.ts
+++ b/website/src/lib/docs.ts
@@ -21,7 +21,9 @@ const descriptionOverrides: Record<string, string> = {
'faq.md': 'Answers to common questions about LosslessCut: free vs app store versions, safety, supported operating systems, updating, and features it doesn\'t have.',
};
-/** Site URL of a doc, by its path relative to docs/: `cli.md` -> `/docs/cli`, `index.md` -> `/docs` */
+/**
+Site URL of a doc, by its path relative to docs/: `cli.md` -> `/docs/cli`, `index.md` -> `/docs`
+*/
export function getDocUrl(docPath: string) {
return `/docs/${docPath.replace(/\.md$/, '').replace(/(^|\/)index$/, '')}`.replace(/\/$/, '');
}
@@ -39,13 +41,19 @@ function summarize(text: string, maxLength = 160) {
return `${collapsed.slice(0, lastSpace > 0 ? lastSpace : maxLength - 1)}…`;
}
-/** Path of a doc file relative to docs/, e.g. `cli.md`. */
+/**
+Path of a doc file relative to docs/, e.g. `cli.md`.
+*/
export const getDocPath = (filePath: string) => path.relative(docsDir, filePath).split(path.sep).join('/');
-/** The heading that a doc's title is taken from: its first `# heading`. */
+/**
+The heading that a doc's title is taken from: its first `# heading`.
+*/
export const findTitleHeading = (tree: Root) => tree.children.find((node): node is Heading => node.type === 'heading' && node.depth === 1);
-/** Frontmatter for a doc: title from its first heading, description from its first paragraph. */
+/**
+Frontmatter for a doc: title from its first heading, description from its first paragraph.
+*/
function getFrontmatter(docPath: string, markdown: string) {
// the frontmatter, if any, is parsed by the loader
const tree = fromMarkdown(markdown.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ''));
@@ -59,7 +67,9 @@ function getFrontmatter(docPath: string, markdown: string) {
};
}
-/** Like Starlight's docsLoader, but for ../docs, and generates the frontmatter that Starlight needs. */
+/**
+Like Starlight's docsLoader, but for ../docs, and generates the frontmatter that Starlight needs.
+*/
export function repoDocsLoader(): Loader {
const globLoader = glob({
base: docsDir,
diff --git a/website/src/lib/remarkDocs.ts b/website/src/lib/remarkDocs.ts
index 36d79b5f..baa7d295 100644
--- a/website/src/lib/remarkDocs.ts
+++ b/website/src/lib/remarkDocs.ts
@@ -15,9 +15,9 @@ import { docsDir, findTitleHeading, getDocPath, getDocUrl, repoDir } from './doc
const isDoc = (file: VFile) => file.path?.startsWith(docsDir + path.sep) ?? false;
/**
- * Removes the doc's `# title` heading, because Starlight shows the title (taken from it) itself.
- * Images in it (e.g. badges) are kept, as a paragraph in its place.
- */
+Removes the doc's `# title` heading, because Starlight shows the title (taken from it) itself.
+Images in it (e.g. badges) are kept, as a paragraph in its place.
+*/
export function remarkRemoveDocTitle() {
return (tree: Root, file: VFile) => {
if (!isDoc(file)) return;
@@ -29,9 +29,9 @@ export function remarkRemoveDocTitle() {
}
/**
- * Rewrites relative links, which are written for browsing the docs on GitHub, to the site's URLs:
- * other docs to their page, other files in the repo to GitHub. Relative images are left to Astro, which bundles them.
- */
+Rewrites relative links, which are written for browsing the docs on GitHub, to the site's URLs:
+other docs to their page, other files in the repo to GitHub. Relative images are left to Astro, which bundles them.
+*/
export function remarkRepoLinks() {
return (tree: Root, file: VFile) => {
if (!isDoc(file)) return;
@@ -67,9 +67,9 @@ export function remarkRepoLinks() {
}
/**
- * Sets the page's id as `slug` in the frontmatter that remark/rehype plugins see. starlight-links-validator
- * uses it to know which page a file is, which it otherwise derives from the file's path in src/content/docs.
- */
+Sets the page's id as `slug` in the frontmatter that remark/rehype plugins see. starlight-links-validator
+uses it to know which page a file is, which it otherwise derives from the file's path in src/content/docs.
+*/
export function remarkDocSlug() {
return (_tree: Root, file: VFile) => {
if (!isDoc(file)) return;