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