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