@boruto_vk7/stickengine 4.1.0 → 4.2.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/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @boruto_vk7/stickengine
2
2
 
3
+ > **4.2.0 — 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,180 @@ 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
+ const cores = Math.max(1, node_os_1.default.cpus().length);
1281
+ k = Math.min(4, Math.max(1, Math.ceil(cores * 0.75)));
1282
+ }
1283
+ k = Math.max(1, Math.min(8, k));
1284
+ if (totalFrames < 24)
1285
+ return 1; // clipe curto: paralelizar não compensa
1286
+ if (totalFrames < 48)
1287
+ return Math.min(2, k);
1288
+ if (totalFrames < 96)
1289
+ return Math.min(3, k);
1290
+ return k;
1291
+ }
1292
+ runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop) {
1293
+ return new Promise((resolve, reject) => {
1294
+ const q = (0, util_js_1.clamp)(Math.round(quality), 1, 100);
1295
+ const opts = ['-nostdin', '-hide_banner'];
1296
+ if (ini > 0)
1297
+ opts.push('-ss', ini.toFixed(3));
1298
+ opts.push('-i', input);
1299
+ const vf = this.buildAnimatedFilters(crop, String(this.options.fit || 'cover'), fps);
1300
+ opts.push('-vf', vf);
1301
+ 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);
1302
+ node_child_process_1.execFile(ffmpegPath || 'ffmpeg', opts, { timeout: 120000, maxBuffer: 16 * 1024 * 1024 }, (err, _so, se) => {
1303
+ if (err) {
1304
+ const detalhe = se ? ' — ' + String(se).split('\n').filter(Boolean).slice(-2).join(' ') : '';
1305
+ reject(new Error('FFmpeg falhou no pedaço do WebP animado: ' + err.message + detalhe));
1306
+ }
1307
+ else
1308
+ resolve();
1309
+ });
1310
+ });
1311
+ }
1312
+ /** Duração efetiva do clipe (considera startTime e maxDuration). */
1313
+ duracaoClipe(mediaInfo) {
1314
+ const durTotal = Number(mediaInfo && mediaInfo.duration) || 0;
1315
+ if (durTotal <= 0)
1316
+ return 0;
1317
+ const inicio = this.startTime > 0 ? this.startTime : 0;
1318
+ let clipe = durTotal - inicio;
1319
+ if (this.maxDuration > 0)
1320
+ clipe = Math.min(clipe, this.maxDuration);
1321
+ return Math.max(0, clipe);
1322
+ }
1323
+ /** Codifica o clipe em K pedaços paralelos (K processos ffmpeg) e remonta.
1324
+ Retorna false quando não dá pra paralelizar (o chamador usa o caminho comum). */
1325
+ async runEncodeAnimadoParalelo(input, output, quality, fps, crop, mediaInfo) {
1326
+ try {
1327
+ const clipe = this.duracaoClipe(mediaInfo);
1328
+ if (clipe <= 0.25)
1329
+ return false; // duração desconhecida/curta demais
1330
+ const total = Math.max(2, Math.round(clipe * fps));
1331
+ const k = this.parallelChunksFor(total);
1332
+ if (k <= 1)
1333
+ return false;
1334
+ // distribui o total de frames em K pedaços (contagem exata por pedaço)
1335
+ const contagens = [];
1336
+ const base = Math.floor(total / k);
1337
+ let resto = total % k;
1338
+ for (let i = 0; i < k; i++)
1339
+ contagens.push(base + (resto-- > 0 ? 1 : 0));
1340
+ const arquivos = [];
1341
+ const promessas = [];
1342
+ let t = inicio;
1343
+ for (let i = 0; i < k; i++) {
1344
+ const arq = output + '.p' + i;
1345
+ arquivos.push(arq);
1346
+ promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop));
1347
+ t += contagens[i] / fps;
1348
+ }
1349
+ try {
1350
+ await Promise.all(promessas);
1351
+ const montado = this.montarWebpAnimado(arquivos.map(a => node_fs_1.default.readFileSync(a)));
1352
+ node_fs_1.default.writeFileSync(output, montado);
1353
+ }
1354
+ finally {
1355
+ for (const a of arquivos) {
1356
+ try {
1357
+ node_fs_1.default.unlinkSync(a);
1358
+ }
1359
+ catch { /* ignore */ }
1360
+ }
1361
+ }
1362
+ return true;
1363
+ }
1364
+ catch (e) {
1365
+ // paralelo é otimização: qualquer falha cai no encode comum
1366
+ this.emit('st.warn', { message: 'encode paralelo falhou (' + ((e && e.message) || e) + ') — usando caminho comum' });
1367
+ return false;
1368
+ }
1369
+ }
1157
1370
  runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg) {
1158
1371
  return new Promise((resolve, reject) => {
1159
1372
  const q = (0, util_js_1.clamp)(Math.round(quality), 1, 100);
@@ -1186,7 +1399,7 @@ class StickEngine extends node_events_1.EventEmitter {
1186
1399
  else {
1187
1400
  opts.push('-lossless', this.options.lossless ? '1' : '0');
1188
1401
  }
1189
- opts.push('-compression_level', '6', '-q:v', String(q), '-quality', String(q));
1402
+ opts.push('-compression_level', String(this.compressionLevelFor(isAnimated)), '-q:v', String(q), '-quality', String(q));
1190
1403
  cmd
1191
1404
  .on('error', (err) => reject(err))
1192
1405
  .on('end', () => resolve())
@@ -1201,11 +1414,20 @@ class StickEngine extends node_events_1.EventEmitter {
1201
1414
  const lossless = this.options.lossless === true;
1202
1415
  let quality = this.options.quality != null
1203
1416
  ? (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);
1417
+ : (isAnimated ? 75 : 90);
1418
+ let fps = (0, util_js_1.clamp)(Math.round(Number(this.options.fps ?? 12) || 12), 1, 60);
1419
+ // orçamento de frames: clipe longo roda com fps menor p/ codificar
1420
+ // menos frames e caber no maxSize sem re-encode (~120 frames no total)
1421
+ const clipeDur = this.duracaoClipe(opts.mediaInfo);
1422
+ if (isAnimated && this.options.fps == null && clipeDur > 6)
1423
+ fps = Math.max(8, Math.round(120 / clipeDur));
1206
1424
  const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
1207
1425
  try {
1208
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1426
+ const paralelo = isAnimated && !watermarkPath
1427
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1428
+ : false;
1429
+ if (!paralelo)
1430
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1209
1431
  }
1210
1432
  catch (err) {
1211
1433
  throw new Error(`FFmpeg falhou ao gerar WebP ${isAnimated ? 'animado' : 'estático'}: ${(0, logger_js_1.errorMessage)(err)}`);
@@ -1215,17 +1437,23 @@ class StickEngine extends node_events_1.EventEmitter {
1215
1437
  }
1216
1438
  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
1439
  let attempts = 0;
1218
- while (!lossless && node_fs_1.default.existsSync(output) && node_fs_1.default.statSync(output).size > limit && attempts < 6) {
1440
+ const maxTentativas = isAnimated ? 3 : 4;
1441
+ while (!lossless && node_fs_1.default.existsSync(output) && node_fs_1.default.statSync(output).size > limit && attempts < maxTentativas) {
1219
1442
  attempts++;
1220
- this.say('info', 'ENCODE', `#${index} acima de ${(0, util_js_1.fmtSize)(limit)} — auto-shrink tentativa ${attempts}`);
1443
+ const excesso = node_fs_1.default.statSync(output).size / limit;
1444
+ this.say('info', 'ENCODE', `#${index} acima de ${(0, util_js_1.fmtSize)(limit)} — auto-shrink tentativa ${attempts} (${Math.round(excesso * 100)}%)`);
1221
1445
  if (isAnimated) {
1222
- quality = Math.max(20, quality - 15);
1223
- fps = Math.max(8, fps - 2);
1446
+ quality = Math.max(20, Math.round(Math.min(quality - 10, quality / Math.sqrt(excesso))));
1447
+ fps = Math.max(8, fps - (excesso > 1.5 ? 3 : 2));
1224
1448
  }
1225
1449
  else {
1226
- quality = Math.max(10, quality - 12);
1450
+ quality = Math.max(10, Math.round(Math.min(quality - 12, quality / Math.sqrt(excesso))));
1227
1451
  }
1228
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1452
+ const paraleloShrink = isAnimated && !watermarkPath
1453
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1454
+ : false;
1455
+ if (!paraleloShrink)
1456
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1229
1457
  if (!node_fs_1.default.existsSync(output))
1230
1458
  throw new Error('FFmpeg falhou no auto-shrink');
1231
1459
  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,180 @@ 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
+ const cores = Math.max(1, os.cpus().length);
1266
+ k = Math.min(4, Math.max(1, Math.ceil(cores * 0.75)));
1267
+ }
1268
+ k = Math.max(1, Math.min(8, k));
1269
+ if (totalFrames < 24)
1270
+ return 1; // clipe curto: paralelizar não compensa
1271
+ if (totalFrames < 48)
1272
+ return Math.min(2, k);
1273
+ if (totalFrames < 96)
1274
+ return Math.min(3, k);
1275
+ return k;
1276
+ }
1277
+ runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop) {
1278
+ return new Promise((resolve, reject) => {
1279
+ const q = clamp(Math.round(quality), 1, 100);
1280
+ const opts = ['-nostdin', '-hide_banner'];
1281
+ if (ini > 0)
1282
+ opts.push('-ss', ini.toFixed(3));
1283
+ opts.push('-i', input);
1284
+ const vf = this.buildAnimatedFilters(crop, String(this.options.fit || 'cover'), fps);
1285
+ opts.push('-vf', vf);
1286
+ 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);
1287
+ execFile(ffmpegPath || 'ffmpeg', opts, { timeout: 120000, maxBuffer: 16 * 1024 * 1024 }, (err, _so, se) => {
1288
+ if (err) {
1289
+ const detalhe = se ? ' — ' + String(se).split('\n').filter(Boolean).slice(-2).join(' ') : '';
1290
+ reject(new Error('FFmpeg falhou no pedaço do WebP animado: ' + err.message + detalhe));
1291
+ }
1292
+ else
1293
+ resolve();
1294
+ });
1295
+ });
1296
+ }
1297
+ /** Duração efetiva do clipe (considera startTime e maxDuration). */
1298
+ duracaoClipe(mediaInfo) {
1299
+ const durTotal = Number(mediaInfo && mediaInfo.duration) || 0;
1300
+ if (durTotal <= 0)
1301
+ return 0;
1302
+ const inicio = this.startTime > 0 ? this.startTime : 0;
1303
+ let clipe = durTotal - inicio;
1304
+ if (this.maxDuration > 0)
1305
+ clipe = Math.min(clipe, this.maxDuration);
1306
+ return Math.max(0, clipe);
1307
+ }
1308
+ /** Codifica o clipe em K pedaços paralelos (K processos ffmpeg) e remonta.
1309
+ Retorna false quando não dá pra paralelizar (o chamador usa o caminho comum). */
1310
+ async runEncodeAnimadoParalelo(input, output, quality, fps, crop, mediaInfo) {
1311
+ try {
1312
+ const clipe = this.duracaoClipe(mediaInfo);
1313
+ if (clipe <= 0.25)
1314
+ return false; // duração desconhecida/curta demais
1315
+ const total = Math.max(2, Math.round(clipe * fps));
1316
+ const k = this.parallelChunksFor(total);
1317
+ if (k <= 1)
1318
+ return false;
1319
+ // distribui o total de frames em K pedaços (contagem exata por pedaço)
1320
+ const contagens = [];
1321
+ const base = Math.floor(total / k);
1322
+ let resto = total % k;
1323
+ for (let i = 0; i < k; i++)
1324
+ contagens.push(base + (resto-- > 0 ? 1 : 0));
1325
+ const arquivos = [];
1326
+ const promessas = [];
1327
+ let t = inicio;
1328
+ for (let i = 0; i < k; i++) {
1329
+ const arq = output + '.p' + i;
1330
+ arquivos.push(arq);
1331
+ promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop));
1332
+ t += contagens[i] / fps;
1333
+ }
1334
+ try {
1335
+ await Promise.all(promessas);
1336
+ const montado = this.montarWebpAnimado(arquivos.map(a => fs.readFileSync(a)));
1337
+ fs.writeFileSync(output, montado);
1338
+ }
1339
+ finally {
1340
+ for (const a of arquivos) {
1341
+ try {
1342
+ fs.unlinkSync(a);
1343
+ }
1344
+ catch { /* ignore */ }
1345
+ }
1346
+ }
1347
+ return true;
1348
+ }
1349
+ catch (e) {
1350
+ // paralelo é otimização: qualquer falha cai no encode comum
1351
+ this.emit('st.warn', { message: 'encode paralelo falhou (' + ((e && e.message) || e) + ') — usando caminho comum' });
1352
+ return false;
1353
+ }
1354
+ }
1142
1355
  runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg) {
1143
1356
  return new Promise((resolve, reject) => {
1144
1357
  const q = clamp(Math.round(quality), 1, 100);
@@ -1171,7 +1384,7 @@ export class StickEngine extends EventEmitter {
1171
1384
  else {
1172
1385
  opts.push('-lossless', this.options.lossless ? '1' : '0');
1173
1386
  }
1174
- opts.push('-compression_level', '6', '-q:v', String(q), '-quality', String(q));
1387
+ opts.push('-compression_level', String(this.compressionLevelFor(isAnimated)), '-q:v', String(q), '-quality', String(q));
1175
1388
  cmd
1176
1389
  .on('error', (err) => reject(err))
1177
1390
  .on('end', () => resolve())
@@ -1186,11 +1399,20 @@ export class StickEngine extends EventEmitter {
1186
1399
  const lossless = this.options.lossless === true;
1187
1400
  let quality = this.options.quality != null
1188
1401
  ? 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);
1402
+ : (isAnimated ? 75 : 90);
1403
+ let fps = clamp(Math.round(Number(this.options.fps ?? 12) || 12), 1, 60);
1404
+ // orçamento de frames: clipe longo roda com fps menor p/ codificar
1405
+ // menos frames e caber no maxSize sem re-encode (~120 frames no total)
1406
+ const clipeDur = this.duracaoClipe(opts.mediaInfo);
1407
+ if (isAnimated && this.options.fps == null && clipeDur > 6)
1408
+ fps = Math.max(8, Math.round(120 / clipeDur));
1191
1409
  const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
1192
1410
  try {
1193
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1411
+ const paralelo = isAnimated && !watermarkPath
1412
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1413
+ : false;
1414
+ if (!paralelo)
1415
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1194
1416
  }
1195
1417
  catch (err) {
1196
1418
  throw new Error(`FFmpeg falhou ao gerar WebP ${isAnimated ? 'animado' : 'estático'}: ${errorMessage(err)}`);
@@ -1200,17 +1422,23 @@ export class StickEngine extends EventEmitter {
1200
1422
  }
1201
1423
  this.say('info', 'ENCODE', `#${index} webp ${isAnimated ? 'animado' : 'estático'} q=${quality}${isAnimated ? ` fps=${fps}` : ''} → ${fmtSize(fs.statSync(output).size)}`, `fit=${fitUsed}`);
1202
1424
  let attempts = 0;
1203
- while (!lossless && fs.existsSync(output) && fs.statSync(output).size > limit && attempts < 6) {
1425
+ const maxTentativas = isAnimated ? 3 : 4;
1426
+ while (!lossless && fs.existsSync(output) && fs.statSync(output).size > limit && attempts < maxTentativas) {
1204
1427
  attempts++;
1205
- this.say('info', 'ENCODE', `#${index} acima de ${fmtSize(limit)} — auto-shrink tentativa ${attempts}`);
1428
+ const excesso = fs.statSync(output).size / limit;
1429
+ this.say('info', 'ENCODE', `#${index} acima de ${fmtSize(limit)} — auto-shrink tentativa ${attempts} (${Math.round(excesso * 100)}%)`);
1206
1430
  if (isAnimated) {
1207
- quality = Math.max(20, quality - 15);
1208
- fps = Math.max(8, fps - 2);
1431
+ quality = Math.max(20, Math.round(Math.min(quality - 10, quality / Math.sqrt(excesso))));
1432
+ fps = Math.max(8, fps - (excesso > 1.5 ? 3 : 2));
1209
1433
  }
1210
1434
  else {
1211
- quality = Math.max(10, quality - 12);
1435
+ quality = Math.max(10, Math.round(Math.min(quality - 12, quality / Math.sqrt(excesso))));
1212
1436
  }
1213
- await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1437
+ const paraleloShrink = isAnimated && !watermarkPath
1438
+ ? await this.runEncodeAnimadoParalelo(input, output, quality, fps, crop, opts.mediaInfo)
1439
+ : false;
1440
+ if (!paraleloShrink)
1441
+ await this.runEncode(input, output, isAnimated, quality, fps, crop, watermarkPath, watermarkCfg);
1214
1442
  if (!fs.existsSync(output))
1215
1443
  throw new Error('FFmpeg falhou no auto-shrink');
1216
1444
  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.0",
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",