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