id3v2frames.c 33.4 KB
Newer Older
1
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: t; c-basic-offset: 2 -*- */
2
3
/* Copyright 2006 Tim-Philipp Müller <tim centricular net>
 * Copyright 2005 Jan Schmidt <thaytan@mad.scientist.com>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 * Copyright 2002,2003 Scott Wheeler <wheeler@kde.org> (portions from taglib)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>
27
#include <stdlib.h>
28
#include <gst/tag/tag.h>
29
#include <gst/base/gsttypefindhelper.h>
30
31
32
33
34
35
36
37
38
39

#ifdef HAVE_ZLIB
#include <zlib.h>
#endif

#include "id3tags.h"

GST_DEBUG_CATEGORY_EXTERN (id3demux_debug);
#define GST_CAT_DEFAULT (id3demux_debug)

40
static gboolean parse_comment_frame (ID3TagsWorking * work);
41
42
static gchar *parse_url_link_frame (ID3TagsWorking * work,
    const gchar ** tag_name);
43
static GArray *parse_text_identification_frame (ID3TagsWorking * work);
44
45
46
47
static gchar *parse_user_text_identification_frame (ID3TagsWorking * work,
    const gchar ** tag_name);
static gchar *parse_unique_file_identifier (ID3TagsWorking * work,
    const gchar ** tag_name);
48
static gboolean parse_relative_volume_adjustment_two (ID3TagsWorking * work);
49
static void parse_obsolete_tdat_frame (ID3TagsWorking * work);
50
static gboolean id3v2_tag_to_taglist (ID3TagsWorking * work,
51
52
53
54
55
56
57
58
    const gchar * tag_name, const gchar * tag_str);
/* Parse a single string into an array of gchar* */
static void parse_split_strings (guint8 encoding, gchar * data, gint data_size,
    GArray ** out_fields);
static void free_tag_strings (GArray * fields);
static gboolean
id3v2_genre_fields_to_taglist (ID3TagsWorking * work, const gchar * tag_name,
    GArray * tag_fields);
59
static gboolean parse_picture_frame (ID3TagsWorking * work);
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#define ID3V2_ENCODING_ISO8859 0x00
#define ID3V2_ENCODING_UTF16   0x01
#define ID3V2_ENCODING_UTF16BE 0x02
#define ID3V2_ENCODING_UTF8    0x03

