Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst-libs / gst / tag / gstvorbistag.c
1 /* GStreamer
2  * Copyright (C) 2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
3  *
4  * gstvorbistag.c: library for reading / modifying vorbis tags
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gsttagvorbis
24  * @short_description: tag mappings and support functions for plugins
25  *                     dealing with vorbiscomments
26  * @see_also: #GstTagList
27  *
28  * <refsect2>
29  * <para>
30  * Contains various utility functions for plugins to parse or create
31  * vorbiscomments and map them to and from #GstTagList<!-- -->s.
32  * </para>
33  * </refsect2>
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39 #include <gst/gsttagsetter.h>
40 #include <gst/base/gstbytereader.h>
41 #include <gst/base/gstbytewriter.h>
42 #include "gsttageditingprivate.h"
43 #include <stdlib.h>
44 #include <string.h>
45
46 /*
47  * see http://xiph.org/ogg/vorbis/doc/v-comment.html
48  */
49 static const GstTagEntryMatch tag_matches[] = {
50   {GST_TAG_TITLE, "TITLE"},
51   {GST_TAG_VERSION, "VERSION"},
52   {GST_TAG_ALBUM, "ALBUM"},
53   {GST_TAG_TRACK_NUMBER, "TRACKNUMBER"},
54   {GST_TAG_ALBUM_VOLUME_NUMBER, "DISCNUMBER"},
55   {GST_TAG_TRACK_COUNT, "TRACKTOTAL"},
56   {GST_TAG_ALBUM_VOLUME_COUNT, "DISCTOTAL"},
57   {GST_TAG_ARTIST, "ARTIST"},
58   {GST_TAG_PERFORMER, "PERFORMER"},
59   {GST_TAG_COMPOSER, "COMPOSER"},
60   {GST_TAG_COPYRIGHT, "COPYRIGHT"},
61   {GST_TAG_LICENSE, "LICENSE"},
62   {GST_TAG_LICENSE_URI, "LICENSE"},
63   {GST_TAG_GEO_LOCATION_NAME, "LOCATION"},
64   {GST_TAG_ORGANIZATION, "ORGANIZATION"},
65   {GST_TAG_DESCRIPTION, "DESCRIPTION"},
66   {GST_TAG_GENRE, "GENRE"},
67   {GST_TAG_DATE, "DATE"},
68   {GST_TAG_CONTACT, "CONTACT"},
69   {GST_TAG_ISRC, "ISRC"},
70   {GST_TAG_COMMENT, "COMMENT"},
71   {GST_TAG_TRACK_GAIN, "REPLAYGAIN_TRACK_GAIN"},
72   {GST_TAG_TRACK_PEAK, "REPLAYGAIN_TRACK_PEAK"},
73   {GST_TAG_ALBUM_GAIN, "REPLAYGAIN_ALBUM_GAIN"},
74   {GST_TAG_ALBUM_PEAK, "REPLAYGAIN_ALBUM_PEAK"},
75   {GST_TAG_REFERENCE_LEVEL, "REPLAYGAIN_REFERENCE_LOUDNESS"},
76   {GST_TAG_MUSICBRAINZ_TRACKID, "MUSICBRAINZ_TRACKID"},
77   {GST_TAG_MUSICBRAINZ_ARTISTID, "MUSICBRAINZ_ARTISTID"},
78   {GST_TAG_MUSICBRAINZ_ALBUMID, "MUSICBRAINZ_ALBUMID"},
79   {GST_TAG_MUSICBRAINZ_ALBUMARTISTID, "MUSICBRAINZ_ALBUMARTISTID"},
80   {GST_TAG_MUSICBRAINZ_TRMID, "MUSICBRAINZ_TRMID"},
81   {GST_TAG_ARTIST_SORTNAME, "ARTISTSORT"},
82   {GST_TAG_ARTIST_SORTNAME, "ARTISTSORTORDER"},
83   {GST_TAG_ARTIST_SORTNAME, "MUSICBRAINZ_SORTNAME"},
84   {GST_TAG_ALBUM_SORTNAME, "ALBUMSORT"},
85   {GST_TAG_ALBUM_SORTNAME, "ALBUMSORTORDER"},
86   {GST_TAG_TITLE_SORTNAME, "TITLESORT"},
87   {GST_TAG_TITLE_SORTNAME, "TITLESORTORDER"},
88   {GST_TAG_ALBUM_ARTIST, "ALBUMARTIST"},
89   {GST_TAG_ALBUM_ARTIST_SORTNAME, "ALBUMARTISTSORT"},
90   {GST_TAG_ALBUM_ARTIST_SORTNAME, "ALBUMARTISTSORTORDER"},
91   {GST_TAG_LANGUAGE_CODE, "LANGUAGE"},
92   {GST_TAG_CDDA_MUSICBRAINZ_DISCID, "MUSICBRAINZ_DISCID"},
93   {GST_TAG_CDDA_CDDB_DISCID, "DISCID"},
94   /* For the apparent de-facto standard for coverart in vorbis comments, see:
95    * http://www.hydrogenaudio.org/forums/lofiversion/index.php/t48386.html */
96   {GST_TAG_PREVIEW_IMAGE, "COVERART"},
97   /* some evidence that "BPM" is used elsewhere:
98    * http://mail.kde.org/pipermail/amarok/2006-May/000090.html
99    */
100   {GST_TAG_BEATS_PER_MINUTE, "BPM"},
101   {NULL, NULL}
102 };
103
104 /**
105  * gst_tag_from_vorbis_tag:
106  * @vorbis_tag: vorbiscomment tag to convert to GStreamer tag
107  *
108  * Looks up the GStreamer tag for a vorbiscomment tag.
109  *
110  * Returns: The corresponding GStreamer tag or NULL if none exists.
111  */
112 G_CONST_RETURN gchar *
113 gst_tag_from_vorbis_tag (const gchar * vorbis_tag)
114 {
115   int i = 0;
116   gchar *real_vorbis_tag;
117
118   g_return_val_if_fail (vorbis_tag != NULL, NULL);
119
120   gst_tag_register_musicbrainz_tags ();
121
122   real_vorbis_tag = g_ascii_strup (vorbis_tag, -1);
123   while (tag_matches[i].gstreamer_tag != NULL) {
124     if (strcmp (real_vorbis_tag, tag_matches[i].original_tag) == 0) {
125       break;
126     }
127     i++;
128   }
129   g_free (real_vorbis_tag);
130   return tag_matches[i].gstreamer_tag;
131 }
132
133 /**
134  * gst_tag_to_vorbis_tag:
135  * @gst_tag: GStreamer tag to convert to vorbiscomment tag
136  *
137  * Looks up the vorbiscomment tag for a GStreamer tag.
138  *
139  * Returns: The corresponding vorbiscomment tag or NULL if none exists.
140  */
141 G_CONST_RETURN gchar *
142 gst_tag_to_vorbis_tag (const gchar * gst_tag)
143 {
144   int i = 0;
145
146   g_return_val_if_fail (gst_tag != NULL, NULL);
147
148   gst_tag_register_musicbrainz_tags ();
149
150   while (tag_matches[i].gstreamer_tag != NULL) {
151     if (strcmp (gst_tag, tag_matches[i].gstreamer_tag) == 0) {
152       return tag_matches[i].original_tag;
153     }
154     i++;
155   }
156   return NULL;
157 }
158
159
160 /**
161  * gst_vorbis_tag_add:
162  * @list: a #GstTagList
163  * @tag: a vorbiscomment tag string (key in key=value), must be valid UTF-8
164  * @value: a vorbiscomment value string (value in key=value), must be valid UTF-8
165  *
166  * Convenience function using gst_tag_from_vorbis_tag(), parsing
167  * a vorbis comment string into the right type and adding it to the
168  * given taglist @list.
169  *
170  * Unknown vorbiscomment tags will be added to the tag list in form
171  * of a #GST_TAG_EXTENDED_COMMENT (since 0.10.10 at least).
172  */
173 void
174 gst_vorbis_tag_add (GstTagList * list, const gchar * tag, const gchar * value)
175 {
176   const gchar *gst_tag;
177   GType tag_type;
178
179   g_return_if_fail (list != NULL);
180   g_return_if_fail (tag != NULL);
181   g_return_if_fail (value != NULL);
182
183   g_return_if_fail (g_utf8_validate (tag, -1, NULL));
184   g_return_if_fail (g_utf8_validate (value, -1, NULL));
185   g_return_if_fail (strchr (tag, '=') == NULL);
186
187   gst_tag = gst_tag_from_vorbis_tag (tag);
188   if (gst_tag == NULL) {
189     gchar *ext_comment;
190
191     ext_comment = g_strdup_printf ("%s=%s", tag, value);
192     gst_tag_list_add (list, GST_TAG_MERGE_APPEND, GST_TAG_EXTENDED_COMMENT,
193         ext_comment, NULL);
194     g_free (ext_comment);
195     return;
196   }
197
198   tag_type = gst_tag_get_type (gst_tag);
199   switch (tag_type) {
200     case G_TYPE_UINT:{
201       guint tmp;
202       gchar *check;
203       gboolean is_track_number_tag;
204       gboolean is_disc_number_tag;
205
206       is_track_number_tag = (strcmp (gst_tag, GST_TAG_TRACK_NUMBER) == 0);
207       is_disc_number_tag = (strcmp (gst_tag, GST_TAG_ALBUM_VOLUME_NUMBER) == 0);
208       tmp = strtoul (value, &check, 10);
209       if (*check == '/' && (is_track_number_tag || is_disc_number_tag)) {
210         guint count;
211
212         check++;
213         count = strtoul (check, &check, 10);
214         if (*check != '\0' || count == 0)
215           break;
216         if (is_track_number_tag) {
217           gst_tag_list_add (list, GST_TAG_MERGE_APPEND, GST_TAG_TRACK_COUNT,
218               count, NULL);
219         } else {
220           gst_tag_list_add (list, GST_TAG_MERGE_APPEND,
221               GST_TAG_ALBUM_VOLUME_COUNT, count, NULL);
222         }
223       }
224       if (*check == '\0') {
225         gst_tag_list_add (list, GST_TAG_MERGE_APPEND, gst_tag, tmp, NULL);
226       }
227       break;
228     }
229     case G_TYPE_STRING:{
230       gchar *valid = NULL;
231
232       /* specialcase for language code */
233       if (strcmp (tag, "LANGUAGE") == 0) {
234         const gchar *s = strchr (value, '[');
235
236         /* Accept both ISO-639-1 and ISO-639-2 codes */
237         if (s && strchr (s, ']') == s + 4) {
238           valid = g_strndup (s + 1, 3);
239         } else if (s && strchr (s, ']') == s + 3) {
240           valid = g_strndup (s + 1, 2);
241         } else if (strlen (value) != 2 && strlen (value) != 3) {
242           GST_WARNING ("doesn't contain an ISO-639 language code: %s", value);
243         }
244       } else if (strcmp (tag, "LICENSE") == 0) {
245         /* license tags in vorbis comments must contain an URI representing
246          * the license and nothing more, at least according to:
247          * http://wiki.xiph.org/index.php/LICENSE_and_COPYRIGHT_tags_on_Vorbis_Comments */
248         if (value && gst_uri_is_valid (value))
249           gst_tag = GST_TAG_LICENSE_URI;
250       }
251
252       if (!valid) {
253         valid = g_strdup (value);
254       }
255       gst_tag_list_add (list, GST_TAG_MERGE_APPEND, gst_tag, valid, NULL);
256       g_free (valid);
257       break;
258     }
259     case G_TYPE_DOUBLE:{
260       gchar *c;
261
262       c = g_strdup (value);
263       g_strdelimit (c, ",", '.');
264       gst_tag_list_add (list, GST_TAG_MERGE_APPEND, gst_tag,
265           g_strtod (c, NULL), NULL);
266       g_free (c);
267       break;
268     }
269     default:{
270       if (tag_type == GST_TYPE_DATE) {
271         guint y, d = 1, m = 1;
272         gchar *check = (gchar *) value;
273
274         y = strtoul (check, &check, 10);
275         if (*check == '-') {
276           check++;
277           m = strtoul (check, &check, 10);
278           if (*check == '-') {
279             check++;
280             d = strtoul (check, &check, 10);
281           }
282         }
283
284         /* accept dates like 2007-00-00 and 2007-05-00 */
285         if (y != 0) {
286           if (m == 0 && d == 0)
287             m = d = 1;
288           else if (m != 0 && d == 0)
289             d = 1;
290         }
291
292         /* date might be followed by a time */
293         if ((*check == '\0' || g_ascii_isspace (*check)) && y != 0 &&
294             g_date_valid_dmy (d, m, y)) {
295           GDate *date;
296
297           date = g_date_new_dmy (d, m, y);
298           gst_tag_list_add (list, GST_TAG_MERGE_APPEND, gst_tag, date, NULL);
299           g_date_free (date);
300         } else {
301           GST_DEBUG ("skipping invalid date '%s' (%u,%u,%u)", value, y, m, d);
302         }
303       } else {
304         GST_WARNING ("Unhandled tag of type '%s' (%d)",
305             g_type_name (tag_type), (gint) tag_type);
306       }
307       break;
308     }
309   }
310 }
311
312 static void
313 gst_vorbis_tag_add_coverart (GstTagList * tags, gchar * img_data_base64,
314     gint base64_len)
315 {
316   GstBuffer *img;
317   gsize img_len;
318
319   if (base64_len < 2)
320     goto not_enough_data;
321
322   /* img_data_base64 points to a temporary copy of the base64 encoded data, so
323    * it's safe to do inpace decoding here
324    */
325   g_base64_decode_inplace (img_data_base64, &img_len);
326   if (img_len == 0)
327     goto decode_failed;
328
329   img =
330       gst_tag_image_data_to_image_buffer ((const guint8 *) img_data_base64,
331       img_len, GST_TAG_IMAGE_TYPE_NONE);
332
333   if (img == NULL)
334     goto convert_failed;
335
336   gst_tag_list_add (tags, GST_TAG_MERGE_APPEND,
337       GST_TAG_PREVIEW_IMAGE, img, NULL);
338
339   gst_buffer_unref (img);
340   return;
341
342 /* ERRORS */
343 not_enough_data:
344   {
345     GST_WARNING ("COVERART tag with too little base64-encoded data");
346     return;
347   }
348 decode_failed:
349   {
350     GST_WARNING ("Couldn't decode base64 image data from COVERART tag");
351     return;
352   }
353 convert_failed:
354   {
355     GST_WARNING ("Couldn't extract image or image type from COVERART tag");
356     return;
357   }
358 }
359
360 /* Standardized way of adding pictures to vorbiscomments:
361  * http://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE
362  */
363 static void
364 gst_vorbis_tag_add_metadata_block_picture (GstTagList * tags,
365     gchar * value, gint value_len)
366 {
367   GstByteReader reader;
368   guint32 img_len = 0, img_type = 0;
369   guint32 img_mimetype_len = 0, img_description_len = 0;
370   gsize decoded_len;
371   const guint8 *data = NULL;
372
373   /* img_data_base64 points to a temporary copy of the base64 encoded data, so
374    * it's safe to do inpace decoding here
375    */
376   g_base64_decode_inplace (value, &decoded_len);
377   if (decoded_len == 0)
378     goto decode_failed;
379
380   gst_byte_reader_init (&reader, (guint8 *) value, decoded_len);
381
382   if (!gst_byte_reader_get_uint32_be (&reader, &img_type))
383     goto error;
384
385   if (!gst_byte_reader_get_uint32_be (&reader, &img_mimetype_len))
386     goto error;
387   if (!gst_byte_reader_skip (&reader, img_mimetype_len))
388     goto error;
389
390   if (!gst_byte_reader_get_uint32_be (&reader, &img_description_len))
391     goto error;
392   if (!gst_byte_reader_skip (&reader, img_description_len))
393     goto error;
394
395   /* Skip width, height, color depth and number of colors for
396    * indexed formats */
397   if (!gst_byte_reader_skip (&reader, 4 * 4))
398     goto error;
399
400   if (!gst_byte_reader_get_uint32_be (&reader, &img_len))
401     goto error;
402
403   if (!gst_byte_reader_get_data (&reader, img_len, &data))
404     goto error;
405
406   gst_tag_list_add_id3_image (tags, data, img_len, img_type);
407
408   return;
409
410 error:
411   GST_WARNING
412       ("Couldn't extract image or image type from METADATA_BLOCK_PICTURE tag");
413   return;
414 decode_failed:
415   GST_WARNING ("Failed to decode Base64 data from METADATA_BLOCK_PICTURE tag");
416   return;
417 }
418
419 /**
420  * gst_tag_list_from_vorbiscomment:
421  * @data: data to convert
422  * @size: size of @data
423  * @id_data: identification data at start of stream
424  * @id_data_length: length of identification data
425  * @vendor_string: pointer to a string that should take the vendor string
426  *                 of this vorbis comment or NULL if you don't need it.
427  *
428  * Creates a new tag list that contains the information parsed out of a
429  * vorbiscomment packet.
430  *
431  * Returns: A new #GstTagList with all tags that could be extracted from the
432  *          given vorbiscomment buffer or NULL on error.
433  */
434 GstTagList *
435 gst_tag_list_from_vorbiscomment (const guint8 * data, gsize size,
436     const guint8 * id_data, const guint id_data_length, gchar ** vendor_string)
437 {
438 #define ADVANCE(x) G_STMT_START{                                                \
439   data += x;                                                                    \
440   size -= x;                                                                    \
441   if (size < 4) goto error;                                                     \
442   cur_size = GST_READ_UINT32_LE (data);                                         \
443   data += 4;                                                                    \
444   size -= 4;                                                                    \
445   if (cur_size > size) goto error;                                              \
446   cur = (gchar*)data;                                                                   \
447 }G_STMT_END
448   gchar *cur, *value;
449   guint cur_size;
450   guint iterations;
451   guint value_len;
452   GstTagList *list;
453
454   g_return_val_if_fail (data != NULL, NULL);
455   g_return_val_if_fail (id_data != NULL || id_data_length == 0, NULL);
456
457   list = gst_tag_list_new ();
458
459   if (size < 11 || size <= id_data_length + 4)
460     goto error;
461
462   if (id_data_length > 0 && memcmp (data, id_data, id_data_length) != 0)
463     goto error;
464
465   ADVANCE (id_data_length);
466
467   if (vendor_string)
468     *vendor_string = g_strndup (cur, cur_size);
469
470   ADVANCE (cur_size);
471   iterations = cur_size;
472   cur_size = 0;
473
474   while (iterations) {
475     ADVANCE (cur_size);
476     iterations--;
477     cur = g_strndup (cur, cur_size);
478     value = strchr (cur, '=');
479     if (value == NULL) {
480       g_free (cur);
481       continue;
482     }
483     *value = '\0';
484     value++;
485     value_len = strlen (value);
486     if (value_len == 0 || !g_utf8_validate (value, value_len, NULL)) {
487       g_free (cur);
488       continue;
489     }
490     /* we'll just ignore COVERARTMIME and typefind the image data */
491     if (g_ascii_strcasecmp (cur, "COVERARTMIME") == 0) {
492       continue;
493     } else if (g_ascii_strcasecmp (cur, "COVERART") == 0) {
494       gst_vorbis_tag_add_coverart (list, value, value_len);
495     } else if (g_ascii_strcasecmp (cur, "METADATA_BLOCK_PICTURE") == 0) {
496       gst_vorbis_tag_add_metadata_block_picture (list, value, value_len);
497     } else {
498       gst_vorbis_tag_add (list, cur, value);
499     }
500     g_free (cur);
501   }
502
503   return list;
504
505 error:
506   gst_tag_list_free (list);
507   return NULL;
508 #undef ADVANCE
509 }
510
511 /**
512  * gst_tag_list_from_vorbiscomment_buffer:
513  * @buffer: buffer to convert
514  * @id_data: identification data at start of stream
515  * @id_data_length: length of identification data
516  * @vendor_string: pointer to a string that should take the vendor string
517  *                 of this vorbis comment or NULL if you don't need it.
518  *
519  * Creates a new tag list that contains the information parsed out of a
520  * vorbiscomment packet.
521  *
522  * Returns: A new #GstTagList with all tags that could be extracted from the
523  *          given vorbiscomment buffer or NULL on error.
524  */
525 GstTagList *
526 gst_tag_list_from_vorbiscomment_buffer (GstBuffer * buffer,
527     const guint8 * id_data, const guint id_data_length, gchar ** vendor_string)
528 {
529   GstTagList *res;
530   guint8 *data;
531   gsize size;
532
533   data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
534   res =
535       gst_tag_list_from_vorbiscomment (data, size, id_data, id_data_length,
536       vendor_string);
537   gst_buffer_unmap (buffer, data, size);
538
539   return res;
540 }
541
542 typedef struct
543 {
544   guint count;
545   guint data_count;
546   GList *entries;
547 }
548 MyForEach;
549
550 static GList *
551 gst_tag_to_metadata_block_picture (const gchar * tag,
552     const GValue * image_value)
553 {
554 #if 0
555   gchar *comment_data, *data_result;
556   const gchar *mime_type;
557   guint mime_type_len;
558   GstStructure *mime_struct;
559   GstBuffer *buffer;
560 #endif
561   GList *l = NULL;
562 #if 0
563   guint8 *data;
564   gsize size;
565   GstByteWriter writer;
566   GstTagImageType image_type = GST_TAG_IMAGE_TYPE_NONE;
567   gint width = 0, height = 0;
568   guint8 *metadata_block;
569   guint metadata_block_len;
570 #endif
571
572   g_return_val_if_fail (image_value != NULL, NULL);
573
574   /* FIXME, no more buffer caps */
575   g_assert_not_reached ();
576
577 #if 0
578   buffer = gst_value_get_buffer (image_value);
579   g_return_val_if_fail (gst_caps_is_fixed (buffer->caps), NULL);
580   mime_struct = gst_caps_get_structure (buffer->caps, 0);
581
582   mime_type = gst_structure_get_name (mime_struct);
583   if (strcmp (mime_type, "text/uri-list") == 0)
584     mime_type = "-->";
585   mime_type_len = strlen (mime_type);
586
587   gst_structure_get (mime_struct, "image-type", GST_TYPE_TAG_IMAGE_TYPE,
588       &image_type, "width", G_TYPE_INT, &width, "height", G_TYPE_INT, &height,
589       NULL);
590
591   metadata_block_len = 32 + mime_type_len + gst_buffer_get_size (buffer);
592   gst_byte_writer_init_with_size (&writer, metadata_block_len, TRUE);
593
594   if (image_type == GST_TAG_IMAGE_TYPE_NONE
595       && strcmp (tag, GST_TAG_PREVIEW_IMAGE) == 0) {
596     gst_byte_writer_put_uint32_be_unchecked (&writer, 0x01);
597   } else {
598     /* Convert to ID3v2 APIC image type */
599     if (image_type == GST_TAG_IMAGE_TYPE_NONE)
600       image_type = GST_TAG_IMAGE_TYPE_UNDEFINED;
601     else
602       image_type = image_type + 2;
603     gst_byte_writer_put_uint32_be_unchecked (&writer, image_type);
604   }
605
606   gst_byte_writer_put_uint32_be_unchecked (&writer, mime_type_len);
607   gst_byte_writer_put_data_unchecked (&writer, (guint8 *) mime_type,
608       mime_type_len);
609   /* description length */
610   gst_byte_writer_put_uint32_be_unchecked (&writer, 0);
611   gst_byte_writer_put_uint32_be_unchecked (&writer, width);
612   gst_byte_writer_put_uint32_be_unchecked (&writer, height);
613   /* color depth */
614   gst_byte_writer_put_uint32_be_unchecked (&writer, 0);
615   /* for indexed formats the number of colors */
616   gst_byte_writer_put_uint32_be_unchecked (&writer, 0);
617
618   data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
619   gst_byte_writer_put_uint32_be_unchecked (&writer, size);
620   gst_byte_writer_put_data_unchecked (&writer, data, size);
621   gst_buffer_unmap (buffer, data, size);
622
623   g_assert (gst_byte_writer_get_pos (&writer) == metadata_block_len);
624
625   metadata_block = gst_byte_writer_reset_and_get_data (&writer);
626   comment_data = g_base64_encode (metadata_block, metadata_block_len);
627   g_free (metadata_block);
628   data_result = g_strdup_printf ("METADATA_BLOCK_PICTURE=%s", comment_data);
629   g_free (comment_data);
630
631   l = g_list_append (l, data_result);
632 #endif
633
634   return l;
635 }
636
637 /**
638  * gst_tag_to_vorbis_comments:
639  * @list: a #GstTagList
640  * @tag: a GStreamer tag identifier, such as #GST_TAG_ARTIST
641  *
642  * Creates a new tag list that contains the information parsed out of a
643  * vorbiscomment packet.
644  *
645  * Returns: A #GList of newly-allowcated key=value strings. Free with
646  *          g_list_foreach (list, (GFunc) g_free, NULL) plus g_list_free (list)
647  */
648 GList *
649 gst_tag_to_vorbis_comments (const GstTagList * list, const gchar * tag)
650 {
651   const gchar *vorbis_tag = NULL;
652   GList *l = NULL;
653   guint i;
654
655   g_return_val_if_fail (list != NULL, NULL);
656   g_return_val_if_fail (tag != NULL, NULL);
657
658   /* Special case: cover art is split into two tags to store data and
659    * MIME-type. Even if the tag list contains multiple entries, there is
660    * no reasonable way to save more than one.
661    * If both, preview image and image, are present we prefer the
662    * image tag.
663    */
664   if ((strcmp (tag, GST_TAG_PREVIEW_IMAGE) == 0 &&
665           gst_tag_list_get_tag_size (list, GST_TAG_IMAGE) == 0) ||
666       strcmp (tag, GST_TAG_IMAGE) == 0) {
667     return gst_tag_to_metadata_block_picture (tag,
668         gst_tag_list_get_value_index (list, tag, 0));
669   }
670
671   if (strcmp (tag, GST_TAG_EXTENDED_COMMENT) != 0) {
672     vorbis_tag = gst_tag_to_vorbis_tag (tag);
673     if (!vorbis_tag)
674       return NULL;
675   }
676
677   /* FIXME: for tags that can map to multiple vorbis comment keys, add all
678    * of the possible keys */
679   for (i = 0; i < gst_tag_list_get_tag_size (list, tag); i++) {
680     GType tag_type = gst_tag_get_type (tag);
681     gchar *result = NULL;
682
683     switch (tag_type) {
684       case G_TYPE_UINT:{
685         guint u;
686
687         if (!gst_tag_list_get_uint_index (list, tag, i, &u))
688           g_return_val_if_reached (NULL);
689         result = g_strdup_printf ("%s=%u", vorbis_tag, u);
690         break;
691       }
692       case G_TYPE_STRING:{
693         const gchar *str = NULL;
694
695         if (!gst_tag_list_peek_string_index (list, tag, i, &str))
696           g_return_val_if_reached (NULL);
697
698         /* special case: GST_TAG_EXTENDED_COMMENT */
699         if (vorbis_tag == NULL) {
700           gchar *key = NULL, *val = NULL;
701
702           if (gst_tag_parse_extended_comment (str, &key, NULL, &val, TRUE)) {
703             result = g_strdup_printf ("%s=%s", key, val);
704             g_free (key);
705             g_free (val);
706           } else {
707             GST_WARNING ("Not a valid extended comment string: %s", str);
708             continue;
709           }
710         } else {
711           result = g_strdup_printf ("%s=%s", vorbis_tag, str);
712         }
713         break;
714       }
715       case G_TYPE_DOUBLE:{
716         gdouble value;
717         gchar buf[G_ASCII_DTOSTR_BUF_SIZE];
718
719         if (!gst_tag_list_get_double_index (list, tag, i, &value))
720           g_return_val_if_reached (NULL);
721         g_ascii_formatd (buf, G_ASCII_DTOSTR_BUF_SIZE, "%f", value);
722         result = g_strconcat (vorbis_tag, "=", buf, NULL);
723         break;
724       }
725       default:{
726         if (tag_type == GST_TYPE_DATE) {
727           GDate *date;
728
729           if (!gst_tag_list_get_date_index (list, tag, i, &date))
730             g_return_val_if_reached (NULL);
731
732           /* vorbis suggests using ISO date formats */
733           result =
734               g_strdup_printf ("%s=%04d-%02d-%02d", vorbis_tag,
735               (gint) g_date_get_year (date), (gint) g_date_get_month (date),
736               (gint) g_date_get_day (date));
737           g_date_free (date);
738         } else {
739           GST_DEBUG ("Couldn't write tag %s", tag);
740           continue;
741         }
742         break;
743       }
744     }
745     l = g_list_prepend (l, result);
746   }
747
748   return g_list_reverse (l);
749 }
750
751 static void
752 write_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
753 {
754   MyForEach *data = (MyForEach *) user_data;
755   GList *comments;
756   GList *it;
757
758   comments = gst_tag_to_vorbis_comments (list, tag);
759
760   for (it = comments; it != NULL; it = it->next) {
761     gchar *result = it->data;
762
763     data->count++;
764     data->data_count += strlen (result);
765     data->entries = g_list_prepend (data->entries, result);
766   }
767
768   g_list_free (comments);
769 }
770
771 /**
772  * gst_tag_list_to_vorbiscomment_buffer:
773  * @list: tag list to convert
774  * @id_data: identification data at start of stream
775  * @id_data_length: length of identification data, may be 0 if @id_data is NULL
776  * @vendor_string: string that describes the vendor string or NULL
777  *
778  * Creates a new vorbiscomment buffer from a tag list.
779  *
780  * Returns: A new #GstBuffer containing a vorbiscomment buffer with all tags
781  *          that could be converted from the given tag list.
782  */
783 GstBuffer *
784 gst_tag_list_to_vorbiscomment_buffer (const GstTagList * list,
785     const guint8 * id_data, const guint id_data_length,
786     const gchar * vendor_string)
787 {
788   GstBuffer *buffer;
789   guint8 *data, *odata;
790   guint i;
791   GList *l;
792   MyForEach my_data = { 0, 0, NULL };
793   guint vendor_len;
794   int required_size;
795
796   g_return_val_if_fail (GST_IS_TAG_LIST (list), NULL);
797   g_return_val_if_fail (id_data != NULL || id_data_length == 0, NULL);
798
799   if (vendor_string == NULL)
800     vendor_string = "GStreamer encoded vorbiscomment";
801   vendor_len = strlen (vendor_string);
802   required_size = id_data_length + 4 + vendor_len + 4 + 1;
803   gst_tag_list_foreach ((GstTagList *) list, write_one_tag, &my_data);
804   required_size += 4 * my_data.count + my_data.data_count;
805
806   buffer = gst_buffer_new_and_alloc (required_size);
807   odata = data = gst_buffer_map (buffer, NULL, NULL, GST_MAP_WRITE);
808   if (id_data_length > 0) {
809     memcpy (data, id_data, id_data_length);
810     data += id_data_length;
811   }
812   GST_WRITE_UINT32_LE (data, vendor_len);
813   data += 4;
814   memcpy (data, vendor_string, vendor_len);
815   data += vendor_len;
816   l = my_data.entries = g_list_reverse (my_data.entries);
817   GST_WRITE_UINT32_LE (data, my_data.count);
818   data += 4;
819   for (i = 0; i < my_data.count; i++) {
820     guint size;
821     gchar *cur;
822
823     g_assert (l != NULL);
824     cur = l->data;
825     l = g_list_next (l);
826     size = strlen (cur);
827     GST_WRITE_UINT32_LE (data, size);
828     data += 4;
829     memcpy (data, cur, size);
830     data += size;
831   }
832   g_list_foreach (my_data.entries, (GFunc) g_free, NULL);
833   g_list_free (my_data.entries);
834   *data = 1;
835   gst_buffer_unmap (buffer, odata, required_size);
836
837   return buffer;
838 }