@boruto_vk7/stickengine 2.0.4 → 4.1.0
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 +226 -119
- package/assets/DejaVuSans.ttf +0 -0
- package/assets/LICENSE-DejaVuSans.txt +78 -0
- package/dist/cjs/StickEngine.d.ts +287 -0
- package/dist/cjs/StickEngine.js +1191 -573
- package/dist/cjs/StickEngine.js.map +1 -1
- package/dist/cjs/canvas.d.ts +16 -0
- package/dist/cjs/canvas.js +108 -0
- package/dist/cjs/canvas.js.map +1 -0
- package/dist/cjs/compat.d.ts +8 -0
- package/dist/cjs/compat.js +18 -5
- package/dist/cjs/compat.js.map +1 -1
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +18 -20
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/logger.d.ts +12 -0
- package/dist/cjs/logger.js +68 -0
- package/dist/cjs/logger.js.map +1 -0
- package/dist/cjs/logo.png +0 -0
- package/dist/cjs/package.json +1 -1
- package/dist/cjs/util.d.ts +71 -0
- package/dist/cjs/util.js +437 -0
- package/dist/cjs/util.js.map +1 -0
- package/dist/esm/StickEngine.d.ts +287 -0
- package/dist/esm/StickEngine.js +1182 -500
- package/dist/esm/StickEngine.js.map +1 -1
- package/dist/esm/canvas.d.ts +16 -0
- package/dist/esm/canvas.js +96 -0
- package/dist/esm/canvas.js.map +1 -0
- package/dist/esm/compat.d.ts +8 -0
- package/dist/esm/compat.js +8 -1
- package/dist/esm/compat.js.map +1 -1
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +10 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/logger.d.ts +12 -0
- package/dist/esm/logger.js +59 -0
- package/dist/esm/logger.js.map +1 -0
- package/dist/esm/logo.png +0 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/util.d.ts +71 -0
- package/dist/esm/util.js +379 -0
- package/dist/esm/util.js.map +1 -0
- package/dist/types/StickEngine.d.ts +195 -18
- package/dist/types/StickEngine.d.ts.map +1 -1
- package/dist/types/canvas.d.ts +17 -0
- package/dist/types/canvas.d.ts.map +1 -0
- package/dist/types/compat.d.ts +8 -1
- package/dist/types/compat.d.ts.map +1 -1
- package/dist/types/index.d.ts +11 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/logger.d.ts +13 -0
- package/dist/types/logger.d.ts.map +1 -0
- package/dist/types/util.d.ts +72 -0
- package/dist/types/util.d.ts.map +1 -0
- package/logo.png +0 -0
- package/logo_small.png +0 -0
- package/package.json +34 -12
- package/dist/cjs/emror.jpg +0 -0
- package/dist/esm/emror.jpg +0 -0
package/dist/esm/StickEngine.js
CHANGED
|
@@ -3,131 +3,230 @@ import fsp from 'node:fs/promises';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
6
7
|
import { EventEmitter } from 'node:events';
|
|
7
8
|
import Crypto from 'node:crypto';
|
|
8
9
|
import axios from 'axios';
|
|
9
10
|
import ffmpeg from 'fluent-ffmpeg';
|
|
10
|
-
import webpMux from 'node-webpmux';
|
|
11
11
|
import Jimp from 'jimp';
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
12
|
+
import { createSelfRequire, resolveWebpImage, clamp, safeUnlink, fmtSize, isHttp, isDataURI, parseDataURItoBuffer, fileTypeFromBuf, buildExifBuffer, injectExifChunk, normalizeCropOptions, scanBbox, scanBboxRGBA, expandMargin, validateCropRect, intersectRect, findDefaultLogo } from './util.js';
|
|
13
|
+
import { logLine, errorMessage } from './logger.js';
|
|
14
|
+
import { getCanvasModule, registerBundledFont, CANVAS_FONT_FAMILY, decodeToCanvas, canvasToRgba, canvasToPng } from './canvas.js';
|
|
15
|
+
const execFileAsync = promisify(execFile);
|
|
16
|
+
const ANIMATED_EXTS = ['gif', 'mp4', 'webm', 'mov', 'mkv', 'avi', 'apng', 'm4v', '3gp', 'ogv', 'mpeg', 'flv'];
|
|
17
|
+
const VALID_FITS = ['natural', 'contain', 'cover', 'fill', 'none'];
|
|
18
|
+
const CANVAS = 512;
|
|
19
|
+
/* ------------------------------------------------------------------ */
|
|
20
|
+
/* FFmpeg/FFprobe binaries */
|
|
21
|
+
/* ------------------------------------------------------------------ */
|
|
15
22
|
let ffmpegPath = null;
|
|
16
23
|
let ffprobePath = null;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
24
|
+
function fixWindowsExe(p) {
|
|
25
|
+
if (process.platform === 'win32' && p && !p.toLowerCase().endsWith('.exe')) {
|
|
26
|
+
const withExe = `${p}.exe`;
|
|
27
|
+
if (fs.existsSync(withExe))
|
|
28
|
+
return withExe;
|
|
29
|
+
}
|
|
30
|
+
return p;
|
|
31
|
+
}
|
|
32
|
+
function loadInstaller(name) {
|
|
33
|
+
try {
|
|
34
|
+
const req = createSelfRequire();
|
|
35
|
+
const installer = req(name);
|
|
36
|
+
if (installer?.path) {
|
|
37
|
+
let p = installer.path;
|
|
38
|
+
if (!fs.existsSync(p))
|
|
39
|
+
p = fixWindowsExe(p);
|
|
40
|
+
if (fs.existsSync(p))
|
|
41
|
+
return p;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
catch { /* ignore */ }
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
function configureFfmpegBinaries(options = {}) {
|
|
48
|
+
ffmpegPath = (options.ffmpegPath && fs.existsSync(options.ffmpegPath) ? options.ffmpegPath : null)
|
|
49
|
+
|| loadInstaller('@ffmpeg-installer/ffmpeg')
|
|
50
|
+
|| 'ffmpeg';
|
|
51
|
+
ffprobePath = (options.ffprobePath && fs.existsSync(options.ffprobePath) ? options.ffprobePath : null)
|
|
52
|
+
|| loadInstaller('@ffprobe-installer/ffprobe')
|
|
53
|
+
|| 'ffprobe';
|
|
54
|
+
try {
|
|
22
55
|
ffmpeg.setFfmpegPath(ffmpegPath);
|
|
23
56
|
}
|
|
24
|
-
|
|
25
|
-
try {
|
|
26
|
-
const require = createRequire(import.meta.url);
|
|
27
|
-
const installer = require('@ffprobe-installer/ffprobe');
|
|
28
|
-
if (installer?.path) {
|
|
29
|
-
ffprobePath = installer.path;
|
|
57
|
+
catch { /* ignore */ }
|
|
58
|
+
try {
|
|
30
59
|
ffmpeg.setFfprobePath(ffprobePath);
|
|
31
60
|
}
|
|
32
|
-
|
|
61
|
+
catch { /* ignore */ }
|
|
62
|
+
}
|
|
63
|
+
configureFfmpegBinaries();
|
|
64
|
+
/** Allows overriding the ffmpeg/ffprobe binaries globally. */
|
|
65
|
+
export function setFfmpegBinaryPaths(options = {}) {
|
|
66
|
+
configureFfmpegBinaries(options);
|
|
67
|
+
}
|
|
68
|
+
/* ------------------------------------------------------------------ */
|
|
69
|
+
/* Probes de áudio (ffprobe) */
|
|
70
|
+
/* ------------------------------------------------------------------ */
|
|
71
|
+
/** Verifica se o arquivo tem pelo menos uma faixa de áudio utilizável. */
|
|
72
|
+
async function probeHasAudio(file) {
|
|
73
|
+
try {
|
|
74
|
+
const { stdout } = await execFileAsync(ffprobePath || 'ffprobe', [
|
|
75
|
+
'-v', 'error',
|
|
76
|
+
'-select_streams', 'a',
|
|
77
|
+
'-show_entries', 'stream=codec_type,codec_name',
|
|
78
|
+
'-of', 'json',
|
|
79
|
+
file
|
|
80
|
+
], { timeout: 20000, maxBuffer: 8 * 1024 * 1024 });
|
|
81
|
+
const streams = JSON.parse(stdout)?.streams;
|
|
82
|
+
return Array.isArray(streams) && streams.length > 0;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Duração (segundos) do arquivo de áudio via ffprobe. */
|
|
89
|
+
async function probeAudioSeconds(file) {
|
|
90
|
+
try {
|
|
91
|
+
const { stdout } = await execFileAsync(ffprobePath || 'ffprobe', [
|
|
92
|
+
'-v', 'error',
|
|
93
|
+
'-show_entries', 'format=duration',
|
|
94
|
+
'-of', 'json',
|
|
95
|
+
file
|
|
96
|
+
], { timeout: 20000, maxBuffer: 8 * 1024 * 1024 });
|
|
97
|
+
return parseFloat(JSON.parse(stdout)?.format?.duration) || 0;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/* ------------------------------------------------------------------ */
|
|
104
|
+
/* Network */
|
|
105
|
+
/* ------------------------------------------------------------------ */
|
|
33
106
|
export async function getBuffer(url, options = {}) {
|
|
107
|
+
let data;
|
|
34
108
|
try {
|
|
35
|
-
const
|
|
109
|
+
const res = await axios({
|
|
36
110
|
method: 'get',
|
|
37
111
|
url,
|
|
38
112
|
headers: {
|
|
39
|
-
'user-agent': 'Mozilla/5.0 (Windows NT
|
|
113
|
+
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
|
40
114
|
'DNT': 1,
|
|
41
115
|
'Upgrade-Insecure-Request': 1,
|
|
42
116
|
...(options.headers || {})
|
|
43
117
|
},
|
|
44
118
|
...options,
|
|
45
119
|
responseType: 'arraybuffer',
|
|
46
|
-
timeout: options.timeout || 45000
|
|
120
|
+
timeout: options.timeout || 45000,
|
|
121
|
+
maxContentLength: 200 * 1024 * 1024
|
|
47
122
|
});
|
|
48
|
-
|
|
123
|
+
data = res.data;
|
|
49
124
|
}
|
|
50
125
|
catch (err) {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
path.join(process.cwd(), 'src/emror.jpg'),
|
|
56
|
-
path.join(process.cwd(), 'dist/cjs/emror.jpg'),
|
|
57
|
-
path.join(process.cwd(), 'dist/esm/emror.jpg'),
|
|
58
|
-
path.join(os.tmpdir(), 'emror.jpg'),
|
|
59
|
-
path.resolve('./src/emror.jpg')
|
|
60
|
-
];
|
|
61
|
-
for (const p of candidates) {
|
|
62
|
-
try {
|
|
63
|
-
if (fs.existsSync(p))
|
|
64
|
-
return fs.readFileSync(p);
|
|
65
|
-
}
|
|
66
|
-
catch { }
|
|
67
|
-
}
|
|
68
|
-
return Buffer.alloc(0);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
function resolveWebpImage() {
|
|
72
|
-
const Image = webpMux.Image || webpMux.default?.Image || webpMux.default;
|
|
73
|
-
if (!Image)
|
|
74
|
-
throw new Error('node-webpmux Image class not found');
|
|
75
|
-
return Image;
|
|
76
|
-
}
|
|
77
|
-
async function fileTypeFromBuf(buf) {
|
|
78
|
-
try {
|
|
79
|
-
const ft = await import('file-type');
|
|
80
|
-
const fn = ft.fileTypeFromBuffer || ft.fromBuffer || ft.default?.fileTypeFromBuffer || ft.default?.fromBuffer;
|
|
81
|
-
if (!fn)
|
|
82
|
-
return undefined;
|
|
83
|
-
return await fn(buf);
|
|
84
|
-
}
|
|
85
|
-
catch {
|
|
86
|
-
try {
|
|
87
|
-
const ft = eval("require")('file-type');
|
|
88
|
-
const fn = ft.fileTypeFromBuffer || ft.fromBuffer || ft.default?.fileTypeFromBuffer || ft.default?.fromBuffer;
|
|
89
|
-
if (!fn)
|
|
90
|
-
return undefined;
|
|
91
|
-
return await fn(buf);
|
|
92
|
-
}
|
|
93
|
-
catch {
|
|
94
|
-
return undefined;
|
|
95
|
-
}
|
|
126
|
+
// erro CLARO: status HTTP, código de rede e mensagem real — sem figurinha de erro falsa
|
|
127
|
+
const status = err?.response?.status ? ` (HTTP ${err.response.status})` : '';
|
|
128
|
+
const code = err?.code ? ` [${err.code}]` : '';
|
|
129
|
+
throw new Error(`Falha ao baixar mídia de ${url}${status}${code}: ${errorMessage(err)}`);
|
|
96
130
|
}
|
|
131
|
+
const buffer = Buffer.from(data);
|
|
132
|
+
if (!buffer.length)
|
|
133
|
+
throw new Error(`Download retornou vazio (0 bytes): ${url}`);
|
|
134
|
+
return buffer;
|
|
97
135
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
function
|
|
102
|
-
return /^data:.*?\/.*?;base64,/i.test(s);
|
|
103
|
-
}
|
|
104
|
-
function parseDataURItoBuffer(dataURI) {
|
|
105
|
-
const base64 = dataURI.split(',')[1];
|
|
106
|
-
return Buffer.from(base64, 'base64');
|
|
107
|
-
}
|
|
108
|
-
function normalizeMetadata(options = {}) {
|
|
136
|
+
/* ------------------------------------------------------------------ */
|
|
137
|
+
/* Metadata / aliases normalization */
|
|
138
|
+
/* ------------------------------------------------------------------ */
|
|
139
|
+
export function normalizeMetadata(options = {}) {
|
|
109
140
|
const meta = options.metadata || options;
|
|
110
141
|
const pack = meta.packname || meta.pack || options.packname || options.pack || 'Lagos Solutions';
|
|
111
142
|
const author = meta.author || options.author || 'StickEngine';
|
|
112
|
-
const emojis = meta.categories || meta.emojis || options.categories || options.emojis || ['
|
|
143
|
+
const emojis = meta.categories || meta.emojis || options.categories || options.emojis || ['\u2728'];
|
|
113
144
|
const id = meta.id || options.id;
|
|
114
145
|
return { pack, author, emojis, id };
|
|
115
146
|
}
|
|
116
147
|
function resolveTempDir(options) {
|
|
117
|
-
const dir = options.tempDir || options.dirTemp || options.Dirtemp || options.DirTemp
|
|
148
|
+
const dir = options.tempDir || options.dirTemp || options.Dirtemp || options.DirTemp
|
|
149
|
+
|| options.dirtemp || options.TempDir || path.join(os.tmpdir(), 'stickengine');
|
|
118
150
|
return path.resolve(dir);
|
|
119
151
|
}
|
|
120
152
|
function resolveWatermark(options) {
|
|
121
|
-
|
|
122
|
-
|
|
153
|
+
return options.watermark ?? options.marcaDagua ?? options.marca_agua
|
|
154
|
+
?? options.MarcaDaAgua ?? options.marcaDaAgua ?? false;
|
|
123
155
|
}
|
|
156
|
+
function resolveWatermarkConfig(value) {
|
|
157
|
+
if (value === undefined || value === false || value === null)
|
|
158
|
+
return null;
|
|
159
|
+
const cfg = {
|
|
160
|
+
type: 'image',
|
|
161
|
+
logoPath: null,
|
|
162
|
+
text: 'Lagos Solutions',
|
|
163
|
+
position: 'bottom-right',
|
|
164
|
+
margin: 10,
|
|
165
|
+
sizePercent: 0.25,
|
|
166
|
+
opacity: 0.85
|
|
167
|
+
};
|
|
168
|
+
if (value === true) {
|
|
169
|
+
cfg.logoPath = findDefaultLogo();
|
|
170
|
+
return cfg;
|
|
171
|
+
}
|
|
172
|
+
if (typeof value === 'string') {
|
|
173
|
+
const possiblePath = path.resolve(value);
|
|
174
|
+
if (/\.(png|jpe?g|webp|bmp|gif)$/i.test(value) && fs.existsSync(possiblePath)) {
|
|
175
|
+
cfg.logoPath = possiblePath;
|
|
176
|
+
return cfg;
|
|
177
|
+
}
|
|
178
|
+
if (fs.existsSync(possiblePath)) {
|
|
179
|
+
cfg.logoPath = possiblePath;
|
|
180
|
+
return cfg;
|
|
181
|
+
}
|
|
182
|
+
cfg.type = 'text';
|
|
183
|
+
cfg.text = value;
|
|
184
|
+
return cfg;
|
|
185
|
+
}
|
|
186
|
+
// object
|
|
187
|
+
cfg.text = value.text || cfg.text;
|
|
188
|
+
cfg.position = value.position || cfg.position;
|
|
189
|
+
cfg.margin = value.margin ?? cfg.margin;
|
|
190
|
+
cfg.sizePercent = value.size ?? value.sizePercent ?? cfg.sizePercent;
|
|
191
|
+
cfg.opacity = value.opacity ?? cfg.opacity;
|
|
192
|
+
const logoRef = value.image || value.logo || value.path;
|
|
193
|
+
if (logoRef) {
|
|
194
|
+
if (fs.existsSync(logoRef))
|
|
195
|
+
cfg.logoPath = logoRef;
|
|
196
|
+
else {
|
|
197
|
+
const resolved = path.resolve(String(logoRef));
|
|
198
|
+
cfg.logoPath = fs.existsSync(resolved) ? resolved : findDefaultLogo();
|
|
199
|
+
}
|
|
200
|
+
return cfg;
|
|
201
|
+
}
|
|
202
|
+
if (value.text) {
|
|
203
|
+
cfg.type = 'text';
|
|
204
|
+
return cfg;
|
|
205
|
+
}
|
|
206
|
+
cfg.logoPath = findDefaultLogo();
|
|
207
|
+
return cfg;
|
|
208
|
+
}
|
|
209
|
+
/* ------------------------------------------------------------------ */
|
|
210
|
+
/* StickEngine */
|
|
211
|
+
/* ------------------------------------------------------------------ */
|
|
124
212
|
export class StickEngine extends EventEmitter {
|
|
125
213
|
options;
|
|
126
214
|
tempDir;
|
|
215
|
+
crop;
|
|
216
|
+
startTime = 0;
|
|
217
|
+
maxDuration = 3;
|
|
218
|
+
maxSize = 1_000_000;
|
|
219
|
+
maxSizeStatic = 100_000;
|
|
127
220
|
queue = [];
|
|
128
221
|
createdFiles = [];
|
|
222
|
+
lastCrop = null;
|
|
223
|
+
lastWarnings = [];
|
|
224
|
+
lastEncodeInfo = { quality: 0, fps: 0, attempts: 0 };
|
|
225
|
+
logs = true;
|
|
129
226
|
constructor(options = {}) {
|
|
130
227
|
super();
|
|
228
|
+
// logs no console: ligados por padrão; `silent:true` ou `logs:false` desligam
|
|
229
|
+
this.logs = !(options.silent === true || options.logs === false);
|
|
131
230
|
const normalizedMeta = normalizeMetadata(options);
|
|
132
231
|
this.tempDir = resolveTempDir(options);
|
|
133
232
|
fs.mkdirSync(this.tempDir, { recursive: true });
|
|
@@ -138,9 +237,16 @@ export class StickEngine extends EventEmitter {
|
|
|
138
237
|
transparent: false,
|
|
139
238
|
autoClean: false,
|
|
140
239
|
fps: 15,
|
|
141
|
-
quality:
|
|
142
|
-
maxDuration:
|
|
143
|
-
fit: '
|
|
240
|
+
quality: undefined,
|
|
241
|
+
maxDuration: 3,
|
|
242
|
+
fit: 'cover',
|
|
243
|
+
cropBorders: true,
|
|
244
|
+
maxSize: 1_000_000,
|
|
245
|
+
maxSizeStatic: 100_000,
|
|
246
|
+
startTime: 0,
|
|
247
|
+
concurrency: 3,
|
|
248
|
+
lossless: false,
|
|
249
|
+
passthroughWebp: false,
|
|
144
250
|
watermark: watermarkValue,
|
|
145
251
|
...options,
|
|
146
252
|
tempDir: this.tempDir,
|
|
@@ -162,7 +268,18 @@ export class StickEngine extends EventEmitter {
|
|
|
162
268
|
const wm = resolveWatermark(options);
|
|
163
269
|
if (wm !== undefined)
|
|
164
270
|
this.options.watermark = wm;
|
|
271
|
+
this.crop = normalizeCropOptions(this.options);
|
|
272
|
+
this.startTime = Math.max(0, Number(this.options.startTime ?? this.options.tempoInicio ?? 0) || 0);
|
|
273
|
+
this.maxDuration = Math.max(0, Number(this.options.maxDuration ?? this.options.tempoMaximo ?? 3) || 0);
|
|
274
|
+
this.maxSize = Math.max(10_000, Number(this.options.maxSize ?? this.options.tamanhoMaximo ?? 1_000_000) || 1_000_000);
|
|
275
|
+
this.maxSizeStatic = Math.max(10_000, Number(this.options.maxSizeStatic ?? 100_000) || 100_000);
|
|
276
|
+
if (!VALID_FITS.includes(String(this.options.fit)))
|
|
277
|
+
this.options.fit = 'cover';
|
|
278
|
+
// Re-resolve binaries if custom paths were passed to the constructor
|
|
279
|
+
if (options.ffmpegPath || options.ffprobePath)
|
|
280
|
+
configureFfmpegBinaries(options);
|
|
165
281
|
}
|
|
282
|
+
/* ---------------- static factories ---------------- */
|
|
166
283
|
static async create(input, options = {}) {
|
|
167
284
|
const engine = new StickEngine({ ...options, autoClean: false });
|
|
168
285
|
return await engine.build(input);
|
|
@@ -179,23 +296,22 @@ export class StickEngine extends EventEmitter {
|
|
|
179
296
|
const r = await StickEngine.create(input, options);
|
|
180
297
|
return r.path;
|
|
181
298
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
this.emit('st.done', result);
|
|
197
|
-
return result;
|
|
299
|
+
/** Converte qualquer áudio/mídia para OGG/Opus do WhatsApp (só prepara, não envia). */
|
|
300
|
+
static async toStickerAudio(input, options = {}) {
|
|
301
|
+
const engine = new StickEngine({ tempDir: options.tempDir, silent: options.silent === true });
|
|
302
|
+
return engine.toStickerAudio(input, options);
|
|
303
|
+
}
|
|
304
|
+
/** Prepara figurinha com som: { sticker, audio, seconds } (só mídia, sem envio). */
|
|
305
|
+
static async createAudioSticker(visual, options = {}) {
|
|
306
|
+
return await createAudioSticker(visual, options);
|
|
307
|
+
}
|
|
308
|
+
/** Log interno (respeita silent/logs e o logger global). */
|
|
309
|
+
say(level, tag, message, detail) {
|
|
310
|
+
if (!this.logs)
|
|
311
|
+
return;
|
|
312
|
+
logLine(level, tag, message, detail);
|
|
198
313
|
}
|
|
314
|
+
/* ---------------- queue API ---------------- */
|
|
199
315
|
addFile(file) {
|
|
200
316
|
this.queue.push(file);
|
|
201
317
|
return this;
|
|
@@ -207,78 +323,226 @@ export class StickEngine extends EventEmitter {
|
|
|
207
323
|
async start() {
|
|
208
324
|
if (!this.queue.length)
|
|
209
325
|
throw new Error('Queue is empty');
|
|
210
|
-
const
|
|
326
|
+
const files = [...this.queue];
|
|
211
327
|
this.queue = [];
|
|
212
|
-
|
|
328
|
+
const results = new Array(files.length);
|
|
329
|
+
const concurrency = clamp(Number(this.options.concurrency ?? 3) || 3, 1, 16);
|
|
330
|
+
let next = 0;
|
|
331
|
+
const worker = async () => {
|
|
332
|
+
while (true) {
|
|
333
|
+
const i = next++;
|
|
334
|
+
if (i >= files.length)
|
|
335
|
+
break;
|
|
336
|
+
try {
|
|
337
|
+
results[i] = { status: 'fulfilled', value: await this.processFile(files[i], i) };
|
|
338
|
+
}
|
|
339
|
+
catch (err) {
|
|
340
|
+
results[i] = { status: 'rejected', reason: err };
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, files.length) }, worker));
|
|
345
|
+
return results;
|
|
213
346
|
}
|
|
214
347
|
clean() {
|
|
215
|
-
for (const file of this.createdFiles)
|
|
216
|
-
|
|
217
|
-
if (fs.existsSync(file))
|
|
218
|
-
fs.unlinkSync(file);
|
|
219
|
-
}
|
|
220
|
-
catch { }
|
|
221
|
-
}
|
|
348
|
+
for (const file of this.createdFiles)
|
|
349
|
+
safeUnlink(file);
|
|
222
350
|
this.createdFiles = [];
|
|
223
351
|
}
|
|
352
|
+
/** Alias de clean() */
|
|
353
|
+
cleanup() {
|
|
354
|
+
this.clean();
|
|
355
|
+
}
|
|
224
356
|
track(file) {
|
|
225
357
|
this.createdFiles.push(file);
|
|
226
358
|
return file;
|
|
227
359
|
}
|
|
360
|
+
/* ---------------- main build ---------------- */
|
|
361
|
+
async build(input) {
|
|
362
|
+
const filePath = await this.processFile(input, 0);
|
|
363
|
+
const buffer = await fsp.readFile(filePath);
|
|
364
|
+
const info = await this.getMediaInfo(filePath);
|
|
365
|
+
const animated = await this.detectAnimatedWebp(filePath);
|
|
366
|
+
if (this.options.autoClean)
|
|
367
|
+
safeUnlink(filePath);
|
|
368
|
+
const result = {
|
|
369
|
+
path: filePath,
|
|
370
|
+
buffer,
|
|
371
|
+
base64: buffer.toString('base64'),
|
|
372
|
+
animated,
|
|
373
|
+
width: info.width || CANVAS,
|
|
374
|
+
height: info.height || CANVAS,
|
|
375
|
+
size: buffer.length,
|
|
376
|
+
duration: info.duration || 0,
|
|
377
|
+
cropped: this.lastCrop,
|
|
378
|
+
warnings: this.lastWarnings
|
|
379
|
+
};
|
|
380
|
+
this.emit('st.done', result);
|
|
381
|
+
return result;
|
|
382
|
+
}
|
|
383
|
+
/* ---------------- pipeline ---------------- */
|
|
228
384
|
async processFile(input, index) {
|
|
229
385
|
const ts = `${Date.now()}_${index}_${Crypto.randomBytes(3).toString('hex')}`;
|
|
230
386
|
const local = [];
|
|
387
|
+
const warnings = [];
|
|
388
|
+
this.lastWarnings = warnings;
|
|
231
389
|
try {
|
|
232
|
-
this.emit('st.start', {
|
|
390
|
+
this.emit('st.start', {
|
|
391
|
+
index,
|
|
392
|
+
input: typeof input === 'string'
|
|
393
|
+
? (input.length > 100 ? `${input.slice(0, 100)}...` : input)
|
|
394
|
+
: '<buffer>'
|
|
395
|
+
});
|
|
233
396
|
const { filePath, extension } = await this.materializeInput(input, ts);
|
|
234
|
-
|
|
397
|
+
const isTempInput = filePath.startsWith(this.tempDir + path.sep) || filePath.startsWith(`${this.tempDir}/`);
|
|
398
|
+
if (isTempInput)
|
|
235
399
|
local.push(filePath);
|
|
236
400
|
const mediaInfo = await this.getMediaInfo(filePath);
|
|
237
401
|
this.emit('st.info', { index, ...mediaInfo, extension });
|
|
238
402
|
let current = filePath;
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
403
|
+
const animatedExt = ANIMATED_EXTS.includes(extension);
|
|
404
|
+
let animated = animatedExt || mediaInfo.duration > 0.05;
|
|
405
|
+
{
|
|
406
|
+
const inputSize = fs.existsSync(filePath) ? fs.statSync(filePath).size : 0;
|
|
407
|
+
const dims = mediaInfo.width ? `${mediaInfo.width}x${mediaInfo.height}` : '';
|
|
408
|
+
const dur = mediaInfo.duration > 0.05 ? ` ${mediaInfo.duration.toFixed(1)}s` : '';
|
|
409
|
+
this.say('info', 'STICKER', `#${index} entrada ${extension.toUpperCase()} ${fmtSize(inputSize)}`, [dims, dur.trim()].filter(Boolean).join(' ') || null);
|
|
410
|
+
}
|
|
411
|
+
/* --- passthrough de webp (opt-in, comportamento antigo) --- */
|
|
412
|
+
if (this.options.passthroughWebp && extension === 'webp') {
|
|
413
|
+
const webpPath = path.join(this.tempDir, `sticker_${ts}.webp`);
|
|
414
|
+
fs.copyFileSync(current, webpPath);
|
|
415
|
+
local.push(webpPath);
|
|
416
|
+
await this.tryAddExif(webpPath, warnings, index);
|
|
417
|
+
this.track(webpPath);
|
|
418
|
+
this.lastCrop = null;
|
|
419
|
+
this.emit('st.data', { index, file: webpPath, animated: await this.detectAnimatedWebp(webpPath), cropped: null, warnings });
|
|
420
|
+
for (const f of local)
|
|
421
|
+
if (f !== webpPath)
|
|
422
|
+
safeUnlink(f);
|
|
423
|
+
return webpPath;
|
|
424
|
+
}
|
|
425
|
+
if (extension === 'webp') {
|
|
426
|
+
animated = await this.detectAnimatedWebp(filePath) || animated;
|
|
427
|
+
}
|
|
428
|
+
/* --- detecção de bordas (corte automático) --- */
|
|
429
|
+
let cropRect = null;
|
|
430
|
+
if (this.crop.enabled) {
|
|
431
|
+
cropRect = animated
|
|
432
|
+
? await this.detectVideoCrop(current, mediaInfo, warnings, index)
|
|
433
|
+
: await this.detectImageCrop(current, ts, local);
|
|
434
|
+
if (cropRect) {
|
|
435
|
+
this.emit('st.info', { index, cropped: cropRect });
|
|
436
|
+
this.say('info', 'CROP', `#${index} borda removida ${mediaInfo.width}x${mediaInfo.height} → ${cropRect.width}x${cropRect.height}`, `x=${cropRect.x} y=${cropRect.y}`);
|
|
437
|
+
}
|
|
438
|
+
else {
|
|
439
|
+
this.say('info', 'CROP', `#${index} sem borda removível — conteúdo preservado`);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const watermarkCfg = resolveWatermarkConfig(this.options.watermark);
|
|
443
|
+
let watermarkPathForFfmpeg = null;
|
|
444
|
+
if (!animated) {
|
|
445
|
+
/* --- caminho estático: canvas (binário embutido) com fallback Jimp --- */
|
|
446
|
+
current = await this.processStatic(current, ts, local, cropRect, watermarkCfg, warnings, index);
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
/* --- animado: overlay ffmpeg (logo ou texto renderizado no canvas) --- */
|
|
450
|
+
if (watermarkCfg) {
|
|
451
|
+
if (watermarkCfg.type === 'image' && watermarkCfg.logoPath) {
|
|
452
|
+
watermarkPathForFfmpeg = watermarkCfg.logoPath;
|
|
453
|
+
}
|
|
454
|
+
else if (watermarkCfg.type === 'text') {
|
|
455
|
+
const overlay = this.renderTextWatermarkOverlay(watermarkCfg, local, index);
|
|
456
|
+
if (overlay) {
|
|
457
|
+
watermarkPathForFfmpeg = overlay;
|
|
458
|
+
this.say('info', 'CANVAS', `#${index} marca d'água de texto renderizada ${fmtSize(fs.statSync(overlay).size)}`);
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
const msg = 'Marca d\u00e1gua de texto indispon\u00edvel (canvas/fonte) \u2014 ignorada.';
|
|
462
|
+
warnings.push(msg);
|
|
463
|
+
this.emit('st.warn', { index, message: msg });
|
|
464
|
+
this.say('warn', 'AVISO', `#${index} ${msg}`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
const msg = 'Logo da marca d\u00e1gua n\u00e3o encontrada \u2014 ignorada.';
|
|
469
|
+
warnings.push(msg);
|
|
470
|
+
this.emit('st.warn', { index, message: msg });
|
|
471
|
+
this.say('warn', 'AVISO', `#${index} ${msg}`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
252
474
|
}
|
|
475
|
+
/* --- conversão para WebP (512x512 no padrão WhatsApp) --- */
|
|
253
476
|
const webpPath = path.join(this.tempDir, `sticker_${ts}.webp`);
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
477
|
+
try {
|
|
478
|
+
await this.convertToWebp(current, webpPath, animated, {
|
|
479
|
+
// no caminho estático o crop JÁ foi aplicado pelo canvas/Jimp —
|
|
480
|
+
// reaplicar no ffmpeg estouraria os limites do quadro 512x512
|
|
481
|
+
crop: animated ? cropRect : null,
|
|
482
|
+
watermarkPath: watermarkPathForFfmpeg,
|
|
483
|
+
watermarkCfg,
|
|
484
|
+
warnings,
|
|
485
|
+
index
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
catch (err) {
|
|
489
|
+
// ffmpeg antigo (<4.3) não decodifica WebP animado — mantém o original (comportamento v2) em vez de falhar
|
|
490
|
+
if (animated && extension === 'webp' && fs.existsSync(current)) {
|
|
491
|
+
fs.copyFileSync(current, webpPath);
|
|
492
|
+
const msg = 'ffmpeg dispon\u00edvel n\u00e3o decodifica WebP animado \u2014 figurinha mantida sem re-encode. ' +
|
|
493
|
+
'Instale ffmpeg \u2265 4.3 no sistema (ou use a op\u00e7\u00e3o ffmpegPath) para padronizar tamanho/dimens\u00f5es.';
|
|
494
|
+
warnings.push(msg);
|
|
495
|
+
this.emit('st.warn', { index, message: msg });
|
|
496
|
+
}
|
|
497
|
+
else {
|
|
498
|
+
throw err;
|
|
499
|
+
}
|
|
260
500
|
}
|
|
501
|
+
local.push(webpPath);
|
|
502
|
+
animated = await this.detectAnimatedWebp(webpPath);
|
|
503
|
+
await this.tryAddExif(webpPath, warnings, index);
|
|
504
|
+
this.lastCrop = cropRect;
|
|
505
|
+
this.track(webpPath);
|
|
506
|
+
this.emit('st.data', { index, file: webpPath, animated, cropped: cropRect, warnings });
|
|
507
|
+
// intermediários saem da memória/temp imediatamente; só o final fica
|
|
261
508
|
for (const f of local)
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
509
|
+
if (f !== webpPath)
|
|
510
|
+
safeUnlink(f);
|
|
511
|
+
this.say('success', 'STICKER', `#${index} figurinha pronta ${fmtSize(fs.statSync(webpPath).size)}`, `${animated ? 'animada' : 'estática'} · 512x512`);
|
|
512
|
+
return webpPath;
|
|
265
513
|
}
|
|
266
514
|
catch (error) {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
}
|
|
273
|
-
catch { }
|
|
274
|
-
}
|
|
515
|
+
const msg = errorMessage(error);
|
|
516
|
+
this.emit('st.error', { index, error: msg });
|
|
517
|
+
this.say('error', 'ERRO', `#${index} ${msg}`);
|
|
518
|
+
for (const f of local)
|
|
519
|
+
safeUnlink(f);
|
|
275
520
|
throw error;
|
|
276
521
|
}
|
|
277
522
|
}
|
|
523
|
+
/** Adiciona EXIF de forma resiliente; em caso de falha, registra aviso e segue. */
|
|
524
|
+
async tryAddExif(webpPath, warnings, index) {
|
|
525
|
+
if (!this.options.metadata)
|
|
526
|
+
return;
|
|
527
|
+
const meta = this.options.metadata;
|
|
528
|
+
const ok = await this.addExif(webpPath, meta);
|
|
529
|
+
if (ok) {
|
|
530
|
+
this.say('info', 'EXIF', `#${index} pack "${meta.pack || meta.packname || ''}" · autor "${meta.author || ''}"`);
|
|
531
|
+
}
|
|
532
|
+
else {
|
|
533
|
+
const msg = 'EXIF do pack/autor n\u00e3o p\u00f4de ser gravado \u2014 a figurinha continua v\u00e1lida.';
|
|
534
|
+
warnings.push(msg);
|
|
535
|
+
this.emit('st.warn', { index, message: msg });
|
|
536
|
+
this.say('warn', 'AVISO', `#${index} ${msg}`);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/* ---------------- input materialization ---------------- */
|
|
278
540
|
async materializeInput(input, ts) {
|
|
279
541
|
if (Buffer.isBuffer(input)) {
|
|
280
542
|
if (input.length === 0)
|
|
281
543
|
throw new Error('Buffer vazio');
|
|
544
|
+
if (input.length > 200 * 1024 * 1024)
|
|
545
|
+
throw new Error('Arquivo muito grande (>200MB)');
|
|
282
546
|
const type = await fileTypeFromBuf(input);
|
|
283
547
|
const extension = type?.ext || 'png';
|
|
284
548
|
const filePath = path.join(this.tempDir, `input_${ts}.${extension}`);
|
|
@@ -289,7 +553,7 @@ export class StickEngine extends EventEmitter {
|
|
|
289
553
|
if (isDataURI(input)) {
|
|
290
554
|
const buffer = parseDataURItoBuffer(input);
|
|
291
555
|
if (buffer.length === 0)
|
|
292
|
-
throw new Error('Base64
|
|
556
|
+
throw new Error('Base64 inv\u00e1lido');
|
|
293
557
|
const type = await fileTypeFromBuf(buffer);
|
|
294
558
|
const extension = type?.ext || 'png';
|
|
295
559
|
const filePath = path.join(this.tempDir, `input_${ts}.${extension}`);
|
|
@@ -297,14 +561,21 @@ export class StickEngine extends EventEmitter {
|
|
|
297
561
|
return { filePath, extension };
|
|
298
562
|
}
|
|
299
563
|
if (isHttp(input)) {
|
|
564
|
+
// getBuffer agora lança erro de verdade em falha de rede/404
|
|
300
565
|
const buffer = await getBuffer(input);
|
|
301
|
-
if (buffer.length
|
|
302
|
-
throw new Error('
|
|
566
|
+
if (buffer.length > 200 * 1024 * 1024)
|
|
567
|
+
throw new Error('Arquivo muito grande (>200MB)');
|
|
303
568
|
const type = await fileTypeFromBuf(buffer);
|
|
304
|
-
|
|
305
|
-
|
|
569
|
+
let extension = type?.ext;
|
|
570
|
+
if (!extension) {
|
|
571
|
+
try {
|
|
572
|
+
extension = path.extname(new URL(input).pathname).replace('.', '');
|
|
573
|
+
}
|
|
574
|
+
catch { /* ignore */ }
|
|
575
|
+
}
|
|
576
|
+
const filePath = path.join(this.tempDir, `input_${ts}.${extension || 'bin'}`);
|
|
306
577
|
fs.writeFileSync(filePath, buffer);
|
|
307
|
-
return { filePath, extension: extension.toLowerCase() };
|
|
578
|
+
return { filePath, extension: (extension || 'bin').toLowerCase() };
|
|
308
579
|
}
|
|
309
580
|
if (fs.existsSync(input)) {
|
|
310
581
|
const filePath = path.resolve(input);
|
|
@@ -323,80 +594,34 @@ export class StickEngine extends EventEmitter {
|
|
|
323
594
|
}
|
|
324
595
|
}
|
|
325
596
|
}
|
|
326
|
-
catch { }
|
|
597
|
+
catch { /* ignore */ }
|
|
327
598
|
}
|
|
328
|
-
throw new Error(
|
|
599
|
+
throw new Error(`Arquivo/caminho inv\u00e1lido: ${input.slice(0, 120)}`);
|
|
329
600
|
}
|
|
330
|
-
throw new Error('
|
|
601
|
+
throw new Error('Tipo de entrada inv\u00e1lido (use Buffer, caminho, URL, base64 ou data URI)');
|
|
331
602
|
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
const img = new Image();
|
|
335
|
-
const json = {
|
|
336
|
-
'sticker-pack-id': metadata.id || `stickengine-${Date.now()}`,
|
|
337
|
-
'sticker-pack-name': metadata.pack || 'Lagos Solutions',
|
|
338
|
-
'sticker-pack-publisher': metadata.author || 'StickEngine',
|
|
339
|
-
'emojis': metadata.emojis?.length ? metadata.emojis : metadata.categories?.length ? metadata.categories : ['✨']
|
|
340
|
-
};
|
|
341
|
-
const exifAttr = Buffer.from([0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00]);
|
|
342
|
-
const jsonBuff = Buffer.from(JSON.stringify(json), 'utf-8');
|
|
343
|
-
const exif = Buffer.concat([exifAttr, jsonBuff]);
|
|
344
|
-
exif.writeUIntLE(jsonBuff.length, 14, 4);
|
|
345
|
-
await img.load(webpPath);
|
|
346
|
-
img.exif = exif;
|
|
347
|
-
const frameCount = typeof img.frameCount === 'number' ? img.frameCount : Array.isArray(img.frames) ? img.frames.length : 0;
|
|
348
|
-
const animated = !!img.hasAnim || frameCount > 1;
|
|
349
|
-
if (animated && img.frames) {
|
|
350
|
-
for (const frame of img.frames) {
|
|
351
|
-
frame.dispose = true;
|
|
352
|
-
frame.blend = false;
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
const saveV3 = async () => {
|
|
356
|
-
return img.save(webpPath, {
|
|
357
|
-
exif: true,
|
|
358
|
-
frames: animated ? img.frames : undefined,
|
|
359
|
-
width: img.width,
|
|
360
|
-
height: img.height,
|
|
361
|
-
loops: img.anim?.loops ?? img.anim?.loopCount ?? 0,
|
|
362
|
-
bgColor: img.anim?.bgColor ?? img.anim?.backgroundColor ?? [0, 0, 0, 0]
|
|
363
|
-
});
|
|
364
|
-
};
|
|
365
|
-
const saveLegacy = async () => {
|
|
366
|
-
const opts = {
|
|
367
|
-
path: webpPath,
|
|
368
|
-
frames: img.frames || [],
|
|
369
|
-
width: img.width || 512,
|
|
370
|
-
height: img.height || 512,
|
|
371
|
-
loops: img.anim?.loopCount ?? img.anim?.loops ?? 0,
|
|
372
|
-
bgColor: img.anim?.backgroundColor ?? img.anim?.bgColor ?? [0, 0, 0, 0],
|
|
373
|
-
exif
|
|
374
|
-
};
|
|
375
|
-
if (typeof img.muxAnim === 'function')
|
|
376
|
-
return img.muxAnim({ path: webpPath, exif: true, width: opts.width, height: opts.height, loops: opts.loops, bgColor: opts.bgColor });
|
|
377
|
-
if (typeof Image.muxAnim === 'function')
|
|
378
|
-
return Image.muxAnim(opts);
|
|
379
|
-
return img.save(webpPath);
|
|
380
|
-
};
|
|
603
|
+
/* ---------------- media info ---------------- */
|
|
604
|
+
async getMediaInfo(file) {
|
|
381
605
|
try {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
}
|
|
606
|
+
const { stdout } = await execFileAsync(ffprobePath || 'ffprobe', [
|
|
607
|
+
'-v', 'error',
|
|
608
|
+
'-select_streams', 'v:0',
|
|
609
|
+
'-show_entries', 'stream=width,height,duration',
|
|
610
|
+
'-show_entries', 'format=duration',
|
|
611
|
+
'-of', 'json',
|
|
612
|
+
file
|
|
613
|
+
], { timeout: 20000, maxBuffer: 8 * 1024 * 1024 });
|
|
614
|
+
const parsed = JSON.parse(stdout);
|
|
615
|
+
const st = parsed?.streams?.[0] || {};
|
|
616
|
+
const duration = parseFloat(st.duration) || parseFloat(parsed?.format?.duration) || 0;
|
|
617
|
+
return {
|
|
618
|
+
width: parseInt(String(st.width), 10) || 0,
|
|
619
|
+
height: parseInt(String(st.height), 10) || 0,
|
|
620
|
+
duration
|
|
621
|
+
};
|
|
392
622
|
}
|
|
393
|
-
catch
|
|
394
|
-
|
|
395
|
-
if (/muxAnim|not currently supported/i.test(msg)) {
|
|
396
|
-
await saveLegacy();
|
|
397
|
-
return;
|
|
398
|
-
}
|
|
399
|
-
throw err;
|
|
623
|
+
catch {
|
|
624
|
+
return { width: 0, height: 0, duration: 0 };
|
|
400
625
|
}
|
|
401
626
|
}
|
|
402
627
|
async detectAnimatedWebp(filePath) {
|
|
@@ -406,91 +631,339 @@ export class StickEngine extends EventEmitter {
|
|
|
406
631
|
const Image = resolveWebpImage();
|
|
407
632
|
const img = new Image();
|
|
408
633
|
await img.load(filePath);
|
|
409
|
-
return !!img.hasAnim
|
|
634
|
+
return !!img.hasAnim
|
|
635
|
+
|| (typeof img.frameCount === 'number' && img.frameCount > 1)
|
|
636
|
+
|| (Array.isArray(img.frames) && img.frames.length > 1);
|
|
410
637
|
}
|
|
411
638
|
catch {
|
|
412
639
|
return false;
|
|
413
640
|
}
|
|
414
641
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
const
|
|
418
|
-
if (
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
642
|
+
/* ---------------- border detection ---------------- */
|
|
643
|
+
async extractFrame(input, time, output) {
|
|
644
|
+
const args = ['-nostdin', '-hide_banner'];
|
|
645
|
+
if (time > 0)
|
|
646
|
+
args.push('-ss', String(time));
|
|
647
|
+
args.push('-i', input, '-frames:v', '1', '-y', output);
|
|
648
|
+
await execFileAsync(ffmpegPath || 'ffmpeg', args, { timeout: 30000, maxBuffer: 16 * 1024 * 1024 });
|
|
649
|
+
}
|
|
650
|
+
async loadJimpSmart(input, ts, local) {
|
|
651
|
+
try {
|
|
652
|
+
return await Jimp.read(input);
|
|
423
653
|
}
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
parts.push('scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos', 'pad=512:512:(ow-iw)/2:(oh-ih)/2:color=black@0');
|
|
430
|
-
break;
|
|
431
|
-
case 'fill':
|
|
432
|
-
parts.push('scale=512:512:flags=lanczos');
|
|
433
|
-
break;
|
|
434
|
-
case 'none':
|
|
435
|
-
parts.push("scale='min(512,iw)':'min(512,ih)':force_original_aspect_ratio=decrease:flags=lanczos");
|
|
436
|
-
break;
|
|
437
|
-
default:
|
|
438
|
-
parts.push('scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos');
|
|
439
|
-
break;
|
|
654
|
+
catch {
|
|
655
|
+
const pngPath = path.join(this.tempDir, `frame_${ts}.png`);
|
|
656
|
+
await this.extractFrame(input, 0, pngPath);
|
|
657
|
+
local.push(pngPath);
|
|
658
|
+
return await Jimp.read(pngPath);
|
|
440
659
|
}
|
|
441
|
-
parts.push('scale=trunc(iw/2)*2:trunc(ih/2)*2:flags=lanczos', 'setsar=1', 'format=rgba');
|
|
442
|
-
return parts.join(',');
|
|
443
660
|
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
const
|
|
449
|
-
if (
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
661
|
+
/** Corte para imagens estáticas: canvas nativo (binário embutido) com fallback Jimp. */
|
|
662
|
+
async detectImageCrop(input, ts, local) {
|
|
663
|
+
try {
|
|
664
|
+
/* 1) canvas nativo — decode e scan em C++ (rápido) */
|
|
665
|
+
const c = getCanvasModule();
|
|
666
|
+
if (c) {
|
|
667
|
+
const cv = await decodeToCanvas(input);
|
|
668
|
+
if (cv) {
|
|
669
|
+
let scale = 1;
|
|
670
|
+
let work = cv;
|
|
671
|
+
const maxSide = Math.max(cv.width, cv.height);
|
|
672
|
+
if (maxSide > 512) {
|
|
673
|
+
scale = maxSide / 512;
|
|
674
|
+
const sw2 = Math.max(1, Math.round(cv.width / scale));
|
|
675
|
+
const sh2 = Math.max(1, Math.round(cv.height / scale));
|
|
676
|
+
work = c.createCanvas(sw2, sh2);
|
|
677
|
+
work.getContext('2d').drawImage(cv, 0, 0, sw2, sh2);
|
|
678
|
+
}
|
|
679
|
+
const frame = canvasToRgba(work);
|
|
680
|
+
const bbox = scanBboxRGBA(frame.data, frame.width, frame.height, this.crop);
|
|
681
|
+
if (!bbox)
|
|
682
|
+
return null;
|
|
683
|
+
// bbox está no espaço reduzido — volta ao espaço original (arredonda p/ fora, nada é cortado)
|
|
684
|
+
const ox = Math.max(0, Math.floor(bbox.x * scale));
|
|
685
|
+
const oy = Math.max(0, Math.floor(bbox.y * scale));
|
|
686
|
+
const ow = Math.min(cv.width - ox, Math.ceil(bbox.width * scale));
|
|
687
|
+
const oh = Math.min(cv.height - oy, Math.ceil(bbox.height * scale));
|
|
688
|
+
const rectC = expandMargin({ x: ox, y: oy, width: ow, height: oh }, this.crop.margin, cv.width, cv.height);
|
|
689
|
+
return validateCropRect(rectC, cv.width, cv.height, this.crop.minSize);
|
|
690
|
+
}
|
|
465
691
|
}
|
|
692
|
+
/* 2) fallback Jimp */
|
|
693
|
+
const img = await this.loadJimpSmart(input, ts, local);
|
|
694
|
+
const w = img.bitmap.width;
|
|
695
|
+
const h = img.bitmap.height;
|
|
696
|
+
const bbox = scanBbox(img, this.crop);
|
|
697
|
+
if (!bbox)
|
|
698
|
+
return null;
|
|
699
|
+
const rect = expandMargin(bbox, this.crop.margin, w, h);
|
|
700
|
+
return validateCropRect(rect, w, h, this.crop.minSize);
|
|
701
|
+
}
|
|
702
|
+
catch {
|
|
703
|
+
return null;
|
|
466
704
|
}
|
|
467
|
-
if (!fs.existsSync(output) || fs.statSync(output).size < 20)
|
|
468
|
-
throw new Error('FFmpeg failed');
|
|
469
705
|
}
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
706
|
+
/** Corte para vídeos/GIFs: cropdetect do ffmpeg (bordas pretas). */
|
|
707
|
+
async detectVideoCropByCropdetect(input, mediaInfo) {
|
|
708
|
+
try {
|
|
709
|
+
const args = ['-nostdin', '-hide_banner', '-i', input, '-an'];
|
|
710
|
+
const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 6) : 0;
|
|
711
|
+
if (sample > 0)
|
|
712
|
+
args.push('-t', String(sample));
|
|
713
|
+
args.push('-vf', `cropdetect=limit=${this.crop.tolerance}:round=2:reset=0`, '-f', 'null', '-');
|
|
714
|
+
const { stdout, stderr } = await execFileAsync(ffmpegPath || 'ffmpeg', args, {
|
|
715
|
+
timeout: 30000,
|
|
716
|
+
maxBuffer: 16 * 1024 * 1024
|
|
717
|
+
});
|
|
718
|
+
const matches = [...`${stdout}${stderr}`.matchAll(/crop=(\d+):(\d+):(\d+):(\d+)/g)];
|
|
719
|
+
if (!matches.length)
|
|
720
|
+
return null;
|
|
721
|
+
const last = matches[matches.length - 1];
|
|
722
|
+
return { width: parseInt(last[1], 10), height: parseInt(last[2], 10), x: parseInt(last[3], 10), y: parseInt(last[4], 10) };
|
|
723
|
+
}
|
|
724
|
+
catch {
|
|
725
|
+
return null;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/** Corte para vídeos: amostra 3 frames e intersecta as áreas com conteúdo (bordas brancas/auto). */
|
|
729
|
+
async detectVideoCropByFrames(input, mediaInfo, local, ts) {
|
|
730
|
+
try {
|
|
731
|
+
const duration = mediaInfo.duration || 0;
|
|
732
|
+
const times = duration > 0 ? [duration * 0.1, duration * 0.5, duration * 0.9] : [0];
|
|
733
|
+
let inter = null;
|
|
734
|
+
let origW = 0;
|
|
735
|
+
let origH = 0;
|
|
736
|
+
for (let i = 0; i < times.length; i++) {
|
|
737
|
+
const framePath = path.join(this.tempDir, `crop_${ts}_${i}.png`);
|
|
738
|
+
await this.extractFrame(input, times[i], framePath);
|
|
739
|
+
local.push(framePath);
|
|
740
|
+
const img = await Jimp.read(framePath);
|
|
741
|
+
origW = img.bitmap.width;
|
|
742
|
+
origH = img.bitmap.height;
|
|
743
|
+
const bbox = scanBbox(img, this.crop);
|
|
744
|
+
if (!bbox)
|
|
745
|
+
return null; // frame inteiramente na cor de fundo: não é borda, é arte
|
|
746
|
+
inter = inter ? intersectRect(inter, bbox) : bbox;
|
|
747
|
+
if (!inter)
|
|
748
|
+
return null;
|
|
749
|
+
}
|
|
750
|
+
if (!inter || !origW || !origH)
|
|
751
|
+
return null;
|
|
752
|
+
const rect = expandMargin(inter, this.crop.margin, origW, origH);
|
|
753
|
+
return validateCropRect(rect, origW, origH, this.crop.minSize);
|
|
754
|
+
}
|
|
755
|
+
catch {
|
|
756
|
+
return null;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
async detectVideoCrop(input, mediaInfo, warnings, index) {
|
|
760
|
+
try {
|
|
761
|
+
if (!mediaInfo.width || !mediaInfo.height)
|
|
762
|
+
return null;
|
|
763
|
+
if (this.crop.color === 'black') {
|
|
764
|
+
const rect = await this.detectVideoCropByCropdetect(input, mediaInfo);
|
|
765
|
+
if (rect) {
|
|
766
|
+
return validateCropRect(rect, mediaInfo.width, mediaInfo.height, this.crop.minSize);
|
|
767
|
+
}
|
|
768
|
+
return null;
|
|
769
|
+
}
|
|
770
|
+
const ts = `${Date.now()}_${Crypto.randomBytes(3).toString('hex')}`;
|
|
771
|
+
const local = [];
|
|
772
|
+
try {
|
|
773
|
+
return await this.detectVideoCropByFrames(input, mediaInfo, local, ts);
|
|
774
|
+
}
|
|
775
|
+
finally {
|
|
776
|
+
for (const f of local)
|
|
777
|
+
safeUnlink(f);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
catch (e) {
|
|
781
|
+
warnings.push(`Detec\u00e7\u00e3o de bordas falhou: ${e?.message || e}`);
|
|
782
|
+
this.emit('st.warn', { index, message: 'Detec\u00e7\u00e3o de bordas falhou' });
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
/* ---------------- static processing (Jimp) ---------------- */
|
|
787
|
+
async processStaticWithJimp(input, ts, local, cropRect, watermarkCfg, warnings) {
|
|
788
|
+
const img = await this.loadJimpSmart(input, ts, local);
|
|
789
|
+
if (cropRect)
|
|
790
|
+
img.crop(cropRect.x, cropRect.y, cropRect.width, cropRect.height);
|
|
791
|
+
if (this.options.edit)
|
|
792
|
+
await this.applyJimpEdits(img, this.options.edit);
|
|
793
|
+
if (watermarkCfg)
|
|
794
|
+
await this.applyWatermarkToImage(img, watermarkCfg, warnings);
|
|
795
|
+
const outPath = path.join(this.tempDir, `proc_${ts}.png`);
|
|
796
|
+
await img.writeAsync(outPath);
|
|
797
|
+
local.push(outPath);
|
|
798
|
+
return outPath;
|
|
799
|
+
}
|
|
800
|
+
/* ---------------- static processing (canvas nativo, fallback Jimp) ---------------- */
|
|
801
|
+
/** Caminho estático: tenta o canvas embutido; se falhar, cai para o Jimp. */
|
|
802
|
+
async processStatic(input, ts, local, cropRect, watermarkCfg, warnings, index) {
|
|
803
|
+
const canvasOut = await this.processStaticWithCanvas(input, ts, local, cropRect, watermarkCfg, warnings, index);
|
|
804
|
+
if (canvasOut)
|
|
805
|
+
return canvasOut;
|
|
806
|
+
const jimpOut = await this.processStaticWithJimp(input, ts, local, cropRect, watermarkCfg, warnings);
|
|
807
|
+
this.say('info', 'JIMP', `#${index} processado com Jimp (fallback)`);
|
|
808
|
+
return jimpOut;
|
|
809
|
+
}
|
|
810
|
+
/** Pipeline estático com @napi-rs/canvas — binário distribuído DENTRO do pacote npm. */
|
|
811
|
+
async processStaticWithCanvas(input, ts, local, cropRect, watermarkCfg, warnings, index) {
|
|
812
|
+
try {
|
|
813
|
+
const c = getCanvasModule();
|
|
814
|
+
if (!c)
|
|
815
|
+
return null;
|
|
816
|
+
const src0 = await decodeToCanvas(input);
|
|
817
|
+
if (!src0)
|
|
818
|
+
return null;
|
|
819
|
+
registerBundledFont(c);
|
|
820
|
+
this.say('info', 'CANVAS', `#${index} decodificado com @napi-rs/canvas (binário embutido no npm)`, `${src0.width}x${src0.height}`);
|
|
821
|
+
/* --- crop --- */
|
|
822
|
+
let src = src0;
|
|
823
|
+
let sw = src0.width;
|
|
824
|
+
let sh = src0.height;
|
|
825
|
+
if (cropRect) {
|
|
826
|
+
const cropped = c.createCanvas(cropRect.width, cropRect.height);
|
|
827
|
+
cropped.getContext('2d').drawImage(src0, cropRect.x, cropRect.y, cropRect.width, cropRect.height, 0, 0, cropRect.width, cropRect.height);
|
|
828
|
+
src = cropped;
|
|
829
|
+
sw = cropRect.width;
|
|
830
|
+
sh = cropRect.height;
|
|
831
|
+
}
|
|
832
|
+
/* --- edits (mesmas opções do modo Jimp, via Skia) --- */
|
|
833
|
+
const edit = (typeof this.options.edit === 'object' && this.options.edit !== null)
|
|
834
|
+
? this.options.edit : null;
|
|
835
|
+
if (edit) {
|
|
836
|
+
const ec = c.createCanvas(sw, sh);
|
|
837
|
+
const ectx = ec.getContext('2d');
|
|
838
|
+
const filters = [];
|
|
839
|
+
if (edit.greyscale)
|
|
840
|
+
filters.push('grayscale(1)');
|
|
841
|
+
if (edit.invert)
|
|
842
|
+
filters.push('invert(1)');
|
|
843
|
+
if (edit.sepia)
|
|
844
|
+
filters.push('sepia(1)');
|
|
845
|
+
if (edit.blur)
|
|
846
|
+
filters.push(`blur(${clamp(Number(edit.blur) || 0, 0, 64)}px)`);
|
|
847
|
+
if (typeof edit.brightness === 'number')
|
|
848
|
+
filters.push(`brightness(${clamp(1 + edit.brightness, 0, 4).toFixed(2)})`);
|
|
849
|
+
if (typeof edit.contrast === 'number')
|
|
850
|
+
filters.push(`contrast(${clamp(1 + edit.contrast, 0, 4).toFixed(2)})`);
|
|
851
|
+
if (filters.length)
|
|
852
|
+
ectx.filter = filters.join(' ');
|
|
853
|
+
ectx.drawImage(src, 0, 0);
|
|
854
|
+
ectx.filter = 'none';
|
|
855
|
+
if (edit.circle) {
|
|
856
|
+
ectx.globalCompositeOperation = 'destination-in';
|
|
857
|
+
ectx.beginPath();
|
|
858
|
+
ectx.arc(sw / 2, sh / 2, Math.min(sw, sh) / 2, 0, Math.PI * 2);
|
|
859
|
+
ectx.closePath();
|
|
860
|
+
ectx.fill();
|
|
861
|
+
ectx.globalCompositeOperation = 'source-over';
|
|
862
|
+
}
|
|
863
|
+
if (edit.text?.content) {
|
|
864
|
+
ectx.font = `32px ${CANVAS_FONT_FAMILY}`;
|
|
865
|
+
ectx.textAlign = 'center';
|
|
866
|
+
ectx.textBaseline = 'bottom';
|
|
867
|
+
const cx = sw / 2;
|
|
868
|
+
const cy = sh - 8;
|
|
869
|
+
if (edit.text.stroke) {
|
|
870
|
+
ectx.lineWidth = 3;
|
|
871
|
+
ectx.strokeStyle = edit.text.color === 'BLACK' ? '#ffffff' : '#000000';
|
|
872
|
+
ectx.strokeText(edit.text.content, cx, cy);
|
|
873
|
+
}
|
|
874
|
+
ectx.fillStyle = edit.text.color === 'BLACK' ? '#000000' : '#ffffff';
|
|
875
|
+
ectx.fillText(edit.text.content, cx, cy);
|
|
876
|
+
}
|
|
877
|
+
src = ec;
|
|
878
|
+
}
|
|
879
|
+
/* --- marca d'água (logo ou texto) --- */
|
|
880
|
+
if (watermarkCfg) {
|
|
881
|
+
const wctx = src.getContext('2d');
|
|
882
|
+
if (watermarkCfg.type === 'image' && watermarkCfg.logoPath) {
|
|
883
|
+
const logoCv = await decodeToCanvas(watermarkCfg.logoPath);
|
|
884
|
+
if (logoCv) {
|
|
885
|
+
const lw = Math.max(8, Math.floor(sw * clamp(watermarkCfg.sizePercent, 0.02, 1)));
|
|
886
|
+
const lh = Math.max(4, Math.floor(logoCv.height * (lw / logoCv.width)));
|
|
887
|
+
const pos = this.watermarkPosition(watermarkCfg.position, watermarkCfg.margin, sw, sh, lw, lh);
|
|
888
|
+
wctx.save();
|
|
889
|
+
wctx.globalAlpha = clamp(watermarkCfg.opacity, 0.05, 1);
|
|
890
|
+
wctx.drawImage(logoCv, pos.x, pos.y, lw, lh);
|
|
891
|
+
wctx.restore();
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
else if (watermarkCfg.text) {
|
|
895
|
+
wctx.font = `16px ${CANVAS_FONT_FAMILY}`;
|
|
896
|
+
const tw = Math.ceil(wctx.measureText(watermarkCfg.text).width);
|
|
897
|
+
const th = 18;
|
|
898
|
+
const pos = this.watermarkPosition(watermarkCfg.position, watermarkCfg.margin, sw, sh, tw, th);
|
|
899
|
+
wctx.save();
|
|
900
|
+
wctx.fillStyle = 'rgba(0, 0, 0, 0.53)';
|
|
901
|
+
wctx.fillRect(pos.x - 5, pos.y - 3, tw + 10, th + 6);
|
|
902
|
+
wctx.fillStyle = '#ffffff';
|
|
903
|
+
wctx.textBaseline = 'top';
|
|
904
|
+
wctx.fillText(watermarkCfg.text, pos.x, pos.y);
|
|
905
|
+
wctx.restore();
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
/* --- composição final 512x512 (fit) --- */
|
|
909
|
+
const out = c.createCanvas(CANVAS, CANVAS);
|
|
910
|
+
const octx = out.getContext('2d');
|
|
911
|
+
const fit = String(this.options.fit || 'natural');
|
|
912
|
+
if (fit === 'fill') {
|
|
913
|
+
octx.drawImage(src, 0, 0, sw, sh, 0, 0, CANVAS, CANVAS);
|
|
914
|
+
}
|
|
915
|
+
else {
|
|
916
|
+
let s;
|
|
917
|
+
if (fit === 'cover')
|
|
918
|
+
s = Math.max(CANVAS / sw, CANVAS / sh);
|
|
919
|
+
else if (fit === 'none')
|
|
920
|
+
s = Math.min(CANVAS / sw, CANVAS / sh, 1);
|
|
921
|
+
else
|
|
922
|
+
s = Math.min(CANVAS / sw, CANVAS / sh); // natural / contain
|
|
923
|
+
const dw = sw * s;
|
|
924
|
+
const dh = sh * s;
|
|
925
|
+
octx.drawImage(src, (CANVAS - dw) / 2, (CANVAS - dh) / 2, dw, dh);
|
|
926
|
+
}
|
|
927
|
+
const outPath = path.join(this.tempDir, `proc_${ts}.png`);
|
|
928
|
+
fs.writeFileSync(outPath, canvasToPng(out));
|
|
929
|
+
local.push(outPath);
|
|
930
|
+
return outPath;
|
|
931
|
+
}
|
|
932
|
+
catch (err) {
|
|
933
|
+
const msg = `Canvas falhou (${errorMessage(err)}) — caindo para Jimp.`;
|
|
934
|
+
warnings.push(msg);
|
|
935
|
+
this.say('warn', 'AVISO', `#${index} ${msg}`);
|
|
936
|
+
return null;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
async applyJimpEdits(image, options) {
|
|
940
|
+
const opts = (typeof options === 'object' && options !== null) ? options : {};
|
|
941
|
+
if (opts.greyscale)
|
|
473
942
|
image.greyscale();
|
|
474
|
-
if (
|
|
943
|
+
if (opts.invert)
|
|
475
944
|
image.invert();
|
|
476
|
-
if (
|
|
945
|
+
if (opts.sepia)
|
|
477
946
|
image.sepia();
|
|
478
|
-
if (
|
|
479
|
-
image.blur(
|
|
480
|
-
if (typeof
|
|
481
|
-
image.brightness(
|
|
482
|
-
if (typeof
|
|
483
|
-
image.contrast(
|
|
484
|
-
if (
|
|
947
|
+
if (opts.blur)
|
|
948
|
+
image.blur(opts.blur);
|
|
949
|
+
if (typeof opts.brightness === 'number')
|
|
950
|
+
image.brightness(opts.brightness);
|
|
951
|
+
if (typeof opts.contrast === 'number')
|
|
952
|
+
image.contrast(opts.contrast);
|
|
953
|
+
if (opts.circle)
|
|
485
954
|
image.circle();
|
|
486
|
-
if (
|
|
487
|
-
image.resize(
|
|
488
|
-
if (
|
|
489
|
-
const fontPath =
|
|
955
|
+
if (opts.resize)
|
|
956
|
+
image.resize(opts.resize.width, opts.resize.height);
|
|
957
|
+
if (opts.text?.content) {
|
|
958
|
+
const fontPath = opts.text.color === 'BLACK' ? Jimp.FONT_SANS_32_BLACK : Jimp.FONT_SANS_32_WHITE;
|
|
490
959
|
const font = await Jimp.loadFont(fontPath);
|
|
491
|
-
const printOptions = {
|
|
492
|
-
|
|
493
|
-
|
|
960
|
+
const printOptions = {
|
|
961
|
+
text: opts.text.content,
|
|
962
|
+
alignmentX: opts.text.alignmentX || Jimp.HORIZONTAL_ALIGN_CENTER,
|
|
963
|
+
alignmentY: opts.text.alignmentY || Jimp.VERTICAL_ALIGN_BOTTOM
|
|
964
|
+
};
|
|
965
|
+
if (opts.text.stroke) {
|
|
966
|
+
const strokeFont = await Jimp.loadFont(opts.text.color === 'BLACK' ? Jimp.FONT_SANS_32_WHITE : Jimp.FONT_SANS_32_BLACK);
|
|
494
967
|
for (let x = -2; x <= 2; x++)
|
|
495
968
|
for (let y = -2; y <= 2; y++)
|
|
496
969
|
if (x !== 0 || y !== 0)
|
|
@@ -498,253 +971,462 @@ export class StickEngine extends EventEmitter {
|
|
|
498
971
|
}
|
|
499
972
|
image.print(font, 0, 0, printOptions, image.bitmap.width, image.bitmap.height);
|
|
500
973
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
async
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
path.join(process.cwd(), 'dist/esm/logo.png'),
|
|
513
|
-
path.resolve('./logo.png')
|
|
514
|
-
];
|
|
515
|
-
for (const p of candidates) {
|
|
516
|
-
try {
|
|
517
|
-
if (fs.existsSync(p) && fs.statSync(p).size > 100)
|
|
518
|
-
return p;
|
|
519
|
-
}
|
|
520
|
-
catch { }
|
|
974
|
+
}
|
|
975
|
+
/** Marca d'água em imagem estática (aplicada sobre a imagem já cortada). */
|
|
976
|
+
async applyWatermarkToImage(image, cfg, warnings) {
|
|
977
|
+
try {
|
|
978
|
+
if (cfg.type === 'image' && cfg.logoPath) {
|
|
979
|
+
const logo = await Jimp.read(cfg.logoPath);
|
|
980
|
+
logo.resize(Math.max(8, Math.floor(image.bitmap.width * clamp(cfg.sizePercent, 0.02, 1))), Jimp.AUTO);
|
|
981
|
+
logo.opacity(clamp(cfg.opacity, 0.05, 1));
|
|
982
|
+
const { x, y } = this.watermarkPosition(cfg.position, cfg.margin, image.bitmap.width, image.bitmap.height, logo.bitmap.width, logo.bitmap.height);
|
|
983
|
+
image.composite(logo, x, y, { mode: Jimp.BLEND_SOURCE_OVER, opacitySource: 1, opacityDest: 1 });
|
|
984
|
+
return;
|
|
521
985
|
}
|
|
986
|
+
if (!cfg.text)
|
|
987
|
+
return;
|
|
988
|
+
await this.printTextWatermark(image, cfg);
|
|
989
|
+
}
|
|
990
|
+
catch {
|
|
991
|
+
warnings.push('Marca d\u00e1gua falhou \u2014 ignorada.');
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
async printTextWatermark(image, cfg) {
|
|
995
|
+
const font = await Jimp.loadFont(Jimp.FONT_SANS_16_WHITE);
|
|
996
|
+
const textWidth = Jimp.measureText(font, cfg.text);
|
|
997
|
+
const textHeight = Jimp.measureTextHeight(font, cfg.text, image.bitmap.width);
|
|
998
|
+
const { x, y } = this.watermarkPosition(cfg.position, cfg.margin, image.bitmap.width, image.bitmap.height, textWidth, textHeight);
|
|
999
|
+
const bg = new Jimp(textWidth + 10, textHeight + 6, 0x00000088);
|
|
1000
|
+
image.composite(bg, x - 5, y - 3);
|
|
1001
|
+
image.print(font, x, y, cfg.text);
|
|
1002
|
+
}
|
|
1003
|
+
watermarkPosition(position, margin, mainW, mainH, w, h) {
|
|
1004
|
+
const m = Math.max(0, margin);
|
|
1005
|
+
let x = mainW - w - m;
|
|
1006
|
+
let y = mainH - h - m;
|
|
1007
|
+
if (position === 'bottom-left') {
|
|
1008
|
+
x = m;
|
|
1009
|
+
y = mainH - h - m;
|
|
1010
|
+
}
|
|
1011
|
+
if (position === 'top-right') {
|
|
1012
|
+
x = mainW - w - m;
|
|
1013
|
+
y = m;
|
|
1014
|
+
}
|
|
1015
|
+
if (position === 'top-left') {
|
|
1016
|
+
x = m;
|
|
1017
|
+
y = m;
|
|
1018
|
+
}
|
|
1019
|
+
if (position === 'center') {
|
|
1020
|
+
x = (mainW - w) / 2;
|
|
1021
|
+
y = (mainH - h) / 2;
|
|
1022
|
+
}
|
|
1023
|
+
return { x: Math.round(x), y: Math.round(y) };
|
|
1024
|
+
}
|
|
1025
|
+
/** Renderiza marca d'água de texto em PNG transparente (overlay ffmpeg em figurinhas animadas). */
|
|
1026
|
+
renderTextWatermarkOverlay(cfg, local, index) {
|
|
1027
|
+
try {
|
|
1028
|
+
const c = getCanvasModule();
|
|
1029
|
+
if (!c || !cfg.text)
|
|
1030
|
+
return null;
|
|
1031
|
+
registerBundledFont(c);
|
|
1032
|
+
const fontPx = 22;
|
|
1033
|
+
const probe = c.createCanvas(8, 8);
|
|
1034
|
+
const pctx = probe.getContext('2d');
|
|
1035
|
+
const font = `${fontPx}px ${CANVAS_FONT_FAMILY}`;
|
|
1036
|
+
pctx.font = font;
|
|
1037
|
+
const w = Math.ceil(pctx.measureText(cfg.text).width) + 20;
|
|
1038
|
+
const h = fontPx + 14;
|
|
1039
|
+
const cv = c.createCanvas(w, h);
|
|
1040
|
+
const ctx = cv.getContext('2d');
|
|
1041
|
+
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
|
|
1042
|
+
ctx.fillRect(0, 0, w, h);
|
|
1043
|
+
ctx.font = font;
|
|
1044
|
+
ctx.fillStyle = '#ffffff';
|
|
1045
|
+
ctx.textBaseline = 'middle';
|
|
1046
|
+
ctx.fillText(cfg.text, 10, h / 2);
|
|
1047
|
+
const outPath = path.join(this.tempDir, `wm_text_${Date.now()}_${index}.png`);
|
|
1048
|
+
fs.writeFileSync(outPath, canvasToPng(cv));
|
|
1049
|
+
local.push(outPath);
|
|
1050
|
+
return outPath;
|
|
1051
|
+
}
|
|
1052
|
+
catch {
|
|
522
1053
|
return null;
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
/* ---------------- ffmpeg filters ---------------- */
|
|
1057
|
+
/**
|
|
1058
|
+
* 'cover' (default) = estilo FIGURINHA GIGANTE: escala até preencher os 512x512
|
|
1059
|
+
* e corta o excedente pelo centro — impossível sobrar borda/faixa.
|
|
1060
|
+
* 'natural'/'contain' = opt-in legado: mídia inteira + faixas transparentes.
|
|
1061
|
+
*/
|
|
1062
|
+
fitChainStatic(fit) {
|
|
1063
|
+
switch (fit) {
|
|
1064
|
+
case 'cover':
|
|
1065
|
+
return [
|
|
1066
|
+
'scale=512:512:force_original_aspect_ratio=increase:flags=lanczos',
|
|
1067
|
+
'crop=512:512:(iw-ow)/2:(ih-oh)/2'
|
|
1068
|
+
];
|
|
1069
|
+
case 'fill':
|
|
1070
|
+
return ['scale=512:512:flags=lanczos'];
|
|
1071
|
+
case 'none':
|
|
1072
|
+
return ["scale='min(512,iw)':'min(512,ih)':force_original_aspect_ratio=decrease:flags=lanczos"];
|
|
1073
|
+
default: // natural / contain (opt-in) -> mídia inteira com barras transparentes
|
|
1074
|
+
return [
|
|
1075
|
+
'scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos',
|
|
1076
|
+
'pad=512:512:(ow-iw)/2:(oh-ih)/2:color=black@0'
|
|
1077
|
+
];
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
fitChainAnimated(fit) {
|
|
1081
|
+
switch (fit) {
|
|
1082
|
+
case 'cover':
|
|
1083
|
+
return [
|
|
1084
|
+
'scale=512:512:force_original_aspect_ratio=increase:flags=lanczos',
|
|
1085
|
+
'crop=512:512:(iw-ow)/2:(ih-oh)/2'
|
|
1086
|
+
];
|
|
1087
|
+
case 'fill':
|
|
1088
|
+
return ['scale=512:512:flags=lanczos'];
|
|
1089
|
+
case 'none':
|
|
1090
|
+
return ["scale='min(512,iw)':'min(512,ih)':force_original_aspect_ratio=decrease:flags=lanczos"];
|
|
1091
|
+
default: // natural / contain (opt-in) -> canvas 512x512 transparente
|
|
1092
|
+
return [
|
|
1093
|
+
'scale=512:512:force_original_aspect_ratio=decrease:flags=lanczos',
|
|
1094
|
+
'pad=512:512:(ow-iw)/2:(oh-ih)/2:color=black@0'
|
|
1095
|
+
];
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
buildStaticFilters(crop, fit) {
|
|
1099
|
+
const parts = [];
|
|
1100
|
+
if (crop)
|
|
1101
|
+
parts.push(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`);
|
|
1102
|
+
parts.push('format=rgba');
|
|
1103
|
+
parts.push(...this.fitChainStatic(fit));
|
|
1104
|
+
parts.push('setsar=1');
|
|
1105
|
+
return parts.join(',');
|
|
1106
|
+
}
|
|
1107
|
+
buildAnimatedFilters(crop, fit, fps) {
|
|
1108
|
+
const parts = [];
|
|
1109
|
+
if (crop)
|
|
1110
|
+
parts.push(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`);
|
|
1111
|
+
parts.push(`fps=${Math.max(1, fps)}`);
|
|
1112
|
+
parts.push('format=rgba');
|
|
1113
|
+
parts.push(...this.fitChainAnimated(fit));
|
|
1114
|
+
parts.push('setsar=1');
|
|
1115
|
+
return parts.join(',');
|
|
1116
|
+
}
|
|
1117
|
+
overlayPositionExpr(position, margin) {
|
|
1118
|
+
const m = Math.max(0, Math.round(margin));
|
|
1119
|
+
switch (position) {
|
|
1120
|
+
case 'bottom-left': return `${m}:main_h-overlay_h-${m}`;
|
|
1121
|
+
case 'top-right': return `main_w-overlay_w-${m}:${m}`;
|
|
1122
|
+
case 'top-left': return `${m}:${m}`;
|
|
1123
|
+
case 'center': return `(main_w-overlay_w)/2:(main_h-overlay_h)/2`;
|
|
1124
|
+
default: return `main_w-overlay_w-${m}:main_h-overlay_h-${m}`;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
buildWatermarkComplex(videoChain, cfg) {
|
|
1128
|
+
const wmW = clamp(Math.round(CANVAS * clamp(cfg.sizePercent, 0.02, 1)), 16, CANVAS);
|
|
1129
|
+
const op = clamp(cfg.opacity, 0.05, 1);
|
|
1130
|
+
const wmChain = [
|
|
1131
|
+
`scale=${wmW}:-2:flags=lanczos`,
|
|
1132
|
+
'format=rgba',
|
|
1133
|
+
...(op < 1 ? [`colorchannelmixer=aa=${op.toFixed(2)}`] : [])
|
|
1134
|
+
].join(',');
|
|
1135
|
+
return [
|
|
1136
|
+
`[0:v]${videoChain}[base]`,
|
|
1137
|
+
`[1:v]${wmChain}[wm]`,
|
|
1138
|
+
`[base][wm]overlay=${this.overlayPositionExpr(cfg.position, cfg.margin)}`
|
|
1139
|
+
].join(';');
|
|
1140
|
+
}
|
|
1141
|
+
/* ---------------- encode ---------------- */
|
|
1142
|
+
runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg) {
|
|
1143
|
+
return new Promise((resolve, reject) => {
|
|
1144
|
+
const q = clamp(Math.round(quality), 1, 100);
|
|
1145
|
+
const fit = String(this.options.fit || 'natural');
|
|
1146
|
+
const opts = ['-vcodec', 'libwebp', '-preset', 'default', '-an'];
|
|
1147
|
+
const cmd = ffmpeg();
|
|
1148
|
+
cmd.input(input);
|
|
1149
|
+
if (isAnimated && this.startTime > 0)
|
|
1150
|
+
cmd.inputOptions(['-ss', String(this.startTime)]);
|
|
1151
|
+
if (watermarkPath && watermarkCfg) {
|
|
1152
|
+
cmd.input(watermarkPath);
|
|
1153
|
+
if (isAnimated) {
|
|
1154
|
+
cmd.complexFilter(this.buildWatermarkComplex(this.buildAnimatedFilters(crop, fit, fps), watermarkCfg));
|
|
1155
|
+
}
|
|
1156
|
+
else {
|
|
1157
|
+
cmd.complexFilter(this.buildWatermarkComplex(this.buildStaticFilters(crop, fit), watermarkCfg));
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
else if (isAnimated) {
|
|
1161
|
+
opts.push('-vf', this.buildAnimatedFilters(crop, fit, fps));
|
|
543
1162
|
}
|
|
544
1163
|
else {
|
|
545
|
-
|
|
546
|
-
isImageWatermark = false;
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
else if (typeof watermark === 'object') {
|
|
550
|
-
text = watermark.text || text;
|
|
551
|
-
position = watermark.position || position;
|
|
552
|
-
margin = watermark.margin ?? margin;
|
|
553
|
-
sizePercent = watermark.size ?? watermark.sizePercent ?? sizePercent;
|
|
554
|
-
if (watermark.image || watermark.logo || watermark.path) {
|
|
555
|
-
isImageWatermark = true;
|
|
556
|
-
logoPath = watermark.image || watermark.logo || watermark.path;
|
|
557
|
-
if (logoPath && !fs.existsSync(logoPath)) {
|
|
558
|
-
const resolved = path.resolve(logoPath);
|
|
559
|
-
if (fs.existsSync(resolved))
|
|
560
|
-
logoPath = resolved;
|
|
561
|
-
else
|
|
562
|
-
logoPath = findLogo();
|
|
563
|
-
}
|
|
1164
|
+
opts.push('-vf', this.buildStaticFilters(crop, fit));
|
|
564
1165
|
}
|
|
565
|
-
|
|
566
|
-
|
|
1166
|
+
if (isAnimated) {
|
|
1167
|
+
opts.push('-loop', '0', '-vsync', '0', '-lossless', '0');
|
|
1168
|
+
if (this.maxDuration > 0)
|
|
1169
|
+
opts.push('-t', String(this.maxDuration));
|
|
567
1170
|
}
|
|
568
1171
|
else {
|
|
569
|
-
|
|
570
|
-
logoPath = findLogo();
|
|
1172
|
+
opts.push('-lossless', this.options.lossless ? '1' : '0');
|
|
571
1173
|
}
|
|
1174
|
+
opts.push('-compression_level', '6', '-q:v', String(q), '-quality', String(q));
|
|
1175
|
+
cmd
|
|
1176
|
+
.on('error', (err) => reject(err))
|
|
1177
|
+
.on('end', () => resolve())
|
|
1178
|
+
.addOutputOptions(opts)
|
|
1179
|
+
.toFormat('webp')
|
|
1180
|
+
.save(output);
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
async convertToWebp(input, output, isAnimated, opts) {
|
|
1184
|
+
const fitUsed = String(this.options.fit || 'cover');
|
|
1185
|
+
const { crop, watermarkPath, watermarkCfg, warnings, index } = opts;
|
|
1186
|
+
const lossless = this.options.lossless === true;
|
|
1187
|
+
let quality = this.options.quality != null
|
|
1188
|
+
? clamp(Number(this.options.quality) || 80, 1, 100)
|
|
1189
|
+
: (isAnimated ? 80 : 90);
|
|
1190
|
+
let fps = clamp(Math.round(Number(this.options.fps ?? 15) || 15), 1, 60);
|
|
1191
|
+
const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
|
|
1192
|
+
try {
|
|
1193
|
+
await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
|
|
572
1194
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
if (typeof watermark === 'object' && watermark.opacity !== undefined) {
|
|
588
|
-
logo.opacity(watermark.opacity);
|
|
589
|
-
}
|
|
590
|
-
else {
|
|
591
|
-
logo.opacity(0.85);
|
|
592
|
-
}
|
|
593
|
-
let x = mainWidth - logo.bitmap.width - margin;
|
|
594
|
-
let y = mainHeight - logo.bitmap.height - margin;
|
|
595
|
-
if (position === 'bottom-left') {
|
|
596
|
-
x = margin;
|
|
597
|
-
y = mainHeight - logo.bitmap.height - margin;
|
|
598
|
-
}
|
|
599
|
-
if (position === 'top-right') {
|
|
600
|
-
x = mainWidth - logo.bitmap.width - margin;
|
|
601
|
-
y = margin;
|
|
602
|
-
}
|
|
603
|
-
if (position === 'top-left') {
|
|
604
|
-
x = margin;
|
|
605
|
-
y = margin;
|
|
606
|
-
}
|
|
607
|
-
if (position === 'center') {
|
|
608
|
-
x = (mainWidth - logo.bitmap.width) / 2;
|
|
609
|
-
y = (mainHeight - logo.bitmap.height) / 2;
|
|
610
|
-
}
|
|
611
|
-
main.composite(logo, x, y, { mode: Jimp.BLEND_SOURCE_OVER, opacitySource: 1, opacityDest: 1 });
|
|
612
|
-
await main.writeAsync(output);
|
|
613
|
-
return;
|
|
1195
|
+
catch (err) {
|
|
1196
|
+
throw new Error(`FFmpeg falhou ao gerar WebP ${isAnimated ? 'animado' : 'estático'}: ${errorMessage(err)}`);
|
|
1197
|
+
}
|
|
1198
|
+
if (!fs.existsSync(output) || fs.statSync(output).size < 20) {
|
|
1199
|
+
throw new Error('FFmpeg falhou ao gerar o WebP (arquivo vazio ou corrompido)');
|
|
1200
|
+
}
|
|
1201
|
+
this.say('info', 'ENCODE', `#${index} webp ${isAnimated ? 'animado' : 'estático'} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${fmtSize(fs.statSync(output).size)}`, `fit=${fitUsed}`);
|
|
1202
|
+
let attempts = 0;
|
|
1203
|
+
while (!lossless && fs.existsSync(output) && fs.statSync(output).size > limit && attempts < 6) {
|
|
1204
|
+
attempts++;
|
|
1205
|
+
this.say('info', 'ENCODE', `#${index} acima de ${fmtSize(limit)} — auto-shrink tentativa ${attempts}`);
|
|
1206
|
+
if (isAnimated) {
|
|
1207
|
+
quality = Math.max(20, quality - 15);
|
|
1208
|
+
fps = Math.max(8, fps - 2);
|
|
614
1209
|
}
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
return;
|
|
1210
|
+
else {
|
|
1211
|
+
quality = Math.max(10, quality - 12);
|
|
618
1212
|
}
|
|
1213
|
+
await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
|
|
1214
|
+
if (!fs.existsSync(output))
|
|
1215
|
+
throw new Error('FFmpeg falhou no auto-shrink');
|
|
1216
|
+
this.say('info', 'ENCODE', `#${index} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${fmtSize(fs.statSync(output).size)}`);
|
|
619
1217
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
1218
|
+
this.lastEncodeInfo = { quality, fps, attempts };
|
|
1219
|
+
const finalSize = fs.existsSync(output) ? fs.statSync(output).size : 0;
|
|
1220
|
+
if (finalSize > limit) {
|
|
1221
|
+
const msg = `N\u00e3o foi poss\u00edvel reduzir abaixo de ${fmtSize(limit)} (ficou com ${fmtSize(finalSize)}). ` +
|
|
1222
|
+
`Aumente maxSize${isAnimated ? '' : 'Static'} se precisar.`;
|
|
1223
|
+
warnings.push(msg);
|
|
1224
|
+
this.emit('st.warn', { index, message: msg });
|
|
623
1225
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
1226
|
+
if (finalSize < 20)
|
|
1227
|
+
throw new Error('FFmpeg falhou ao gerar o WebP');
|
|
1228
|
+
}
|
|
1229
|
+
/* ---------------- EXIF ---------------- */
|
|
1230
|
+
async addExif(webpPath, metadata) {
|
|
1231
|
+
try {
|
|
1232
|
+
const Image = resolveWebpImage();
|
|
1233
|
+
const exif = buildExifBuffer(metadata);
|
|
1234
|
+
const img = new Image();
|
|
1235
|
+
await img.load(webpPath);
|
|
1236
|
+
img.exif = exif;
|
|
1237
|
+
await img.save(webpPath);
|
|
1238
|
+
const check = new Image();
|
|
1239
|
+
await check.load(webpPath);
|
|
1240
|
+
if (!check.exif || check.exif.length < 24)
|
|
1241
|
+
throw new Error('EXIF n\u00e3o persistido pelo webpmux');
|
|
1242
|
+
return true;
|
|
633
1243
|
}
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
y = margin;
|
|
1244
|
+
catch {
|
|
1245
|
+
return await injectExifChunk(webpPath, buildExifBuffer(metadata));
|
|
637
1246
|
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1247
|
+
}
|
|
1248
|
+
/* ---------------- figurinha com som (só preparação de mídia) ---------------- */
|
|
1249
|
+
/**
|
|
1250
|
+
* Converte qualquer áudio/mídia para OGG/Opus no padrão WhatsApp.
|
|
1251
|
+
* NÃO envia nada — devolve o buffer pronto para o bot acoplar à figurinha.
|
|
1252
|
+
*/
|
|
1253
|
+
async toStickerAudio(input, options = {}) {
|
|
1254
|
+
const ts = `${Date.now()}_a_${Crypto.randomBytes(3).toString('hex')}`;
|
|
1255
|
+
const local = [];
|
|
1256
|
+
const startTime = Math.max(0, Number(options.startTime ?? 0) || 0);
|
|
1257
|
+
const seconds = Math.max(0, Number(options.seconds ?? 0) || 0);
|
|
1258
|
+
const bitrate = clamp(Math.round(Number(options.bitrate ?? 64) || 64), 16, 320);
|
|
1259
|
+
const mono = options.mono === true;
|
|
1260
|
+
const sampleRate = clamp(Math.round(Number(options.sampleRate ?? 48000) || 48000), 8000, 96000);
|
|
1261
|
+
this.say('info', 'AUDIO', 'preparando clipe de áudio OGG/Opus (padrão WhatsApp)', startTime > 0 ? `início ${startTime}s${seconds > 0 ? ` · duração ${seconds}s` : ''}` : (seconds > 0 ? `duração ${seconds}s` : null));
|
|
1262
|
+
const { filePath } = await this.materializeInput(input, ts);
|
|
1263
|
+
if (filePath.startsWith(this.tempDir + path.sep) || filePath.startsWith(`${this.tempDir}/`))
|
|
1264
|
+
local.push(filePath);
|
|
1265
|
+
if (!(await probeHasAudio(filePath))) {
|
|
1266
|
+
throw new Error('A mídia enviada não tem faixa de áudio utilizável. Envie um áudio, música ou vídeo COM som.');
|
|
641
1267
|
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
1268
|
+
const outPath = path.join(this.tempDir, `audio_${ts}.ogg`);
|
|
1269
|
+
local.push(outPath);
|
|
1270
|
+
await this.convertAudioToOggOpus(filePath, outPath, { startTime, seconds, bitrate, mono, sampleRate });
|
|
1271
|
+
const dur = await probeAudioSeconds(outPath);
|
|
1272
|
+
const buffer = await fsp.readFile(outPath);
|
|
1273
|
+
for (const f of local)
|
|
1274
|
+
safeUnlink(f);
|
|
1275
|
+
const result = {
|
|
1276
|
+
buffer,
|
|
1277
|
+
seconds: Math.round(dur * 100) / 100,
|
|
1278
|
+
mime: 'audio/ogg; codecs=opus',
|
|
1279
|
+
bitrate
|
|
1280
|
+
};
|
|
1281
|
+
this.say('success', 'AUDIO', `clipe pronto ${fmtSize(buffer.length)} · ${result.seconds.toFixed(1)}s`, `opus ${bitrate}k · ${mono ? 'mono' : 'estéreo'} · ${sampleRate}Hz`);
|
|
1282
|
+
this.emit('st.audio', result);
|
|
1283
|
+
return result;
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Figurinha com som — prepara os DOIS arquivos de mídia (sticker WebP 512x512
|
|
1287
|
+
* com EXIF + clipe OGG/Opus). NÃO envia nada: o bot recebe os buffers e envia
|
|
1288
|
+
* com a lib que quiser (Baileys, wha.evo, etc.).
|
|
1289
|
+
*
|
|
1290
|
+
* @param visual imagem, vídeo ou figurinha (Buffer/caminho/URL/base64)
|
|
1291
|
+
* @param audio áudio para acoplar (Buffer/caminho/URL). Se null e o visual
|
|
1292
|
+
* for vídeo com som, usa a própria trilha do vídeo.
|
|
1293
|
+
*/
|
|
1294
|
+
async createAudioSticker(visual, audio = null, audioOptions = {}) {
|
|
1295
|
+
const ts = `${Date.now()}_${Crypto.randomBytes(3).toString('hex')}`;
|
|
1296
|
+
this.say('info', 'AUDIO-STICKER', 'preparando figurinha com som (só mídia — o envio é responsabilidade do bot)');
|
|
1297
|
+
/* 1. visual materializado uma única vez */
|
|
1298
|
+
const { filePath: visualFile, extension } = await this.materializeInput(visual, `${ts}_v`);
|
|
1299
|
+
/* 2. fonte de áudio resolvida ANTES do pipeline visual (que apaga temporários) */
|
|
1300
|
+
let audioFile = null;
|
|
1301
|
+
let audioIsTemp = false;
|
|
1302
|
+
if (audio != null) {
|
|
1303
|
+
const m = await this.materializeInput(audio, `${ts}_a`);
|
|
1304
|
+
audioFile = m.filePath;
|
|
1305
|
+
audioIsTemp = audioFile.startsWith(this.tempDir + path.sep) || audioFile.startsWith(`${this.tempDir}/`);
|
|
645
1306
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
await
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
});
|
|
1307
|
+
else {
|
|
1308
|
+
audioFile = visualFile;
|
|
1309
|
+
}
|
|
1310
|
+
if (!(await probeHasAudio(audioFile))) {
|
|
1311
|
+
throw new Error(audio == null
|
|
1312
|
+
? `O visual enviado (${extension}) não tem trilha de áudio. Para figurinha com som, envie um áudio junto (parâmetro audio) ou use um vídeo com som.`
|
|
1313
|
+
: 'O áudio enviado não tem faixa utilizável (arquivo corrompido ou sem som).');
|
|
1314
|
+
}
|
|
1315
|
+
/* 3. clipe OGG/Opus (duração é parâmetro LIVRE; default: áudio inteiro) */
|
|
1316
|
+
const startTime = Math.max(0, Number(audioOptions.startTime ?? this.options.audioStartTime ?? 0) || 0);
|
|
1317
|
+
const seconds = Math.max(0, Number(audioOptions.seconds ?? this.options.audioSeconds ?? 0) || 0);
|
|
1318
|
+
const bitrate = clamp(Math.round(Number(audioOptions.bitrate ?? this.options.audioBitrate ?? 64) || 64), 16, 320);
|
|
1319
|
+
const mono = audioOptions.mono ?? this.options.audioMono ?? false;
|
|
1320
|
+
const sampleRate = clamp(Math.round(Number(audioOptions.sampleRate ?? this.options.audioSampleRate ?? 48000) || 48000), 8000, 96000);
|
|
1321
|
+
const oggPath = path.join(this.tempDir, `audio_${ts}.ogg`);
|
|
1322
|
+
await this.convertAudioToOggOpus(audioFile, oggPath, { startTime, seconds, bitrate, mono, sampleRate });
|
|
1323
|
+
const audioSeconds = Math.round((await probeAudioSeconds(oggPath)) * 100) / 100;
|
|
1324
|
+
const audioBuffer = await fsp.readFile(oggPath);
|
|
1325
|
+
safeUnlink(oggPath);
|
|
1326
|
+
if (audioIsTemp && audioFile)
|
|
1327
|
+
safeUnlink(audioFile);
|
|
1328
|
+
/* 4. visual → WebP 512x512 com EXIF (pipeline completo: crop + watermark + shrink) */
|
|
1329
|
+
const stickerPath = await this.processFile(visualFile, 0);
|
|
1330
|
+
const stickerBuffer = await fsp.readFile(stickerPath);
|
|
1331
|
+
const animated = await this.detectAnimatedWebp(stickerPath);
|
|
1332
|
+
const result = {
|
|
1333
|
+
sticker: stickerBuffer,
|
|
1334
|
+
audio: audioBuffer,
|
|
1335
|
+
seconds: audioSeconds,
|
|
1336
|
+
animated,
|
|
1337
|
+
audioMime: 'audio/ogg; codecs=opus',
|
|
1338
|
+
stickerSize: stickerBuffer.length,
|
|
1339
|
+
audioSize: audioBuffer.length,
|
|
1340
|
+
warnings: [...(this.lastWarnings || [])]
|
|
1341
|
+
};
|
|
1342
|
+
this.say('success', 'AUDIO-STICKER', `figurinha com som pronta: sticker ${fmtSize(result.stickerSize)} + áudio ${fmtSize(result.audioSize)} (${audioSeconds.toFixed(1)}s)`, `${animated ? 'animada' : 'estática'} · opus ${bitrate}k`);
|
|
1343
|
+
this.emit('st.audioSticker', result);
|
|
1344
|
+
return result;
|
|
661
1345
|
}
|
|
1346
|
+
/** ffmpeg: qualquer fonte de áudio → OGG/Opus (formato de áudio do WhatsApp). */
|
|
1347
|
+
async convertAudioToOggOpus(srcFile, outPath, o) {
|
|
1348
|
+
const args = ['-nostdin', '-hide_banner', '-y'];
|
|
1349
|
+
if (o.startTime > 0)
|
|
1350
|
+
args.push('-ss', String(o.startTime));
|
|
1351
|
+
args.push('-i', srcFile);
|
|
1352
|
+
if (o.seconds > 0)
|
|
1353
|
+
args.push('-t', String(o.seconds));
|
|
1354
|
+
args.push('-map', '0:a:0', '-vn', '-sn', '-dn');
|
|
1355
|
+
args.push('-c:a', 'libopus', '-b:a', `${o.bitrate}k`, '-ar', String(o.sampleRate));
|
|
1356
|
+
if (o.mono)
|
|
1357
|
+
args.push('-ac', '1');
|
|
1358
|
+
args.push('-f', 'ogg', outPath);
|
|
1359
|
+
try {
|
|
1360
|
+
await execFileAsync(ffmpegPath || 'ffmpeg', args, { timeout: 120000, maxBuffer: 16 * 1024 * 1024 });
|
|
1361
|
+
}
|
|
1362
|
+
catch (err) {
|
|
1363
|
+
throw new Error(`Falha ao converter áudio para OGG/Opus: ${errorMessage(err)}. ` +
|
|
1364
|
+
`Se você usa ffmpegPath customizado, verifique se o binário tem libopus habilitado.`);
|
|
1365
|
+
}
|
|
1366
|
+
if (!fs.existsSync(outPath) || fs.statSync(outPath).size < 64) {
|
|
1367
|
+
throw new Error('Áudio OGG/Opus saiu vazio — a fonte não tem faixa de áudio decodificável.');
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/* ---------------- misc ---------------- */
|
|
662
1371
|
static fileToBase64(filePath) {
|
|
663
1372
|
return fs.readFileSync(filePath).toString('base64');
|
|
664
1373
|
}
|
|
1374
|
+
/** Informações do último encode (qualidade/fps/tentativas de shrink). */
|
|
1375
|
+
get lastInfo() {
|
|
1376
|
+
return { ...this.lastEncodeInfo };
|
|
1377
|
+
}
|
|
665
1378
|
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
if (isDataURI(input))
|
|
679
|
-
finalInput = parseDataURItoBuffer(input);
|
|
680
|
-
else if (isHttp(input))
|
|
681
|
-
finalInput = await getBuffer(input);
|
|
682
|
-
}
|
|
683
|
-
const result = await engine.build(finalInput);
|
|
684
|
-
await conn.sendMessage(jid, { sticker: { url: result.buffer }, ...options }, { quoted });
|
|
685
|
-
return result.buffer;
|
|
1379
|
+
/* ------------------------------------------------------------------ */
|
|
1380
|
+
/* API pública v4 — SÓ PREPARAÇÃO DE MÍDIA */
|
|
1381
|
+
/* Este módulo NÃO envia mensagens e NÃO conhece Baileys. */
|
|
1382
|
+
/* O bot recebe os buffers prontos e envia da forma que preferir. */
|
|
1383
|
+
/* ------------------------------------------------------------------ */
|
|
1384
|
+
/**
|
|
1385
|
+
* Converte qualquer áudio/mídia para OGG/Opus do WhatsApp.
|
|
1386
|
+
* Ex.: `const { buffer, seconds } = await toStickerAudio(musicBuffer)`
|
|
1387
|
+
*/
|
|
1388
|
+
export async function toStickerAudio(input, options = {}) {
|
|
1389
|
+
const engine = new StickEngine({ tempDir: options.tempDir, silent: options.silent === true });
|
|
1390
|
+
return engine.toStickerAudio(input, options);
|
|
686
1391
|
}
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
1392
|
+
/**
|
|
1393
|
+
* Prepara figurinha com som: devolve { sticker, audio, seconds, ... }.
|
|
1394
|
+
* `options.audio` = áudio a acoplar; se ausente, usa a trilha do vídeo.
|
|
1395
|
+
* Duração do clipe é LIVRE: `options.audioSeconds` corta (default: áudio inteiro).
|
|
1396
|
+
*/
|
|
1397
|
+
export async function createAudioSticker(visual, options = {}) {
|
|
1398
|
+
const { audio = null, audioStartTime, audioSeconds, audioBitrate, audioMono, audioSampleRate, silent, tempDir, ...engineOpts } = options;
|
|
1399
|
+
const engine = new StickEngine({ ...engineOpts, tempDir, silent: silent === true });
|
|
1400
|
+
return engine.createAudioSticker(visual, audio, {
|
|
1401
|
+
startTime: audioStartTime,
|
|
1402
|
+
seconds: audioSeconds,
|
|
1403
|
+
bitrate: audioBitrate,
|
|
1404
|
+
mono: audioMono,
|
|
1405
|
+
sampleRate: audioSampleRate
|
|
698
1406
|
});
|
|
699
|
-
let finalInput = input;
|
|
700
|
-
if (typeof input === 'string') {
|
|
701
|
-
if (isDataURI(input))
|
|
702
|
-
finalInput = parseDataURItoBuffer(input);
|
|
703
|
-
else if (isHttp(input))
|
|
704
|
-
finalInput = await getBuffer(input);
|
|
705
|
-
}
|
|
706
|
-
const result = await engine.build(finalInput);
|
|
707
|
-
await conn.sendMessage(jid, { sticker: { url: result.buffer }, ...options }, { quoted });
|
|
708
|
-
return result.buffer;
|
|
709
1407
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
fs.writeFileSync(filePath, media);
|
|
717
|
-
const out = path.join(engine.tempDir, `out_${ts}.webp`);
|
|
718
|
-
await engine.convertToWebp(filePath, out, false);
|
|
719
|
-
const buf = fs.readFileSync(out);
|
|
720
|
-
try {
|
|
721
|
-
fs.unlinkSync(filePath);
|
|
722
|
-
fs.unlinkSync(out);
|
|
723
|
-
}
|
|
724
|
-
catch { }
|
|
725
|
-
return buf;
|
|
1408
|
+
/* ------------------------------------------------------------------ */
|
|
1409
|
+
/* Legacy helpers */
|
|
1410
|
+
/* ------------------------------------------------------------------ */
|
|
1411
|
+
export async function imageToWebp(media, options = {}) {
|
|
1412
|
+
// sem fit forçado: herda o padrão da engine (cover = figurinha gigante, sem bordas)
|
|
1413
|
+
return await StickEngine.toBuffer(media, options);
|
|
726
1414
|
}
|
|
727
|
-
export async function videoToWebp(media) {
|
|
728
|
-
|
|
729
|
-
const ts = `${Date.now()}_${Crypto.randomBytes(3).toString('hex')}`;
|
|
730
|
-
const filePath = path.join(engine.tempDir, `vid_${ts}.mp4`);
|
|
731
|
-
fs.writeFileSync(filePath, media);
|
|
732
|
-
const out = path.join(engine.tempDir, `out_${ts}.webp`);
|
|
733
|
-
await engine.convertToWebp(filePath, out, true);
|
|
734
|
-
const buf = fs.readFileSync(out);
|
|
735
|
-
try {
|
|
736
|
-
fs.unlinkSync(filePath);
|
|
737
|
-
fs.unlinkSync(out);
|
|
738
|
-
}
|
|
739
|
-
catch { }
|
|
740
|
-
return buf;
|
|
1415
|
+
export async function videoToWebp(media, options = {}) {
|
|
1416
|
+
return await StickEngine.toBuffer(media, { fps: 15, maxDuration: 5, ...options });
|
|
741
1417
|
}
|
|
742
1418
|
export async function writeExifImg(media, metadata) {
|
|
743
|
-
const result = await StickEngine.create(media, {
|
|
1419
|
+
const result = await StickEngine.create(media, {
|
|
1420
|
+
metadata: {
|
|
1421
|
+
pack: metadata.packname || metadata.pack,
|
|
1422
|
+
author: metadata.author,
|
|
1423
|
+
emojis: metadata.categories || metadata.emojis
|
|
1424
|
+
}
|
|
1425
|
+
});
|
|
744
1426
|
return result.path;
|
|
745
1427
|
}
|
|
746
1428
|
export async function writeExifVid(media, metadata) {
|
|
747
|
-
return writeExifImg(media, metadata);
|
|
1429
|
+
return await writeExifImg(media, metadata);
|
|
748
1430
|
}
|
|
749
1431
|
export const imageToWebp2 = imageToWebp;
|
|
750
1432
|
export const videoToWebp2 = videoToWebp;
|