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