-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathid3parser.c
More file actions
533 lines (445 loc) · 17.9 KB
/
id3parser.c
File metadata and controls
533 lines (445 loc) · 17.9 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#include "id3parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pspiofilemgr.h>
#include <jpeglib.h>
#include <png.h>
// ---- Detect image format from magic bytes ----
static int isPNG(const unsigned char *data, int size) {
return (size >= 8 && data[0] == 0x89 && data[1] == 'P' &&
data[2] == 'N' && data[3] == 'G');
}
static int isJPEG(const unsigned char *data, int size) {
return (size >= 2 && data[0] == 0xFF && data[1] == 0xD8);
}
// ---- Helpers ----
static int read_syncsafe(const unsigned char *b) {
return ((b[0] & 0x7F) << 21) | ((b[1] & 0x7F) << 14) |
((b[2] & 0x7F) << 7) | (b[3] & 0x7F);
}
static int read_be32(const unsigned char *b) {
return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
}
static void trim(char *s) {
int len = strlen(s);
while (len > 0 && (s[len-1] == ' ' || s[len-1] == '\0')) len--;
s[len] = '\0';
}
static void safe_copy(char *dst, const unsigned char *src, int len, int maxlen) {
if (len >= maxlen) len = maxlen - 1;
memcpy(dst, src, len);
dst[len] = '\0';
trim(dst);
}
// ---- ID3v1 parser (last 128 bytes of file) ----
static int parse_id3v1(SceUID fd, ID3Info *info) {
unsigned char tag[128];
sceIoLseek32(fd, -128, SEEK_END);
if (sceIoRead(fd, tag, 128) != 128) return -1;
if (memcmp(tag, "TAG", 3) != 0) return -1;
safe_copy(info->title, tag + 3, 30, ID3_TITLE_LEN);
safe_copy(info->artist, tag + 33, 30, ID3_ARTIST_LEN);
safe_copy(info->album, tag + 63, 30, ID3_ALBUM_LEN);
return 0;
}
// ---- ID3v2 parser ----
static int parse_id3v2(SceUID fd, ID3Info *info, int loadCover) {
unsigned char header[10];
sceIoLseek32(fd, 0, SEEK_SET);
if (sceIoRead(fd, header, 10) != 10) return -1;
if (memcmp(header, "ID3", 3) != 0) return -1;
int version = header[3]; // 3 = ID3v2.3, 4 = ID3v2.4
int tagSize = read_syncsafe(header + 6);
int pos = 10;
while (pos < tagSize + 10) {
unsigned char frameHeader[10];
sceIoLseek32(fd, pos, SEEK_SET);
if (sceIoRead(fd, frameHeader, 10) != 10) break;
char frameId[5];
memcpy(frameId, frameHeader, 4);
frameId[4] = '\0';
int frameSize;
if (version == 4) {
frameSize = read_syncsafe(frameHeader + 4);
} else {
frameSize = read_be32(frameHeader + 4);
}
if (frameSize <= 0 || frameSize > tagSize) break;
if (frameHeader[0] == 0) break; // padding
pos += 10;
// Text frames: TIT2 (title), TPE1 (artist), TALB (album)
if (strcmp(frameId, "TIT2") == 0 || strcmp(frameId, "TPE1") == 0 ||
strcmp(frameId, "TALB") == 0) {
int readSize = frameSize;
if (readSize > 512) readSize = 512;
unsigned char *data = (unsigned char *)malloc(readSize);
if (data) {
sceIoLseek32(fd, pos, SEEK_SET);
sceIoRead(fd, data, readSize);
// First byte is encoding: 0=ISO-8859-1, 1=UTF-16, 3=UTF-8
int encoding = data[0];
unsigned char *textStart = data + 1;
int textLen = readSize - 1;
// For UTF-16 (encoding 1), skip BOM
if (encoding == 1 && textLen >= 2) {
textStart += 2;
textLen -= 2;
// Simple: just take every other byte (ASCII subset)
int j = 0;
unsigned char ascii[256];
int i;
for (i = 0; i < textLen - 1 && j < 255; i += 2) {
if (textStart[i+1] == 0 && textStart[i] != 0) {
ascii[j++] = textStart[i];
} else if (textStart[i] == 0 && textStart[i+1] != 0) {
ascii[j++] = textStart[i+1];
}
}
ascii[j] = '\0';
textStart = ascii;
textLen = j;
if (strcmp(frameId, "TIT2") == 0)
safe_copy(info->title, textStart, textLen, ID3_TITLE_LEN);
else if (strcmp(frameId, "TPE1") == 0)
safe_copy(info->artist, textStart, textLen, ID3_ARTIST_LEN);
else if (strcmp(frameId, "TALB") == 0)
safe_copy(info->album, textStart, textLen, ID3_ALBUM_LEN);
} else {
// ISO-8859-1 or UTF-8 (treat as ASCII)
if (strcmp(frameId, "TIT2") == 0)
safe_copy(info->title, textStart, textLen, ID3_TITLE_LEN);
else if (strcmp(frameId, "TPE1") == 0)
safe_copy(info->artist, textStart, textLen, ID3_ARTIST_LEN);
else if (strcmp(frameId, "TALB") == 0)
safe_copy(info->album, textStart, textLen, ID3_ALBUM_LEN);
}
free(data);
}
}
// APIC frame (album art)
else if (strcmp(frameId, "APIC") == 0 && !info->hasCover) {
if (!loadCover) {
// Just mark that cover exists if frame is big enough to contain image
if (frameSize > 32) {
info->hasCover = 1;
}
} else if (frameSize <= MAX_COVER_SIZE && frameSize > 32) {
unsigned char *data = (unsigned char *)malloc(frameSize);
if (data) {
sceIoLseek32(fd, pos, SEEK_SET);
sceIoRead(fd, data, frameSize);
// APIC format: encoding(1) + mime(null-term) + pictype(1) + desc(null-term) + data
int encoding = data[0];
int offset = 1; // skip encoding byte
// skip mime type string (always ISO-8859-1)
while (offset < frameSize && data[offset] != '\0') offset++;
offset++; // skip null
offset++; // skip picture type byte
// skip description string
if (encoding == 1 || encoding == 2) {
// UTF-16: null terminator is 0x00 0x00
while (offset + 1 < frameSize &&
!(data[offset] == '\0' && data[offset+1] == '\0'))
offset += 2;
offset += 2; // skip double null
} else {
// ISO-8859-1 or UTF-8: single null terminator
while (offset < frameSize && data[offset] != '\0') offset++;
offset++; // skip null
}
int imgSize = frameSize - offset;
if (imgSize > 0 && offset < frameSize) {
// Verify we actually landed on image data
if (isJPEG(data + offset, imgSize) || isPNG(data + offset, imgSize)) {
info->coverData = (unsigned char *)malloc(imgSize);
if (info->coverData) {
memcpy(info->coverData, data + offset, imgSize);
info->coverSize = imgSize;
info->hasCover = 1;
}
} else {
// Fallback: scan for JPEG/PNG magic bytes in frame data
int scan;
for (scan = 1; scan < frameSize - 4; scan++) {
if (isJPEG(data + scan, frameSize - scan) ||
isPNG(data + scan, frameSize - scan)) {
imgSize = frameSize - scan;
info->coverData = (unsigned char *)malloc(imgSize);
if (info->coverData) {
memcpy(info->coverData, data + scan, imgSize);
info->coverSize = imgSize;
info->hasCover = 1;
}
break;
}
}
}
}
free(data);
}
}
}
pos += frameSize;
}
return 0;
}
// ---- Estimate MP3 duration from first frame header + file size ----
static int estimate_duration(SceUID fd) {
unsigned char buf[4];
int fileSize;
int pos;
fileSize = sceIoLseek32(fd, 0, SEEK_END);
// Look for sync word in first 64KB
int searchLimit = 65536;
if (searchLimit > fileSize) searchLimit = fileSize;
sceIoLseek32(fd, 0, SEEK_SET);
// Skip ID3v2 tag if present
unsigned char id3header[10];
sceIoRead(fd, id3header, 10);
int startPos = 0;
if (memcmp(id3header, "ID3", 3) == 0) {
startPos = 10 + read_syncsafe(id3header + 6);
}
static const int bitrates[16] = {
0, 32, 40, 48, 56, 64, 80, 96,
112, 128, 160, 192, 224, 256, 320, 0
};
for (pos = startPos; pos < searchLimit; pos++) {
sceIoLseek32(fd, pos, SEEK_SET);
if (sceIoRead(fd, buf, 4) != 4) break;
// MPEG sync word
if (buf[0] == 0xFF && (buf[1] & 0xE0) == 0xE0) {
int bitrateIdx = (buf[2] >> 4) & 0x0F;
if (bitrateIdx > 0 && bitrateIdx < 15) {
int bitrate = bitrates[bitrateIdx];
int audioSize = fileSize - startPos;
if (bitrate > 0) {
return audioSize / (bitrate * 125); // 125 = 1000/8
}
}
}
}
return 0; // unknown
}
// ---- Public API ----
int id3_parse(const char *filepath, ID3Info *info, int loadCover) {
memset(info, 0, sizeof(ID3Info));
SceUID fd = sceIoOpen(filepath, PSP_O_RDONLY, 0777);
if (fd < 0) return -1;
// Try ID3v2 first (beginning of file), then fallback to ID3v1
parse_id3v2(fd, info, loadCover);
// If ID3v2 didn't give us a title, try ID3v1
if (info->title[0] == '\0') {
parse_id3v1(fd, info);
}
// Estimate duration
info->duration = estimate_duration(fd);
sceIoClose(fd);
// If still no title, use filename
if (info->title[0] == '\0') {
const char *fname = strrchr(filepath, '/');
if (fname) fname++; else fname = filepath;
strncpy(info->title, fname, ID3_TITLE_LEN - 1);
// Remove .mp3 extension
char *ext = strrchr(info->title, '.');
if (ext) *ext = '\0';
}
if (info->artist[0] == '\0') {
strcpy(info->artist, "Unknown Artist");
}
return 0;
}
void id3_free(ID3Info *info) {
if (info->coverData) {
free(info->coverData);
info->coverData = NULL;
}
info->hasCover = 0;
info->coverSize = 0;
}
// ---- PNG memory read helpers ----
typedef struct {
const unsigned char *data;
int size;
int offset;
} PngMemReader;
static void png_mem_read_fn(png_structp png, png_bytep outBytes, png_size_t byteCount) {
PngMemReader *reader = (PngMemReader *)png_get_io_ptr(png);
if (reader->offset + (int)byteCount > reader->size) {
png_error(png, "Read past end");
return;
}
memcpy(outBytes, reader->data + reader->offset, byteCount);
reader->offset += byteCount;
}
// ---- Nearest-neighbor downscale helper ----
static unsigned int *downscalePixels(unsigned int *src, int srcW, int srcH,
int dstW, int dstH) {
unsigned int *dst = (unsigned int *)malloc(dstW * dstH * 4);
if (!dst) return NULL;
int y, x;
for (y = 0; y < dstH; y++) {
int sy = y * srcH / dstH;
for (x = 0; x < dstW; x++) {
int sx = x * srcW / dstW;
dst[y * dstW + x] = src[sy * srcW + sx];
}
}
return dst;
}
// ---- Decode PNG cover art ----
static unsigned int *decodePNG(const unsigned char *data, int dataSize,
int maxW, int maxH, int *outW, int *outH) {
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png) return NULL;
png_infop pngInfo = png_create_info_struct(png);
if (!pngInfo) { png_destroy_read_struct(&png, NULL, NULL); return NULL; }
if (setjmp(png_jmpbuf(png))) {
png_destroy_read_struct(&png, &pngInfo, NULL);
return NULL;
}
PngMemReader reader;
reader.data = data;
reader.size = dataSize;
reader.offset = 0;
png_set_read_fn(png, &reader, png_mem_read_fn);
png_read_info(png, pngInfo);
int w = png_get_image_width(png, pngInfo);
int h = png_get_image_height(png, pngInfo);
int colorType = png_get_color_type(png, pngInfo);
int bitDepth = png_get_bit_depth(png, pngInfo);
// Convert to 8-bit RGBA
if (bitDepth == 16) png_set_strip_16(png);
if (colorType == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) png_set_expand_gray_1_2_4_to_8(png);
if (png_get_valid(png, pngInfo, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
if (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY)
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
png_read_update_info(png, pngInfo);
unsigned int *pixels = (unsigned int *)malloc(w * h * 4);
if (!pixels) { png_destroy_read_struct(&png, &pngInfo, NULL); return NULL; }
png_bytep *rows = (png_bytep *)malloc(h * sizeof(png_bytep));
if (!rows) { free(pixels); png_destroy_read_struct(&png, &pngInfo, NULL); return NULL; }
int y;
for (y = 0; y < h; y++)
rows[y] = (png_bytep)(pixels + y * w);
png_read_image(png, rows);
free(rows);
png_destroy_read_struct(&png, &pngInfo, NULL);
// Convert RGBA to ABGR8888 in-place
int i;
for (i = 0; i < w * h; i++) {
unsigned int px = pixels[i];
unsigned char r = px & 0xFF;
unsigned char g = (px >> 8) & 0xFF;
unsigned char b = (px >> 16) & 0xFF;
unsigned char a = (px >> 24) & 0xFF;
pixels[i] = (a << 24) | (b << 16) | (g << 8) | r;
}
// Downscale if needed
if (w > maxW || h > maxH) {
int newW = w, newH = h;
if (newW > maxW) { newH = newH * maxW / newW; newW = maxW; }
if (newH > maxH) { newW = newW * maxH / newH; newH = maxH; }
if (newW < 1) newW = 1;
if (newH < 1) newH = 1;
unsigned int *scaled = downscalePixels(pixels, w, h, newW, newH);
free(pixels);
if (!scaled) return NULL;
pixels = scaled;
w = newW;
h = newH;
}
*outW = w;
*outH = h;
return pixels;
}
// ---- JPEG decode for album art ----
unsigned int *id3_decode_cover(ID3Info *info, int maxW, int maxH,
int *outW, int *outH) {
if (!info->hasCover || !info->coverData || info->coverSize <= 0)
return NULL;
// Check if it's PNG
if (isPNG(info->coverData, info->coverSize)) {
return decodePNG(info->coverData, info->coverSize, maxW, maxH, outW, outH);
}
// Check if it's JPEG
if (!isJPEG(info->coverData, info->coverSize)) {
return NULL; // unknown format
}
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, info->coverData, info->coverSize);
if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
jpeg_destroy_decompress(&cinfo);
return NULL;
}
// Scale down if larger than max
int origW = cinfo.image_width;
int origH = cinfo.image_height;
int scale = 1;
while ((origW / scale) > maxW || (origH / scale) > maxH) {
scale *= 2;
if (scale >= 8) { scale = 8; break; }
}
cinfo.scale_num = 1;
cinfo.scale_denom = scale;
cinfo.out_color_space = JCS_RGB;
jpeg_start_decompress(&cinfo);
int w = cinfo.output_width;
int h = cinfo.output_height;
int row_stride = w * 3;
unsigned int *pixels = (unsigned int *)malloc(w * h * 4);
if (!pixels) {
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return NULL;
}
unsigned char *rowbuf = (unsigned char *)malloc(row_stride);
if (!rowbuf) {
free(pixels);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return NULL;
}
int y;
for (y = 0; y < (int)cinfo.output_height; y++) {
unsigned char *row = rowbuf;
jpeg_read_scanlines(&cinfo, &row, 1);
int x;
for (x = 0; x < w; x++) {
unsigned char r = rowbuf[x * 3 + 0];
unsigned char g = rowbuf[x * 3 + 1];
unsigned char b = rowbuf[x * 3 + 2];
// ABGR8888 format for PSP
pixels[y * w + x] = 0xFF000000 | (b << 16) | (g << 8) | r;
}
}
free(rowbuf);
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
// Downscale if libjpeg's 1/N scaling wasn't enough
if (w > maxW || h > maxH) {
int newW = w, newH = h;
if (newW > maxW) { newH = newH * maxW / newW; newW = maxW; }
if (newH > maxH) { newW = newW * maxH / newH; newH = maxH; }
if (newW < 1) newW = 1;
if (newH < 1) newH = 1;
unsigned int *scaled = downscalePixels(pixels, w, h, newW, newH);
free(pixels);
if (!scaled) return NULL;
pixels = scaled;
w = newW;
h = newH;
}
*outW = w;
*outH = h;
info->coverWidth = w;
info->coverHeight = h;
return pixels;
}