3d300e7a33b657ccf391eae50be1fa233b630fa3
[platform/upstream/gstreamer.git] / ext / libav / gstavdemux.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>,
3  *               <2006> Edward Hervey <bilboed@bilboed.com>
4  *               <2006> Wim Taymans <wim@fluendo.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <string.h>
27
28 #include <libavformat/avformat.h>
29 /* #include <ffmpeg/avi.h> */
30 #include <gst/gst.h>
31 #include <gst/base/gstflowcombiner.h>
32
33 #include "gstav.h"
34 #include "gstavcodecmap.h"
35 #include "gstavutils.h"
36 #include "gstavprotocol.h"
37
38 #define MAX_STREAMS 20
39
40 typedef struct _GstFFMpegDemux GstFFMpegDemux;
41 typedef struct _GstFFStream GstFFStream;
42
43 struct _GstFFStream
44 {
45   GstPad *pad;
46
47   AVStream *avstream;
48
49   gboolean unknown;
50   GstClockTime last_ts;
51   gboolean discont;
52   gboolean eos;
53
54   GstTagList *tags;             /* stream tags */
55 };
56
57 struct _GstFFMpegDemux
58 {
59   GstElement element;
60
61   /* We need to keep track of our pads, so we do so here. */
62   GstPad *sinkpad;
63
64   gboolean have_group_id;
65   guint group_id;
66
67   AVFormatContext *context;
68   gboolean opened;
69
70   GstFFStream *streams[MAX_STREAMS];
71
72   GstFlowCombiner *flowcombiner;
73
74   gint videopads, audiopads;
75
76   GstClockTime start_time;
77   GstClockTime duration;
78
79   /* TRUE if working in pull-mode */
80   gboolean seekable;
81
82   /* TRUE if the avformat demuxer can reliably handle streaming mode */
83   gboolean can_push;
84
85   gboolean flushing;
86
87   /* segment stuff */
88   GstSegment segment;
89
90   /* cached seek in READY */
91   GstEvent *seek_event;
92
93   /* cached upstream events */
94   GList *cached_events;
95
96   /* push mode data */
97   GstFFMpegPipe ffpipe;
98   GstTask *task;
99   GRecMutex task_lock;
100 };
101
102 typedef struct _GstFFMpegDemuxClass GstFFMpegDemuxClass;
103
104 struct _GstFFMpegDemuxClass
105 {
106   GstElementClass parent_class;
107
108   AVInputFormat *in_plugin;
109   GstPadTemplate *sinktempl;
110   GstPadTemplate *videosrctempl;
111   GstPadTemplate *audiosrctempl;
112 };
113
114 /* A number of function prototypes are given so we can refer to them later. */
115 static void gst_ffmpegdemux_class_init (GstFFMpegDemuxClass * klass);
116 static void gst_ffmpegdemux_base_init (GstFFMpegDemuxClass * klass);
117 static void gst_ffmpegdemux_init (GstFFMpegDemux * demux);
118 static void gst_ffmpegdemux_finalize (GObject * object);
119
120 static gboolean gst_ffmpegdemux_sink_event (GstPad * sinkpad,
121     GstObject * parent, GstEvent * event);
122 static GstFlowReturn gst_ffmpegdemux_chain (GstPad * sinkpad,
123     GstObject * parent, GstBuffer * buf);
124
125 static void gst_ffmpegdemux_loop (GstFFMpegDemux * demux);
126 static gboolean gst_ffmpegdemux_sink_activate (GstPad * sinkpad,
127     GstObject * parent);
128 static gboolean gst_ffmpegdemux_sink_activate_mode (GstPad * sinkpad,
129     GstObject * parent, GstPadMode mode, gboolean active);
130
131 #if 0
132 static gboolean
133 gst_ffmpegdemux_src_convert (GstPad * pad,
134     GstFormat src_fmt,
135     gint64 src_value, GstFormat * dest_fmt, gint64 * dest_value);
136 #endif
137 static gboolean
138 gst_ffmpegdemux_send_event (GstElement * element, GstEvent * event);
139 static GstStateChangeReturn
140 gst_ffmpegdemux_change_state (GstElement * element, GstStateChange transition);
141
142 #define GST_FFDEMUX_PARAMS_QDATA g_quark_from_static_string("avdemux-params")
143
144 static GstElementClass *parent_class = NULL;
145
146 static const gchar *
147 gst_ffmpegdemux_averror (gint av_errno)
148 {
149   const gchar *message = NULL;
150
151   switch (av_errno) {
152     case AVERROR (EINVAL):
153       message = "Unknown error";
154       break;
155     case AVERROR (EIO):
156       message = "Input/output error";
157       break;
158     case AVERROR (EDOM):
159       message = "Number syntax expected in filename";
160       break;
161     case AVERROR (ENOMEM):
162       message = "Not enough memory";
163       break;
164     case AVERROR (EILSEQ):
165       message = "Unknown format";
166       break;
167     case AVERROR (ENOSYS):
168       message = "Operation not supported";
169       break;
170     default:
171       message = "Unhandled error code received";
172       break;
173   }
174
175   return message;
176 }
177
178 static void
179 gst_ffmpegdemux_base_init (GstFFMpegDemuxClass * klass)
180 {
181   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
182   AVInputFormat *in_plugin;
183   gchar *p, *name;
184   GstCaps *sinkcaps;
185   GstPadTemplate *sinktempl, *audiosrctempl, *videosrctempl;
186   gchar *longname, *description;
187
188   in_plugin = (AVInputFormat *)
189       g_type_get_qdata (G_OBJECT_CLASS_TYPE (klass), GST_FFDEMUX_PARAMS_QDATA);
190   g_assert (in_plugin != NULL);
191
192   p = name = g_strdup (in_plugin->name);
193   while (*p) {
194     if (*p == '.' || *p == ',')
195       *p = '_';
196     p++;
197   }
198
199   /* construct the element details struct */
200   longname = g_strdup_printf ("libav %s demuxer", in_plugin->long_name);
201   description = g_strdup_printf ("libav %s demuxer", in_plugin->long_name);
202   gst_element_class_set_metadata (element_class, longname,
203       "Codec/Demuxer", description,
204       "Wim Taymans <wim@fluendo.com>, "
205       "Ronald Bultje <rbultje@ronald.bitfreak.net>, "
206       "Edward Hervey <bilboed@bilboed.com>");
207   g_free (longname);
208   g_free (description);
209
210   /* pad templates */
211   sinkcaps = gst_ffmpeg_formatid_to_caps (name);
212   sinktempl = gst_pad_template_new ("sink",
213       GST_PAD_SINK, GST_PAD_ALWAYS, sinkcaps);
214   videosrctempl = gst_pad_template_new ("video_%u",
215       GST_PAD_SRC, GST_PAD_SOMETIMES, GST_CAPS_ANY);
216   audiosrctempl = gst_pad_template_new ("audio_%u",
217       GST_PAD_SRC, GST_PAD_SOMETIMES, GST_CAPS_ANY);
218
219   gst_element_class_add_pad_template (element_class, videosrctempl);
220   gst_element_class_add_pad_template (element_class, audiosrctempl);
221   gst_element_class_add_pad_template (element_class, sinktempl);
222
223   klass->in_plugin = in_plugin;
224   klass->videosrctempl = videosrctempl;
225   klass->audiosrctempl = audiosrctempl;
226   klass->sinktempl = sinktempl;
227 }
228
229 static void
230 gst_ffmpegdemux_class_init (GstFFMpegDemuxClass * klass)
231 {
232   GObjectClass *gobject_class;
233   GstElementClass *gstelement_class;
234
235   gobject_class = (GObjectClass *) klass;
236   gstelement_class = (GstElementClass *) klass;
237
238   parent_class = g_type_class_peek_parent (klass);
239
240   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_ffmpegdemux_finalize);
241
242   gstelement_class->change_state = gst_ffmpegdemux_change_state;
243   gstelement_class->send_event = gst_ffmpegdemux_send_event;
244 }
245
246 static void
247 gst_ffmpegdemux_init (GstFFMpegDemux * demux)
248 {
249   GstFFMpegDemuxClass *oclass =
250       (GstFFMpegDemuxClass *) (G_OBJECT_GET_CLASS (demux));
251   gint n;
252
253   demux->sinkpad = gst_pad_new_from_template (oclass->sinktempl, "sink");
254   gst_pad_set_activate_function (demux->sinkpad,
255       GST_DEBUG_FUNCPTR (gst_ffmpegdemux_sink_activate));
256   gst_pad_set_activatemode_function (demux->sinkpad,
257       GST_DEBUG_FUNCPTR (gst_ffmpegdemux_sink_activate_mode));
258   gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);
259
260   /* push based setup */
261   /* the following are not used in pull-based mode, so safe to set anyway */
262   gst_pad_set_event_function (demux->sinkpad,
263       GST_DEBUG_FUNCPTR (gst_ffmpegdemux_sink_event));
264   gst_pad_set_chain_function (demux->sinkpad,
265       GST_DEBUG_FUNCPTR (gst_ffmpegdemux_chain));
266   /* task for driving ffmpeg in loop function */
267   demux->task =
268       gst_task_new ((GstTaskFunction) gst_ffmpegdemux_loop, demux, NULL);
269   g_rec_mutex_init (&demux->task_lock);
270   gst_task_set_lock (demux->task, &demux->task_lock);
271
272   demux->have_group_id = FALSE;
273   demux->group_id = G_MAXUINT;
274
275   demux->opened = FALSE;
276   demux->context = NULL;
277
278   for (n = 0; n < MAX_STREAMS; n++) {
279     demux->streams[n] = NULL;
280   }
281   demux->videopads = 0;
282   demux->audiopads = 0;
283
284   demux->seek_event = NULL;
285   gst_segment_init (&demux->segment, GST_FORMAT_TIME);
286
287   demux->flowcombiner = gst_flow_combiner_new ();
288
289   /* push based data */
290   g_mutex_init (&demux->ffpipe.tlock);
291   g_cond_init (&demux->ffpipe.cond);
292   demux->ffpipe.adapter = gst_adapter_new ();
293
294   /* blacklist unreliable push-based demuxers */
295   if (strcmp (oclass->in_plugin->name, "ape"))
296     demux->can_push = TRUE;
297   else
298     demux->can_push = FALSE;
299 }
300
301 static void
302 gst_ffmpegdemux_finalize (GObject * object)
303 {
304   GstFFMpegDemux *demux;
305
306   demux = (GstFFMpegDemux *) object;
307
308   gst_flow_combiner_free (demux->flowcombiner);
309
310   g_mutex_clear (&demux->ffpipe.tlock);
311   g_cond_clear (&demux->ffpipe.cond);
312   gst_object_unref (demux->ffpipe.adapter);
313
314   gst_object_unref (demux->task);
315   g_rec_mutex_clear (&demux->task_lock);
316
317   G_OBJECT_CLASS (parent_class)->finalize (object);
318 }
319
320 static void
321 gst_ffmpegdemux_close (GstFFMpegDemux * demux)
322 {
323   gint n;
324   GstEvent **event_p;
325
326   if (!demux->opened)
327     return;
328
329   /* remove pads from ourselves */
330   for (n = 0; n < MAX_STREAMS; n++) {
331     GstFFStream *stream;
332
333     stream = demux->streams[n];
334     if (stream) {
335       if (stream->pad) {
336         gst_flow_combiner_remove_pad (demux->flowcombiner, stream->pad);
337         gst_element_remove_pad (GST_ELEMENT (demux), stream->pad);
338       }
339       if (stream->tags)
340         gst_tag_list_unref (stream->tags);
341       g_free (stream);
342     }
343     demux->streams[n] = NULL;
344   }
345   demux->videopads = 0;
346   demux->audiopads = 0;
347
348   /* close demuxer context from ffmpeg */
349   if (demux->seekable)
350     gst_ffmpegdata_close (demux->context->pb);
351   else
352     gst_ffmpeg_pipe_close (demux->context->pb);
353   demux->context->pb = NULL;
354   avformat_close_input (&demux->context);
355   if (demux->context)
356     avformat_free_context (demux->context);
357   demux->context = NULL;
358
359   GST_OBJECT_LOCK (demux);
360   demux->opened = FALSE;
361   event_p = &demux->seek_event;
362   gst_event_replace (event_p, NULL);
363   GST_OBJECT_UNLOCK (demux);
364
365   gst_segment_init (&demux->segment, GST_FORMAT_TIME);
366 }
367
368 /* send an event to all the source pads .
369  * Takes ownership of the event.
370  *
371  * Returns FALSE if none of the source pads handled the event.
372  */
373 static gboolean
374 gst_ffmpegdemux_push_event (GstFFMpegDemux * demux, GstEvent * event)
375 {
376   gboolean res;
377   gint n;
378
379   res = TRUE;
380
381   for (n = 0; n < MAX_STREAMS; n++) {
382     GstFFStream *s = demux->streams[n];
383
384     if (s && s->pad) {
385       gst_event_ref (event);
386       res &= gst_pad_push_event (s->pad, event);
387     }
388   }
389   gst_event_unref (event);
390
391   return res;
392 }
393
394 /* set flags on all streams */
395 static void
396 gst_ffmpegdemux_set_flags (GstFFMpegDemux * demux, gboolean discont,
397     gboolean eos)
398 {
399   GstFFStream *s;
400   gint n;
401
402   for (n = 0; n < MAX_STREAMS; n++) {
403     if ((s = demux->streams[n])) {
404       s->discont = discont;
405       s->eos = eos;
406     }
407   }
408 }
409
410 /* check if all streams are eos */
411 static gboolean
412 gst_ffmpegdemux_is_eos (GstFFMpegDemux * demux)
413 {
414   GstFFStream *s;
415   gint n;
416
417   for (n = 0; n < MAX_STREAMS; n++) {
418     if ((s = demux->streams[n])) {
419       GST_DEBUG ("stream %d %p eos:%d", n, s, s->eos);
420       if (!s->eos)
421         return FALSE;
422     }
423   }
424   return TRUE;
425 }
426
427 /* Returns True if we at least outputted one buffer */
428 static gboolean
429 gst_ffmpegdemux_has_outputted (GstFFMpegDemux * demux)
430 {
431   GstFFStream *s;
432   gint n;
433
434   for (n = 0; n < MAX_STREAMS; n++) {
435     if ((s = demux->streams[n])) {
436       if (GST_CLOCK_TIME_IS_VALID (s->last_ts))
437         return TRUE;
438     }
439   }
440   return FALSE;
441 }
442
443 static gboolean
444 gst_ffmpegdemux_do_seek (GstFFMpegDemux * demux, GstSegment * segment)
445 {
446   gboolean ret;
447   gint seekret;
448   gint64 target;
449   gint64 fftarget;
450   AVStream *stream;
451   gint index;
452
453   /* find default index and fail if none is present */
454   index = av_find_default_stream_index (demux->context);
455   GST_LOG_OBJECT (demux, "default stream index %d", index);
456   if (index < 0)
457     return FALSE;
458
459   ret = TRUE;
460
461   /* get the stream for seeking */
462   stream = demux->context->streams[index];
463   /* initial seek position */
464   target = segment->position;
465   /* convert target to ffmpeg time */
466   fftarget = gst_ffmpeg_time_gst_to_ff (target, stream->time_base);
467
468   GST_LOG_OBJECT (demux, "do seek to time %" GST_TIME_FORMAT,
469       GST_TIME_ARGS (target));
470
471   /* if we need to land on a keyframe, try to do so, we don't try to do a 
472    * keyframe seek if we are not absolutely sure we have an index.*/
473   if (segment->flags & GST_SEEK_FLAG_KEY_UNIT) {
474     gint keyframeidx;
475
476     GST_LOG_OBJECT (demux, "looking for keyframe in ffmpeg for time %"
477         GST_TIME_FORMAT, GST_TIME_ARGS (target));
478
479     /* search in the index for the previous keyframe */
480     keyframeidx =
481         av_index_search_timestamp (stream, fftarget, AVSEEK_FLAG_BACKWARD);
482
483     GST_LOG_OBJECT (demux, "keyframeidx: %d", keyframeidx);
484
485     if (keyframeidx >= 0) {
486       fftarget = stream->index_entries[keyframeidx].timestamp;
487       target = gst_ffmpeg_time_ff_to_gst (fftarget, stream->time_base);
488
489       GST_LOG_OBJECT (demux,
490           "Found a keyframe at ffmpeg idx: %d timestamp :%" GST_TIME_FORMAT,
491           keyframeidx, GST_TIME_ARGS (target));
492     }
493   }
494
495   GST_DEBUG_OBJECT (demux,
496       "About to call av_seek_frame (context, %d, %" G_GINT64_FORMAT
497       ", 0) for time %" GST_TIME_FORMAT, index, fftarget,
498       GST_TIME_ARGS (target));
499
500   if ((seekret =
501           av_seek_frame (demux->context, index, fftarget,
502               AVSEEK_FLAG_BACKWARD)) < 0)
503     goto seek_failed;
504
505   GST_DEBUG_OBJECT (demux, "seek success, returned %d", seekret);
506
507   segment->position = target;
508   segment->time = target;
509   segment->start = target;
510
511   return ret;
512
513   /* ERRORS */
514 seek_failed:
515   {
516     GST_WARNING_OBJECT (demux, "Call to av_seek_frame failed : %d", seekret);
517     return FALSE;
518   }
519 }
520
521 static gboolean
522 gst_ffmpegdemux_perform_seek (GstFFMpegDemux * demux, GstEvent * event)
523 {
524   gboolean res;
525   gdouble rate;
526   GstFormat format;
527   GstSeekFlags flags;
528   GstSeekType cur_type, stop_type;
529   gint64 cur, stop;
530   gboolean flush;
531   gboolean update;
532   GstSegment seeksegment;
533
534   if (!demux->seekable) {
535     GST_DEBUG_OBJECT (demux, "in push mode; ignoring seek");
536     return FALSE;
537   }
538
539   GST_DEBUG_OBJECT (demux, "starting seek");
540
541   if (event) {
542     gst_event_parse_seek (event, &rate, &format, &flags,
543         &cur_type, &cur, &stop_type, &stop);
544
545     /* we have to have a format as the segment format. Try to convert
546      * if not. */
547     if (demux->segment.format != format) {
548       GstFormat fmt;
549
550       fmt = demux->segment.format;
551       res = TRUE;
552       /* FIXME, use source pad */
553       if (cur_type != GST_SEEK_TYPE_NONE && cur != -1)
554         res = gst_pad_query_convert (demux->sinkpad, format, cur, fmt, &cur);
555       if (res && stop_type != GST_SEEK_TYPE_NONE && stop != -1)
556         res = gst_pad_query_convert (demux->sinkpad, format, stop, fmt, &stop);
557       if (!res)
558         goto no_format;
559
560       format = fmt;
561     }
562   } else {
563     flags = 0;
564   }
565
566   flush = flags & GST_SEEK_FLAG_FLUSH;
567
568   /* send flush start */
569   if (flush) {
570     /* mark flushing so that the streaming thread can react on it */
571     GST_OBJECT_LOCK (demux);
572     demux->flushing = TRUE;
573     GST_OBJECT_UNLOCK (demux);
574     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_start ());
575     gst_ffmpegdemux_push_event (demux, gst_event_new_flush_start ());
576   } else {
577     gst_pad_pause_task (demux->sinkpad);
578   }
579
580   /* grab streaming lock, this should eventually be possible, either
581    * because the task is paused or our streaming thread stopped
582    * because our peer is flushing. */
583   GST_PAD_STREAM_LOCK (demux->sinkpad);
584
585   /* make copy into temp structure, we can only update the main one
586    * when we actually could do the seek. */
587   memcpy (&seeksegment, &demux->segment, sizeof (GstSegment));
588
589   /* now configure the seek segment */
590   if (event) {
591     gst_segment_do_seek (&seeksegment, rate, format, flags,
592         cur_type, cur, stop_type, stop, &update);
593   }
594
595   GST_DEBUG_OBJECT (demux, "segment configured from %" G_GINT64_FORMAT
596       " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
597       seeksegment.start, seeksegment.stop, seeksegment.position);
598
599   /* make the sinkpad available for data passing since we might need
600    * it when doing the seek */
601   if (flush) {
602     GST_OBJECT_LOCK (demux);
603     demux->flushing = FALSE;
604     GST_OBJECT_UNLOCK (demux);
605     gst_pad_push_event (demux->sinkpad, gst_event_new_flush_stop (TRUE));
606   }
607
608   /* do the seek, segment.position contains new position. */
609   res = gst_ffmpegdemux_do_seek (demux, &seeksegment);
610
611   /* and prepare to continue streaming */
612   if (flush) {
613     /* send flush stop, peer will accept data and events again. We
614      * are not yet providing data as we still have the STREAM_LOCK. */
615     gst_ffmpegdemux_push_event (demux, gst_event_new_flush_stop (TRUE));
616   }
617   /* if successfull seek, we update our real segment and push
618    * out the new segment. */
619   if (res) {
620     memcpy (&demux->segment, &seeksegment, sizeof (GstSegment));
621
622     if (demux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
623       gst_element_post_message (GST_ELEMENT (demux),
624           gst_message_new_segment_start (GST_OBJECT (demux),
625               demux->segment.format, demux->segment.position));
626     }
627
628     /* now send the newsegment, FIXME, do this from the streaming thread */
629     GST_DEBUG_OBJECT (demux, "Sending newsegment %" GST_SEGMENT_FORMAT,
630         &demux->segment);
631
632     gst_ffmpegdemux_push_event (demux, gst_event_new_segment (&demux->segment));
633   }
634
635   /* Mark discont on all srcpads and remove eos */
636   gst_ffmpegdemux_set_flags (demux, TRUE, FALSE);
637
638   /* and restart the task in case it got paused explicitely or by
639    * the FLUSH_START event we pushed out. */
640   gst_pad_start_task (demux->sinkpad, (GstTaskFunction) gst_ffmpegdemux_loop,
641       demux->sinkpad, NULL);
642
643   /* and release the lock again so we can continue streaming */
644   GST_PAD_STREAM_UNLOCK (demux->sinkpad);
645
646   return res;
647
648   /* ERROR */
649 no_format:
650   {
651     GST_DEBUG_OBJECT (demux, "undefined format given, seek aborted.");
652     return FALSE;
653   }
654 }
655
656 static gboolean
657 gst_ffmpegdemux_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
658 {
659   GstFFMpegDemux *demux;
660   gboolean res = TRUE;
661
662   demux = (GstFFMpegDemux *) parent;
663
664   switch (GST_EVENT_TYPE (event)) {
665     case GST_EVENT_SEEK:
666       res = gst_ffmpegdemux_perform_seek (demux, event);
667       gst_event_unref (event);
668       break;
669     case GST_EVENT_LATENCY:
670       res = gst_pad_push_event (demux->sinkpad, event);
671       break;
672     case GST_EVENT_NAVIGATION:
673     case GST_EVENT_QOS:
674     default:
675       res = FALSE;
676       gst_event_unref (event);
677       break;
678   }
679
680   return res;
681 }
682
683 static gboolean
684 gst_ffmpegdemux_send_event (GstElement * element, GstEvent * event)
685 {
686   GstFFMpegDemux *demux = (GstFFMpegDemux *) (element);
687   gboolean res;
688
689   switch (GST_EVENT_TYPE (event)) {
690     case GST_EVENT_SEEK:
691       GST_OBJECT_LOCK (demux);
692       if (!demux->opened) {
693         GstEvent **event_p;
694
695         GST_DEBUG_OBJECT (demux, "caching seek event");
696         event_p = &demux->seek_event;
697         gst_event_replace (event_p, event);
698         GST_OBJECT_UNLOCK (demux);
699
700         res = TRUE;
701       } else {
702         GST_OBJECT_UNLOCK (demux);
703         res = gst_ffmpegdemux_perform_seek (demux, event);
704         gst_event_unref (event);
705       }
706       break;
707     default:
708       res = FALSE;
709       break;
710   }
711
712   return res;
713 }
714
715 static gboolean
716 gst_ffmpegdemux_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
717 {
718   GstFFMpegDemux *demux;
719   GstFFStream *stream;
720   AVStream *avstream;
721   gboolean res = FALSE;
722
723   if (!(stream = gst_pad_get_element_private (pad)))
724     return FALSE;
725
726   avstream = stream->avstream;
727
728   demux = (GstFFMpegDemux *) parent;
729
730   switch (GST_QUERY_TYPE (query)) {
731     case GST_QUERY_POSITION:
732     {
733       GstFormat format;
734       gint64 timeposition;
735
736       gst_query_parse_position (query, &format, NULL);
737
738       timeposition = stream->last_ts;
739       if (!(GST_CLOCK_TIME_IS_VALID (timeposition)))
740         break;
741
742       switch (format) {
743         case GST_FORMAT_TIME:
744           gst_query_set_position (query, GST_FORMAT_TIME, timeposition);
745           res = TRUE;
746           break;
747         case GST_FORMAT_DEFAULT:
748           gst_query_set_position (query, GST_FORMAT_DEFAULT,
749               gst_util_uint64_scale (timeposition, avstream->avg_frame_rate.num,
750                   GST_SECOND * avstream->avg_frame_rate.den));
751           res = TRUE;
752           break;
753         case GST_FORMAT_BYTES:
754           if (demux->videopads + demux->audiopads == 1 &&
755               GST_PAD_PEER (demux->sinkpad) != NULL)
756             res = gst_pad_query_default (pad, parent, query);
757           break;
758         default:
759           break;
760       }
761     }
762       break;
763     case GST_QUERY_DURATION:
764     {
765       GstFormat format;
766       gint64 timeduration;
767
768       gst_query_parse_duration (query, &format, NULL);
769
770       timeduration =
771           gst_ffmpeg_time_ff_to_gst (avstream->duration, avstream->time_base);
772       if (!(GST_CLOCK_TIME_IS_VALID (timeduration))) {
773         /* use duration of complete file if the stream duration is not known */
774         timeduration = demux->duration;
775         if (!(GST_CLOCK_TIME_IS_VALID (timeduration)))
776           break;
777       }
778
779       switch (format) {
780         case GST_FORMAT_TIME:
781           gst_query_set_duration (query, GST_FORMAT_TIME, timeduration);
782           res = TRUE;
783           break;
784         case GST_FORMAT_DEFAULT:
785           gst_query_set_duration (query, GST_FORMAT_DEFAULT,
786               gst_util_uint64_scale (timeduration, avstream->avg_frame_rate.num,
787                   GST_SECOND * avstream->avg_frame_rate.den));
788           res = TRUE;
789           break;
790         case GST_FORMAT_BYTES:
791           if (demux->videopads + demux->audiopads == 1 &&
792               GST_PAD_PEER (demux->sinkpad) != NULL)
793             res = gst_pad_query_default (pad, parent, query);
794           break;
795         default:
796           break;
797       }
798     }
799       break;
800     case GST_QUERY_SEEKING:{
801       GstFormat format;
802       gboolean seekable;
803       gint64 dur = -1;
804
805       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
806       seekable = demux->seekable;
807       if (!gst_pad_query_duration (pad, format, &dur)) {
808         /* unlikely that we don't know duration but can seek */
809         seekable = FALSE;
810         dur = -1;
811       }
812       gst_query_set_seeking (query, format, seekable, 0, dur);
813       res = TRUE;
814       break;
815     }
816     case GST_QUERY_SEGMENT:{
817       GstFormat format;
818       gint64 start, stop;
819
820       format = demux->segment.format;
821
822       start =
823           gst_segment_to_stream_time (&demux->segment, format,
824           demux->segment.start);
825       if ((stop = demux->segment.stop) == -1)
826         stop = demux->segment.duration;
827       else
828         stop = gst_segment_to_stream_time (&demux->segment, format, stop);
829
830       gst_query_set_segment (query, demux->segment.rate, format, start, stop);
831       res = TRUE;
832       break;
833     }
834     default:
835       /* FIXME : ADD GST_QUERY_CONVERT */
836       res = gst_pad_query_default (pad, parent, query);
837       break;
838   }
839
840   return res;
841 }
842
843 #if 0
844 /* FIXME, reenable me */
845 static gboolean
846 gst_ffmpegdemux_src_convert (GstPad * pad,
847     GstFormat src_fmt,
848     gint64 src_value, GstFormat * dest_fmt, gint64 * dest_value)
849 {
850   GstFFStream *stream;
851   gboolean res = TRUE;
852   AVStream *avstream;
853
854   if (!(stream = gst_pad_get_element_private (pad)))
855     return FALSE;
856
857   avstream = stream->avstream;
858   if (avstream->codec->codec_type != AVMEDIA_TYPE_VIDEO)
859     return FALSE;
860
861   switch (src_fmt) {
862     case GST_FORMAT_TIME:
863       switch (*dest_fmt) {
864         case GST_FORMAT_DEFAULT:
865           *dest_value = gst_util_uint64_scale (src_value,
866               avstream->avg_frame_rate.num,
867               GST_SECOND * avstream->avg_frame_rate.den);
868           break;
869         default:
870           res = FALSE;
871           break;
872       }
873       break;
874     case GST_FORMAT_DEFAULT:
875       switch (*dest_fmt) {
876         case GST_FORMAT_TIME:
877           *dest_value = gst_util_uint64_scale (src_value,
878               GST_SECOND * avstream->avg_frame_rate.num,
879               avstream->avg_frame_rate.den);
880           break;
881         default:
882           res = FALSE;
883           break;
884       }
885       break;
886     default:
887       res = FALSE;
888       break;
889   }
890
891   return res;
892 }
893 #endif
894
895 static gchar *
896 gst_ffmpegdemux_create_padname (const gchar * templ, gint n)
897 {
898   GString *string;
899
900   /* FIXME, we just want to printf the number according to the template but
901    * then the format string is not a literal and we can't check arguments and
902    * this generates a compiler error */
903   string = g_string_new (templ);
904   g_string_truncate (string, string->len - 2);
905   g_string_append_printf (string, "%u", n);
906
907   return g_string_free (string, FALSE);
908 }
909
910 static GstFFStream *
911 gst_ffmpegdemux_get_stream (GstFFMpegDemux * demux, AVStream * avstream)
912 {
913   GstFFMpegDemuxClass *oclass;
914   GstPadTemplate *templ = NULL;
915   GstPad *pad;
916   GstCaps *caps;
917   gint num;
918   gchar *padname;
919   const gchar *codec;
920   AVCodecContext *ctx;
921   GstFFStream *stream;
922   GstEvent *event;
923   gchar *stream_id;
924
925   ctx = avstream->codec;
926
927   oclass = (GstFFMpegDemuxClass *) G_OBJECT_GET_CLASS (demux);
928
929   if (demux->streams[avstream->index] != NULL)
930     goto exists;
931
932   /* create new stream */
933   stream = g_new0 (GstFFStream, 1);
934   demux->streams[avstream->index] = stream;
935
936   /* mark stream as unknown */
937   stream->unknown = TRUE;
938   stream->discont = TRUE;
939   stream->avstream = avstream;
940   stream->last_ts = GST_CLOCK_TIME_NONE;
941   stream->tags = NULL;
942
943   switch (ctx->codec_type) {
944     case AVMEDIA_TYPE_VIDEO:
945       templ = oclass->videosrctempl;
946       num = demux->videopads++;
947       break;
948     case AVMEDIA_TYPE_AUDIO:
949       templ = oclass->audiosrctempl;
950       num = demux->audiopads++;
951       break;
952     default:
953       goto unknown_type;
954   }
955
956   /* get caps that belongs to this stream */
957   caps = gst_ffmpeg_codecid_to_caps (ctx->codec_id, ctx, TRUE);
958   if (caps == NULL)
959     goto unknown_caps;
960
961   /* stream is known now */
962   stream->unknown = FALSE;
963
964   /* create new pad for this stream */
965   padname =
966       gst_ffmpegdemux_create_padname (GST_PAD_TEMPLATE_NAME_TEMPLATE (templ),
967       num);
968   pad = gst_pad_new_from_template (templ, padname);
969   g_free (padname);
970
971   gst_pad_use_fixed_caps (pad);
972   gst_pad_set_active (pad, TRUE);
973
974   gst_pad_set_query_function (pad, gst_ffmpegdemux_src_query);
975   gst_pad_set_event_function (pad, gst_ffmpegdemux_src_event);
976
977   /* store pad internally */
978   stream->pad = pad;
979   gst_pad_set_element_private (pad, stream);
980
981   /* transform some useful info to GstClockTime and remember */
982   {
983     GstClockTime tmp;
984
985     /* FIXME, actually use the start_time in some way */
986     tmp = gst_ffmpeg_time_ff_to_gst (avstream->start_time, avstream->time_base);
987     GST_DEBUG_OBJECT (demux, "stream %d: start time: %" GST_TIME_FORMAT,
988         avstream->index, GST_TIME_ARGS (tmp));
989
990     tmp = gst_ffmpeg_time_ff_to_gst (avstream->duration, avstream->time_base);
991     GST_DEBUG_OBJECT (demux, "stream %d: duration: %" GST_TIME_FORMAT,
992         avstream->index, GST_TIME_ARGS (tmp));
993   }
994
995   demux->streams[avstream->index] = stream;
996
997
998   stream_id =
999       gst_pad_create_stream_id_printf (pad, GST_ELEMENT_CAST (demux), "%03u",
1000       avstream->index);
1001
1002   event = gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
1003   if (event) {
1004     if (gst_event_parse_group_id (event, &demux->group_id))
1005       demux->have_group_id = TRUE;
1006     else
1007       demux->have_group_id = FALSE;
1008     gst_event_unref (event);
1009   } else if (!demux->have_group_id) {
1010     demux->have_group_id = TRUE;
1011     demux->group_id = gst_util_group_id_next ();
1012   }
1013   event = gst_event_new_stream_start (stream_id);
1014   if (demux->have_group_id)
1015     gst_event_set_group_id (event, demux->group_id);
1016
1017   gst_pad_push_event (pad, event);
1018   g_free (stream_id);
1019
1020   GST_INFO_OBJECT (pad, "adding pad with caps %" GST_PTR_FORMAT, caps);
1021   gst_pad_set_caps (pad, caps);
1022   gst_caps_unref (caps);
1023
1024   /* activate and add */
1025   gst_element_add_pad (GST_ELEMENT (demux), pad);
1026   gst_flow_combiner_add_pad (demux->flowcombiner, pad);
1027
1028   /* metadata */
1029   if ((codec = gst_ffmpeg_get_codecid_longname (ctx->codec_id))) {
1030     stream->tags = gst_tag_list_new_empty ();
1031
1032     gst_tag_list_add (stream->tags, GST_TAG_MERGE_REPLACE,
1033         (ctx->codec_type == AVMEDIA_TYPE_VIDEO) ?
1034         GST_TAG_VIDEO_CODEC : GST_TAG_AUDIO_CODEC, codec, NULL);
1035   }
1036
1037   return stream;
1038
1039   /* ERRORS */
1040 exists:
1041   {
1042     GST_DEBUG_OBJECT (demux, "Pad existed (stream %d)", avstream->index);
1043     return demux->streams[avstream->index];
1044   }
1045 unknown_type:
1046   {
1047     GST_WARNING_OBJECT (demux, "Unknown pad type %d", ctx->codec_type);
1048     return stream;
1049   }
1050 unknown_caps:
1051   {
1052     GST_WARNING_OBJECT (demux, "Unknown caps for codec %d", ctx->codec_id);
1053     return stream;
1054   }
1055 }
1056
1057 #if 0
1058     /* Re-enable once converted to new AVMetaData API
1059      * See #566605
1060      */
1061 static gchar *
1062 my_safe_copy (gchar * input)
1063 {
1064   gchar *output;
1065
1066   if (!(g_utf8_validate (input, -1, NULL))) {
1067     output = g_convert (input, strlen (input),
1068         "UTF-8", "ISO-8859-1", NULL, NULL, NULL);
1069   } else {
1070     output = g_strdup (input);
1071   }
1072
1073   return output;
1074 }
1075
1076 static GstTagList *
1077 gst_ffmpegdemux_read_tags (GstFFMpegDemux * demux)
1078 {
1079   GstTagList *tlist;
1080   gboolean hastag = FALSE;
1081
1082   tlist = gst_tag_list_new ();
1083
1084   if (*demux->context->title) {
1085     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1086         GST_TAG_TITLE, my_safe_copy (demux->context->title), NULL);
1087     hastag = TRUE;
1088   }
1089   if (*demux->context->author) {
1090     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1091         GST_TAG_ARTIST, my_safe_copy (demux->context->author), NULL);
1092     hastag = TRUE;
1093   }
1094   if (*demux->context->copyright) {
1095     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1096         GST_TAG_COPYRIGHT, my_safe_copy (demux->context->copyright), NULL);
1097     hastag = TRUE;
1098   }
1099   if (*demux->context->comment) {
1100     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1101         GST_TAG_COMMENT, my_safe_copy (demux->context->comment), NULL);
1102     hastag = TRUE;
1103   }
1104   if (*demux->context->album) {
1105     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1106         GST_TAG_ALBUM, my_safe_copy (demux->context->album), NULL);
1107     hastag = TRUE;
1108   }
1109   if (demux->context->track) {
1110     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1111         GST_TAG_TRACK_NUMBER, demux->context->track, NULL);
1112     hastag = TRUE;
1113   }
1114   if (*demux->context->genre) {
1115     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1116         GST_TAG_GENRE, my_safe_copy (demux->context->genre), NULL);
1117     hastag = TRUE;
1118   }
1119   if (demux->context->year) {
1120     gst_tag_list_add (tlist, GST_TAG_MERGE_REPLACE,
1121         GST_TAG_DATE, g_date_new_dmy (1, 1, demux->context->year), NULL);
1122     hastag = TRUE;
1123   }
1124
1125   if (!hastag) {
1126     gst_tag_list_unref (tlist);
1127     tlist = NULL;
1128   }
1129   return tlist;
1130 }
1131 #endif
1132
1133 static gboolean
1134 gst_ffmpegdemux_open (GstFFMpegDemux * demux)
1135 {
1136   AVIOContext *iocontext = NULL;
1137   GstFFMpegDemuxClass *oclass =
1138       (GstFFMpegDemuxClass *) G_OBJECT_GET_CLASS (demux);
1139   gint res, n_streams, i;
1140 #if 0
1141   /* Re-enable once converted to new AVMetaData API
1142    * See #566605
1143    */
1144   GstTagList *tags;
1145 #endif
1146   GstEvent *event;
1147   GList *cached_events;
1148
1149   /* to be sure... */
1150   gst_ffmpegdemux_close (demux);
1151
1152   /* open via our input protocol hack */
1153   if (demux->seekable)
1154     res = gst_ffmpegdata_open (demux->sinkpad, AVIO_FLAG_READ, &iocontext);
1155   else
1156     res = gst_ffmpeg_pipe_open (&demux->ffpipe, AVIO_FLAG_READ, &iocontext);
1157
1158   if (res < 0)
1159     goto beach;
1160
1161   demux->context = avformat_alloc_context ();
1162   demux->context->pb = iocontext;
1163   res = avformat_open_input (&demux->context, NULL, oclass->in_plugin, NULL);
1164
1165   GST_DEBUG_OBJECT (demux, "av_open_input returned %d", res);
1166   if (res < 0)
1167     goto beach;
1168
1169   res = gst_ffmpeg_av_find_stream_info (demux->context);
1170   GST_DEBUG_OBJECT (demux, "av_find_stream_info returned %d", res);
1171   if (res < 0)
1172     goto beach;
1173
1174   n_streams = demux->context->nb_streams;
1175   GST_DEBUG_OBJECT (demux, "we have %d streams", n_streams);
1176
1177   /* open_input_file() automatically reads the header. We can now map each
1178    * created AVStream to a GstPad to make GStreamer handle it. */
1179   for (i = 0; i < n_streams; i++) {
1180     gst_ffmpegdemux_get_stream (demux, demux->context->streams[i]);
1181   }
1182
1183   gst_element_no_more_pads (GST_ELEMENT (demux));
1184
1185   /* transform some useful info to GstClockTime and remember */
1186   demux->start_time = gst_util_uint64_scale_int (demux->context->start_time,
1187       GST_SECOND, AV_TIME_BASE);
1188   GST_DEBUG_OBJECT (demux, "start time: %" GST_TIME_FORMAT,
1189       GST_TIME_ARGS (demux->start_time));
1190   if (demux->context->duration > 0)
1191     demux->duration = gst_util_uint64_scale_int (demux->context->duration,
1192         GST_SECOND, AV_TIME_BASE);
1193   else
1194     demux->duration = GST_CLOCK_TIME_NONE;
1195
1196   GST_DEBUG_OBJECT (demux, "duration: %" GST_TIME_FORMAT,
1197       GST_TIME_ARGS (demux->duration));
1198
1199   /* store duration in the segment as well */
1200   demux->segment.duration = demux->duration;
1201
1202   GST_OBJECT_LOCK (demux);
1203   demux->opened = TRUE;
1204   event = demux->seek_event;
1205   demux->seek_event = NULL;
1206   cached_events = demux->cached_events;
1207   demux->cached_events = NULL;
1208   GST_OBJECT_UNLOCK (demux);
1209
1210   if (event) {
1211     gst_ffmpegdemux_perform_seek (demux, event);
1212     gst_event_unref (event);
1213   } else {
1214     GST_DEBUG_OBJECT (demux, "Sending segment %" GST_SEGMENT_FORMAT,
1215         &demux->segment);
1216     gst_ffmpegdemux_push_event (demux, gst_event_new_segment (&demux->segment));
1217   }
1218
1219   while (cached_events) {
1220     event = cached_events->data;
1221     GST_INFO_OBJECT (demux, "pushing cached event: %" GST_PTR_FORMAT, event);
1222     gst_ffmpegdemux_push_event (demux, event);
1223     cached_events = g_list_delete_link (cached_events, cached_events);
1224   }
1225
1226 #if 0
1227   /* Re-enable once converted to new AVMetaData API
1228    * See #566605
1229    */
1230   /* grab the global tags */
1231   tags = gst_ffmpegdemux_read_tags (demux);
1232   if (tags) {
1233     GST_INFO_OBJECT (demux, "global tags: %" GST_PTR_FORMAT, tags);
1234     gst_element_found_tags (GST_ELEMENT (demux), tags);
1235   }
1236 #endif
1237
1238   /* now handle the stream tags */
1239   for (i = 0; i < n_streams; i++) {
1240     GstFFStream *stream;
1241
1242     stream = gst_ffmpegdemux_get_stream (demux, demux->context->streams[i]);
1243     if (stream->tags != NULL && stream->pad != NULL) {
1244       GST_INFO_OBJECT (stream->pad, "stream tags: %" GST_PTR_FORMAT,
1245           stream->tags);
1246       gst_pad_push_event (stream->pad,
1247           gst_event_new_tag (gst_tag_list_ref (stream->tags)));
1248     }
1249   }
1250
1251   return TRUE;
1252
1253   /* ERRORS */
1254 beach:
1255   {
1256     GST_ELEMENT_ERROR (demux, LIBRARY, FAILED, (NULL),
1257         ("%s", gst_ffmpegdemux_averror (res)));
1258     return FALSE;
1259   }
1260 }
1261
1262 #define GST_FFMPEG_TYPE_FIND_SIZE 4096
1263 #define GST_FFMPEG_TYPE_FIND_MIN_SIZE 256
1264
1265 static void
1266 gst_ffmpegdemux_type_find (GstTypeFind * tf, gpointer priv)
1267 {
1268   const guint8 *data;
1269   AVInputFormat *in_plugin = (AVInputFormat *) priv;
1270   gint res = 0;
1271   guint64 length;
1272   GstCaps *sinkcaps;
1273
1274   /* We want GST_FFMPEG_TYPE_FIND_SIZE bytes, but if the file is shorter than
1275    * that we'll give it a try... */
1276   length = gst_type_find_get_length (tf);
1277   if (length == 0 || length > GST_FFMPEG_TYPE_FIND_SIZE)
1278     length = GST_FFMPEG_TYPE_FIND_SIZE;
1279
1280   /* The ffmpeg typefinders assume there's a certain minimum amount of data
1281    * and will happily do invalid memory access if there isn't, so let's just
1282    * skip the ffmpeg typefinders if the data available is too short
1283    * (in which case it's unlikely to be a media file anyway) */
1284   if (length < GST_FFMPEG_TYPE_FIND_MIN_SIZE) {
1285     GST_LOG ("not typefinding %" G_GUINT64_FORMAT " bytes, too short", length);
1286     return;
1287   }
1288
1289   GST_LOG ("typefinding %" G_GUINT64_FORMAT " bytes", length);
1290   if (in_plugin->read_probe &&
1291       (data = gst_type_find_peek (tf, 0, length)) != NULL) {
1292     AVProbeData probe_data;
1293
1294     probe_data.filename = "";
1295     probe_data.buf = (guint8 *) data;
1296     probe_data.buf_size = length;
1297
1298     res = in_plugin->read_probe (&probe_data);
1299     if (res > 0) {
1300       res = MAX (1, res * GST_TYPE_FIND_MAXIMUM / AVPROBE_SCORE_MAX);
1301       /* Restrict the probability for MPEG-TS streams, because there is
1302        * probably a better version in plugins-base, if the user has a recent
1303        * plugins-base (in fact we shouldn't even get here for ffmpeg mpegts or
1304        * mpegtsraw typefinders, since we blacklist them) */
1305       if (g_str_has_prefix (in_plugin->name, "mpegts"))
1306         res = MIN (res, GST_TYPE_FIND_POSSIBLE);
1307
1308       sinkcaps = gst_ffmpeg_formatid_to_caps (in_plugin->name);
1309
1310       GST_LOG ("libav typefinder '%s' suggests %" GST_PTR_FORMAT ", p=%u%%",
1311           in_plugin->name, sinkcaps, res);
1312
1313       gst_type_find_suggest (tf, res, sinkcaps);
1314       gst_caps_unref (sinkcaps);
1315     }
1316   }
1317 }
1318
1319 /* Task */
1320 static void
1321 gst_ffmpegdemux_loop (GstFFMpegDemux * demux)
1322 {
1323   GstFlowReturn ret;
1324   gint res;
1325   AVPacket pkt;
1326   GstPad *srcpad;
1327   GstFFStream *stream;
1328   AVStream *avstream;
1329   GstBuffer *outbuf = NULL;
1330   GstClockTime timestamp, duration;
1331   gint outsize;
1332   gboolean rawvideo;
1333   GstFlowReturn stream_last_flow;
1334
1335   /* open file if we didn't so already */
1336   if (!demux->opened)
1337     if (!gst_ffmpegdemux_open (demux))
1338       goto open_failed;
1339
1340   GST_DEBUG_OBJECT (demux, "about to read a frame");
1341
1342   /* read a frame */
1343   res = av_read_frame (demux->context, &pkt);
1344   if (res < 0)
1345     goto read_failed;
1346
1347   /* get the stream */
1348   stream =
1349       gst_ffmpegdemux_get_stream (demux,
1350       demux->context->streams[pkt.stream_index]);
1351
1352   /* check if we know the stream */
1353   if (stream->unknown)
1354     goto done;
1355
1356   /* get more stuff belonging to this stream */
1357   avstream = stream->avstream;
1358
1359   /* do timestamps, we do this first so that we can know when we
1360    * stepped over the segment stop position. */
1361   timestamp = gst_ffmpeg_time_ff_to_gst (pkt.pts, avstream->time_base);
1362   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
1363     stream->last_ts = timestamp;
1364   }
1365   duration = gst_ffmpeg_time_ff_to_gst (pkt.duration, avstream->time_base);
1366   if (G_UNLIKELY (!duration)) {
1367     GST_WARNING_OBJECT (demux, "invalid buffer duration, setting to NONE");
1368     duration = GST_CLOCK_TIME_NONE;
1369   }
1370
1371
1372   GST_DEBUG_OBJECT (demux,
1373       "pkt pts:%" GST_TIME_FORMAT
1374       " / size:%d / stream_index:%d / flags:%d / duration:%" GST_TIME_FORMAT
1375       " / pos:%" G_GINT64_FORMAT, GST_TIME_ARGS (timestamp), pkt.size,
1376       pkt.stream_index, pkt.flags, GST_TIME_ARGS (duration), (gint64) pkt.pos);
1377
1378   /* check start_time */
1379 #if 0
1380   if (demux->start_time != -1 && demux->start_time > timestamp)
1381     goto drop;
1382 #endif
1383
1384   if (GST_CLOCK_TIME_IS_VALID (timestamp))
1385     timestamp -= demux->start_time;
1386
1387   /* check if we ran outside of the segment */
1388   if (demux->segment.stop != -1 && timestamp > demux->segment.stop)
1389     goto drop;
1390
1391   /* prepare to push packet to peer */
1392   srcpad = stream->pad;
1393
1394   rawvideo = (avstream->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1395       avstream->codec->codec_id == AV_CODEC_ID_RAWVIDEO);
1396
1397   if (rawvideo)
1398     outsize = gst_ffmpeg_avpicture_get_size (avstream->codec->pix_fmt,
1399         avstream->codec->width, avstream->codec->height);
1400   else
1401     outsize = pkt.size;
1402
1403   outbuf = gst_buffer_new_and_alloc (outsize);
1404
1405   /* copy the data from packet into the target buffer
1406    * and do conversions for raw video packets */
1407   if (rawvideo) {
1408     AVPicture src, dst;
1409     const gchar *plugin_name =
1410         ((GstFFMpegDemuxClass *) (G_OBJECT_GET_CLASS (demux)))->in_plugin->name;
1411     GstMapInfo map;
1412
1413     if (strcmp (plugin_name, "gif") == 0) {
1414       src.data[0] = pkt.data;
1415       src.data[1] = NULL;
1416       src.data[2] = NULL;
1417       src.linesize[0] = avstream->codec->width * 3;
1418     } else {
1419       GST_WARNING ("Unknown demuxer %s, no idea what to do", plugin_name);
1420       gst_ffmpeg_avpicture_fill (&src, pkt.data,
1421           avstream->codec->pix_fmt, avstream->codec->width,
1422           avstream->codec->height);
1423     }
1424
1425     gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1426     gst_ffmpeg_avpicture_fill (&dst, map.data,
1427         avstream->codec->pix_fmt, avstream->codec->width,
1428         avstream->codec->height);
1429
1430     av_picture_copy (&dst, &src, avstream->codec->pix_fmt,
1431         avstream->codec->width, avstream->codec->height);
1432     gst_buffer_unmap (outbuf, &map);
1433   } else {
1434     gst_buffer_fill (outbuf, 0, pkt.data, outsize);
1435   }
1436
1437   GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1438   GST_BUFFER_DURATION (outbuf) = duration;
1439
1440   /* mark keyframes */
1441   if (!(pkt.flags & AV_PKT_FLAG_KEY)) {
1442     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1443   }
1444
1445   /* Mark discont */
1446   if (stream->discont) {
1447     GST_DEBUG_OBJECT (demux, "marking DISCONT");
1448     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
1449     stream->discont = FALSE;
1450   }
1451
1452   GST_DEBUG_OBJECT (demux,
1453       "Sending out buffer time:%" GST_TIME_FORMAT " size:%" G_GSIZE_FORMAT,
1454       GST_TIME_ARGS (timestamp), gst_buffer_get_size (outbuf));
1455
1456   ret = stream_last_flow = gst_pad_push (srcpad, outbuf);
1457
1458   /* if a pad is in e.g. WRONG_STATE, we want to pause to unlock the STREAM_LOCK */
1459   if (((ret = gst_flow_combiner_update_flow (demux->flowcombiner,
1460                   ret)) != GST_FLOW_OK)) {
1461     GST_WARNING_OBJECT (demux, "stream_movi flow: %s / %s",
1462         gst_flow_get_name (stream_last_flow), gst_flow_get_name (ret));
1463     goto pause;
1464   }
1465
1466 done:
1467   /* can destroy the packet now */
1468   av_free_packet (&pkt);
1469
1470   return;
1471
1472   /* ERRORS */
1473 pause:
1474   {
1475     GST_LOG_OBJECT (demux, "pausing task, reason %d (%s)", ret,
1476         gst_flow_get_name (ret));
1477     if (demux->seekable)
1478       gst_pad_pause_task (demux->sinkpad);
1479     else {
1480       GstFFMpegPipe *ffpipe = &demux->ffpipe;
1481
1482       GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1483       /* pause task and make sure loop stops */
1484       gst_task_pause (demux->task);
1485       g_rec_mutex_lock (&demux->task_lock);
1486       g_rec_mutex_unlock (&demux->task_lock);
1487       demux->ffpipe.srcresult = ret;
1488       GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1489     }
1490
1491     if (ret == GST_FLOW_EOS) {
1492       if (demux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
1493         gint64 stop;
1494
1495         if ((stop = demux->segment.stop) == -1)
1496           stop = demux->segment.duration;
1497
1498         GST_LOG_OBJECT (demux, "posting segment done");
1499         gst_element_post_message (GST_ELEMENT (demux),
1500             gst_message_new_segment_done (GST_OBJECT (demux),
1501                 demux->segment.format, stop));
1502         gst_ffmpegdemux_push_event (demux,
1503             gst_event_new_segment_done (demux->segment.format, stop));
1504       } else {
1505         GST_LOG_OBJECT (demux, "pushing eos");
1506         gst_ffmpegdemux_push_event (demux, gst_event_new_eos ());
1507       }
1508     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
1509       GST_ELEMENT_ERROR (demux, STREAM, FAILED,
1510           ("Internal data stream error."),
1511           ("streaming stopped, reason %s", gst_flow_get_name (ret)));
1512       gst_ffmpegdemux_push_event (demux, gst_event_new_eos ());
1513     }
1514     return;
1515   }
1516 open_failed:
1517   {
1518     ret = GST_FLOW_ERROR;
1519     goto pause;
1520   }
1521 read_failed:
1522   {
1523     /* something went wrong... */
1524     GST_WARNING_OBJECT (demux, "av_read_frame returned %d", res);
1525
1526     GST_OBJECT_LOCK (demux);
1527     /* pause appropriatly based on if we are flushing or not */
1528     if (demux->flushing)
1529       ret = GST_FLOW_FLUSHING;
1530     else if (gst_ffmpegdemux_has_outputted (demux)
1531         || gst_ffmpegdemux_is_eos (demux)) {
1532       GST_DEBUG_OBJECT (demux, "We are EOS");
1533       ret = GST_FLOW_EOS;
1534     } else
1535       ret = GST_FLOW_ERROR;
1536     GST_OBJECT_UNLOCK (demux);
1537
1538     goto pause;
1539   }
1540 drop:
1541   {
1542     GST_DEBUG_OBJECT (demux, "dropping buffer out of segment, stream eos");
1543     stream->eos = TRUE;
1544     if (gst_ffmpegdemux_is_eos (demux)) {
1545       av_free_packet (&pkt);
1546       GST_DEBUG_OBJECT (demux, "we are eos");
1547       ret = GST_FLOW_EOS;
1548       goto pause;
1549     } else {
1550       GST_DEBUG_OBJECT (demux, "some streams are not yet eos");
1551       goto done;
1552     }
1553   }
1554 }
1555
1556
1557 static gboolean
1558 gst_ffmpegdemux_sink_event (GstPad * sinkpad, GstObject * parent,
1559     GstEvent * event)
1560 {
1561   GstFFMpegDemux *demux;
1562   GstFFMpegPipe *ffpipe;
1563   gboolean result = TRUE;
1564
1565   demux = (GstFFMpegDemux *) parent;
1566   ffpipe = &(demux->ffpipe);
1567
1568   GST_LOG_OBJECT (demux, "event: %" GST_PTR_FORMAT, event);
1569
1570   switch (GST_EVENT_TYPE (event)) {
1571     case GST_EVENT_FLUSH_START:
1572       /* forward event */
1573       gst_pad_event_default (sinkpad, parent, event);
1574
1575       /* now unblock the chain function */
1576       GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1577       ffpipe->srcresult = GST_FLOW_FLUSHING;
1578       GST_FFMPEG_PIPE_SIGNAL (ffpipe);
1579       GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1580
1581       /* loop might run into WRONG_STATE and end itself,
1582        * but may also be waiting in a ffmpeg read
1583        * trying to break that would make ffmpeg believe eos,
1584        * so no harm to have the loop 'pausing' there ... */
1585       goto done;
1586     case GST_EVENT_FLUSH_STOP:
1587       /* forward event */
1588       gst_pad_event_default (sinkpad, parent, event);
1589
1590       GST_OBJECT_LOCK (demux);
1591       g_list_foreach (demux->cached_events, (GFunc) gst_mini_object_unref,
1592           NULL);
1593       g_list_free (demux->cached_events);
1594       GST_OBJECT_UNLOCK (demux);
1595       GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1596       gst_adapter_clear (ffpipe->adapter);
1597       ffpipe->srcresult = GST_FLOW_OK;
1598       /* loop may have decided to end itself as a result of flush WRONG_STATE */
1599       gst_task_start (demux->task);
1600       demux->flushing = FALSE;
1601       GST_LOG_OBJECT (demux, "loop started");
1602       GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1603       goto done;
1604     case GST_EVENT_EOS:
1605       /* inform the src task that it can stop now */
1606       GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1607       ffpipe->eos = TRUE;
1608       GST_FFMPEG_PIPE_SIGNAL (ffpipe);
1609       GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1610
1611       /* eat this event for now, task will send eos when finished */
1612       gst_event_unref (event);
1613       goto done;
1614     case GST_EVENT_STREAM_START:
1615     case GST_EVENT_CAPS:
1616       GST_LOG_OBJECT (demux, "dropping %s event", GST_EVENT_TYPE_NAME (event));
1617       gst_event_unref (event);
1618       goto done;
1619     default:
1620       /* for a serialized event, wait until an earlier data is gone,
1621        * though this is no guarantee as to when task is done with it.
1622        *
1623        * If the demuxer isn't opened, push straight away, since we'll
1624        * be waiting against a cond that will never be signalled. */
1625       if (GST_EVENT_IS_SERIALIZED (event)) {
1626         if (demux->opened) {
1627           GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1628           while (!ffpipe->needed)
1629             GST_FFMPEG_PIPE_WAIT (ffpipe);
1630           GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1631         } else {
1632           /* queue events and send them later (esp. tag events) */
1633           GST_OBJECT_LOCK (demux);
1634           demux->cached_events = g_list_append (demux->cached_events, event);
1635           GST_OBJECT_UNLOCK (demux);
1636           goto done;
1637         }
1638       }
1639       break;
1640   }
1641
1642   result = gst_pad_event_default (sinkpad, parent, event);
1643
1644 done:
1645
1646   return result;
1647 }
1648
1649 static GstFlowReturn
1650 gst_ffmpegdemux_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * buffer)
1651 {
1652   GstFFMpegDemux *demux;
1653   GstFFMpegPipe *ffpipe;
1654
1655   demux = (GstFFMpegDemux *) parent;
1656   ffpipe = &demux->ffpipe;
1657
1658   GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1659
1660   if (G_UNLIKELY (ffpipe->eos))
1661     goto eos;
1662
1663   if (G_UNLIKELY (ffpipe->srcresult != GST_FLOW_OK))
1664     goto ignore;
1665
1666   GST_DEBUG ("Giving a buffer of %" G_GSIZE_FORMAT " bytes",
1667       gst_buffer_get_size (buffer));
1668   gst_adapter_push (ffpipe->adapter, buffer);
1669   buffer = NULL;
1670   while (gst_adapter_available (ffpipe->adapter) >= ffpipe->needed) {
1671     GST_DEBUG ("Adapter has more that requested (ffpipe->needed:%d)",
1672         ffpipe->needed);
1673     GST_FFMPEG_PIPE_SIGNAL (ffpipe);
1674     GST_FFMPEG_PIPE_WAIT (ffpipe);
1675     /* may have become flushing */
1676     if (G_UNLIKELY (ffpipe->srcresult != GST_FLOW_OK))
1677       goto ignore;
1678   }
1679
1680   GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1681
1682   return GST_FLOW_OK;
1683
1684 /* special cases */
1685 eos:
1686   {
1687     GST_DEBUG_OBJECT (demux, "ignoring buffer at end-of-stream");
1688     GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1689
1690     gst_buffer_unref (buffer);
1691     return GST_FLOW_EOS;
1692   }
1693 ignore:
1694   {
1695     GST_DEBUG_OBJECT (demux, "ignoring buffer because src task encountered %s",
1696         gst_flow_get_name (ffpipe->srcresult));
1697     GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1698
1699     if (buffer)
1700       gst_buffer_unref (buffer);
1701     return GST_FLOW_FLUSHING;
1702   }
1703 }
1704
1705 static gboolean
1706 gst_ffmpegdemux_sink_activate (GstPad * sinkpad, GstObject * parent)
1707 {
1708   GstQuery *query;
1709   gboolean pull_mode;
1710   GstSchedulingFlags flags;
1711
1712   query = gst_query_new_scheduling ();
1713
1714   if (!gst_pad_peer_query (sinkpad, query)) {
1715     gst_query_unref (query);
1716     goto activate_push;
1717   }
1718
1719   pull_mode = gst_query_has_scheduling_mode_with_flags (query,
1720       GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
1721
1722   gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
1723   if (flags & GST_SCHEDULING_FLAG_SEQUENTIAL)
1724     pull_mode = FALSE;
1725
1726   gst_query_unref (query);
1727
1728   if (!pull_mode)
1729     goto activate_push;
1730
1731   GST_DEBUG_OBJECT (sinkpad, "activating pull");
1732   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
1733
1734 activate_push:
1735   {
1736     GST_DEBUG_OBJECT (sinkpad, "activating push");
1737     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
1738   }
1739 }
1740
1741 /* push mode:
1742  * - not seekable
1743  * - use gstpipe protocol, like ffmpeg's pipe protocol
1744  * - (independently managed) task driving ffmpeg
1745  */
1746 static gboolean
1747 gst_ffmpegdemux_sink_activate_push (GstPad * sinkpad, GstObject * parent,
1748     gboolean active)
1749 {
1750   GstFFMpegDemux *demux;
1751   gboolean res = FALSE;
1752
1753   demux = (GstFFMpegDemux *) (parent);
1754
1755   if (active) {
1756     if (demux->can_push == FALSE) {
1757       GST_WARNING_OBJECT (demux, "Demuxer can't reliably operate in push-mode");
1758       goto beach;
1759     }
1760     demux->ffpipe.eos = FALSE;
1761     demux->ffpipe.srcresult = GST_FLOW_OK;
1762     demux->ffpipe.needed = 0;
1763     demux->seekable = FALSE;
1764     res = gst_task_start (demux->task);
1765   } else {
1766     GstFFMpegPipe *ffpipe = &demux->ffpipe;
1767
1768     /* release chain and loop */
1769     GST_FFMPEG_PIPE_MUTEX_LOCK (ffpipe);
1770     demux->ffpipe.srcresult = GST_FLOW_FLUSHING;
1771     /* end streaming by making ffmpeg believe eos */
1772     demux->ffpipe.eos = TRUE;
1773     GST_FFMPEG_PIPE_SIGNAL (ffpipe);
1774     GST_FFMPEG_PIPE_MUTEX_UNLOCK (ffpipe);
1775
1776     /* make sure streaming ends */
1777     gst_task_stop (demux->task);
1778     g_rec_mutex_lock (&demux->task_lock);
1779     g_rec_mutex_unlock (&demux->task_lock);
1780     res = gst_task_join (demux->task);
1781     demux->seekable = FALSE;
1782   }
1783
1784 beach:
1785   return res;
1786 }
1787
1788 /* pull mode:
1789  * - seekable
1790  * - use gstreamer protocol, like ffmpeg's file protocol
1791  * - task driving ffmpeg based on sink pad
1792  */
1793 static gboolean
1794 gst_ffmpegdemux_sink_activate_pull (GstPad * sinkpad, GstObject * parent,
1795     gboolean active)
1796 {
1797   GstFFMpegDemux *demux;
1798   gboolean res;
1799
1800   demux = (GstFFMpegDemux *) parent;
1801
1802   if (active) {
1803     demux->seekable = TRUE;
1804     res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_ffmpegdemux_loop,
1805         demux, NULL);
1806   } else {
1807     res = gst_pad_stop_task (sinkpad);
1808     demux->seekable = FALSE;
1809   }
1810
1811   return res;
1812 }
1813
1814 static gboolean
1815 gst_ffmpegdemux_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
1816     GstPadMode mode, gboolean active)
1817 {
1818   gboolean res;
1819
1820   switch (mode) {
1821     case GST_PAD_MODE_PUSH:
1822       res = gst_ffmpegdemux_sink_activate_push (sinkpad, parent, active);
1823       break;
1824     case GST_PAD_MODE_PULL:
1825       res = gst_ffmpegdemux_sink_activate_pull (sinkpad, parent, active);
1826       break;
1827     default:
1828       res = FALSE;
1829       break;
1830   }
1831   return res;
1832 }
1833
1834 static GstStateChangeReturn
1835 gst_ffmpegdemux_change_state (GstElement * element, GstStateChange transition)
1836 {
1837   GstFFMpegDemux *demux = (GstFFMpegDemux *) (element);
1838   GstStateChangeReturn ret;
1839
1840   switch (transition) {
1841     case GST_STATE_CHANGE_READY_TO_PAUSED:
1842 #if 0
1843       /* test seek in READY here */
1844       gst_element_send_event (element, gst_event_new_seek (1.0,
1845               GST_FORMAT_TIME, GST_SEEK_FLAG_NONE,
1846               GST_SEEK_TYPE_SET, 10 * GST_SECOND,
1847               GST_SEEK_TYPE_SET, 13 * GST_SECOND));
1848 #endif
1849       break;
1850     default:
1851       break;
1852   }
1853
1854   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1855
1856   switch (transition) {
1857     case GST_STATE_CHANGE_PAUSED_TO_READY:
1858       gst_ffmpegdemux_close (demux);
1859       gst_adapter_clear (demux->ffpipe.adapter);
1860       g_list_foreach (demux->cached_events, (GFunc) gst_mini_object_unref,
1861           NULL);
1862       g_list_free (demux->cached_events);
1863       demux->cached_events = NULL;
1864       demux->have_group_id = FALSE;
1865       demux->group_id = G_MAXUINT;
1866       break;
1867     default:
1868       break;
1869   }
1870
1871   return ret;
1872 }
1873
1874 gboolean
1875 gst_ffmpegdemux_register (GstPlugin * plugin)
1876 {
1877   GType type;
1878   AVInputFormat *in_plugin;
1879   gchar *extensions;
1880   GTypeInfo typeinfo = {
1881     sizeof (GstFFMpegDemuxClass),
1882     (GBaseInitFunc) gst_ffmpegdemux_base_init,
1883     NULL,
1884     (GClassInitFunc) gst_ffmpegdemux_class_init,
1885     NULL,
1886     NULL,
1887     sizeof (GstFFMpegDemux),
1888     0,
1889     (GInstanceInitFunc) gst_ffmpegdemux_init,
1890   };
1891
1892   in_plugin = av_iformat_next (NULL);
1893
1894   GST_LOG ("Registering demuxers");
1895
1896   while (in_plugin) {
1897     gchar *type_name, *typefind_name;
1898     gchar *p, *name = NULL;
1899     gint rank;
1900     gboolean register_typefind_func = TRUE;
1901
1902     GST_LOG ("Attempting to handle libav demuxer plugin %s [%s]",
1903         in_plugin->name, in_plugin->long_name);
1904
1905     /* no emulators */
1906     if (!strncmp (in_plugin->long_name, "raw ", 4) ||
1907         !strncmp (in_plugin->long_name, "pcm ", 4) ||
1908         !strcmp (in_plugin->name, "audio_device") ||
1909         !strncmp (in_plugin->name, "image", 5) ||
1910         !strcmp (in_plugin->name, "mpegvideo") ||
1911         !strcmp (in_plugin->name, "mjpeg") ||
1912         !strcmp (in_plugin->name, "redir") ||
1913         !strncmp (in_plugin->name, "u8", 2) ||
1914         !strncmp (in_plugin->name, "u16", 3) ||
1915         !strncmp (in_plugin->name, "u24", 3) ||
1916         !strncmp (in_plugin->name, "u32", 3) ||
1917         !strncmp (in_plugin->name, "s8", 2) ||
1918         !strncmp (in_plugin->name, "s16", 3) ||
1919         !strncmp (in_plugin->name, "s24", 3) ||
1920         !strncmp (in_plugin->name, "s32", 3) ||
1921         !strncmp (in_plugin->name, "f32", 3) ||
1922         !strncmp (in_plugin->name, "f64", 3) ||
1923         !strcmp (in_plugin->name, "mulaw") || !strcmp (in_plugin->name, "alaw")
1924         )
1925       goto next;
1926
1927     /* no network demuxers */
1928     if (!strcmp (in_plugin->name, "sdp") ||
1929         !strcmp (in_plugin->name, "rtsp") ||
1930         !strcmp (in_plugin->name, "applehttp")
1931         )
1932       goto next;
1933
1934     /* these don't do what one would expect or
1935      * are only partially functional/useful */
1936     if (!strcmp (in_plugin->name, "aac") ||
1937         !strcmp (in_plugin->name, "wv") ||
1938         !strcmp (in_plugin->name, "ass") ||
1939         !strcmp (in_plugin->name, "ffmetadata"))
1940       goto next;
1941
1942     /* Don't use the typefind functions of formats for which we already have
1943      * better typefind functions */
1944     if (!strcmp (in_plugin->name, "mov,mp4,m4a,3gp,3g2,mj2") ||
1945         !strcmp (in_plugin->name, "ass") ||
1946         !strcmp (in_plugin->name, "avi") ||
1947         !strcmp (in_plugin->name, "asf") ||
1948         !strcmp (in_plugin->name, "mpegvideo") ||
1949         !strcmp (in_plugin->name, "mp3") ||
1950         !strcmp (in_plugin->name, "matroska") ||
1951         !strcmp (in_plugin->name, "matroska_webm") ||
1952         !strcmp (in_plugin->name, "matroska,webm") ||
1953         !strcmp (in_plugin->name, "mpeg") ||
1954         !strcmp (in_plugin->name, "wav") ||
1955         !strcmp (in_plugin->name, "au") ||
1956         !strcmp (in_plugin->name, "tta") ||
1957         !strcmp (in_plugin->name, "rm") ||
1958         !strcmp (in_plugin->name, "amr") ||
1959         !strcmp (in_plugin->name, "ogg") ||
1960         !strcmp (in_plugin->name, "aiff") ||
1961         !strcmp (in_plugin->name, "ape") ||
1962         !strcmp (in_plugin->name, "dv") ||
1963         !strcmp (in_plugin->name, "flv") ||
1964         !strcmp (in_plugin->name, "mpc") ||
1965         !strcmp (in_plugin->name, "mpc8") ||
1966         !strcmp (in_plugin->name, "mpegts") ||
1967         !strcmp (in_plugin->name, "mpegtsraw") ||
1968         !strcmp (in_plugin->name, "mxf") ||
1969         !strcmp (in_plugin->name, "nuv") ||
1970         !strcmp (in_plugin->name, "swf") ||
1971         !strcmp (in_plugin->name, "voc") ||
1972         !strcmp (in_plugin->name, "pva") ||
1973         !strcmp (in_plugin->name, "gif") || !strcmp (in_plugin->name, "vc1test")
1974         )
1975       register_typefind_func = FALSE;
1976
1977     /* Set the rank of demuxers known to work to MARGINAL.
1978      * Set demuxers for which we already have another implementation to NONE
1979      * Set All others to NONE*/
1980     if (!strcmp (in_plugin->name, "wsvqa") ||
1981         !strcmp (in_plugin->name, "wsaud") ||
1982         !strcmp (in_plugin->name, "wc3movie") ||
1983         !strcmp (in_plugin->name, "voc") ||
1984         !strcmp (in_plugin->name, "tta") ||
1985         !strcmp (in_plugin->name, "sol") ||
1986         !strcmp (in_plugin->name, "smk") ||
1987         !strcmp (in_plugin->name, "vmd") ||
1988         !strcmp (in_plugin->name, "film_cpk") ||
1989         !strcmp (in_plugin->name, "ingenient") ||
1990         !strcmp (in_plugin->name, "psxstr") ||
1991         !strcmp (in_plugin->name, "nuv") ||
1992         !strcmp (in_plugin->name, "nut") ||
1993         !strcmp (in_plugin->name, "nsv") ||
1994         !strcmp (in_plugin->name, "mxf") ||
1995         !strcmp (in_plugin->name, "mmf") ||
1996         !strcmp (in_plugin->name, "mm") ||
1997         !strcmp (in_plugin->name, "ipmovie") ||
1998         !strcmp (in_plugin->name, "ape") ||
1999         !strcmp (in_plugin->name, "RoQ") ||
2000         !strcmp (in_plugin->name, "idcin") ||
2001         !strcmp (in_plugin->name, "gxf") ||
2002         !strcmp (in_plugin->name, "ffm") ||
2003         !strcmp (in_plugin->name, "ea") ||
2004         !strcmp (in_plugin->name, "daud") ||
2005         !strcmp (in_plugin->name, "avs") ||
2006         !strcmp (in_plugin->name, "aiff") ||
2007         !strcmp (in_plugin->name, "4xm") ||
2008         !strcmp (in_plugin->name, "yuv4mpegpipe") ||
2009         !strcmp (in_plugin->name, "pva") ||
2010         !strcmp (in_plugin->name, "mpc") || !strcmp (in_plugin->name, "gif"))
2011       rank = GST_RANK_MARGINAL;
2012     else {
2013       GST_DEBUG ("ignoring %s", in_plugin->name);
2014       rank = GST_RANK_NONE;
2015       goto next;
2016     }
2017
2018     p = name = g_strdup (in_plugin->name);
2019     while (*p) {
2020       if (*p == '.' || *p == ',')
2021         *p = '_';
2022       p++;
2023     }
2024
2025     /* construct the type */
2026     type_name = g_strdup_printf ("avdemux_%s", name);
2027
2028     /* if it's already registered, drop it */
2029     if (g_type_from_name (type_name)) {
2030       g_free (type_name);
2031       goto next;
2032     }
2033
2034     typefind_name = g_strdup_printf ("avtype_%s", name);
2035
2036     /* create the type now */
2037     type = g_type_register_static (GST_TYPE_ELEMENT, type_name, &typeinfo, 0);
2038     g_type_set_qdata (type, GST_FFDEMUX_PARAMS_QDATA, (gpointer) in_plugin);
2039
2040     if (in_plugin->extensions)
2041       extensions = g_strdelimit (g_strdup (in_plugin->extensions), " ", ',');
2042     else
2043       extensions = NULL;
2044
2045     if (!gst_element_register (plugin, type_name, rank, type) ||
2046         (register_typefind_func == TRUE &&
2047             !gst_type_find_register (plugin, typefind_name, rank,
2048                 gst_ffmpegdemux_type_find, extensions, NULL, in_plugin,
2049                 NULL))) {
2050       g_warning ("Register of type avdemux_%s failed", name);
2051       g_free (type_name);
2052       g_free (typefind_name);
2053       return FALSE;
2054     }
2055
2056     g_free (type_name);
2057     g_free (typefind_name);
2058     g_free (extensions);
2059
2060   next:
2061     g_free (name);
2062     in_plugin = av_iformat_next (in_plugin);
2063   }
2064
2065   GST_LOG ("Finished registering demuxers");
2066
2067   return TRUE;
2068 }