[LIBMPG123]
[reactos.git] / reactos / sdk / 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 #ifndef NO_ID3V2
660 int skiptag = 0;
661 #endif
662 unsigned char major = first4bytes & 0xff;
663 debug1("ID3v2: major tag version: %i", major);
664 if(major == 0xff) return 0; /* Invalid... */
665 if((ret2 = fr->rd->read_frame_body(fr, buf, 6)) < 0) /* read more header information */
666 return ret2;
667
668 if(buf[0] == 0xff) return 0; /* Revision, will never be 0xff. */
669
670 /* second new byte are some nice flags, if these are invalid skip the whole thing */
671 flags = buf[1];
672 debug1("ID3v2: flags 0x%08x", flags);
673 /* use 4 bytes from buf to construct 28bit uint value and return 1; return 0 if bytes are not synchsafe */
674 #define synchsafe_to_long(buf,res) \
675 ( \
676 (((buf)[0]|(buf)[1]|(buf)[2]|(buf)[3]) & 0x80) ? 0 : \
677 (res = (((unsigned long) (buf)[0]) << 21) \
678 | (((unsigned long) (buf)[1]) << 14) \
679 | (((unsigned long) (buf)[2]) << 7) \
680 | ((unsigned long) (buf)[3]) \
681 ,1) \
682 )
683 /* id3v2.3 does not store synchsafe frame sizes, but synchsafe tag size - doh! */
684 #define bytes_to_long(buf,res) \
685 ( \
686 major == 3 ? \
687 (res = (((unsigned long) (buf)[0]) << 24) \
688 | (((unsigned long) (buf)[1]) << 16) \
689 | (((unsigned long) (buf)[2]) << 8) \
690 | ((unsigned long) (buf)[3]) \
691 ,1) : synchsafe_to_long(buf,res) \
692 )
693 /* for id3v2.2 only */
694 #define threebytes_to_long(buf,res) \
695 ( \
696 res = (((unsigned long) (buf)[0]) << 16) \
697 | (((unsigned long) (buf)[1]) << 8) \
698 | ((unsigned long) (buf)[2]) \
699 )
700
701 /* length-10 or length-20 (footer present); 4 synchsafe integers == 28 bit number */
702 /* we have already read 10 bytes, so left are length or length+10 bytes belonging to tag */
703 if(!synchsafe_to_long(buf+2,length))
704 {
705 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]);
706 return 0;
707 }
708 debug1("ID3v2: tag data length %lu", length);
709 #ifndef NO_ID3V2
710 if(VERBOSE2) fprintf(stderr,"Note: ID3v2.%i rev %i tag of %lu bytes\n", major, buf[0], length);
711 /* skip if unknown version/scary flags, parse otherwise */
712 if(fr->p.flags & MPG123_SKIP_ID3V2)
713 {
714 if(VERBOSE3)
715 fprintf(stderr, "Note: Skipping ID3v2 tag per user request.\n");
716 skiptag = 1;
717 }
718 if((flags & UNKNOWN_FLAGS) || (major > 4) || (major < 2))
719 {
720 if(NOQUIET)
721 warning2( "ID3v2: Won't parse the ID3v2 tag with major version"
722 " %u and flags 0x%xu - some extra code may be needed"
723 , major, flags );
724 skiptag = 1;
725 }
726 if(length < 10)
727 {
728 if(NOQUIET)
729 warning1("ID3v2: unrealistic small tag lengh %lu, skipping", length);
730 skiptag = 1;
731 }
732 if(skiptag)
733 {
734 #endif
735 if((ret2 = fr->rd->skip_bytes(fr,length)) < 0) /* will not store data in backbuff! */
736 ret = ret2;
737 #ifndef NO_ID3V2
738 }
739 else
740 {
741 unsigned char* tagdata = NULL;
742 fr->id3v2.version = major;
743 /* try to interpret that beast */
744 if((tagdata = (unsigned char*) malloc(length+1)) != NULL)
745 {
746 debug("ID3v2: analysing frames...");
747 if((ret2 = fr->rd->read_frame_body(fr,tagdata,length)) > 0)
748 {
749 unsigned long tagpos = 0;
750 debug1("ID3v2: have read at all %lu bytes for the tag now", (unsigned long)length+6);
751 /* going to apply strlen for strings inside frames, make sure that it doesn't overflow! */
752 tagdata[length] = 0;
753 if(flags & EXTHEAD_FLAG)
754 {
755 debug("ID3v2: skipping extended header");
756 if(!bytes_to_long(tagdata, tagpos))
757 {
758 ret = 0;
759 if(NOQUIET) error4("Bad (non-synchsafe) tag offset: 0x%02x%02x%02x%02x", tagdata[0], tagdata[1], tagdata[2], tagdata[3]);
760 }
761 }
762 if(ret > 0)
763 {
764 char id[5];
765 unsigned long framesize;
766 unsigned long fflags; /* need 16 bits, actually */
767 id[4] = 0;
768 /* pos now advanced after ext head, now a frame has to follow */
769 while(tagpos < length-10) /* I want to read at least a full header */
770 {
771 int i = 0;
772 unsigned long pos = tagpos;
773 int head_part = fr->id3v2.version == 2 ? 3 : 4; /* bytes of frame title and of framesize value */
774 /* level 1,2,3 - 0 is info from lame/info tag! */
775 /* rva tags with ascending significance, then general frames */
776 enum frame_types tt = unknown;
777 /* we may have entered the padding zone or any other strangeness: check if we have valid frame id characters */
778 for(i=0; i< head_part; ++i)
779 if( !( ((tagdata[tagpos+i] > 47) && (tagdata[tagpos+i] < 58))
780 || ((tagdata[tagpos+i] > 64) && (tagdata[tagpos+i] < 91)) ) )
781 {
782 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]);
783 /* This is no hard error... let's just hope that we got something meaningful already (ret==1 in that case). */
784 goto tagparse_cleanup; /* Need to escape two loops here. */
785 }
786 if(ret > 0)
787 {
788 /* 4 or 3 bytes id */
789 strncpy(id, (char*) tagdata+pos, head_part);
790 id[head_part] = 0; /* terminate for 3 or 4 bytes */
791 pos += head_part;
792 tagpos += head_part;
793 /* size as 32 bits or 28 bits */
794 if(fr->id3v2.version == 2) threebytes_to_long(tagdata+pos, framesize);
795 else
796 if(!bytes_to_long(tagdata+pos, framesize))
797 {
798 /* Just assume that up to now there was some good data. */
799 if(NOQUIET) error1("ID3v2: non-syncsafe size of %s frame, skipping the remainder of tag", id);
800 break;
801 }
802 if(VERBOSE3) fprintf(stderr, "Note: ID3v2 %s frame of size %lu\n", id, framesize);
803 tagpos += head_part + framesize; /* the important advancement in whole tag */
804 if(tagpos > length)
805 {
806 if(NOQUIET) error("Whoa! ID3v2 frame claims to be larger than the whole rest of the tag.");
807 break;
808 }
809 pos += head_part;
810 if(fr->id3v2.version > 2)
811 {
812 fflags = (((unsigned long) tagdata[pos]) << 8) | ((unsigned long) tagdata[pos+1]);
813 pos += 2;
814 tagpos += 2;
815 }
816 else fflags = 0;
817 /* for sanity, after full parsing tagpos should be == pos */
818 /* debug4("ID3v2: found %s frame, size %lu (as bytes: 0x%08lx), flags 0x%016lx", id, framesize, framesize, fflags); */
819 /* %0abc0000 %0h00kmnp */
820 #define BAD_FFLAGS (unsigned long) 36784
821 #define PRES_TAG_FFLAG 16384
822 #define PRES_FILE_FFLAG 8192
823 #define READ_ONLY_FFLAG 4096
824 #define GROUP_FFLAG 64
825 #define COMPR_FFLAG 8
826 #define ENCR_FFLAG 4
827 #define UNSYNC_FFLAG 2
828 #define DATLEN_FFLAG 1
829 if(head_part < 4 && promote_framename(fr, id) != 0) continue;
830
831 /* shall not or want not handle these */
832 if(fflags & (BAD_FFLAGS | COMPR_FFLAG | ENCR_FFLAG))
833 {
834 if(NOQUIET) warning("ID3v2: skipping invalid/unsupported frame");
835 continue;
836 }
837
838 for(i = 0; i < KNOWN_FRAMES; ++i)
839 if(!strncmp(frame_type[i], id, 4)){ tt = i; break; }
840
841 if(id[0] == 'T' && tt != extra) tt = text;
842
843 if(tt != unknown)
844 {
845 int rva_mode = -1; /* mix / album */
846 unsigned long realsize = framesize;
847 unsigned char* realdata = tagdata+pos;
848 if((flags & UNSYNC_FLAG) || (fflags & UNSYNC_FFLAG))
849 {
850 unsigned long ipos = 0;
851 unsigned long opos = 0;
852 debug("Id3v2: going to de-unsync the frame data");
853 /* de-unsync: FF00 -> FF; real FF00 is simply represented as FF0000 ... */
854 /* damn, that means I have to delete bytes from withing the data block... thus need temporal storage */
855 /* standard mandates that de-unsync should always be safe if flag is set */
856 realdata = (unsigned char*) malloc(framesize); /* will need <= bytes */
857 if(realdata == NULL)
858 {
859 if(NOQUIET) error("ID3v2: unable to allocate working buffer for de-unsync");
860 continue;
861 }
862 /* now going byte per byte through the data... */
863 realdata[0] = tagdata[pos];
864 opos = 1;
865 for(ipos = pos+1; ipos < pos+framesize; ++ipos)
866 {
867 if(!((tagdata[ipos] == 0) && (tagdata[ipos-1] == 0xff)))
868 {
869 realdata[opos++] = tagdata[ipos];
870 }
871 }
872 realsize = opos;
873 debug2("ID3v2: de-unsync made %lu out of %lu bytes", realsize, framesize);
874 }
875 pos = 0; /* now at the beginning again... */
876 switch(tt)
877 {
878 case comment:
879 case uslt:
880 process_comment(fr, tt, realdata, realsize, comment+1, id);
881 break;
882 case extra: /* perhaps foobar2000's work */
883 process_extra(fr, realdata, realsize, extra+1, id);
884 break;
885 case rva2: /* "the" RVA tag */
886 {
887 /* starts with null-terminated identification */
888 if(VERBOSE3) fprintf(stderr, "Note: RVA2 identification \"%s\"\n", realdata);
889 /* default: some individual value, mix mode */
890 rva_mode = 0;
891 if( !strncasecmp((char*)realdata, "album", 5)
892 || !strncasecmp((char*)realdata, "audiophile", 10)
893 || !strncasecmp((char*)realdata, "user", 4))
894 rva_mode = 1;
895 if(fr->rva.level[rva_mode] <= rva2+1)
896 {
897 pos += strlen((char*) realdata) + 1;
898 if(realdata[pos] == 1)
899 {
900 ++pos;
901 /* only handle master channel */
902 debug("ID3v2: it is for the master channel");
903 /* two bytes adjustment, one byte for bits representing peak - n bytes, eh bits, for peak */
904 /* 16 bit signed integer = dB * 512 ... the double cast is needed to preserve the sign of negative values! */
905 fr->rva.gain[rva_mode] = (float) ( (((short)((signed char)realdata[pos])) << 8) | realdata[pos+1] ) / 512;
906 pos += 2;
907 if(VERBOSE3) fprintf(stderr, "Note: RVA value %fdB\n", fr->rva.gain[rva_mode]);
908 /* heh, the peak value is represented by a number of bits - but in what manner? Skipping that part */
909 fr->rva.peak[rva_mode] = 0;
910 fr->rva.level[rva_mode] = rva2+1;
911 }
912 }
913 }
914 break;
915 /* non-rva metainfo, simply store... */
916 case text:
917 process_text(fr, realdata, realsize, id);
918 break;
919 case picture:
920 if (fr->p.flags & MPG123_PICTURE)
921 process_picture(fr, realdata, realsize);
922
923 break;
924 default: if(NOQUIET) error1("ID3v2: unknown frame type %i", tt);
925 }
926 if((flags & UNSYNC_FLAG) || (fflags & UNSYNC_FFLAG)) free(realdata);
927 }
928 #undef BAD_FFLAGS
929 #undef PRES_TAG_FFLAG
930 #undef PRES_FILE_FFLAG
931 #undef READ_ONLY_FFLAG
932 #undef GROUP_FFLAG
933 #undef COMPR_FFLAG
934 #undef ENCR_FFLAG
935 #undef UNSYNC_FFLAG
936 #undef DATLEN_FFLAG
937 }
938 else break;
939 #undef KNOWN_FRAMES
940 }
941 }
942 }
943 else
944 {
945 /* There are tags with zero length. Strictly not an error, then. */
946 if(length > 0 && NOQUIET && ret2 != MPG123_NEED_MORE) error("ID3v2: Duh, not able to read ID3v2 tag data.");
947 ret = ret2;
948 }
949 tagparse_cleanup:
950 free(tagdata);
951 }
952 else
953 {
954 if(NOQUIET) error1("ID3v2: Arrg! Unable to allocate %lu bytes for interpreting ID3v2 data - trying to skip instead.", length);
955 if((ret2 = fr->rd->skip_bytes(fr,length)) < 0) ret = ret2; /* will not store data in backbuff! */
956 else ret = 0;
957 }
958 }
959 #endif /* NO_ID3V2 */
960 /* skip footer if present */
961 if((ret > 0) && (flags & FOOTER_FLAG) && ((ret2 = fr->rd->skip_bytes(fr,length)) < 0)) ret = ret2;
962
963 return ret;
964 #undef UNSYNC_FLAG
965 #undef EXTHEAD_FLAG
966 #undef EXP_FLAG
967 #undef FOOTER_FLAG
968 #undef UNKOWN_FLAGS
969 }
970
971 #ifndef NO_ID3V2 /* Disabling all the rest... */
972
973 static void convert_latin1(mpg123_string *sb, const unsigned char* s, size_t l, const int noquiet)
974 {
975 size_t length = l;
976 size_t i;
977 unsigned char *p;
978 /* determine real length, a latin1 character can at most take 2 in UTF8 */
979 for(i=0; i<l; ++i)
980 if(s[i] >= 0x80) ++length;
981
982 debug1("UTF-8 length: %lu", (unsigned long)length);
983 /* one extra zero byte for paranoia */
984 if(!mpg123_resize_string(sb, length+1)){ mpg123_free_string(sb); return ; }
985
986 p = (unsigned char*) sb->p; /* Signedness doesn't matter but it shows I thought about the non-issue */
987 for(i=0; i<l; ++i)
988 if(s[i] < 0x80){ *p = s[i]; ++p; }
989 else /* two-byte encoding */
990 {
991 *p = 0xc0 | (s[i]>>6);
992 *(p+1) = 0x80 | (s[i] & 0x3f);
993 p+=2;
994 }
995
996 sb->p[length] = 0;
997 sb->fill = length+1;
998 }
999
1000 /*
1001 Check if we have a byte oder mark(s) there, return:
1002 -1: little endian
1003 0: no BOM
1004 1: big endian
1005
1006 This modifies source and len to indicate the data _after_ the BOM(s).
1007 Note on nasty data: The last encountered BOM determines the endianness.
1008 I have seen data with multiple BOMS, namely from "the" id3v2 program.
1009 Not nice, but what should I do?
1010 */
1011 static int check_bom(const unsigned char** source, size_t *len)
1012 {
1013 int this_bom = 0;
1014 int further_bom = 0;
1015
1016 if(*len < 2) return 0;
1017
1018 if((*source)[0] == 0xff && (*source)[1] == 0xfe)
1019 this_bom = -1;
1020
1021 if((*source)[0] == 0xfe && (*source)[1] == 0xff)
1022 this_bom = 1;
1023
1024 /* Skip the detected BOM. */
1025 if(this_bom != 0)
1026 {
1027 *source += 2;
1028 *len -= 2;
1029 /* Check for following BOMs. The last one wins! */
1030 further_bom = check_bom(source, len);
1031 if(further_bom == 0) return this_bom; /* End of the recursion. */
1032 else return further_bom;
1033 }
1034 else return 0;
1035 }
1036
1037 #define FULLPOINT(f,s) ( (((f)&0x3ff)<<10) + ((s)&0x3ff) + 0x10000 )
1038 /* Remember: There's a limit at 0x1ffff. */
1039 #define UTF8LEN(x) ( (x)<0x80 ? 1 : ((x)<0x800 ? 2 : ((x)<0x10000 ? 3 : 4)))
1040 static void convert_utf16bom(mpg123_string *sb, const unsigned char* s, size_t l, const int noquiet)
1041 {
1042 size_t i;
1043 size_t n; /* number bytes that make up full pairs */
1044 unsigned char *p;
1045 size_t length = 0; /* the resulting UTF-8 length */
1046 /* Determine real length... extreme case can be more than utf-16 length. */
1047 size_t high = 0;
1048 size_t low = 1;
1049 int bom_endian;
1050
1051 debug1("convert_utf16 with length %lu", (unsigned long)l);
1052
1053 bom_endian = check_bom(&s, &l);
1054 debug1("UTF16 endianness check: %i", bom_endian);
1055
1056 if(bom_endian == -1) /* little-endian */
1057 {
1058 high = 1; /* The second byte is the high byte. */
1059 low = 0; /* The first byte is the low byte. */
1060 }
1061
1062 n = (l/2)*2; /* number bytes that make up full pairs */
1063
1064 /* first: get length, check for errors -- stop at first one */
1065 for(i=0; i < n; i+=2)
1066 {
1067 unsigned long point = ((unsigned long) s[i+high]<<8) + s[i+low];
1068 if((point & 0xfc00) == 0xd800) /* lead surrogate */
1069 {
1070 unsigned short second = (i+3 < l) ? (s[i+2+high]<<8) + s[i+2+low] : 0;
1071 if((second & 0xfc00) == 0xdc00) /* good... */
1072 {
1073 point = FULLPOINT(point,second);
1074 length += UTF8LEN(point); /* possibly 4 bytes */
1075 i+=2; /* We overstepped one word. */
1076 }
1077 else /* if no valid pair, break here */
1078 {
1079 if(noquiet) error2("Invalid UTF16 surrogate pair at %li (0x%04lx).", (unsigned long)i, point);
1080 n = i; /* Forget the half pair, END! */
1081 break;
1082 }
1083 }
1084 else length += UTF8LEN(point); /* 1,2 or 3 bytes */
1085 }
1086
1087 if(!mpg123_resize_string(sb, length+1)){ mpg123_free_string(sb); return ; }
1088
1089 /* Now really convert, skip checks as these have been done just before. */
1090 p = (unsigned char*) sb->p; /* Signedness doesn't matter but it shows I thought about the non-issue */
1091 for(i=0; i < n; i+=2)
1092 {
1093 unsigned long codepoint = ((unsigned long) s[i+high]<<8) + s[i+low];
1094 if((codepoint & 0xfc00) == 0xd800) /* lead surrogate */
1095 {
1096 unsigned short second = (s[i+2+high]<<8) + s[i+2+low];
1097 codepoint = FULLPOINT(codepoint,second);
1098 i+=2; /* We overstepped one word. */
1099 }
1100 if(codepoint < 0x80) *p++ = (unsigned char) codepoint;
1101 else if(codepoint < 0x800)
1102 {
1103 *p++ = (unsigned char) (0xc0 | (codepoint>>6));
1104 *p++ = (unsigned char) (0x80 | (codepoint & 0x3f));
1105 }
1106 else if(codepoint < 0x10000)
1107 {
1108 *p++ = (unsigned char) (0xe0 | (codepoint>>12));
1109 *p++ = 0x80 | ((codepoint>>6) & 0x3f);
1110 *p++ = 0x80 | (codepoint & 0x3f);
1111 }
1112 else if (codepoint < 0x200000)
1113 {
1114 *p++ = (unsigned char) (0xf0 | codepoint>>18);
1115 *p++ = (unsigned char) (0x80 | ((codepoint>>12) & 0x3f));
1116 *p++ = (unsigned char) (0x80 | ((codepoint>>6) & 0x3f));
1117 *p++ = (unsigned char) (0x80 | (codepoint & 0x3f));
1118 } /* ignore bigger ones (that are not possible here anyway) */
1119 }
1120 sb->p[sb->size-1] = 0; /* paranoia... */
1121 sb->fill = sb->size;
1122 }
1123 #undef UTF8LEN
1124 #undef FULLPOINT
1125
1126 static void convert_utf8(mpg123_string *sb, const unsigned char* source, size_t len, const int noquiet)
1127 {
1128 if(mpg123_resize_string(sb, len+1))
1129 {
1130 memcpy(sb->p, source, len);
1131 sb->p[len] = 0;
1132 sb->fill = len+1;
1133 }
1134 else mpg123_free_string(sb);
1135 }
1136
1137 #endif