@boruto_vk7/stickengine 4.2.2 → 4.2.4

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,6 +1,6 @@
1
1
  # @boruto_vk7/stickengine
2
2
 
3
- > **4.2.2 — 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`.
3
+ > **4.2.4 — TURBO ADAPTATIVO**: WebP animado é codificado **em paralelo** e os pedaços são remontados byte a byte, sem recodificar a junção. O nº de processos **se adapta ao ambiente**: Termux → 2 (celular esquenta), Docker/VPS → o limite real do cgroup (não os núcleos do host), bare metal → os núcleos da máquina (teto 4); cada pedaço limita as threads de decode para não disputar a cota. Defaults de velocidade: `fps` 15→10, `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 de 2 vCPU agora sai em poucos segundos. Ajuste manual com `parallelChunks` ou `STICKENGINE_PARALLEL_CHUNKS` (`1` desliga o paralelismo).
4
4
 
5
5
 
6
6
  [![npm](https://img.shields.io/npm/v/@boruto_vk7/stickengine)](https://www.npmjs.com/package/@boruto_vk7/stickengine)
@@ -761,7 +761,7 @@ class StickEngine extends node_events_1.EventEmitter {
761
761
  async detectVideoCropByCropdetect(input, mediaInfo) {
762
762
  try {
763
763
  const args = ['-nostdin', '-hide_banner', '-i', input, '-an'];
764
- const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 3) : 0;
764
+ const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 2) : 0;
765
765
  if (sample > 0)
766
766
  args.push('-t', String(sample));
767
767
  args.push('-vf', `cropdetect=limit=${this.crop.tolerance}:round=2:reset=0`, '-f', 'null', '-');
@@ -1270,6 +1270,22 @@ class StickEngine extends node_events_1.EventEmitter {
1270
1270
  // 1 em animados é ~indistinguível visualmente e bem mais rápido.
1271
1271
  return isAnimated ? 1 : 4;
1272
1272
  }
1273
+ /** Rodando em Termux (Android)? */
1274
+ staticTermux() {
1275
+ return process.env.TERMUX_VERSION != null
1276
+ || /^\/data\/data\/com\.termux/.test(String(process.env.PREFIX || process.env.TERMUX_PREFIX || ''));
1277
+ }
1278
+ /** Cota de CPU real do ambiente: respeita o limite do cgroup (Docker/VPS);
1279
+ * em bare metal/Termux é o nº de núcleos do aparelho. */
1280
+ cotaCpu() {
1281
+ if (this.__cotaCpu == null) {
1282
+ let c = typeof node_os_1.default.availableParallelism === 'function'
1283
+ ? node_os_1.default.availableParallelism()
1284
+ : node_os_1.default.cpus().length;
1285
+ this.__cotaCpu = Math.max(1, Math.round(c));
1286
+ }
1287
+ return this.__cotaCpu;
1288
+ }
1273
1289
  parallelChunksFor(totalFrames) {
1274
1290
  const opt = this.options.parallelChunks;
1275
1291
  let k = 0;
@@ -1277,18 +1293,19 @@ class StickEngine extends node_events_1.EventEmitter {
1277
1293
  k = Math.round(Number(opt) || 0);
1278
1294
  }
1279
1295
  else {
1280
- // calibração por ambiente: Docker/VPS com cota de CPU (os.cpus() vê
1281
- // os núcleos do host e superestima em planos com cota pequena)
1296
+ // calibração manual por ambiente (VPS/Docker) tem prioridade
1282
1297
  const env = parseInt(String(process.env.STICKENGINE_PARALLEL_CHUNKS || ''), 10);
1283
1298
  if (Number.isFinite(env) && env >= 1) {
1284
1299
  k = env;
1285
1300
  }
1301
+ else if (this.staticTermux()) {
1302
+ k = 2; // Termux: celular esquenta e faz throttle — 2 é o ponto doce
1303
+ }
1286
1304
  else {
1287
- // availableParallelism respeita a cota de CPU do container
1288
- const cores = typeof node_os_1.default.availableParallelism === 'function'
1289
- ? node_os_1.default.availableParallelism()
1290
- : node_os_1.default.cpus().length;
1291
- k = Math.min(4, Math.max(1, Math.ceil(cores * 0.75)));
1305
+ // Docker/VPS: usa o LIMITE do container (cota do cgroup, não os
1306
+ // núcleos do host que os.cpus() superestima); bare metal cai no
1307
+ // nº real de núcleos
1308
+ k = Math.min(4, this.cotaCpu());
1292
1309
  }
1293
1310
  }
1294
1311
  k = Math.max(1, Math.min(8, k));
@@ -1300,12 +1317,15 @@ class StickEngine extends node_events_1.EventEmitter {
1300
1317
  return Math.min(3, k);
1301
1318
  return k;
1302
1319
  }
1303
- runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop) {
1320
+ runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop, threads) {
1304
1321
  return new Promise((resolve, reject) => {
1305
1322
  const q = (0, util_js_1.clamp)(Math.round(quality), 1, 100);
1306
1323
  const opts = ['-nostdin', '-hide_banner'];
1307
1324
  if (ini > 0)
1308
1325
  opts.push('-ss', ini.toFixed(3));
1326
+ // limita as threads de DECODE de cada pedaço: sem isso cada ffmpeg
1327
+ // cria threads p/ todos os núcleos do host e disputam a cota do container
1328
+ opts.push('-threads', String(Math.max(1, Math.round(threads || 1))));
1309
1329
  opts.push('-i', input);
1310
1330
  const vf = this.buildAnimatedFilters(crop, String(this.options.fit || 'cover'), fps);
1311
1331
  opts.push('-vf', vf);
@@ -1348,6 +1368,8 @@ class StickEngine extends node_events_1.EventEmitter {
1348
1368
  let resto = total % k;
1349
1369
  for (let i = 0; i < k; i++)
1350
1370
  contagens.push(base + (resto-- > 0 ? 1 : 0));
1371
+ // threads de decode por pedaço: a soma dos pedaços ≈ a cota do container
1372
+ const th = Math.max(1, Math.min(4, Math.ceil(this.cotaCpu() / k)));
1351
1373
  const arquivos = [];
1352
1374
  const promessas = [];
1353
1375
  let t = this.startTime > 0 ? this.startTime : 0;
@@ -1355,7 +1377,7 @@ class StickEngine extends node_events_1.EventEmitter {
1355
1377
  // extensão .webp obrigatória: o muxer do ffmpeg é escolhido pela extensão
1356
1378
  const arq = output.replace(/\.webp$/i, '') + '.p' + i + '.webp';
1357
1379
  arquivos.push(arq);
1358
- promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop));
1380
+ promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop, th));
1359
1381
  t += contagens[i] / fps;
1360
1382
  }
1361
1383
  try {
@@ -1428,12 +1450,12 @@ class StickEngine extends node_events_1.EventEmitter {
1428
1450
  let quality = this.options.quality != null
1429
1451
  ? (0, util_js_1.clamp)(Number(this.options.quality) || 80, 1, 100)
1430
1452
  : (isAnimated ? 75 : 90);
1431
- let fps = (0, util_js_1.clamp)(Math.round(Number(this.options.fps ?? 12) || 12), 1, 60);
1453
+ let fps = (0, util_js_1.clamp)(Math.round(Number(this.options.fps ?? 10) || 10), 1, 60);
1432
1454
  // orçamento de frames: clipe longo roda com fps menor p/ codificar
1433
- // menos frames e caber no maxSize sem re-encode (~120 frames no total)
1455
+ // menos frames e caber no maxSize sem re-encode (~100 frames no total)
1434
1456
  const clipeDur = this.duracaoClipe(opts.mediaInfo);
1435
- if (isAnimated && this.options.fps == null && clipeDur > 6)
1436
- fps = Math.max(8, Math.round(120 / clipeDur));
1457
+ if (isAnimated && this.options.fps == null && clipeDur > 10)
1458
+ fps = Math.max(8, Math.round(100 / clipeDur));
1437
1459
  const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
1438
1460
  try {
1439
1461
  const paralelo = isAnimated && !watermarkPath
@@ -746,7 +746,7 @@ export class StickEngine extends EventEmitter {
746
746
  async detectVideoCropByCropdetect(input, mediaInfo) {
747
747
  try {
748
748
  const args = ['-nostdin', '-hide_banner', '-i', input, '-an'];
749
- const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 3) : 0;
749
+ const sample = mediaInfo.duration > 0 ? Math.min(mediaInfo.duration, 2) : 0;
750
750
  if (sample > 0)
751
751
  args.push('-t', String(sample));
752
752
  args.push('-vf', `cropdetect=limit=${this.crop.tolerance}:round=2:reset=0`, '-f', 'null', '-');
@@ -1255,6 +1255,22 @@ export class StickEngine extends EventEmitter {
1255
1255
  // 1 em animados é ~indistinguível visualmente e bem mais rápido.
1256
1256
  return isAnimated ? 1 : 4;
1257
1257
  }
1258
+ /** Rodando em Termux (Android)? */
1259
+ staticTermux() {
1260
+ return process.env.TERMUX_VERSION != null
1261
+ || /^\/data\/data\/com\.termux/.test(String(process.env.PREFIX || process.env.TERMUX_PREFIX || ''));
1262
+ }
1263
+ /** Cota de CPU real do ambiente: respeita o limite do cgroup (Docker/VPS);
1264
+ * em bare metal/Termux é o nº de núcleos do aparelho. */
1265
+ cotaCpu() {
1266
+ if (this.__cotaCpu == null) {
1267
+ let c = typeof os.availableParallelism === 'function'
1268
+ ? os.availableParallelism()
1269
+ : os.cpus().length;
1270
+ this.__cotaCpu = Math.max(1, Math.round(c));
1271
+ }
1272
+ return this.__cotaCpu;
1273
+ }
1258
1274
  parallelChunksFor(totalFrames) {
1259
1275
  const opt = this.options.parallelChunks;
1260
1276
  let k = 0;
@@ -1262,18 +1278,19 @@ export class StickEngine extends EventEmitter {
1262
1278
  k = Math.round(Number(opt) || 0);
1263
1279
  }
1264
1280
  else {
1265
- // calibração por ambiente: Docker/VPS com cota de CPU (os.cpus() vê
1266
- // os núcleos do host e superestima em planos com cota pequena)
1281
+ // calibração manual por ambiente (VPS/Docker) tem prioridade
1267
1282
  const env = parseInt(String(process.env.STICKENGINE_PARALLEL_CHUNKS || ''), 10);
1268
1283
  if (Number.isFinite(env) && env >= 1) {
1269
1284
  k = env;
1270
1285
  }
1286
+ else if (this.staticTermux()) {
1287
+ k = 2; // Termux: celular esquenta e faz throttle — 2 é o ponto doce
1288
+ }
1271
1289
  else {
1272
- // availableParallelism respeita a cota de CPU do container
1273
- const cores = typeof os.availableParallelism === 'function'
1274
- ? os.availableParallelism()
1275
- : os.cpus().length;
1276
- k = Math.min(4, Math.max(1, Math.ceil(cores * 0.75)));
1290
+ // Docker/VPS: usa o LIMITE do container (cota do cgroup, não os
1291
+ // núcleos do host que os.cpus() superestima); bare metal cai no
1292
+ // nº real de núcleos
1293
+ k = Math.min(4, this.cotaCpu());
1277
1294
  }
1278
1295
  }
1279
1296
  k = Math.max(1, Math.min(8, k));
@@ -1285,12 +1302,15 @@ export class StickEngine extends EventEmitter {
1285
1302
  return Math.min(3, k);
1286
1303
  return k;
1287
1304
  }
1288
- runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop) {
1305
+ runEncodeChunk(input, output, ini, frames, isAnimated, quality, fps, crop, threads) {
1289
1306
  return new Promise((resolve, reject) => {
1290
1307
  const q = clamp(Math.round(quality), 1, 100);
1291
1308
  const opts = ['-nostdin', '-hide_banner'];
1292
1309
  if (ini > 0)
1293
1310
  opts.push('-ss', ini.toFixed(3));
1311
+ // limita as threads de DECODE de cada pedaço: sem isso cada ffmpeg
1312
+ // cria threads p/ todos os núcleos do host e disputam a cota do container
1313
+ opts.push('-threads', String(Math.max(1, Math.round(threads || 1))));
1294
1314
  opts.push('-i', input);
1295
1315
  const vf = this.buildAnimatedFilters(crop, String(this.options.fit || 'cover'), fps);
1296
1316
  opts.push('-vf', vf);
@@ -1333,6 +1353,8 @@ export class StickEngine extends EventEmitter {
1333
1353
  let resto = total % k;
1334
1354
  for (let i = 0; i < k; i++)
1335
1355
  contagens.push(base + (resto-- > 0 ? 1 : 0));
1356
+ // threads de decode por pedaço: a soma dos pedaços ≈ a cota do container
1357
+ const th = Math.max(1, Math.min(4, Math.ceil(this.cotaCpu() / k)));
1336
1358
  const arquivos = [];
1337
1359
  const promessas = [];
1338
1360
  let t = this.startTime > 0 ? this.startTime : 0;
@@ -1340,7 +1362,7 @@ export class StickEngine extends EventEmitter {
1340
1362
  // extensão .webp obrigatória: o muxer do ffmpeg é escolhido pela extensão
1341
1363
  const arq = output.replace(/\.webp$/i, '') + '.p' + i + '.webp';
1342
1364
  arquivos.push(arq);
1343
- promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop));
1365
+ promessas.push(this.runEncodeChunk(input, arq, t, contagens[i], true, quality, fps, crop, th));
1344
1366
  t += contagens[i] / fps;
1345
1367
  }
1346
1368
  try {
@@ -1413,12 +1435,12 @@ export class StickEngine extends EventEmitter {
1413
1435
  let quality = this.options.quality != null
1414
1436
  ? clamp(Number(this.options.quality) || 80, 1, 100)
1415
1437
  : (isAnimated ? 75 : 90);
1416
- let fps = clamp(Math.round(Number(this.options.fps ?? 12) || 12), 1, 60);
1438
+ let fps = clamp(Math.round(Number(this.options.fps ?? 10) || 10), 1, 60);
1417
1439
  // orçamento de frames: clipe longo roda com fps menor p/ codificar
1418
- // menos frames e caber no maxSize sem re-encode (~120 frames no total)
1440
+ // menos frames e caber no maxSize sem re-encode (~100 frames no total)
1419
1441
  const clipeDur = this.duracaoClipe(opts.mediaInfo);
1420
- if (isAnimated && this.options.fps == null && clipeDur > 6)
1421
- fps = Math.max(8, Math.round(120 / clipeDur));
1442
+ if (isAnimated && this.options.fps == null && clipeDur > 10)
1443
+ fps = Math.max(8, Math.round(100 / clipeDur));
1422
1444
  const limit = isAnimated ? this.maxSize : this.maxSizeStatic;
1423
1445
  try {
1424
1446
  const paralelo = isAnimated && !watermarkPath
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boruto_vk7/stickengine",
3
- "version": "4.2.2",
3
+ "version": "4.2.4",
4
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",