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