gboolean
id3demux_id3v2_parse_frame (ID3TagsWorking * work)
{
  const gchar *tag_name;
  gboolean result = FALSE;
  gint i;
  guint8 *frame_data = work->hdr.frame_data;
  guint frame_data_size = work->cur_frame_size;
  gchar *tag_str = NULL;
75
  GArray *tag_fields = NULL;
76

77
78
79
80
#ifdef HAVE_ZLIB
  guint8 *uncompressed_data = NULL;
#endif

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
  /* Check that the frame id is valid */
  for (i = 0; i < 5 && work->frame_id[i] != '\0'; i++) {
    if (!g_ascii_isalnum (work->frame_id[i])) {
      GST_DEBUG ("Encountered invalid frame_id");
      return FALSE;
    }
  }

  /* Can't handle encrypted frames right now */
  if (work->frame_flags & ID3V2_FRAME_FORMAT_ENCRYPTION) {
    GST_WARNING ("Encrypted frames are not supported");
    return FALSE;
  }

  if (work->frame_flags & ID3V2_FRAME_FORMAT_UNSYNCHRONISATION) {
    GST_WARNING ("ID3v2 frame with unsupported unsynchronisation applied. "
        "May fail badly");
  }

  tag_name = gst_tag_from_id3_tag (work->frame_id);
101
  if (tag_name == NULL &&
102
      strncmp (work->frame_id, "RVA2", 4) != 0 &&
103
      strncmp (work->frame_id, "TXXX", 4) != 0 &&
104
      strncmp (work->frame_id, "TDAT", 4) != 0 &&
105
      strncmp (work->frame_id, "UFID", 4) != 0) {
106
    return FALSE;
107
  }
108
109
110
111
112
113
114
115

  if (work->frame_flags & (ID3V2_FRAME_FORMAT_COMPRESSION |
          ID3V2_FRAME_FORMAT_DATA_LENGTH_INDICATOR)) {
    if (work->hdr.frame_data_size <= 4)
      return FALSE;
    work->parse_size = read_synch_uint (frame_data, 4);
    frame_data += 4;
    frame_data_size -= 4;
116
117
118
119
120
    if (work->parse_size < frame_data_size) {
      GST_WARNING ("ID3v2 frame %s has invalid size %d.", tag_name,
          frame_data_size);
      return FALSE;
    }
121
122
123
  }

  work->parse_size = frame_data_size;
124
125

  if (work->frame_flags & ID3V2_FRAME_FORMAT_COMPRESSION) {
126
#ifdef HAVE_ZLIB
127
128
129
    uLongf destSize = work->parse_size;
    Bytef *dest, *src;

130
    uncompressed_data = g_malloc (work->parse_size);
131

132
    dest = (Bytef *) uncompressed_data;
133
134
135
    src = (Bytef *) frame_data;

    if (uncompress (dest, &destSize, src, frame_data_size) != Z_OK) {
136
      g_free (uncompressed_data);
137
138
      return FALSE;
    }
139
140
    if (destSize != work->parse_size) {
      GST_WARNING
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
141
142
          ("Decompressing ID3v2 frame %s did not produce expected size %d bytes (got %lu)",
          tag_name, work->parse_size, destSize);
143
      g_free (uncompressed_data);
144
145
      return FALSE;
    }
146
    work->parse_data = uncompressed_data;
147
148
149
150
151
#else
    GST_WARNING ("Compressed ID3v2 tag frame could not be decompressed"
        " because gstid3demux was compiled without zlib support");
    return FALSE;
#endif
152
  } else {
153
    work->parse_data = frame_data;
154
155
156
  }

  if (work->frame_id[0] == 'T') {
157
158
159
160
    if (strcmp (work->frame_id, "TDAT") == 0) {
      parse_obsolete_tdat_frame (work);
      result = TRUE;
    } else if (strcmp (work->frame_id, "TXXX") == 0) {
161
      /* Handle user text frame */
162
      tag_str = parse_user_text_identification_frame (work, &tag_name);
163
164
165
    } else {
      /* Text identification frame */
      tag_fields = parse_text_identification_frame (work);
166
    }
167
168
169
  } else if (work->frame_id[0] == 'W' && strcmp (work->frame_id, "WXXX") != 0) {
    /* URL link frame: ISO-8859-1 encoded, one frame per tag */
    tag_str = parse_url_link_frame (work, &tag_name);
170
171
  } else if (!strcmp (work->frame_id, "COMM")) {
    /* Comment */
172
    result = parse_comment_frame (work);
173
174
  } else if (!strcmp (work->frame_id, "APIC")) {
    /* Attached picture */
175
    result = parse_picture_frame (work);
176
177
  } else if (!strcmp (work->frame_id, "RVA2")) {
    /* Relative volume */
178
    result = parse_relative_volume_adjustment_two (work);
179
180
  } else if (!strcmp (work->frame_id, "UFID")) {
    /* Unique file identifier */
181
    tag_str = parse_unique_file_identifier (work, &tag_name);
182
  }
183
184
185
186
187
188
189
#ifdef HAVE_ZLIB
  if (work->frame_flags & ID3V2_FRAME_FORMAT_COMPRESSION) {
    g_free (uncompressed_data);
    uncompressed_data = NULL;
    work->parse_data = frame_data;
  }
#endif
190
191
192
193
194
195

  if (tag_str != NULL) {
    /* g_print ("Tag %s value %s\n", tag_name, tag_str); */
    result = id3v2_tag_to_taglist (work, tag_name, tag_str);
    g_free (tag_str);
  }
196
197
198
199
200
  if (tag_fields != NULL) {
    if (strcmp (work->frame_id, "TCON") == 0) {
      /* Genre strings need special treatment */
      result |= id3v2_genre_fields_to_taglist (work, tag_name, tag_fields);
    } else {
201
202
203
204
205
206
207
      gint t;

      for (t = 0; t < tag_fields->len; t++) {
        tag_str = g_array_index (tag_fields, gchar *, t);
        if (tag_str != NULL && tag_str[0] != '\0')
          result |= id3v2_tag_to_taglist (work, tag_name, tag_str);
      }
208
209
210
    }
    free_tag_strings (tag_fields);
  }
211
212
213
214

  return result;
}

