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