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