215
static gboolean
216
217
parse_comment_frame (ID3TagsWorking * work)
{
218
  guint dummy;
219
220
  guint8 encoding;
  gchar language[4];
221
222
  GArray *fields = NULL;
  gchar *description, *text;
223
224

  if (work->parse_size < 6)
225
    return FALSE;
226
227

  encoding = work->parse_data[0];
228
229
230
231
  language[0] = g_ascii_tolower (work->parse_data[1]);
  language[1] = g_ascii_tolower (work->parse_data[2]);
  language[2] = g_ascii_tolower (work->parse_data[3]);
  language[3] = '\0';
232

233
234
  parse_split_strings (encoding, (gchar *) work->parse_data + 4,
      work->parse_size - 4, &fields);
235

236
  if (fields == NULL || fields->len < 2) {
237
    GST_WARNING ("Failed to decode comment frame");
238
239
    goto fail;
  }
240
241
  description = g_array_index (fields, gchar *, 0);
  text = g_array_index (fields, gchar *, 1);
242
243

  if (!g_utf8_validate (text, -1, NULL)) {
244
    GST_WARNING ("Converted string is not valid utf-8");
245
    goto fail;
246
247
248
249
250
251
252
  }

  /* skip our own dummy descriptions (from id3v2mux) */
  if (strlen (description) > 0 && g_utf8_validate (description, -1, NULL) &&
      sscanf (description, "c%u", &dummy) != 1) {
    gchar *s;

253
254
255
256
257
    /* must be either an ISO-639-1 or ISO-639-2 language code */
    if (language[0] != '\0' &&
        g_ascii_isalpha (language[0]) &&
        g_ascii_isalpha (language[1]) &&
        (g_ascii_isalpha (language[2]) || language[2] == '\0')) {
258
      s = g_strdup_printf ("%s[%s]=%s", description, language, text);
259
    } else {
260
      s = g_strdup_printf ("%s=%s", description, text);
261
    }
262
263
264
265
266
267
268
269
    gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
        GST_TAG_EXTENDED_COMMENT, s, NULL);
    g_free (s);
  } else if (text != NULL && *text != '\0') {
    gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
        GST_TAG_COMMENT, text, NULL);
  } else {
    goto fail;
270
271
  }

272
  free_tag_strings (fields);
273
  return TRUE;
274

275
276
277
278
279
280
fail:
  {
    GST_WARNING ("failed to parse COMM frame");
    free_tag_strings (fields);
    return FALSE;
  }
281
282
}

