realmedia: Add support for group-id in the stream-start event
[platform/upstream/gstreamer.git] / gst / realmedia / rmdemux.c
1 /* GStreamer RealMedia demuxer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) <2003> David A. Schleef <ds@schleef.org>
4  * Copyright (C) <2004> Stephane Loeuillet <gstreamer@leroutier.net>
5  * Copyright (C) <2005> Owen Fraser-Green <owen@discobabe.net>
6  * Copyright (C) <2005> Michael Smith <fluendo.com>
7  * Copyright (C) <2006> Wim Taymans <wim@fluendo.com>
8  * Copyright (C) <2006> Tim-Philipp Müller <tim centricular net>
9  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public
22  * License along with this library; if not, write to the
23  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #  include "config.h"
29 #endif
30
31 #include "rmdemux.h"
32 #include "rmutils.h"
33
34 #include <string.h>
35 #include <ctype.h>
36
37 #define RMDEMUX_GUINT32_GET(a)  GST_READ_UINT32_BE(a)
38 #define RMDEMUX_GUINT16_GET(a)  GST_READ_UINT16_BE(a)
39 #define RMDEMUX_FOURCC_GET(a)   GST_READ_UINT32_LE(a)
40 #define HEADER_SIZE 10
41 #define DATA_SIZE 8
42
43 #define MAX_FRAGS 256
44
45 static const guint8 sipr_subpk_size[4] = { 29, 19, 37, 20 };
46
47 typedef struct _GstRMDemuxIndex GstRMDemuxIndex;
48
49 struct _GstRMDemuxStream
50 {
51   guint32 subtype;
52   guint32 fourcc;
53   guint32 subformat;
54   guint32 format;
55
56   int id;
57   GstPad *pad;
58   GstFlowReturn last_flow;
59   gboolean discont;
60   int timescale;
61
62   int sample_index;
63   GstRMDemuxIndex *index;
64   int index_length;
65   gint framerate_numerator;
66   gint framerate_denominator;
67   guint32 seek_offset;
68
69   guint16 width;
70   guint16 height;
71   guint16 flavor;
72   guint16 rate;                 /* samplerate         */
73   guint16 n_channels;           /* channels           */
74   guint16 sample_width;         /* bits_per_sample    */
75   guint16 leaf_size;            /* subpacket_size     */
76   guint32 packet_size;          /* coded_frame_size   */
77   guint16 version;
78   guint32 extra_data_size;      /* codec_data_length  */
79   guint8 *extra_data;           /* extras             */
80   guint32 bitrate;
81
82   gboolean needs_descrambling;
83   guint subpackets_needed;      /* subpackets needed for descrambling    */
84   GPtrArray *subpackets;        /* array containing subpacket GstBuffers */
85
86   /* Variables needed for fixing timestamps. */
87   GstClockTime next_ts, last_ts;
88   guint16 next_seq, last_seq;
89
90   gint frag_seqnum;
91   gint frag_subseq;
92   guint frag_length;
93   guint frag_current;
94   guint frag_count;
95   guint frag_offset[MAX_FRAGS];
96   GstAdapter *adapter;
97
98   GstTagList *pending_tags;
99 };
100
101 struct _GstRMDemuxIndex
102 {
103   guint32 offset;
104   GstClockTime timestamp;
105 };
106
107 static GstStaticPadTemplate gst_rmdemux_sink_template =
108 GST_STATIC_PAD_TEMPLATE ("sink",
109     GST_PAD_SINK,
110     GST_PAD_ALWAYS,
111     GST_STATIC_CAPS ("application/vnd.rn-realmedia")
112     );
113
114 static GstStaticPadTemplate gst_rmdemux_videosrc_template =
115 GST_STATIC_PAD_TEMPLATE ("video_%u",
116     GST_PAD_SRC,
117     GST_PAD_SOMETIMES,
118     GST_STATIC_CAPS_ANY);
119
120 static GstStaticPadTemplate gst_rmdemux_audiosrc_template =
121 GST_STATIC_PAD_TEMPLATE ("audio_%u",
122     GST_PAD_SRC,
123     GST_PAD_SOMETIMES,
124     GST_STATIC_CAPS_ANY);
125
126 GST_DEBUG_CATEGORY_STATIC (rmdemux_debug);
127 #define GST_CAT_DEFAULT rmdemux_debug
128
129 static GstElementClass *parent_class = NULL;
130
131 static void gst_rmdemux_class_init (GstRMDemuxClass * klass);
132 static void gst_rmdemux_base_init (GstRMDemuxClass * klass);
133 static void gst_rmdemux_init (GstRMDemux * rmdemux);
134 static void gst_rmdemux_finalize (GObject * object);
135 static GstStateChangeReturn gst_rmdemux_change_state (GstElement * element,
136     GstStateChange transition);
137 static GstFlowReturn gst_rmdemux_chain (GstPad * pad, GstObject * parent,
138     GstBuffer * buffer);
139 static void gst_rmdemux_loop (GstPad * pad);
140 static gboolean gst_rmdemux_sink_activate (GstPad * sinkpad,
141     GstObject * parent);
142 static gboolean gst_rmdemux_sink_activate_mode (GstPad * sinkpad,
143     GstObject * parent, GstPadMode mode, gboolean active);
144 static gboolean gst_rmdemux_sink_event (GstPad * pad, GstObject * parent,
145     GstEvent * event);
146 static gboolean gst_rmdemux_src_event (GstPad * pad, GstObject * parent,
147     GstEvent * event);
148 static void gst_rmdemux_send_event (GstRMDemux * rmdemux, GstEvent * event);
149 static gboolean gst_rmdemux_src_query (GstPad * pad, GstObject * parent,
150     GstQuery * query);
151 static gboolean gst_rmdemux_perform_seek (GstRMDemux * rmdemux,
152     GstEvent * event);
153
154 static void gst_rmdemux_parse__rmf (GstRMDemux * rmdemux, const guint8 * data,
155     int length);
156 static void gst_rmdemux_parse_prop (GstRMDemux * rmdemux, const guint8 * data,
157     int length);
158 static void gst_rmdemux_parse_mdpr (GstRMDemux * rmdemux,
159     const guint8 * data, int length);
160 static guint gst_rmdemux_parse_indx (GstRMDemux * rmdemux, const guint8 * data,
161     int length);
162 static void gst_rmdemux_parse_data (GstRMDemux * rmdemux, const guint8 * data,
163     int length);
164 static void gst_rmdemux_parse_cont (GstRMDemux * rmdemux, const guint8 * data,
165     int length);
166 static GstFlowReturn gst_rmdemux_parse_packet (GstRMDemux * rmdemux,
167     GstBuffer * in, guint16 version);
168 static void gst_rmdemux_parse_indx_data (GstRMDemux * rmdemux,
169     const guint8 * data, int length);
170 static void gst_rmdemux_stream_clear_cached_subpackets (GstRMDemux * rmdemux,
171     GstRMDemuxStream * stream);
172 static GstRMDemuxStream *gst_rmdemux_get_stream_by_id (GstRMDemux * rmdemux,
173     int id);
174
175 static GType
176 gst_rmdemux_get_type (void)
177 {
178   static GType rmdemux_type = 0;
179
180   if (!rmdemux_type) {
181     static const GTypeInfo rmdemux_info = {
182       sizeof (GstRMDemuxClass),
183       (GBaseInitFunc) gst_rmdemux_base_init, NULL,
184       (GClassInitFunc) gst_rmdemux_class_init,
185       NULL, NULL, sizeof (GstRMDemux), 0,
186       (GInstanceInitFunc) gst_rmdemux_init,
187     };
188
189     rmdemux_type =
190         g_type_register_static (GST_TYPE_ELEMENT, "GstRMDemux", &rmdemux_info,
191         0);
192   }
193   return rmdemux_type;
194 }
195
196 static void
197 gst_rmdemux_base_init (GstRMDemuxClass * klass)
198 {
199   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
200
201   gst_element_class_add_pad_template (element_class,
202       gst_static_pad_template_get (&gst_rmdemux_sink_template));
203   gst_element_class_add_pad_template (element_class,
204       gst_static_pad_template_get (&gst_rmdemux_videosrc_template));
205   gst_element_class_add_pad_template (element_class,
206       gst_static_pad_template_get (&gst_rmdemux_audiosrc_template));
207   gst_element_class_set_static_metadata (element_class, "RealMedia Demuxer",
208       "Codec/Demuxer",
209       "Demultiplex a RealMedia file into audio and video streams",
210       "David Schleef <ds@schleef.org>");
211 }
212
213 static void
214 gst_rmdemux_class_init (GstRMDemuxClass * klass)
215 {
216   GObjectClass *gobject_class;
217   GstElementClass *gstelement_class;
218
219   gobject_class = (GObjectClass *) klass;
220   gstelement_class = (GstElementClass *) klass;
221
222   parent_class = g_type_class_peek_parent (klass);
223
224   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_rmdemux_change_state);
225
226   GST_DEBUG_CATEGORY_INIT (rmdemux_debug, "rmdemux",
227       0, "Demuxer for Realmedia streams");
228
229   gobject_class->finalize = gst_rmdemux_finalize;
230 }
231
232 static void
233 gst_rmdemux_finalize (GObject * object)
234 {
235   GstRMDemux *rmdemux = GST_RMDEMUX (object);
236
237   if (rmdemux->adapter) {
238     g_object_unref (rmdemux->adapter);
239     rmdemux->adapter = NULL;
240   }
241
242   GST_CALL_PARENT (G_OBJECT_CLASS, finalize, (object));
243 }
244
245 static void
246 gst_rmdemux_init (GstRMDemux * rmdemux)
247 {
248   rmdemux->sinkpad =
249       gst_pad_new_from_static_template (&gst_rmdemux_sink_template, "sink");
250   gst_pad_set_event_function (rmdemux->sinkpad,
251       GST_DEBUG_FUNCPTR (gst_rmdemux_sink_event));
252   gst_pad_set_chain_function (rmdemux->sinkpad,
253       GST_DEBUG_FUNCPTR (gst_rmdemux_chain));
254   gst_pad_set_activate_function (rmdemux->sinkpad,
255       GST_DEBUG_FUNCPTR (gst_rmdemux_sink_activate));
256   gst_pad_set_activatemode_function (rmdemux->sinkpad,
257       GST_DEBUG_FUNCPTR (gst_rmdemux_sink_activate_mode));
258
259   gst_element_add_pad (GST_ELEMENT (rmdemux), rmdemux->sinkpad);
260
261   rmdemux->adapter = gst_adapter_new ();
262   rmdemux->first_ts = GST_CLOCK_TIME_NONE;
263   rmdemux->base_ts = GST_CLOCK_TIME_NONE;
264   rmdemux->need_newsegment = TRUE;
265   rmdemux->have_group_id = FALSE;
266   rmdemux->group_id = G_MAXUINT;
267
268   gst_rm_utils_run_tests ();
269 }
270
271 static gboolean
272 gst_rmdemux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
273 {
274   gboolean ret;
275
276   switch (GST_EVENT_TYPE (event)) {
277     case GST_EVENT_SEGMENT:
278       gst_event_unref (event);
279       ret = TRUE;
280       break;
281     default:
282       ret = gst_pad_event_default (pad, parent, event);
283       break;
284   }
285   return ret;
286 }
287
288 static gboolean
289 gst_rmdemux_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
290 {
291   gboolean ret = TRUE;
292
293   GstRMDemux *rmdemux = GST_RMDEMUX (parent);
294
295   GST_LOG_OBJECT (rmdemux, "handling src event");
296
297   switch (GST_EVENT_TYPE (event)) {
298     case GST_EVENT_SEEK:
299     {
300       gboolean running;
301
302       GST_LOG_OBJECT (rmdemux, "Event on src: SEEK");
303       /* can't seek if we are not seekable, FIXME could pass the
304        * seek query upstream after converting it to bytes using
305        * the average bitrate of the stream. */
306       if (!rmdemux->seekable) {
307         ret = FALSE;
308         GST_DEBUG ("seek on non seekable stream");
309         goto done_unref;
310       }
311
312       GST_OBJECT_LOCK (rmdemux);
313       /* check if we can do the seek now */
314       running = rmdemux->running;
315       GST_OBJECT_UNLOCK (rmdemux);
316
317       /* now do the seek */
318       if (running) {
319         ret = gst_rmdemux_perform_seek (rmdemux, event);
320       } else
321         ret = TRUE;
322
323       gst_event_unref (event);
324       break;
325     }
326     default:
327       GST_LOG_OBJECT (rmdemux, "Event on src: type=%d", GST_EVENT_TYPE (event));
328       ret = gst_pad_event_default (pad, parent, event);
329       break;
330   }
331
332   return ret;
333
334 done_unref:
335   GST_DEBUG ("error handling event");
336   gst_event_unref (event);
337   return ret;
338 }
339
340 /* Validate that this looks like a reasonable point to seek to */
341 static gboolean
342 gst_rmdemux_validate_offset (GstRMDemux * rmdemux)
343 {
344   GstBuffer *buffer;
345   GstFlowReturn flowret;
346   guint16 version, length;
347   gboolean ret = TRUE;
348   GstMapInfo map;
349
350   buffer = NULL;
351   flowret = gst_pad_pull_range (rmdemux->sinkpad, rmdemux->offset, 4, &buffer);
352
353   if (flowret != GST_FLOW_OK) {
354     GST_DEBUG_OBJECT (rmdemux, "Failed to pull data at offset %d",
355         rmdemux->offset);
356     return FALSE;
357   }
358   /* TODO: Can we also be seeking to a 'DATA' chunk header? Check this.
359    * Also, for the case we currently handle, can we check any more? It's pretty
360    * sucky to not be validating a little more heavily than this... */
361   /* This should now be the start of a data packet header. That begins with
362    * a 2-byte 'version' field, which has to be 0 or 1, then a length. I'm not
363    * certain what values are valid for length, but it must always be at least
364    * 4 bytes, and we can check that it won't take us past our known total size
365    */
366
367   gst_buffer_map (buffer, &map, GST_MAP_READ);
368   version = RMDEMUX_GUINT16_GET (map.data);
369   if (version != 0 && version != 1) {
370     GST_DEBUG_OBJECT (rmdemux, "Expected version 0 or 1, got %d",
371         (int) version);
372     ret = FALSE;
373   }
374
375   length = RMDEMUX_GUINT16_GET (map.data + 2);
376   /* TODO: Also check against total stream length */
377   if (length < 4) {
378     GST_DEBUG_OBJECT (rmdemux, "Expected length >= 4, got %d", (int) length);
379     ret = FALSE;
380   }
381   gst_buffer_unmap (buffer, &map);
382
383   if (ret) {
384     rmdemux->offset += 4;
385     gst_adapter_clear (rmdemux->adapter);
386     gst_adapter_push (rmdemux->adapter, buffer);
387   } else {
388     GST_WARNING_OBJECT (rmdemux, "Failed to validate seek offset at %d",
389         rmdemux->offset);
390     gst_buffer_unref (buffer);
391   }
392
393   return ret;
394 }
395
396 static gboolean
397 find_seek_offset_bytes (GstRMDemux * rmdemux, guint target)
398 {
399   int i;
400   GSList *cur;
401   gboolean ret = FALSE;
402
403   for (cur = rmdemux->streams; cur; cur = cur->next) {
404     GstRMDemuxStream *stream = cur->data;
405
406     /* Search backwards through this stream's index until we find the first
407      * timestamp before our target time */
408     for (i = stream->index_length - 1; i >= 0; i--) {
409       if (stream->index[i].offset <= target) {
410         /* Set the seek_offset for the stream so we don't bother parsing it
411          * until we've passed that point */
412         stream->seek_offset = stream->index[i].offset;
413         rmdemux->offset = stream->index[i].offset;
414         ret = TRUE;
415         break;
416       }
417     }
418   }
419   return ret;
420 }
421
422 static gboolean
423 find_seek_offset_time (GstRMDemux * rmdemux, GstClockTime time)
424 {
425   int i, n_stream;
426   gboolean ret = FALSE;
427   GSList *cur;
428   GstClockTime earliest = GST_CLOCK_TIME_NONE;
429
430   n_stream = 0;
431   for (cur = rmdemux->streams; cur; cur = cur->next, n_stream++) {
432     GstRMDemuxStream *stream = cur->data;
433
434     /* Search backwards through this stream's index until we find the first
435      * timestamp before our target time */
436     for (i = stream->index_length - 1; i >= 0; i--) {
437       if (stream->index[i].timestamp <= time) {
438         /* Set the seek_offset for the stream so we don't bother parsing it
439          * until we've passed that point */
440         stream->seek_offset = stream->index[i].offset;
441
442         /* If it's also the earliest timestamp we've seen of all streams, then
443          * that's our target!
444          */
445         if (earliest == GST_CLOCK_TIME_NONE ||
446             stream->index[i].timestamp < earliest) {
447           earliest = stream->index[i].timestamp;
448           rmdemux->offset = stream->index[i].offset;
449           GST_DEBUG_OBJECT (rmdemux,
450               "We're looking for %" GST_TIME_FORMAT
451               " and we found that stream %d has the latest index at %"
452               GST_TIME_FORMAT, GST_TIME_ARGS (rmdemux->segment.start), n_stream,
453               GST_TIME_ARGS (earliest));
454         }
455
456         ret = TRUE;
457
458         break;
459       }
460     }
461     stream->discont = TRUE;
462   }
463   return ret;
464 }
465
466 static gboolean
467 gst_rmdemux_perform_seek (GstRMDemux * rmdemux, GstEvent * event)
468 {
469   gboolean validated;
470   gboolean ret = TRUE;
471   gboolean flush;
472   GstFormat format;
473   gdouble rate;
474   GstSeekFlags flags;
475   GstSeekType cur_type, stop_type;
476   gint64 cur, stop;
477   gboolean update;
478
479   if (event) {
480     GST_DEBUG_OBJECT (rmdemux, "seek with event");
481
482     gst_event_parse_seek (event, &rate, &format, &flags,
483         &cur_type, &cur, &stop_type, &stop);
484
485     /* we can only seek on time */
486     if (format != GST_FORMAT_TIME) {
487       GST_DEBUG_OBJECT (rmdemux, "can only seek on TIME");
488       goto error;
489     }
490     /* cannot yet do backwards playback */
491     if (rate <= 0.0) {
492       GST_DEBUG_OBJECT (rmdemux, "can only seek with positive rate, not %lf",
493           rate);
494       goto error;
495     }
496   } else {
497     GST_DEBUG_OBJECT (rmdemux, "seek without event");
498
499     flags = 0;
500     rate = 1.0;
501   }
502
503   GST_DEBUG_OBJECT (rmdemux, "seek, rate %g", rate);
504
505   flush = flags & GST_SEEK_FLAG_FLUSH;
506
507   /* first step is to unlock the streaming thread if it is
508    * blocked in a chain call, we do this by starting the flush. */
509   if (flush) {
510     gst_pad_push_event (rmdemux->sinkpad, gst_event_new_flush_start ());
511     gst_rmdemux_send_event (rmdemux, gst_event_new_flush_start ());
512   } else {
513     gst_pad_pause_task (rmdemux->sinkpad);
514   }
515
516   GST_LOG_OBJECT (rmdemux, "Done starting flushes");
517
518   /* now grab the stream lock so that streaming cannot continue, for
519    * non flushing seeks when the element is in PAUSED this could block
520    * forever. */
521   GST_PAD_STREAM_LOCK (rmdemux->sinkpad);
522
523   GST_LOG_OBJECT (rmdemux, "Took streamlock");
524
525   if (event) {
526     gst_segment_do_seek (&rmdemux->segment, rate, format, flags,
527         cur_type, cur, stop_type, stop, &update);
528   }
529
530   GST_DEBUG_OBJECT (rmdemux, "segment positions set to %" GST_TIME_FORMAT "-%"
531       GST_TIME_FORMAT, GST_TIME_ARGS (rmdemux->segment.start),
532       GST_TIME_ARGS (rmdemux->segment.stop));
533
534   /* we need to stop flushing on the sinkpad as we're going to use it
535    * next. We can do this as we have the STREAM lock now. */
536   gst_pad_push_event (rmdemux->sinkpad, gst_event_new_flush_stop (TRUE));
537
538   GST_LOG_OBJECT (rmdemux, "Pushed FLUSH_STOP event");
539
540   /* For each stream, find the first index offset equal to or before our seek 
541    * target. Of these, find the smallest offset. That's where we seek to.
542    *
543    * Then we pull 4 bytes from that offset, and validate that we've seeked to a
544    * what looks like a plausible packet.
545    * If that fails, restart, with the seek target set to one less than the
546    * offset we just tried. If we run out of places to try, treat that as a fatal
547    * error.
548    */
549   if (!find_seek_offset_time (rmdemux, rmdemux->segment.position)) {
550     GST_LOG_OBJECT (rmdemux, "Failed to find seek offset by time");
551     ret = FALSE;
552     goto done;
553   }
554
555   GST_LOG_OBJECT (rmdemux, "Validating offset %u", rmdemux->offset);
556   validated = gst_rmdemux_validate_offset (rmdemux);
557   while (!validated) {
558     GST_INFO_OBJECT (rmdemux, "Failed to validate offset at %u",
559         rmdemux->offset);
560     if (!find_seek_offset_bytes (rmdemux, rmdemux->offset - 1)) {
561       ret = FALSE;
562       goto done;
563     }
564     validated = gst_rmdemux_validate_offset (rmdemux);
565   }
566
567   GST_LOG_OBJECT (rmdemux, "Found final offset. Excellent!");
568
569   /* now we have a new position, prepare for streaming again */
570   {
571     /* Reset the demuxer state */
572     rmdemux->state = RMDEMUX_STATE_DATA_PACKET;
573
574     if (flush)
575       gst_rmdemux_send_event (rmdemux, gst_event_new_flush_stop (TRUE));
576
577     /* must send newsegment event from streaming thread, so just set flag */
578     rmdemux->need_newsegment = TRUE;
579
580     /* notify start of new segment */
581     if (rmdemux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
582       gst_element_post_message (GST_ELEMENT_CAST (rmdemux),
583           gst_message_new_segment_start (GST_OBJECT_CAST (rmdemux),
584               GST_FORMAT_TIME, rmdemux->segment.position));
585     }
586
587     /* restart our task since it might have been stopped when we did the 
588      * flush. */
589     gst_pad_start_task (rmdemux->sinkpad, (GstTaskFunction) gst_rmdemux_loop,
590         rmdemux->sinkpad, NULL);
591   }
592
593 done:
594   /* streaming can continue now */
595   GST_PAD_STREAM_UNLOCK (rmdemux->sinkpad);
596
597   return ret;
598
599 error:
600   {
601     GST_DEBUG_OBJECT (rmdemux, "seek failed");
602     return FALSE;
603   }
604 }
605
606
607 static gboolean
608 gst_rmdemux_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
609 {
610   gboolean res = FALSE;
611   GstRMDemux *rmdemux;
612
613   rmdemux = GST_RMDEMUX (parent);
614
615   switch (GST_QUERY_TYPE (query)) {
616     case GST_QUERY_POSITION:
617       GST_DEBUG_OBJECT (rmdemux, "Position query: no idea from demuxer!");
618       break;
619     case GST_QUERY_DURATION:{
620       GstFormat fmt;
621
622       gst_query_parse_duration (query, &fmt, NULL);
623       if (fmt == GST_FORMAT_TIME) {
624         GST_OBJECT_LOCK (rmdemux);
625         if (G_LIKELY (rmdemux->running)) {
626           gst_query_set_duration (query, GST_FORMAT_TIME, rmdemux->duration);
627           GST_DEBUG_OBJECT (rmdemux, "duration set to %" GST_TIME_FORMAT,
628               GST_TIME_ARGS (rmdemux->duration));
629           res = TRUE;
630         }
631         GST_OBJECT_UNLOCK (rmdemux);
632       }
633       break;
634     }
635     case GST_QUERY_SEEKING:{
636       GstFormat fmt;
637
638       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
639       if (fmt == GST_FORMAT_TIME) {
640         GST_OBJECT_LOCK (rmdemux);
641         if (G_LIKELY (rmdemux->running)) {
642           gst_query_set_seeking (query, GST_FORMAT_TIME, rmdemux->seekable,
643               0, rmdemux->duration);
644           res = TRUE;
645         }
646         GST_OBJECT_UNLOCK (rmdemux);
647       }
648       break;
649     }
650     default:
651       res = gst_pad_query_default (pad, parent, query);
652       break;
653   }
654
655   return res;
656 }
657
658 static void
659 gst_rmdemux_reset (GstRMDemux * rmdemux)
660 {
661   GSList *cur;
662
663   GST_OBJECT_LOCK (rmdemux);
664   rmdemux->running = FALSE;
665   GST_OBJECT_UNLOCK (rmdemux);
666
667   for (cur = rmdemux->streams; cur; cur = cur->next) {
668     GstRMDemuxStream *stream = cur->data;
669
670     g_object_unref (stream->adapter);
671     gst_rmdemux_stream_clear_cached_subpackets (rmdemux, stream);
672     gst_element_remove_pad (GST_ELEMENT (rmdemux), stream->pad);
673     if (stream->pending_tags)
674       gst_tag_list_unref (stream->pending_tags);
675     if (stream->subpackets)
676       g_ptr_array_free (stream->subpackets, TRUE);
677     g_free (stream->index);
678     g_free (stream);
679   }
680   g_slist_free (rmdemux->streams);
681   rmdemux->streams = NULL;
682   rmdemux->n_audio_streams = 0;
683   rmdemux->n_video_streams = 0;
684
685   if (rmdemux->pending_tags != NULL) {
686     gst_tag_list_unref (rmdemux->pending_tags);
687     rmdemux->pending_tags = NULL;
688   }
689
690   gst_adapter_clear (rmdemux->adapter);
691   rmdemux->state = RMDEMUX_STATE_HEADER;
692   rmdemux->have_pads = FALSE;
693
694   gst_segment_init (&rmdemux->segment, GST_FORMAT_UNDEFINED);
695   rmdemux->first_ts = GST_CLOCK_TIME_NONE;
696   rmdemux->base_ts = GST_CLOCK_TIME_NONE;
697   rmdemux->need_newsegment = TRUE;
698
699   rmdemux->have_group_id = FALSE;
700   rmdemux->group_id = G_MAXUINT;
701 }
702
703 static GstStateChangeReturn
704 gst_rmdemux_change_state (GstElement * element, GstStateChange transition)
705 {
706   GstRMDemux *rmdemux = GST_RMDEMUX (element);
707   GstStateChangeReturn res;
708
709   switch (transition) {
710     case GST_STATE_CHANGE_NULL_TO_READY:
711       break;
712     case GST_STATE_CHANGE_READY_TO_PAUSED:
713       rmdemux->state = RMDEMUX_STATE_HEADER;
714       rmdemux->have_pads = FALSE;
715       gst_segment_init (&rmdemux->segment, GST_FORMAT_TIME);
716       rmdemux->running = FALSE;
717       break;
718     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
719       break;
720     default:
721       break;
722   }
723
724   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
725
726   switch (transition) {
727     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
728       break;
729     case GST_STATE_CHANGE_PAUSED_TO_READY:{
730       gst_rmdemux_reset (rmdemux);
731       break;
732     }
733     case GST_STATE_CHANGE_READY_TO_NULL:
734       break;
735     default:
736       break;
737   }
738
739   return res;
740 }
741
742 /* this function is called when the pad is activated and should start
743  * processing data.
744  *
745  * We check if we can do random access to decide if we work push or
746  * pull based.
747  */
748 static gboolean
749 gst_rmdemux_sink_activate (GstPad * sinkpad, GstObject * parent)
750 {
751   GstQuery *query;
752   gboolean pull_mode;
753
754   query = gst_query_new_scheduling ();
755
756   if (!gst_pad_peer_query (sinkpad, query)) {
757     gst_query_unref (query);
758     goto activate_push;
759   }
760
761   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
762       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
763   gst_query_unref (query);
764
765   if (!pull_mode)
766     goto activate_push;
767
768   GST_DEBUG_OBJECT (sinkpad, "activating pull");
769   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
770
771 activate_push:
772   {
773     GST_DEBUG_OBJECT (sinkpad, "activating push");
774     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
775   }
776 }
777
778 static gboolean
779 gst_rmdemux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
780     GstPadMode mode, gboolean active)
781 {
782   gboolean res;
783   GstRMDemux *demux;
784
785   demux = GST_RMDEMUX (parent);
786
787   switch (mode) {
788     case GST_PAD_MODE_PUSH:
789       demux->seekable = FALSE;
790       demux->running = active;
791       res = TRUE;
792       break;
793     case GST_PAD_MODE_PULL:
794       if (active) {
795         demux->seekable = TRUE;
796         demux->offset = 0;
797         demux->loop_state = RMDEMUX_LOOP_STATE_HEADER;
798         demux->data_offset = G_MAXUINT;
799         res =
800             gst_pad_start_task (sinkpad, (GstTaskFunction) gst_rmdemux_loop,
801             sinkpad, NULL);
802       } else {
803         res = gst_pad_stop_task (sinkpad);
804       }
805       break;
806     default:
807       res = FALSE;
808       break;
809   }
810   return res;
811 }
812
813
814 /* random access mode - just pass over to our chain function */
815 static void
816 gst_rmdemux_loop (GstPad * pad)
817 {
818   GstRMDemux *rmdemux;
819   GstBuffer *buffer;
820   GstFlowReturn ret = GST_FLOW_OK;
821   guint size;
822
823   rmdemux = GST_RMDEMUX (GST_PAD_PARENT (pad));
824
825   GST_LOG_OBJECT (rmdemux, "loop with state=%d and offset=0x%x",
826       rmdemux->loop_state, rmdemux->offset);
827
828   switch (rmdemux->state) {
829     case RMDEMUX_STATE_HEADER:
830       size = HEADER_SIZE;
831       break;
832     case RMDEMUX_STATE_HEADER_DATA:
833       size = DATA_SIZE;
834       break;
835     case RMDEMUX_STATE_DATA_PACKET:
836       size = rmdemux->avg_packet_size;
837       break;
838     case RMDEMUX_STATE_EOS:
839       GST_LOG_OBJECT (rmdemux, "At EOS, pausing task");
840       ret = GST_FLOW_EOS;
841       goto need_pause;
842     default:
843       GST_LOG_OBJECT (rmdemux, "Default: requires %d bytes (state is %d)",
844           (int) rmdemux->size, rmdemux->state);
845       size = rmdemux->size;
846   }
847
848   buffer = NULL;
849   ret = gst_pad_pull_range (pad, rmdemux->offset, size, &buffer);
850   if (ret != GST_FLOW_OK) {
851     if (rmdemux->offset == rmdemux->index_offset) {
852       /* The index isn't available so forget about it */
853       rmdemux->loop_state = RMDEMUX_LOOP_STATE_DATA;
854       rmdemux->offset = rmdemux->data_offset;
855       GST_OBJECT_LOCK (rmdemux);
856       rmdemux->running = TRUE;
857       rmdemux->seekable = FALSE;
858       GST_OBJECT_UNLOCK (rmdemux);
859       return;
860     } else {
861       GST_DEBUG_OBJECT (rmdemux, "Unable to pull %d bytes at offset 0x%08x "
862           "(pull_range returned flow %s, state is %d)", (gint) size,
863           rmdemux->offset, gst_flow_get_name (ret), GST_STATE (rmdemux));
864       goto need_pause;
865     }
866   }
867
868   size = gst_buffer_get_size (buffer);
869
870   /* Defer to the chain function */
871   ret = gst_rmdemux_chain (pad, GST_OBJECT_CAST (rmdemux), buffer);
872   if (ret != GST_FLOW_OK) {
873     GST_DEBUG_OBJECT (rmdemux, "Chain flow failed at offset 0x%08x",
874         rmdemux->offset);
875     goto need_pause;
876   }
877
878   rmdemux->offset += size;
879
880   switch (rmdemux->loop_state) {
881     case RMDEMUX_LOOP_STATE_HEADER:
882       if (rmdemux->offset >= rmdemux->data_offset) {
883         /* It's the end of the header */
884         rmdemux->loop_state = RMDEMUX_LOOP_STATE_INDEX;
885         rmdemux->offset = rmdemux->index_offset;
886       }
887       break;
888     case RMDEMUX_LOOP_STATE_INDEX:
889       if (rmdemux->state == RMDEMUX_STATE_HEADER) {
890         if (rmdemux->index_offset == 0) {
891           /* We've read the last index */
892           rmdemux->loop_state = RMDEMUX_LOOP_STATE_DATA;
893           rmdemux->offset = rmdemux->data_offset;
894           GST_OBJECT_LOCK (rmdemux);
895           rmdemux->running = TRUE;
896           GST_OBJECT_UNLOCK (rmdemux);
897         } else {
898           /* Get the next index */
899           rmdemux->offset = rmdemux->index_offset;
900         }
901       }
902       break;
903     case RMDEMUX_LOOP_STATE_DATA:
904       break;
905   }
906
907   return;
908
909   /* ERRORS */
910 need_pause:
911   {
912     const gchar *reason = gst_flow_get_name (ret);
913
914     GST_LOG_OBJECT (rmdemux, "pausing task, reason %s", reason);
915     rmdemux->segment_running = FALSE;
916     gst_pad_pause_task (rmdemux->sinkpad);
917
918     if (ret == GST_FLOW_EOS) {
919       /* perform EOS logic */
920       if (rmdemux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
921         gint64 stop;
922
923         /* for segment playback we need to post when (in stream time)
924          * we stopped, this is either stop (when set) or the duration. */
925         if ((stop = rmdemux->segment.stop) == -1)
926           stop = rmdemux->segment.duration;
927
928         GST_LOG_OBJECT (rmdemux, "Sending segment done, at end of segment");
929         gst_element_post_message (GST_ELEMENT (rmdemux),
930             gst_message_new_segment_done (GST_OBJECT (rmdemux),
931                 GST_FORMAT_TIME, stop));
932         gst_rmdemux_send_event (rmdemux,
933             gst_event_new_segment_done (GST_FORMAT_TIME, stop));
934       } else {
935         /* normal playback, send EOS to all linked pads */
936         GST_LOG_OBJECT (rmdemux, "Sending EOS, at end of stream");
937         gst_rmdemux_send_event (rmdemux, gst_event_new_eos ());
938       }
939     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
940       GST_ELEMENT_ERROR (rmdemux, STREAM, FAILED,
941           (NULL), ("stream stopped, reason %s", reason));
942       gst_rmdemux_send_event (rmdemux, gst_event_new_eos ());
943     }
944     return;
945   }
946 }
947
948 static gboolean
949 gst_rmdemux_fourcc_isplausible (guint32 fourcc)
950 {
951   int i;
952
953   for (i = 0; i < 4; i++) {
954     if (!isprint ((int) ((unsigned char *) (&fourcc))[i])) {
955       return FALSE;
956     }
957   }
958   return TRUE;
959 }
960
961 static GstFlowReturn
962 gst_rmdemux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
963 {
964   GstFlowReturn ret = GST_FLOW_OK;
965   const guint8 *data;
966   guint16 version;
967   guint avail;
968
969   GstRMDemux *rmdemux = GST_RMDEMUX (parent);
970
971   if (rmdemux->base_ts == -1) {
972     if (GST_BUFFER_DTS_IS_VALID (buffer))
973       rmdemux->base_ts = GST_BUFFER_DTS (buffer);
974     else
975       rmdemux->base_ts = GST_BUFFER_PTS (buffer);
976
977     GST_LOG_OBJECT (rmdemux, "base_ts %" GST_TIME_FORMAT,
978         GST_TIME_ARGS (rmdemux->base_ts));
979   }
980
981   gst_adapter_push (rmdemux->adapter, buffer);
982
983   GST_LOG_OBJECT (rmdemux, "Chaining buffer of size %" G_GSIZE_FORMAT,
984       gst_buffer_get_size (buffer));
985
986   while (TRUE) {
987     avail = gst_adapter_available (rmdemux->adapter);
988
989     GST_LOG_OBJECT (rmdemux, "looping in chain, avail %u", avail);
990     switch (rmdemux->state) {
991       case RMDEMUX_STATE_HEADER:
992       {
993         if (gst_adapter_available (rmdemux->adapter) < HEADER_SIZE)
994           goto unlock;
995
996         data = gst_adapter_map (rmdemux->adapter, HEADER_SIZE);
997
998         rmdemux->object_id = RMDEMUX_FOURCC_GET (data + 0);
999         rmdemux->size = RMDEMUX_GUINT32_GET (data + 4) - HEADER_SIZE;
1000         rmdemux->object_version = RMDEMUX_GUINT16_GET (data + 8);
1001
1002         /* Sanity-check. We assume that the FOURCC is printable ASCII */
1003         if (!gst_rmdemux_fourcc_isplausible (rmdemux->object_id)) {
1004           /* Failed. Remain in HEADER state, try again... We flush only 
1005            * the actual FOURCC, not the entire header, because we could 
1006            * need to resync anywhere at all... really, this should never 
1007            * happen. */
1008           GST_WARNING_OBJECT (rmdemux, "Bogus looking header, unprintable "
1009               "FOURCC");
1010           gst_adapter_unmap (rmdemux->adapter);
1011           gst_adapter_flush (rmdemux->adapter, 4);
1012
1013           break;
1014         }
1015
1016         GST_LOG_OBJECT (rmdemux, "header found with object_id=%"
1017             GST_FOURCC_FORMAT
1018             " size=%08x object_version=%d",
1019             GST_FOURCC_ARGS (rmdemux->object_id), rmdemux->size,
1020             rmdemux->object_version);
1021
1022         gst_adapter_unmap (rmdemux->adapter);
1023         gst_adapter_flush (rmdemux->adapter, HEADER_SIZE);
1024
1025         switch (rmdemux->object_id) {
1026           case GST_MAKE_FOURCC ('.', 'R', 'M', 'F'):
1027             rmdemux->state = RMDEMUX_STATE_HEADER_RMF;
1028             break;
1029           case GST_MAKE_FOURCC ('P', 'R', 'O', 'P'):
1030             rmdemux->state = RMDEMUX_STATE_HEADER_PROP;
1031             break;
1032           case GST_MAKE_FOURCC ('M', 'D', 'P', 'R'):
1033             rmdemux->state = RMDEMUX_STATE_HEADER_MDPR;
1034             break;
1035           case GST_MAKE_FOURCC ('I', 'N', 'D', 'X'):
1036             rmdemux->state = RMDEMUX_STATE_HEADER_INDX;
1037             break;
1038           case GST_MAKE_FOURCC ('D', 'A', 'T', 'A'):
1039             rmdemux->state = RMDEMUX_STATE_HEADER_DATA;
1040             break;
1041           case GST_MAKE_FOURCC ('C', 'O', 'N', 'T'):
1042             rmdemux->state = RMDEMUX_STATE_HEADER_CONT;
1043             break;
1044           default:
1045             rmdemux->state = RMDEMUX_STATE_HEADER_UNKNOWN;
1046             break;
1047         }
1048         break;
1049       }
1050       case RMDEMUX_STATE_HEADER_UNKNOWN:
1051       {
1052         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1053           goto unlock;
1054
1055         GST_WARNING_OBJECT (rmdemux, "Unknown object_id %" GST_FOURCC_FORMAT,
1056             GST_FOURCC_ARGS (rmdemux->object_id));
1057
1058         gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1059         rmdemux->state = RMDEMUX_STATE_HEADER;
1060         break;
1061       }
1062       case RMDEMUX_STATE_HEADER_RMF:
1063       {
1064         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1065           goto unlock;
1066
1067         if ((rmdemux->object_version == 0) || (rmdemux->object_version == 1)) {
1068           data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1069           gst_rmdemux_parse__rmf (rmdemux, data, rmdemux->size);
1070           gst_adapter_unmap (rmdemux->adapter);
1071           gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1072         } else {
1073           gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1074         }
1075         rmdemux->state = RMDEMUX_STATE_HEADER;
1076         break;
1077       }
1078       case RMDEMUX_STATE_HEADER_PROP:
1079       {
1080         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1081           goto unlock;
1082
1083         data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1084         gst_rmdemux_parse_prop (rmdemux, data, rmdemux->size);
1085         gst_adapter_unmap (rmdemux->adapter);
1086         gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1087
1088         rmdemux->state = RMDEMUX_STATE_HEADER;
1089         break;
1090       }
1091       case RMDEMUX_STATE_HEADER_MDPR:
1092       {
1093         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1094           goto unlock;
1095
1096         data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1097         gst_rmdemux_parse_mdpr (rmdemux, data, rmdemux->size);
1098         gst_adapter_unmap (rmdemux->adapter);
1099         gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1100
1101         rmdemux->state = RMDEMUX_STATE_HEADER;
1102         break;
1103       }
1104       case RMDEMUX_STATE_HEADER_CONT:
1105       {
1106         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1107           goto unlock;
1108
1109         data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1110         gst_rmdemux_parse_cont (rmdemux, data, rmdemux->size);
1111         gst_adapter_unmap (rmdemux->adapter);
1112         gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1113
1114         rmdemux->state = RMDEMUX_STATE_HEADER;
1115         break;
1116       }
1117       case RMDEMUX_STATE_HEADER_DATA:
1118       {
1119         /* If we haven't already done so then signal there are no more pads */
1120         if (!rmdemux->have_pads) {
1121           GST_LOG_OBJECT (rmdemux, "no more pads");
1122           gst_element_no_more_pads (GST_ELEMENT (rmdemux));
1123           rmdemux->have_pads = TRUE;
1124         }
1125
1126         /* The actual header is only 8 bytes */
1127         rmdemux->size = DATA_SIZE;
1128         GST_LOG_OBJECT (rmdemux, "data available %" G_GSIZE_FORMAT,
1129             gst_adapter_available (rmdemux->adapter));
1130         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1131           goto unlock;
1132
1133         data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1134         gst_rmdemux_parse_data (rmdemux, data, rmdemux->size);
1135         gst_adapter_unmap (rmdemux->adapter);
1136         gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1137
1138         rmdemux->state = RMDEMUX_STATE_DATA_PACKET;
1139         break;
1140       }
1141       case RMDEMUX_STATE_HEADER_INDX:
1142       {
1143         if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1144           goto unlock;
1145
1146         data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1147         rmdemux->size = gst_rmdemux_parse_indx (rmdemux, data, rmdemux->size);
1148         /* Only flush the header */
1149         gst_adapter_unmap (rmdemux->adapter);
1150         gst_adapter_flush (rmdemux->adapter, HEADER_SIZE);
1151
1152         rmdemux->state = RMDEMUX_STATE_INDX_DATA;
1153         break;
1154       }
1155       case RMDEMUX_STATE_INDX_DATA:
1156       {
1157         /* There's not always an data to get... */
1158         if (rmdemux->size > 0) {
1159           if (gst_adapter_available (rmdemux->adapter) < rmdemux->size)
1160             goto unlock;
1161
1162           data = gst_adapter_map (rmdemux->adapter, rmdemux->size);
1163           gst_rmdemux_parse_indx_data (rmdemux, data, rmdemux->size);
1164           gst_adapter_unmap (rmdemux->adapter);
1165           gst_adapter_flush (rmdemux->adapter, rmdemux->size);
1166         }
1167
1168         rmdemux->state = RMDEMUX_STATE_HEADER;
1169         break;
1170       }
1171       case RMDEMUX_STATE_DATA_PACKET:
1172       {
1173         guint8 header[4];
1174
1175         if (gst_adapter_available (rmdemux->adapter) < 2)
1176           goto unlock;
1177
1178         gst_adapter_copy (rmdemux->adapter, header, 0, 2);
1179         version = RMDEMUX_GUINT16_GET (header);
1180         GST_LOG_OBJECT (rmdemux, "Data packet with version=%d", version);
1181
1182         if (version == 0 || version == 1) {
1183           guint16 length;
1184
1185           if (gst_adapter_available (rmdemux->adapter) < 4)
1186             goto unlock;
1187
1188           gst_adapter_copy (rmdemux->adapter, header, 0, 4);
1189
1190           length = RMDEMUX_GUINT16_GET (header + 2);
1191           GST_LOG_OBJECT (rmdemux, "Got length %d", length);
1192
1193           if (length < 4) {
1194             GST_LOG_OBJECT (rmdemux, "length too small, dropping");
1195             /* Invalid, just drop it */
1196             gst_adapter_flush (rmdemux->adapter, 4);
1197           } else {
1198             GstBuffer *buffer;
1199
1200             avail = gst_adapter_available (rmdemux->adapter);
1201             if (avail < length)
1202               goto unlock;
1203
1204             GST_LOG_OBJECT (rmdemux, "we have %u available and we needed %d",
1205                 avail, length);
1206
1207             /* flush version and length */
1208             gst_adapter_flush (rmdemux->adapter, 4);
1209             length -= 4;
1210
1211             buffer = gst_adapter_take_buffer (rmdemux->adapter, length);
1212
1213             ret = gst_rmdemux_parse_packet (rmdemux, buffer, version);
1214             rmdemux->chunk_index++;
1215           }
1216
1217           if (rmdemux->chunk_index == rmdemux->n_chunks || length == 0)
1218             rmdemux->state = RMDEMUX_STATE_HEADER;
1219         } else {
1220           /* Stream done */
1221           gst_adapter_flush (rmdemux->adapter, 2);
1222
1223           if (rmdemux->data_offset == 0) {
1224             GST_LOG_OBJECT (rmdemux,
1225                 "No further data, internal demux state EOS");
1226             rmdemux->state = RMDEMUX_STATE_EOS;
1227           } else
1228             rmdemux->state = RMDEMUX_STATE_HEADER;
1229         }
1230         break;
1231       }
1232       case RMDEMUX_STATE_EOS:
1233         gst_rmdemux_send_event (rmdemux, gst_event_new_eos ());
1234         goto unlock;
1235       default:
1236         GST_WARNING_OBJECT (rmdemux, "Unhandled state %d", rmdemux->state);
1237         goto unlock;
1238     }
1239   }
1240
1241 unlock:
1242   return ret;
1243 }
1244
1245 static GstRMDemuxStream *
1246 gst_rmdemux_get_stream_by_id (GstRMDemux * rmdemux, int id)
1247 {
1248   GSList *cur;
1249
1250   for (cur = rmdemux->streams; cur; cur = cur->next) {
1251     GstRMDemuxStream *stream = cur->data;
1252
1253     if (stream->id == id) {
1254       return stream;
1255     }
1256   }
1257
1258   return NULL;
1259 }
1260
1261 static void
1262 gst_rmdemux_send_event (GstRMDemux * rmdemux, GstEvent * event)
1263 {
1264   GSList *cur;
1265
1266   for (cur = rmdemux->streams; cur; cur = cur->next) {
1267     GstRMDemuxStream *stream = cur->data;
1268
1269     GST_DEBUG_OBJECT (rmdemux, "Pushing %s event on pad %s",
1270         GST_EVENT_TYPE_NAME (event), GST_PAD_NAME (stream->pad));
1271
1272     switch (GST_EVENT_TYPE (event)) {
1273       case GST_EVENT_FLUSH_STOP:
1274         stream->last_ts = -1;
1275         stream->next_ts = -1;
1276         stream->last_seq = -1;
1277         stream->next_seq = -1;
1278         stream->last_flow = GST_FLOW_OK;
1279         break;
1280       default:
1281         break;
1282     }
1283     gst_event_ref (event);
1284     gst_pad_push_event (stream->pad, event);
1285   }
1286   gst_event_unref (event);
1287 }
1288
1289 static void
1290 gst_rmdemux_add_stream (GstRMDemux * rmdemux, GstRMDemuxStream * stream)
1291 {
1292   GstCaps *stream_caps = NULL;
1293   const gchar *codec_tag = NULL;
1294   gchar *codec_name = NULL;
1295   gchar *stream_id;
1296   int version = 0;
1297
1298   if (stream->subtype == GST_RMDEMUX_STREAM_VIDEO) {
1299     char *name = g_strdup_printf ("video_%u", rmdemux->n_video_streams);
1300
1301     stream->pad =
1302         gst_pad_new_from_static_template (&gst_rmdemux_videosrc_template, name);
1303     g_free (name);
1304
1305     codec_tag = GST_TAG_VIDEO_CODEC;
1306
1307     switch (stream->fourcc) {
1308       case GST_RM_VDO_RV10:
1309         version = 1;
1310         break;
1311       case GST_RM_VDO_RV20:
1312         version = 2;
1313         break;
1314       case GST_RM_VDO_RV30:
1315         version = 3;
1316         break;
1317       case GST_RM_VDO_RV40:
1318         version = 4;
1319         break;
1320       default:
1321         stream_caps = gst_caps_new_simple ("video/x-unknown-fourcc",
1322             "fourcc", G_TYPE_UINT, stream->fourcc, NULL);
1323         GST_WARNING_OBJECT (rmdemux,
1324             "Unknown video FOURCC code \"%" GST_FOURCC_FORMAT "\" (%08x)",
1325             GST_FOURCC_ARGS (stream->fourcc), stream->fourcc);
1326     }
1327
1328     if (version) {
1329       stream_caps =
1330           gst_caps_new_simple ("video/x-pn-realvideo", "rmversion", G_TYPE_INT,
1331           (int) version,
1332           "format", G_TYPE_INT,
1333           (int) stream->format,
1334           "subformat", G_TYPE_INT, (int) stream->subformat, NULL);
1335     }
1336
1337     if (stream_caps) {
1338       gst_caps_set_simple (stream_caps,
1339           "width", G_TYPE_INT, stream->width,
1340           "height", G_TYPE_INT, stream->height,
1341           "framerate", GST_TYPE_FRACTION, stream->framerate_numerator,
1342           stream->framerate_denominator, NULL);
1343     }
1344     rmdemux->n_video_streams++;
1345
1346   } else if (stream->subtype == GST_RMDEMUX_STREAM_AUDIO) {
1347     char *name = g_strdup_printf ("audio_%u", rmdemux->n_audio_streams);
1348
1349     stream->pad =
1350         gst_pad_new_from_static_template (&gst_rmdemux_audiosrc_template, name);
1351     GST_LOG_OBJECT (rmdemux, "Created audio pad \"%s\"", name);
1352     g_free (name);
1353
1354     codec_tag = GST_TAG_AUDIO_CODEC;
1355
1356     switch (stream->fourcc) {
1357         /* Older RealAudio Codecs */
1358       case GST_RM_AUD_14_4:
1359         version = 1;
1360         break;
1361
1362       case GST_RM_AUD_28_8:
1363         version = 2;
1364         break;
1365
1366         /* DolbyNet (Dolby AC3, low bitrate) */
1367       case GST_RM_AUD_DNET:
1368         stream_caps =
1369             gst_caps_new_simple ("audio/x-ac3", "rate", G_TYPE_INT,
1370             (int) stream->rate, NULL);
1371         stream->needs_descrambling = TRUE;
1372         stream->subpackets_needed = 1;
1373         stream->subpackets = NULL;
1374         break;
1375
1376         /* MPEG-4 based */
1377       case GST_RM_AUD_RAAC:
1378       case GST_RM_AUD_RACP:
1379         stream_caps =
1380             gst_caps_new_simple ("audio/mpeg", "mpegversion", G_TYPE_INT,
1381             (int) 4, "framed", G_TYPE_BOOLEAN, TRUE, NULL);
1382         if (stream->extra_data_size > 0) {
1383           /* strip off an unknown byte in the extra data */
1384           stream->extra_data_size--;
1385           stream->extra_data++;
1386         }
1387         stream->needs_descrambling = TRUE;
1388         stream->subpackets_needed = 1;
1389         stream->subpackets = NULL;
1390         break;
1391
1392         /* Sony ATRAC3 */
1393       case GST_RM_AUD_ATRC:
1394         stream_caps = gst_caps_new_empty_simple ("audio/x-vnd.sony.atrac3");
1395         stream->needs_descrambling = TRUE;
1396         stream->subpackets_needed = stream->height;
1397         stream->subpackets = NULL;
1398         break;
1399
1400         /* RealAudio G2 audio */
1401       case GST_RM_AUD_COOK:
1402         version = 8;
1403         stream->needs_descrambling = TRUE;
1404         stream->subpackets_needed = stream->height;
1405         stream->subpackets = NULL;
1406         break;
1407
1408         /* RALF is lossless */
1409       case GST_RM_AUD_RALF:
1410         GST_DEBUG_OBJECT (rmdemux, "RALF");
1411         stream_caps = gst_caps_new_empty_simple ("audio/x-ralf-mpeg4-generic");
1412         break;
1413
1414       case GST_RM_AUD_SIPR:
1415
1416         if (stream->flavor > 3) {
1417           GST_WARNING_OBJECT (rmdemux, "bad SIPR flavor %d, freeing it",
1418               stream->flavor);
1419           g_free (stream);
1420           goto beach;
1421         }
1422
1423         GST_DEBUG_OBJECT (rmdemux, "SIPR");
1424         stream_caps = gst_caps_new_empty_simple ("audio/x-sipro");
1425         stream->needs_descrambling = TRUE;
1426         stream->subpackets_needed = stream->height;
1427         stream->subpackets = NULL;
1428         stream->leaf_size = sipr_subpk_size[stream->flavor];
1429
1430         break;
1431
1432       default:
1433         stream_caps = gst_caps_new_simple ("video/x-unknown-fourcc",
1434             "fourcc", G_TYPE_UINT, stream->fourcc, NULL);
1435         GST_WARNING_OBJECT (rmdemux,
1436             "Unknown audio FOURCC code \"%" GST_FOURCC_FORMAT "\" (%08x)",
1437             GST_FOURCC_ARGS (stream->fourcc), stream->fourcc);
1438         break;
1439     }
1440
1441     if (version) {
1442       stream_caps =
1443           gst_caps_new_simple ("audio/x-pn-realaudio", "raversion", G_TYPE_INT,
1444           (int) version, NULL);
1445     }
1446
1447     if (stream_caps) {
1448       gst_caps_set_simple (stream_caps,
1449           "flavor", G_TYPE_INT, (int) stream->flavor,
1450           "rate", G_TYPE_INT, (int) stream->rate,
1451           "channels", G_TYPE_INT, (int) stream->n_channels,
1452           "width", G_TYPE_INT, (int) stream->sample_width,
1453           "leaf_size", G_TYPE_INT, (int) stream->leaf_size,
1454           "packet_size", G_TYPE_INT, (int) stream->packet_size,
1455           "bitrate", G_TYPE_INT, (int) stream->bitrate,
1456           "height", G_TYPE_INT, (int) stream->height, NULL);
1457     }
1458     rmdemux->n_audio_streams++;
1459   } else {
1460     GST_WARNING_OBJECT (rmdemux, "not adding stream of type %d, freeing it",
1461         stream->subtype);
1462     g_free (stream);
1463     goto beach;
1464   }
1465
1466   GST_PAD_ELEMENT_PRIVATE (stream->pad) = stream;
1467   rmdemux->streams = g_slist_append (rmdemux->streams, stream);
1468   GST_LOG_OBJECT (rmdemux, "n_streams is now %d",
1469       g_slist_length (rmdemux->streams));
1470
1471   GST_LOG ("stream->pad = %p, stream_caps = %" GST_PTR_FORMAT, stream->pad,
1472       stream_caps);
1473
1474   if (stream->pad && stream_caps) {
1475     GstEvent *event;
1476
1477     GST_LOG_OBJECT (rmdemux, "%d bytes of extra data for stream %s",
1478         stream->extra_data_size, GST_PAD_NAME (stream->pad));
1479
1480     /* add codec_data if there is any */
1481     if (stream->extra_data_size > 0) {
1482       GstBuffer *buffer;
1483
1484       buffer = gst_buffer_new_and_alloc (stream->extra_data_size);
1485       gst_buffer_fill (buffer, 0, stream->extra_data, stream->extra_data_size);
1486
1487       gst_caps_set_simple (stream_caps, "codec_data", GST_TYPE_BUFFER,
1488           buffer, NULL);
1489
1490       gst_buffer_unref (buffer);
1491     }
1492
1493     gst_pad_use_fixed_caps (stream->pad);
1494
1495     gst_pad_set_event_function (stream->pad,
1496         GST_DEBUG_FUNCPTR (gst_rmdemux_src_event));
1497     gst_pad_set_query_function (stream->pad,
1498         GST_DEBUG_FUNCPTR (gst_rmdemux_src_query));
1499
1500     GST_DEBUG_OBJECT (rmdemux, "adding pad %s with caps %" GST_PTR_FORMAT
1501         ", stream_id=%d", GST_PAD_NAME (stream->pad), stream_caps, stream->id);
1502     gst_pad_set_active (stream->pad, TRUE);
1503
1504     stream_id =
1505         gst_pad_create_stream_id_printf (stream->pad,
1506         GST_ELEMENT_CAST (rmdemux), "%03u", stream->id);
1507
1508     event =
1509         gst_pad_get_sticky_event (rmdemux->sinkpad, GST_EVENT_STREAM_START, 0);
1510     if (event) {
1511       if (gst_event_parse_group_id (event, &rmdemux->group_id))
1512         rmdemux->have_group_id = TRUE;
1513       else
1514         rmdemux->have_group_id = FALSE;
1515       gst_event_unref (event);
1516     } else if (!rmdemux->have_group_id) {
1517       rmdemux->have_group_id = TRUE;
1518       rmdemux->group_id = gst_util_group_id_next ();
1519     }
1520
1521     event = gst_event_new_stream_start (stream_id);
1522     if (rmdemux->have_group_id)
1523       gst_event_set_group_id (event, rmdemux->group_id);
1524
1525     gst_pad_push_event (stream->pad, event);
1526     g_free (stream_id);
1527
1528     gst_pad_set_caps (stream->pad, stream_caps);
1529
1530     codec_name = gst_pb_utils_get_codec_description (stream_caps);
1531
1532     /* save for later, we must send the tags after the newsegment event */
1533     if (codec_tag != NULL && codec_name != NULL) {
1534       if (stream->pending_tags == NULL)
1535         stream->pending_tags = gst_tag_list_new_empty ();
1536       gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_KEEP,
1537           codec_tag, codec_name, NULL);
1538       g_free (codec_name);
1539     }
1540     gst_element_add_pad (GST_ELEMENT_CAST (rmdemux), stream->pad);
1541   }
1542
1543 beach:
1544
1545   if (stream_caps)
1546     gst_caps_unref (stream_caps);
1547 }
1548
1549 static int
1550 re_skip_pascal_string (const guint8 * ptr)
1551 {
1552   int length;
1553
1554   length = ptr[0];
1555
1556   return length + 1;
1557 }
1558
1559 static void
1560 gst_rmdemux_parse__rmf (GstRMDemux * rmdemux, const guint8 * data, int length)
1561 {
1562   GST_LOG_OBJECT (rmdemux, "file_version: %d", RMDEMUX_GUINT32_GET (data));
1563   GST_LOG_OBJECT (rmdemux, "num_headers: %d", RMDEMUX_GUINT32_GET (data + 4));
1564 }
1565
1566 static void
1567 gst_rmdemux_parse_prop (GstRMDemux * rmdemux, const guint8 * data, int length)
1568 {
1569   GST_LOG_OBJECT (rmdemux, "max bitrate: %d", RMDEMUX_GUINT32_GET (data));
1570   GST_LOG_OBJECT (rmdemux, "avg bitrate: %d", RMDEMUX_GUINT32_GET (data + 4));
1571   GST_LOG_OBJECT (rmdemux, "max packet size: %d",
1572       RMDEMUX_GUINT32_GET (data + 8));
1573   rmdemux->avg_packet_size = RMDEMUX_GUINT32_GET (data + 12);
1574   GST_LOG_OBJECT (rmdemux, "avg packet size: %d", rmdemux->avg_packet_size);
1575   rmdemux->num_packets = RMDEMUX_GUINT32_GET (data + 16);
1576   GST_LOG_OBJECT (rmdemux, "number of packets: %d", rmdemux->num_packets);
1577
1578   GST_LOG_OBJECT (rmdemux, "duration: %d", RMDEMUX_GUINT32_GET (data + 20));
1579   rmdemux->duration = RMDEMUX_GUINT32_GET (data + 20) * GST_MSECOND;
1580
1581   GST_LOG_OBJECT (rmdemux, "preroll: %d", RMDEMUX_GUINT32_GET (data + 24));
1582   rmdemux->index_offset = RMDEMUX_GUINT32_GET (data + 28);
1583   GST_LOG_OBJECT (rmdemux, "offset of INDX section: 0x%08x",
1584       rmdemux->index_offset);
1585   rmdemux->data_offset = RMDEMUX_GUINT32_GET (data + 32);
1586   GST_LOG_OBJECT (rmdemux, "offset of DATA section: 0x%08x",
1587       rmdemux->data_offset);
1588   GST_LOG_OBJECT (rmdemux, "n streams: %d", RMDEMUX_GUINT16_GET (data + 36));
1589   GST_LOG_OBJECT (rmdemux, "flags: 0x%04x", RMDEMUX_GUINT16_GET (data + 38));
1590 }
1591
1592 static void
1593 gst_rmdemux_parse_mdpr (GstRMDemux * rmdemux, const guint8 * data, int length)
1594 {
1595   GstRMDemuxStream *stream;
1596   char *stream1_type_string;
1597   char *stream2_type_string;
1598   guint str_len = 0;
1599   int stream_type;
1600   int offset;
1601   guint32 max_bitrate;
1602   guint32 avg_bitrate;
1603
1604   stream = g_new0 (GstRMDemuxStream, 1);
1605
1606   stream->id = RMDEMUX_GUINT16_GET (data);
1607   stream->index = NULL;
1608   stream->seek_offset = 0;
1609   stream->last_ts = -1;
1610   stream->next_ts = -1;
1611   stream->last_flow = GST_FLOW_OK;
1612   stream->discont = TRUE;
1613   stream->adapter = gst_adapter_new ();
1614   GST_LOG_OBJECT (rmdemux, "stream_number=%d", stream->id);
1615
1616   /* parse the bitrates */
1617   max_bitrate = RMDEMUX_GUINT32_GET (data + 2);
1618   avg_bitrate = RMDEMUX_GUINT32_GET (data + 6);
1619   stream->bitrate = avg_bitrate;
1620   GST_LOG_OBJECT (rmdemux, "Stream max bitrate=%u", max_bitrate);
1621   GST_LOG_OBJECT (rmdemux, "Stream avg bitrate=%u", avg_bitrate);
1622   if (max_bitrate != 0) {
1623     if (stream->pending_tags == NULL)
1624       stream->pending_tags = gst_tag_list_new_empty ();
1625     gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE,
1626         GST_TAG_MAXIMUM_BITRATE, max_bitrate, NULL);
1627   }
1628   if (avg_bitrate != 0) {
1629     if (stream->pending_tags == NULL)
1630       stream->pending_tags = gst_tag_list_new_empty ();
1631     gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE,
1632         GST_TAG_BITRATE, avg_bitrate, NULL);
1633   }
1634
1635   offset = 30;
1636   stream1_type_string = gst_rm_utils_read_string8 (data + offset,
1637       length - offset, &str_len);
1638   offset += str_len;
1639   stream2_type_string = gst_rm_utils_read_string8 (data + offset,
1640       length - offset, &str_len);
1641   offset += str_len;
1642
1643   /* stream1_type_string for audio and video stream is a "put_whatever_you_want" field :
1644    * observed values :
1645    * - "[The ]Video/Audio Stream" (File produced by an official Real encoder)
1646    * - "RealVideoPremierePlugIn-VIDEO/AUDIO" (File produced by Abobe Premiere)
1647    *
1648    * so, we should not rely on it to know which stream type it is
1649    */
1650
1651   GST_LOG_OBJECT (rmdemux, "stream type: %s", stream1_type_string);
1652   GST_LOG_OBJECT (rmdemux, "MIME type=%s", stream2_type_string);
1653
1654   if (strcmp (stream2_type_string, "video/x-pn-realvideo") == 0) {
1655     stream_type = GST_RMDEMUX_STREAM_VIDEO;
1656   } else if (strcmp (stream2_type_string,
1657           "video/x-pn-multirate-realvideo") == 0) {
1658     stream_type = GST_RMDEMUX_STREAM_VIDEO;
1659   } else if (strcmp (stream2_type_string, "audio/x-pn-realaudio") == 0) {
1660     stream_type = GST_RMDEMUX_STREAM_AUDIO;
1661   } else if (strcmp (stream2_type_string,
1662           "audio/x-pn-multirate-realaudio") == 0) {
1663     stream_type = GST_RMDEMUX_STREAM_AUDIO;
1664   } else if (strcmp (stream2_type_string,
1665           "audio/x-pn-multirate-realaudio-live") == 0) {
1666     stream_type = GST_RMDEMUX_STREAM_AUDIO;
1667   } else if (strcmp (stream2_type_string, "audio/x-ralf-mpeg4-generic") == 0) {
1668     /* Another audio type found in the real testsuite */
1669     stream_type = GST_RMDEMUX_STREAM_AUDIO;
1670   } else if (strcmp (stream1_type_string, "") == 0 &&
1671       strcmp (stream2_type_string, "logical-fileinfo") == 0) {
1672     stream_type = GST_RMDEMUX_STREAM_FILEINFO;
1673   } else {
1674     stream_type = GST_RMDEMUX_STREAM_UNKNOWN;
1675     GST_WARNING_OBJECT (rmdemux, "unknown stream type \"%s\",\"%s\"",
1676         stream1_type_string, stream2_type_string);
1677   }
1678   g_free (stream1_type_string);
1679   g_free (stream2_type_string);
1680
1681   offset += 4;
1682
1683   stream->subtype = stream_type;
1684   switch (stream_type) {
1685
1686     case GST_RMDEMUX_STREAM_VIDEO:
1687       /* RV10/RV20/RV30/RV40 => video/x-pn-realvideo, version=1,2,3,4 */
1688       stream->fourcc = RMDEMUX_FOURCC_GET (data + offset + 8);
1689       stream->width = RMDEMUX_GUINT16_GET (data + offset + 12);
1690       stream->height = RMDEMUX_GUINT16_GET (data + offset + 14);
1691       stream->rate = RMDEMUX_GUINT16_GET (data + offset + 16);
1692       stream->subformat = RMDEMUX_GUINT32_GET (data + offset + 26);
1693       stream->format = RMDEMUX_GUINT32_GET (data + offset + 30);
1694       stream->extra_data_size = length - (offset + 26);
1695       stream->extra_data = (guint8 *) data + offset + 26;
1696       /* Natural way to represent framerates here requires unsigned 32 bit
1697        * numerator, which we don't have. For the nasty case, approximate...
1698        */
1699       {
1700         guint32 numerator = RMDEMUX_GUINT16_GET (data + offset + 22) * 65536 +
1701             RMDEMUX_GUINT16_GET (data + offset + 24);
1702         if (numerator > G_MAXINT) {
1703           stream->framerate_numerator = (gint) (numerator >> 1);
1704           stream->framerate_denominator = 32768;
1705         } else {
1706           stream->framerate_numerator = (gint) numerator;
1707           stream->framerate_denominator = 65536;
1708         }
1709       }
1710
1711       GST_DEBUG_OBJECT (rmdemux,
1712           "Video stream with fourcc=%" GST_FOURCC_FORMAT
1713           " width=%d height=%d rate=%d framerate=%d/%d subformat=%x format=%x extra_data_size=%d",
1714           GST_FOURCC_ARGS (stream->fourcc), stream->width, stream->height,
1715           stream->rate, stream->framerate_numerator,
1716           stream->framerate_denominator, stream->subformat, stream->format,
1717           stream->extra_data_size);
1718       break;
1719     case GST_RMDEMUX_STREAM_AUDIO:{
1720       stream->version = RMDEMUX_GUINT16_GET (data + offset + 4);
1721       GST_INFO ("stream version = %u", stream->version);
1722       switch (stream->version) {
1723         case 3:
1724           stream->fourcc = GST_RM_AUD_14_4;
1725           stream->packet_size = 20;
1726           stream->rate = 8000;
1727           stream->n_channels = 1;
1728           stream->sample_width = 16;
1729           stream->flavor = 1;
1730           stream->leaf_size = 0;
1731           stream->height = 0;
1732           break;
1733         case 4:
1734           stream->flavor = RMDEMUX_GUINT16_GET (data + offset + 22);
1735           stream->packet_size = RMDEMUX_GUINT32_GET (data + offset + 24);
1736           /* stream->frame_size = RMDEMUX_GUINT32_GET (data + offset + 42); */
1737           stream->leaf_size = RMDEMUX_GUINT16_GET (data + offset + 44);
1738           stream->height = RMDEMUX_GUINT16_GET (data + offset + 40);
1739           stream->rate = RMDEMUX_GUINT16_GET (data + offset + 48);
1740           stream->sample_width = RMDEMUX_GUINT16_GET (data + offset + 52);
1741           stream->n_channels = RMDEMUX_GUINT16_GET (data + offset + 54);
1742           stream->fourcc = RMDEMUX_FOURCC_GET (data + offset + 62);
1743           stream->extra_data_size = RMDEMUX_GUINT32_GET (data + offset + 69);
1744           GST_DEBUG_OBJECT (rmdemux, "%u bytes of extra codec data",
1745               stream->extra_data_size);
1746           if (length - (offset + 73) >= stream->extra_data_size) {
1747             stream->extra_data = (guint8 *) data + offset + 73;
1748           } else {
1749             GST_WARNING_OBJECT (rmdemux, "codec data runs beyond MDPR chunk");
1750             stream->extra_data_size = 0;
1751           }
1752           break;
1753         case 5:
1754           stream->flavor = RMDEMUX_GUINT16_GET (data + offset + 22);
1755           stream->packet_size = RMDEMUX_GUINT32_GET (data + offset + 24);
1756           /* stream->frame_size = RMDEMUX_GUINT32_GET (data + offset + 42); */
1757           stream->leaf_size = RMDEMUX_GUINT16_GET (data + offset + 44);
1758           stream->height = RMDEMUX_GUINT16_GET (data + offset + 40);
1759           stream->rate = RMDEMUX_GUINT16_GET (data + offset + 54);
1760           stream->sample_width = RMDEMUX_GUINT16_GET (data + offset + 58);
1761           stream->n_channels = RMDEMUX_GUINT16_GET (data + offset + 60);
1762           stream->fourcc = RMDEMUX_FOURCC_GET (data + offset + 66);
1763           stream->extra_data_size = RMDEMUX_GUINT32_GET (data + offset + 74);
1764           GST_DEBUG_OBJECT (rmdemux, "%u bytes of extra codec data",
1765               stream->extra_data_size);
1766           if (length - (offset + 78) >= stream->extra_data_size) {
1767             stream->extra_data = (guint8 *) data + offset + 78;
1768           } else {
1769             GST_WARNING_OBJECT (rmdemux, "codec data runs beyond MDPR chunk");
1770             stream->extra_data_size = 0;
1771           }
1772           break;
1773         default:{
1774           GST_WARNING_OBJECT (rmdemux, "Unhandled audio stream version %d",
1775               stream->version);
1776           break;
1777         }
1778       }
1779       /*  14_4, 28_8, cook, dnet, sipr, raac, racp, ralf, atrc */
1780       GST_DEBUG_OBJECT (rmdemux,
1781           "Audio stream with rate=%d sample_width=%d n_channels=%d",
1782           stream->rate, stream->sample_width, stream->n_channels);
1783
1784       break;
1785     }
1786     case GST_RMDEMUX_STREAM_FILEINFO:
1787     {
1788       int element_nb;
1789
1790       /* Length of this section */
1791       GST_DEBUG_OBJECT (rmdemux, "length2: 0x%08x",
1792           RMDEMUX_GUINT32_GET (data + offset));
1793       offset += 4;
1794
1795       /* Unknown : 00 00 00 00 */
1796       offset += 4;
1797
1798       /* Number of variables that would follow (loop iterations) */
1799       element_nb = RMDEMUX_GUINT32_GET (data + offset);
1800       offset += 4;
1801
1802       while (element_nb) {
1803         /* Category Id : 00 00 00 XX 00 00 */
1804         offset += 6;
1805
1806         /* Variable Name */
1807         offset += re_skip_pascal_string (data + offset);
1808
1809         /* Variable Value Type */
1810         /*   00 00 00 00 00 => integer/boolean, preceded by length */
1811         /*   00 00 00 02 00 => pascal string, preceded by length, no trailing \0 */
1812         offset += 5;
1813
1814         /* Variable Value */
1815         offset += re_skip_pascal_string (data + offset);
1816
1817         element_nb--;
1818       }
1819     }
1820       break;
1821     case GST_RMDEMUX_STREAM_UNKNOWN:
1822     default:
1823       break;
1824   }
1825
1826   gst_rmdemux_add_stream (rmdemux, stream);
1827 }
1828
1829 static guint
1830 gst_rmdemux_parse_indx (GstRMDemux * rmdemux, const guint8 * data, int length)
1831 {
1832   int n;
1833   int id;
1834
1835   n = RMDEMUX_GUINT32_GET (data);
1836   id = RMDEMUX_GUINT16_GET (data + 4);
1837   rmdemux->index_offset = RMDEMUX_GUINT32_GET (data + 6);
1838
1839   GST_DEBUG_OBJECT (rmdemux, "Number of indices=%d Stream ID=%d length=%d", n,
1840       id, length);
1841
1842   /* Point to the next index_stream */
1843   rmdemux->index_stream = gst_rmdemux_get_stream_by_id (rmdemux, id);
1844
1845   /* Return the length of the index */
1846   return 14 * n;
1847 }
1848
1849 static void
1850 gst_rmdemux_parse_indx_data (GstRMDemux * rmdemux, const guint8 * data,
1851     int length)
1852 {
1853   int i;
1854   int n;
1855   GstRMDemuxIndex *index;
1856
1857   /* The number of index records */
1858   n = length / 14;
1859
1860   if (rmdemux->index_stream == NULL)
1861     return;
1862
1863   /* don't parse the index a second time when operating pull-based and
1864    * reaching the end of the file */
1865   if (rmdemux->index_stream->index_length > 0) {
1866     GST_DEBUG_OBJECT (rmdemux, "Already have an index for this stream");
1867     return;
1868   }
1869
1870   index = g_malloc (sizeof (GstRMDemuxIndex) * n);
1871   rmdemux->index_stream->index = index;
1872   rmdemux->index_stream->index_length = n;
1873
1874   for (i = 0; i < n; i++) {
1875     index[i].timestamp = RMDEMUX_GUINT32_GET (data + 2) * GST_MSECOND;
1876     index[i].offset = RMDEMUX_GUINT32_GET (data + 6);
1877
1878     GST_DEBUG_OBJECT (rmdemux, "Index found for timestamp=%f (at offset=%x)",
1879         gst_guint64_to_gdouble (index[i].timestamp) / GST_SECOND,
1880         index[i].offset);
1881     data += 14;
1882   }
1883 }
1884
1885 static void
1886 gst_rmdemux_parse_data (GstRMDemux * rmdemux, const guint8 * data, int length)
1887 {
1888   rmdemux->n_chunks = RMDEMUX_GUINT32_GET (data);
1889   rmdemux->data_offset = RMDEMUX_GUINT32_GET (data + 4);
1890   rmdemux->chunk_index = 0;
1891   GST_DEBUG_OBJECT (rmdemux, "Data chunk found with %d packets "
1892       "(next data at 0x%08x)", rmdemux->n_chunks, rmdemux->data_offset);
1893 }
1894
1895 static void
1896 gst_rmdemux_parse_cont (GstRMDemux * rmdemux, const guint8 * data, int length)
1897 {
1898   GstTagList *tags;
1899
1900   tags = gst_rm_utils_read_tags (data, length, gst_rm_utils_read_string16);
1901
1902   GST_LOG_OBJECT (rmdemux, "tags: %" GST_PTR_FORMAT, tags);
1903
1904   rmdemux->pending_tags =
1905       gst_tag_list_merge (rmdemux->pending_tags, tags, GST_TAG_MERGE_APPEND);
1906 }
1907
1908 static GstFlowReturn
1909 gst_rmdemux_combine_flows (GstRMDemux * rmdemux, GstRMDemuxStream * stream,
1910     GstFlowReturn ret)
1911 {
1912   GSList *cur;
1913
1914   /* store the value */
1915   stream->last_flow = ret;
1916
1917   /* if it's success we can return the value right away */
1918   if (ret == GST_FLOW_OK)
1919     goto done;
1920
1921   /* any other error that is not-linked can be returned right
1922    * away */
1923   if (ret != GST_FLOW_NOT_LINKED)
1924     goto done;
1925
1926   for (cur = rmdemux->streams; cur; cur = cur->next) {
1927     GstRMDemuxStream *ostream = cur->data;
1928
1929     ret = ostream->last_flow;
1930     /* some other return value (must be SUCCESS but we can return
1931      * other values as well) */
1932     if (ret != GST_FLOW_NOT_LINKED)
1933       goto done;
1934   }
1935   /* if we get here, all other pads were unlinked and we return
1936    * NOT_LINKED then */
1937 done:
1938   return ret;
1939 }
1940
1941 static void
1942 gst_rmdemux_stream_clear_cached_subpackets (GstRMDemux * rmdemux,
1943     GstRMDemuxStream * stream)
1944 {
1945   if (stream->subpackets == NULL || stream->subpackets->len == 0)
1946     return;
1947
1948   GST_DEBUG_OBJECT (rmdemux, "discarding %u previously collected subpackets",
1949       stream->subpackets->len);
1950   g_ptr_array_foreach (stream->subpackets, (GFunc) gst_mini_object_unref, NULL);
1951   g_ptr_array_set_size (stream->subpackets, 0);
1952 }
1953
1954 static GstFlowReturn
1955 gst_rmdemux_descramble_audio (GstRMDemux * rmdemux, GstRMDemuxStream * stream)
1956 {
1957   GstFlowReturn ret = GST_FLOW_ERROR;
1958   GstBuffer *outbuf;
1959   GstMapInfo outmap;
1960   guint packet_size = stream->packet_size;
1961   guint height = stream->subpackets->len;
1962   guint leaf_size = stream->leaf_size;
1963   guint p, x;
1964
1965   g_assert (stream->height == height);
1966
1967   GST_LOG ("packet_size = %u, leaf_size = %u, height= %u", packet_size,
1968       leaf_size, height);
1969
1970   outbuf = gst_buffer_new_and_alloc (height * packet_size);
1971   gst_buffer_map (outbuf, &outmap, GST_MAP_WRITE);
1972
1973   for (p = 0; p < height; ++p) {
1974     GstBuffer *b = g_ptr_array_index (stream->subpackets, p);
1975     GstMapInfo map;
1976
1977     gst_buffer_map (b, &map, GST_MAP_READ);
1978
1979     if (p == 0) {
1980       GST_BUFFER_PTS (outbuf) = GST_BUFFER_PTS (b);
1981       GST_BUFFER_DTS (outbuf) = GST_BUFFER_DTS (b);
1982     }
1983
1984     for (x = 0; x < packet_size / leaf_size; ++x) {
1985       guint idx;
1986
1987       idx = height * x + ((height + 1) / 2) * (p % 2) + (p / 2);
1988
1989       /* GST_LOG ("%3u => %3u", (height * p) + x, idx); */
1990       memcpy (outmap.data + leaf_size * idx, map.data + leaf_size * x,
1991           leaf_size);
1992     }
1993     gst_buffer_unmap (b, &map);
1994   }
1995   gst_buffer_unmap (outbuf, &outmap);
1996
1997   /* some decoders, such as realaudiodec, need to be fed in packet units */
1998   for (p = 0; p < height; ++p) {
1999     GstBuffer *subbuf;
2000
2001     subbuf =
2002         gst_buffer_copy_region (outbuf, GST_BUFFER_COPY_ALL, p * packet_size,
2003         packet_size);
2004
2005     GST_LOG_OBJECT (rmdemux, "pushing buffer dts %" GST_TIME_FORMAT ", pts %"
2006         GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_DTS (subbuf)),
2007         GST_TIME_ARGS (GST_BUFFER_PTS (subbuf)));
2008
2009     if (stream->discont) {
2010       GST_BUFFER_FLAG_SET (subbuf, GST_BUFFER_FLAG_DISCONT);
2011       stream->discont = FALSE;
2012     }
2013
2014     ret = gst_pad_push (stream->pad, subbuf);
2015     if (ret != GST_FLOW_OK)
2016       break;
2017   }
2018
2019   gst_buffer_unref (outbuf);
2020
2021   gst_rmdemux_stream_clear_cached_subpackets (rmdemux, stream);
2022
2023   return ret;
2024 }
2025
2026 static GstFlowReturn
2027 gst_rmdemux_descramble_dnet_audio (GstRMDemux * rmdemux,
2028     GstRMDemuxStream * stream)
2029 {
2030   GstBuffer *buf;
2031
2032   buf = g_ptr_array_index (stream->subpackets, 0);
2033   g_ptr_array_index (stream->subpackets, 0) = NULL;
2034   g_ptr_array_set_size (stream->subpackets, 0);
2035
2036   buf = gst_rm_utils_descramble_dnet_buffer (buf);
2037
2038   if (stream->discont) {
2039     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
2040     stream->discont = FALSE;
2041   }
2042   return gst_pad_push (stream->pad, buf);
2043 }
2044
2045 static GstFlowReturn
2046 gst_rmdemux_descramble_mp4a_audio (GstRMDemux * rmdemux,
2047     GstRMDemuxStream * stream)
2048 {
2049   GstFlowReturn res;
2050   GstBuffer *buf, *outbuf;
2051   guint frames, index, i;
2052   GstMapInfo map;
2053   GstClockTime timestamp;
2054
2055   res = GST_FLOW_OK;
2056
2057   buf = g_ptr_array_index (stream->subpackets, 0);
2058   g_ptr_array_index (stream->subpackets, 0) = NULL;
2059   g_ptr_array_set_size (stream->subpackets, 0);
2060
2061   gst_buffer_map (buf, &map, GST_MAP_READ);
2062   timestamp = GST_BUFFER_PTS (buf);
2063
2064   frames = (map.data[1] & 0xf0) >> 4;
2065   index = 2 * frames + 2;
2066
2067   for (i = 0; i < frames; i++) {
2068     guint len = (map.data[i * 2 + 2] << 8) | map.data[i * 2 + 3];
2069
2070     outbuf = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, index, len);
2071     if (i == 0) {
2072       GST_BUFFER_PTS (outbuf) = timestamp;
2073       GST_BUFFER_DTS (outbuf) = timestamp;
2074     }
2075
2076     index += len;
2077
2078     if (stream->discont) {
2079       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
2080       stream->discont = FALSE;
2081     }
2082     res = gst_pad_push (stream->pad, outbuf);
2083     if (res != GST_FLOW_OK)
2084       break;
2085   }
2086   gst_buffer_unmap (buf, &map);
2087   gst_buffer_unref (buf);
2088   return res;
2089 }
2090
2091 static GstFlowReturn
2092 gst_rmdemux_descramble_sipr_audio (GstRMDemux * rmdemux,
2093     GstRMDemuxStream * stream)
2094 {
2095   GstFlowReturn ret;
2096   GstBuffer *outbuf;
2097   GstMapInfo outmap;
2098   guint packet_size = stream->packet_size;
2099   guint height = stream->subpackets->len;
2100   guint p;
2101
2102   g_assert (stream->height == height);
2103
2104   GST_LOG ("packet_size = %u, leaf_size = %u, height= %u", packet_size,
2105       stream->leaf_size, height);
2106
2107   outbuf = gst_buffer_new_and_alloc (height * packet_size);
2108   gst_buffer_map (outbuf, &outmap, GST_MAP_WRITE);
2109
2110   for (p = 0; p < height; ++p) {
2111     GstBuffer *b = g_ptr_array_index (stream->subpackets, p);
2112
2113     if (p == 0) {
2114       GST_BUFFER_DTS (outbuf) = GST_BUFFER_DTS (b);
2115       GST_BUFFER_PTS (outbuf) = GST_BUFFER_PTS (b);
2116     }
2117
2118     gst_buffer_extract (b, 0, outmap.data + packet_size * p, packet_size);
2119   }
2120   gst_buffer_unmap (outbuf, &outmap);
2121
2122   GST_LOG_OBJECT (rmdemux, "pushing buffer dts %" GST_TIME_FORMAT ", pts %"
2123       GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
2124       GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
2125
2126   if (stream->discont) {
2127     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
2128     stream->discont = FALSE;
2129   }
2130
2131   outbuf = gst_rm_utils_descramble_sipr_buffer (outbuf);
2132
2133   ret = gst_pad_push (stream->pad, outbuf);
2134
2135   gst_rmdemux_stream_clear_cached_subpackets (rmdemux, stream);
2136
2137   return ret;
2138 }
2139
2140 static GstFlowReturn
2141 gst_rmdemux_handle_scrambled_packet (GstRMDemux * rmdemux,
2142     GstRMDemuxStream * stream, GstBuffer * buf, gboolean keyframe)
2143 {
2144   GstFlowReturn ret;
2145
2146   if (stream->subpackets == NULL)
2147     stream->subpackets = g_ptr_array_sized_new (stream->subpackets_needed);
2148
2149   GST_LOG ("Got subpacket %u/%u, len=%" G_GSIZE_FORMAT ", key=%d",
2150       stream->subpackets->len + 1, stream->subpackets_needed,
2151       gst_buffer_get_size (buf), keyframe);
2152
2153   if (keyframe && stream->subpackets->len > 0) {
2154     gst_rmdemux_stream_clear_cached_subpackets (rmdemux, stream);
2155   }
2156
2157   g_ptr_array_add (stream->subpackets, buf);
2158
2159   if (stream->subpackets->len < stream->subpackets_needed)
2160     return GST_FLOW_OK;
2161
2162   g_assert (stream->subpackets->len >= 1);
2163
2164   switch (stream->fourcc) {
2165     case GST_RM_AUD_DNET:
2166       ret = gst_rmdemux_descramble_dnet_audio (rmdemux, stream);
2167       break;
2168     case GST_RM_AUD_COOK:
2169     case GST_RM_AUD_ATRC:
2170       ret = gst_rmdemux_descramble_audio (rmdemux, stream);
2171       break;
2172     case GST_RM_AUD_RAAC:
2173     case GST_RM_AUD_RACP:
2174       ret = gst_rmdemux_descramble_mp4a_audio (rmdemux, stream);
2175       break;
2176     case GST_RM_AUD_SIPR:
2177       ret = gst_rmdemux_descramble_sipr_audio (rmdemux, stream);
2178       break;
2179     default:
2180       ret = GST_FLOW_ERROR;
2181       g_assert_not_reached ();
2182   }
2183
2184   return ret;
2185 }
2186
2187 #define PARSE_NUMBER(data, size, number, label) \
2188 G_STMT_START {                                  \
2189   if (size < 2)                                 \
2190     goto label;                                 \
2191   number = GST_READ_UINT16_BE (data);           \
2192   if (!(number & 0xc000)) {                     \
2193     if (size < 4)                               \
2194       goto label;                               \
2195     number = GST_READ_UINT32_BE (data);         \
2196     data += 4;                                  \
2197     size -= 4;                                  \
2198   } else {                                      \
2199     number &= 0x3fff;                           \
2200     data += 2;                                  \
2201     size -= 2;                                  \
2202   }                                             \
2203 } G_STMT_END
2204
2205 static GstFlowReturn
2206 gst_rmdemux_parse_video_packet (GstRMDemux * rmdemux, GstRMDemuxStream * stream,
2207     GstBuffer * in, guint offset, guint16 version,
2208     GstClockTime timestamp, gboolean key)
2209 {
2210   GstFlowReturn ret;
2211   GstMapInfo map;
2212   const guint8 *data;
2213   gsize size;
2214
2215   gst_buffer_map (in, &map, GST_MAP_READ);
2216
2217   data = map.data + offset;
2218   size = map.size - offset;
2219
2220   /* if size <= 2, we want this method to return the same GstFlowReturn as it
2221    * was previously for that given stream. */
2222   ret = stream->last_flow;
2223
2224   while (size > 2) {
2225     guint8 pkg_header;
2226     guint pkg_offset;
2227     guint pkg_length;
2228     guint pkg_subseq = 0, pkg_seqnum = G_MAXUINT;
2229     guint fragment_size;
2230     GstBuffer *fragment;
2231
2232     pkg_header = *data++;
2233     size--;
2234
2235     /* packet header
2236      * bit 7: 1=last block in block chain
2237      * bit 6: 1=short header (only one block?)
2238      */
2239     if ((pkg_header & 0xc0) == 0x40) {
2240       /* skip unknown byte */
2241       data++;
2242       size--;
2243       pkg_offset = 0;
2244       pkg_length = size;
2245     } else {
2246       if ((pkg_header & 0x40) == 0) {
2247         pkg_subseq = (*data++) & 0x7f;
2248         size--;
2249       } else {
2250         pkg_subseq = 0;
2251       }
2252
2253       /* length */
2254       PARSE_NUMBER (data, size, pkg_length, not_enough_data);
2255
2256       /* offset */
2257       PARSE_NUMBER (data, size, pkg_offset, not_enough_data);
2258
2259       /* seqnum */
2260       if (size < 1)
2261         goto not_enough_data;
2262
2263       pkg_seqnum = *data++;
2264       size--;
2265     }
2266
2267     GST_DEBUG_OBJECT (rmdemux,
2268         "seq %d, subseq %d, offset %d, length %d, size %" G_GSIZE_FORMAT
2269         ", header %02x", pkg_seqnum, pkg_subseq, pkg_offset, pkg_length, size,
2270         pkg_header);
2271
2272     /* calc size of fragment */
2273     if ((pkg_header & 0xc0) == 0x80) {
2274       fragment_size = pkg_offset;
2275     } else {
2276       if ((pkg_header & 0xc0) == 0)
2277         fragment_size = size;
2278       else
2279         fragment_size = pkg_length;
2280     }
2281     GST_DEBUG_OBJECT (rmdemux, "fragment size %d", fragment_size);
2282
2283     /* get the fragment */
2284     fragment =
2285         gst_buffer_copy_region (in, GST_BUFFER_COPY_ALL, data - map.data,
2286         fragment_size);
2287
2288     if (pkg_subseq == 1) {
2289       GST_DEBUG_OBJECT (rmdemux, "start new fragment");
2290       gst_adapter_clear (stream->adapter);
2291       stream->frag_current = 0;
2292       stream->frag_count = 0;
2293       stream->frag_length = pkg_length;
2294     } else if (pkg_subseq == 0) {
2295       GST_DEBUG_OBJECT (rmdemux, "non fragmented packet");
2296       stream->frag_current = 0;
2297       stream->frag_count = 0;
2298       stream->frag_length = fragment_size;
2299     }
2300
2301     /* put fragment in adapter */
2302     gst_adapter_push (stream->adapter, fragment);
2303     stream->frag_offset[stream->frag_count] = stream->frag_current;
2304     stream->frag_current += fragment_size;
2305     stream->frag_count++;
2306
2307     if (stream->frag_count > MAX_FRAGS)
2308       goto too_many_fragments;
2309
2310     GST_DEBUG_OBJECT (rmdemux, "stored fragment in adapter %d/%d",
2311         stream->frag_current, stream->frag_length);
2312
2313     /* flush fragment when complete */
2314     if (stream->frag_current >= stream->frag_length) {
2315       GstBuffer *out;
2316       GstMapInfo outmap;
2317       guint8 *outdata;
2318       guint header_size;
2319       gint i, avail;
2320
2321       /* calculate header size, which is:
2322        * 1 byte for the number of fragments - 1
2323        * for each fragment:
2324        *   4 bytes 0x00000001 little endian
2325        *   4 bytes fragment offset
2326        *
2327        * This is also the matroska header for realvideo, the decoder needs the
2328        * fragment offsets, both in ffmpeg and real .so, so we just give it that
2329        * in front of the data.
2330        */
2331       header_size = 1 + (8 * (stream->frag_count));
2332
2333       GST_DEBUG_OBJECT (rmdemux,
2334           "fragmented completed. count %d, header_size %u", stream->frag_count,
2335           header_size);
2336
2337       avail = gst_adapter_available (stream->adapter);
2338
2339       out = gst_buffer_new_and_alloc (header_size + avail);
2340       gst_buffer_map (out, &outmap, GST_MAP_WRITE);
2341       outdata = outmap.data;
2342
2343       /* create header */
2344       *outdata++ = stream->frag_count - 1;
2345       for (i = 0; i < stream->frag_count; i++) {
2346         GST_WRITE_UINT32_LE (outdata, 0x00000001);
2347         outdata += 4;
2348         GST_WRITE_UINT32_LE (outdata, stream->frag_offset[i]);
2349         outdata += 4;
2350       }
2351
2352       /* copy packet data after the header now */
2353       gst_adapter_copy (stream->adapter, outdata, 0, avail);
2354       gst_adapter_flush (stream->adapter, avail);
2355
2356       stream->frag_current = 0;
2357       stream->frag_count = 0;
2358       stream->frag_length = 0;
2359
2360       if (timestamp != -1) {
2361         if (rmdemux->first_ts != -1 && timestamp > rmdemux->first_ts)
2362           timestamp -= rmdemux->first_ts;
2363         else
2364           timestamp = 0;
2365
2366         if (rmdemux->base_ts != -1)
2367           timestamp += rmdemux->base_ts;
2368       }
2369       gst_buffer_unmap (out, &outmap);
2370
2371       /* video has DTS */
2372       GST_BUFFER_DTS (out) = timestamp;
2373       GST_BUFFER_PTS (out) = GST_CLOCK_TIME_NONE;
2374
2375       GST_LOG_OBJECT (rmdemux, "pushing timestamp %" GST_TIME_FORMAT,
2376           GST_TIME_ARGS (timestamp));
2377
2378       if (stream->discont) {
2379         GST_BUFFER_FLAG_SET (out, GST_BUFFER_FLAG_DISCONT);
2380         stream->discont = FALSE;
2381       }
2382
2383       if (!key) {
2384         GST_BUFFER_FLAG_SET (out, GST_BUFFER_FLAG_DELTA_UNIT);
2385       }
2386
2387       ret = gst_pad_push (stream->pad, out);
2388       ret = gst_rmdemux_combine_flows (rmdemux, stream, ret);
2389       if (ret != GST_FLOW_OK)
2390         break;
2391
2392       timestamp = GST_CLOCK_TIME_NONE;
2393     }
2394     data += fragment_size;
2395     size -= fragment_size;
2396   }
2397   GST_DEBUG_OBJECT (rmdemux, "%" G_GSIZE_FORMAT " bytes left", size);
2398
2399 done:
2400   gst_buffer_unmap (in, &map);
2401   gst_buffer_unref (in);
2402
2403   return ret;
2404
2405   /* ERRORS */
2406 not_enough_data:
2407   {
2408     GST_ELEMENT_WARNING (rmdemux, STREAM, DECODE, ("Skipping bad packet."),
2409         (NULL));
2410     ret = GST_FLOW_OK;
2411     goto done;
2412   }
2413 too_many_fragments:
2414   {
2415     GST_ELEMENT_ERROR (rmdemux, STREAM, DECODE,
2416         ("Got more fragments (%u) than can be handled (%u)",
2417             stream->frag_count, MAX_FRAGS), (NULL));
2418     ret = GST_FLOW_ERROR;
2419     goto done;
2420   }
2421 }
2422
2423 static GstFlowReturn
2424 gst_rmdemux_parse_audio_packet (GstRMDemux * rmdemux, GstRMDemuxStream * stream,
2425     GstBuffer * in, guint offset, guint16 version,
2426     GstClockTime timestamp, gboolean key)
2427 {
2428   GstFlowReturn ret;
2429   GstBuffer *buffer;
2430
2431   buffer = gst_buffer_copy_region (in, GST_BUFFER_COPY_MEMORY, offset, -1);
2432
2433   if (rmdemux->first_ts != -1 && timestamp > rmdemux->first_ts)
2434     timestamp -= rmdemux->first_ts;
2435   else
2436     timestamp = 0;
2437
2438   if (rmdemux->base_ts != -1)
2439     timestamp += rmdemux->base_ts;
2440
2441   GST_BUFFER_PTS (buffer) = timestamp;
2442   GST_BUFFER_DTS (buffer) = timestamp;
2443
2444   if (stream->needs_descrambling) {
2445     GST_LOG_OBJECT (rmdemux, "descramble timestamp %" GST_TIME_FORMAT,
2446         GST_TIME_ARGS (timestamp));
2447     ret = gst_rmdemux_handle_scrambled_packet (rmdemux, stream, buffer, key);
2448   } else {
2449     GST_LOG_OBJECT (rmdemux,
2450         "Pushing buffer of size %" G_GSIZE_FORMAT ", timestamp %"
2451         GST_TIME_FORMAT "to pad %s", gst_buffer_get_size (buffer),
2452         GST_TIME_ARGS (timestamp), GST_PAD_NAME (stream->pad));
2453
2454     if (stream->discont) {
2455       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2456       stream->discont = FALSE;
2457     }
2458     ret = gst_pad_push (stream->pad, buffer);
2459   }
2460
2461   gst_buffer_unref (in);
2462
2463   return ret;
2464 }
2465
2466 static GstFlowReturn
2467 gst_rmdemux_parse_packet (GstRMDemux * rmdemux, GstBuffer * in, guint16 version)
2468 {
2469   guint16 id;
2470   GstRMDemuxStream *stream;
2471   gsize size, offset;
2472   GstFlowReturn cret, ret;
2473   GstClockTime timestamp;
2474   gboolean key;
2475   GstMapInfo map;
2476   guint8 *data;
2477   guint8 flags;
2478   guint32 ts;
2479
2480   gst_buffer_map (in, &map, GST_MAP_READ);
2481   data = map.data;
2482   size = map.size;
2483
2484   /* stream number */
2485   id = RMDEMUX_GUINT16_GET (data);
2486
2487   stream = gst_rmdemux_get_stream_by_id (rmdemux, id);
2488   if (!stream || !stream->pad)
2489     goto unknown_stream;
2490
2491   /* timestamp in Msec */
2492   ts = RMDEMUX_GUINT32_GET (data + 2);
2493   timestamp = ts * GST_MSECOND;
2494
2495   rmdemux->segment.position = timestamp;
2496
2497   GST_LOG_OBJECT (rmdemux, "Parsing a packet for stream=%d, timestamp=%"
2498       GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT ", version=%d, ts=%u", id,
2499       GST_TIME_ARGS (timestamp), size, version, ts);
2500
2501   if (rmdemux->first_ts == GST_CLOCK_TIME_NONE) {
2502     GST_DEBUG_OBJECT (rmdemux, "First timestamp: %" GST_TIME_FORMAT,
2503         GST_TIME_ARGS (timestamp));
2504     rmdemux->first_ts = timestamp;
2505   }
2506
2507   /* skip stream_id and timestamp */
2508   data += (2 + 4);
2509   size -= (2 + 4);
2510
2511   /* get flags */
2512   flags = GST_READ_UINT8 (data + 1);
2513
2514   data += 2;
2515   size -= 2;
2516
2517   /* version 1 has an extra byte */
2518   if (version == 1) {
2519     data += 1;
2520     size -= 1;
2521   }
2522   offset = data - map.data;
2523   gst_buffer_unmap (in, &map);
2524
2525   key = (flags & 0x02) != 0;
2526   GST_DEBUG_OBJECT (rmdemux, "flags %d, Keyframe %d", flags, key);
2527
2528   if (rmdemux->need_newsegment) {
2529     GstEvent *event;
2530
2531     event = gst_event_new_segment (&rmdemux->segment);
2532
2533     GST_DEBUG_OBJECT (rmdemux, "sending NEWSEGMENT event, segment.start= %"
2534         GST_TIME_FORMAT, GST_TIME_ARGS (rmdemux->segment.start));
2535
2536     gst_rmdemux_send_event (rmdemux, event);
2537     rmdemux->need_newsegment = FALSE;
2538
2539     if (rmdemux->pending_tags != NULL) {
2540       gst_rmdemux_send_event (rmdemux,
2541           gst_event_new_tag (rmdemux->pending_tags));
2542       rmdemux->pending_tags = NULL;
2543     }
2544   }
2545
2546   if (stream->pending_tags != NULL) {
2547     GST_LOG_OBJECT (stream->pad, "tags %" GST_PTR_FORMAT, stream->pending_tags);
2548     gst_pad_push_event (stream->pad, gst_event_new_tag (stream->pending_tags));
2549     stream->pending_tags = NULL;
2550   }
2551
2552   if ((rmdemux->offset + size) <= stream->seek_offset) {
2553     GST_DEBUG_OBJECT (rmdemux,
2554         "Stream %d is skipping: seek_offset=%d, offset=%d, size=%"
2555         G_GSIZE_FORMAT, stream->id, stream->seek_offset, rmdemux->offset, size);
2556     cret = GST_FLOW_OK;
2557     gst_buffer_unref (in);
2558     goto beach;
2559   }
2560
2561   /* do special headers */
2562   if (stream->subtype == GST_RMDEMUX_STREAM_VIDEO) {
2563     ret =
2564         gst_rmdemux_parse_video_packet (rmdemux, stream, in, offset,
2565         version, timestamp, key);
2566   } else if (stream->subtype == GST_RMDEMUX_STREAM_AUDIO) {
2567     ret =
2568         gst_rmdemux_parse_audio_packet (rmdemux, stream, in, offset,
2569         version, timestamp, key);
2570   } else {
2571     gst_buffer_unref (in);
2572     ret = GST_FLOW_OK;
2573   }
2574
2575   cret = gst_rmdemux_combine_flows (rmdemux, stream, ret);
2576
2577 beach:
2578   return cret;
2579
2580   /* ERRORS */
2581 unknown_stream:
2582   {
2583     GST_WARNING_OBJECT (rmdemux, "No stream for stream id %d in parsing "
2584         "data packet", id);
2585     gst_buffer_unmap (in, &map);
2586     gst_buffer_unref (in);
2587     return GST_FLOW_OK;
2588   }
2589 }
2590
2591 gboolean
2592 gst_rmdemux_plugin_init (GstPlugin * plugin)
2593 {
2594   return gst_element_register (plugin, "rmdemux",
2595       GST_RANK_PRIMARY, GST_TYPE_RMDEMUX);
2596 }