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