283
static GArray *
284
285
286
parse_text_identification_frame (ID3TagsWorking * work)
{
  guchar encoding;
287
  GArray *fields = NULL;
288
289
290
291
292

  if (work->parse_size < 2)
    return NULL;

  encoding = work->parse_data[0];
293
294
  parse_split_strings (encoding, (gchar *) work->parse_data + 1,
      work->parse_size - 1, &fields);
295
296
  if (fields) {
    if (fields->len > 0) {
297
298
      GST_LOG ("Read %d fields from Text ID frame of size %d with encoding %d"
          ". First is '%s'", fields->len, work->parse_size - 1, encoding,
299
300
          g_array_index (fields, gchar *, 0));
    } else {
301
302
      GST_LOG ("Read 0 fields from Text ID frame of size %d with encoding %d",
          work->parse_size - 1, encoding);
303
304
    }
  }
305

306
  return fields;
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
static gboolean
link_is_known_license (const gchar * url)
{
  return g_str_has_prefix (url, "http://creativecommons.org/licenses/");
}

static gchar *
parse_url_link_frame (ID3TagsWorking * work, const gchar ** tag_name)
{
  gsize len;
  gchar *nul, *data, *link;

  *tag_name = NULL;

  if (work->parse_size == 0)
    return NULL;

  data = (gchar *) work->parse_data;
  /* if there's more data then the string is long, we only want to parse the
   * data up to the terminating zero to g_convert and ignore the rest, as
   * per spec */
  nul = memchr (data, '\0', work->parse_size);
  if (nul != NULL) {
    len = (gsize) (nul - data);
  } else {
    len = work->parse_size;
  }

  link = g_convert (data, len, "UTF-8", "ISO-8859-1", NULL, NULL, NULL);

  if (link == NULL || !gst_uri_is_valid (link)) {
    GST_DEBUG ("Invalid URI in %s frame: %s", work->frame_id,
        GST_STR_NULL (link));
    g_free (link);
    return NULL;
  }

  /* we don't know if it's a link to a page that explains the copyright
   * situation, or a link that points to/represents a license, the ID3 spec
   * does not separate those two things; for now only put known license URIs
   * into GST_TAG_LICENSE_URI and everything else into GST_TAG_COPYRIGHT_URI */
  if (strcmp (work->frame_id, "WCOP") == 0) {
    if (link_is_known_license (link))
      *tag_name = GST_TAG_LICENSE_URI;
    else
      *tag_name = GST_TAG_COPYRIGHT_URI;
355
356
357
358
359
  } else if (strcmp (work->frame_id, "WOAF") == 0) {
    /* can't be bothered to create a CONTACT_URI tag for this, so let's just
     * put into into GST_TAG_CONTACT, which is where it ends up when reading
     * the info from vorbis comments as well */
    *tag_name = GST_TAG_CONTACT;
360
361
362
363
364
365
  }

  return link;
}


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
static gchar *
parse_user_text_identification_frame (ID3TagsWorking * work,
    const gchar ** tag_name)
{
  gchar *ret;
  guchar encoding;
  GArray *fields = NULL;

  *tag_name = NULL;

  if (work->parse_size < 2)
    return NULL;

  encoding = work->parse_data[0];

  parse_split_strings (encoding, (gchar *) work->parse_data + 1,
      work->parse_size - 1, &fields);

  if (fields == NULL)
    return NULL;

  if (fields->len != 2) {
    GST_WARNING ("Expected 2 fields in TXXX frame, but got %d", fields->len);
    free_tag_strings (fields);
    return NULL;
  }

  *tag_name =
      gst_tag_from_id3_user_tag ("TXXX", g_array_index (fields, gchar *, 0));

  GST_LOG ("TXXX frame of size %d. Mapped descriptor '%s' to GStreamer tag %s",
      work->parse_size - 1, g_array_index (fields, gchar *, 0),
      GST_STR_NULL (*tag_name));

  if (*tag_name) {
    ret = g_strdup (g_array_index (fields, gchar *, 1));
    /* GST_LOG ("%s = %s", *tag_name, GST_STR_NULL (ret)); */
  } else {
    ret = NULL;
  }

  free_tag_strings (fields);
  return ret;
}

411
412
413
static gboolean
parse_id_string (ID3TagsWorking * work, gchar ** p_str, gint * p_len,
    gint * p_datalen)
414
415
416
417
{
  gint len, datalen;

  if (work->parse_size < 2)
418
    return FALSE;
419
420
421
422
423
424
425

  for (len = 0; len < work->parse_size - 1; ++len) {
    if (work->parse_data[len] == '\0')
      break;
  }

  datalen = work->parse_size - (len + 1);
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
  if (len == 0 || datalen <= 0)
    return FALSE;

  *p_str = g_strndup ((gchar *) work->parse_data, len);
  *p_len = len;
  *p_datalen = datalen;

  return TRUE;
}

static gchar *
parse_unique_file_identifier (ID3TagsWorking * work, const gchar ** tag_name)
{
  gint len, datalen;
  gchar *owner_id, *data, *ret = NULL;

  GST_LOG ("parsing UFID frame of size %d", work->parse_size);

  if (!parse_id_string (work, &owner_id, &len, &datalen))
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
    return NULL;

  data = (gchar *) work->parse_data + len + 1;
  GST_LOG ("UFID owner ID: %s (+ %d bytes of data)", owner_id, datalen);

  if (strcmp (owner_id, "http://musicbrainz.org") == 0 &&
      g_utf8_validate (data, datalen, NULL)) {
    *tag_name = GST_TAG_MUSICBRAINZ_TRACKID;
    ret = g_strndup (data, datalen);
  } else {
    GST_INFO ("Unknown UFID owner ID: %s", owner_id);
  }
  g_free (owner_id);

  return ret;
}

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
/* parse data and return length of the next string in the given encoding,
 * including the NUL terminator */
static gint
scan_encoded_string (guint8 encoding, gchar * data, gint data_size)
{
  gint i;

  switch (encoding) {
    case ID3V2_ENCODING_ISO8859:
    case ID3V2_ENCODING_UTF8:
      for (i = 0; i < data_size; ++i) {
        if (data[i] == '\0')
          return i + 1;
      }
      break;
    case ID3V2_ENCODING_UTF16:
    case ID3V2_ENCODING_UTF16BE:
      /* we don't care about BOMs here and treat them as part of the string */
      /* Find '\0\0' terminator */
      for (i = 0; i < data_size - 1; i += 2) {
        if (data[i] == '\0' && data[i + 1] == '\0')
          return i + 2;
      }
      break;
    default:
      break;
  }

  return 0;
}

static gboolean
parse_picture_frame (ID3TagsWorking * work)
{
  GstBuffer *image = NULL;
  GstCaps *image_caps = NULL;
  gboolean is_pic_uri = FALSE;
  guint8 txt_encoding, pic_type;
500
  gchar *c, *mime_str = NULL;
501
502
  gint len, datalen;

503
  GST_LOG ("APIC frame (ID3v2.%u)", ID3V2_VER_MAJOR (work->hdr.version));
504
505
506
507
508
509
510
511

  if (work->parse_size < 1 + 1 + 1 + 1 + 1)
    goto not_enough_data;

  txt_encoding = work->parse_data[0];
  ++work->parse_data;
  --work->parse_size;

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
  /* Read image format; in early ID3v2 versions this is a fixed-length
   * 3-character string without terminator; in later versions (>= 2.3.0)
   * this is a NUL-terminated string of variable length */
  if (ID3V2_VER_MAJOR (work->hdr.version) < 3) {
    if (work->parse_size < 3)
      goto not_enough_data;

    mime_str = g_strndup ((gchar *) work->parse_data, 3);
    len = 3;
  } else {
    if (!parse_id_string (work, &mime_str, &len, &datalen))
      return FALSE;
    ++len;                      /* for string terminator */
  }

  /* Fix up 'jpg' => 'jpeg' in mime/media type */
  if (mime_str != NULL &&
      (g_ascii_strcasecmp (mime_str, "jpg") == 0 ||
          g_ascii_strcasecmp (mime_str, "image/jpg") == 0)) {
    g_free (mime_str);
    mime_str = g_strdup ("jpeg");
  }

  /* Make lower-case */
  for (c = mime_str; c != NULL && *c != '\0'; ++c) {
    *c = g_ascii_tolower (*c);
538
539
540
541
542
543
544
545
546
547
548
549
  }

  is_pic_uri = (mime_str != NULL && strcmp (mime_str, "-->") == 0);

  if (mime_str && *mime_str && strchr (mime_str, '/') == NULL && !is_pic_uri) {
    gchar *tmp;

    tmp = g_strdup_printf ("image/%s", mime_str);
    g_free (mime_str);
    mime_str = tmp;
  }

550
  if (work->parse_size < len + 1 + 1 + 1)
551
552
    goto not_enough_data;

553
554
  work->parse_data += len;
  work->parse_size -= len;
555

556
  /* Read image type */
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
  pic_type = work->parse_data[0];
  ++work->parse_data;
  --work->parse_size;

  GST_LOG ("APIC frame mime type    : %s", GST_STR_NULL (mime_str));
  GST_LOG ("APIC frame picture type : 0x%02x", (guint) pic_type);

  if (work->parse_size < 1 + 1)
    goto not_enough_data;

  len = scan_encoded_string (txt_encoding, (gchar *) work->parse_data,
      work->parse_size);

  if (len < 1)
    goto error;

  /* just skip the description string ... */
  GST_LOG ("Skipping description string (%d bytes in original coding)", len);

  if (work->parse_size < len + 1)
    goto not_enough_data;

  work->parse_data += len;
  work->parse_size -= len;

  GST_DEBUG ("image data is %u bytes", work->parse_size);

  if (work->parse_size <= 0)
    goto not_enough_data;

  if (is_pic_uri) {
    gchar *uri;

    uri = g_strndup ((gchar *) work->parse_data, work->parse_size);
    GST_DEBUG ("image URI: %s", uri);

    image = gst_buffer_new ();
    GST_BUFFER_MALLOCDATA (image) = (guint8 *) uri;     /* take ownership */
    GST_BUFFER_DATA (image) = (guint8 *) uri;
    GST_BUFFER_SIZE (image) = work->parse_size;

    image_caps = gst_caps_new_simple ("text/uri-list", NULL);
  } else {
    image = gst_buffer_new_and_alloc (work->parse_size);
    memcpy (GST_BUFFER_DATA (image), work->parse_data, work->parse_size);

    /* if possible use GStreamer media type rather than declared type */
    image_caps = gst_type_find_helper_for_buffer (NULL, image, NULL);
    if (image_caps) {
      GST_DEBUG ("Found GStreamer media type: %" GST_PTR_FORMAT, image_caps);
    } else if (mime_str && *mime_str) {
      GST_DEBUG ("No GStreamer media type found, using declared type");
      image_caps = gst_caps_new_simple (mime_str, NULL);
    } else {
      GST_DEBUG ("Empty declared mime type, ignoring image frame");
      image = NULL;
      image_caps = NULL;
      goto error;
    }
  }

  if (image && image_caps) {
619

620
    if (pic_type == 0x01 || pic_type == 0x02) {
621
622
623
      /* file icon for preview. Don't add image-type to caps, since there
       * is only supposed to be one of these. */
      gst_buffer_set_caps (image, image_caps);
624
625
626
      gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
          GST_TAG_PREVIEW_IMAGE, image, NULL);
    } else {
627
628
629
630
631
632
633
634
635
636
      GstTagImageType gst_tag_pic_type = GST_TAG_IMAGE_TYPE_UNDEFINED;

      /* Remap the ID3v2 APIC type our ImageType enum */
      if (pic_type >= 0x3 && pic_type <= 0x14)
        gst_tag_pic_type = (GstTagImageType) (pic_type - 2);

      gst_structure_set (gst_caps_get_structure (image_caps, 0),
          "image-type", GST_TYPE_TAG_IMAGE_TYPE, gst_tag_pic_type, NULL);

      gst_buffer_set_caps (image, image_caps);
637
638
639
      gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
          GST_TAG_IMAGE, image, NULL);
    }
640
641

    gst_caps_unref (image_caps);
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
    gst_buffer_unref (image);
  }

  g_free (mime_str);
  return TRUE;

