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