@boruto_vk7/stickengine 2.0.5 → 4.1.0

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