not_enough_data:
  {
    GST_DEBUG ("not enough data, skipping APIC frame");
    /* fall through to error */
  }
error:
  {
    GST_DEBUG ("problem parsing APIC frame, skipping");
    g_free (mime_str);
    return FALSE;
  }
}

661
662
#define ID3V2_RVA2_CHANNEL_MASTER  1

663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
static gboolean
parse_relative_volume_adjustment_two (ID3TagsWorking * work)
{
  const gchar *gain_tag_name = NULL;
  const gchar *peak_tag_name = NULL;
  gdouble gain_dB, peak_val;
  guint64 peak;
  guint8 *data, chan, peak_bits;
  gchar *id;
  gint len, datalen, i;

  if (!parse_id_string (work, &id, &len, &datalen))
    return FALSE;

  if (datalen < (1 + 2 + 1)) {
    GST_WARNING ("broken RVA2 frame, data size only %d bytes", datalen);
    g_free (id);
    return FALSE;
  }

  data = work->parse_data + len + 1;
  chan = GST_READ_UINT8 (data);
  gain_dB = (gdouble) ((gint16) GST_READ_UINT16_BE (data + 1)) / 512.0;
  /* The meaning of the peak value is not defined in the ID3v2 spec. However,
   * the first/only implementation of this seems to have been in XMMS, and
   * other libs (like mutagen) seem to follow that implementation as well:
   * see http://bugs.xmms.org/attachment.cgi?id=113&action=view */
  peak_bits = GST_READ_UINT8 (data + 1 + 2);
  if (peak_bits > 64) {
    GST_WARNING ("silly peak precision of %d bits, ignoring", (gint) peak_bits);
    peak_bits = 0;
  }
  data += 1 + 2 + 1;
  datalen -= 1 + 2 + 1;
  if (peak_bits == 16) {
    peak = GST_READ_UINT16_BE (data);
  } else {
    peak = 0;
    for (i = 0; i < (GST_ROUND_UP_8 (peak_bits) / 8) && datalen > 0; ++i) {
      peak = peak << 8;
      peak |= GST_READ_UINT8 (data);
      ++data;
      --datalen;
    }
  }

  peak = peak << (64 - GST_ROUND_UP_8 (peak_bits));
710
711
  peak_val =
      gst_guint64_to_gdouble (peak) / gst_util_guint64_to_gdouble (G_MAXINT64);
712
713
714
  GST_LOG ("RVA2 frame: id=%s, chan=%u, adj=%.2fdB, peak_bits=%u, peak=%.2f",
      id, chan, gain_dB, (guint) peak_bits, peak_val);

715
  if (chan == ID3V2_RVA2_CHANNEL_MASTER && strcmp (id, "track") == 0) {
716
717
    gain_tag_name = GST_TAG_TRACK_GAIN;
    peak_tag_name = GST_TAG_TRACK_PEAK;
718
  } else if (chan == ID3V2_RVA2_CHANNEL_MASTER && strcmp (id, "album") == 0) {
719
720
721
    gain_tag_name = GST_TAG_ALBUM_GAIN;
    peak_tag_name = GST_TAG_ALBUM_PEAK;
  } else {
722
    GST_INFO ("Unhandled RVA2 frame id '%s' for channel %d", id, chan);
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
  }

  if (gain_tag_name) {
    gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
        gain_tag_name, gain_dB, NULL);
  }
  if (peak_tag_name && peak_bits > 0) {
    gst_tag_list_add (work->tags, GST_TAG_MERGE_APPEND,
        peak_tag_name, peak_val, NULL);
  }

  g_free (id);

  return (gain_tag_name != NULL || peak_tag_name != NULL);
}

