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