media-compressor-js 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +61 -2
- package/package.json +35 -4
- package/src/browser/imageCompressor.js +154 -0
- package/src/browser/mediaDetect.js +123 -0
- package/src/browser/videoCompressor.js +264 -0
- package/src/imageCompressor.js +285 -0
- package/src/index.js +9 -0
- package/src/videoCompressor.js +207 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 opensourcecitizens
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# media-compressor-js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Image and video compression for Node and the browser. Two separate runtimes behind one interface:
|
|
4
|
+
|
|
5
|
+
- **`src/`** — Node. Compresses by spawning the real `ffmpeg`/`ffprobe` binaries as child processes. Used by the bulk-import CLI scripts in `examples/`.
|
|
6
|
+
- **`src/browser/`** — Browser. Compresses using Web APIs only (Canvas for images, ffmpeg.wasm for video) — no server round-trip. Used by the HTML demos in `examples/`.
|
|
7
|
+
|
|
8
|
+
Both expose the same shape: `probe(input, opts)`, `compress(input, output, probeInfo, opts)`, `extractThumbnail(input, output, ..., opts)`.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
npm install
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
const { imageCompressor, videoCompressor } = require('media-compressor-js');
|
|
20
|
+
|
|
21
|
+
const info = await videoCompressor.probe('input.mp4');
|
|
22
|
+
await videoCompressor.compress('input.mp4', 'output.mp4', info, { crf: 22, preset: 'slow' });
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Browser entry points are separate subpaths (`media-compressor-js/browser/imageCompressor`, etc.) since they depend on `window`/`Canvas`/ffmpeg.wasm and can't run in Node.
|
|
26
|
+
|
|
27
|
+
See `examples/` for runnable scripts and HTML demos of both.
|
|
28
|
+
|
|
29
|
+
## Media compression: algorithms and strategies
|
|
30
|
+
|
|
31
|
+
### Images — Node (`src/imageCompressor.js`)
|
|
32
|
+
|
|
33
|
+
Compresses via `ffmpeg`, choosing the output codec at runtime rather than hardcoding one, because `libwebp` is an optional ffmpeg build flag, not a given:
|
|
34
|
+
|
|
35
|
+
- **libwebp available** → WebP for everything (best compression, supports alpha and animation).
|
|
36
|
+
- **not available, no alpha channel** → MJPEG (`-q:v` mapped from a 0–100 quality to ffmpeg's 2–31 qscale, where 2 is best).
|
|
37
|
+
- **not available, source may have alpha** (`.png`/`.webp`) → PNG (lossless, keeps transparency rather than silently flattening it).
|
|
38
|
+
- **not available, animated** → GIF (ffmpeg's built-in encoder, preserves animation instead of collapsing to one frame).
|
|
39
|
+
|
|
40
|
+
ffmpeg capability is probed once per binary and cached, not re-probed per file. Downscaling is aspect-ratio-preserving and **never upscales** (`scale='min(iw,maxDim)':'min(ih,maxDim)'`). EXIF (including GPS) is stripped unconditionally via `-map_metadata -1` before any upload — a privacy default, not just a size one. Thumbnails reuse the same encode path with a smaller `maxDim`/`quality`, not a separate code path.
|
|
41
|
+
|
|
42
|
+
### Video — Node (`src/videoCompressor.js`)
|
|
43
|
+
|
|
44
|
+
`libx264` at a configurable CRF (default 22 — lower is better quality/bigger file) and preset (default `slow`), profile `high`, level `4.0`, `yuv420p` pixel format for broad compatibility. Audio is re-encoded to AAC 128kbps/48kHz when present, dropped entirely otherwise. Downscaling only triggers if the source is taller than `maxHeight` (`scale=-2:maxHeight`), never upscales.
|
|
45
|
+
|
|
46
|
+
Two strategies worth calling out specifically:
|
|
47
|
+
- **Deterministic re-encoding** (`opts.deterministic`): forces `-threads 1` plus `-fflags +bitexact -flags:v +bitexact`, so re-encoding an unchanged source produces the same bytes on every run — the same content-addressed CID on IPFS, avoiding duplicate pins of identical content. Costs encode speed (single-threaded) for that guarantee.
|
|
48
|
+
- **Progressive-start output**: `-movflags +faststart` moves the `moov` atom to the front of the file, so playback from an IPFS gateway can begin before the whole object has downloaded.
|
|
49
|
+
|
|
50
|
+
Thumbnails are a single JPEG frame grabbed at ~10% into the video's duration (`-ss` seek + `-frames:v 1`), not the first frame (often a black/blank frame).
|
|
51
|
+
|
|
52
|
+
### Images — Browser (`src/browser/imageCompressor.js`)
|
|
53
|
+
|
|
54
|
+
Canvas API only (`drawImage` → `toBlob`) — deliberately not ffmpeg.wasm, since a browser already has a native, zero-dependency way to re-encode a still image, unlike video. WebP is attempted first; if the browser's `toBlob` silently substitutes a different format (checked via the *returned* blob's real `.type`, not just trusting the request), it falls back to JPEG. Downscaling is aspect-ratio-preserving and never upscales. Animated GIF/WebP sources are **skipped untouched** rather than compressed — Canvas's `drawImage` only ever grabs a single frame, and silently flattening an animation to a still image is treated as a worse outcome than not compressing at all. EXIF is stripped as a side effect of the Canvas round-trip, not a separate step. If the compressed result isn't actually smaller than the source, the original is kept.
|
|
55
|
+
|
|
56
|
+
### Video — Browser (`src/browser/videoCompressor.js`)
|
|
57
|
+
|
|
58
|
+
ffmpeg.wasm (the same encoder as the Node path, compiled to WebAssembly, run in a Worker) — there's no native browser API for video re-encoding the way Canvas covers images. Real cost: ~30MB of WASM downloaded once per page session, and single-threaded, native-slow x264 encoding on the uploader's own device. To avoid paying that cost needlessly, `probe()` deliberately does **not** use ffmpeg.wasm at all — a native `<video>` element already gives duration/dimensions for free, so an over-long upload can be rejected before the WASM is ever loaded.
|
|
59
|
+
|
|
60
|
+
### Supporting strategy: content-based type detection (`src/browser/mediaDetect.js`)
|
|
61
|
+
|
|
62
|
+
Not a compression algorithm itself, but the strategy both image and video paths lean on: mime type is detected from the file's actual byte signature (magic numbers — PNG/GIF/JPEG headers, the RIFF/WEBP form type, the MP4 `ftyp` box), never from file extension or the browser-reported `.type`, both of which a renamed or mislabeled file would fool.
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "media-compressor-js",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Image and video compression for Node and the browser, built on ffmpeg/ffprobe (Node) and Canvas/ffmpeg.wasm (browser).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js",
|
|
9
|
+
"./browser/imageCompressor": "./src/browser/imageCompressor.js",
|
|
10
|
+
"./browser/videoCompressor": "./src/browser/videoCompressor.js",
|
|
11
|
+
"./browser/mediaDetect": "./src/browser/mediaDetect.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node --test"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"image-compression",
|
|
21
|
+
"video-compression",
|
|
22
|
+
"ffmpeg",
|
|
23
|
+
"ffprobe",
|
|
24
|
+
"canvas",
|
|
25
|
+
"ffmpeg-wasm",
|
|
26
|
+
"ipfs"
|
|
27
|
+
],
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "https://github.com/opensourcecitizens/media-compressor.git",
|
|
31
|
+
"directory": "js"
|
|
32
|
+
},
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/opensourcecitizens/media-compressor/issues"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/opensourcecitizens/media-compressor/tree/main/js#readme"
|
|
37
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// lib/browser/imageCompressor.js — client-side image compression via the
|
|
4
|
+
// Canvas API. Deliberately not ffmpeg.wasm: unlike video, a browser has a
|
|
5
|
+
// real, zero-dependency way to re-encode a still image (draw it to a
|
|
6
|
+
// <canvas>, read it back with toBlob) — no ~30MB WASM download needed just
|
|
7
|
+
// for images. This mirrors lib/imageCompressor.js's (the Node bulk-import
|
|
8
|
+
// path's) goals — downscale-only, WebP preferred with a safe fallback,
|
|
9
|
+
// never ship a file bigger than the source — using browser-native APIs
|
|
10
|
+
// instead of shelling out to a native ffmpeg binary, which isn't available
|
|
11
|
+
// in a browser at all.
|
|
12
|
+
//
|
|
13
|
+
// What's NOT attempted here, on purpose:
|
|
14
|
+
// - Animated GIF/WebP: Canvas's drawImage only ever grabs a single
|
|
15
|
+
// frame. Re-encoding an animated source through this path would
|
|
16
|
+
// silently flatten it to a still image — the exact failure mode
|
|
17
|
+
// lib/imageCompressor.js's Node-side codec selection (picking `gif` as
|
|
18
|
+
// a fallback specifically because it preserves animation) was built
|
|
19
|
+
// to avoid. So any GIF or WebP input is skipped untouched here rather
|
|
20
|
+
// than risk destroying an animation this code can't detect frame
|
|
21
|
+
// count for cheaply. compress() reports `skipped: true` with a reason
|
|
22
|
+
// so callers can tell "not compressed" apart from "failed".
|
|
23
|
+
// - EXIF stripping isn't a separate step: Canvas's drawImage/toBlob
|
|
24
|
+
// round-trip drops all metadata (including GPS EXIF tags) by
|
|
25
|
+
// construction — the same privacy outcome lib/imageCompressor.js gets
|
|
26
|
+
// from `-map_metadata -1`, just automatic here rather than a flag.
|
|
27
|
+
//
|
|
28
|
+
// Plain <script src> global (window.BrowserImageCompressor) — see
|
|
29
|
+
// mediaDetect.js's header for why there's no module system in this
|
|
30
|
+
// directory.
|
|
31
|
+
|
|
32
|
+
(function (global) {
|
|
33
|
+
const SKIP_MIME_TYPES = { 'image/gif': true, 'image/webp': true };
|
|
34
|
+
|
|
35
|
+
function scaleDimensions(width, height, maxDim) {
|
|
36
|
+
if (!maxDim || (width <= maxDim && height <= maxDim)) return { width, height };
|
|
37
|
+
const scale = maxDim / Math.max(width, height);
|
|
38
|
+
return {
|
|
39
|
+
width: Math.max(1, Math.round(width * scale)),
|
|
40
|
+
height: Math.max(1, Math.round(height * scale)),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function loadBitmap(file) {
|
|
45
|
+
// createImageBitmap decodes off the main thread and works directly
|
|
46
|
+
// from a Blob in every current browser; fall back to the classic
|
|
47
|
+
// <img> + object URL dance only if it's unavailable.
|
|
48
|
+
if (typeof createImageBitmap === 'function') {
|
|
49
|
+
return createImageBitmap(file);
|
|
50
|
+
}
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
const url = URL.createObjectURL(file);
|
|
53
|
+
const img = new Image();
|
|
54
|
+
img.onload = () => {
|
|
55
|
+
URL.revokeObjectURL(url);
|
|
56
|
+
resolve(img);
|
|
57
|
+
};
|
|
58
|
+
img.onerror = () => {
|
|
59
|
+
URL.revokeObjectURL(url);
|
|
60
|
+
reject(new Error('could not decode image'));
|
|
61
|
+
};
|
|
62
|
+
img.src = url;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function canvasToBlob(canvas, mime, quality) {
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
canvas.toBlob(
|
|
69
|
+
(blob) => (blob ? resolve(blob) : reject(new Error(`canvas.toBlob produced no data for ${mime}`))),
|
|
70
|
+
mime,
|
|
71
|
+
quality
|
|
72
|
+
);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Encodes `canvas` preferring WebP, falling back to JPEG if the browser
|
|
78
|
+
* doesn't actually support WebP output. Some browsers accept the mime
|
|
79
|
+
* string without complaint but silently hand back a PNG anyway — that's
|
|
80
|
+
* detected by checking the returned blob's real .type, not just trusting
|
|
81
|
+
* the request. Others reject/produce no blob at all for an unsupported
|
|
82
|
+
* type rather than substituting one — canvasToBlob rejects in that case,
|
|
83
|
+
* so the webp attempt is wrapped rather than left to propagate, or an
|
|
84
|
+
* unsupported browser would throw here instead of falling back to jpeg.
|
|
85
|
+
*/
|
|
86
|
+
async function encodeCanvas(canvas, quality) {
|
|
87
|
+
try {
|
|
88
|
+
const webp = await canvasToBlob(canvas, 'image/webp', quality);
|
|
89
|
+
if (webp.type === 'image/webp') return { blob: webp, mime: 'image/webp' };
|
|
90
|
+
} catch (err) {
|
|
91
|
+
// fall through to jpeg below
|
|
92
|
+
}
|
|
93
|
+
const jpeg = await canvasToBlob(canvas, 'image/jpeg', quality);
|
|
94
|
+
return { blob: jpeg, mime: 'image/jpeg' };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Compresses an image File/Blob. Returns:
|
|
99
|
+
* { blob, mime, width, height, skipped, reason }
|
|
100
|
+
* `skipped: true` (blob === the original file, mime === its detected
|
|
101
|
+
* type) means "left untouched" — an animated source, a decode failure,
|
|
102
|
+
* or a case where compression didn't actually save anything — not a
|
|
103
|
+
* thrown error; callers upload `blob` either way.
|
|
104
|
+
*
|
|
105
|
+
* opts: { quality=0.8 (Canvas toBlob's native 0–1 scale, not the Node
|
|
106
|
+
* lib's 0–100 -q:v scale — deliberately not translated, so this
|
|
107
|
+
* reads like ordinary Canvas API code), maxDim=1920 }
|
|
108
|
+
*/
|
|
109
|
+
async function compress(file, opts) {
|
|
110
|
+
opts = opts || {};
|
|
111
|
+
const quality = opts.quality != null ? opts.quality : 0.8;
|
|
112
|
+
const maxDim = opts.maxDim || 1920;
|
|
113
|
+
|
|
114
|
+
const detected = await global.MediaDetect.detectFile(file);
|
|
115
|
+
const mime = detected.mime || file.type || null;
|
|
116
|
+
|
|
117
|
+
if (mime && SKIP_MIME_TYPES[mime]) {
|
|
118
|
+
return { blob: file, mime: mime, width: null, height: null, skipped: true, reason: 'animated-source-not-recompressed' };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
let bitmap;
|
|
122
|
+
try {
|
|
123
|
+
bitmap = await loadBitmap(file);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
return { blob: file, mime: mime, width: null, height: null, skipped: true, reason: `decode-failed: ${err.message}` };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ImageBitmap only ever has .width/.height; the <img> fallback path's
|
|
129
|
+
// HTMLImageElement has both, but .naturalWidth/.naturalHeight is the
|
|
130
|
+
// platform-correct property for its actual decoded size (.width can
|
|
131
|
+
// reflect CSS/layout, not that this element is ever attached to the
|
|
132
|
+
// DOM here, but naturalWidth is unambiguous regardless).
|
|
133
|
+
const sourceWidth = bitmap.naturalWidth != null ? bitmap.naturalWidth : bitmap.width;
|
|
134
|
+
const sourceHeight = bitmap.naturalHeight != null ? bitmap.naturalHeight : bitmap.height;
|
|
135
|
+
const { width, height } = scaleDimensions(sourceWidth, sourceHeight, maxDim);
|
|
136
|
+
|
|
137
|
+
const canvas = document.createElement('canvas');
|
|
138
|
+
canvas.width = width;
|
|
139
|
+
canvas.height = height;
|
|
140
|
+
const ctx = canvas.getContext('2d');
|
|
141
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
142
|
+
if (bitmap.close) bitmap.close(); // release ImageBitmap decode memory promptly
|
|
143
|
+
|
|
144
|
+
const encoded = await encodeCanvas(canvas, quality);
|
|
145
|
+
|
|
146
|
+
if (encoded.blob.size >= file.size) {
|
|
147
|
+
return { blob: file, mime: mime, width: sourceWidth, height: sourceHeight, skipped: true, reason: 'compressed-not-smaller' };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { blob: encoded.blob, mime: encoded.mime, width: width, height: height, skipped: false, reason: null };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
global.BrowserImageCompressor = { compress: compress };
|
|
154
|
+
})(typeof window !== 'undefined' ? window : this);
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// lib/browser/mediaDetect.js — byte-signature (magic-number) detection of
|
|
4
|
+
// image/video mime type from the first bytes of a File/Blob's actual
|
|
5
|
+
// contents, not its extension or browser-reported .type (a renamed or
|
|
6
|
+
// mislabeled file would fool either of those; this looks at what the
|
|
7
|
+
// bytes actually are).
|
|
8
|
+
//
|
|
9
|
+
// Same algorithm as web/components/ImageViewer.js's detectMime and the
|
|
10
|
+
// getMimeType duplicates elsewhere in this repo — see
|
|
11
|
+
// ../../../../shared/mime-sniff/README.md for why there are multiple
|
|
12
|
+
// copies instead of one shared module (three incompatible bundlers/
|
|
13
|
+
// runtimes, no workspace tooling) and how they're kept honest: this file
|
|
14
|
+
// is checked against the same shared/mime-sniff/test-vectors.js spec via
|
|
15
|
+
// check-sync.js's TARGETS, so it can't silently drift from the other five.
|
|
16
|
+
//
|
|
17
|
+
// Plain <script src> global (window.MediaDetect), no module system —
|
|
18
|
+
// matches how every other file in this directory (ipfsconnector_http.js,
|
|
19
|
+
// ipfsconnector_ws.js) is loaded by the *.html seed tools; there's no bundler
|
|
20
|
+
// here to hand an ES module to.
|
|
21
|
+
|
|
22
|
+
(function (global) {
|
|
23
|
+
function toHex(bytes) {
|
|
24
|
+
return Array.from(bytes)
|
|
25
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
26
|
+
.join('')
|
|
27
|
+
.toUpperCase();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function detectMime(bytes) {
|
|
31
|
+
const header = toHex(bytes.slice(0, 4));
|
|
32
|
+
switch (header) {
|
|
33
|
+
case '89504E47':
|
|
34
|
+
return 'image/png';
|
|
35
|
+
case '47494638':
|
|
36
|
+
return 'image/gif';
|
|
37
|
+
case 'FFD8FFDB':
|
|
38
|
+
case 'FFD8FFE0':
|
|
39
|
+
case 'FFD8FFFE':
|
|
40
|
+
case 'FFD8FFE1':
|
|
41
|
+
return 'image/jpeg';
|
|
42
|
+
case '52494646': {
|
|
43
|
+
// RIFF is a generic container (WebP, WAV, AVI, ...) - the form
|
|
44
|
+
// type at byte offset 8 is what actually says "WEBP". This is the
|
|
45
|
+
// format lib/imageCompressor.js (the Node bulk-import path)
|
|
46
|
+
// prefers whenever the ffmpeg build it runs on has libwebp.
|
|
47
|
+
const form = toHex(bytes.slice(8, 12));
|
|
48
|
+
return form === '57454250' ? 'image/webp' : null;
|
|
49
|
+
}
|
|
50
|
+
default: {
|
|
51
|
+
// MP4 ftyp box lives at byte offset 4 (e.g. ....ftypisom) -
|
|
52
|
+
// videoCompressor.js always emits mp4 via `-f mp4`, brand
|
|
53
|
+
// confirmed as "isom" against real ffmpeg output.
|
|
54
|
+
const ftyp = toHex(bytes.slice(4, 12));
|
|
55
|
+
switch (ftyp) {
|
|
56
|
+
case '6674797069736F6D': // ftyp isom
|
|
57
|
+
case '667479704D534E56': // ftyp MSNV
|
|
58
|
+
case '6674797071742020': // ftyp qt
|
|
59
|
+
return 'video/mp4';
|
|
60
|
+
default:
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 'image' | 'video' | null, derived from the detected mime.
|
|
68
|
+
function detectMediaKind(mime) {
|
|
69
|
+
if (!mime) return null;
|
|
70
|
+
if (mime.indexOf('image/') === 0) return 'image';
|
|
71
|
+
if (mime.indexOf('video/') === 0) return 'video';
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Reads `file` (a File/Blob) into a Uint8Array of its full contents.
|
|
77
|
+
* The one shared FileReader-to-bytes implementation — detectFile below
|
|
78
|
+
* uses it (sliced to the first 12 bytes) instead of duplicating the
|
|
79
|
+
* reader setup, and IpfsConnector's getAsByteArray (ipfsconnector_http.js /
|
|
80
|
+
* ipfsconnector_ws.js, used by uploadipfs.html before an upload) delegates
|
|
81
|
+
* here instead of keeping its own copy.
|
|
82
|
+
*/
|
|
83
|
+
function getAsByteArray(file) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const reader = new FileReader();
|
|
86
|
+
reader.addEventListener('loadend', (e) => resolve(new Uint8Array(e.target.result)));
|
|
87
|
+
reader.addEventListener('error', () => reject(reader.error || new Error('failed to read file')));
|
|
88
|
+
reader.readAsArrayBuffer(file);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Reads just enough of `file` (a File/Blob) to run byte-signature
|
|
94
|
+
* detection — 12 bytes covers every format in the switch above, so this
|
|
95
|
+
* never reads the whole file just to classify it.
|
|
96
|
+
* Resolves { mime, kind } — both null when the bytes aren't recognized.
|
|
97
|
+
*/
|
|
98
|
+
function detectFile(file) {
|
|
99
|
+
return getAsByteArray(file.slice(0, 12)).then((bytes) => {
|
|
100
|
+
const mime = detectMime(bytes);
|
|
101
|
+
return { mime: mime, kind: detectMediaKind(mime) };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const MediaDetect = {
|
|
106
|
+
detectMime: detectMime,
|
|
107
|
+
detectMediaKind: detectMediaKind,
|
|
108
|
+
detectFile: detectFile,
|
|
109
|
+
getAsByteArray: getAsByteArray,
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
global.MediaDetect = MediaDetect;
|
|
113
|
+
|
|
114
|
+
// Also exported via module.exports (in addition to, not instead of, the
|
|
115
|
+
// window global above) so bundler-based code — e.g. src/react's
|
|
116
|
+
// ImageViewer — can `require`/`import` this file directly instead of
|
|
117
|
+
// depending on load order and a shared global. The *.html seed tools
|
|
118
|
+
// still load this as a plain <script src> global; this branch is a
|
|
119
|
+
// no-op there (no `module` global exists in that context).
|
|
120
|
+
if (typeof module !== 'undefined' && module.exports) {
|
|
121
|
+
module.exports = MediaDetect;
|
|
122
|
+
}
|
|
123
|
+
})(typeof window !== 'undefined' ? window : this);
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// lib/browser/videoCompressor.js — client-side video compression via
|
|
4
|
+
// ffmpeg.wasm. Unlike images (see imageCompressor.js), a browser has no
|
|
5
|
+
// native way to re-encode video — this is genuinely the same library the
|
|
6
|
+
// original (now-replaced) mp4video_ffmpeg_compression.js sketch reached
|
|
7
|
+
// for, done with the current API and sane settings this time (that sketch
|
|
8
|
+
// used `-crf 0`, which is *larger* than the source and often undecodable
|
|
9
|
+
// on iOS/Safari; see examplecompressbulk.js's header for the full
|
|
10
|
+
// writeup). ffmpeg itself isn't available as a native binary in a browser
|
|
11
|
+
// the way lib/videoCompressor.js (the Node bulk-import path) can shell out
|
|
12
|
+
// to it — this is the WASM build of the same encoder, run in a Worker.
|
|
13
|
+
//
|
|
14
|
+
// Real cost of that: ~30MB of WASM downloaded (once — cached across calls
|
|
15
|
+
// in this page's lifetime, not per file) and native-slow, single-threaded
|
|
16
|
+
// x264 encoding on the uploader's own device. That's why `probe()` below
|
|
17
|
+
// deliberately does NOT use ffmpeg.wasm at all — a native <video> element
|
|
18
|
+
// already gives duration/dimensions for free, so the 30s cap
|
|
19
|
+
// examplecompressbulk.js/importcompressedbulk.js enforce server-side can
|
|
20
|
+
// be checked, and a too-long upload rejected, *before* ever paying to load
|
|
21
|
+
// ffmpeg.wasm.
|
|
22
|
+
//
|
|
23
|
+
// CDN + global names below were confirmed against the live npm registry
|
|
24
|
+
// and unpkg's actual file listing while building this, not assumed from
|
|
25
|
+
// memory — @ffmpeg/ffmpeg's UMD build assigns `window.FFmpegWASM.FFmpeg`,
|
|
26
|
+
// @ffmpeg/util's assigns `window.FFmpegUtil.{fetchFile, toBlobURL}`. If
|
|
27
|
+
// you bump these versions, re-check both — UMD global names are not part
|
|
28
|
+
// of any semver contract.
|
|
29
|
+
//
|
|
30
|
+
// Plain <script src> global (window.BrowserVideoCompressor) — see
|
|
31
|
+
// mediaDetect.js's header for why there's no module system in this
|
|
32
|
+
// directory.
|
|
33
|
+
|
|
34
|
+
(function (global) {
|
|
35
|
+
// @ffmpeg/ffmpeg is pinned to 0.12.10 specifically, not just "whatever's
|
|
36
|
+
// current" - this matters here. Its worker chunk (814.ffmpeg.js below)
|
|
37
|
+
// tries `importScripts(coreURL)` first and falls back to a dynamic
|
|
38
|
+
// `import(coreURL)` if that throws, which it always does inside a module
|
|
39
|
+
// worker (spec behavior, confirmed via MDN - not origin-dependent, so
|
|
40
|
+
// self-hosting these files instead of using a CDN would NOT avoid this).
|
|
41
|
+
// In 0.12.11+ (checked up through 0.12.15) and in 0.12.7-0.12.9, that
|
|
42
|
+
// fallback is bundled as webpack's auto-generated stub for an
|
|
43
|
+
// unresolvable dynamic require - a dead function that unconditionally
|
|
44
|
+
// throws `Error("Cannot find module '"+url+"'")` no matter what URL you
|
|
45
|
+
// give it. That's the exact, literal source of a
|
|
46
|
+
// "Cannot find module 'blob:...'" error from inside ffmpeg.load().
|
|
47
|
+
// 0.12.10's build is the one confirmed (by diffing the actual fetched
|
|
48
|
+
// chunk content, not assumed) to still bundle a real, working
|
|
49
|
+
// `await import(r)` in that fallback path instead of the broken stub -
|
|
50
|
+
// matches the @ffmpeg/core version already pinned below. Re-verify this
|
|
51
|
+
// exact regression before bumping either version.
|
|
52
|
+
const FFMPEG_JS_URL = 'https://unpkg.com/@ffmpeg/ffmpeg@0.12.10/dist/umd/ffmpeg.js';
|
|
53
|
+
const FFMPEG_UTIL_URL = 'https://unpkg.com/@ffmpeg/util@0.12.1/dist/umd/index.js';
|
|
54
|
+
// Must be the `esm` build, not `umd`, despite everything else here being
|
|
55
|
+
// UMD - confirmed by diffing both: dist/umd/ffmpeg-core.js is a plain
|
|
56
|
+
// script (`var createFFmpegCore = ...`), zero `export` statements; only
|
|
57
|
+
// dist/esm/ffmpeg-core.js ends with `export default createFFmpegCore`.
|
|
58
|
+
// The worker's fallback loader (see 814.ffmpeg.js's note above) grabs
|
|
59
|
+
// the core via a real dynamic `import(coreURL)`, which needs an actual
|
|
60
|
+
// ES module - importing the UMD build "succeeds" (it's syntactically
|
|
61
|
+
// valid JS either way) but yields an empty module namespace, so
|
|
62
|
+
// `.default` comes back undefined and it throws
|
|
63
|
+
// "failed to import ffmpeg-core.js". Matches what the worker's own code
|
|
64
|
+
// does by default (it swaps "/umd/" for "/esm/" on its fallback URL
|
|
65
|
+
// when no coreURL is given at all) - passing an explicit coreURL skips
|
|
66
|
+
// that swap, so it has to be pre-pointed at esm here instead.
|
|
67
|
+
const FFMPEG_CORE_BASE = 'https://unpkg.com/@ffmpeg/core@0.12.10/dist/esm';
|
|
68
|
+
// Worker chunk id (814) is webpack's internal numeric chunk id, not part
|
|
69
|
+
// of any semver contract, but has been stable across every 0.12.x build
|
|
70
|
+
// checked while diagnosing this. See getFfmpeg() below for why this
|
|
71
|
+
// needs to be loaded as a blob: URL (classWorkerURL) at all - separate
|
|
72
|
+
// issue (cross-origin Worker construction) from the one above.
|
|
73
|
+
const FFMPEG_WORKER_URL = 'https://unpkg.com/@ffmpeg/ffmpeg@0.12.10/dist/umd/814.ffmpeg.js';
|
|
74
|
+
|
|
75
|
+
function loadScriptOnce(src, type) {
|
|
76
|
+
return new Promise((resolve, reject) => {
|
|
77
|
+
// NOTE: do not set window.exports (or window.module) here. Both
|
|
78
|
+
// @ffmpeg/ffmpeg's and @ffmpeg/util's UMD builds branch on
|
|
79
|
+
// `typeof exports === "object"` to decide whether they're in a
|
|
80
|
+
// CommonJS environment; in a plain <script src> browser load that's
|
|
81
|
+
// "undefined", so they correctly fall through to assigning the
|
|
82
|
+
// global (window.FFmpegWASM / window.FFmpegUtil). Pre-defining
|
|
83
|
+
// window.exports = {} makes that check true and diverts them into
|
|
84
|
+
// setting window.exports.FFmpegWASM / .FFmpegUtil instead — the
|
|
85
|
+
// exact cause of "Cannot read properties of undefined (reading
|
|
86
|
+
// 'FFmpeg')" a few lines below. Don't reintroduce it.
|
|
87
|
+
//
|
|
88
|
+
// Also don't load either file as `<script type="module">` — both
|
|
89
|
+
// are plain UMD bundles (verified against the actual published
|
|
90
|
+
// files, not ES modules with `export` statements), so a module
|
|
91
|
+
// script tag changes how they're parsed/executed for no benefit.
|
|
92
|
+
const existing = document.querySelector(`script[data-ffmpeg-loader="${src}"]`);
|
|
93
|
+
if (existing) {
|
|
94
|
+
existing.addEventListener('load', () => resolve());
|
|
95
|
+
existing.addEventListener('error', () => reject(new Error(`failed to load ${src}`)));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const el = document.createElement('script');
|
|
99
|
+
el.src = src;
|
|
100
|
+
if(type != null) el.type = type;
|
|
101
|
+
el.setAttribute('data-ffmpeg-loader', src);
|
|
102
|
+
el.onload = () => resolve();
|
|
103
|
+
el.onerror = () => reject(new Error(`failed to load ${src}`));
|
|
104
|
+
document.head.appendChild(el);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Loaded (or in-flight) at most once per page load, not once per file -
|
|
109
|
+
// this is the ~30MB-download cost, paid once regardless of how many
|
|
110
|
+
// videos get compressed in this session.
|
|
111
|
+
let ffmpegPromise = null;
|
|
112
|
+
|
|
113
|
+
function getFfmpeg() {
|
|
114
|
+
if (!ffmpegPromise) {
|
|
115
|
+
ffmpegPromise = (async () => {
|
|
116
|
+
if (!global.FFmpegWASM) await loadScriptOnce(FFMPEG_JS_URL);
|
|
117
|
+
if (!global.FFmpegUtil) await loadScriptOnce(FFMPEG_UTIL_URL);
|
|
118
|
+
const FFmpeg = global.FFmpegWASM.FFmpeg;
|
|
119
|
+
const toBlobURL = global.FFmpegUtil.toBlobURL;
|
|
120
|
+
const ffmpeg = new FFmpeg();
|
|
121
|
+
await ffmpeg.load({
|
|
122
|
+
coreURL: await toBlobURL(`${FFMPEG_CORE_BASE}/ffmpeg-core.js`, 'text/javascript'),
|
|
123
|
+
wasmURL: await toBlobURL(`${FFMPEG_CORE_BASE}/ffmpeg-core.wasm`, 'application/wasm'),
|
|
124
|
+
classWorkerURL: await toBlobURL(FFMPEG_WORKER_URL, 'text/javascript'),
|
|
125
|
+
});
|
|
126
|
+
//console.log('getFfmpeg ... loaded ffmpeg',ffmpeg);
|
|
127
|
+
return ffmpeg;
|
|
128
|
+
})().catch((err) => {
|
|
129
|
+
console.error(err);
|
|
130
|
+
ffmpegPromise = null; // let a retry actually retry instead of replaying the same failure forever
|
|
131
|
+
throw err;
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
return ffmpegPromise;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Reads duration + dimensions via a native <video> element's metadata -
|
|
139
|
+
* zero ffmpeg cost. Rejects on a corrupt/unsupported file rather than
|
|
140
|
+
* hanging; always revokes its object URL.
|
|
141
|
+
* Resolves { durationSec, width, height }.
|
|
142
|
+
*/
|
|
143
|
+
function probe(file) {
|
|
144
|
+
return new Promise((resolve, reject) => {
|
|
145
|
+
const url = URL.createObjectURL(file);
|
|
146
|
+
const videoEl = document.createElement('video');
|
|
147
|
+
videoEl.preload = 'metadata';
|
|
148
|
+
videoEl.muted = true;
|
|
149
|
+
|
|
150
|
+
const cleanup = () => URL.revokeObjectURL(url);
|
|
151
|
+
|
|
152
|
+
videoEl.onloadedmetadata = () => {
|
|
153
|
+
const duration = videoEl.duration;
|
|
154
|
+
cleanup();
|
|
155
|
+
if (!Number.isFinite(duration)) {
|
|
156
|
+
reject(new Error('could not determine duration (no metadata reported)'));
|
|
157
|
+
} else {
|
|
158
|
+
resolve({ durationSec: duration, width: videoEl.videoWidth, height: videoEl.videoHeight });
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
videoEl.onerror = () => {
|
|
162
|
+
cleanup();
|
|
163
|
+
reject(new Error('could not read video metadata (corrupt or unsupported file)'));
|
|
164
|
+
};
|
|
165
|
+
videoEl.src = url;
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function guessInputExt(file) {
|
|
170
|
+
const m = /\.[a-z0-9]+$/i.exec(file.name || '');
|
|
171
|
+
return m ? m[0] : '.mp4';
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Re-encodes `file` to mp4 (libx264/aac, faststart) via ffmpeg.wasm.
|
|
176
|
+
* Mirrors lib/videoCompressor.js's flags (crf/faststart/pix_fmt) with a
|
|
177
|
+
* faster default preset — WASM x264 is far slower than the native
|
|
178
|
+
* binary that library shells out to, and this runs on the uploader's
|
|
179
|
+
* own device/tab rather than a bulk-import server that can afford to
|
|
180
|
+
* wait. `-c:a aac` is always included regardless of whether the source
|
|
181
|
+
* has audio — verified against real ffmpeg (not assumed): encoding a
|
|
182
|
+
* silent input with `-c:a aac` present exits 0 and simply produces no
|
|
183
|
+
* audio stream, it does not error.
|
|
184
|
+
*
|
|
185
|
+
* probeInfo: from probe() above — used only to decide whether to scale.
|
|
186
|
+
* opts: { crf=23, preset='veryfast', maxHeight=1080, onLog(message) }
|
|
187
|
+
* Returns { blob, mime, width, height, skipped, reason } — same shape as
|
|
188
|
+
* imageCompressor.js's compress(), so callers don't need to branch on
|
|
189
|
+
* media kind to read the result.
|
|
190
|
+
*/
|
|
191
|
+
async function compress(file, probeInfo, opts) {
|
|
192
|
+
opts = opts || {};
|
|
193
|
+
const ffmpeg = await getFfmpeg();
|
|
194
|
+
const fetchFile = global.FFmpegUtil.fetchFile;
|
|
195
|
+
let removeLogListener = null;
|
|
196
|
+
if (opts.onLog) {
|
|
197
|
+
const handler = ({ message }) => opts.onLog(message);
|
|
198
|
+
ffmpeg.on('log', handler);
|
|
199
|
+
removeLogListener = () => ffmpeg.off('log', handler);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const inputName = 'input' + guessInputExt(file);
|
|
203
|
+
const outputName = 'output.mp4';
|
|
204
|
+
|
|
205
|
+
try {
|
|
206
|
+
await ffmpeg.writeFile(inputName, await fetchFile(file));
|
|
207
|
+
|
|
208
|
+
const args = ['-i', inputName, '-map_metadata', '-1'];
|
|
209
|
+
if (opts.maxHeight && probeInfo && probeInfo.height > opts.maxHeight) {
|
|
210
|
+
args.push('-vf', `scale=-2:${opts.maxHeight}`);
|
|
211
|
+
}
|
|
212
|
+
args.push(
|
|
213
|
+
'-c:v', 'libx264',
|
|
214
|
+
'-preset', opts.preset || 'veryfast',
|
|
215
|
+
'-crf', String(opts.crf != null ? opts.crf : 23),
|
|
216
|
+
'-pix_fmt', 'yuv420p',
|
|
217
|
+
'-c:a', 'aac',
|
|
218
|
+
'-b:a', '128k',
|
|
219
|
+
'-movflags', '+faststart',
|
|
220
|
+
outputName
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
const exitCode = await ffmpeg.exec(args);
|
|
224
|
+
if (exitCode !== 0) throw new Error(`ffmpeg.wasm exited ${exitCode} — see console for the log if opts.onLog wasn't set`);
|
|
225
|
+
|
|
226
|
+
const data = await ffmpeg.readFile(outputName);
|
|
227
|
+
const compressedBlob = new Blob([data.buffer], { type: 'video/mp4' });
|
|
228
|
+
|
|
229
|
+
// Never ship a file bigger than the source — same rule
|
|
230
|
+
// imageCompressor.js applies, and lib/videoCompressor.js (the Node
|
|
231
|
+
// bulk-import path) applies server-side. Returned in the same shape
|
|
232
|
+
// as imageCompressor.js's compress() ({ blob, mime, width, height,
|
|
233
|
+
// skipped, reason }) rather than a bare Blob, so callers can treat
|
|
234
|
+
// either media kind identically.
|
|
235
|
+
if (compressedBlob.size >= file.size) {
|
|
236
|
+
return {
|
|
237
|
+
blob: file,
|
|
238
|
+
mime: file.type || null,
|
|
239
|
+
width: probeInfo && probeInfo.width,
|
|
240
|
+
height: probeInfo && probeInfo.height,
|
|
241
|
+
skipped: true,
|
|
242
|
+
reason: 'compressed-not-smaller',
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
blob: compressedBlob,
|
|
247
|
+
mime: 'video/mp4',
|
|
248
|
+
width: probeInfo && probeInfo.width,
|
|
249
|
+
height: probeInfo && probeInfo.height,
|
|
250
|
+
skipped: false,
|
|
251
|
+
reason: null,
|
|
252
|
+
};
|
|
253
|
+
} finally {
|
|
254
|
+
if (removeLogListener) removeLogListener();
|
|
255
|
+
// Best-effort cleanup of ffmpeg's virtual FS — a failure to delete
|
|
256
|
+
// (e.g. writeFile itself never succeeded) shouldn't mask the real
|
|
257
|
+
// error from the try block above.
|
|
258
|
+
await ffmpeg.deleteFile(inputName).catch(() => {});
|
|
259
|
+
await ffmpeg.deleteFile(outputName).catch(() => {});
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
global.BrowserVideoCompressor = { probe: probe, compress: compress };
|
|
264
|
+
})(typeof window !== 'undefined' ? window : this);
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// lib/imageCompressor.js — native-ffmpeg image compression, mirroring
|
|
4
|
+
// lib/videoCompressor.js's shape so importcompressedbulk.js can call either compressor
|
|
5
|
+
// through the same interface (probe / compress / extractThumbnail).
|
|
6
|
+
//
|
|
7
|
+
// Uses ffmpeg rather than a separate image library (sharp/libvips, etc.) on
|
|
8
|
+
// purpose: ffmpeg is already a hard dependency for video, so this avoids
|
|
9
|
+
// adding a second native-compiled dependency just for images.
|
|
10
|
+
//
|
|
11
|
+
// Output format is chosen at runtime, not hardcoded, because libwebp is an
|
|
12
|
+
// *optional* ffmpeg build flag, not a given — confirmed the hard way:
|
|
13
|
+
// Homebrew's own `ffmpeg` formula on macOS ships without it (no `webp`
|
|
14
|
+
// dependency in `brew deps ffmpeg`), while most Debian/Ubuntu apt packages
|
|
15
|
+
// do include it. So:
|
|
16
|
+
// - libwebp available -> WebP for everything (best compression, alpha,
|
|
17
|
+
// animation support).
|
|
18
|
+
// - not available, source has no alpha -> MJPEG (near-universal, lossy,
|
|
19
|
+
// small).
|
|
20
|
+
// - not available, source may have alpha (.png/.webp) -> PNG (lossless,
|
|
21
|
+
// always built in, keeps transparency correct over silently discarding
|
|
22
|
+
// it).
|
|
23
|
+
// - not available, animated -> GIF (ffmpeg's native encoder, no external
|
|
24
|
+
// lib needed, keeps the animation instead of collapsing it to one frame).
|
|
25
|
+
// Capability is probed once per ffmpeg binary and cached — see
|
|
26
|
+
// getCapabilities() — so this costs one extra spawn per run, not per file.
|
|
27
|
+
// compress()/extractThumbnail() return the *actual* output path used, since
|
|
28
|
+
// the extension depends on which of these was picked; callers must use the
|
|
29
|
+
// returned path rather than assume the one they requested.
|
|
30
|
+
//
|
|
31
|
+
// Pure functions only: no CLI parsing, no process.exit(), no console
|
|
32
|
+
// output — see lib/videoCompressor.js's header comment for the rationale.
|
|
33
|
+
|
|
34
|
+
const path = require('path');
|
|
35
|
+
const { spawn } = require('child_process');
|
|
36
|
+
|
|
37
|
+
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tif', '.tiff']);
|
|
38
|
+
|
|
39
|
+
// Extensions that can plausibly be animated. Anything else skips the extra
|
|
40
|
+
// -count_frames probe pass below (slow — it fully decodes the file).
|
|
41
|
+
// NOTE: animated PNG (APNG) is not detected here and will be compressed as
|
|
42
|
+
// a static image, losing its animation. Flag this to callers if APNG shows
|
|
43
|
+
// up in real uploads; not expected from the current mobile capture flow.
|
|
44
|
+
const POSSIBLY_ANIMATED_EXTENSIONS = new Set(['.gif', '.webp']);
|
|
45
|
+
|
|
46
|
+
// ffmpeg/ffprobe always print a ~10-line version/build-config/library-
|
|
47
|
+
// version banner to stderr before anything else, regardless of whether the
|
|
48
|
+
// call fails. `-hide_banner` (added at every call site below) stops it at
|
|
49
|
+
// the source; this is a second, defensive pass over whatever stderr shows
|
|
50
|
+
// up anyway (a caller that forgets the flag, or an unexpected ffmpeg
|
|
51
|
+
// build), so an error message is never mostly boilerplate someone has to
|
|
52
|
+
// scroll past to find the one line that matters.
|
|
53
|
+
function cleanStderr(stderr) {
|
|
54
|
+
return stderr
|
|
55
|
+
.split('\n')
|
|
56
|
+
.filter((line) => !/^ffmpeg version |^ {2}(built with|configuration:|lib(avutil|avcodec|avformat|avdevice|avfilter|swscale|swresample|postproc)\s)/.test(line))
|
|
57
|
+
.join('\n')
|
|
58
|
+
.trim();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Renders argv back into a copy-pasteable command line for error messages -
|
|
62
|
+
// informational only (naive whitespace quoting, not real shell escaping).
|
|
63
|
+
function formatCommand(bin, args) {
|
|
64
|
+
const quoted = args.map((a) => (/\s/.test(a) ? `"${a}"` : a));
|
|
65
|
+
return [bin, ...quoted].join(' ');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function runCommand(bin, args, { timeoutMs = 60000 } = {}) {
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
let proc;
|
|
71
|
+
try {
|
|
72
|
+
proc = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
73
|
+
} catch (err) {
|
|
74
|
+
reject(err);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let stdout = Buffer.alloc(0);
|
|
79
|
+
let stderr = '';
|
|
80
|
+
let timedOut = false;
|
|
81
|
+
const timer = setTimeout(() => {
|
|
82
|
+
timedOut = true;
|
|
83
|
+
proc.kill('SIGKILL');
|
|
84
|
+
}, timeoutMs);
|
|
85
|
+
|
|
86
|
+
proc.stdout.on('data', (chunk) => { stdout = Buffer.concat([stdout, chunk]); });
|
|
87
|
+
proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
|
|
88
|
+
|
|
89
|
+
proc.on('error', (err) => {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
if (err.code === 'ENOENT') {
|
|
92
|
+
reject(new Error(`'${bin}' not found on PATH — install ffmpeg or set FFMPEG_PATH/FFPROBE_PATH`));
|
|
93
|
+
} else {
|
|
94
|
+
reject(err);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
proc.on('close', (code) => {
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
if (timedOut) {
|
|
101
|
+
reject(new Error(`timed out after ${timeoutMs}ms running: ${formatCommand(bin, args)}`));
|
|
102
|
+
} else if (code !== 0) {
|
|
103
|
+
const cleaned = cleanStderr(stderr).slice(-2000);
|
|
104
|
+
reject(new Error(`exit ${code} running: ${formatCommand(bin, args)}${cleaned ? `\n${cleaned}` : ''}`));
|
|
105
|
+
} else {
|
|
106
|
+
resolve({ stdout, stderr });
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function checkBinaries({ ffmpegBin = 'ffmpeg', ffprobeBin = 'ffprobe', timeoutMs = 15000 } = {}) {
|
|
113
|
+
for (const bin of [ffmpegBin, ffprobeBin]) {
|
|
114
|
+
await runCommand(bin, ['-version'], { timeoutMs });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Cached per ffmpeg binary path so a bulk run only probes this once, not
|
|
119
|
+
// once per file. `ffmpeg -h encoder=<name>` always exits 0 whether or not
|
|
120
|
+
// the encoder exists — the only signal is the message text on stdout.
|
|
121
|
+
const capabilityCache = new Map();
|
|
122
|
+
|
|
123
|
+
async function getCapabilities(ffmpegBin, timeoutMs) {
|
|
124
|
+
if (!capabilityCache.has(ffmpegBin)) {
|
|
125
|
+
capabilityCache.set(ffmpegBin, detectWebpSupport(ffmpegBin, timeoutMs));
|
|
126
|
+
}
|
|
127
|
+
return capabilityCache.get(ffmpegBin);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function detectWebpSupport(ffmpegBin, timeoutMs) {
|
|
131
|
+
try {
|
|
132
|
+
const { stdout } = await runCommand(ffmpegBin, ['-hide_banner', '-h', 'encoder=libwebp'], { timeoutMs: timeoutMs || 15000 });
|
|
133
|
+
return { webp: /^Encoder libwebp/m.test(stdout.toString()) };
|
|
134
|
+
} catch (err) {
|
|
135
|
+
return { webp: false };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Probes an image for dimensions + a best-effort animation check.
|
|
141
|
+
* Throws if no image/video stream is found (ffprobe reports still images
|
|
142
|
+
* under codec_type "video").
|
|
143
|
+
*/
|
|
144
|
+
async function probe(filePath, { ffprobeBin = 'ffprobe', timeoutMs = 15000 } = {}) {
|
|
145
|
+
const { stdout } = await runCommand(
|
|
146
|
+
ffprobeBin,
|
|
147
|
+
['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', filePath],
|
|
148
|
+
{ timeoutMs }
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
let data;
|
|
152
|
+
try {
|
|
153
|
+
data = JSON.parse(stdout.toString());
|
|
154
|
+
} catch (err) {
|
|
155
|
+
throw new Error(`ffprobe returned non-JSON output: ${err.message}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const stream = (data.streams || []).find((s) => s.codec_type === 'video');
|
|
159
|
+
if (!stream) {
|
|
160
|
+
const found = (data.streams || []).map((s) => s.codec_type).join(', ');
|
|
161
|
+
throw new Error(`no image stream found (${found ? `file has: ${found}` : 'file has no streams at all'})`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
let isAnimated = false;
|
|
165
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
166
|
+
if (POSSIBLY_ANIMATED_EXTENSIONS.has(ext)) {
|
|
167
|
+
// Frame count is unreliable without a full decode for gif/webp — do the
|
|
168
|
+
// decode explicitly rather than guess. Fine for images (small/fast);
|
|
169
|
+
// would be far too slow to do this for video.
|
|
170
|
+
try {
|
|
171
|
+
const { stdout: countOut } = await runCommand(
|
|
172
|
+
ffprobeBin,
|
|
173
|
+
['-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames', '-print_format', 'json', filePath],
|
|
174
|
+
{ timeoutMs: Math.max(timeoutMs, 30000) }
|
|
175
|
+
);
|
|
176
|
+
const countData = JSON.parse(countOut.toString());
|
|
177
|
+
const nbFrames = parseInt(countData.streams && countData.streams[0] && countData.streams[0].nb_read_frames, 10);
|
|
178
|
+
isAnimated = Number.isFinite(nbFrames) && nbFrames > 1;
|
|
179
|
+
} catch (err) {
|
|
180
|
+
isAnimated = false; // best-effort; treat as static if counting fails
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
width: stream.width,
|
|
186
|
+
height: stream.height,
|
|
187
|
+
codec: stream.codec_name,
|
|
188
|
+
isAnimated,
|
|
189
|
+
formatBytes: parseInt(data.format && data.format.size, 10) || null,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Extensions whose source pixels might carry an alpha channel. Used only to
|
|
194
|
+
// pick a safe *fallback* encoder when libwebp is unavailable — JPEG/BMP/TIFF
|
|
195
|
+
// sources are treated as opaque, PNG/WebP sources are treated as possibly
|
|
196
|
+
// transparent so a fallback never silently flattens transparency to black.
|
|
197
|
+
const POSSIBLY_ALPHA_EXTENSIONS = new Set(['.png', '.webp']);
|
|
198
|
+
|
|
199
|
+
function pickCodec(inputPath, probeInfo, caps) {
|
|
200
|
+
if (caps.webp) return { codec: 'libwebp', ext: '.webp' };
|
|
201
|
+
if (probeInfo.isAnimated) return { codec: 'gif', ext: '.gif' }; // always built in, no external lib
|
|
202
|
+
const mayHaveAlpha = POSSIBLY_ALPHA_EXTENSIONS.has(path.extname(inputPath).toLowerCase());
|
|
203
|
+
return mayHaveAlpha ? { codec: 'png', ext: '.png' } : { codec: 'mjpeg', ext: '.jpg' };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function buildEncodeArgs(inputPath, outputPath, probeInfo, opts) {
|
|
207
|
+
const args = ['-hide_banner', '-y', '-i', inputPath];
|
|
208
|
+
|
|
209
|
+
// Strips EXIF (including GPS location tags) before the file is published
|
|
210
|
+
// to IPFS — a privacy default, not just a size one.
|
|
211
|
+
args.push('-map_metadata', '-1');
|
|
212
|
+
|
|
213
|
+
if (probeInfo.isAnimated) {
|
|
214
|
+
args.push('-loop', '0');
|
|
215
|
+
} else {
|
|
216
|
+
args.push('-frames:v', '1');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (opts.maxDim) {
|
|
220
|
+
// min(iw, maxDim) never exceeds the source, so this only ever downscales.
|
|
221
|
+
args.push('-vf', `scale='min(iw,${opts.maxDim})':'min(ih,${opts.maxDim})':force_original_aspect_ratio=decrease`);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const quality = opts.quality != null ? opts.quality : 80;
|
|
225
|
+
if (opts.codec === 'libwebp') {
|
|
226
|
+
args.push('-c:v', 'libwebp', '-lossless', '0', '-q:v', String(quality));
|
|
227
|
+
} else if (opts.codec === 'gif') {
|
|
228
|
+
args.push('-c:v', 'gif');
|
|
229
|
+
} else if (opts.codec === 'png') {
|
|
230
|
+
args.push('-c:v', 'png');
|
|
231
|
+
} else {
|
|
232
|
+
// mjpeg: map 0 (worst) - 100 (best) "quality" onto ffmpeg's qscale,
|
|
233
|
+
// where 2 is best and 31 is worst.
|
|
234
|
+
const qscale = Math.max(2, Math.min(31, Math.round(31 - (quality / 100) * 29)));
|
|
235
|
+
args.push('-c:v', 'mjpeg', '-q:v', String(qscale));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
args.push('-an', outputPath);
|
|
239
|
+
|
|
240
|
+
return args;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Encodes inputPath -> outputPath, animated or static per probeInfo.isAnimated.
|
|
245
|
+
* Picks WebP when the ffmpeg build supports it, otherwise a safe fallback
|
|
246
|
+
* (see pickCodec above) — so the *requested* outputPath's extension may not
|
|
247
|
+
* match what's actually written. Returns { outputPath, codec } with the
|
|
248
|
+
* path actually used; callers must use that, not the one they passed in.
|
|
249
|
+
* opts: { ffmpegBin, timeoutMs, quality, maxDim }
|
|
250
|
+
*/
|
|
251
|
+
async function compress(inputPath, outputPath, probeInfo, opts = {}) {
|
|
252
|
+
const ffmpegBin = opts.ffmpegBin || 'ffmpeg';
|
|
253
|
+
const caps = await getCapabilities(ffmpegBin, opts.timeoutMs);
|
|
254
|
+
const { codec, ext } = pickCodec(inputPath, probeInfo, caps);
|
|
255
|
+
const finalOutputPath = outputPath.replace(/\.[^./\\]+$/, ext);
|
|
256
|
+
|
|
257
|
+
await runCommand(ffmpegBin, buildEncodeArgs(inputPath, finalOutputPath, probeInfo, { ...opts, codec }), {
|
|
258
|
+
timeoutMs: opts.timeoutMs || 60000,
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
return { outputPath: finalOutputPath, codec };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Same encode path as compress(), just defaulting to a much smaller max
|
|
266
|
+
* dimension and lower quality — a feed-thumbnail-sized variant rather than
|
|
267
|
+
* a distinct code path. Returns { outputPath, codec } like compress().
|
|
268
|
+
* opts: { ffmpegBin, timeoutMs, quality, maxDim }
|
|
269
|
+
*/
|
|
270
|
+
async function extractThumbnail(inputPath, thumbPath, probeInfo, opts = {}) {
|
|
271
|
+
return compress(inputPath, thumbPath, probeInfo, {
|
|
272
|
+
ffmpegBin: opts.ffmpegBin,
|
|
273
|
+
timeoutMs: opts.timeoutMs || 30000,
|
|
274
|
+
quality: opts.quality != null ? opts.quality : 60,
|
|
275
|
+
maxDim: opts.maxDim || 320,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
module.exports = {
|
|
280
|
+
IMAGE_EXTENSIONS,
|
|
281
|
+
checkBinaries,
|
|
282
|
+
probe,
|
|
283
|
+
compress,
|
|
284
|
+
extractThumbnail,
|
|
285
|
+
};
|
package/src/index.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// lib/videoCompressor.js — native-ffmpeg video compression, extracted from
|
|
4
|
+
// examplecompressbulk.js so both examplecompressbulk.js (video-only) and importcompressedbulk.js
|
|
5
|
+
// (mixed image/video) share one implementation instead of two copies that
|
|
6
|
+
// can drift apart.
|
|
7
|
+
//
|
|
8
|
+
// Pure functions only: no CLI arg parsing, no process.exit(), no console
|
|
9
|
+
// output beyond what the caller chooses to do with thrown errors. Every
|
|
10
|
+
// tunable (binary paths, crf, preset, timeouts, ...) is passed in via an
|
|
11
|
+
// options object so this file is usable standalone (unit tests, other
|
|
12
|
+
// scripts) as well as from a CLI wrapper.
|
|
13
|
+
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const { spawn } = require('child_process');
|
|
16
|
+
|
|
17
|
+
const VIDEO_EXTENSIONS = new Set([
|
|
18
|
+
'.mp4', '.mov', '.m4v', '.avi', '.mkv', '.webm', '.3gp', '.wmv', '.mpg', '.mpeg',
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
// ffmpeg/ffprobe always print a ~10-line version/build-config/library-
|
|
22
|
+
// version banner to stderr before anything else, regardless of whether the
|
|
23
|
+
// call fails. `-hide_banner` (added at every call site below) stops it at
|
|
24
|
+
// the source; this is a second, defensive pass over whatever stderr shows
|
|
25
|
+
// up anyway (a caller that forgets the flag, or an unexpected ffmpeg
|
|
26
|
+
// build), so an error message is never mostly boilerplate someone has to
|
|
27
|
+
// scroll past to find the one line that matters.
|
|
28
|
+
function cleanStderr(stderr) {
|
|
29
|
+
return stderr
|
|
30
|
+
.split('\n')
|
|
31
|
+
.filter((line) => !/^ffmpeg version |^ {2}(built with|configuration:|lib(avutil|avcodec|avformat|avdevice|avfilter|swscale|swresample|postproc)\s)/.test(line))
|
|
32
|
+
.join('\n')
|
|
33
|
+
.trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Renders argv back into a copy-pasteable command line for error messages -
|
|
37
|
+
// informational only (naive whitespace quoting, not real shell escaping).
|
|
38
|
+
function formatCommand(bin, args) {
|
|
39
|
+
const quoted = args.map((a) => (/\s/.test(a) ? `"${a}"` : a));
|
|
40
|
+
return [bin, ...quoted].join(' ');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function runCommand(bin, args, { timeoutMs = 600000 } = {}) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
let proc;
|
|
46
|
+
try {
|
|
47
|
+
proc = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
48
|
+
} catch (err) {
|
|
49
|
+
reject(err);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let stdout = Buffer.alloc(0);
|
|
54
|
+
let stderr = '';
|
|
55
|
+
let timedOut = false;
|
|
56
|
+
const timer = setTimeout(() => {
|
|
57
|
+
timedOut = true;
|
|
58
|
+
proc.kill('SIGKILL');
|
|
59
|
+
}, timeoutMs);
|
|
60
|
+
|
|
61
|
+
proc.stdout.on('data', (chunk) => { stdout = Buffer.concat([stdout, chunk]); });
|
|
62
|
+
proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
|
|
63
|
+
|
|
64
|
+
proc.on('error', (err) => {
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
if (err.code === 'ENOENT') {
|
|
67
|
+
reject(new Error(`'${bin}' not found on PATH — install ffmpeg or set FFMPEG_PATH/FFPROBE_PATH`));
|
|
68
|
+
} else {
|
|
69
|
+
reject(err);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
proc.on('close', (code) => {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
if (timedOut) {
|
|
76
|
+
reject(new Error(`timed out after ${timeoutMs}ms running: ${formatCommand(bin, args)}`));
|
|
77
|
+
} else if (code !== 0) {
|
|
78
|
+
const cleaned = cleanStderr(stderr).slice(-2000);
|
|
79
|
+
reject(new Error(`exit ${code} running: ${formatCommand(bin, args)}${cleaned ? `\n${cleaned}` : ''}`));
|
|
80
|
+
} else {
|
|
81
|
+
resolve({ stdout, stderr });
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Confirms both binaries are runnable. Throws with an install hint rather
|
|
89
|
+
* than exiting — callers decide how a preflight failure should surface.
|
|
90
|
+
*/
|
|
91
|
+
async function checkBinaries({ ffmpegBin = 'ffmpeg', ffprobeBin = 'ffprobe', timeoutMs = 15000 } = {}) {
|
|
92
|
+
for (const bin of [ffmpegBin, ffprobeBin]) {
|
|
93
|
+
await runCommand(bin, ['-version'], { timeoutMs });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Probes a video file for the fields the compressor / duration gate need.
|
|
99
|
+
* Throws if the file has no video stream or duration can't be determined.
|
|
100
|
+
*/
|
|
101
|
+
async function probe(filePath, { ffprobeBin = 'ffprobe', timeoutMs = 30000 } = {}) {
|
|
102
|
+
const { stdout } = await runCommand(
|
|
103
|
+
ffprobeBin,
|
|
104
|
+
['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', filePath],
|
|
105
|
+
{ timeoutMs }
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
let data;
|
|
109
|
+
try {
|
|
110
|
+
data = JSON.parse(stdout.toString());
|
|
111
|
+
} catch (err) {
|
|
112
|
+
throw new Error(`ffprobe returned non-JSON output: ${err.message}`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const videoStream = (data.streams || []).find((s) => s.codec_type === 'video');
|
|
116
|
+
const audioStream = (data.streams || []).find((s) => s.codec_type === 'audio');
|
|
117
|
+
if (!videoStream) {
|
|
118
|
+
const found = (data.streams || []).map((s) => s.codec_type).join(', ');
|
|
119
|
+
throw new Error(`no video stream found (${found ? `file has: ${found}` : 'file has no streams at all'})`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let durationSec = parseFloat(data.format && data.format.duration);
|
|
123
|
+
if (!Number.isFinite(durationSec)) durationSec = parseFloat(videoStream.duration);
|
|
124
|
+
if (!Number.isFinite(durationSec)) {
|
|
125
|
+
throw new Error(
|
|
126
|
+
`could not determine duration (format.duration=${JSON.stringify(data.format && data.format.duration)}, ` +
|
|
127
|
+
`stream.duration=${JSON.stringify(videoStream.duration)}, format=${data.format && data.format.format_name})`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
durationSec,
|
|
133
|
+
width: videoStream.width,
|
|
134
|
+
height: videoStream.height,
|
|
135
|
+
videoCodec: videoStream.codec_name,
|
|
136
|
+
hasAudio: Boolean(audioStream),
|
|
137
|
+
formatBytes: parseInt(data.format && data.format.size, 10) || null,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function buildEncodeArgs(inputPath, outputPath, probeInfo, opts) {
|
|
142
|
+
const args = ['-hide_banner', '-y', '-i', inputPath];
|
|
143
|
+
|
|
144
|
+
// Best-effort determinism: strip metadata that varies run-to-run
|
|
145
|
+
// (encode timestamps, creation dates) so re-encoding an unchanged source
|
|
146
|
+
// tends to produce the same bytes -> the same IPFS CID, avoiding
|
|
147
|
+
// duplicate pins of identical content. libx264 is only bit-exact across
|
|
148
|
+
// runs with a fixed thread count, hence opts.deterministic below.
|
|
149
|
+
args.push('-map_metadata', '-1', '-fflags', '+bitexact', '-flags:v', '+bitexact');
|
|
150
|
+
|
|
151
|
+
if (opts.deterministic) args.push('-threads', '1');
|
|
152
|
+
|
|
153
|
+
if (opts.maxHeight && probeInfo.height > opts.maxHeight) {
|
|
154
|
+
args.push('-vf', `scale=-2:${opts.maxHeight}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
args.push(
|
|
158
|
+
'-c:v', 'libx264',
|
|
159
|
+
'-preset', opts.preset || 'slow',
|
|
160
|
+
'-crf', String(opts.crf != null ? opts.crf : 22),
|
|
161
|
+
'-profile:v', 'high',
|
|
162
|
+
'-level', '4.0',
|
|
163
|
+
'-pix_fmt', 'yuv420p'
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
if (probeInfo.hasAudio) args.push('-c:a', 'aac', '-b:a', '128k', '-ar', '48000');
|
|
167
|
+
else args.push('-an');
|
|
168
|
+
|
|
169
|
+
// Moves the moov atom to the front so playback from an IPFS gateway can
|
|
170
|
+
// start before the whole object has downloaded.
|
|
171
|
+
args.push('-movflags', '+faststart', '-f', 'mp4', outputPath);
|
|
172
|
+
|
|
173
|
+
return args;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Encodes inputPath -> outputPath (always .mp4). probeInfo must come from
|
|
178
|
+
* probe() — height/hasAudio drive the scale filter and audio codec choice.
|
|
179
|
+
* opts: { ffmpegBin, timeoutMs, crf, preset, maxHeight, deterministic }
|
|
180
|
+
*/
|
|
181
|
+
async function compress(inputPath, outputPath, probeInfo, opts = {}) {
|
|
182
|
+
console.log('compress called ...')
|
|
183
|
+
await runCommand(opts.ffmpegBin || 'ffmpeg', buildEncodeArgs(inputPath, outputPath, probeInfo, opts), {
|
|
184
|
+
timeoutMs: opts.timeoutMs || 600000,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Extracts a single JPEG poster frame at ~10% into the video.
|
|
190
|
+
* opts: { ffmpegBin, timeoutMs }
|
|
191
|
+
*/
|
|
192
|
+
async function extractThumbnail(inputPath, thumbPath, durationSec, opts = {}) {
|
|
193
|
+
const seekAt = Math.max(0, Math.min(durationSec * 0.1, Math.max(0, durationSec - 0.1)));
|
|
194
|
+
await runCommand(
|
|
195
|
+
opts.ffmpegBin || 'ffmpeg',
|
|
196
|
+
['-hide_banner', '-y', '-ss', seekAt.toFixed(2), '-i', inputPath, '-frames:v', '1', '-q:v', '4', thumbPath],
|
|
197
|
+
{ timeoutMs: opts.timeoutMs || 30000 }
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = {
|
|
202
|
+
VIDEO_EXTENSIONS,
|
|
203
|
+
checkBinaries,
|
|
204
|
+
probe,
|
|
205
|
+
compress,
|
|
206
|
+
extractThumbnail,
|
|
207
|
+
};
|