739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
static void
parse_obsolete_tdat_frame (ID3TagsWorking * work)
{
  if (work->parse_size >= 5 &&
      work->parse_data[0] == ID3V2_ENCODING_ISO8859 &&
      g_ascii_isdigit (work->parse_data[1]) &&
      g_ascii_isdigit (work->parse_data[2]) &&
      g_ascii_isdigit (work->parse_data[3]) &&
      g_ascii_isdigit (work->parse_data[4])) {
    work->pending_day = (10 * g_ascii_digit_value (work->parse_data[1])) +
        g_ascii_digit_value (work->parse_data[2]);
    work->pending_month = (10 * g_ascii_digit_value (work->parse_data[3])) +
        g_ascii_digit_value (work->parse_data[4]);
    GST_LOG ("date (dd/mm) %02u/%02u", work->pending_day, work->pending_month);
  }
}

756
757
static gboolean
id3v2_tag_to_taglist (ID3TagsWorking * work, const gchar * tag_name,
758
    const gchar * tag_str)
759
760
761
762
{
  GType tag_type = gst_tag_get_type (tag_name);
  GstTagList *tag_list = work->tags;

763
764
765
  if (tag_str == NULL)
    return FALSE;

766
767
768
  switch (tag_type) {
    case G_TYPE_UINT:
    {
769
770
771
      gint current, total;

      if (sscanf (tag_str, "%d/%d", &current, &total) == 2) {
772
773
        if (total <= 0) {
          GST_WARNING ("Ignoring invalid value for total %d in tag %s",
774
775
776
777
778
779
780
781
782
              total, tag_name);
        } else {
          if (strcmp (tag_name, GST_TAG_TRACK_NUMBER) == 0) {
            gst_tag_list_add (tag_list, GST_TAG_MERGE_APPEND,
                GST_TAG_TRACK_COUNT, total, NULL);
          } else if (strcmp (tag_name, GST_TAG_ALBUM_VOLUME_NUMBER) == 0) {
            gst_tag_list_add (tag_list, GST_TAG_MERGE_APPEND,
                GST_TAG_ALBUM_VOLUME_COUNT, total, NULL);
          }
783
        }
784
785
786
787
      } else if (sscanf (tag_str, "%d", &current) != 1) {
        /* Not an integer in the string */
        GST_WARNING ("Tag string for tag %s does not contain an integer - "
            "ignoring", tag_name);
788
        break;
789
      }
790

791
792
793
      if (current <= 0) {
        GST_WARNING ("Ignoring invalid value %d in tag %s", current, tag_name);
      } else {
794
795
796
        gst_tag_list_add (tag_list, GST_TAG_MERGE_APPEND, tag_name, current,
            NULL);
      }
797
798
799
800
801
802
803
      break;
    }
    case G_TYPE_UINT64:
    {
      guint64 tmp;

      g_assert (strcmp (tag_name, GST_TAG_DURATION) == 0);
804
      tmp = strtoul (tag_str, NULL, 10);
805
806
807
808
809
810
811
812
      if (tmp == 0) {
        break;
      }
      gst_tag_list_add (tag_list, GST_TAG_MERGE_APPEND,
          GST_TAG_DURATION, tmp * 1000 * 1000, NULL);
      break;
    }
    case G_TYPE_STRING:{
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
      const GValue *val;
      guint i, num;

      /* make sure we add each unique string only once per tag, we don't want
       * to have the same genre in the genre list multiple times, for example,
       * or the same DiscID in there twice just because it's contained in the
       * tag multiple times under different TXXX user tags */
      num = gst_tag_list_get_tag_size (tag_list, tag_name);
      for (i = 0; i < num; ++i) {
        val = gst_tag_list_get_value_index (tag_list, tag_name, i);
        if (val != NULL && strcmp (g_value_get_string (val), tag_str) == 0)
          break;
      }
      if (i == num) {
        gst_tag_list_add (tag_list, GST_TAG_MERGE_APPEND,
            tag_name, tag_str, NULL);
829
      }
830
831
      break;
    }
832

833
    default:{
834
      gchar *tmp = NULL;
835
836
      GValue src = { 0, };
      GValue dest = { 0, };
837

838
      /* Ensure that any date string is complete */
839
840
841
842
843
844
845
846
847
848
849
850
851
      if (tag_type == GST_TYPE_DATE) {
        guint year = 1901, month = 1, day = 1;

        /* Dates can be yyyy-MM-dd, yyyy-MM or yyyy, but we need
         * the first type */
        if (sscanf (tag_str, "%04u-%02u-%02u", &year, &month, &day) == 0)
          break;

        tmp = g_strdup_printf ("%04u-%02u-%02u", year, month, day);
        tag_str = tmp;
      }

      /* handles anything else */
852
853
854
      g_value_init (&src, G_TYPE_STRING);
      g_value_set_string (&src, (const gchar *) tag_str);
      g_value_init (&dest, tag_type);
855

856
857
858
      if (g_value_transform (&src, &dest)) {
        gst_tag_list_add_values (tag_list, GST_TAG_MERGE_APPEND,
            tag_name, &dest, NULL);
859
860
861
862
863
864
865
      } else if (tag_type == G_TYPE_DOUBLE) {
        /* replaygain tags in TXXX frames ... */
        g_value_set_double (&dest, g_strtod (tag_str, NULL));
        gst_tag_list_add_values (tag_list, GST_TAG_MERGE_KEEP,
            tag_name, &dest, NULL);
        GST_LOG ("Converted string '%s' to double %f", tag_str,
            g_value_get_double (&dest));
866
867
868
869
      } else {
        GST_WARNING ("Failed to transform tag from string to type '%s'",
            g_type_name (tag_type));
      }
870

871
872
      g_value_unset (&src);
      g_value_unset (&dest);
873
      g_free (tmp);
874
875
876
877
878
879
880
      break;
    }
  }

  return TRUE;
}

