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