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