881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
/* Check that an array of characters contains only digits */
static gboolean
id3v2_are_digits (const gchar * chars, gint size)
{
  gint i;

  for (i = 0; i < size; i++) {
    if (!g_ascii_isdigit (chars[i]))
      return FALSE;
  }
  return TRUE;
}

static gboolean
id3v2_genre_string_to_taglist (ID3TagsWorking * work, const gchar * tag_name,
    const gchar * tag_str, gint len)
{
  g_return_val_if_fail (tag_str != NULL, FALSE);

  /* If it's a number, it might be a defined genre */
  if (id3v2_are_digits (tag_str, len)) {
    tag_str = gst_tag_id3_genre_get (strtol (tag_str, NULL, 10));
903
    return id3v2_tag_to_taglist (work, tag_name, tag_str);
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
  }
  /* Otherwise it might be "RX" or "CR" */
  if (len == 2) {
    if (g_ascii_strncasecmp ("rx", tag_str, len) == 0)
      return id3v2_tag_to_taglist (work, tag_name, "Remix");

    if (g_ascii_strncasecmp ("cr", tag_str, len) == 0)
      return id3v2_tag_to_taglist (work, tag_name, "Cover");
  }

  /* Otherwise it's a string */
  return id3v2_tag_to_taglist (work, tag_name, tag_str);
}

