@boruto_vk7/stickengine 4.1.0 → 4.2.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/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @boruto_vk7/stickengine
2
2
 
3
+ > **4.2.1 — TURBO**: WebP animado agora é codificado **em paralelo** (um processo ffmpeg por núcleo, até 4) e os pedaços são remontados byte a byte, sem recodificar a junção. Defaults de velocidade: `fps` 15→12, `quality` animado 80→75, `compressionLevel` 6→1 (6 multiplicava o tempo de encode), auto-shrink proporcional (≤3 tentativas) e ffmpeg do sistema preferido quando tem `libwebp`. Um clipe de 4s que levava ~20s numa VPS fraca agora sai em poucos segundos. Desative o paralelismo com `parallelChunks: 1`.
4
+
5
+
3
6
  [![npm](https://img.shields.io/npm/v/@boruto_vk7/stickengine)](https://www.npmjs.com/package/@boruto_vk7/stickengine)
4
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
8
  [![Node](https://img.shields.io/node/v/@boruto_vk7/stickengine)](package.json)
@@ -59,11 +59,48 @@ function loadInstaller(name) {
59
59
  catch { /* ignore */ }
60
60
  return null;
61
61
  }
62
+ function resolveSystemBinary(name) {
63
+ const envVar = name === 'ffmpeg' ? 'STICKENGINE_FFMPEG_PATH' : 'STICKENGINE_FFPROBE_PATH';
64
+ if (process.env[envVar] && node_fs_1.default.existsSync(process.env[envVar]))
65
+ return process.env[envVar];
66
+ for (const dir of String(process.env.PATH || '').split(node_path_1.default.delimiter)) {
67
+ if (!dir)
68
+ continue;
69
+ try {
70
+ const p = node_path_1.default.join(dir, name);
71
+ node_fs_1.default.accessSync(p, node_fs_1.default.constants.X_OK);
72
+ return p;
73
+ }
74
+ catch { /* ignore */ }
75
+ }
76
+ return null;
77
+ }
78
+ let systemFfmpegValidado = null; // cache: ffmpeg do sistema tem libwebp?
79
+ function systemFfmpegTemLibwebp(bin) {
80
+ if (systemFfmpegValidado !== null)
81
+ return systemFfmpegValidado;
82
+ try {
83
+ const so = node_child_process_1.execFileSync(bin, ['-hide_banner', '-encoders'], { timeout: 15000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
84
+ systemFfmpegValidado = /libwebp/.test(String(so || ''));
85
+ }
86
+ catch {
87
+ systemFfmpegValidado = false;
88
+ }
89
+ return systemFfmpegValidado;
90
+ }
62
91
  function configureFfmpegBinaries(options = {}) {
92
+ // build da distro (com SIMD) costuma ser bem mais rápida que o binário
93
+ // estático genérico de 2018 embutido; valida libwebp antes de usar.
94
+ const prefereSistema = options.preferSystemBinaries !== false
95
+ && String(process.env.STICKENGINE_PREFER_SYSTEM ?? '1') !== '0';
96
+ const sistemaFfmpeg = prefereSistema ? resolveSystemBinary('ffmpeg') : null;
97
+ const sistemaFfprobe = prefereSistema ? resolveSystemBinary('ffprobe') : null;
63
98
  ffmpegPath = (options.ffmpegPath && node_fs_1.default.existsSync(options.ffmpegPath) ? options.ffmpegPath : null)
99
+ || (sistemaFfmpeg && systemFfmpegTemLibwebp(sistemaFfmpeg) ? sistemaFfmpeg : null)
64
100
  || loadInstaller('@ffmpeg-installer/ffmpeg')
65
101
  || 'ffmpeg';
66
102
  ffprobePath = (options.ffprobePath && node_fs_1.default.existsSync(options.ffprobePath) ? options.ffprobePath : null)
103
+ || (sistemaFfprobe && node_fs_1.default.existsSync(sistemaFfprobe) ? sistemaFfprobe : null)
67
104
  || loadInstaller('@ffprobe-installer/ffprobe')
68
105
  || 'ffprobe';
69
106
  try {
@@ -251,7 +288,8 @@ class StickEngine extends node_events_1.EventEmitter {
251
288
  edit: false,
252
289
  transparent: false,
253
290
  autoClean: false,
254
- fps: 15,
291
+ fps: undefined,
292
+ parallelChunks: 'auto',
255
293
  quality: undefined,
256
294
  maxDuration: 3,
257
295
  fit: 'cover',
@@ -290,8 +328,8 @@ class StickEngine extends node_events_1.EventEmitter {
290
328
  this.maxSizeStatic = Math.max(10_000, Number(this.options.maxSizeStatic ?? 100_000) || 100_000);
291
329
  if (!VALID_FITS.includes(String(this.options.fit)))
292
330
  this.options.fit = 'cover';
293
- // Re-resolve binaries if custom paths were passed to the constructor
294
- if (options.ffmpegPath || options.ffprobePath)
331
+ // Re-resolve binaries (caminhos explícitos ou preferência de sistema)
332
+ if (options.ffmpegPath || options.ffprobePath || options.preferSystemBinaries != null)
295
333
  configureFfmpegBinaries(options);
296
334
  }
297
335
  /* ---------------- static factories ---------------- */
@@ -497,7 +535,8 @@ class StickEngine extends node_events_1.EventEmitter {
497
535
  watermarkPath: watermarkPathForFfmpeg,
498
536
  watermarkCfg,
499
537
  warnings,
500
- index
538
+ index,
539
+ mediaInfo
501
540
  });
502
541
  }
503
542
  catch (err) {
@@ -722,7 +761,7 @@ class StickEngine extends node_events_1.EventEmitter {
722
761
  async detectVideoCropByCropdetect(input, mediaInfo) {
723
762
  try {
724
763
  const args = ['-nostdin', '-hide_banner', '-i', input, '-an'];
725
- const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 6) : 0;
764
+ const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 3) : 0;
726
765
  if (sample > 0)
727
766
  args.push('-t', String(sample));
728
767
  args.push('-vf', `cropdetect=limit=${this.crop.tolerance}:round=2:reset=0`, '-f', 'null', '-');
@@ -1154,6 +1193,184 @@ class StickEngine extends node_events_1.EventEmitter {
1154
1193
  ].join(';');
1155
1194
  }
1156
1195
  /* ---------------- encode ---------------- */
1196
+
1197
+ /* ---- WebP animado em paralelo (4.2.0): divide o clipe em pedaços, codifica
1198
+ cada pedaço num processo ffmpeg próprio (um por núcleo) e remonta os chunks
1199
+ ANMF byte a byte — a junção não recodifica nada. ---- */
1200
+ lerChunksRiffWebp(buf) {
1201
+ if (buf.length < 12 || buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WEBP')
1202
+ throw new Error('pedaço não é um WebP (RIFF/WEBP)');
1203
+ const chunks = [];
1204
+ let off = 12;
1205
+ while (off + 8 <= buf.length) {
1206
+ const id = buf.toString('latin1', off, off + 4);
1207
+ const sz = buf.readUInt32LE(off + 4);
1208
+ const ini = off + 8;
1209
+ if (ini + sz > buf.length)
1210
+ break;
1211
+ chunks.push({ id, payload: buf.subarray(ini, ini + sz) });
1212
+ off = ini + sz + (sz % 2);
1213
+ }
1214
+ return chunks;
1215
+ }
1216
+ montarWebpAnimado(pedacos) {
1217
+ let vp8x = null;
1218
+ let anim = null;
1219
+ const anmfs = [];
1220
+ for (const pedaco of pedacos) {
1221
+ const chunks = this.lerChunksRiffWebp(pedaco);
1222
+ let temAnmf = false;
1223
+ for (const c of chunks) {
1224
+ if (c.id === 'VP8X') {
1225
+ if (!vp8x)
1226
+ vp8x = Buffer.from(c.payload);
1227
+ }
1228
+ else if (c.id === 'ANIM') {
1229
+ if (!anim)
1230
+ anim = Buffer.from(c.payload);
1231
+ }
1232
+ else if (c.id === 'ANMF') {
1233
+ anmfs.push(Buffer.from(c.payload));
1234
+ temAnmf = true;
1235
+ }
1236
+ }
1237
+ if (!temAnmf)
1238
+ throw new Error('pedaço sem frames (ANMF) — WebP animado inválido');
1239
+ }
1240
+ if (!vp8x || !anim || !anmfs.length)
1241
+ throw new Error('WebP animado incompleto (VP8X/ANIM/ANMF ausente)');
1242
+ vp8x[0] |= 0x02; // garante flag de animação ligada
1243
+ const partes = [];
1244
+ const pushChunk = (id, payload) => {
1245
+ partes.push(Buffer.from(id, 'latin1'));
1246
+ const szb = Buffer.alloc(4);
1247
+ szb.writeUInt32LE(payload.length);
1248
+ partes.push(szb);
1249
+ partes.push(payload);
1250
+ if (payload.length % 2)
1251
+ partes.push(Buffer.alloc(1));
1252
+ };
1253
+ pushChunk('VP8X', vp8x);
1254
+ pushChunk('ANIM', anim);
1255
+ for (const f of anmfs)
1256
+ pushChunk('ANMF', f);
1257
+ const corpo = Buffer.concat(partes);
1258
+ const header = Buffer.alloc(12);
1259
+ header.write('RIFF', 0, 'latin1');
1260
+ header.writeUInt32LE(4 + corpo.length, 4);
1261
+ header.write('WEBP', 8, 'latin1');
1262
+ return Buffer.concat([header, corpo]);
1263
+ }
1264
+ compressionLevelFor(isAnimated) {
1265
+ if (this.options.compressionLevel != null) {
1266
+ const n = Math.round(Number(this.options.compressionLevel) || 0);
1267
+ return Math.max(0, Math.min(6, n));
1268
+ }
1269
+ // 6 é o esforço máximo do libwebp (multiplica o tempo de encode);
1270
+ // 1 em animados é ~indistinguível visualmente e bem mais rápido.
1271
+ return isAnimated ? 1 : 4;
1272
+ }
1273
+ parallelChunksFor(totalFrames) {
1274
+ const opt = this.options.parallelChunks;
1275
+ let k = 0;
1276
+ if (opt != null && opt !== 'auto') {
1277
+ k = Math.round(Number(opt) || 0);
1278
+ }
1279
+ else {
1280
+ // availableParallelism respeita a cota de CPU do container (VPS/Docker);
1281
+ // cpus() vê os núcleos do host e superestima em planos pequenos
1282
+ const cores = typeof node_os_1.default.availableParallelism === 'function'
1283
+ ? node_os_1.default.availableParallelism()
1284
+ : node_os_1.default.cpus().length;
1285
+ k = Math.min(4, Math.max(1, Math.ceil(cores * 0.75)));
1286
+ }
1287
+ k = Math.max(1, Math.min(8, k));
1288
+ if (totalFrames < 24)
1289
+ return 1; // clipe curto: paralelizar não compensa
1290
+ if (totalFrames < 48)
1291
+ return Math.min(2, k);
1292
+ if (totalFrames < 96)
1293
+ return Math.min(3, k);
1294
+ return k;
1295
+ }
1296
+ runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop) {
1297
+ return new Promise((resolve, reject) => {
1298
+ const q = (0, util_js_1.clamp)(Math.round(quality), 1, 100);
1299
+ const opts = ['-nostdin', '-hide_banner'];
1300
+ if (ini > 0)
1301
+ opts.push('-ss', ini.toFixed(3));
1302
+ opts.push('-i', input);
1303
+ const vf = this.buildAnimatedFilters(crop, String(this.options.fit || 'cover'), fps);
1304
+ opts.push('-vf', vf);
1305
+ opts.push('-frames:v', String(frames), '-c:v', 'libwebp', '-preset', 'default', '-an', '-loop', '0', '-vsync', '0', '-lossless', '0', '-compression_level', String(this.compressionLevelFor(isAnimated)), '-q:v', String(q), '-quality', String(q), '-y', output);
1306
+ node_child_process_1.execFile(ffmpegPath || 'ffmpeg', opts, { timeout: 120000, maxBuffer: 16 * 1024 * 1024 }, (err, _so, se) => {
1307
+ if (err) {
1308
+ const detalhe = se ? ' — ' + String(se).split('\n').filter(Boolean).slice(-2).join(' ') : '';
1309
+ reject(new Error('FFmpeg falhou no pedaço do WebP animado: ' + err.message + detalhe));
1310
+ }
1311
+ else
1312
+ resolve();
1313
+ });
1314
+ });
1315
+ }
1316
+ /** Duração efetiva do clipe (considera startTime e maxDuration). */
1317
+ duracaoClipe(mediaInfo) {
1318
+ const durTotal = Number(mediaInfo && mediaInfo.duration) || 0;
1319
+ if (durTotal <= 0)
1320
+ return 0;
1321
+ const inicio = this.startTime > 0 ? this.startTime : 0;
1322
+ let clipe = durTotal - inicio;
1323
+ if (this.maxDuration > 0)
1324
+ clipe = Math.min(clipe, this.maxDuration);
1325
+ return Math.max(0, clipe);
1326
+ }
1327
+ /** Codifica o clipe em K pedaços paralelos (K processos ffmpeg) e remonta.
1328
+ Retorna false quando não dá pra paralelizar (o chamador usa o caminho comum). */
1329
+ async runEncodeAnimadoParalelo(input, output, quality, fps, crop, mediaInfo) {
1330
+ try {
1331
+ const clipe = this.duracaoClipe(mediaInfo);
1332
+ if (clipe <= 0.25)
1333
+ return false; // duração desconhecida/curta demais
1334
+ const total = Math.max(2, Math.round(clipe * fps));
1335
+ const k = this.parallelChunksFor(total);
1336
+ if (k <= 1)
1337
+ return false;
1338
+ // distribui o total de frames em K pedaços (contagem exata por pedaço)
1339
+ const contagens = [];
1340
+ const base = Math.floor(total / k);
1341
+ let resto = total % k;
1342
+ for (let i = 0; i < k; i++)
1343
+ contagens.push(base + (resto-- > 0 ? 1 : 0));
1344
+ const arquivos = [];
1345
+ const promessas = [];
1346
+ let t = inicio;
1347
+ for (let i = 0; i < k; i++) {
1348
+ const arq = output + '.p' + i;
1349
+ arquivos.push(arq);
1350
+ promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop));
1351
+ t += contagens[i] / fps;
1352
+ }
1353
+ try {
1354
+ await Promise.all(promessas);
1355
+ const montado = this.montarWebpAnimado(arquivos.map(a => node_fs_1.default.readFileSync(a)));
1356
+ node_fs_1.default.writeFileSync(output, montado);
1357
+ }
1358
+ finally {
1359
+ for (const a of arquivos) {
1360
+ try {
1361
+ node_fs_1.default.unlinkSync(a);
1362
+ }
1363
+ catch { /* ignore */ }
1364
+ }
1365
+ }
1366
+ return true;
1367
+ }
1368
+ catch (e) {
1369
+ // paralelo é otimização: qualquer falha cai no encode comum
1370
+ this.emit('st.warn', { message: 'encode paralelo falhou (' + ((e && e.message) || e) + ') — usando caminho comum' });
1371
+ return false;
1372
+ }
1373
+ }
1157
1374
  runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg) {
1158
1375
  return new Promise((resolve, reject) => {
1159
1376
  const q = (0, util_js_1.clamp)(Math.round(quality), 1, 100);
@@ -1186,7 +1403,7 @@ class StickEngine extends node_events_1.EventEmitter {
1186
1403
  else {
1187
1404
  opts.push('-lossless', this.options.lossless ? '1' : '0');
1188
1405
  }
1189
- opts.push('-compression_level', '6', '-q:v', String(q), '-quality', String(q));
1406
+ opts.push('-compression_level', String(this.compressionLevelFor(isAnimated)), '-q:v', String(q), '-quality', String(q));
1190
1407
  cmd
1191
1408
  .on('error', (err) => reject(err))
1192
1409
  .on('end', () => resolve())
@@ -1201,11 +1418,20 @@ class StickEngine extends node_events_1.EventEmitter {
1201
1418
  const lossless = this.options.lossless === true;
1202
1419
  let quality = this.options.quality != null
1203
1420
  ? (0, util_js_1.clamp)(Number(this.options.quality) || 80, 1, 100)
1204
- : (isAnimated ? 80 : 90);
1205
- let fps = (0, util_js_1.clamp)(Math.round(Number(this.options.fps ?? 15) || 15), 1, 60);
1421
+ : (isAnimated ? 75 : 90);
1422
+ let fps = (0, util_js_1.clamp)(Math.round(Number(this.options.fps ?? 12) || 12), 1, 60);
1423
+ // orçamento de frames: clipe longo roda com fps menor p/ codificar
1424
+ // menos frames e caber no maxSize sem re-encode (~120 frames no total)
1425
+ const clipeDur = this.duracaoClipe(opts.mediaInfo);
1426
+ if (isAnimated && this.options.fps == null && clipeDur > 6)
1427
+ fps = Math.max(8, Math.round(120 / clipeDur));
1206
1428
  const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
1207
1429
  try {
1208
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1430
+ const paralelo = isAnimated && !watermarkPath
1431
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1432
+ : false;
1433
+ if (!paralelo)
1434
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1209
1435
  }
1210
1436
  catch (err) {
1211
1437
  throw new Error(`FFmpeg falhou ao gerar WebP ${isAnimated ? 'animado' : 'estático'}: ${(0, logger_js_1.errorMessage)(err)}`);
@@ -1215,17 +1441,23 @@ class StickEngine extends node_events_1.EventEmitter {
1215
1441
  }
1216
1442
  this.say('info', 'ENCODE', `#${index} webp ${isAnimated ? 'animado' : 'estático'} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${(0, util_js_1.fmtSize)(node_fs_1.default.statSync(output).size)}`, `fit=${fitUsed}`);
1217
1443
  let attempts = 0;
1218
- while (!lossless && node_fs_1.default.existsSync(output) && node_fs_1.default.statSync(output).size > limit && attempts < 6) {
1444
+ const maxTentativas = isAnimated ? 3 : 4;
1445
+ while (!lossless && node_fs_1.default.existsSync(output) && node_fs_1.default.statSync(output).size > limit && attempts < maxTentativas) {
1219
1446
  attempts++;
1220
- this.say('info', 'ENCODE', `#${index} acima de ${(0, util_js_1.fmtSize)(limit)} — auto-shrink tentativa ${attempts}`);
1447
+ const excesso = node_fs_1.default.statSync(output).size / limit;
1448
+ this.say('info', 'ENCODE', `#${index} acima de ${(0, util_js_1.fmtSize)(limit)} — auto-shrink tentativa ${attempts} (${Math.round(excesso * 100)}%)`);
1221
1449
  if (isAnimated) {
1222
- quality = Math.max(20, quality - 15);
1223
- fps = Math.max(8, fps - 2);
1450
+ quality = Math.max(20, Math.round(Math.min(quality - 10, quality / Math.sqrt(excesso))));
1451
+ fps = Math.max(8, fps - (excesso > 1.5 ? 3 : 2));
1224
1452
  }
1225
1453
  else {
1226
- quality = Math.max(10, quality - 12);
1454
+ quality = Math.max(10, Math.round(Math.min(quality - 12, quality / Math.sqrt(excesso))));
1227
1455
  }
1228
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1456
+ const paraleloShrink = isAnimated && !watermarkPath
1457
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1458
+ : false;
1459
+ if (!paraleloShrink)
1460
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1229
1461
  if (!node_fs_1.default.existsSync(output))
1230
1462
  throw new Error('FFmpeg falhou no auto-shrink');
1231
1463
  this.say('info', 'ENCODE', `#${index} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${(0, util_js_1.fmtSize)(node_fs_1.default.statSync(output).size)}`);
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import fsp from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
- import { execFile } from 'node:child_process';
5
+ import { execFile, execFileSync } from 'node:child_process';
6
6
  import { promisify } from 'node:util';
7
7
  import { EventEmitter } from 'node:events';
8
8
  import Crypto from 'node:crypto';
@@ -44,11 +44,48 @@ function loadInstaller(name) {
44
44
  catch { /* ignore */ }
45
45
  return null;
46
46
  }
47
+ function resolveSystemBinary(name) {
48
+ const envVar = name === 'ffmpeg' ? 'STICKENGINE_FFMPEG_PATH' : 'STICKENGINE_FFPROBE_PATH';
49
+ if (process.env[envVar] && fs.existsSync(process.env[envVar]))
50
+ return process.env[envVar];
51
+ for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
52
+ if (!dir)
53
+ continue;
54
+ try {
55
+ const p = path.join(dir, name);
56
+ fs.accessSync(p, fs.constants.X_OK);
57
+ return p;
58
+ }
59
+ catch { /* ignore */ }
60
+ }
61
+ return null;
62
+ }
63
+ let systemFfmpegValidado = null; // cache: ffmpeg do sistema tem libwebp?
64
+ function systemFfmpegTemLibwebp(bin) {
65
+ if (systemFfmpegValidado !== null)
66
+ return systemFfmpegValidado;
67
+ try {
68
+ const so = execFileSync(bin, ['-hide_banner', '-encoders'], { timeout: 15000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
69
+ systemFfmpegValidado = /libwebp/.test(String(so || ''));
70
+ }
71
+ catch {
72
+ systemFfmpegValidado = false;
73
+ }
74
+ return systemFfmpegValidado;
75
+ }
47
76
  function configureFfmpegBinaries(options = {}) {
77
+ // build da distro (com SIMD) costuma ser bem mais rápida que o binário
78
+ // estático genérico de 2018 embutido; valida libwebp antes de usar.
79
+ const prefereSistema = options.preferSystemBinaries !== false
80
+ && String(process.env.STICKENGINE_PREFER_SYSTEM ?? '1') !== '0';
81
+ const sistemaFfmpeg = prefereSistema ? resolveSystemBinary('ffmpeg') : null;
82
+ const sistemaFfprobe = prefereSistema ? resolveSystemBinary('ffprobe') : null;
48
83
  ffmpegPath = (options.ffmpegPath && fs.existsSync(options.ffmpegPath) ? options.ffmpegPath : null)
84
+ || (sistemaFfmpeg && systemFfmpegTemLibwebp(sistemaFfmpeg) ? sistemaFfmpeg : null)
49
85
  || loadInstaller('@ffmpeg-installer/ffmpeg')
50
86
  || 'ffmpeg';
51
87
  ffprobePath = (options.ffprobePath && fs.existsSync(options.ffprobePath) ? options.ffprobePath : null)
88
+ || (sistemaFfprobe && fs.existsSync(sistemaFfprobe) ? sistemaFfprobe : null)
52
89
  || loadInstaller('@ffprobe-installer/ffprobe')
53
90
  || 'ffprobe';
54
91
  try {
@@ -236,7 +273,8 @@ export class StickEngine extends EventEmitter {
236
273
  edit: false,
237
274
  transparent: false,
238
275
  autoClean: false,
239
- fps: 15,
276
+ fps: undefined,
277
+ parallelChunks: 'auto',
240
278
  quality: undefined,
241
279
  maxDuration: 3,
242
280
  fit: 'cover',
@@ -275,8 +313,8 @@ export class StickEngine extends EventEmitter {
275
313
  this.maxSizeStatic = Math.max(10_000, Number(this.options.maxSizeStatic ?? 100_000) || 100_000);
276
314
  if (!VALID_FITS.includes(String(this.options.fit)))
277
315
  this.options.fit = 'cover';
278
- // Re-resolve binaries if custom paths were passed to the constructor
279
- if (options.ffmpegPath || options.ffprobePath)
316
+ // Re-resolve binaries (caminhos explícitos ou preferência de sistema)
317
+ if (options.ffmpegPath || options.ffprobePath || options.preferSystemBinaries != null)
280
318
  configureFfmpegBinaries(options);
281
319
  }
282
320
  /* ---------------- static factories ---------------- */
@@ -482,7 +520,8 @@ export class StickEngine extends EventEmitter {
482
520
  watermarkPath: watermarkPathForFfmpeg,
483
521
  watermarkCfg,
484
522
  warnings,
485
- index
523
+ index,
524
+ mediaInfo
486
525
  });
487
526
  }
488
527
  catch (err) {
@@ -707,7 +746,7 @@ export class StickEngine extends EventEmitter {
707
746
  async detectVideoCropByCropdetect(input, mediaInfo) {
708
747
  try {
709
748
  const args = ['-nostdin', '-hide_banner', '-i', input, '-an'];
710
- const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 6) : 0;
749
+ const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 3) : 0;
711
750
  if (sample > 0)
712
751
  args.push('-t', String(sample));
713
752
  args.push('-vf', `cropdetect=limit=${this.crop.tolerance}:round=2:reset=0`, '-f', 'null', '-');
@@ -1139,6 +1178,184 @@ export class StickEngine extends EventEmitter {
1139
1178
  ].join(';');
1140
1179
  }
1141
1180
  /* ---------------- encode ---------------- */
1181
+
1182
+ /* ---- WebP animado em paralelo (4.2.0): divide o clipe em pedaços, codifica
1183
+ cada pedaço num processo ffmpeg próprio (um por núcleo) e remonta os chunks
1184
+ ANMF byte a byte — a junção não recodifica nada. ---- */
1185
+ lerChunksRiffWebp(buf) {
1186
+ if (buf.length < 12 || buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WEBP')
1187
+ throw new Error('pedaço não é um WebP (RIFF/WEBP)');
1188
+ const chunks = [];
1189
+ let off = 12;
1190
+ while (off + 8 <= buf.length) {
1191
+ const id = buf.toString('latin1', off, off + 4);
1192
+ const sz = buf.readUInt32LE(off + 4);
1193
+ const ini = off + 8;
1194
+ if (ini + sz > buf.length)
1195
+ break;
1196
+ chunks.push({ id, payload: buf.subarray(ini, ini + sz) });
1197
+ off = ini + sz + (sz % 2);
1198
+ }
1199
+ return chunks;
1200
+ }
1201
+ montarWebpAnimado(pedacos) {
1202
+ let vp8x = null;
1203
+ let anim = null;
1204
+ const anmfs = [];
1205
+ for (const pedaco of pedacos) {
1206
+ const chunks = this.lerChunksRiffWebp(pedaco);
1207
+ let temAnmf = false;
1208
+ for (const c of chunks) {
1209
+ if (c.id === 'VP8X') {
1210
+ if (!vp8x)
1211
+ vp8x = Buffer.from(c.payload);
1212
+ }
1213
+ else if (c.id === 'ANIM') {
1214
+ if (!anim)
1215
+ anim = Buffer.from(c.payload);
1216
+ }
1217
+ else if (c.id === 'ANMF') {
1218
+ anmfs.push(Buffer.from(c.payload));
1219
+ temAnmf = true;
1220
+ }
1221
+ }
1222
+ if (!temAnmf)
1223
+ throw new Error('pedaço sem frames (ANMF) — WebP animado inválido');
1224
+ }
1225
+ if (!vp8x || !anim || !anmfs.length)
1226
+ throw new Error('WebP animado incompleto (VP8X/ANIM/ANMF ausente)');
1227
+ vp8x[0] |= 0x02; // garante flag de animação ligada
1228
+ const partes = [];
1229
+ const pushChunk = (id, payload) => {
1230
+ partes.push(Buffer.from(id, 'latin1'));
1231
+ const szb = Buffer.alloc(4);
1232
+ szb.writeUInt32LE(payload.length);
1233
+ partes.push(szb);
1234
+ partes.push(payload);
1235
+ if (payload.length % 2)
1236
+ partes.push(Buffer.alloc(1));
1237
+ };
1238
+ pushChunk('VP8X', vp8x);
1239
+ pushChunk('ANIM', anim);
1240
+ for (const f of anmfs)
1241
+ pushChunk('ANMF', f);
1242
+ const corpo = Buffer.concat(partes);
1243
+ const header = Buffer.alloc(12);
1244
+ header.write('RIFF', 0, 'latin1');
1245
+ header.writeUInt32LE(4 + corpo.length, 4);
1246
+ header.write('WEBP', 8, 'latin1');
1247
+ return Buffer.concat([header, corpo]);
1248
+ }
1249
+ compressionLevelFor(isAnimated) {
1250
+ if (this.options.compressionLevel != null) {
1251
+ const n = Math.round(Number(this.options.compressionLevel) || 0);
1252
+ return Math.max(0, Math.min(6, n));
1253
+ }
1254
+ // 6 é o esforço máximo do libwebp (multiplica o tempo de encode);
1255
+ // 1 em animados é ~indistinguível visualmente e bem mais rápido.
1256
+ return isAnimated ? 1 : 4;
1257
+ }
1258
+ parallelChunksFor(totalFrames) {
1259
+ const opt = this.options.parallelChunks;
1260
+ let k = 0;
1261
+ if (opt != null && opt !== 'auto') {
1262
+ k = Math.round(Number(opt) || 0);
1263
+ }
1264
+ else {
1265
+ // availableParallelism respeita a cota de CPU do container (VPS/Docker);
1266
+ // cpus() vê os núcleos do host e superestima em planos pequenos
1267
+ const cores = typeof os.availableParallelism === 'function'
1268
+ ? os.availableParallelism()
1269
+ : os.cpus().length;
1270
+ k = Math.min(4, Math.max(1, Math.ceil(cores * 0.75)));
1271
+ }
1272
+ k = Math.max(1, Math.min(8, k));
1273
+ if (totalFrames < 24)
1274
+ return 1; // clipe curto: paralelizar não compensa
1275
+ if (totalFrames < 48)
1276
+ return Math.min(2, k);
1277
+ if (totalFrames < 96)
1278
+ return Math.min(3, k);
1279
+ return k;
1280
+ }
1281
+ runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop) {
1282
+ return new Promise((resolve, reject) => {
1283
+ const q = clamp(Math.round(quality), 1, 100);
1284
+ const opts = ['-nostdin', '-hide_banner'];
1285
+ if (ini > 0)
1286
+ opts.push('-ss', ini.toFixed(3));
1287
+ opts.push('-i', input);
1288
+ const vf = this.buildAnimatedFilters(crop, String(this.options.fit || 'cover'), fps);
1289
+ opts.push('-vf', vf);
1290
+ opts.push('-frames:v', String(frames), '-c:v', 'libwebp', '-preset', 'default', '-an', '-loop', '0', '-vsync', '0', '-lossless', '0', '-compression_level', String(this.compressionLevelFor(isAnimated)), '-q:v', String(q), '-quality', String(q), '-y', output);
1291
+ execFile(ffmpegPath || 'ffmpeg', opts, { timeout: 120000, maxBuffer: 16 * 1024 * 1024 }, (err, _so, se) => {
1292
+ if (err) {
1293
+ const detalhe = se ? ' — ' + String(se).split('\n').filter(Boolean).slice(-2).join(' ') : '';
1294
+ reject(new Error('FFmpeg falhou no pedaço do WebP animado: ' + err.message + detalhe));
1295
+ }
1296
+ else
1297
+ resolve();
1298
+ });
1299
+ });
1300
+ }
1301
+ /** Duração efetiva do clipe (considera startTime e maxDuration). */
1302
+ duracaoClipe(mediaInfo) {
1303
+ const durTotal = Number(mediaInfo && mediaInfo.duration) || 0;
1304
+ if (durTotal <= 0)
1305
+ return 0;
1306
+ const inicio = this.startTime > 0 ? this.startTime : 0;
1307
+ let clipe = durTotal - inicio;
1308
+ if (this.maxDuration > 0)
1309
+ clipe = Math.min(clipe, this.maxDuration);
1310
+ return Math.max(0, clipe);
1311
+ }
1312
+ /** Codifica o clipe em K pedaços paralelos (K processos ffmpeg) e remonta.
1313
+ Retorna false quando não dá pra paralelizar (o chamador usa o caminho comum). */
1314
+ async runEncodeAnimadoParalelo(input, output, quality, fps, crop, mediaInfo) {
1315
+ try {
1316
+ const clipe = this.duracaoClipe(mediaInfo);
1317
+ if (clipe <= 0.25)
1318
+ return false; // duração desconhecida/curta demais
1319
+ const total = Math.max(2, Math.round(clipe * fps));
1320
+ const k = this.parallelChunksFor(total);
1321
+ if (k <= 1)
1322
+ return false;
1323
+ // distribui o total de frames em K pedaços (contagem exata por pedaço)
1324
+ const contagens = [];
1325
+ const base = Math.floor(total / k);
1326
+ let resto = total % k;
1327
+ for (let i = 0; i < k; i++)
1328
+ contagens.push(base + (resto-- > 0 ? 1 : 0));
1329
+ const arquivos = [];
1330
+ const promessas = [];
1331
+ let t = inicio;
1332
+ for (let i = 0; i < k; i++) {
1333
+ const arq = output + '.p' + i;
1334
+ arquivos.push(arq);
1335
+ promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop));
1336
+ t += contagens[i] / fps;
1337
+ }
1338
+ try {
1339
+ await Promise.all(promessas);
1340
+ const montado = this.montarWebpAnimado(arquivos.map(a => fs.readFileSync(a)));
1341
+ fs.writeFileSync(output, montado);
1342
+ }
1343
+ finally {
1344
+ for (const a of arquivos) {
1345
+ try {
1346
+ fs.unlinkSync(a);
1347
+ }
1348
+ catch { /* ignore */ }
1349
+ }
1350
+ }
1351
+ return true;
1352
+ }
1353
+ catch (e) {
1354
+ // paralelo é otimização: qualquer falha cai no encode comum
1355
+ this.emit('st.warn', { message: 'encode paralelo falhou (' + ((e && e.message) || e) + ') — usando caminho comum' });
1356
+ return false;
1357
+ }
1358
+ }
1142
1359
  runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg) {
1143
1360
  return new Promise((resolve, reject) => {
1144
1361
  const q = clamp(Math.round(quality), 1, 100);
@@ -1171,7 +1388,7 @@ export class StickEngine extends EventEmitter {
1171
1388
  else {
1172
1389
  opts.push('-lossless', this.options.lossless ? '1' : '0');
1173
1390
  }
1174
- opts.push('-compression_level', '6', '-q:v', String(q), '-quality', String(q));
1391
+ opts.push('-compression_level', String(this.compressionLevelFor(isAnimated)), '-q:v', String(q), '-quality', String(q));
1175
1392
  cmd
1176
1393
  .on('error', (err) => reject(err))
1177
1394
  .on('end', () => resolve())
@@ -1186,11 +1403,20 @@ export class StickEngine extends EventEmitter {
1186
1403
  const lossless = this.options.lossless === true;
1187
1404
  let quality = this.options.quality != null
1188
1405
  ? 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);
1406
+ : (isAnimated ? 75 : 90);
1407
+ let fps = clamp(Math.round(Number(this.options.fps ?? 12) || 12), 1, 60);
1408
+ // orçamento de frames: clipe longo roda com fps menor p/ codificar
1409
+ // menos frames e caber no maxSize sem re-encode (~120 frames no total)
1410
+ const clipeDur = this.duracaoClipe(opts.mediaInfo);
1411
+ if (isAnimated && this.options.fps == null && clipeDur > 6)
1412
+ fps = Math.max(8, Math.round(120 / clipeDur));
1191
1413
  const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
1192
1414
  try {
1193
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1415
+ const paralelo = isAnimated && !watermarkPath
1416
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1417
+ : false;
1418
+ if (!paralelo)
1419
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1194
1420
  }
1195
1421
  catch (err) {
1196
1422
  throw new Error(`FFmpeg falhou ao gerar WebP ${isAnimated ? 'animado' : 'estático'}: ${errorMessage(err)}`);
@@ -1200,17 +1426,23 @@ export class StickEngine extends EventEmitter {
1200
1426
  }
1201
1427
  this.say('info', 'ENCODE', `#${index} webp ${isAnimated ? 'animado' : 'estático'} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${fmtSize(fs.statSync(output).size)}`, `fit=${fitUsed}`);
1202
1428
  let attempts = 0;
1203
- while (!lossless && fs.existsSync(output) && fs.statSync(output).size > limit && attempts < 6) {
1429
+ const maxTentativas = isAnimated ? 3 : 4;
1430
+ while (!lossless && fs.existsSync(output) && fs.statSync(output).size > limit && attempts < maxTentativas) {
1204
1431
  attempts++;
1205
- this.say('info', 'ENCODE', `#${index} acima de ${fmtSize(limit)} — auto-shrink tentativa ${attempts}`);
1432
+ const excesso = fs.statSync(output).size / limit;
1433
+ this.say('info', 'ENCODE', `#${index} acima de ${fmtSize(limit)} — auto-shrink tentativa ${attempts} (${Math.round(excesso * 100)}%)`);
1206
1434
  if (isAnimated) {
1207
- quality = Math.max(20, quality - 15);
1208
- fps = Math.max(8, fps - 2);
1435
+ quality = Math.max(20, Math.round(Math.min(quality - 10, quality / Math.sqrt(excesso))));
1436
+ fps = Math.max(8, fps - (excesso > 1.5 ? 3 : 2));
1209
1437
  }
1210
1438
  else {
1211
- quality = Math.max(10, quality - 12);
1439
+ quality = Math.max(10, Math.round(Math.min(quality - 12, quality / Math.sqrt(excesso))));
1212
1440
  }
1213
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1441
+ const paraleloShrink = isAnimated && !watermarkPath
1442
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1443
+ : false;
1444
+ if (!paraleloShrink)
1445
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1214
1446
  if (!fs.existsSync(output))
1215
1447
  throw new Error('FFmpeg falhou no auto-shrink');
1216
1448
  this.say('info', 'ENCODE', `#${index} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${fmtSize(fs.statSync(output).size)}`);
@@ -89,6 +89,13 @@ export interface StickEngineOptions {
89
89
  maxSize?: number;
90
90
  tamanhoMaximo?: number;
91
91
  maxSizeStatic?: number;
92
+ /** Nº de processos ffmpeg para codificar WebP animado em paralelo
93
+ * ('auto' [padrão]: até 4, conforme os núcleos e a duração; 1 desliga). */
94
+ parallelChunks?: number | 'auto';
95
+ /** Nível de compressão do libwebp 0-6 (padrão: 1 animado / 4 estático — 6 é muito lento). */
96
+ compressionLevel?: number;
97
+ /** Preferir ffmpeg/ffprobe do sistema ao binário embutido (padrão true; exige libwebp no binário do sistema). */
98
+ preferSystemBinaries?: boolean;
92
99
  startTime?: number;
93
100
  tempoInicio?: number;
94
101
  tempoMaximo?: number;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@boruto_vk7/stickengine",
3
- "version": "4.1.0",
4
- "description": "WhatsApp sticker engine - media preparation only: 512x512 static/animated WebP, automatic black-border removal, full-bleed cover fit, audio sticker pair (WebP + OGG/Opus), bundled canvas and ffmpeg binaries, pack EXIF, chalk logging. No message sending, no Baileys coupling.",
3
+ "version": "4.2.1",
4
+ "description": "WhatsApp sticker engine - media preparation only: 512x512 static/animated WebP, parallel animated encoding, automatic black-border removal, full-bleed cover fit, audio sticker pair (WebP + OGG/Opus), bundled canvas and ffmpeg binaries, pack EXIF, chalk logging. No message sending, no Baileys coupling.",
5
5
  "author": "Borutovk7 - Lagos Solutions",
6
6
  "license": "MIT",
7
7
  "type": "module",