4661ef80a87a69a403bc9eadc4e616cb821da228
[platform/upstream/gst-plugins-good.git] / gst / matroska / ebml-read.c
1 /* GStreamer EBML I/O
2  * (c) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
3  *
4  * ebml-read.c: read EBML data from file/stream
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 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <string.h>
27
28 #include "ebml-read.h"
29 #include "ebml-ids.h"
30
31 enum {
32   /* FILL ME */
33   LAST_SIGNAL
34 };
35
36 static void gst_ebml_read_class_init   (GstEbmlReadClass *klass);
37 static void gst_ebml_read_init         (GstEbmlRead      *ebml);
38 static GstElementStateReturn
39             gst_ebml_read_change_state (GstElement       *element);
40
41 static GstElementClass *parent_class = NULL;
42
43 GType
44 gst_ebml_read_get_type (void) 
45 {
46   static GType gst_ebml_read_type = 0;
47
48   if (!gst_ebml_read_type) {
49     static const GTypeInfo gst_ebml_read_info = {
50       sizeof (GstEbmlReadClass),      
51       NULL,
52       NULL,
53       (GClassInitFunc) gst_ebml_read_class_init,
54       NULL,
55       NULL,
56       sizeof (GstEbmlRead),
57       0,
58       (GInstanceInitFunc) gst_ebml_read_init,
59     };
60
61     gst_ebml_read_type =
62         g_type_register_static (GST_TYPE_ELEMENT, "GstEbmlRead",
63                                 &gst_ebml_read_info, 0);
64   }
65
66   return gst_ebml_read_type;
67 }
68
69 static void
70 gst_ebml_read_class_init (GstEbmlReadClass *klass) 
71 {
72   GstElementClass *gstelement_class = (GstElementClass *) klass;
73
74   parent_class = g_type_class_ref (GST_TYPE_ELEMENT);
75
76   gstelement_class->change_state = gst_ebml_read_change_state;
77 }
78
79 static void
80 gst_ebml_read_init (GstEbmlRead *ebml)
81 {
82   ebml->sinkpad = NULL;
83   ebml->bs = NULL;
84   ebml->level = NULL;
85 }
86
87 static GstElementStateReturn
88 gst_ebml_read_change_state (GstElement *element)
89 {
90   GstEbmlRead *ebml = GST_EBML_READ (element);
91
92   switch (GST_STATE_TRANSITION (element)) {
93     case GST_STATE_READY_TO_PAUSED:
94       if (!ebml->sinkpad)
95         return GST_STATE_FAILURE;
96       ebml->bs = gst_bytestream_new (ebml->sinkpad);
97       break;
98     case GST_STATE_PAUSED_TO_READY:
99       gst_bytestream_destroy (ebml->bs);
100       while (ebml->level) {
101         GstEbmlLevel *level = ebml->level->data;
102
103         ebml->level = g_list_remove (ebml->level, level);
104         g_free (level);
105       }
106       break;
107     default:
108       break;
109   }
110
111   if (GST_ELEMENT_CLASS (parent_class)->change_state)
112     return GST_ELEMENT_CLASS (parent_class)->change_state (element);
113
114   return GST_STATE_SUCCESS;
115 }
116
117 /*
118  * Return: the amount of levels in the hierarchy that the
119  * current element lies higher than the previous one.
120  * The opposite isn't done - that's auto-done using master
121  * element reading.
122  */
123
124 static guint
125 gst_ebml_read_element_level_up (GstEbmlRead *ebml)
126 {
127   guint num = 0;
128   guint64 pos = gst_bytestream_tell (ebml->bs);
129
130   while (ebml->level != NULL) {
131     GList *last = g_list_last (ebml->level);
132     GstEbmlLevel *level = last->data;
133
134     if (pos >= level->start + level->length) {
135       ebml->level = g_list_remove (ebml->level, level);
136       g_free (level);
137       num++;
138     } else
139       break;
140   }
141
142   return num;
143 }
144
145 /*
146  * Read: the element content data ID.
147  * Return: the number of bytes read or -1 on error.
148  */
149
150 static gint
151 gst_ebml_read_element_id (GstEbmlRead *ebml,
152                           guint32     *id,
153                           guint       *level_up)
154 {
155   guint8 *data;
156   gint len_mask = 0x80, read = 1, n = 1;
157   guint32 total;
158
159   while (gst_bytestream_peek_bytes (ebml->bs, &data, 1) != 1) {
160     GstEvent *event = NULL;
161     guint32 remaining;
162
163     /* Here, we might encounter EOS */
164     gst_bytestream_get_status (ebml->bs, &remaining, &event);
165     if (event) {
166       gst_pad_event_default (ebml->sinkpad, event);
167     } else {
168       guint64 pos = gst_bytestream_tell (ebml->bs);
169       gst_event_unref (event);
170       GST_ELEMENT_ERROR (ebml, RESOURCE, READ, (NULL),
171                          ("Read error at position %llu (0x%llx)",
172                          pos, pos));
173       return -1;
174     }
175   }
176   total = data[0];
177   while (read <= 4 && !(total & len_mask)) {
178     read++;
179     len_mask >>= 1;
180   }
181   if (read > 4) {
182     guint64 pos = gst_bytestream_tell (ebml->bs);
183     GST_ELEMENT_ERROR (ebml, STREAM, DEMUX, (NULL),
184                        ("Invalid EBML ID size tag (0x%x) at position %llu (0x%llx)",
185                        data[0], pos, pos));
186     return -1;
187   }
188
189   if (gst_bytestream_peek_bytes (ebml->bs, &data, read) != read) {
190     guint64 pos = gst_bytestream_tell (ebml->bs);
191     GST_ELEMENT_ERROR (ebml, RESOURCE, READ, (NULL),
192                        ("Read error at position %llu (0x%llx)", pos, pos));
193     return -1;
194   }
195   while (n < read)
196     total = (total << 8) | data[n++];
197
198   *id = total;
199
200   /* level */
201   if (level_up)
202     *level_up = gst_ebml_read_element_level_up (ebml);
203
204   return read;
205 }
206
207 /*
208  * Read: element content length.
209  * Return: the number of bytes read or -1 on error.
210  */
211
212 static gint
213 gst_ebml_read_element_length (GstEbmlRead *ebml,
214                               guint64     *length)
215 {
216   guint8 *data;
217   gint len_mask = 0x80, read = 1, n = 1, num_ffs = 0;
218   guint64 total;
219
220   if (gst_bytestream_peek_bytes (ebml->bs, &data, 1) != 1) {
221     guint64 pos = gst_bytestream_tell (ebml->bs);
222     GST_ELEMENT_ERROR (ebml, RESOURCE, READ, (NULL),
223                        ("Read error at position %llu (0x%llx)", pos, pos));
224     return -1;
225   }
226   total = data[0];
227   while (read <= 8 && !(total & len_mask)) {
228     read++;
229     len_mask >>= 1;
230   }
231   if (read > 8) {
232     guint64 pos = gst_bytestream_tell (ebml->bs);
233     GST_ELEMENT_ERROR (ebml, STREAM, DEMUX, (NULL),
234                        ("Invalid EBML length size tag (0x%x) at position %llu (0x%llx)",
235                        data[0], pos, pos));
236     return -1;
237   }
238
239   if ((total &= (len_mask - 1)) == len_mask - 1)
240     num_ffs++;
241   if (gst_bytestream_peek_bytes (ebml->bs, &data, read) != read) {
242     guint64 pos = gst_bytestream_tell (ebml->bs);
243     GST_ELEMENT_ERROR (ebml, RESOURCE, READ, (NULL),
244                        ("Read error at position %llu (0x%llx)", pos, pos));
245     return -1;
246   }
247   while (n < read) {
248     if (data[n] == 0xff)
249       num_ffs++;
250     total = (total << 8) | data[n];
251     n++;
252   }
253
254   if (read == num_ffs)
255     *length = G_MAXUINT64;
256   else
257     *length = total;
258
259   return read;
260 }
261
262 /*
263  * Read: the actual data.
264  * Return: the data, as a GstBuffer.
265  */
266
267 static GstBuffer *
268 gst_ebml_read_element_data (GstEbmlRead *ebml,
269                             guint64      length)
270 {
271   GstBuffer *buf = NULL;
272
273   if (gst_bytestream_peek (ebml->bs, &buf, length) != length) {
274     guint64 pos = gst_bytestream_tell (ebml->bs);
275     GST_ELEMENT_ERROR (ebml, RESOURCE, READ, (NULL),
276                        ("Read error at position %llu (0x%llx)", pos, pos));
277     if (buf)
278       gst_buffer_unref (buf);
279     return NULL;
280   }
281
282   gst_bytestream_flush_fast (ebml->bs, length);
283
284   return buf;
285 }
286
287 /*
288  * Return: the ID of the next element.
289  * Level_up contains the amount of levels that this
290  * next element lies higher than the previous one.
291  */
292
293 guint32
294 gst_ebml_peek_id (GstEbmlRead *ebml,
295                   guint       *level_up)
296 {
297   guint32 id;
298
299   g_assert (level_up);
300
301   if (gst_ebml_read_element_id (ebml, &id, level_up) < 0)
302     return 0;
303
304   return id;
305 }
306
307 /*
308  * Seek to a given offset.
309  */
310
311 GstEvent *
312 gst_ebml_read_seek (GstEbmlRead *ebml,
313                     guint64      offset)
314 {
315   guint32 remaining;
316   GstEvent *event = NULL;
317   guchar *data;
318
319   /* first, flush remaining buffers */
320   gst_bytestream_get_status (ebml->bs, &remaining, &event);
321   if (event) {
322     g_warning ("Unexpected event before seek");
323     gst_event_unref (event);
324   }
325   if (remaining)
326     gst_bytestream_flush_fast (ebml->bs, remaining);
327
328   /* now seek */
329   if (!gst_bytestream_seek (ebml->bs, offset, GST_SEEK_METHOD_SET)) {
330     GST_ELEMENT_ERROR (ebml, RESOURCE, SEEK, (NULL),
331                        ("Seek to position %llu (0x%llx) failed", offset, offset));
332     return NULL;
333   }
334
335   while (!event) {
336     /* and now, peek a new byte. This will fail because there's a
337      * pending event. Then, take the event and return it. */
338     if (gst_bytestream_peek_bytes (ebml->bs, &data, 1)) {
339       GST_WARNING ("Unexpected data after seek - this means seek failed");
340       break;
341     }
342
343     /* get the discont event and return */
344     gst_bytestream_get_status (ebml->bs, &remaining, &event);
345     if (!event) {
346       GST_WARNING ("No discontinuity event after seek - seek failed");
347       break;
348     } else if (GST_EVENT_TYPE (event) != GST_EVENT_DISCONTINUOUS) {
349       gst_pad_event_default (ebml->sinkpad, event);
350       event = NULL;
351     }
352   }
353
354   return event;
355 }
356
357 /*
358  * Skip the next element.
359  */
360
361 gboolean
362 gst_ebml_read_skip (GstEbmlRead *ebml)
363 {
364   gint bytes;
365   guint32 id, remaining;
366   guint64 length;
367   GstEvent *event;
368
369   if ((bytes = gst_ebml_read_element_id (ebml, &id, NULL)) < 0)
370     return FALSE;
371   gst_bytestream_flush_fast (ebml->bs, bytes);
372
373   if ((bytes = gst_ebml_read_element_length (ebml, &length)) < 0)
374     return FALSE;
375   gst_bytestream_flush_fast (ebml->bs, bytes);
376
377   /* do we have enough bytes left to skip? */
378   gst_bytestream_get_status (ebml->bs, &remaining, &event);
379   if (event) {
380     g_warning ("Unexpected event before skip");
381     gst_event_unref (event);
382   }
383
384   if (remaining >= length)
385     return gst_bytestream_flush (ebml->bs, length);
386
387   if (!(event = gst_ebml_read_seek (ebml,
388                         gst_bytestream_tell (ebml->bs) + length)))
389     return FALSE;
390
391   gst_event_unref (event);
392
393   return TRUE;
394 }
395
396 /*
397  * Read the next element as a GstBuffer (binary).
398  */
399
400 gboolean
401 gst_ebml_read_buffer (GstEbmlRead *ebml,
402                       guint32     *id,
403                       GstBuffer  **buf)
404 {
405   gint bytes;
406   guint64 length;
407
408   if ((bytes = gst_ebml_read_element_id (ebml, id, NULL)) < 0)
409     return FALSE;
410   gst_bytestream_flush_fast (ebml->bs, bytes);
411
412   if ((bytes = gst_ebml_read_element_length (ebml, &length)) < 0)
413     return FALSE;
414   gst_bytestream_flush_fast (ebml->bs, bytes);
415
416   return ((*buf = gst_ebml_read_element_data (ebml, length)) != NULL);
417 }
418
419 /*
420  * Read the next element as an unsigned int.
421  */
422
423 gboolean
424 gst_ebml_read_uint (GstEbmlRead *ebml,
425                     guint32     *id,
426                     guint64     *num)
427 {
428   GstBuffer *buf;
429   guint8 *data;
430   guint size;
431
432   if (!gst_ebml_read_buffer (ebml, id, &buf))
433     return FALSE;
434
435   data = GST_BUFFER_DATA (buf);
436   size = GST_BUFFER_SIZE (buf);
437   if (size < 1 || size > 8) {
438     GST_ELEMENT_ERROR (ebml, STREAM, DEMUX, (NULL),
439                        ("Invalid integer element size %d at position %llu (0x%llu)",
440                        size, GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf)));
441     gst_buffer_unref (buf);
442     return FALSE;
443   }
444   *num = 0;
445   while (size > 0) {
446     *num = (*num << 8) | data[GST_BUFFER_SIZE (buf) - size];
447     size--;
448   }
449
450   gst_buffer_unref (buf);
451
452   return TRUE;
453 }
454
455 /*
456  * Read the next element as a signed int.
457  */
458
459 gboolean
460 gst_ebml_read_sint (GstEbmlRead *ebml,
461                     guint32     *id,
462                     gint64      *num)
463 {
464   GstBuffer *buf;
465   guint8 *data;
466   guint size, negative = 0, n = 0;
467
468   if (!gst_ebml_read_buffer (ebml, id, &buf))
469     return FALSE;
470
471   data = GST_BUFFER_DATA (buf);
472   size = GST_BUFFER_SIZE (buf);
473   if (size < 1 || size > 8) {
474     GST_ELEMENT_ERROR (ebml, STREAM, DEMUX, (NULL),
475                        ("Invalid integer element size %d at position %llu (0x%llx)",
476                        size, GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf)));
477     gst_buffer_unref (buf);
478     return FALSE;
479   }
480   if (data[0] & 0x80) {
481     negative = 1;
482     data[0] &= ~0x80;
483   }
484   *num = 0;
485   while (n < size) {
486     *num = (*num << 8) | data[n++];
487   }
488
489   /* make signed */
490   if (negative) {
491     *num = *num - (1LL << ((8 * size) - 1));
492   }
493
494   gst_buffer_unref (buf);
495
496   return TRUE;
497 }
498
499 /*
500  * Read the next element as a float.
501  */
502
503 gboolean
504 gst_ebml_read_float (GstEbmlRead *ebml,
505                      guint32     *id,
506                      gdouble     *num)
507 {
508   GstBuffer *buf;
509   guint8 *data;
510   guint size;
511
512   if (!gst_ebml_read_buffer (ebml, id, &buf))
513     return FALSE;
514
515   data = GST_BUFFER_DATA (buf);
516   size = GST_BUFFER_SIZE (buf);
517
518   if (size != 4 && size != 8 && size != 10) {
519     GST_ELEMENT_ERROR (ebml, STREAM, DEMUX, (NULL),
520                        ("Invalid float element size %d at position %llu (0x%llx)",
521                        size, GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf)));
522     gst_buffer_unref (buf);
523     return FALSE;
524   }
525
526   if (size == 10) {
527     GST_ELEMENT_ERROR (ebml, CORE, NOT_IMPLEMENTED, (NULL),
528                        ("FIXME! 10-byte floats unimplemented"));
529     gst_buffer_unref (buf);
530     return FALSE;
531   }
532
533   if (size == 4) {
534     gfloat f;
535
536 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
537     f = * (gfloat *) data;
538 #else
539     while (size > 0) {
540       ((guint8 *) &f)[size - 1] = data[4 - size];
541       size--;
542     }
543 #endif
544
545     *num = f;
546   } else {
547     gdouble d;
548
549 #if (G_BYTE_ORDER == G_BIG_ENDIAN)
550     d = * (gdouble *) data;
551 #else
552     while (size > 0) {
553       ((guint8 *) &d)[size - 1] = data[8 - size];
554       size--;
555     }
556 #endif
557
558     *num = d;
559   }
560
561   gst_buffer_unref (buf);
562
563   return TRUE;
564 }
565
566 /*
567  * Read the next element as an ASCII string.
568  */
569
570 gboolean
571 gst_ebml_read_ascii (GstEbmlRead *ebml,
572                      guint32     *id,
573                      gchar      **str)
574 {
575   GstBuffer *buf;
576
577   if (!gst_ebml_read_buffer (ebml, id, &buf))
578     return FALSE;
579
580   *str = g_malloc (GST_BUFFER_SIZE (buf) + 1);
581   memcpy (*str, GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
582   (*str)[GST_BUFFER_SIZE (buf)] = '\0';
583
584   gst_buffer_unref (buf);
585
586   return TRUE;
587 }
588
589 /*
590  * Read the next element as a UTF-8 string.
591  */
592
593 gboolean
594 gst_ebml_read_utf8 (GstEbmlRead *ebml,
595                     guint32     *id,
596                     gchar      **str)
597 {
598   return gst_ebml_read_ascii (ebml, id, str);
599 }
600
601 /*
602  * Read the next element as a date (nanoseconds since 1/1/2000).
603  */
604
605 gboolean
606 gst_ebml_read_date (GstEbmlRead *ebml,
607                     guint32     *id,
608                     gint64      *date)
609 {
610   return gst_ebml_read_sint (ebml, id, date);
611 }
612
613 /*
614  * Read the next element, but only the header. The contents
615  * are supposed to be sub-elements which can be read separately.
616  */
617
618 gboolean
619 gst_ebml_read_master (GstEbmlRead *ebml,
620                       guint32     *id)
621 {
622   gint bytes;
623   guint64 length;
624   GstEbmlLevel *level;
625
626   if ((bytes = gst_ebml_read_element_id (ebml, id, NULL)) < 0)
627     return FALSE;
628   gst_bytestream_flush_fast (ebml->bs, bytes);
629
630   if ((bytes = gst_ebml_read_element_length (ebml, &length)) < 0)
631     return FALSE;
632   gst_bytestream_flush_fast (ebml->bs, bytes);
633
634   /* remember level */
635   level = g_new (GstEbmlLevel, 1);
636   level->start = gst_bytestream_tell (ebml->bs);
637   level->length = length;
638   ebml->level = g_list_append (ebml->level, level);
639
640   return TRUE;
641 }
642
643 /*
644  * Read the next element as binary data.
645  */
646
647 gboolean
648 gst_ebml_read_binary (GstEbmlRead *ebml,
649                       guint32     *id,
650                       guint8     **binary,
651                       guint64     *length)
652 {
653   GstBuffer *buf;
654
655   if (!gst_ebml_read_buffer (ebml, id, &buf))
656     return FALSE;
657
658   *length = GST_BUFFER_SIZE (buf);
659   *binary = g_memdup (GST_BUFFER_DATA (buf), GST_BUFFER_SIZE (buf));
660
661   gst_buffer_unref (buf);
662
663   return TRUE;
664 }
665
666 /*
667  * Read an EBML header.
668  */
669
670 gboolean
671 gst_ebml_read_header (GstEbmlRead *ebml,
672                       gchar      **doctype,
673                       guint       *version)
674 {
675   /* this function is the first to be called */
676   guint32 id;
677   guint level_up;
678
679   /* default init */
680   if (doctype)
681     *doctype = NULL;
682   if (version)
683     *version = 1;
684
685   if (!(id = gst_ebml_peek_id (ebml, &level_up)))
686     return FALSE;
687   if (level_up != 0 || id != GST_EBML_ID_HEADER) {
688     GST_ELEMENT_ERROR (ebml, STREAM, WRONG_TYPE, (NULL), (NULL));
689     return FALSE;
690   }
691   if (!gst_ebml_read_master (ebml, &id))
692     return FALSE;
693   g_assert (id == GST_EBML_ID_HEADER);
694
695   while (TRUE) {
696     if (!(id = gst_ebml_peek_id (ebml, &level_up)))
697       return FALSE;
698
699     /* end-of-header */
700     if (level_up)
701       break;
702
703     switch (id) {
704       /* is our read version uptodate? */
705       case GST_EBML_ID_EBMLREADVERSION: {
706         guint64 num;
707
708         if (!gst_ebml_read_uint (ebml, &id, &num))
709           return FALSE;
710         g_assert (id == GST_EBML_ID_EBMLREADVERSION);
711         if (num != GST_EBML_VERSION)
712           return FALSE;
713         break;
714       }
715
716       /* we only handle 8 byte lengths at max */
717       case GST_EBML_ID_EBMLMAXSIZELENGTH: {
718         guint64 num;
719
720         if (!gst_ebml_read_uint (ebml, &id, &num))
721           return FALSE;
722         g_assert (id == GST_EBML_ID_EBMLMAXSIZELENGTH);
723         if (num != sizeof (guint64))
724           return FALSE;
725         break;
726       }
727
728       /* we handle 4 byte IDs at max */
729       case GST_EBML_ID_EBMLMAXIDLENGTH: {
730         guint64 num;
731
732         if (!gst_ebml_read_uint (ebml, &id, &num))
733           return FALSE;
734         g_assert (id == GST_EBML_ID_EBMLMAXIDLENGTH);
735         if (num != sizeof (guint32))
736           return FALSE;
737         break;
738       }
739
740       case GST_EBML_ID_DOCTYPE: {
741         gchar *text;
742
743         if (!gst_ebml_read_ascii (ebml, &id, &text))
744           return FALSE;
745         g_assert (id == GST_EBML_ID_DOCTYPE); 
746         if (doctype) {
747           if (doctype)
748             g_free (*doctype);
749           *doctype = text;
750         } else
751           g_free (text);
752         break;
753       }
754
755       case GST_EBML_ID_DOCTYPEREADVERSION: {
756         guint64 num;
757
758         if (!gst_ebml_read_uint (ebml, &id, &num))
759           return FALSE;
760         g_assert (id == GST_EBML_ID_DOCTYPEREADVERSION); 
761         if (version)
762           *version = num;
763         break;
764       }
765
766       default:
767         GST_WARNING ("Unknown data type 0x%x in EBML header (ignored)", id);
768         /* pass-through */
769
770       /* we ignore these two, as they don't tell us anything we care about */
771       case GST_EBML_ID_VOID:
772       case GST_EBML_ID_EBMLVERSION:
773       case GST_EBML_ID_DOCTYPEVERSION:
774         if (!gst_ebml_read_skip (ebml))
775           return FALSE;
776         break;
777     }
778   }
779
780   return TRUE;
781 }