static gboolean
id3v2_genre_fields_to_taglist (ID3TagsWorking * work, const gchar * tag_name,
    GArray * tag_fields)
{
  gchar *tag_str = NULL;
  gboolean result = FALSE;
  gint i;

  for (i = 0; i < tag_fields->len; i++) {
    gint len;

    tag_str = g_array_index (tag_fields, gchar *, 0);
    if (tag_str == NULL)
      continue;

    len = strlen (tag_str);
934
935
936
    /* Only supposed to see '(n)' type numeric genre strings in ID3 <= 2.3.0
     * but apparently we see them in 2.4.0 sometimes too */
    if (TRUE || work->hdr.version <= 0x300) {   /* <= 2.3.0 */
937
938
939
940
941
942
      /* Check for genre numbers wrapped in parentheses, possibly
       * followed by a string */
      while (len >= 2) {
        gint pos;
        gboolean found = FALSE;

943
944
945
946
947
948
949
950
951
952
953
        /* Double parenthesis ends the numeric genres, but we need
         * to swallow the first one so we actually output '(' */
        if (tag_str[0] == '(' && tag_str[1] == '(') {
          tag_str++;
          len--;
          break;
        }

        /* If the first char is not a parenthesis, then stop
         * looking for parenthesised genre strings */
        if (tag_str[0] != '(')
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
          break;

        for (pos = 1; pos < len; pos++) {
          if (tag_str[pos] == ')') {
            gchar *tmp_str;

            tmp_str = g_strndup (tag_str + 1, pos - 1);
            result |=
                id3v2_genre_string_to_taglist (work, tag_name, tmp_str,
                pos - 1);
            g_free (tmp_str);
            tag_str += pos + 1;
            len -= pos + 1;
            found = TRUE;
            break;
          }
970
971
972
973
974
975

          /* If we encounter a non-digit while searching for a closing 
           * parenthesis, we should not try and interpret this as a 
           * numeric genre string */
          if (!g_ascii_isdigit (tag_str[pos]))
            break;
976
977
978
979
980
981
        }
        if (!found)
          break;                /* There was no closing parenthesis */
      }
    }

982
    if (len > 0 && tag_str != NULL)
983
984
985
986
987
      result |= id3v2_genre_string_to_taglist (work, tag_name, tag_str, len);
  }
  return result;
}

988
989
990
static const gchar utf16enc[] = "UTF-16";
static const gchar utf16leenc[] = "UTF-16LE";
static const gchar utf16beenc[] = "UTF-16BE";
991

992
static gboolean
993
find_utf16_bom (gchar * data, const gchar ** p_in_encoding)
994
995
996
997
998
{
  guint16 marker = (GST_READ_UINT8 (data) << 8) | GST_READ_UINT8 (data + 1);

  switch (marker) {
    case 0xFFFE:
999
      *p_in_encoding = utf16leenc;
1000
      return TRUE;
For faster browsing, not all history is shown. View entire blame