tizen 2.0 init
[framework/multimedia/gst-plugins-good0.10.git] / gst / matroska / matroska-read-common.c
1 /* GStreamer Matroska muxer/demuxer
2  * (c) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
3  * (c) 2006 Tim-Philipp Müller <tim centricular net>
4  * (c) 2008 Sebastian Dröge <slomo@circular-chaos.org>
5  * (c) 2011 Debarshi Ray <rishi@gnu.org>
6  *
7  * matroska-read-common.c: shared by matroska file/stream demuxer and parser
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include <stdio.h>
30 #include <string.h>
31
32 #ifdef HAVE_ZLIB
33 #include <zlib.h>
34 #endif
35
36 #ifdef HAVE_BZ2
37 #include <bzlib.h>
38 #endif
39
40 #include <gst/tag/tag.h>
41 #include <gst/base/gsttypefindhelper.h>
42
43 #include "lzo.h"
44
45 #include "ebml-read.h"
46 #include "matroska-read-common.h"
47
48 GST_DEBUG_CATEGORY (matroskareadcommon_debug);
49 #define GST_CAT_DEFAULT matroskareadcommon_debug
50
51 #define DEBUG_ELEMENT_START(common, ebml, element) \
52     GST_DEBUG_OBJECT (common, "Parsing " element " element at offset %" \
53         G_GUINT64_FORMAT, gst_ebml_read_get_pos (ebml))
54
55 #define DEBUG_ELEMENT_STOP(common, ebml, element, ret) \
56     GST_DEBUG_OBJECT (common, "Parsing " element " element " \
57         " finished with '%s'", gst_flow_get_name (ret))
58
59 static gboolean
60 gst_matroska_decompress_data (GstMatroskaTrackEncoding * enc,
61     guint8 ** data_out, guint * size_out,
62     GstMatroskaTrackCompressionAlgorithm algo)
63 {
64   guint8 *new_data = NULL;
65   guint new_size = 0;
66   guint8 *data = *data_out;
67   guint size = *size_out;
68   gboolean ret = TRUE;
69
70   if (algo == GST_MATROSKA_TRACK_COMPRESSION_ALGORITHM_ZLIB) {
71 #ifdef HAVE_ZLIB
72     /* zlib encoded data */
73     z_stream zstream;
74     guint orig_size;
75     int result;
76
77     orig_size = size;
78     zstream.zalloc = (alloc_func) 0;
79     zstream.zfree = (free_func) 0;
80     zstream.opaque = (voidpf) 0;
81     if (inflateInit (&zstream) != Z_OK) {
82       GST_WARNING ("zlib initialization failed.");
83       ret = FALSE;
84       goto out;
85     }
86     zstream.next_in = (Bytef *) data;
87     zstream.avail_in = orig_size;
88     new_size = orig_size;
89     new_data = g_malloc (new_size);
90     zstream.avail_out = new_size;
91     zstream.next_out = (Bytef *) new_data;
92
93     do {
94       result = inflate (&zstream, Z_NO_FLUSH);
95       if (result != Z_OK && result != Z_STREAM_END) {
96         GST_WARNING ("zlib decompression failed.");
97         g_free (new_data);
98         inflateEnd (&zstream);
99         break;
100       }
101       new_size += 4000;
102       new_data = g_realloc (new_data, new_size);
103       zstream.next_out = (Bytef *) (new_data + zstream.total_out);
104       zstream.avail_out += 4000;
105     } while (zstream.avail_in != 0 && result != Z_STREAM_END);
106
107     if (result != Z_STREAM_END) {
108       ret = FALSE;
109       goto out;
110     } else {
111       new_size = zstream.total_out;
112       inflateEnd (&zstream);
113     }
114 #else
115     GST_WARNING ("zlib encoded tracks not supported.");
116     ret = FALSE;
117     goto out;
118 #endif
119   } else if (algo == GST_MATROSKA_TRACK_COMPRESSION_ALGORITHM_BZLIB) {
120 #ifdef HAVE_BZ2
121     /* bzip2 encoded data */
122     bz_stream bzstream;
123     guint orig_size;
124     int result;
125
126     bzstream.bzalloc = NULL;
127     bzstream.bzfree = NULL;
128     bzstream.opaque = NULL;
129     orig_size = size;
130
131     if (BZ2_bzDecompressInit (&bzstream, 0, 0) != BZ_OK) {
132       GST_WARNING ("bzip2 initialization failed.");
133       ret = FALSE;
134       goto out;
135     }
136
137     bzstream.next_in = (char *) data;
138     bzstream.avail_in = orig_size;
139     new_size = orig_size;
140     new_data = g_malloc (new_size);
141     bzstream.avail_out = new_size;
142     bzstream.next_out = (char *) new_data;
143
144     do {
145       result = BZ2_bzDecompress (&bzstream);
146       if (result != BZ_OK && result != BZ_STREAM_END) {
147         GST_WARNING ("bzip2 decompression failed.");
148         g_free (new_data);
149         BZ2_bzDecompressEnd (&bzstream);
150         break;
151       }
152       new_size += 4000;
153       new_data = g_realloc (new_data, new_size);
154       bzstream.next_out = (char *) (new_data + bzstream.total_out_lo32);
155       bzstream.avail_out += 4000;
156     } while (bzstream.avail_in != 0 && result != BZ_STREAM_END);
157
158     if (result != BZ_STREAM_END) {
159       ret = FALSE;
160       goto out;
161     } else {
162       new_size = bzstream.total_out_lo32;
163       BZ2_bzDecompressEnd (&bzstream);
164     }
165 #else
166     GST_WARNING ("bzip2 encoded tracks not supported.");
167     ret = FALSE;
168     goto out;
169 #endif
170   } else if (algo == GST_MATROSKA_TRACK_COMPRESSION_ALGORITHM_LZO1X) {
171     /* lzo encoded data */
172     int result;
173     int orig_size, out_size;
174
175     orig_size = size;
176     out_size = size;
177     new_size = size;
178     new_data = g_malloc (new_size);
179
180     do {
181       orig_size = size;
182       out_size = new_size;
183
184       result = lzo1x_decode (new_data, &out_size, data, &orig_size);
185
186       if (orig_size > 0) {
187         new_size += 4000;
188         new_data = g_realloc (new_data, new_size);
189       }
190     } while (orig_size > 0 && result == LZO_OUTPUT_FULL);
191
192     new_size -= out_size;
193
194     if (result != LZO_OUTPUT_FULL) {
195       GST_WARNING ("lzo decompression failed");
196       g_free (new_data);
197
198       ret = FALSE;
199       goto out;
200     }
201
202   } else if (algo == GST_MATROSKA_TRACK_COMPRESSION_ALGORITHM_HEADERSTRIP) {
203     /* header stripped encoded data */
204     if (enc->comp_settings_length > 0) {
205       new_data = g_malloc (size + enc->comp_settings_length);
206       new_size = size + enc->comp_settings_length;
207
208       memcpy (new_data, enc->comp_settings, enc->comp_settings_length);
209       memcpy (new_data + enc->comp_settings_length, data, size);
210     }
211   } else {
212     GST_ERROR ("invalid compression algorithm %d", algo);
213     ret = FALSE;
214   }
215
216 out:
217
218   if (!ret) {
219     *data_out = NULL;
220     *size_out = 0;
221   } else {
222     *data_out = new_data;
223     *size_out = new_size;
224   }
225
226   return ret;
227 }
228
229 GstFlowReturn
230 gst_matroska_decode_content_encodings (GArray * encodings)
231 {
232   gint i;
233
234   if (encodings == NULL)
235     return GST_FLOW_OK;
236
237   for (i = 0; i < encodings->len; i++) {
238     GstMatroskaTrackEncoding *enc =
239         &g_array_index (encodings, GstMatroskaTrackEncoding, i);
240     guint8 *data = NULL;
241     guint size;
242
243     if ((enc->scope & GST_MATROSKA_TRACK_ENCODING_SCOPE_NEXT_CONTENT_ENCODING)
244         == 0)
245       continue;
246
247     /* Encryption not supported yet */
248     if (enc->type != 0)
249       return GST_FLOW_ERROR;
250
251     if (i + 1 >= encodings->len)
252       return GST_FLOW_ERROR;
253
254     if (enc->comp_settings_length == 0)
255       continue;
256
257     data = enc->comp_settings;
258     size = enc->comp_settings_length;
259
260     if (!gst_matroska_decompress_data (enc, &data, &size, enc->comp_algo))
261       return GST_FLOW_ERROR;
262
263     g_free (enc->comp_settings);
264
265     enc->comp_settings = data;
266     enc->comp_settings_length = size;
267   }
268
269   return GST_FLOW_OK;
270 }
271
272 gboolean
273 gst_matroska_decode_data (GArray * encodings, guint8 ** data_out,
274     guint * size_out, GstMatroskaTrackEncodingScope scope, gboolean free)
275 {
276   guint8 *data;
277   guint size;
278   gboolean ret = TRUE;
279   gint i;
280
281   g_return_val_if_fail (encodings != NULL, FALSE);
282   g_return_val_if_fail (data_out != NULL && *data_out != NULL, FALSE);
283   g_return_val_if_fail (size_out != NULL, FALSE);
284
285   data = *data_out;
286   size = *size_out;
287
288   for (i = 0; i < encodings->len; i++) {
289     GstMatroskaTrackEncoding *enc =
290         &g_array_index (encodings, GstMatroskaTrackEncoding, i);
291     guint8 *new_data = NULL;
292     guint new_size = 0;
293
294     if ((enc->scope & scope) == 0)
295       continue;
296
297     /* Encryption not supported yet */
298     if (enc->type != 0) {
299       ret = FALSE;
300       break;
301     }
302
303     new_data = data;
304     new_size = size;
305
306     ret =
307         gst_matroska_decompress_data (enc, &new_data, &new_size,
308         enc->comp_algo);
309
310     if (!ret)
311       break;
312
313     if ((data == *data_out && free) || (data != *data_out))
314       g_free (data);
315
316     data = new_data;
317     size = new_size;
318   }
319
320   if (!ret) {
321     if ((data == *data_out && free) || (data != *data_out))
322       g_free (data);
323
324     *data_out = NULL;
325     *size_out = 0;
326   } else {
327     *data_out = data;
328     *size_out = size;
329   }
330
331   return ret;
332 }
333
334 static gint
335 gst_matroska_index_compare (GstMatroskaIndex * i1, GstMatroskaIndex * i2)
336 {
337   if (i1->time < i2->time)
338     return -1;
339   else if (i1->time > i2->time)
340     return 1;
341   else if (i1->block < i2->block)
342     return -1;
343   else if (i1->block > i2->block)
344     return 1;
345   else
346     return 0;
347 }
348
349 gint
350 gst_matroska_index_seek_find (GstMatroskaIndex * i1, GstClockTime * time,
351     gpointer user_data)
352 {
353   if (i1->time < *time)
354     return -1;
355   else if (i1->time > *time)
356     return 1;
357   else
358     return 0;
359 }
360
361 GstMatroskaIndex *
362 gst_matroska_read_common_do_index_seek (GstMatroskaReadCommon * common,
363     GstMatroskaTrackContext * track, gint64 seek_pos, GArray ** _index,
364     gint * _entry_index)
365 {
366   GstMatroskaIndex *entry = NULL;
367   GArray *index;
368
369   if (!common->index || !common->index->len)
370     return NULL;
371
372   /* find entry just before or at the requested position */
373   if (track && track->index_table)
374     index = track->index_table;
375   else
376     index = common->index;
377
378   entry =
379       gst_util_array_binary_search (index->data, index->len,
380       sizeof (GstMatroskaIndex),
381       (GCompareDataFunc) gst_matroska_index_seek_find, GST_SEARCH_MODE_BEFORE,
382       &seek_pos, NULL);
383
384   if (entry == NULL)
385     entry = &g_array_index (index, GstMatroskaIndex, 0);
386
387   if (_index)
388     *_index = index;
389   if (_entry_index)
390     *_entry_index = entry - (GstMatroskaIndex *) index->data;
391
392   return entry;
393 }
394
395 static gint
396 gst_matroska_read_common_encoding_cmp (GstMatroskaTrackEncoding * a,
397     GstMatroskaTrackEncoding * b)
398 {
399   if (b->order > a->order)
400     return 1;
401   else if (b->order < a->order)
402     return -1;
403   else
404     return 0;
405 }
406
407 static gboolean
408 gst_matroska_read_common_encoding_order_unique (GArray * encodings, guint64
409     order)
410 {
411   gint i;
412
413   if (encodings == NULL || encodings->len == 0)
414     return TRUE;
415
416   for (i = 0; i < encodings->len; i++)
417     if (g_array_index (encodings, GstMatroskaTrackEncoding, i).order == order)
418       return FALSE;
419
420   return TRUE;
421 }
422
423 /* takes ownership of taglist */
424 void
425 gst_matroska_read_common_found_global_tag (GstMatroskaReadCommon * common,
426     GstElement * el, GstTagList * taglist)
427 {
428   if (common->global_tags) {
429     /* nothing sent yet, add to cache */
430     gst_tag_list_insert (common->global_tags, taglist, GST_TAG_MERGE_APPEND);
431     gst_tag_list_free (taglist);
432   } else {
433     /* hm, already sent, no need to cache and wait anymore */
434     GST_DEBUG_OBJECT (common, "Sending late global tags %" GST_PTR_FORMAT,
435         taglist);
436     gst_element_found_tags (el, taglist);
437   }
438 }
439
440 gint64
441 gst_matroska_read_common_get_length (GstMatroskaReadCommon * common)
442 {
443   GstFormat fmt = GST_FORMAT_BYTES;
444   gint64 end = -1;
445
446   if (!gst_pad_query_peer_duration (common->sinkpad, &fmt, &end) ||
447       fmt != GST_FORMAT_BYTES || end < 0)
448     GST_DEBUG_OBJECT (common, "no upstream length");
449
450   return end;
451 }
452
453 /* determine track to seek in */
454 GstMatroskaTrackContext *
455 gst_matroska_read_common_get_seek_track (GstMatroskaReadCommon * common,
456     GstMatroskaTrackContext * track)
457 {
458   gint i;
459
460   if (track && track->type == GST_MATROSKA_TRACK_TYPE_VIDEO)
461     return track;
462
463   for (i = 0; i < common->src->len; i++) {
464     GstMatroskaTrackContext *stream;
465
466     stream = g_ptr_array_index (common->src, i);
467     if (stream->type == GST_MATROSKA_TRACK_TYPE_VIDEO && stream->index_table)
468       track = stream;
469   }
470
471   return track;
472 }
473
474 /* skip unknown or alike element */
475 GstFlowReturn
476 gst_matroska_read_common_parse_skip (GstMatroskaReadCommon * common,
477     GstEbmlRead * ebml, const gchar * parent_name, guint id)
478 {
479   if (id == GST_EBML_ID_VOID) {
480     GST_DEBUG_OBJECT (common, "Skipping EBML Void element");
481   } else if (id == GST_EBML_ID_CRC32) {
482     GST_DEBUG_OBJECT (common, "Skipping EBML CRC32 element");
483   } else {
484     GST_WARNING_OBJECT (common,
485         "Unknown %s subelement 0x%x - ignoring", parent_name, id);
486   }
487
488   return gst_ebml_read_skip (ebml);
489 }
490
491 static GstFlowReturn
492 gst_matroska_read_common_parse_attached_file (GstMatroskaReadCommon * common,
493     GstEbmlRead * ebml, GstTagList * taglist)
494 {
495   guint32 id;
496   GstFlowReturn ret;
497   gchar *description = NULL;
498   gchar *filename = NULL;
499   gchar *mimetype = NULL;
500   guint8 *data = NULL;
501   guint64 datalen = 0;
502
503   DEBUG_ELEMENT_START (common, ebml, "AttachedFile");
504
505   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
506     DEBUG_ELEMENT_STOP (common, ebml, "AttachedFile", ret);
507     return ret;
508   }
509
510   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
511     /* read all sub-entries */
512
513     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
514       break;
515
516     switch (id) {
517       case GST_MATROSKA_ID_FILEDESCRIPTION:
518         if (description) {
519           GST_WARNING_OBJECT (common, "FileDescription can only appear once");
520           break;
521         }
522
523         ret = gst_ebml_read_utf8 (ebml, &id, &description);
524         GST_DEBUG_OBJECT (common, "FileDescription: %s",
525             GST_STR_NULL (description));
526         break;
527       case GST_MATROSKA_ID_FILENAME:
528         if (filename) {
529           GST_WARNING_OBJECT (common, "FileName can only appear once");
530           break;
531         }
532
533         ret = gst_ebml_read_utf8 (ebml, &id, &filename);
534
535         GST_DEBUG_OBJECT (common, "FileName: %s", GST_STR_NULL (filename));
536         break;
537       case GST_MATROSKA_ID_FILEMIMETYPE:
538         if (mimetype) {
539           GST_WARNING_OBJECT (common, "FileMimeType can only appear once");
540           break;
541         }
542
543         ret = gst_ebml_read_ascii (ebml, &id, &mimetype);
544         GST_DEBUG_OBJECT (common, "FileMimeType: %s", GST_STR_NULL (mimetype));
545         break;
546       case GST_MATROSKA_ID_FILEDATA:
547         if (data) {
548           GST_WARNING_OBJECT (common, "FileData can only appear once");
549           break;
550         }
551
552         ret = gst_ebml_read_binary (ebml, &id, &data, &datalen);
553         GST_DEBUG_OBJECT (common, "FileData of size %" G_GUINT64_FORMAT,
554             datalen);
555         break;
556
557       default:
558         ret = gst_matroska_read_common_parse_skip (common, ebml,
559             "AttachedFile", id);
560         break;
561       case GST_MATROSKA_ID_FILEUID:
562         ret = gst_ebml_read_skip (ebml);
563         break;
564     }
565   }
566
567   DEBUG_ELEMENT_STOP (common, ebml, "AttachedFile", ret);
568
569   if (filename && mimetype && data && datalen > 0) {
570     GstTagImageType image_type = GST_TAG_IMAGE_TYPE_NONE;
571     GstBuffer *tagbuffer = NULL;
572     GstCaps *caps;
573     gchar *filename_lc = g_utf8_strdown (filename, -1);
574
575     GST_DEBUG_OBJECT (common, "Creating tag for attachment with "
576         "filename '%s', mimetype '%s', description '%s', "
577         "size %" G_GUINT64_FORMAT, filename, mimetype,
578         GST_STR_NULL (description), datalen);
579
580     /* TODO: better heuristics for different image types */
581     if (strstr (filename_lc, "cover")) {
582       if (strstr (filename_lc, "back"))
583         image_type = GST_TAG_IMAGE_TYPE_BACK_COVER;
584       else
585         image_type = GST_TAG_IMAGE_TYPE_FRONT_COVER;
586     } else if (g_str_has_prefix (mimetype, "image/") ||
587         g_str_has_suffix (filename_lc, "png") ||
588         g_str_has_suffix (filename_lc, "jpg") ||
589         g_str_has_suffix (filename_lc, "jpeg") ||
590         g_str_has_suffix (filename_lc, "gif") ||
591         g_str_has_suffix (filename_lc, "bmp")) {
592       image_type = GST_TAG_IMAGE_TYPE_UNDEFINED;
593     }
594     g_free (filename_lc);
595
596     /* First try to create an image tag buffer from this */
597     if (image_type != GST_TAG_IMAGE_TYPE_NONE) {
598       tagbuffer =
599           gst_tag_image_data_to_image_buffer (data, datalen, image_type);
600
601       if (!tagbuffer)
602         image_type = GST_TAG_IMAGE_TYPE_NONE;
603     }
604
605     /* if this failed create an attachment buffer */
606     if (!tagbuffer) {
607       tagbuffer = gst_buffer_new_and_alloc (datalen);
608
609       memcpy (GST_BUFFER_DATA (tagbuffer), data, datalen);
610       GST_BUFFER_SIZE (tagbuffer) = datalen;
611
612       caps = gst_type_find_helper_for_buffer (NULL, tagbuffer, NULL);
613       if (caps == NULL)
614         caps = gst_caps_new_simple (mimetype, NULL);
615       gst_buffer_set_caps (tagbuffer, caps);
616       gst_caps_unref (caps);
617     }
618
619     /* Set filename and description on the caps */
620     caps = GST_BUFFER_CAPS (tagbuffer);
621     gst_caps_set_simple (caps, "filename", G_TYPE_STRING, filename, NULL);
622     if (description)
623       gst_caps_set_simple (caps, "description", G_TYPE_STRING, description,
624           NULL);
625
626     GST_DEBUG_OBJECT (common,
627         "Created attachment buffer with caps: %" GST_PTR_FORMAT, caps);
628
629     /* and append to the tag list */
630     if (image_type != GST_TAG_IMAGE_TYPE_NONE)
631       gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND, GST_TAG_IMAGE, tagbuffer,
632           NULL);
633     else
634       gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND, GST_TAG_ATTACHMENT,
635           tagbuffer, NULL);
636
637     /* the tag list adds it own ref */
638     gst_buffer_unref (tagbuffer);
639   }
640
641   g_free (filename);
642   g_free (mimetype);
643   g_free (data);
644   g_free (description);
645
646   return ret;
647 }
648
649 GstFlowReturn
650 gst_matroska_read_common_parse_attachments (GstMatroskaReadCommon * common,
651     GstElement * el, GstEbmlRead * ebml)
652 {
653   guint32 id;
654   GstFlowReturn ret = GST_FLOW_OK;
655   GstTagList *taglist;
656
657   DEBUG_ELEMENT_START (common, ebml, "Attachments");
658
659   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
660     DEBUG_ELEMENT_STOP (common, ebml, "Attachments", ret);
661     return ret;
662   }
663
664   taglist = gst_tag_list_new ();
665
666   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
667     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
668       break;
669
670     switch (id) {
671       case GST_MATROSKA_ID_ATTACHEDFILE:
672         ret = gst_matroska_read_common_parse_attached_file (common, ebml,
673             taglist);
674         break;
675
676       default:
677         ret = gst_matroska_read_common_parse_skip (common, ebml,
678             "Attachments", id);
679         break;
680     }
681   }
682   DEBUG_ELEMENT_STOP (common, ebml, "Attachments", ret);
683
684   if (gst_structure_n_fields (GST_STRUCTURE (taglist)) > 0) {
685     GST_DEBUG_OBJECT (common, "Storing attachment tags");
686     gst_matroska_read_common_found_global_tag (common, el, taglist);
687   } else {
688     GST_DEBUG_OBJECT (common, "No valid attachments found");
689     gst_tag_list_free (taglist);
690   }
691
692   common->attachments_parsed = TRUE;
693
694   return ret;
695 }
696
697 GstFlowReturn
698 gst_matroska_read_common_parse_chapters (GstMatroskaReadCommon * common,
699     GstEbmlRead * ebml)
700 {
701   guint32 id;
702   GstFlowReturn ret = GST_FLOW_OK;
703
704   GST_WARNING_OBJECT (common, "Parsing of chapters not implemented yet");
705
706   /* TODO: implement parsing of chapters */
707
708   DEBUG_ELEMENT_START (common, ebml, "Chapters");
709
710   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
711     DEBUG_ELEMENT_STOP (common, ebml, "Chapters", ret);
712     return ret;
713   }
714
715   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
716     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
717       break;
718
719     switch (id) {
720       default:
721         ret = gst_ebml_read_skip (ebml);
722         break;
723     }
724   }
725
726   DEBUG_ELEMENT_STOP (common, ebml, "Chapters", ret);
727   return ret;
728 }
729
730 GstFlowReturn
731 gst_matroska_read_common_parse_header (GstMatroskaReadCommon * common,
732     GstEbmlRead * ebml)
733 {
734   GstFlowReturn ret;
735   gchar *doctype;
736   guint version;
737   guint32 id;
738
739   /* this function is the first to be called */
740
741   /* default init */
742   doctype = NULL;
743   version = 1;
744
745   ret = gst_ebml_peek_id (ebml, &id);
746   if (ret != GST_FLOW_OK)
747     return ret;
748
749   GST_DEBUG_OBJECT (common, "id: %08x", id);
750
751   if (id != GST_EBML_ID_HEADER) {
752     GST_ERROR_OBJECT (common, "Failed to read header");
753     goto exit;
754   }
755
756   ret = gst_ebml_read_master (ebml, &id);
757   if (ret != GST_FLOW_OK)
758     return ret;
759
760   while (gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
761     ret = gst_ebml_peek_id (ebml, &id);
762     if (ret != GST_FLOW_OK)
763       return ret;
764
765     switch (id) {
766         /* is our read version uptodate? */
767       case GST_EBML_ID_EBMLREADVERSION:{
768         guint64 num;
769
770         ret = gst_ebml_read_uint (ebml, &id, &num);
771         if (ret != GST_FLOW_OK)
772           return ret;
773         if (num != GST_EBML_VERSION) {
774           GST_ERROR_OBJECT (ebml, "Unsupported EBML version %" G_GUINT64_FORMAT,
775               num);
776           return GST_FLOW_ERROR;
777         }
778
779         GST_DEBUG_OBJECT (ebml, "EbmlReadVersion: %" G_GUINT64_FORMAT, num);
780         break;
781       }
782
783         /* we only handle 8 byte lengths at max */
784       case GST_EBML_ID_EBMLMAXSIZELENGTH:{
785         guint64 num;
786
787         ret = gst_ebml_read_uint (ebml, &id, &num);
788         if (ret != GST_FLOW_OK)
789           return ret;
790         if (num > sizeof (guint64)) {
791           GST_ERROR_OBJECT (ebml,
792               "Unsupported EBML maximum size %" G_GUINT64_FORMAT, num);
793           return GST_FLOW_ERROR;
794         }
795         GST_DEBUG_OBJECT (ebml, "EbmlMaxSizeLength: %" G_GUINT64_FORMAT, num);
796         break;
797       }
798
799         /* we handle 4 byte IDs at max */
800       case GST_EBML_ID_EBMLMAXIDLENGTH:{
801         guint64 num;
802
803         ret = gst_ebml_read_uint (ebml, &id, &num);
804         if (ret != GST_FLOW_OK)
805           return ret;
806         if (num > sizeof (guint32)) {
807           GST_ERROR_OBJECT (ebml,
808               "Unsupported EBML maximum ID %" G_GUINT64_FORMAT, num);
809           return GST_FLOW_ERROR;
810         }
811         GST_DEBUG_OBJECT (ebml, "EbmlMaxIdLength: %" G_GUINT64_FORMAT, num);
812         break;
813       }
814
815       case GST_EBML_ID_DOCTYPE:{
816         gchar *text;
817
818         ret = gst_ebml_read_ascii (ebml, &id, &text);
819         if (ret != GST_FLOW_OK)
820           return ret;
821
822         GST_DEBUG_OBJECT (ebml, "EbmlDocType: %s", GST_STR_NULL (text));
823
824         if (doctype)
825           g_free (doctype);
826         doctype = text;
827         break;
828       }
829
830       case GST_EBML_ID_DOCTYPEREADVERSION:{
831         guint64 num;
832
833         ret = gst_ebml_read_uint (ebml, &id, &num);
834         if (ret != GST_FLOW_OK)
835           return ret;
836         version = num;
837         GST_DEBUG_OBJECT (ebml, "EbmlReadVersion: %" G_GUINT64_FORMAT, num);
838         break;
839       }
840
841       default:
842         ret = gst_matroska_read_common_parse_skip (common, ebml,
843             "EBML header", id);
844         if (ret != GST_FLOW_OK)
845           return ret;
846         break;
847
848         /* we ignore these two, as they don't tell us anything we care about */
849       case GST_EBML_ID_EBMLVERSION:
850       case GST_EBML_ID_DOCTYPEVERSION:
851         ret = gst_ebml_read_skip (ebml);
852         if (ret != GST_FLOW_OK)
853           return ret;
854         break;
855     }
856   }
857
858 exit:
859
860   if ((doctype != NULL && !strcmp (doctype, GST_MATROSKA_DOCTYPE_MATROSKA)) ||
861       (doctype != NULL && !strcmp (doctype, GST_MATROSKA_DOCTYPE_WEBM)) ||
862       (doctype == NULL)) {
863     if (version <= 2) {
864       if (doctype) {
865         GST_INFO_OBJECT (common, "Input is %s version %d", doctype, version);
866       } else {
867         GST_WARNING_OBJECT (common, "Input is EBML without doctype, assuming "
868             "matroska (version %d)", version);
869       }
870       ret = GST_FLOW_OK;
871     } else {
872       GST_ELEMENT_ERROR (common, STREAM, DEMUX, (NULL),
873           ("Demuxer version (2) is too old to read %s version %d",
874               GST_STR_NULL (doctype), version));
875       ret = GST_FLOW_ERROR;
876     }
877     g_free (doctype);
878   } else {
879     GST_ELEMENT_ERROR (common, STREAM, WRONG_TYPE, (NULL),
880         ("Input is not a matroska stream (doctype=%s)", doctype));
881     ret = GST_FLOW_ERROR;
882     g_free (doctype);
883   }
884
885   return ret;
886 }
887
888 static GstFlowReturn
889 gst_matroska_read_common_parse_index_cuetrack (GstMatroskaReadCommon * common,
890     GstEbmlRead * ebml, guint * nentries)
891 {
892   guint32 id;
893   GstFlowReturn ret;
894   GstMatroskaIndex idx;
895
896   idx.pos = (guint64) - 1;
897   idx.track = 0;
898   idx.time = GST_CLOCK_TIME_NONE;
899   idx.block = 1;
900
901   DEBUG_ELEMENT_START (common, ebml, "CueTrackPositions");
902
903   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
904     DEBUG_ELEMENT_STOP (common, ebml, "CueTrackPositions", ret);
905     return ret;
906   }
907
908   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
909     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
910       break;
911
912     switch (id) {
913         /* track number */
914       case GST_MATROSKA_ID_CUETRACK:
915       {
916         guint64 num;
917
918         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
919           break;
920
921         if (num == 0) {
922           idx.track = 0;
923           GST_WARNING_OBJECT (common, "Invalid CueTrack 0");
924           break;
925         }
926
927         GST_DEBUG_OBJECT (common, "CueTrack: %" G_GUINT64_FORMAT, num);
928         idx.track = num;
929         break;
930       }
931
932         /* position in file */
933       case GST_MATROSKA_ID_CUECLUSTERPOSITION:
934       {
935         guint64 num;
936
937         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
938           break;
939
940         if (num > G_MAXINT64) {
941           GST_WARNING_OBJECT (common, "CueClusterPosition %" G_GUINT64_FORMAT
942               " too large", num);
943           break;
944         }
945
946         idx.pos = num;
947         break;
948       }
949
950         /* number of block in the cluster */
951       case GST_MATROSKA_ID_CUEBLOCKNUMBER:
952       {
953         guint64 num;
954
955         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
956           break;
957
958         if (num == 0) {
959           GST_WARNING_OBJECT (common, "Invalid CueBlockNumber 0");
960           break;
961         }
962
963         GST_DEBUG_OBJECT (common, "CueBlockNumber: %" G_GUINT64_FORMAT, num);
964         idx.block = num;
965
966         /* mild sanity check, disregard strange cases ... */
967         if (idx.block > G_MAXUINT16) {
968           GST_DEBUG_OBJECT (common, "... looks suspicious, ignoring");
969           idx.block = 1;
970         }
971         break;
972       }
973
974       default:
975         ret = gst_matroska_read_common_parse_skip (common, ebml,
976             "CueTrackPositions", id);
977         break;
978
979       case GST_MATROSKA_ID_CUECODECSTATE:
980       case GST_MATROSKA_ID_CUEREFERENCE:
981         ret = gst_ebml_read_skip (ebml);
982         break;
983     }
984   }
985
986   DEBUG_ELEMENT_STOP (common, ebml, "CueTrackPositions", ret);
987
988   /* (e.g.) lavf typically creates entries without a block number,
989    * which is bogus and leads to contradictory information */
990   if (common->index->len) {
991     GstMatroskaIndex *last_idx;
992
993     last_idx = &g_array_index (common->index, GstMatroskaIndex,
994         common->index->len - 1);
995     if (last_idx->block == idx.block && last_idx->pos == idx.pos &&
996         last_idx->track == idx.track && idx.time > last_idx->time) {
997       GST_DEBUG_OBJECT (common, "Cue entry refers to same location, "
998           "but has different time than previous entry; discarding");
999       idx.track = 0;
1000     }
1001   }
1002
1003   if ((ret == GST_FLOW_OK || ret == GST_FLOW_UNEXPECTED)
1004       && idx.pos != (guint64) - 1 && idx.track > 0) {
1005     g_array_append_val (common->index, idx);
1006     (*nentries)++;
1007   } else if (ret == GST_FLOW_OK || ret == GST_FLOW_UNEXPECTED) {
1008     GST_DEBUG_OBJECT (common, "CueTrackPositions without valid content");
1009   }
1010
1011   return ret;
1012 }
1013
1014 static GstFlowReturn
1015 gst_matroska_read_common_parse_index_pointentry (GstMatroskaReadCommon *
1016     common, GstEbmlRead * ebml)
1017 {
1018   guint32 id;
1019   GstFlowReturn ret;
1020   GstClockTime time = GST_CLOCK_TIME_NONE;
1021   guint nentries = 0;
1022
1023   DEBUG_ELEMENT_START (common, ebml, "CuePoint");
1024
1025   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1026     DEBUG_ELEMENT_STOP (common, ebml, "CuePoint", ret);
1027     return ret;
1028   }
1029
1030   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1031     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1032       break;
1033
1034     switch (id) {
1035         /* one single index entry ('point') */
1036       case GST_MATROSKA_ID_CUETIME:
1037       {
1038         if ((ret = gst_ebml_read_uint (ebml, &id, &time)) != GST_FLOW_OK)
1039           break;
1040
1041         GST_DEBUG_OBJECT (common, "CueTime: %" G_GUINT64_FORMAT, time);
1042         time = time * common->time_scale;
1043         break;
1044       }
1045
1046         /* position in the file + track to which it belongs */
1047       case GST_MATROSKA_ID_CUETRACKPOSITIONS:
1048       {
1049         if ((ret =
1050                 gst_matroska_read_common_parse_index_cuetrack (common, ebml,
1051                     &nentries)) != GST_FLOW_OK)
1052           break;
1053         break;
1054       }
1055
1056       default:
1057         ret = gst_matroska_read_common_parse_skip (common, ebml, "CuePoint",
1058             id);
1059         break;
1060     }
1061   }
1062
1063   DEBUG_ELEMENT_STOP (common, ebml, "CuePoint", ret);
1064
1065   if (nentries > 0) {
1066     if (time == GST_CLOCK_TIME_NONE) {
1067       GST_WARNING_OBJECT (common, "CuePoint without valid time");
1068       g_array_remove_range (common->index, common->index->len - nentries,
1069           nentries);
1070     } else {
1071       gint i;
1072
1073       for (i = common->index->len - nentries; i < common->index->len; i++) {
1074         GstMatroskaIndex *idx =
1075             &g_array_index (common->index, GstMatroskaIndex, i);
1076
1077         idx->time = time;
1078         GST_DEBUG_OBJECT (common, "Index entry: pos=%" G_GUINT64_FORMAT
1079             ", time=%" GST_TIME_FORMAT ", track=%u, block=%u", idx->pos,
1080             GST_TIME_ARGS (idx->time), (guint) idx->track, (guint) idx->block);
1081       }
1082     }
1083   } else {
1084     GST_DEBUG_OBJECT (common, "Empty CuePoint");
1085   }
1086
1087   return ret;
1088 }
1089
1090 gint
1091 gst_matroska_read_common_stream_from_num (GstMatroskaReadCommon * common,
1092     guint track_num)
1093 {
1094   guint n;
1095
1096   g_assert (common->src->len == common->num_streams);
1097   for (n = 0; n < common->src->len; n++) {
1098     GstMatroskaTrackContext *context = g_ptr_array_index (common->src, n);
1099
1100     if (context->num == track_num) {
1101       return n;
1102     }
1103   }
1104
1105   if (n == common->num_streams)
1106     GST_WARNING_OBJECT (common,
1107         "Failed to find corresponding pad for tracknum %d", track_num);
1108
1109   return -1;
1110 }
1111
1112 GstFlowReturn
1113 gst_matroska_read_common_parse_index (GstMatroskaReadCommon * common,
1114     GstEbmlRead * ebml)
1115 {
1116   guint32 id;
1117   GstFlowReturn ret = GST_FLOW_OK;
1118   guint i;
1119
1120   if (common->index)
1121     g_array_free (common->index, TRUE);
1122   common->index =
1123       g_array_sized_new (FALSE, FALSE, sizeof (GstMatroskaIndex), 128);
1124
1125   DEBUG_ELEMENT_START (common, ebml, "Cues");
1126
1127   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1128     DEBUG_ELEMENT_STOP (common, ebml, "Cues", ret);
1129     return ret;
1130   }
1131
1132   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1133     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1134       break;
1135
1136     switch (id) {
1137         /* one single index entry ('point') */
1138       case GST_MATROSKA_ID_POINTENTRY:
1139         ret = gst_matroska_read_common_parse_index_pointentry (common, ebml);
1140         break;
1141
1142       default:
1143         ret = gst_matroska_read_common_parse_skip (common, ebml, "Cues", id);
1144         break;
1145     }
1146   }
1147   DEBUG_ELEMENT_STOP (common, ebml, "Cues", ret);
1148
1149   /* Sort index by time, smallest time first, for easier searching */
1150   g_array_sort (common->index, (GCompareFunc) gst_matroska_index_compare);
1151
1152   /* Now sort the track specific index entries into their own arrays */
1153   for (i = 0; i < common->index->len; i++) {
1154     GstMatroskaIndex *idx = &g_array_index (common->index, GstMatroskaIndex,
1155         i);
1156     gint track_num;
1157     GstMatroskaTrackContext *ctx;
1158
1159     if (common->element_index) {
1160       gint writer_id;
1161
1162       if (idx->track != 0 &&
1163           (track_num =
1164               gst_matroska_read_common_stream_from_num (common,
1165                   idx->track)) != -1) {
1166         ctx = g_ptr_array_index (common->src, track_num);
1167
1168         if (ctx->index_writer_id == -1)
1169           gst_index_get_writer_id (common->element_index,
1170               GST_OBJECT (ctx->pad), &ctx->index_writer_id);
1171         writer_id = ctx->index_writer_id;
1172       } else {
1173         if (common->element_index_writer_id == -1)
1174           gst_index_get_writer_id (common->element_index, GST_OBJECT (common),
1175               &common->element_index_writer_id);
1176         writer_id = common->element_index_writer_id;
1177       }
1178
1179       GST_LOG_OBJECT (common, "adding association %" GST_TIME_FORMAT "-> %"
1180           G_GUINT64_FORMAT " for writer id %d", GST_TIME_ARGS (idx->time),
1181           idx->pos, writer_id);
1182       gst_index_add_association (common->element_index, writer_id,
1183           GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, idx->time,
1184           GST_FORMAT_BYTES, idx->pos + common->ebml_segment_start, NULL);
1185     }
1186
1187     if (idx->track == 0)
1188       continue;
1189
1190     track_num = gst_matroska_read_common_stream_from_num (common, idx->track);
1191     if (track_num == -1)
1192       continue;
1193
1194     ctx = g_ptr_array_index (common->src, track_num);
1195
1196     if (ctx->index_table == NULL)
1197       ctx->index_table =
1198           g_array_sized_new (FALSE, FALSE, sizeof (GstMatroskaIndex), 128);
1199
1200     g_array_append_vals (ctx->index_table, idx, 1);
1201   }
1202
1203   common->index_parsed = TRUE;
1204
1205   /* sanity check; empty index normalizes to no index */
1206   if (common->index->len == 0) {
1207     g_array_free (common->index, TRUE);
1208     common->index = NULL;
1209   }
1210
1211   return ret;
1212 }
1213
1214 GstFlowReturn
1215 gst_matroska_read_common_parse_info (GstMatroskaReadCommon * common,
1216     GstElement * el, GstEbmlRead * ebml)
1217 {
1218   GstFlowReturn ret = GST_FLOW_OK;
1219   gdouble dur_f = -1.0;
1220   guint32 id;
1221
1222   DEBUG_ELEMENT_START (common, ebml, "SegmentInfo");
1223
1224   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1225     DEBUG_ELEMENT_STOP (common, ebml, "SegmentInfo", ret);
1226     return ret;
1227   }
1228
1229   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1230     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1231       break;
1232
1233     switch (id) {
1234         /* cluster timecode */
1235       case GST_MATROSKA_ID_TIMECODESCALE:{
1236         guint64 num;
1237
1238         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1239           break;
1240
1241
1242         GST_DEBUG_OBJECT (common, "TimeCodeScale: %" G_GUINT64_FORMAT, num);
1243         common->time_scale = num;
1244         break;
1245       }
1246
1247       case GST_MATROSKA_ID_DURATION:{
1248         if ((ret = gst_ebml_read_float (ebml, &id, &dur_f)) != GST_FLOW_OK)
1249           break;
1250
1251         if (dur_f <= 0.0) {
1252           GST_WARNING_OBJECT (common, "Invalid duration %lf", dur_f);
1253           break;
1254         }
1255
1256         GST_DEBUG_OBJECT (common, "Duration: %lf", dur_f);
1257         break;
1258       }
1259
1260       case GST_MATROSKA_ID_WRITINGAPP:{
1261         gchar *text;
1262
1263         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1264           break;
1265
1266         GST_DEBUG_OBJECT (common, "WritingApp: %s", GST_STR_NULL (text));
1267         common->writing_app = text;
1268         break;
1269       }
1270
1271       case GST_MATROSKA_ID_MUXINGAPP:{
1272         gchar *text;
1273
1274         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1275           break;
1276
1277         GST_DEBUG_OBJECT (common, "MuxingApp: %s", GST_STR_NULL (text));
1278         common->muxing_app = text;
1279         break;
1280       }
1281
1282       case GST_MATROSKA_ID_DATEUTC:{
1283         gint64 time;
1284
1285         if ((ret = gst_ebml_read_date (ebml, &id, &time)) != GST_FLOW_OK)
1286           break;
1287
1288         GST_DEBUG_OBJECT (common, "DateUTC: %" G_GINT64_FORMAT, time);
1289         common->created = time;
1290         break;
1291       }
1292
1293       case GST_MATROSKA_ID_TITLE:{
1294         gchar *text;
1295         GstTagList *taglist;
1296
1297         if ((ret = gst_ebml_read_utf8 (ebml, &id, &text)) != GST_FLOW_OK)
1298           break;
1299
1300         GST_DEBUG_OBJECT (common, "Title: %s", GST_STR_NULL (text));
1301         taglist = gst_tag_list_new ();
1302         gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND, GST_TAG_TITLE, text,
1303             NULL);
1304         gst_matroska_read_common_found_global_tag (common, el, taglist);
1305         g_free (text);
1306         break;
1307       }
1308
1309       default:
1310         ret = gst_matroska_read_common_parse_skip (common, ebml,
1311             "SegmentInfo", id);
1312         break;
1313
1314         /* fall through */
1315       case GST_MATROSKA_ID_SEGMENTUID:
1316       case GST_MATROSKA_ID_SEGMENTFILENAME:
1317       case GST_MATROSKA_ID_PREVUID:
1318       case GST_MATROSKA_ID_PREVFILENAME:
1319       case GST_MATROSKA_ID_NEXTUID:
1320       case GST_MATROSKA_ID_NEXTFILENAME:
1321       case GST_MATROSKA_ID_SEGMENTFAMILY:
1322       case GST_MATROSKA_ID_CHAPTERTRANSLATE:
1323         ret = gst_ebml_read_skip (ebml);
1324         break;
1325     }
1326   }
1327
1328   if (dur_f > 0.0) {
1329     GstClockTime dur_u;
1330
1331     dur_u = gst_gdouble_to_guint64 (dur_f *
1332         gst_guint64_to_gdouble (common->time_scale));
1333     if (GST_CLOCK_TIME_IS_VALID (dur_u) && dur_u <= G_MAXINT64)
1334       gst_segment_set_duration (&common->segment, GST_FORMAT_TIME, dur_u);
1335   }
1336
1337   DEBUG_ELEMENT_STOP (common, ebml, "SegmentInfo", ret);
1338
1339   common->segmentinfo_parsed = TRUE;
1340
1341   return ret;
1342 }
1343
1344 static GstFlowReturn
1345 gst_matroska_read_common_parse_metadata_id_simple_tag (GstMatroskaReadCommon *
1346     common, GstEbmlRead * ebml, GstTagList ** p_taglist)
1347 {
1348   /* FIXME: check if there are more useful mappings */
1349   static const struct
1350   {
1351     const gchar *matroska_tagname;
1352     const gchar *gstreamer_tagname;
1353   }
1354   tag_conv[] = {
1355     {
1356     GST_MATROSKA_TAG_ID_TITLE, GST_TAG_TITLE}, {
1357     GST_MATROSKA_TAG_ID_ARTIST, GST_TAG_ARTIST}, {
1358     GST_MATROSKA_TAG_ID_AUTHOR, GST_TAG_ARTIST}, {
1359     GST_MATROSKA_TAG_ID_ALBUM, GST_TAG_ALBUM}, {
1360     GST_MATROSKA_TAG_ID_COMMENTS, GST_TAG_COMMENT}, {
1361     GST_MATROSKA_TAG_ID_BITSPS, GST_TAG_BITRATE}, {
1362     GST_MATROSKA_TAG_ID_BPS, GST_TAG_BITRATE}, {
1363     GST_MATROSKA_TAG_ID_ENCODER, GST_TAG_ENCODER}, {
1364     GST_MATROSKA_TAG_ID_DATE, GST_TAG_DATE}, {
1365     GST_MATROSKA_TAG_ID_ISRC, GST_TAG_ISRC}, {
1366     GST_MATROSKA_TAG_ID_COPYRIGHT, GST_TAG_COPYRIGHT}, {
1367     GST_MATROSKA_TAG_ID_BPM, GST_TAG_BEATS_PER_MINUTE}, {
1368     GST_MATROSKA_TAG_ID_TERMS_OF_USE, GST_TAG_LICENSE}, {
1369     GST_MATROSKA_TAG_ID_COMPOSER, GST_TAG_COMPOSER}, {
1370     GST_MATROSKA_TAG_ID_LEAD_PERFORMER, GST_TAG_PERFORMER}, {
1371     GST_MATROSKA_TAG_ID_GENRE, GST_TAG_GENRE}
1372   };
1373   GstFlowReturn ret;
1374   guint32 id;
1375   gchar *value = NULL;
1376   gchar *tag = NULL;
1377
1378   DEBUG_ELEMENT_START (common, ebml, "SimpleTag");
1379
1380   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1381     DEBUG_ELEMENT_STOP (common, ebml, "SimpleTag", ret);
1382     return ret;
1383   }
1384
1385   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1386     /* read all sub-entries */
1387
1388     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1389       break;
1390
1391     switch (id) {
1392       case GST_MATROSKA_ID_TAGNAME:
1393         g_free (tag);
1394         tag = NULL;
1395         ret = gst_ebml_read_ascii (ebml, &id, &tag);
1396         GST_DEBUG_OBJECT (common, "TagName: %s", GST_STR_NULL (tag));
1397         break;
1398
1399       case GST_MATROSKA_ID_TAGSTRING:
1400         g_free (value);
1401         value = NULL;
1402         ret = gst_ebml_read_utf8 (ebml, &id, &value);
1403         GST_DEBUG_OBJECT (common, "TagString: %s", GST_STR_NULL (value));
1404         break;
1405
1406       default:
1407         ret = gst_matroska_read_common_parse_skip (common, ebml, "SimpleTag",
1408             id);
1409         break;
1410         /* fall-through */
1411
1412       case GST_MATROSKA_ID_TAGLANGUAGE:
1413       case GST_MATROSKA_ID_TAGDEFAULT:
1414       case GST_MATROSKA_ID_TAGBINARY:
1415         ret = gst_ebml_read_skip (ebml);
1416         break;
1417     }
1418   }
1419
1420   DEBUG_ELEMENT_STOP (common, ebml, "SimpleTag", ret);
1421
1422   if (tag && value) {
1423     guint i;
1424
1425     for (i = 0; i < G_N_ELEMENTS (tag_conv); i++) {
1426       const gchar *tagname_gst = tag_conv[i].gstreamer_tagname;
1427
1428       const gchar *tagname_mkv = tag_conv[i].matroska_tagname;
1429
1430       if (strcmp (tagname_mkv, tag) == 0) {
1431         GValue dest = { 0, };
1432         GType dest_type = gst_tag_get_type (tagname_gst);
1433
1434         /* Ensure that any date string is complete */
1435         if (dest_type == GST_TYPE_DATE) {
1436           guint year = 1901, month = 1, day = 1;
1437
1438           /* Dates can be yyyy-MM-dd, yyyy-MM or yyyy, but we need
1439            * the first type */
1440           if (sscanf (value, "%04u-%02u-%02u", &year, &month, &day) != 0) {
1441             g_free (value);
1442             value = g_strdup_printf ("%04u-%02u-%02u", year, month, day);
1443           }
1444         }
1445
1446         g_value_init (&dest, dest_type);
1447         if (gst_value_deserialize (&dest, value)) {
1448           gst_tag_list_add_values (*p_taglist, GST_TAG_MERGE_APPEND,
1449               tagname_gst, &dest, NULL);
1450         } else {
1451           GST_WARNING_OBJECT (common, "Can't transform tag '%s' with "
1452               "value '%s' to target type '%s'", tag, value,
1453               g_type_name (dest_type));
1454         }
1455         g_value_unset (&dest);
1456         break;
1457       }
1458     }
1459   }
1460
1461   g_free (tag);
1462   g_free (value);
1463
1464   return ret;
1465 }
1466
1467 static GstFlowReturn
1468 gst_matroska_read_common_parse_metadata_id_tag (GstMatroskaReadCommon * common,
1469     GstEbmlRead * ebml, GstTagList ** p_taglist)
1470 {
1471   guint32 id;
1472   GstFlowReturn ret;
1473
1474   DEBUG_ELEMENT_START (common, ebml, "Tag");
1475
1476   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1477     DEBUG_ELEMENT_STOP (common, ebml, "Tag", ret);
1478     return ret;
1479   }
1480
1481   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1482     /* read all sub-entries */
1483
1484     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1485       break;
1486
1487     switch (id) {
1488       case GST_MATROSKA_ID_SIMPLETAG:
1489         ret = gst_matroska_read_common_parse_metadata_id_simple_tag (common,
1490             ebml, p_taglist);
1491         break;
1492
1493       default:
1494         ret = gst_matroska_read_common_parse_skip (common, ebml, "Tag", id);
1495         break;
1496     }
1497   }
1498
1499   DEBUG_ELEMENT_STOP (common, ebml, "Tag", ret);
1500
1501   return ret;
1502 }
1503
1504 GstFlowReturn
1505 gst_matroska_read_common_parse_metadata (GstMatroskaReadCommon * common,
1506     GstElement * el, GstEbmlRead * ebml)
1507 {
1508   GstTagList *taglist;
1509   GstFlowReturn ret = GST_FLOW_OK;
1510   guint32 id;
1511   GList *l;
1512   guint64 curpos;
1513
1514   curpos = gst_ebml_read_get_pos (ebml);
1515
1516   /* Make sure we don't parse a tags element twice and
1517    * post it's tags twice */
1518   curpos = gst_ebml_read_get_pos (ebml);
1519   for (l = common->tags_parsed; l; l = l->next) {
1520     guint64 *pos = l->data;
1521
1522     if (*pos == curpos) {
1523       GST_DEBUG_OBJECT (common, "Skipping already parsed Tags at offset %"
1524           G_GUINT64_FORMAT, curpos);
1525       return GST_FLOW_OK;
1526     }
1527   }
1528
1529   common->tags_parsed =
1530       g_list_prepend (common->tags_parsed, g_slice_new (guint64));
1531   *((guint64 *) common->tags_parsed->data) = curpos;
1532   /* fall-through */
1533
1534   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1535     DEBUG_ELEMENT_STOP (common, ebml, "Tags", ret);
1536     return ret;
1537   }
1538
1539   taglist = gst_tag_list_new ();
1540
1541   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1542     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1543       break;
1544
1545     switch (id) {
1546       case GST_MATROSKA_ID_TAG:
1547         ret = gst_matroska_read_common_parse_metadata_id_tag (common, ebml,
1548             &taglist);
1549         break;
1550
1551       default:
1552         ret = gst_matroska_read_common_parse_skip (common, ebml, "Tags", id);
1553         break;
1554         /* FIXME: Use to limit the tags to specific pads */
1555       case GST_MATROSKA_ID_TARGETS:
1556         ret = gst_ebml_read_skip (ebml);
1557         break;
1558     }
1559   }
1560
1561   DEBUG_ELEMENT_STOP (common, ebml, "Tags", ret);
1562
1563   gst_matroska_read_common_found_global_tag (common, el, taglist);
1564
1565   return ret;
1566 }
1567
1568 static GstFlowReturn
1569 gst_matroska_read_common_peek_adapter (GstMatroskaReadCommon * common, guint
1570     peek, const guint8 ** data)
1571 {
1572   *data = gst_adapter_peek (common->adapter, peek);
1573   if (*data == NULL)
1574     return GST_FLOW_UNEXPECTED;
1575
1576   return GST_FLOW_OK;
1577 }
1578
1579 /*
1580  * Calls pull_range for (offset,size) without advancing our offset
1581  */
1582 GstFlowReturn
1583 gst_matroska_read_common_peek_bytes (GstMatroskaReadCommon * common, guint64
1584     offset, guint size, GstBuffer ** p_buf, guint8 ** bytes)
1585 {
1586   GstFlowReturn ret;
1587
1588   /* Caching here actually makes much less difference than one would expect.
1589    * We do it mainly to avoid pulling buffers of 1 byte all the time */
1590   if (common->cached_buffer) {
1591     guint64 cache_offset = GST_BUFFER_OFFSET (common->cached_buffer);
1592     guint cache_size = GST_BUFFER_SIZE (common->cached_buffer);
1593
1594     if (cache_offset <= common->offset &&
1595         (common->offset + size) <= (cache_offset + cache_size)) {
1596       if (p_buf)
1597         *p_buf = gst_buffer_create_sub (common->cached_buffer,
1598             common->offset - cache_offset, size);
1599       if (bytes)
1600         *bytes = GST_BUFFER_DATA (common->cached_buffer) + common->offset -
1601             cache_offset;
1602       return GST_FLOW_OK;
1603     }
1604     /* not enough data in the cache, free cache and get a new one */
1605     gst_buffer_unref (common->cached_buffer);
1606     common->cached_buffer = NULL;
1607   }
1608
1609   /* refill the cache */
1610   ret = gst_pad_pull_range (common->sinkpad, common->offset,
1611       MAX (size, 64 * 1024), &common->cached_buffer);
1612   if (ret != GST_FLOW_OK) {
1613     common->cached_buffer = NULL;
1614     return ret;
1615   }
1616
1617   if (GST_BUFFER_SIZE (common->cached_buffer) >= size) {
1618     if (p_buf)
1619       *p_buf = gst_buffer_create_sub (common->cached_buffer, 0, size);
1620     if (bytes)
1621       *bytes = GST_BUFFER_DATA (common->cached_buffer);
1622     return GST_FLOW_OK;
1623   }
1624
1625   /* Not possible to get enough data, try a last time with
1626    * requesting exactly the size we need */
1627   gst_buffer_unref (common->cached_buffer);
1628   common->cached_buffer = NULL;
1629
1630   ret =
1631       gst_pad_pull_range (common->sinkpad, common->offset, size,
1632       &common->cached_buffer);
1633   if (ret != GST_FLOW_OK) {
1634     GST_DEBUG_OBJECT (common, "pull_range returned %d", ret);
1635     if (p_buf)
1636       *p_buf = NULL;
1637     if (bytes)
1638       *bytes = NULL;
1639     return ret;
1640   }
1641
1642   if (GST_BUFFER_SIZE (common->cached_buffer) < size) {
1643     GST_WARNING_OBJECT (common, "Dropping short buffer at offset %"
1644         G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", common->offset,
1645         size, GST_BUFFER_SIZE (common->cached_buffer));
1646
1647     gst_buffer_unref (common->cached_buffer);
1648     common->cached_buffer = NULL;
1649     if (p_buf)
1650       *p_buf = NULL;
1651     if (bytes)
1652       *bytes = NULL;
1653     return GST_FLOW_UNEXPECTED;
1654   }
1655
1656   if (p_buf)
1657     *p_buf = gst_buffer_create_sub (common->cached_buffer, 0, size);
1658   if (bytes)
1659     *bytes = GST_BUFFER_DATA (common->cached_buffer);
1660
1661   return GST_FLOW_OK;
1662 }
1663
1664 static GstFlowReturn
1665 gst_matroska_read_common_peek_pull (GstMatroskaReadCommon * common, guint peek,
1666     guint8 ** data)
1667 {
1668   return gst_matroska_read_common_peek_bytes (common, common->offset, peek,
1669       NULL, data);
1670 }
1671
1672 GstFlowReturn
1673 gst_matroska_read_common_peek_id_length_pull (GstMatroskaReadCommon * common,
1674     GstElement * el, guint32 * _id, guint64 * _length, guint * _needed)
1675 {
1676   return gst_ebml_peek_id_length (_id, _length, _needed,
1677       (GstPeekData) gst_matroska_read_common_peek_pull, (gpointer) common, el,
1678       common->offset);
1679 }
1680
1681 GstFlowReturn
1682 gst_matroska_read_common_peek_id_length_push (GstMatroskaReadCommon * common,
1683     GstElement * el, guint32 * _id, guint64 * _length, guint * _needed)
1684 {
1685   return gst_ebml_peek_id_length (_id, _length, _needed,
1686       (GstPeekData) gst_matroska_read_common_peek_adapter, (gpointer) common,
1687       el, common->offset);
1688 }
1689
1690 static GstFlowReturn
1691 gst_matroska_read_common_read_track_encoding (GstMatroskaReadCommon * common,
1692     GstEbmlRead * ebml, GstMatroskaTrackContext * context)
1693 {
1694   GstMatroskaTrackEncoding enc = { 0, };
1695   GstFlowReturn ret;
1696   guint32 id;
1697
1698   DEBUG_ELEMENT_START (common, ebml, "ContentEncoding");
1699   /* Set default values */
1700   enc.scope = 1;
1701   /* All other default values are 0 */
1702
1703   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1704     DEBUG_ELEMENT_STOP (common, ebml, "ContentEncoding", ret);
1705     return ret;
1706   }
1707
1708   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1709     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1710       break;
1711
1712     switch (id) {
1713       case GST_MATROSKA_ID_CONTENTENCODINGORDER:{
1714         guint64 num;
1715
1716         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1717           break;
1718
1719         if (!gst_matroska_read_common_encoding_order_unique (context->encodings,
1720                 num)) {
1721           GST_ERROR_OBJECT (common, "ContentEncodingOrder %" G_GUINT64_FORMAT
1722               "is not unique for track %d", num, context->num);
1723           ret = GST_FLOW_ERROR;
1724           break;
1725         }
1726
1727         GST_DEBUG_OBJECT (common, "ContentEncodingOrder: %" G_GUINT64_FORMAT,
1728             num);
1729         enc.order = num;
1730         break;
1731       }
1732       case GST_MATROSKA_ID_CONTENTENCODINGSCOPE:{
1733         guint64 num;
1734
1735         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1736           break;
1737
1738         if (num > 7 && num == 0) {
1739           GST_ERROR_OBJECT (common, "Invalid ContentEncodingScope %"
1740               G_GUINT64_FORMAT, num);
1741           ret = GST_FLOW_ERROR;
1742           break;
1743         }
1744
1745         GST_DEBUG_OBJECT (common, "ContentEncodingScope: %" G_GUINT64_FORMAT,
1746             num);
1747         enc.scope = num;
1748
1749         break;
1750       }
1751       case GST_MATROSKA_ID_CONTENTENCODINGTYPE:{
1752         guint64 num;
1753
1754         if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK)
1755           break;
1756
1757         if (num > 1) {
1758           GST_ERROR_OBJECT (common, "Invalid ContentEncodingType %"
1759               G_GUINT64_FORMAT, num);
1760           ret = GST_FLOW_ERROR;
1761           break;
1762         } else if (num != 0) {
1763           GST_ERROR_OBJECT (common, "Encrypted tracks are not supported yet");
1764           ret = GST_FLOW_ERROR;
1765           break;
1766         }
1767         GST_DEBUG_OBJECT (common, "ContentEncodingType: %" G_GUINT64_FORMAT,
1768             num);
1769         enc.type = num;
1770         break;
1771       }
1772       case GST_MATROSKA_ID_CONTENTCOMPRESSION:{
1773
1774         DEBUG_ELEMENT_START (common, ebml, "ContentCompression");
1775
1776         if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK)
1777           break;
1778
1779         while (ret == GST_FLOW_OK &&
1780             gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1781           if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1782             break;
1783
1784           switch (id) {
1785             case GST_MATROSKA_ID_CONTENTCOMPALGO:{
1786               guint64 num;
1787
1788               if ((ret = gst_ebml_read_uint (ebml, &id, &num)) != GST_FLOW_OK) {
1789                 break;
1790               }
1791               if (num > 3) {
1792                 GST_ERROR_OBJECT (common, "Invalid ContentCompAlgo %"
1793                     G_GUINT64_FORMAT, num);
1794                 ret = GST_FLOW_ERROR;
1795                 break;
1796               }
1797               GST_DEBUG_OBJECT (common, "ContentCompAlgo: %" G_GUINT64_FORMAT,
1798                   num);
1799               enc.comp_algo = num;
1800
1801               break;
1802             }
1803             case GST_MATROSKA_ID_CONTENTCOMPSETTINGS:{
1804               guint8 *data;
1805               guint64 size;
1806
1807               if ((ret =
1808                       gst_ebml_read_binary (ebml, &id, &data,
1809                           &size)) != GST_FLOW_OK) {
1810                 break;
1811               }
1812               enc.comp_settings = data;
1813               enc.comp_settings_length = size;
1814               GST_DEBUG_OBJECT (common,
1815                   "ContentCompSettings of size %" G_GUINT64_FORMAT, size);
1816               break;
1817             }
1818             default:
1819               GST_WARNING_OBJECT (common,
1820                   "Unknown ContentCompression subelement 0x%x - ignoring", id);
1821               ret = gst_ebml_read_skip (ebml);
1822               break;
1823           }
1824         }
1825         DEBUG_ELEMENT_STOP (common, ebml, "ContentCompression", ret);
1826         break;
1827       }
1828
1829       case GST_MATROSKA_ID_CONTENTENCRYPTION:
1830         GST_ERROR_OBJECT (common, "Encrypted tracks not yet supported");
1831         gst_ebml_read_skip (ebml);
1832         ret = GST_FLOW_ERROR;
1833         break;
1834       default:
1835         GST_WARNING_OBJECT (common,
1836             "Unknown ContentEncoding subelement 0x%x - ignoring", id);
1837         ret = gst_ebml_read_skip (ebml);
1838         break;
1839     }
1840   }
1841
1842   DEBUG_ELEMENT_STOP (common, ebml, "ContentEncoding", ret);
1843   if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
1844     return ret;
1845
1846   /* TODO: Check if the combination of values is valid */
1847
1848   g_array_append_val (context->encodings, enc);
1849
1850   return ret;
1851 }
1852
1853 GstFlowReturn
1854 gst_matroska_read_common_read_track_encodings (GstMatroskaReadCommon * common,
1855     GstEbmlRead * ebml, GstMatroskaTrackContext * context)
1856 {
1857   GstFlowReturn ret;
1858   guint32 id;
1859
1860   DEBUG_ELEMENT_START (common, ebml, "ContentEncodings");
1861
1862   if ((ret = gst_ebml_read_master (ebml, &id)) != GST_FLOW_OK) {
1863     DEBUG_ELEMENT_STOP (common, ebml, "ContentEncodings", ret);
1864     return ret;
1865   }
1866
1867   context->encodings =
1868       g_array_sized_new (FALSE, FALSE, sizeof (GstMatroskaTrackEncoding), 1);
1869
1870   while (ret == GST_FLOW_OK && gst_ebml_read_has_remaining (ebml, 1, TRUE)) {
1871     if ((ret = gst_ebml_peek_id (ebml, &id)) != GST_FLOW_OK)
1872       break;
1873
1874     switch (id) {
1875       case GST_MATROSKA_ID_CONTENTENCODING:
1876         ret = gst_matroska_read_common_read_track_encoding (common, ebml,
1877             context);
1878         break;
1879       default:
1880         GST_WARNING_OBJECT (common,
1881             "Unknown ContentEncodings subelement 0x%x - ignoring", id);
1882         ret = gst_ebml_read_skip (ebml);
1883         break;
1884     }
1885   }
1886
1887   DEBUG_ELEMENT_STOP (common, ebml, "ContentEncodings", ret);
1888   if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
1889     return ret;
1890
1891   /* Sort encodings according to their order */
1892   g_array_sort (context->encodings,
1893       (GCompareFunc) gst_matroska_read_common_encoding_cmp);
1894
1895   return gst_matroska_decode_content_encodings (context->encodings);
1896 }
1897
1898 /* call with object lock held */
1899 void
1900 gst_matroska_read_common_reset_streams (GstMatroskaReadCommon * common,
1901     GstClockTime time, gboolean full)
1902 {
1903   gint i;
1904
1905   GST_DEBUG_OBJECT (common, "resetting stream state");
1906
1907   g_assert (common->src->len == common->num_streams);
1908   for (i = 0; i < common->src->len; i++) {
1909     GstMatroskaTrackContext *context = g_ptr_array_index (common->src, i);
1910     context->pos = time;
1911     context->set_discont = TRUE;
1912     context->eos = FALSE;
1913     context->from_time = GST_CLOCK_TIME_NONE;
1914
1915 #ifdef MKV_DEMUX_MODIFICATION
1916     context->found_next_kframe = FALSE;
1917     context->num_frames_bw_keyframes = 0;
1918     context->avg_duration_bw_keyframes = GST_CLOCK_TIME_NONE;
1919     context->frames_to_show_bw_keyframes = 0;
1920     context->prev_kframe_timestamp = GST_CLOCK_TIME_NONE;
1921     context->next_kframe_timestamp = GST_CLOCK_TIME_NONE;
1922     context->last_ts = GST_CLOCK_TIME_NONE;
1923 #endif
1924
1925     if (full)
1926       context->last_flow = GST_FLOW_OK;
1927     if (context->type == GST_MATROSKA_TRACK_TYPE_VIDEO) {
1928       GstMatroskaTrackVideoContext *videocontext =
1929           (GstMatroskaTrackVideoContext *) context;
1930       /* demux object lock held by caller */
1931       videocontext->earliest_time = GST_CLOCK_TIME_NONE;
1932     }
1933   }
1934 }
1935
1936 gboolean
1937 gst_matroska_read_common_tracknumber_unique (GstMatroskaReadCommon * common,
1938     guint64 num)
1939 {
1940   gint i;
1941
1942   g_assert (common->src->len == common->num_streams);
1943   for (i = 0; i < common->src->len; i++) {
1944     GstMatroskaTrackContext *context = g_ptr_array_index (common->src, i);
1945
1946     if (context->num == num)
1947       return FALSE;
1948   }
1949
1950   return TRUE;
1951 }