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