Skip to content

The swiss army knife of lossless video/audio editing

test function getFfmpegJpegQuality #2718

Mikael Finstad260129074808
diff --git a/src/main/ffmpeg.ts b/src/main/ffmpeg.ts
index a7194daa..e68d21c2 100644
--- a/src/main/ffmpeg.ts
+++ b/src/main/ffmpeg.ts
@@ -15,6 +15,8 @@ import isDev from './isDev.js';
import logger from './logger.js';
import { parseFfmpegProgressLine } from './progress.js';
import { parseFfprobeDuration } from '../common/util.js';
+import { getFfmpegJpegQuality } from './ffmpegUtil.js';
+
// cannot use process.kill: https://github.com/sindresorhus/execa/issues/1177
const runningFfmpegs = new Set<{
@@ -455,13 +457,6 @@ export async function silenceDetect({ filePath, streamId, filterOptions, boundin
});
}
-function getFfmpegJpegQuality(quality: number) {
- // Normal range for JPEG is 2-31 with 31 being the worst quality.
- const qMin = 2;
- const qMax = 31;
- return Math.min(Math.max(qMin, quality, Math.round((1 - quality) * (qMax - qMin) + qMin)), qMax);
-}
-
function getQualityOpts({ captureFormat, quality }: { captureFormat: CaptureFormat, quality: number }) {
if (captureFormat === 'jpeg') return ['-q:v', String(getFfmpegJpegQuality(quality))];
if (captureFormat === 'webp') return ['-q:v', String(Math.max(0, Math.min(100, Math.round(quality * 100))))];
diff --git a/src/main/ffmpegUtil.test.ts b/src/main/ffmpegUtil.test.ts
new file mode 100644
index 00000000..7f9bc865
--- /dev/null
+++ b/src/main/ffmpegUtil.test.ts
@@ -0,0 +1,26 @@
+// eslint-disable-next-line import/no-extraneous-dependencies
+import { describe, expect, test } from 'vitest';
+import { getFfmpegJpegQuality } from './ffmpegUtil';
+
+describe('getFfmpegJpegQuality', () => {
+ test('quality 1 -> best (2)', () => {
+ expect(getFfmpegJpegQuality(1)).toBe(2);
+ });
+
+ test('quality 0 -> worst (31)', () => {
+ expect(getFfmpegJpegQuality(0)).toBe(31);
+ });
+
+ test('mid quality 0.5 -> 17', () => {
+ expect(getFfmpegJpegQuality(0.5)).toBe(17);
+ });
+
+ test('values below 0 are clamped to range (->31)', () => {
+ expect(getFfmpegJpegQuality(-1)).toBe(31);
+ });
+
+ test('values above 1 are clamped to range', () => {
+ // 2 is returned for small >1 values that are <= the internal qMin after rounding
+ expect(getFfmpegJpegQuality(100)).toBe(2);
+ });
+});
diff --git a/src/main/ffmpegUtil.ts b/src/main/ffmpegUtil.ts
new file mode 100644
index 00000000..057cae7f
--- /dev/null
+++ b/src/main/ffmpegUtil.ts
@@ -0,0 +1,12 @@
+/**
+ * Convert 0-1 quality to ffmpeg jpeg quality scale
+ * @param quality 0-1 where 1 is best quality
+ * @returns ffmpeg jpeg quality value
+ */
+// eslint-disable-next-line import/prefer-default-export
+export function getFfmpegJpegQuality(quality: number) {
+ // Normal range for JPEG is 2-31 with 31 being the worst quality.
+ const qMin = 2;
+ const qMax = 31;
+ return Math.min(Math.max(qMin, Math.round((1 - quality) * (qMax - qMin) + qMin)), qMax);
+}