swf2js 0.0.0-stage → 0.1.1
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-GPL +680 -0
- package/README.md +208 -2
- package/package.json +24 -4
- package/src/cli.js +272 -0
- package/src/decoder/button-decoder.js +136 -0
- package/src/decoder/shape-decoder.js +786 -0
- package/src/decoder/symbol-table.js +36 -0
- package/src/decoder/tag-decoder.js +1190 -0
- package/src/decoder/tag-types.js +258 -0
- package/src/emitter/asset-encoder.js +708 -0
- package/src/emitter/bundle-emitter.js +596 -0
- package/src/emitter/embedded-swf.js +246 -0
- package/src/emitter/font-encoder.js +365 -0
- package/src/emitter/timeline-data-codec.js +58 -0
- package/src/model/swf-document.js +59 -0
- package/src/model/transpile-result.js +32 -0
- package/src/parser/bit-reader.js +237 -0
- package/src/parser/decompressor.js +91 -0
- package/src/parser/swf-parser.js +164 -0
- package/src/pretty-printer/pretty-printer.js +137 -0
- package/src/runtime/avm1-runtime.js +4907 -0
- package/src/runtime/avm2-runtime.js +1591 -0
- package/src/runtime/embedded-movie-runtime.js +208 -0
- package/src/runtime/index.js +17 -0
- package/src/runtime/movie-runtime.js +306 -0
- package/src/runtime/swflib.js +14050 -0
- package/src/transpiler/actionscript.js +390 -0
- package/src/transpiler/avm1/avm1-ir.js +205 -0
- package/src/transpiler/avm1/avm1-opcodes.js +149 -0
- package/src/transpiler/avm1/avm1-rewrite.js +291 -0
- package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
- package/src/transpiler/avm2/abc-reader.js +416 -0
- package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
- package/src/transpiler/cfg-structurer.js +876 -0
- package/src/transpiler/timeline/display-list.js +643 -0
- package/src/transpiler/timeline/timeline-codegen.js +6354 -0
- package/src/util/diagnostics.js +50 -0
- package/src/util/logger.js +40 -0
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Asset encoding helpers — JPEG cleanup, PNG from RGBA, sound dumps,
|
|
3
|
+
* base64 / data-URI helpers for the Bundle_Emitter.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { deflateSync, inflateSync } from 'zlib';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {Uint8Array} data
|
|
11
|
+
* @returns {string}
|
|
12
|
+
*/
|
|
13
|
+
export function toBase64(data) {
|
|
14
|
+
return Buffer.from(data).toString('base64');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {string} mimeType
|
|
19
|
+
* @param {Uint8Array} data
|
|
20
|
+
* @returns {string}
|
|
21
|
+
*/
|
|
22
|
+
export function toDataUri(mimeType, data) {
|
|
23
|
+
return `data:${mimeType};base64,${toBase64(data)}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Strip Flash's erroneous FFD9FFD8 (EOI+SOI) marker pairs and normalise SOI/EOI.
|
|
28
|
+
* @param {Uint8Array} data
|
|
29
|
+
* @returns {Uint8Array}
|
|
30
|
+
*/
|
|
31
|
+
export function fixJpegData(data) {
|
|
32
|
+
if (!data || data.length === 0) return new Uint8Array(0);
|
|
33
|
+
|
|
34
|
+
// Remove FFD9 FFD8 sequences that Flash inserts between tables and image data
|
|
35
|
+
const cleaned = [];
|
|
36
|
+
for (let i = 0; i < data.length; i++) {
|
|
37
|
+
if (
|
|
38
|
+
i + 3 < data.length &&
|
|
39
|
+
data[i] === 0xff && data[i + 1] === 0xd9 &&
|
|
40
|
+
data[i + 2] === 0xff && data[i + 3] === 0xd8
|
|
41
|
+
) {
|
|
42
|
+
i += 3; // with for-loop i++, skips all 4 bytes
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
cleaned.push(data[i]);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let out = Uint8Array.from(cleaned);
|
|
49
|
+
|
|
50
|
+
// Drop a leading lone EOI
|
|
51
|
+
if (out.length >= 2 && out[0] === 0xff && out[1] === 0xd9) {
|
|
52
|
+
out = out.slice(2);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Ensure SOI
|
|
56
|
+
if (out.length < 2 || out[0] !== 0xff || out[1] !== 0xd8) {
|
|
57
|
+
const withSoi = new Uint8Array(out.length + 2);
|
|
58
|
+
withSoi[0] = 0xff;
|
|
59
|
+
withSoi[1] = 0xd8;
|
|
60
|
+
withSoi.set(out, 2);
|
|
61
|
+
out = withSoi;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Ensure EOI
|
|
65
|
+
if (out.length < 2 || out[out.length - 2] !== 0xff || out[out.length - 1] !== 0xd9) {
|
|
66
|
+
const withEoi = new Uint8Array(out.length + 2);
|
|
67
|
+
withEoi.set(out, 0);
|
|
68
|
+
withEoi[withEoi.length - 2] = 0xff;
|
|
69
|
+
withEoi[withEoi.length - 1] = 0xd9;
|
|
70
|
+
out = withEoi;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Join JPEGTables + DefineBits image data into a standalone JPEG.
|
|
78
|
+
* @param {Uint8Array|null|undefined} jpegTables
|
|
79
|
+
* @param {Uint8Array} imageData
|
|
80
|
+
* @returns {Uint8Array}
|
|
81
|
+
*/
|
|
82
|
+
export function buildJpegFromTables(jpegTables, imageData) {
|
|
83
|
+
if (!jpegTables || jpegTables.length === 0) {
|
|
84
|
+
return fixJpegData(imageData);
|
|
85
|
+
}
|
|
86
|
+
const combined = new Uint8Array(jpegTables.length + imageData.length);
|
|
87
|
+
combined.set(jpegTables, 0);
|
|
88
|
+
combined.set(imageData, jpegTables.length);
|
|
89
|
+
return fixJpegData(combined);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Encode an RGBA buffer as a PNG file (zlib-compressed IDAT).
|
|
94
|
+
* @param {Uint8Array} rgba - width*height*4 bytes
|
|
95
|
+
* @param {number} width
|
|
96
|
+
* @param {number} height
|
|
97
|
+
* @returns {Uint8Array}
|
|
98
|
+
*/
|
|
99
|
+
export function encodePng(rgba, width, height) {
|
|
100
|
+
const rowSize = 1 + width * 4; // filter byte + RGBA
|
|
101
|
+
const raw = new Uint8Array(rowSize * height);
|
|
102
|
+
for (let y = 0; y < height; y++) {
|
|
103
|
+
const rowStart = y * rowSize;
|
|
104
|
+
raw[rowStart] = 0; // none filter
|
|
105
|
+
const src = y * width * 4;
|
|
106
|
+
raw.set(rgba.subarray(src, src + width * 4), rowStart + 1);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const compressed = deflateSync(Buffer.from(raw));
|
|
110
|
+
|
|
111
|
+
const signature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
|
|
112
|
+
const ihdr = new Uint8Array(13);
|
|
113
|
+
const ihdrView = new DataView(ihdr.buffer);
|
|
114
|
+
ihdrView.setUint32(0, width);
|
|
115
|
+
ihdrView.setUint32(4, height);
|
|
116
|
+
ihdr[8] = 8; // bit depth
|
|
117
|
+
ihdr[9] = 6; // RGBA
|
|
118
|
+
ihdr[10] = 0; // compression
|
|
119
|
+
ihdr[11] = 0; // filter
|
|
120
|
+
ihdr[12] = 0; // interlace
|
|
121
|
+
|
|
122
|
+
const chunks = [
|
|
123
|
+
signature,
|
|
124
|
+
pngChunk('IHDR', ihdr),
|
|
125
|
+
pngChunk('IDAT', new Uint8Array(compressed)),
|
|
126
|
+
pngChunk('IEND', new Uint8Array(0)),
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
let total = 0;
|
|
130
|
+
for (const c of chunks) total += c.length;
|
|
131
|
+
const out = new Uint8Array(total);
|
|
132
|
+
let offset = 0;
|
|
133
|
+
for (const c of chunks) {
|
|
134
|
+
out.set(c, offset);
|
|
135
|
+
offset += c.length;
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @param {string} type - 4-char chunk type
|
|
142
|
+
* @param {Uint8Array} data
|
|
143
|
+
* @returns {Uint8Array}
|
|
144
|
+
*/
|
|
145
|
+
function pngChunk(type, data) {
|
|
146
|
+
const out = new Uint8Array(12 + data.length);
|
|
147
|
+
const view = new DataView(out.buffer);
|
|
148
|
+
view.setUint32(0, data.length);
|
|
149
|
+
out[4] = type.charCodeAt(0);
|
|
150
|
+
out[5] = type.charCodeAt(1);
|
|
151
|
+
out[6] = type.charCodeAt(2);
|
|
152
|
+
out[7] = type.charCodeAt(3);
|
|
153
|
+
out.set(data, 8);
|
|
154
|
+
const crc = crc32(out.subarray(4, 8 + data.length));
|
|
155
|
+
view.setUint32(8 + data.length, crc >>> 0);
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** @type {Uint32Array|null} */
|
|
160
|
+
let crcTable = null;
|
|
161
|
+
|
|
162
|
+
function makeCrcTable() {
|
|
163
|
+
const table = new Uint32Array(256);
|
|
164
|
+
for (let n = 0; n < 256; n++) {
|
|
165
|
+
let c = n;
|
|
166
|
+
for (let k = 0; k < 8; k++) {
|
|
167
|
+
c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
|
|
168
|
+
}
|
|
169
|
+
table[n] = c >>> 0;
|
|
170
|
+
}
|
|
171
|
+
return table;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* @param {Uint8Array} buf
|
|
176
|
+
* @returns {number}
|
|
177
|
+
*/
|
|
178
|
+
function crc32(buf) {
|
|
179
|
+
if (!crcTable) crcTable = makeCrcTable();
|
|
180
|
+
let c = 0xffffffff;
|
|
181
|
+
for (let i = 0; i < buf.length; i++) {
|
|
182
|
+
c = crcTable[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
|
183
|
+
}
|
|
184
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Wrap raw PCM samples in a minimal WAV (RIFF) header.
|
|
189
|
+
* @param {Uint8Array} pcm
|
|
190
|
+
* @param {number} sampleRate
|
|
191
|
+
* @param {boolean} is16bit
|
|
192
|
+
* @param {boolean} isStereo
|
|
193
|
+
* @returns {Uint8Array}
|
|
194
|
+
*/
|
|
195
|
+
export function wrapWav(pcm, sampleRate, is16bit, isStereo) {
|
|
196
|
+
const channels = isStereo ? 2 : 1;
|
|
197
|
+
const bitsPerSample = is16bit ? 16 : 8;
|
|
198
|
+
const byteRate = sampleRate * channels * (bitsPerSample / 8);
|
|
199
|
+
const blockAlign = channels * (bitsPerSample / 8);
|
|
200
|
+
const dataSize = pcm.length;
|
|
201
|
+
const padding = dataSize & 1;
|
|
202
|
+
const out = new Uint8Array(44 + dataSize + padding);
|
|
203
|
+
const view = new DataView(out.buffer);
|
|
204
|
+
const writeStr = (offset, s) => {
|
|
205
|
+
for (let i = 0; i < s.length; i++) out[offset + i] = s.charCodeAt(i);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
writeStr(0, 'RIFF');
|
|
209
|
+
view.setUint32(4, 36 + dataSize + padding, true);
|
|
210
|
+
writeStr(8, 'WAVE');
|
|
211
|
+
writeStr(12, 'fmt ');
|
|
212
|
+
view.setUint32(16, 16, true); // PCM chunk size
|
|
213
|
+
view.setUint16(20, 1, true); // PCM format
|
|
214
|
+
view.setUint16(22, channels, true);
|
|
215
|
+
view.setUint32(24, sampleRate, true);
|
|
216
|
+
view.setUint32(28, byteRate, true);
|
|
217
|
+
view.setUint16(32, blockAlign, true);
|
|
218
|
+
view.setUint16(34, bitsPerSample, true);
|
|
219
|
+
writeStr(36, 'data');
|
|
220
|
+
view.setUint32(40, dataSize, true);
|
|
221
|
+
out.set(pcm, 44);
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const SWF_ADPCM_STEP_TABLE = [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31,
|
|
226
|
+
34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143,
|
|
227
|
+
157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658,
|
|
228
|
+
724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024,
|
|
229
|
+
3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
|
|
230
|
+
15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767];
|
|
231
|
+
const SWF_ADPCM_INDEX_TABLES = [
|
|
232
|
+
[-1, 2], [-1, -1, 2, 4], [-1, -1, -1, -1, 2, 4, 6, 8],
|
|
233
|
+
[-1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16],
|
|
234
|
+
];
|
|
235
|
+
|
|
236
|
+
/** Decode one ADPCMSOUNDDATA record, optionally stopping at its declared frame count. */
|
|
237
|
+
export function decodeSwfAdpcmStream(data, stereo = false, sampleLimit) {
|
|
238
|
+
const bytes = data || new Uint8Array(0);
|
|
239
|
+
const bitLength = bytes.length * 8;
|
|
240
|
+
let bit = 0;
|
|
241
|
+
function readBits(width) {
|
|
242
|
+
let value = 0;
|
|
243
|
+
for (let i = 0; i < width; i++, bit++) value = (value << 1) | ((bytes[Math.floor(bit / 8)] >> (7 - (bit & 7))) & 1);
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
if (!bytes.length) return { pcm: new Uint8Array(0), sampleCount: 0 };
|
|
247
|
+
|
|
248
|
+
// The code size applies to the entire record, not to individual packets.
|
|
249
|
+
const codeSize = readBits(2);
|
|
250
|
+
const codeBits = codeSize + 2;
|
|
251
|
+
const signMask = 1 << (codeBits - 1);
|
|
252
|
+
const magnitudeMask = signMask - 1;
|
|
253
|
+
const indexTable = SWF_ADPCM_INDEX_TABLES[codeSize];
|
|
254
|
+
const channels = stereo ? 2 : 1;
|
|
255
|
+
const headerBits = channels * 22;
|
|
256
|
+
const frameBits = channels * codeBits;
|
|
257
|
+
const availableFrames = Math.floor((bitLength - bit) / frameBits);
|
|
258
|
+
const maxFrames = Number.isFinite(sampleLimit)
|
|
259
|
+
? Math.min(availableFrames, Math.max(0, Math.trunc(sampleLimit)))
|
|
260
|
+
: availableFrames;
|
|
261
|
+
const pcm = new Uint8Array(maxFrames * channels * 2);
|
|
262
|
+
const view = new DataView(pcm.buffer);
|
|
263
|
+
const predictors = new Int16Array(channels);
|
|
264
|
+
const indexes = new Uint8Array(channels);
|
|
265
|
+
let sampleCount = 0;
|
|
266
|
+
|
|
267
|
+
while (sampleCount < maxFrames && bit + headerBits <= bitLength) {
|
|
268
|
+
for (let channel = 0; channel < channels; channel++) {
|
|
269
|
+
predictors[channel] = readBits(16);
|
|
270
|
+
indexes[channel] = readBits(6);
|
|
271
|
+
view.setInt16((sampleCount * channels + channel) * 2, predictors[channel], true);
|
|
272
|
+
}
|
|
273
|
+
sampleCount++;
|
|
274
|
+
|
|
275
|
+
for (let frame = 1; frame < 4096 && sampleCount < maxFrames && bit + frameBits <= bitLength; frame++) {
|
|
276
|
+
for (let channel = 0; channel < channels; channel++) {
|
|
277
|
+
const code = readBits(codeBits);
|
|
278
|
+
const magnitude = code & magnitudeMask;
|
|
279
|
+
const step = SWF_ADPCM_STEP_TABLE[indexes[channel]];
|
|
280
|
+
let diff = step >> (codeBits - 1);
|
|
281
|
+
for (let magnitudeBit = 0; magnitudeBit < codeBits - 1; magnitudeBit++) {
|
|
282
|
+
if (magnitude & (1 << magnitudeBit)) diff += step >> (codeBits - 2 - magnitudeBit);
|
|
283
|
+
}
|
|
284
|
+
predictors[channel] = Math.max(-32768, Math.min(32767,
|
|
285
|
+
predictors[channel] + ((code & signMask) ? -diff : diff)));
|
|
286
|
+
indexes[channel] = Math.max(0, Math.min(88, indexes[channel] + indexTable[magnitude]));
|
|
287
|
+
view.setInt16((sampleCount * channels + channel) * 2, predictors[channel], true);
|
|
288
|
+
}
|
|
289
|
+
sampleCount++;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const byteCount = sampleCount * channels * 2;
|
|
293
|
+
return { pcm: byteCount < pcm.length ? pcm.slice(0, byteCount) : pcm, sampleCount };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Encode a decoded Bitmap character to a file-ready buffer.
|
|
298
|
+
* @param {object} bitmap - BitmapCharacter
|
|
299
|
+
* @param {Uint8Array|null} [jpegTables]
|
|
300
|
+
* @param {boolean} [includeMaskCoverage]
|
|
301
|
+
* @returns {{ mimeType: string, ext: string, data: Uint8Array, alphaMimeType?: string, alphaExt?: string, alphaData?: Uint8Array, width?: number, height?: number, maskCoverage?: string }}
|
|
302
|
+
*/
|
|
303
|
+
export function encodeBitmap(bitmap, jpegTables = null, includeMaskCoverage = false) {
|
|
304
|
+
const fmt = bitmap.format;
|
|
305
|
+
|
|
306
|
+
if (fmt === 'lossless1' || fmt === 'lossless2') {
|
|
307
|
+
const width = bitmap.width || 0;
|
|
308
|
+
const height = bitmap.height || 0;
|
|
309
|
+
const data = encodePng(bitmap.rawData || new Uint8Array(0), width, height);
|
|
310
|
+
const maskCoverage = includeMaskCoverage && fmt === 'lossless2'
|
|
311
|
+
? encodeBitmapMaskCoverage(bitmap.rawData, width * height, 3, 4) : undefined;
|
|
312
|
+
return { mimeType: 'image/png', ext: 'png', data, maskCoverage };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const bytes = bitmap.rawData;
|
|
316
|
+
if ((fmt === 'jpeg2' || fmt === 'jpeg3' || fmt === 'jpeg4') && bytes?.length >= 10) {
|
|
317
|
+
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
318
|
+
// JPEG2–4 can contain PNG or GIF89a data with their own transparency.
|
|
319
|
+
if (bytes.length >= 24 && header.getUint32(0) === 0x89504e47 && header.getUint32(4) === 0x0d0a1a0a) {
|
|
320
|
+
return { mimeType: 'image/png', ext: 'png', data: bytes,
|
|
321
|
+
width: header.getUint32(16), height: header.getUint32(20) };
|
|
322
|
+
}
|
|
323
|
+
if (header.getUint32(0) === 0x47494638 && header.getUint16(4) === 0x3961) {
|
|
324
|
+
return { mimeType: 'image/gif', ext: 'gif', data: bytes,
|
|
325
|
+
width: header.getUint16(6, true), height: header.getUint16(8, true) };
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
let jpegBytes;
|
|
330
|
+
if (fmt === 'jpeg1') {
|
|
331
|
+
jpegBytes = buildJpegFromTables(jpegTables, bitmap.rawData || new Uint8Array(0));
|
|
332
|
+
} else {
|
|
333
|
+
jpegBytes = fixJpegData(bitmap.rawData || new Uint8Array(0));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if ((fmt === 'jpeg3' || fmt === 'jpeg4') && bitmap.alphaData?.length) {
|
|
337
|
+
const { width, height } = jpegDimensions(jpegBytes);
|
|
338
|
+
if (!width || !height) throw new Error('JPEG3/4 alpha image has no JPEG dimensions');
|
|
339
|
+
const alpha = new Uint8Array(inflateSync(Buffer.from(bitmap.alphaData)));
|
|
340
|
+
if (alpha.length < width * height) {
|
|
341
|
+
throw new Error(`JPEG3/4 alpha plane is truncated (${alpha.length} < ${width * height})`);
|
|
342
|
+
}
|
|
343
|
+
const rgba = new Uint8Array(width * height * 4);
|
|
344
|
+
for (let i = 0; i < width * height; i++) {
|
|
345
|
+
const p = i * 4;
|
|
346
|
+
rgba[p] = rgba[p + 1] = rgba[p + 2] = 255;
|
|
347
|
+
rgba[p + 3] = alpha[i];
|
|
348
|
+
}
|
|
349
|
+
return {
|
|
350
|
+
mimeType: 'image/jpeg', ext: 'jpg', data: jpegBytes,
|
|
351
|
+
alphaMimeType: 'image/png', alphaExt: 'png', alphaData: encodePng(rgba, width, height),
|
|
352
|
+
width, height,
|
|
353
|
+
maskCoverage: includeMaskCoverage ? encodeBitmapMaskCoverage(alpha, width * height, 0, 1) : undefined,
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return { mimeType: 'image/jpeg', ext: 'jpg', data: jpegBytes };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function encodeBitmapMaskCoverage(alpha, pixels, offset, stride) {
|
|
361
|
+
if (!alpha || !pixels || alpha.length <= offset + (pixels - 1) * stride) return undefined;
|
|
362
|
+
const first = alpha[offset] > 0;
|
|
363
|
+
let index = 1;
|
|
364
|
+
while (index < pixels && (alpha[offset + index * stride] > 0) === first) index++;
|
|
365
|
+
// Missing metadata means ordinary rectangular coverage. An empty bitset
|
|
366
|
+
// represents an explicitly transparent image without allocating anything.
|
|
367
|
+
if (index === pixels) return first ? undefined : '';
|
|
368
|
+
if (pixels > 4 * 1024 * 1024) return undefined;
|
|
369
|
+
const bits = Buffer.alloc(Math.ceil(pixels / 8));
|
|
370
|
+
for (let i = 0; i < pixels; i++) {
|
|
371
|
+
if (alpha[offset + i * stride] > 0) bits[i >> 3] |= 1 << (i & 7);
|
|
372
|
+
}
|
|
373
|
+
return bits.toString('base64');
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Read dimensions from a JPEG Start Of Frame segment. */
|
|
377
|
+
function jpegDimensions(data) {
|
|
378
|
+
let i = 2;
|
|
379
|
+
while (i + 3 < data.length) {
|
|
380
|
+
if (data[i] !== 0xff) { i++; continue; }
|
|
381
|
+
while (data[i] === 0xff) i++;
|
|
382
|
+
const marker = data[i++];
|
|
383
|
+
if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7) || marker === 0x01) continue;
|
|
384
|
+
if (i + 1 >= data.length) break;
|
|
385
|
+
const length = (data[i] << 8) | data[i + 1];
|
|
386
|
+
if (length < 2 || i + length > data.length) break;
|
|
387
|
+
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) {
|
|
388
|
+
if (length < 7) break;
|
|
389
|
+
return { height: (data[i + 3] << 8) | data[i + 4], width: (data[i + 5] << 8) | data[i + 6] };
|
|
390
|
+
}
|
|
391
|
+
i += length;
|
|
392
|
+
}
|
|
393
|
+
return { width: 0, height: 0 };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function isNellymoser(codec) { return codec === 4 || codec === 5 || codec === 6; }
|
|
397
|
+
|
|
398
|
+
function compressedSampleRate(codec, rate) {
|
|
399
|
+
if (codec === 5) return 8000;
|
|
400
|
+
return codec === 4 || codec === 11 ? 16000 : rate;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function speexFrames(data, aligned) {
|
|
404
|
+
// Mode lengths include the corresponding narrowband/wideband header bits.
|
|
405
|
+
const narrowBits = [5, 43, 119, 160, 220, 300, 364, 492, 79];
|
|
406
|
+
const wideBits = [4, 36, 112, 192, 352];
|
|
407
|
+
const length = data.length * 8;
|
|
408
|
+
function read(at, bits) {
|
|
409
|
+
let value = 0;
|
|
410
|
+
for (let i = at; i < at + bits; i++) value = (value << 1) | ((data[i >> 3] >> (7 - (i & 7))) & 1);
|
|
411
|
+
return value;
|
|
412
|
+
}
|
|
413
|
+
function padding(at, end) {
|
|
414
|
+
if (at === end) return true;
|
|
415
|
+
if (read(at, 1)) return false;
|
|
416
|
+
const width = end - at - 1;
|
|
417
|
+
const value = read(at + 1, width);
|
|
418
|
+
return value === 0 || value === (1 << width) - 1;
|
|
419
|
+
}
|
|
420
|
+
const frames = [];
|
|
421
|
+
let start = 0;
|
|
422
|
+
while (start < length) {
|
|
423
|
+
if (length - start < 8 && padding(start, length)) return frames;
|
|
424
|
+
const base = narrowBits[read(start, 5)];
|
|
425
|
+
if (!base) return null;
|
|
426
|
+
let end = start + base;
|
|
427
|
+
if (end < length && read(end, 1)) {
|
|
428
|
+
if (end + 4 > length) return null;
|
|
429
|
+
const extension = wideBits[read(end + 1, 3)];
|
|
430
|
+
if (!extension) return null;
|
|
431
|
+
end += extension;
|
|
432
|
+
}
|
|
433
|
+
if (end > length) return null;
|
|
434
|
+
const bytes = Math.ceil((end - start) / 8);
|
|
435
|
+
const frame = Buffer.alloc(bytes);
|
|
436
|
+
for (let bit = 0; bit < end - start; bit++) {
|
|
437
|
+
frame[bit >> 3] |= read(start + bit, 1) << (7 - (bit & 7));
|
|
438
|
+
}
|
|
439
|
+
// A zero followed by ones terminates the packet without adding a frame.
|
|
440
|
+
const unused = bytes * 8 - (end - start);
|
|
441
|
+
if (unused) frame[bytes - 1] |= (1 << (unused - 1)) - 1;
|
|
442
|
+
frames.push(frame);
|
|
443
|
+
const next = aligned ? Math.ceil(end / 8) * 8 : end;
|
|
444
|
+
if (aligned && !padding(end, next)) return null;
|
|
445
|
+
start = next;
|
|
446
|
+
}
|
|
447
|
+
return frames;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function splitCompressedPackets(data, codec) {
|
|
451
|
+
if (codec === 11) {
|
|
452
|
+
const packets = speexFrames(data, true) || speexFrames(data, false);
|
|
453
|
+
if (!packets?.length) return { warning: 'Speex data is empty, truncated, or uses an unsupported frame mode' };
|
|
454
|
+
return { packets };
|
|
455
|
+
}
|
|
456
|
+
if (!data.length || data.length % 64) {
|
|
457
|
+
return { warning: 'Nellymoser data is empty or ends in a truncated 64-byte packet' };
|
|
458
|
+
}
|
|
459
|
+
const packets = [];
|
|
460
|
+
for (let i = 0; i < data.length; i += 64) packets.push(data.subarray(i, i + 64));
|
|
461
|
+
return { packets };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function decodeFlvAudio(packets, codec, sampleRate) {
|
|
465
|
+
const samplesPerPacket = codec === 11 ? 320 : 256;
|
|
466
|
+
const name = codec === 11 ? 'Speex' : 'Nellymoser';
|
|
467
|
+
// SWF and FLV use the same codec IDs and payloads. Decode all packets
|
|
468
|
+
// together so the decoder keeps its overlap/prediction between frames.
|
|
469
|
+
const flv = Buffer.alloc(13 + packets.reduce((size, packet) => size + 16 + packet.length, 0));
|
|
470
|
+
flv.set([0x46, 0x4c, 0x56, 1, 4, 0, 0, 0, 9]);
|
|
471
|
+
const rateFlag = Math.max(0, [5512, 11025, 22050, 44100].indexOf(sampleRate));
|
|
472
|
+
let offset = 13;
|
|
473
|
+
for (let i = 0; i < packets.length; i++) {
|
|
474
|
+
const packet = packets[i], tagSize = 16 + packet.length;
|
|
475
|
+
const millis = Math.round(i * samplesPerPacket * 1000 / sampleRate);
|
|
476
|
+
flv[offset] = 8;
|
|
477
|
+
flv.writeUIntBE(packet.length + 1, offset + 1, 3);
|
|
478
|
+
flv.writeUIntBE(millis & 0xffffff, offset + 4, 3);
|
|
479
|
+
flv[offset + 7] = millis >>> 24;
|
|
480
|
+
flv[offset + 11] = (codec << 4) | (rateFlag << 2) | 2;
|
|
481
|
+
flv.set(packet, offset + 12);
|
|
482
|
+
flv.writeUInt32BE(tagSize - 4, offset + tagSize - 4);
|
|
483
|
+
offset += tagSize;
|
|
484
|
+
}
|
|
485
|
+
const decoded = spawnSync('ffmpeg', ['-nostdin', '-v', 'error', '-xerror', '-f', 'flv', '-i', 'pipe:0',
|
|
486
|
+
'-map', '0:a:0', '-c:a', 'pcm_s16le', '-f', 's16le', 'pipe:1'], {
|
|
487
|
+
input: flv, maxBuffer: packets.length * samplesPerPacket * 2 + 65536, timeout: 120000,
|
|
488
|
+
});
|
|
489
|
+
if (decoded.error?.code === 'ENOENT') return { warning: `${name} decoding requires FFmpeg on PATH` };
|
|
490
|
+
if (decoded.error || decoded.status !== 0 || decoded.stdout.length !== packets.length * samplesPerPacket * 2) {
|
|
491
|
+
const detail = decoded.error?.message || decoded.stderr?.toString().trim().split('\n')[0];
|
|
492
|
+
return { warning: `FFmpeg could not decode the ${name} packets${detail ? ': ' + detail : ''}` };
|
|
493
|
+
}
|
|
494
|
+
return { pcm: decoded.stdout };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Encode a decoded Sound character to a file-ready buffer. */
|
|
498
|
+
export function encodeSound(sound) {
|
|
499
|
+
const raw = sound.rawData || new Uint8Array(0);
|
|
500
|
+
|
|
501
|
+
if (isNellymoser(sound.codecId) || sound.codecId === 11) {
|
|
502
|
+
const sampleRate = compressedSampleRate(sound.codecId, sound.sampleRate || 44100);
|
|
503
|
+
const split = splitCompressedPackets(raw, sound.codecId);
|
|
504
|
+
const { pcm, warning } = split.packets ? decodeFlvAudio(split.packets, sound.codecId, sampleRate) : split;
|
|
505
|
+
if (!pcm) return { mimeType: 'application/octet-stream', ext: 'bin', data: raw, warning: `Sound ${sound.characterId}: ${warning}` };
|
|
506
|
+
const sampleCount = Number.isFinite(sound.sampleCount)
|
|
507
|
+
? Math.min(pcm.length / 2, Math.max(0, Math.trunc(sound.sampleCount))) : pcm.length / 2;
|
|
508
|
+
return { mimeType: 'audio/wav', ext: 'wav', data: wrapWav(pcm.subarray(0, sampleCount * 2), sampleRate, true, false), sampleRate, sampleCount };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
if (sound.codecId === 2) {
|
|
512
|
+
// MP3: first SI16 is SeekSamples, then MP3 frames
|
|
513
|
+
const mp3 = raw.length >= 2 ? raw.slice(2) : raw;
|
|
514
|
+
return { mimeType: 'audio/mpeg', ext: 'mp3', data: mp3 };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
if (sound.codecId === 0 || sound.codecId === 1 || sound.codecId === 3) {
|
|
518
|
+
const stereo = !!sound.isStereo;
|
|
519
|
+
const is16bit = sound.codecId === 1 || !!sound.is16bit;
|
|
520
|
+
let pcm = raw;
|
|
521
|
+
if (sound.codecId === 1) {
|
|
522
|
+
pcm = decodeSwfAdpcmStream(raw, stereo, sound.sampleCount).pcm;
|
|
523
|
+
} else if (sound.codecId === 3) {
|
|
524
|
+
const bytesPerFrame = (stereo ? 2 : 1) * (is16bit ? 2 : 1);
|
|
525
|
+
const available = Math.floor(raw.length / bytesPerFrame);
|
|
526
|
+
const frames = Number.isFinite(sound.sampleCount)
|
|
527
|
+
? Math.min(available, Math.max(0, Math.trunc(sound.sampleCount)))
|
|
528
|
+
: available;
|
|
529
|
+
pcm = raw.subarray(0, frames * bytesPerFrame);
|
|
530
|
+
}
|
|
531
|
+
return { mimeType: 'audio/wav', ext: 'wav', data: wrapWav(pcm, sound.sampleRate || 44100, is16bit, stereo) };
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const label = `codec${sound.codecId}`;
|
|
535
|
+
return {
|
|
536
|
+
mimeType: 'application/octet-stream',
|
|
537
|
+
ext: 'bin',
|
|
538
|
+
data: raw,
|
|
539
|
+
warning: `Sound ${sound.characterId}: ${label} not playable in v1 — dumped raw bytes`,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Combine stream blocks into a browser-playable MP3 or PCM WAV asset.
|
|
545
|
+
* MP3 bytes remain compressed; PCM, ADPCM, Nellymoser, and Speex emit PCM WAV.
|
|
546
|
+
* @param {object[]} tags
|
|
547
|
+
* @returns {{ mimeType: string, ext: string, data: Uint8Array, warning?: string }|null}
|
|
548
|
+
*/
|
|
549
|
+
export function encodeSoundStream(tags) {
|
|
550
|
+
let head = null;
|
|
551
|
+
const blocks = [];
|
|
552
|
+
const seekMap = [];
|
|
553
|
+
let frameIndex = 0;
|
|
554
|
+
let sampleCursor = 0;
|
|
555
|
+
for (const tag of tags || []) {
|
|
556
|
+
if (!tag) continue;
|
|
557
|
+
if (tag.type === 'ShowFrame') { frameIndex++; continue; }
|
|
558
|
+
if (tag.type === 'SoundStreamHead') {
|
|
559
|
+
head = tag;
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (tag.type !== 'SoundStreamBlock' || !head) continue;
|
|
563
|
+
blocks.push({ tag, frame: frameIndex });
|
|
564
|
+
}
|
|
565
|
+
if (!head || !blocks.some(({ tag }) => tag.rawData?.length)) return null;
|
|
566
|
+
const codec = head.streamCompression | 0;
|
|
567
|
+
const rateTable = [5512, 11025, 22050, 44100];
|
|
568
|
+
const sampleRate = rateTable[head.streamRate | 0] || 44100;
|
|
569
|
+
if (isNellymoser(codec) || codec === 11) {
|
|
570
|
+
const rate = compressedSampleRate(codec, sampleRate);
|
|
571
|
+
const packets = [];
|
|
572
|
+
for (const { tag, frame } of blocks) {
|
|
573
|
+
const raw = tag.rawData;
|
|
574
|
+
if (!raw?.length) continue;
|
|
575
|
+
const split = splitCompressedPackets(raw, codec);
|
|
576
|
+
if (!split.packets) return { mimeType: 'application/octet-stream', ext: 'bin', data: new Uint8Array(0), warning: split.warning };
|
|
577
|
+
const sampleCount = split.packets.length * (codec === 11 ? 320 : 256);
|
|
578
|
+
seekMap.push({ frame, sampleCount, seekSamples: 0, audioSampleStart: sampleCursor });
|
|
579
|
+
sampleCursor += sampleCount;
|
|
580
|
+
for (const packet of split.packets) packets.push(packet);
|
|
581
|
+
}
|
|
582
|
+
const { pcm, warning } = decodeFlvAudio(packets, codec, rate);
|
|
583
|
+
if (!pcm) return { mimeType: 'application/octet-stream', ext: 'bin', data: new Uint8Array(0), warning };
|
|
584
|
+
return { mimeType: 'audio/wav', ext: 'wav', data: wrapWav(pcm, rate, true, false),
|
|
585
|
+
streamSync: { codec, sampleRate: rate, latencySeek: 0, seekMap } };
|
|
586
|
+
}
|
|
587
|
+
if (codec !== 0 && codec !== 1 && codec !== 2 && codec !== 3) {
|
|
588
|
+
return {
|
|
589
|
+
mimeType: 'application/octet-stream', ext: 'bin', data: new Uint8Array(0),
|
|
590
|
+
warning: `SoundStream codec ${codec} is not playable in browser v1`,
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (codec === 2) {
|
|
595
|
+
const chunks = [];
|
|
596
|
+
for (const { tag, frame } of blocks) {
|
|
597
|
+
const raw = tag.rawData || new Uint8Array(0);
|
|
598
|
+
const sampleCount = tag.sampleCount == null ? raw[0] | (raw[1] << 8) : tag.sampleCount | 0;
|
|
599
|
+
let seekSamples = tag.seekSamples;
|
|
600
|
+
if (seekSamples == null) {
|
|
601
|
+
seekSamples = raw[2] | (raw[3] << 8);
|
|
602
|
+
if (seekSamples & 0x8000) seekSamples -= 0x10000;
|
|
603
|
+
}
|
|
604
|
+
// An empty MP3 packet carries no media position. Keeping it as a
|
|
605
|
+
// seek anchor would jump past samples still playing from the prior packet.
|
|
606
|
+
if (raw.length <= 4) continue;
|
|
607
|
+
seekMap.push({ frame, sampleCount, seekSamples, audioSampleStart: sampleCursor });
|
|
608
|
+
sampleCursor += Math.max(0, sampleCount);
|
|
609
|
+
chunks.push(tag.mp3Data || raw.subarray(4));
|
|
610
|
+
}
|
|
611
|
+
const length = chunks.reduce((n, chunk) => n + chunk.length, 0);
|
|
612
|
+
if (!length) return null;
|
|
613
|
+
const data = new Uint8Array(length);
|
|
614
|
+
let offset = 0;
|
|
615
|
+
for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.length; }
|
|
616
|
+
return {
|
|
617
|
+
mimeType: 'audio/mpeg', ext: 'mp3', data,
|
|
618
|
+
streamSync: { codec, sampleRate, latencySeek: head.latencySeek | 0, seekMap },
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const channels = head.streamStereo ? 2 : 1;
|
|
623
|
+
const pcmParts = [];
|
|
624
|
+
for (const { tag, frame } of blocks) {
|
|
625
|
+
const raw = tag.rawData || new Uint8Array(0);
|
|
626
|
+
let pcm, sampleCount;
|
|
627
|
+
if (codec === 1) {
|
|
628
|
+
const decoded = decodeSwfAdpcmStream(raw, channels === 2);
|
|
629
|
+
pcm = decoded.pcm;
|
|
630
|
+
sampleCount = decoded.sampleCount;
|
|
631
|
+
} else {
|
|
632
|
+
const bytesPerSample = head.stream16bit ? 2 : 1;
|
|
633
|
+
const blockAlign = channels * bytesPerSample;
|
|
634
|
+
const usableBytes = raw.length - (raw.length % blockAlign);
|
|
635
|
+
pcm = raw.slice(0, usableBytes);
|
|
636
|
+
sampleCount = usableBytes / blockAlign;
|
|
637
|
+
// Format 0 is native-endian (big-endian in SWF); format 3 is explicit LE.
|
|
638
|
+
if (codec === 0 && bytesPerSample === 2) {
|
|
639
|
+
pcm = pcm.slice();
|
|
640
|
+
for (let i = 0; i + 1 < pcm.length; i += 2) { const byte = pcm[i]; pcm[i] = pcm[i + 1]; pcm[i + 1] = byte; }
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
if (sampleCount === 0 && pcmParts.length === 0) continue;
|
|
644
|
+
pcmParts.push(pcm);
|
|
645
|
+
seekMap.push({ frame, sampleCount, seekSamples: 0, audioSampleStart: sampleCursor });
|
|
646
|
+
sampleCursor += sampleCount;
|
|
647
|
+
}
|
|
648
|
+
const pcmLength = pcmParts.reduce((n, part) => n + part.length, 0);
|
|
649
|
+
if (!pcmLength) return null;
|
|
650
|
+
const pcm = new Uint8Array(pcmLength);
|
|
651
|
+
let pcmOffset = 0;
|
|
652
|
+
for (const part of pcmParts) { pcm.set(part, pcmOffset); pcmOffset += part.length; }
|
|
653
|
+
const outputIs16Bit = codec === 1 || !!head.stream16bit;
|
|
654
|
+
return {
|
|
655
|
+
mimeType: 'audio/wav', ext: 'wav',
|
|
656
|
+
data: wrapWav(pcm, sampleRate, outputIs16Bit, channels === 2),
|
|
657
|
+
streamSync: { codec, sampleRate, latencySeek: 0, seekMap },
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Encode each declared stream independently, keeping its SWF frame interval. */
|
|
662
|
+
export function encodeSoundStreamSegments(tags) {
|
|
663
|
+
const segments = [];
|
|
664
|
+
let frame = 0;
|
|
665
|
+
let segment = null;
|
|
666
|
+
let packetFrame = -1;
|
|
667
|
+
for (const tag of tags || []) {
|
|
668
|
+
if (tag?.type === 'SoundStreamHead') {
|
|
669
|
+
// A frame can contain a single stream packet. If a header follows it,
|
|
670
|
+
// the packet keeps its preceding header and plays through this frame.
|
|
671
|
+
const boundary = packetFrame === frame ? frame + 1 : frame;
|
|
672
|
+
if (segment) segment.end = boundary;
|
|
673
|
+
segment = { start: boundary, tagFrame: frame, end: null, tags: [tag] };
|
|
674
|
+
segments.push(segment);
|
|
675
|
+
} else if (tag?.type === 'ShowFrame') {
|
|
676
|
+
frame++;
|
|
677
|
+
if (segment) segment.tags.push(tag);
|
|
678
|
+
} else if (tag?.type === 'SoundStreamBlock' && segment && packetFrame !== frame) {
|
|
679
|
+
segment.tags.push(tag);
|
|
680
|
+
packetFrame = frame;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return segments.map(({ start, tagFrame, end, tags }) => {
|
|
684
|
+
const encoded = encodeSoundStream(tags);
|
|
685
|
+
if (encoded?.streamSync) {
|
|
686
|
+
for (const block of encoded.streamSync.seekMap) block.frame += tagFrame;
|
|
687
|
+
}
|
|
688
|
+
return { start, end, encoded };
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function spriteSoundStreamTags(frames) {
|
|
693
|
+
const tags = [];
|
|
694
|
+
let head = null;
|
|
695
|
+
for (const frame of frames || []) {
|
|
696
|
+
if (frame?.streamHead && frame.streamHead !== head) {
|
|
697
|
+
head = frame.streamHead;
|
|
698
|
+
tags.push(head);
|
|
699
|
+
}
|
|
700
|
+
if (head && frame?.streamBlocks?.length) tags.push(...frame.streamBlocks);
|
|
701
|
+
tags.push({ type: 'ShowFrame' });
|
|
702
|
+
}
|
|
703
|
+
return tags;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export function encodeSpriteSoundStream(frames) {
|
|
707
|
+
return encodeSoundStream(spriteSoundStreamTags(frames));
|
|
708
|
+
}
|