146d59e02ea15c8d9db6df91de6cdc14ffbc1eb1
[reactos.git] / reactos / lib / 3rdparty / libmpg123 / id3.c
1 /*
2 id3: ID3v2.3 and ID3v2.4 parsing (a relevant subset)
3
4 copyright 2006-2013 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Thomas Orgis
7 */
8
9 #include "mpg123lib_intern.h"
10 #include "id3.h"
11 #include "debug.h"
12
13 #ifndef NO_ID3V2 /* Only the main parsing routine will always be there. */
14
15 /* We know the usual text frames plus some specifics. */
16 #define KNOWN_FRAMES 5
17 static const char frame_type[KNOWN_FRAMES][5] = { "COMM", "TXXX", "RVA2", "USLT", "APIC" };
18 enum frame_types { unknown = -2, text = -1, comment, extra, rva2, uslt, picture };
19
20 /* UTF support definitions */
21
22 typedef void (*text_converter)(mpg123_string *sb, const unsigned char* source, size_t len, const int noquiet);
23
24 static void convert_latin1 (mpg123_string *sb, const unsigned char* source, size_t len, const int noquiet);
25 static void convert_utf16bom(mpg123_string *sb, const unsigned char* source, size_t len, const int noquiet);
26 static void convert_utf8 (mpg123_string *sb, const unsigned char* source, size_t len, const int noquiet);
27
28 static const text_converter text_converters[4] =
29 {
30 convert_latin1,
31 /* We always check for (multiple) BOM in 16bit unicode. Without BOM, UTF16 BE is the default.
32 Errors in encoding are detected anyway. */
33 convert_utf16bom,
34 convert_utf16bom,
35 convert_utf8
36 };
37
38 static const unsigned int encoding_widths[4] = { 1, 2, 2, 1 };
39
40 /* the code starts here... */
41
42 static void null_id3_links(mpg123_handle *fr)
43 {
44 fr->id3v2.title = NULL;
45 fr->id3v2.artist = NULL;
46 fr->id3v2.album = NULL;
47 fr->id3v2.year = NULL;
48 fr->id3v2.genre = NULL;
49 fr->id3v2.comment = NULL;
50 }
51
52 void init_id3(mpg123_handle *fr)
53 {
54 fr->id3v2.version = 0; /* nothing there */
55 null_id3_links(fr);
56 fr->id3v2.comments = 0;
57 fr->id3v2.comment_list = NULL;
58 fr->id3v2.texts = 0;
59 fr->id3v2.text = NULL;
60 fr->id3v2.extras = 0;
61 fr->id3v2.extra = NULL;
62 fr->id3v2.pictures = 0;
63 fr->id3v2.picture = NULL;
64 }
65
66 /* Managing of the text, comment and extra lists. */
67
68 /* Initialize one element. */
69 static void init_mpg123_text(mpg123_text *txt)
70 {
71 mpg123_init_string(&txt->text);
72 mpg123_init_string(&txt->description);
73 txt->id[0] = 0;
74 txt->id[1] = 0;
75 txt->id[2] = 0;
76 txt->id[3] = 0;
77 txt->lang[0] = 0;
78 txt->lang[1] = 0;
79 txt->lang[2] = 0;
80 }
81
82 static void init_mpg123_picture(mpg123_picture *pic)
83 {
84 mpg123_init_string(&pic->mime_type);
85 mpg123_init_string(&pic->description);
86 pic->type = 0;
87 pic->size = 0;
88 pic->data = NULL;
89 }
90
91 /* Free memory of one element. */
92 static void free_mpg123_text(mpg123_text *txt)
93 {
94 mpg123_free_string(&txt->text);
95 mpg123_free_string(&txt->description);
96 }
97
98 static void free_mpg123_picture(mpg123_picture * pic)
99 {
100 mpg123_free_string(&pic->mime_type);
101 mpg123_free_string(&pic->description);
102 if (pic->data != NULL)
103 free(pic->data);
104 }
105
106 /* Free memory of whole list. */
107 #define free_comment(mh) free_id3_text(&((mh)->id3v2.comment_list), &((mh)->id3v2.comments))
108 #define free_text(mh) free_id3_text(&((mh)->id3v2.text), &((mh)->id3v2.texts))
109 #define free_extra(mh) free_id3_text(&((mh)->id3v2.extra), &((mh)->id3v2.extras))
110 #define free_picture(mh) free_id3_picture(&((mh)->id3v2.picture), &((mh)->id3v2.pictures))
111 static void free_id3_text(mpg123_text **list, size_t *size)
112 {
113 size_t i;
114 for(i=0; i<*size; ++i) free_mpg123_text(&((*list)[i]));
115
116 free(*list);
117 *list = NULL;
118 *size = 0;
119 }
120 static void free_id3_picture(mpg123_picture **list, size_t *size)
121 {
122 size_t i;
123 for(i=0; i<*size; ++i) free_mpg123_picture(&((*list)[i]));
124
125 free(*list);
126 *list = NULL;
127 *size = 0;
128 }
129
130 /* Add items to the list. */
131 #define add_comment(mh) add_id3_text(&((mh)->id3v2.comment_list), &((mh)->id3v2.comments))
132 #define add_text(mh) add_id3_text(&((mh)->id3v2.text), &((mh)->id3v2.texts))
133 #define add_extra(mh) add_id3_text(&((mh)->id3v2.extra), &((mh)->id3v2.extras))
134 #define add_picture(mh) add_id3_picture(&((mh)->id3v2.picture), &((mh)->id3v2.pictures))
135 static mpg123_text *add_id3_text(mpg123_text **list, size_t *size)
136 {
137 mpg123_text *x = safe_realloc(*list, sizeof(mpg123_text)*(*size+1));
138 if(x == NULL) return NULL; /* bad */
139
140 *list = x;
141 *size += 1;
142 init_mpg123_text(&((*list)[*size-1]));
143
144 return &((*list)[*size-1]); /* Return pointer to the added text. */
145 }
146 static mpg123_picture *add_id3_picture(mpg123_picture **list, size_t *size)
147 {
148 mpg123_picture *x = safe_realloc(*list, sizeof(mpg123_picture)*(*size+1));
149 if(x == NULL) return NULL; /* bad */
150
151 *list = x;
152 *size += 1;
153 init_mpg123_picture(&((*list)[*size-1]));
154
155 return &((*list)[*size-1]); /* Return pointer to the added picture. */
156 }
157
158
159 /* Remove the last item. */
160 #define pop_comment(mh) pop_id3_text(&((mh)->id3v2.comment_list), &((mh)->id3v2.comments))
161 #define pop_text(mh) pop_id3_text(&((mh)->id3v2.text), &((mh)->id3v2.texts))
162 #define pop_extra(mh) pop_id3_text(&((mh)->id3v2.extra), &((mh)->id3v2.extras))
163 #define pop_picture(mh) pop_id3_picture(&((mh)->id3v2.picture), &((mh)->id3v2.pictures))
164 static void pop_id3_text(mpg123_text **list, size_t *size)
165 {
166 mpg123_text *x;
167 if(*size < 1) return;
168
169 free_mpg123_text(&((*list)[*size-1]));
170 if(*size > 1)
171 {
172 x = safe_realloc(*list, sizeof(mpg123_text)*(*size-1));
173 if(x != NULL){ *list = x; *size -= 1; }
174 }
175 else
176 {
177 free(*list);
178 *list = NULL;
179 *size = 0;
180 }
181 }
182 static void pop_id3_picture(mpg123_picture **list, size_t *size)
183 {
184 mpg123_picture *x;
185 if(*size < 1) return;
186
187 free_mpg123_picture(&((*list)[*size-1]));
188 if(*size > 1)
189 {
190 x = safe_realloc(*list, sizeof(mpg123_picture)*(*size-1));
191 if(x != NULL){ *list = x; *size -= 1; }
192 }
193 else
194 {
195 free(*list);
196 *list = NULL;
197 *size = 0;
198 }
199 }
200
201 /* OK, back to the higher level functions. */
202
203 void exit_id3(mpg123_handle *fr)
204 {
205 free_picture(fr);
206 free_comment(fr);
207 free_extra(fr);
208 free_text(fr);
209 }
210
211 void reset_id3(mpg123_handle *fr)
212 {
213 exit_id3(fr);
214 init_id3(fr);
215 }
216
217 /* Set the id3v2.artist id3v2.title ... links to elements of the array. */
218 void id3_link(mpg123_handle *fr)
219 {
220 size_t i;
221 mpg123_id3v2 *v2 = &fr->id3v2;
222 debug("linking ID3v2");
223 null_id3_links(fr);
224 for(i=0; i<v2->texts; ++i)
225 {
226 mpg123_text *entry = &v2->text[i];
227 if (!strncmp("TIT2", entry->id, 4)) v2->title = &entry->text;
228 else if(!strncmp("TALB", entry->id, 4)) v2->album = &entry->text;
229 else if(!strncmp("TPE1", entry->id, 4)) v2->artist = &entry->text;
230 else if(!strncmp("TYER", entry->id, 4)) v2->year = &entry->text;
231 else if(!strncmp("TCON", entry->id, 4)) v2->genre = &entry->text;
232 }
233 for(i=0; i<v2->comments; ++i)
234 {
235 mpg123_text *entry = &v2->comment_list[i];
236 if(entry->description.fill == 0 || entry->description.p[0] == 0)
237 v2->comment = &entry->text;
238 }
239 /* When no generic comment found, use the last non-generic one. */
240 if(v2->comment == NULL && v2->comments > 0)
241 v2->comment = &v2->comment_list[v2->comments-1].text;
242 }
243
244 /*
245 Store ID3 text data in an mpg123_string; either verbatim copy or everything translated to UTF-8 encoding.
246 Preserve the zero string separator (I don't need strlen for the total size).
247
248 ID3v2 standard says that there should be one text frame of specific type per tag, and subsequent tags overwrite old values.
249 So, I always replace the text that may be stored already (perhaps with a list of zero-separated strings, though).
250 */
251 static void store_id3_text(mpg123_string *sb, unsigned char *source, size_t source_size, const int noquiet, const int notranslate)
252 {
253 if(!source_size)
254 {
255 debug("Empty id3 data!");
256 return;
257 }
258
259 /* We shall just copy the data. Client wants to decode itself. */
260 if(notranslate)
261 {
262 /* Future: Add a path for ID3 errors. */
263 if(!mpg123_resize_string(sb, source_size))
264 {
265 if(noquiet) error("Cannot resize target string, out of memory?");
266 return;
267 }
268 memcpy(sb->p, source, source_size);
269 sb->fill = source_size;
270 debug1("stored undecoded ID3 text of size %"SIZE_P, (size_p)source_size);
271 return;
272 }
273
274 id3_to_utf8(sb, source[0], source+1, source_size-1, noquiet);
275
276 if(sb->fill) debug1("UTF-8 string (the first one): %s", sb->p);
277 else if(noquiet) error("unable to convert string to UTF-8 (out of memory, junk input?)!");
278 }
279
280 /* On error, sb->size is 0. */
281 void id3_to_utf8(mpg123_string *sb, unsigned char encoding, const unsigned char *source, size_t source_size, int noquiet)
282 {
283 unsigned int bwidth;
284 debug1("encoding: %u", encoding);
285 /* A note: ID3v2.3 uses UCS-2 non-variable 16bit encoding, v2.4 uses UTF16.
286 UTF-16 uses a reserved/private range in UCS-2 to add the magic, so we just always treat it as UTF. */
287 if(encoding > mpg123_id3_enc_max)
288 {
289 if(noquiet) error1("Unknown text encoding %u, I take no chances, sorry!", encoding);
290
291 mpg123_free_string(sb);
292 return;
293 }
294 bwidth = encoding_widths[encoding];
295 /* Hack! I've seen a stray zero byte before BOM. Is that supposed to happen? */
296 if(encoding != mpg123_id3_utf16be) /* UTF16be _can_ beging with a null byte! */
297 while(source_size > bwidth && source[0] == 0)
298 {
299 --source_size;
300 ++source;
301 debug("skipped leading zero");
302 }
303 if(source_size % bwidth)
304 {
305 /* When we need two bytes for a character, it's strange to have an uneven bytestream length. */
306 if(noquiet) warning2("Weird tag size %d for encoding %u - I will probably trim too early or something but I think the MP3 is broken.", (int)source_size, encoding);
307 source_size -= source_size % bwidth;
308 }
309 text_converters[encoding](sb, source, source_size, noquiet);
310 }
311
312 static unsigned char *next_text(unsigned char* prev, unsigned char encoding, size_t limit)
313 {
314 unsigned char *text = prev;
315 size_t width = encoding_widths[encoding];
316
317 /* So I go lengths to find zero or double zero...
318 Remember bug 2834636: Only check for aligned NULLs! */
319 while(text-prev < (ssize_t)limit)
320 {
321 if(text[0] == 0)
322 {
323 if(width <= limit-(text-prev))
324 {
325 size_t i = 1;
326 for(; i<width; ++i) if(text[i] != 0) break;
327
328 if(i == width) /* found a null wide enough! */
329 {
330 text += width;
331 break;
332 }
333 }
334 else return NULL; /* No full character left? This text is broken */
335 }
336
337 text += width;
338 }
339 if((size_t)(text-prev) >= limit) text = NULL;
340
341 return text;
342 }
343
344 static const char *enc_name(unsigned char enc)
345 {
346 switch(enc)
347 {
348 case 0: return "Latin 1";
349 case 1: return "UTF-16 BOM";
350 case 2: return "UTF-16 BE";
351 case 3: return "UTF-8";
352 default: return "unknown!";
353 }
354 }
355
356 static void process_text(mpg123_handle *fr, unsigned char *realdata, size_t realsize, char *id)
357 {
358 /* Text encoding $xx */
359 /* The text (encoded) ... */
360 mpg123_text *t = add_text(fr);
361 if(VERBOSE4) fprintf(stderr, "Note: Storing text from %s encoding\n", enc_name(realdata[0]));
362 if(t == NULL)
363 {
364 if(NOQUIET) error("Unable to attach new text!");
365 return;
366 }
367 memcpy(t->id, id, 4);
368 store_id3_text(&t->text, realdata, realsize, NOQUIET, fr->p.flags & MPG123_PLAIN_ID3TEXT);
369 if(VERBOSE4) fprintf(stderr, "Note: ID3v2 %c%c%c%c text frame: %s\n", id[0], id[1], id[2], id[3], t->text.p);
370 }
371
372 static void process_picture(mpg123_handle *fr, unsigned char *realdata, size_t realsize)
373 {
374 unsigned char encoding = realdata[0];
375 mpg123_picture *i = NULL;
376 unsigned char* workpoint;
377 if(realsize == 0)
378 {
379 debug("Empty id3 data!");
380 return;
381 }
382 if(VERBOSE4) fprintf(stderr, "Note: Storing picture from APIC frame.\n");
383 /* decompose realdata accordingly */
384 i = add_picture(fr);
385 if(i == NULL)
386 {
387 if(NOQUIET) error("Unable to attach new picture!");
388 return;
389 }
390 realdata++; realsize--;
391 /* get mime type (encoding is always latin-1) */
392 workpoint = next_text(realdata, 0, realsize);
393 if (workpoint == NULL) {
394 pop_picture(fr);
395 if (NOQUIET) error("Unable to get mime type for picture; skipping picture.");
396 return;
397 }
398 id3_to_utf8(&i->mime_type, 0, realdata, workpoint - realdata, NOQUIET);
399 realsize -= workpoint - realdata;
400 realdata = workpoint;
401 /* get picture type */
402 i->type = realdata[0];
403 realdata++; realsize--;
404 /* get description (encoding is encoding) */
405 workpoint = next_text(realdata, encoding, realsize);
406 if (workpoint == NULL) {
407 if (NOQUIET) error("Unable to get description for picture; skipping picture.");
408 pop_picture(fr);
409 return;
410 }
411 id3_to_utf8(&i->description, encoding, realdata, workpoint - realdata, NOQUIET);
412 realsize -= workpoint - realdata;
413 if (realsize == 0) {
414 if (NOQUIET) error("No picture data defined; skipping picture.");
415 pop_picture(fr);
416 return;
417 }
418 /* store_id3_picture(i, picture, realsize, NOQUIET)) */
419 i->data = (unsigned char*)malloc(realsize);
420 if (i->data == NULL) {
421 if (NOQUIET) error("Unable to allocate memory for picture; skipping picture");
422 pop_picture(fr);
423 return;
424 }
425 memcpy(i->data, workpoint, realsize);
426 i->size = realsize;
427 if(VERBOSE4) fprintf(stderr, "Note: ID3v2 APIC picture frame of type: %d\n", i->type);
428 }
429
430 /* Store a new comment that perhaps is a RVA / RVA_ALBUM/AUDIOPHILE / RVA_MIX/RADIO one
431 Special gimmik: It also stores USLT to the texts. Stucture is the same as for comments. */
432 static void process_comment(mpg123_handle *fr, enum frame_types tt, unsigned char *realdata, size_t realsize, int rva_level, char *id)
433 {
434 /* Text encoding $xx */
435 /* Language $xx xx xx */
436 /* Short description (encoded!) <text> $00 (00) */
437 /* Then the comment text (encoded) ... */
438 unsigned char encoding = realdata[0];
439 unsigned char *lang = realdata+1; /* I'll only use the 3 bytes! */
440 unsigned char *descr = realdata+4;
441 unsigned char *text = NULL;
442 mpg123_text *xcom = NULL;
443 mpg123_text localcom; /* UTF-8 variant for local processing. */
444
445 if(realsize < (size_t)(descr-realdata))
446 {
447 if(NOQUIET) error1("Invalid frame size of %"SIZE_P" (too small for anything).", (size_p)realsize);
448 return;
449 }
450 xcom = (tt == uslt ? add_text(fr) : add_comment(fr));
451 if(VERBOSE4) fprintf(stderr, "Note: Storing comment from %s encoding\n", enc_name(realdata[0]));
452 if(xcom == NULL)
453 {
454 if(NOQUIET) error("Unable to attach new comment!");
455 return;
456 }
457 memcpy(xcom->lang, lang, 3);
458 memcpy(xcom->id, id, 4);
459 /* Now I can abuse a byte from lang for the encoding. */
460 descr[-1] = encoding;
461 /* Be careful with finding the end of description, I have to honor encoding here. */
462 text = next_text(descr, encoding, realsize-(descr-realdata));
463 if(text == NULL)
464 {
465 if(NOQUIET) error("No comment text / valid description?");
466 pop_comment(fr);
467 return;
468 }
469
470 init_mpg123_text(&localcom);
471 /* Store the text, without translation to UTF-8, but for comments always a local copy in UTF-8.
472 Reminder: No bailing out from here on without freeing the local comment data! */
473 store_id3_text(&xcom->description, descr-1, text-descr+1, NOQUIET, fr->p.flags & MPG123_PLAIN_ID3TEXT);
474 if(tt == comment)
475 store_id3_text(&localcom.description, descr-1, text-descr+1, NOQUIET, 0);
476
477 text[-1] = encoding; /* Byte abusal for encoding... */
478 store_id3_text(&xcom->text, text-1, realsize+1-(text-realdata), NOQUIET, fr->p.flags & MPG123_PLAIN_ID3TEXT);
479 /* Remember: I will probably decode the above (again) for rva comment checking. So no messing around, please. */
480
481 if(VERBOSE4) /* Do _not_ print the verbatim text: The encoding might be funny! */
482 {
483 fprintf(stderr, "Note: ID3 comm/uslt desc of length %"SIZE_P".\n", (size_p)xcom->description.fill);
484 fprintf(stderr, "Note: ID3 comm/uslt text of length %"SIZE_P".\n", (size_p)xcom->text.fill);
485 }
486 /* Look out for RVA info only when we really deal with a straight comment. */
487 if(tt == comment && localcom.description.fill > 0)
488 {
489 int rva_mode = -1; /* mix / album */
490 if( !strcasecmp(localcom.description.p, "rva")
491 || !strcasecmp(localcom.description.p, "rva_mix")
492 || !strcasecmp(localcom.description.p, "rva_track")
493 || !strcasecmp(localcom.description.p, "rva_radio") )
494 rva_mode = 0;
495 else if( !strcasecmp(localcom.description.p, "rva_album")
496 || !strcasecmp(localcom.description.p, "rva_audiophile")
497 || !strcasecmp(localcom.description.p, "rva_user") )
498 rva_mode = 1;
499 if((rva_mode > -1) && (fr->rva.level[rva_mode] <= rva_level))
500 {
501 /* Only translate the contents in here where we really need them. */
502 store_id3_text(&localcom.text, text-1, realsize+1-(text-realdata), NOQUIET, 0);
503 if(localcom.text.fill > 0)
504 {
505 fr->rva.gain[rva_mode] = (float) atof(localcom.text.p);
506 if(VERBOSE3) fprintf(stderr, "Note: RVA value %fdB\n", fr->rva.gain[rva_mode]);
507 fr->rva.peak[rva_mode] = 0;
508 fr->rva.level[rva_mode] = rva_level;
509 }
510 }
511 }
512 /* Make sure to free the local memory... */
513 free_mpg123_text(&localcom);
514 }
515
516 static void process_extra(mpg123_handle *fr, unsigned char* realdata, size_t realsize, int rva_level, char *id)
517 {
518 /* Text encoding $xx */
519 /* Description ... $00 (00) */
520 /* Text ... */
521 unsigned char encoding = realdata[0];
522 unsigned char *descr = realdata+1; /* remember, the encoding is descr[-1] */
523 unsigned char *text;
524 mpg123_text *xex;
525 mpg123_text localex;
526
527 if((int)realsize < descr-realdata)
528 {
529 if(NOQUIET) error1("Invalid frame size of %lu (too small for anything).", (unsigned long)realsize);
530 return;
531 }
532 text = next_text(descr, encoding, realsize-(descr-realdata));
533 if(VERBOSE4) fprintf(stderr, "Note: Storing extra from %s encoding\n", enc_name(realdata[0]));
534 if(text == NULL)
535 {
536 if(NOQUIET) error("No extra frame text / valid description?");
537 return;
538 }
539 xex = add_extra(fr);
540 if(xex == NULL)
541 {
542 if(NOQUIET) error("Unable to attach new extra text!");
543 return;
544 }
545 memcpy(xex->id, id, 4);
546 init_mpg123_text(&localex); /* For our local copy. */
547
548 /* The outside storage gets reencoded to UTF-8 only if not requested otherwise.
549 Remember that we really need the -1 here to hand in the encoding byte!*/
550 store_id3_text(&xex->description, descr-1, text-descr+1, NOQUIET, fr->p.flags & MPG123_PLAIN_ID3TEXT);
551 /* Our local copy is always stored in UTF-8! */
552 store_id3_text(&localex.description, descr-1, text-descr+1, NOQUIET, 0);
553 /* At first, only store the outside copy of the payload. We may not need the local copy. */
554 text[-1] = encoding;
555 store_id3_text(&xex->text, text-1, realsize-(text-realdata)+1, NOQUIET, fr->p.flags & MPG123_PLAIN_ID3TEXT);
556
557 /* Now check if we would like to interpret this extra info for RVA. */
558 if(localex.description.fill > 0)
559 {
560 int is_peak = 0;
561 int rva_mode = -1; /* mix / album */
562
563 if(!strncasecmp(localex.description.p, "replaygain_track_",17))
564 {
565 if(VERBOSE3) fprintf(stderr, "Note: RVA ReplayGain track gain/peak\n");
566
567 rva_mode = 0;
568 if(!strcasecmp(localex.description.p, "replaygain_track_peak")) is_peak = 1;
569 else if(strcasecmp(localex.description.p, "replaygain_track_gain")) rva_mode = -1;
570 }
571 else
572 if(!strncasecmp(localex.description.p, "replaygain_album_",17))
573 {
574 if(VERBOSE3) fprintf(stderr, "Note: RVA ReplayGain album gain/peak\n");
575
576 rva_mode = 1;
577 if(!strcasecmp(localex.description.p, "replaygain_album_peak")) is_peak = 1;
578 else if(strcasecmp(localex.description.p, "replaygain_album_gain")) rva_mode = -1;
579 }
580 if((rva_mode > -1) && (fr->rva.level[rva_mode] <= rva_level))
581 {
582 /* Now we need the translated copy of the data. */
583 store_id3_text(&localex.text, text-1, realsize-(text-realdata)+1, NOQUIET, 0);
584 if(localex.text.fill > 0)
585 {
586 if(is_peak)
587 {
588 fr->rva.peak[rva_mode] = (float) atof(localex.text.p);
589 if(VERBOSE3) fprintf(stderr, "Note: RVA peak %f\n", fr->rva.peak[rva_mode]);
590 }
591 else
592 {
593 fr->rva.gain[rva_mode] = (float) atof(localex.text.p);
594 if(VERBOSE3) fprintf(stderr, "Note: RVA gain %fdB\n", fr->rva.gain[rva_mode]);
595 }
596 fr->rva.level[rva_mode] = rva_level;
597 }
598 }
599 }
600
601 free_mpg123_text(&localex);
602 }
603
604 /* Make a ID3v2.3+ 4-byte ID from a ID3v2.2 3-byte ID
605 Note that not all frames survived to 2.4; the mapping goes to 2.3 .
606 A notable miss is the old RVA frame, which is very unspecific anyway.
607 This function returns -1 when a not known 3 char ID was encountered, 0 otherwise. */
608 static int promote_framename(mpg123_handle *fr, char *id) /* fr because of VERBOSE macros */
609 {
610 size_t i;
611 char *old[] =
612 {
613 "COM", "TAL", "TBP", "TCM", "TCO", "TCR", "TDA", "TDY", "TEN", "TFT",
614 "TIM", "TKE", "TLA", "TLE", "TMT", "TOA", "TOF", "TOL", "TOR", "TOT",
615 "TP1", "TP2", "TP3", "TP4", "TPA", "TPB", "TRC", "TDA", "TRK", "TSI",
616 "TSS", "TT1", "TT2", "TT3", "TXT", "TXX", "TYE"
617 };
618 char *new[] =
619 {
620 "COMM", "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDAT", "TDLY", "TENC", "TFLT",
621 "TIME", "TKEY", "TLAN", "TLEN", "TMED", "TOPE", "TOFN", "TOLY", "TORY", "TOAL",
622 "TPE1", "TPE2", "TPE3", "TPE4", "TPOS", "TPUB", "TSRC", "TRDA", "TRCK", "TSIZ",
623 "TSSE", "TIT1", "TIT2", "TIT3", "TEXT", "TXXX", "TYER"
624 };
625 for(i=0; i<sizeof(old)/sizeof(char*); ++i)
626 {
627 if(!strncmp(id, old[i], 3))
628 {
629 memcpy(id, new[i], 4);
630 if(VERBOSE3) fprintf(stderr, "Translated ID3v2.2 frame %s to %s\n", old[i], new[i]);
631 return 0;
632 }
633 }
634 if(VERBOSE3) fprintf(stderr, "Ignoring untranslated ID3v2.2 frame %c%c%c\n", id[0], id[1], id[2]);
635 return -1;
636 }
637
638 #endif /* NO_ID3V2 */
639
640 /*
641 trying to parse ID3v2.3 and ID3v2.4 tags...
642
643 returns: 0: bad or just unparseable tag
644 1: good, (possibly) new tag info
645 <0: reader error (may need more data feed, try again)
646 */
647 int parse_new_id3(mpg123_handle *fr, unsigned long first4bytes)
648 {
649 #define UNSYNC_FLAG 128
650 #define EXTHEAD_FLAG 64
651 #define EXP_FLAG 32
652 #define FOOTER_FLAG 16
653 #define UNKNOWN_FLAGS 15 /* 00001111*/
654 unsigned char buf[6];
655 unsigned long length=0;
656 unsigned char flags = 0;
657 int ret = 1;
658 int ret2;
659 unsigned char major = first4bytes & 0xff;
660 debug1("ID3v2: major tag version: %i", major);
661 if(major == 0xff) return 0; /* Invalid... */
662 if((ret2 = fr->rd->read_frame_body(fr, buf, 6)) < 0) /* read more header information */
663 return ret2;
664
665 if(buf[0] == 0xff) return 0; /* Revision, will never be 0xff. */
666
667 /* second new byte are some nice flags, if these are invalid skip the whole thing */
668 flags = buf[1];
669 debug1("ID3v2: flags 0x%08x", flags);
670 /* use 4 bytes from buf to construct 28bit uint value and return 1; return 0 if bytes are not synchsafe */
671 #define synchsafe_to_long(buf,res) \
672 ( \
673 (((buf)[0]|(buf)[1]|(buf)[2]|(buf)[3]) & 0x80) ? 0 : \
674 (res = (((unsigned long) (buf)[0]) << 21) \
675 | (((unsigned long) (buf)[1]) << 14) \
676 | (((unsigned long) (buf)[2]) << 7) \
677 | ((unsigned long) (buf)[3]) \
678 ,1) \
679 )
680 /* id3v2.3 does not store synchsafe frame sizes, but synchsafe tag size - doh! */
681 #define bytes_to_long(buf,res) \
682 ( \
683 major == 3 ? \
684 (res = (((unsigned long) (buf)[0]) << 24) \
685 | (((unsigned long) (buf)[1]) << 16) \
686 | (((unsigned long) (buf)[2]) << 8) \
687 | ((unsigned long) (buf)[3]) \
688 ,1) : synchsafe_to_long(buf,res) \
689 )
690 /* for id3v2.2 only */
691 #define threebytes_to_long(buf,res) \
692 ( \
693 res = (((unsigned long) (buf)[0]) << 16) \
694 | (((unsigned long) (buf)[1]) << 8) \
695 | ((unsigned long) (buf)[2]) \
696 )
697
698 /* length-10 or length-20 (footer present); 4 synchsafe integers == 28 bit number */
699 /* we have already read 10 bytes, so left are length or length+10 bytes belonging to tag */
700 if(!synchsafe_to_long(buf+2,length))
701 {
702 if(NOQUIET) error4("Bad tag length (not synchsafe): 0x%02x%02x%02x%02x; You got a bad ID3 tag here.", buf[2],buf[3],buf[4],buf[5]);
703 return 0;
704 }
705 debug1("ID3v2: tag data length %lu", length);
706 #ifndef NO_ID3V2
707 if(VERBOSE2) fprintf(stderr,"Note: ID3v2.%i rev %i tag of %lu bytes\n", major, buf[0], length);
708 /* skip if unknown version/scary flags, parse otherwise */
709 if(fr->p.flags & MPG123_SKIP_ID3V2 || ((flags & UNKNOWN_FLAGS) || (major > 4) || (major < 2)))
710 {
711 if(NOQUIET)
712 {
713 if(fr->p.flags & MPG123_SKIP_ID3V2)
714 {
715 if(VERBOSE3) fprintf(stderr, "Note: Skipping ID3v2 tag per user request.\n");
716 }
717 else /* Must be because of scary Tag properties. */
718 warning2("ID3v2: Won't parse the ID3v2 tag with major version %u and flags 0x%xu - some extra code may be needed", major, flags);
719 }
720 #endif
721 if((ret2 = fr->rd->skip_bytes(fr,length)) < 0) /* will not store data in backbuff! */
722 ret = ret2;
723 #ifndef NO_ID3V2
724 }
725 else
726 {
727 unsigned char* tagdata = NULL;
728 fr->id3v2.version = major;
729 /* try to interpret that beast */
730 if((tagdata = (unsigned char*) malloc(length+1)) != NULL)
731 {
732 debug("ID3v2: analysing frames...");
733 if((ret2 = fr->rd->read_frame_body(fr,tagdata,length)) > 0)
734 {
735 unsigned long tagpos = 0;
736 debug1("ID3v2: have read at all %lu bytes for the tag now", (unsigned long)length+6);
737 /* going to apply strlen for strings inside frames, make sure that it doesn't overflow! */
738 tagdata[length] = 0;
739 if(flags & EXTHEAD_FLAG)
740 {
741 debug("ID3v2: skipping extended header");
742 if(!bytes_to_long(tagdata, tagpos))
743 {
744 ret = 0;
745 if(NOQUIET) error4("Bad (non-synchsafe) tag offset: 0x%02x%02x%02x%02x", tagdata[0], tagdata[1], tagdata[2], tagdata[3]);
746 }
747 }
748 if(ret > 0)
749 {
750 char id[5];
751 unsigned long framesize;
752 unsigned long fflags; /* need 16 bits, actually */
753 id[4] = 0;
754 /* pos now advanced after ext head, now a frame has to follow */
755 while(tagpos < length-10) /* I want to read at least a full header */
756 {
757 int i = 0;
758 unsigned long pos = tagpos;
759 int head_part = fr->id3v2.version == 2 ? 3 : 4; /* bytes of frame title and of framesize value */
760 /* level 1,2,3 - 0 is info from lame/info tag! */
761 /* rva tags with ascending significance, then general frames */
762 enum frame_types tt = unknown;
763 /* we may have entered the padding zone or any other strangeness: check if we have valid frame id characters */
764 for(i=0; i< head_part; ++i)
765 if( !( ((tagdata[tagpos+i] > 47) && (tagdata[tagpos+i] < 58))
766 || ((tagdata[tagpos+i] > 64) && (tagdata[tagpos+i] < 91)) ) )
767 {
768 debug5("ID3v2: real tag data apparently ended after %lu bytes with 0x%02x%02x%02x%02x", tagpos, tagdata[tagpos], tagdata[tagpos+1], tagdata[tagpos+2], tagdata[tagpos+3]);
769 /* This is no hard error... let's just hope that we got something meaningful already (ret==1 in that case). */
770 goto tagparse_cleanup; /* Need to escape two loops here. */
771 }
772 if(ret > 0)
773 {
774 /* 4 or 3 bytes id */
775 strncpy(id, (char*) tagdata+pos, head_part);
776 id[head_part] = 0; /* terminate for 3 or 4 bytes */
777 pos += head_part;
778 tagpos += head_part;
779 /* size as 32 bits or 28 bits */
780 if(fr->id3v2.version == 2) threebytes_to_long(tagdata+pos, framesize);
781 else
782 if(!bytes_to_long(tagdata+pos, framesize))
783 {
784 /* Just assume that up to now there was some good data. */
785 if(NOQUIET) error1("ID3v2: non-syncsafe size of %s frame, skipping the remainder of tag", id);
786 break;
787 }
788 if(VERBOSE3) fprintf(stderr, "Note: ID3v2 %s frame of size %lu\n", id, framesize);
789 tagpos += head_part + framesize; /* the important advancement in whole tag */
790 if(tagpos > length)
791 {
792 if(NOQUIET) error("Whoa! ID3v2 frame claims to be larger than the whole rest of the tag.");
793 break;
794 }
795 pos += head_part;
796 if(fr->id3v2.version > 2)
797 {
798 fflags = (((unsigned long) tagdata[pos]) << 8) | ((unsigned long) tagdata[pos+1]);
799 pos += 2;
800 tagpos += 2;
801 }
802 else fflags = 0;
803 /* for sanity, after full parsing tagpos should be == pos */
804 /* debug4("ID3v2: found %s frame, size %lu (as bytes: 0x%08lx), flags 0x%016lx", id, framesize, framesize, fflags); */
805 /* %0abc0000 %0h00kmnp */
806 #define BAD_FFLAGS (unsigned long) 36784
807 #define PRES_TAG_FFLAG 16384
808 #define PRES_FILE_FFLAG 8192
809 #define READ_ONLY_FFLAG 4096
810 #define GROUP_FFLAG 64
811 #define COMPR_FFLAG 8
812 #define ENCR_FFLAG 4
813 #define UNSYNC_FFLAG 2
814 #define DATLEN_FFLAG 1
815 if(head_part < 4 && promote_framename(fr, id) != 0) continue;
816
817 /* shall not or want not handle these */
818 if(fflags & (BAD_FFLAGS | COMPR_FFLAG | ENCR_FFLAG))
819 {
820 if(NOQUIET) warning("ID3v2: skipping invalid/unsupported frame");
821 continue;
822 }
823
824 for(i = 0; i < KNOWN_FRAMES; ++i)
825 if(!strncmp(frame_type[i], id, 4)){ tt = i; break; }
826
827 if(id[0] == 'T' && tt != extra) tt = text;
828
829 if(tt != unknown)
830 {
831 int rva_mode = -1; /* mix / album */
832 unsigned long realsize = framesize;
833 unsigned char* realdata = tagdata+pos;
834 if((flags & UNSYNC_FLAG) || (fflags & UNSYNC_FFLAG))
835 {
836 unsigned long ipos = 0;
837 unsigned long opos = 0;
838 debug("Id3v2: going to de-unsync the frame data");
839 /* de-unsync: FF00 -> FF; real FF00 is simply represented as FF0000 ... */
840 /* damn, that means I have to delete bytes from withing the data block... thus need temporal storage */
841 /* standard mandates that de-unsync should always be safe if flag is set */
842 realdata = (unsigned char*) malloc(framesize); /* will need <= bytes */
843 if(realdata == NULL)
844 {
845 if(NOQUIET) error("ID3v2: unable to allocate working buffer for de-unsync");
846 continue;
847 }
848 /* now going byte per byte through the data... */
849 realdata[0] = tagdata[pos];
850 opos = 1;
851 for(ipos = pos+1; ipos < pos+framesize; ++ipos)
852 {
853 if(!((tagdata[ipos] == 0) && (tagdata[ipos-1] == 0xff)))
854 {
855 realdata[opos++] = tagdata[ipos];
856 }
857 }
858 realsize = opos;
859 debug2("ID3v2: de-unsync made %lu out of %lu bytes", realsize, framesize);
860 }
861 pos = 0; /* now at the beginning again... */
862 switch(tt)
863 {
864 case comment:
865 case uslt:
866 process_comment(fr, tt, realdata, realsize, comment+1, id);
867 break;
868 case extra: /* perhaps foobar2000's work */
869 process_extra(fr, realdata, realsize, extra+1, id);
870 break;
871 case rva2: /* "the" RVA tag */
872 {
873 /* starts with null-terminated identification */
874 if(VERBOSE3) fprintf(stderr, "Note: RVA2 identification \"%s\"\n", realdata);
875 /* default: some individual value, mix mode */
876 rva_mode = 0;
877 if( !strncasecmp((char*)realdata, "album", 5)
878 || !strncasecmp((char*)realdata, "audiophile", 10)
879 || !strncasecmp((char*)realdata, "user", 4))
880 rva_mode = 1;
881 if(fr->rva.level[rva_mode] <= rva2+1)
882 {
883 pos += strlen((char*) realdata) + 1;
884 if(realdata[pos] == 1)
885 {
886 ++pos;
887 /* only handle master channel */
888 debug("ID3v2: it is for the master channel");
889 /* two bytes adjustment, one byte for bits representing peak - n bytes, eh bits, for peak */
890 /* 16 bit signed integer = dB * 512 ... the double cast is needed to preserve the sign of negative values! */
891 fr->rva.gain[rva_mode] = (float) ( (((short)((signed char)realdata[pos])) << 8) | realdata[pos+1] ) / 512;
892 pos += 2;
893 if(VERBOSE3) fprintf(stderr, "Note: RVA value %fdB\n", fr->rva.gain[rva_mode]);
894 /* heh, the peak value is represented by a number of bits - but in what manner? Skipping that part */
895 fr->rva.peak[rva_mode] = 0;
896 fr->rva.level[rva_mode] = rva2+1;
897 }
898 }
899 }
900 break;
901 /* non-rva metainfo, simply store... */
902 case text:
903 process_text(fr, realdata, realsize, id);
904 break;
905 case picture:
906 if (fr->p.flags & MPG123_PICTURE)
907 process_picture(fr, realdata, realsize);
908
909 break;
910 default: if(NOQUIET) error1("ID3v2: unknown frame type %i", tt);
911 }
912 if((flags & UNSYNC_FLAG) || (fflags & UNSYNC_FFLAG)) free(realdata);
913 }
914 #undef BAD_FFLAGS
915 #undef PRES_TAG_FFLAG
916 #undef PRES_FILE_FFLAG
917 #undef READ_ONLY_FFLAG
918 #undef GROUP_FFLAG
919 #undef COMPR_FFLAG
920 #undef ENCR_FFLAG
921 #undef UNSYNC_FFLAG
922 #undef DATLEN_FFLAG
923 }
924 else break;
925 #undef KNOWN_FRAMES
926 }
927 }
928 }
929 else
930 {
931 /* There are tags with zero length. Strictly not an error, then. */
932 if(length > 0 && NOQUIET && ret2 != MPG123_NEED_MORE) error("ID3v2: Duh, not able to read ID3v2 tag data.");
933 ret = ret2;
934 }
935 tagparse_cleanup:
936 free(tagdata);
937 }
938 else
939 {
940 if(NOQUIET) error1("ID3v2: Arrg! Unable to allocate %lu bytes for interpreting ID3v2 data - trying to skip instead.", length);
941 if((ret2 = fr->rd->skip_bytes(fr,length)) < 0) ret = ret2; /* will not store data in backbuff! */
942 else ret = 0;
943 }
944 }
945 #endif /* NO_ID3V2 */
946 /* skip footer if present */
947 if((ret > 0) && (flags & FOOTER_FLAG) && ((ret2 = fr->rd->skip_bytes(fr,length)) < 0)) ret = ret2;
948
949 return ret;
950 #undef UNSYNC_FLAG
951 #undef EXTHEAD_FLAG
952 #undef EXP_FLAG
953 #undef FOOTER_FLAG
954 #undef UNKOWN_FLAGS
955 }
956
957 #ifndef NO_ID3V2 /* Disabling all the rest... */
958
959 static void convert_latin1(mpg123_string *sb, const unsigned char* s, size_t l, const int noquiet)
960 {
961 size_t length = l;
962 size_t i;
963 unsigned char *p;
964 /* determine real length, a latin1 character can at most take 2 in UTF8 */
965 for(i=0; i<l; ++i)
966 if(s[i] >= 0x80) ++length;
967
968 debug1("UTF-8 length: %lu", (unsigned long)length);
969 /* one extra zero byte for paranoia */
970 if(!mpg123_resize_string(sb, length+1)){ mpg123_free_string(sb); return ; }
971
972 p = (unsigned char*) sb->p; /* Signedness doesn't matter but it shows I thought about the non-issue */
973 for(i=0; i<l; ++i)
974 if(s[i] < 0x80){ *p = s[i]; ++p; }
975 else /* two-byte encoding */
976 {
977 *p = 0xc0 | (s[i]>>6);
978 *(p+1) = 0x80 | (s[i] & 0x3f);
979 p+=2;
980 }
981
982 sb->p[length] = 0;
983 sb->fill = length+1;
984 }
985
986 /*
987 Check if we have a byte oder mark(s) there, return:
988 -1: little endian
989 0: no BOM
990 1: big endian
991
992 This modifies source and len to indicate the data _after_ the BOM(s).
993 Note on nasty data: The last encountered BOM determines the endianness.
994 I have seen data with multiple BOMS, namely from "the" id3v2 program.
995 Not nice, but what should I do?
996 */
997 static int check_bom(const unsigned char** source, size_t *len)
998 {
999 int this_bom = 0;
1000 int further_bom = 0;
1001
1002 if(*len < 2) return 0;
1003
1004 if((*source)[0] == 0xff && (*source)[1] == 0xfe)
1005 this_bom = -1;
1006
1007 if((*source)[0] == 0xfe && (*source)[1] == 0xff)
1008 this_bom = 1;
1009
1010 /* Skip the detected BOM. */
1011 if(this_bom != 0)
1012 {
1013 *source += 2;
1014 *len -= 2;
1015 /* Check for following BOMs. The last one wins! */
1016 further_bom = check_bom(source, len);
1017 if(further_bom == 0) return this_bom; /* End of the recursion. */
1018 else return further_bom;
1019 }
1020 else return 0;
1021 }
1022
1023 #define FULLPOINT(f,s) ( (((f)&0x3ff)<<10) + ((s)&0x3ff) + 0x10000 )
1024 /* Remember: There's a limit at 0x1ffff. */
1025 #define UTF8LEN(x) ( (x)<0x80 ? 1 : ((x)<0x800 ? 2 : ((x)<0x10000 ? 3 : 4)))
1026 static void convert_utf16bom(mpg123_string *sb, const unsigned char* s, size_t l, const int noquiet)
1027 {
1028 size_t i;
1029 size_t n; /* number bytes that make up full pairs */
1030 unsigned char *p;
1031 size_t length = 0; /* the resulting UTF-8 length */
1032 /* Determine real length... extreme case can be more than utf-16 length. */
1033 size_t high = 0;
1034 size_t low = 1;
1035 int bom_endian;
1036
1037 debug1("convert_utf16 with length %lu", (unsigned long)l);
1038
1039 bom_endian = check_bom(&s, &l);
1040 debug1("UTF16 endianness check: %i", bom_endian);
1041
1042 if(bom_endian == -1) /* little-endian */
1043 {
1044 high = 1; /* The second byte is the high byte. */
1045 low = 0; /* The first byte is the low byte. */
1046 }
1047
1048 n = (l/2)*2; /* number bytes that make up full pairs */
1049
1050 /* first: get length, check for errors -- stop at first one */
1051 for(i=0; i < n; i+=2)
1052 {
1053 unsigned long point = ((unsigned long) s[i+high]<<8) + s[i+low];
1054 if((point & 0xd800) == 0xd800) /* lead surrogate */
1055 {
1056 unsigned short second = (i+3 < l) ? (s[i+2+high]<<8) + s[i+2+low] : 0;
1057 if((second & 0xdc00) == 0xdc00) /* good... */
1058 {
1059 point = FULLPOINT(point,second);
1060 length += UTF8LEN(point); /* possibly 4 bytes */
1061 i+=2; /* We overstepped one word. */
1062 }
1063 else /* if no valid pair, break here */
1064 {
1065 if(noquiet) error2("Invalid UTF16 surrogate pair at %li (0x%04lx).", (unsigned long)i, point);
1066 n = i; /* Forget the half pair, END! */
1067 break;
1068 }
1069 }
1070 else length += UTF8LEN(point); /* 1,2 or 3 bytes */
1071 }
1072
1073 if(!mpg123_resize_string(sb, length+1)){ mpg123_free_string(sb); return ; }
1074
1075 /* Now really convert, skip checks as these have been done just before. */
1076 p = (unsigned char*) sb->p; /* Signedness doesn't matter but it shows I thought about the non-issue */
1077 for(i=0; i < n; i+=2)
1078 {
1079 unsigned long codepoint = ((unsigned long) s[i+high]<<8) + s[i+low];
1080 if((codepoint & 0xd800) == 0xd800) /* lead surrogate */
1081 {
1082 unsigned short second = (s[i+2+high]<<8) + s[i+2+low];
1083 codepoint = FULLPOINT(codepoint,second);
1084 i+=2; /* We overstepped one word. */
1085 }
1086 if(codepoint < 0x80) *p++ = (unsigned char) codepoint;
1087 else if(codepoint < 0x800)
1088 {
1089 *p++ = (unsigned char) (0xc0 | (codepoint>>6));
1090 *p++ = (unsigned char) (0x80 | (codepoint & 0x3f));
1091 }
1092 else if(codepoint < 0x10000)
1093 {
1094 *p++ = (unsigned char) (0xe0 | (codepoint>>12));
1095 *p++ = 0x80 | ((codepoint>>6) & 0x3f);
1096 *p++ = 0x80 | (codepoint & 0x3f);
1097 }
1098 else if (codepoint < 0x200000)
1099 {
1100 *p++ = (unsigned char) (0xf0 | codepoint>>18);
1101 *p++ = (unsigned char) (0x80 | ((codepoint>>12) & 0x3f));
1102 *p++ = (unsigned char) (0x80 | ((codepoint>>6) & 0x3f));
1103 *p++ = (unsigned char) (0x80 | (codepoint & 0x3f));
1104 } /* ignore bigger ones (that are not possible here anyway) */
1105 }
1106 sb->p[sb->size-1] = 0; /* paranoia... */
1107 sb->fill = sb->size;
1108 }
1109 #undef UTF8LEN
1110 #undef FULLPOINT
1111
1112 static void convert_utf8(mpg123_string *sb, const unsigned char* source, size_t len, const int noquiet)
1113 {
1114 if(mpg123_resize_string(sb, len+1))
1115 {
1116 memcpy(sb->p, source, len);
1117 sb->p[len] = 0;
1118 sb->fill = len+1;
1119 }
1120 else mpg123_free_string(sb);
1121 }
1122
1123 #endif