-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathcgbi-to-png.ts
More file actions
202 lines (166 loc) · 5.57 KB
/
Copy pathcgbi-to-png.ts
File metadata and controls
202 lines (166 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import pako from "pako";
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
import CommonFormats, { Category } from "src/CommonFormats.ts";
async function revertCgBIBuffer(input: Uint8Array | ArrayBuffer): Promise<Uint8Array> {
const buffer = input instanceof Uint8Array ? input : new Uint8Array(input);
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
for (let i = 0; i < 8; i++) {
if (buffer[i] !== PNG_SIGNATURE[i]) {
throw new Error("Not a PNG file");
}
}
const concat = (arrays: Uint8Array[]) => {
const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const arr of arrays) {
result.set(arr, offset);
offset += arr.length;
}
return result;
};
const crcTable = (() => {
const table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
table[i] = c >>> 0;
}
return table;
})();
const crc32 = (data: Uint8Array, crc = 0xffffffff) => {
for (let i = 0; i < data.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc & 0xff) ^ data[i]];
}
return (crc ^ 0xffffffff) >>> 0;
};
const ignoreChunkTypes = new Set(["CgBI", "iDOT"]);
const chunks: { length: number; type: string; data: Uint8Array; crc: number }[] = [];
let offset = 8;
const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
let isIphoneCompressed = false;
let idatCgbiData = new Uint8Array(0);
let width = 0, height = 0;
while (offset < buffer.length) {
const length = view.getUint32(offset, false);
offset += 4;
const typeBytes = buffer.slice(offset, offset + 4);
const type = String.fromCharCode(...typeBytes);
offset += 4;
const data = buffer.slice(offset, offset + length);
offset += length;
const crc = view.getUint32(offset, false);
offset += 4;
if (type === "CgBI") {
isIphoneCompressed = true;
}
if (ignoreChunkTypes.has(type)) {
continue;
}
if (type === "IHDR") {
const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
width = dataView.getUint32(0, false);
height = dataView.getUint32(4, false);
}
if (type === "IDAT" && isIphoneCompressed) {
idatCgbiData = concat([idatCgbiData, data]);
continue;
}
if (type === "IEND" && isIphoneCompressed) {
const uncompressed = pako.inflateRaw(idatCgbiData);
const newData = new Uint8Array(uncompressed.length);
let i = 0;
for (let y = 0; y < height; y++) {
newData[i] = uncompressed[i]; // filter byte
i++;
for (let x = 0; x < width; x++) {
newData[i] = uncompressed[i + 2]; // B → R
newData[i + 1] = uncompressed[i + 1]; // G
newData[i + 2] = uncompressed[i]; // R → B
newData[i + 3] = uncompressed[i + 3]; // A
i += 4;
}
}
const compressedIdat = pako.deflate(newData);
const typeIdat = new Uint8Array([73, 68, 65, 84]); // "IDAT"
const combined = concat([typeIdat, compressedIdat]);
const newCrc = crc32(combined);
chunks.push({
length: compressedIdat.length,
type: "IDAT",
data: compressedIdat,
crc: newCrc
});
}
chunks.push({ length, type, data, crc });
}
const header = buffer.slice(0, 8);
const parts: Uint8Array[] = [header];
for (const chunk of chunks) {
const lenBuf = new Uint8Array(4);
new DataView(lenBuf.buffer).setUint32(0, chunk.length, false);
parts.push(lenBuf);
const typeBuf = new Uint8Array(4);
for (let i = 0; i < 4; i++) {
typeBuf[i] = chunk.type.charCodeAt(i);
}
parts.push(typeBuf);
if (chunk.length > 0) {
parts.push(chunk.data);
}
const crcBuf = new Uint8Array(4);
new DataView(crcBuf.buffer).setUint32(0, chunk.crc, false);
parts.push(crcBuf);
}
return concat(parts);
}
class cgbiToPngHandler implements FormatHandler {
public name = "CgBI to PNG converter";
public ready = true;
public supportedFormats: FileFormat[] = [
{
name: "iPhone optimized CgBI PNG",
format: "cgbi-png",
extension: "png",
mime: "image/png",
from: true,
to: false,
internal: "cgbi-png",
category: Category.IMAGE,
lossless: true
},
CommonFormats.PNG.supported("png", false, true, true),
];
async init(): Promise<void> {
this.ready = true;
}
async doConvert(
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat,
_args?: string[]
): Promise<FileData[]> {
if (inputFormat.internal !== "cgbi-png" || outputFormat.internal !== "png") {
throw new TypeError(`Unsupported conversion: ${inputFormat.internal} → ${outputFormat.internal}`);
}
const outputFiles: FileData[] = [];
for (const inputFile of inputFiles) {
try {
const standardPng = await revertCgBIBuffer(inputFile.bytes);
const dotIndex = inputFile.name.lastIndexOf('.');
const baseName = dotIndex !== -1 ? inputFile.name.substring(0, dotIndex) : inputFile.name;
const outputName = `${baseName}.${outputFormat.extension}`;
outputFiles.push({
bytes: standardPng,
name: outputName
});
} catch (error) {
throw new Error(`Failed to convert ${inputFile.name}: ${(error as Error).message}`);
}
}
return outputFiles;
}
}
export default cgbiToPngHandler;