92bfd29f934dad7e6e3457100dbadc86ed547caf
[platform/upstream/gstreamer.git] / gst / videoparsers / gstmpeg4videoparse.c
1 /* GStreamer
2  * Copyright (C) <2008> Mindfruit B.V.
3  *   @author Sjoerd Simons <sjoerd@luon.net>
4  * Copyright (C) <2007> Julien Moutte <julien@fluendo.com>
5  * Copyright (C) <2011> Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>
6  * Copyright (C) <2011> Nokia Corporation
7  * Copyright (C) <2011> Intel
8  * Copyright (C) <2011> Collabora Ltd.
9  * Copyright (C) <2011> Thibault Saunier <thibault.saunier@collabora.com>
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public
22  * License along with this library; if not, write to the
23  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <string.h>
32 #include <gst/base/gstbytereader.h>
33 #include <gst/pbutils/codec-utils.h>
34 #include <gst/video/video.h>
35
36 #include "gstmpeg4videoparse.h"
37
38 GST_DEBUG_CATEGORY (mpeg4v_parse_debug);
39 #define GST_CAT_DEFAULT mpeg4v_parse_debug
40
41 static GstStaticPadTemplate src_template =
42 GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC,
43     GST_PAD_ALWAYS,
44     GST_STATIC_CAPS ("video/mpeg, "
45         "mpegversion = (int) 4, "
46         "width = (int)[ 0, max ], "
47         "height = (int)[ 0, max ], "
48         "framerate = (fraction)[ 0, max ] ,"
49         "parsed = (boolean) true, " "systemstream = (boolean) false; "
50         "video/x-divx, " "divxversion = (int) [ 4, 5 ]")
51     );
52
53 static GstStaticPadTemplate sink_template =
54 GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK,
55     GST_PAD_ALWAYS,
56     GST_STATIC_CAPS ("video/mpeg, "
57         "mpegversion = (int) 4, " "systemstream = (boolean) false; "
58         "video/x-divx, " "divxversion = (int) [ 4, 5 ]")
59     );
60
61 /* Properties */
62 #define DEFAULT_PROP_DROP TRUE
63 #define DEFAULT_CONFIG_INTERVAL (0)
64
65 enum
66 {
67   PROP_0,
68   PROP_DROP,
69   PROP_CONFIG_INTERVAL,
70   PROP_LAST
71 };
72
73 #define gst_mpeg4vparse_parent_class parent_class
74 G_DEFINE_TYPE (GstMpeg4VParse, gst_mpeg4vparse, GST_TYPE_BASE_PARSE);
75
76 static gboolean gst_mpeg4vparse_start (GstBaseParse * parse);
77 static gboolean gst_mpeg4vparse_stop (GstBaseParse * parse);
78 static GstFlowReturn gst_mpeg4vparse_handle_frame (GstBaseParse * parse,
79     GstBaseParseFrame * frame, gint * skipsize);
80 static GstFlowReturn gst_mpeg4vparse_parse_frame (GstBaseParse * parse,
81     GstBaseParseFrame * frame);
82 static GstFlowReturn gst_mpeg4vparse_pre_push_frame (GstBaseParse * parse,
83     GstBaseParseFrame * frame);
84 static gboolean gst_mpeg4vparse_set_caps (GstBaseParse * parse, GstCaps * caps);
85 static GstCaps *gst_mpeg4vparse_get_caps (GstBaseParse * parse,
86     GstCaps * filter);
87
88 static void gst_mpeg4vparse_set_property (GObject * object, guint prop_id,
89     const GValue * value, GParamSpec * pspec);
90 static void gst_mpeg4vparse_get_property (GObject * object, guint prop_id,
91     GValue * value, GParamSpec * pspec);
92 static gboolean gst_mpeg4vparse_event (GstBaseParse * parse, GstEvent * event);
93 static gboolean gst_mpeg4vparse_src_event (GstBaseParse * parse,
94     GstEvent * event);
95
96 static void
97 gst_mpeg4vparse_set_property (GObject * object, guint property_id,
98     const GValue * value, GParamSpec * pspec)
99 {
100   GstMpeg4VParse *parse = GST_MPEG4VIDEO_PARSE (object);
101
102   switch (property_id) {
103     case PROP_DROP:
104       parse->drop = g_value_get_boolean (value);
105       break;
106     case PROP_CONFIG_INTERVAL:
107       parse->interval = g_value_get_uint (value);
108       break;
109     default:
110       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
111   }
112 }
113
114 static void
115 gst_mpeg4vparse_get_property (GObject * object, guint property_id,
116     GValue * value, GParamSpec * pspec)
117 {
118   GstMpeg4VParse *parse = GST_MPEG4VIDEO_PARSE (object);
119
120   switch (property_id) {
121     case PROP_DROP:
122       g_value_set_boolean (value, parse->drop);
123       break;
124     case PROP_CONFIG_INTERVAL:
125       g_value_set_uint (value, parse->interval);
126       break;
127     default:
128       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
129   }
130 }
131
132 static void
133 gst_mpeg4vparse_class_init (GstMpeg4VParseClass * klass)
134 {
135   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
136   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
137   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
138
139   parent_class = g_type_class_peek_parent (klass);
140
141   gobject_class->set_property = gst_mpeg4vparse_set_property;
142   gobject_class->get_property = gst_mpeg4vparse_get_property;
143
144   g_object_class_install_property (gobject_class, PROP_DROP,
145       g_param_spec_boolean ("drop", "drop",
146           "Drop data untill valid configuration data is received either "
147           "in the stream or through caps", DEFAULT_PROP_DROP,
148           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
149
150   g_object_class_install_property (gobject_class, PROP_CONFIG_INTERVAL,
151       g_param_spec_uint ("config-interval",
152           "Configuration Send Interval",
153           "Send Configuration Insertion Interval in seconds (configuration headers "
154           "will be multiplexed in the data stream when detected.) (0 = disabled)",
155           0, 3600, DEFAULT_CONFIG_INTERVAL,
156           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
157
158   gst_element_class_add_pad_template (element_class,
159       gst_static_pad_template_get (&src_template));
160   gst_element_class_add_pad_template (element_class,
161       gst_static_pad_template_get (&sink_template));
162
163   gst_element_class_set_static_metadata (element_class,
164       "MPEG 4 video elementary stream parser", "Codec/Parser/Video",
165       "Parses MPEG-4 Part 2 elementary video streams",
166       "Julien Moutte <julien@fluendo.com>");
167
168   GST_DEBUG_CATEGORY_INIT (mpeg4v_parse_debug, "mpeg4videoparse", 0,
169       "MPEG-4 video parser");
170
171   /* Override BaseParse vfuncs */
172   parse_class->start = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_start);
173   parse_class->stop = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_stop);
174   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_handle_frame);
175   parse_class->pre_push_frame =
176       GST_DEBUG_FUNCPTR (gst_mpeg4vparse_pre_push_frame);
177   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_set_caps);
178   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_get_caps);
179   parse_class->sink_event = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_event);
180   parse_class->src_event = GST_DEBUG_FUNCPTR (gst_mpeg4vparse_src_event);
181 }
182
183 static void
184 gst_mpeg4vparse_init (GstMpeg4VParse * parse)
185 {
186   parse->interval = DEFAULT_CONFIG_INTERVAL;
187   parse->last_report = GST_CLOCK_TIME_NONE;
188
189   gst_base_parse_set_pts_interpolation (GST_BASE_PARSE (parse), FALSE);
190 }
191
192 static void
193 gst_mpeg4vparse_reset_frame (GstMpeg4VParse * mp4vparse)
194 {
195   /* done parsing; reset state */
196   mp4vparse->last_sc = -1;
197   mp4vparse->vop_offset = -1;
198   mp4vparse->vo_found = FALSE;
199   mp4vparse->config_found = FALSE;
200   mp4vparse->vol_offset = -1;
201   mp4vparse->vo_offset = -1;
202 }
203
204 static void
205 gst_mpeg4vparse_reset (GstMpeg4VParse * mp4vparse)
206 {
207   gst_mpeg4vparse_reset_frame (mp4vparse);
208   mp4vparse->update_caps = TRUE;
209   mp4vparse->profile = NULL;
210   mp4vparse->level = NULL;
211   mp4vparse->pending_key_unit_ts = GST_CLOCK_TIME_NONE;
212   mp4vparse->force_key_unit_event = NULL;
213
214   gst_buffer_replace (&mp4vparse->config, NULL);
215   memset (&mp4vparse->vol, 0, sizeof (mp4vparse->vol));
216 }
217
218 static gboolean
219 gst_mpeg4vparse_start (GstBaseParse * parse)
220 {
221   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
222
223   GST_DEBUG_OBJECT (parse, "start");
224
225   gst_mpeg4vparse_reset (mp4vparse);
226   /* at least this much for a valid frame */
227   gst_base_parse_set_min_frame_size (parse, 6);
228
229   return TRUE;
230 }
231
232 static gboolean
233 gst_mpeg4vparse_stop (GstBaseParse * parse)
234 {
235   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
236
237   GST_DEBUG_OBJECT (parse, "stop");
238
239   gst_mpeg4vparse_reset (mp4vparse);
240
241   return TRUE;
242 }
243
244 static gboolean
245 gst_mpeg4vparse_process_config (GstMpeg4VParse * mp4vparse,
246     const guint8 * data, guint offset, gsize size)
247 {
248   GstMpeg4VisualObject *vo;
249
250   /* only do stuff if something new */
251   if (mp4vparse->config
252       && !gst_buffer_memcmp (mp4vparse->config, offset, data, size))
253     return TRUE;
254
255   if (mp4vparse->vol_offset < 0) {
256     GST_WARNING ("No video object Layer parsed in this frame, cannot accept "
257         "config");
258     return FALSE;
259   }
260
261   vo = mp4vparse->vo_found ? &mp4vparse->vo : NULL;
262
263   /* If the parsing fail, we accept the config only if we don't have
264    * any config yet. */
265   if (gst_mpeg4_parse_video_object_layer (&mp4vparse->vol,
266           vo, data + mp4vparse->vol_offset,
267           size - mp4vparse->vol_offset) != GST_MPEG4_PARSER_OK &&
268       mp4vparse->config)
269     return FALSE;
270
271   GST_LOG_OBJECT (mp4vparse, "Width/Height: %u/%u, "
272       "time increment resolution: %u fixed time increment: %u",
273       mp4vparse->vol.width, mp4vparse->vol.height,
274       mp4vparse->vol.vop_time_increment_resolution,
275       mp4vparse->vol.fixed_vop_time_increment);
276
277
278   GST_LOG_OBJECT (mp4vparse, "accepting parsed config size %" G_GSSIZE_FORMAT,
279       size);
280
281   if (mp4vparse->config != NULL)
282     gst_buffer_unref (mp4vparse->config);
283
284   mp4vparse->config = gst_buffer_new_wrapped (g_memdup (data, size), size);
285
286   /* trigger src caps update */
287   mp4vparse->update_caps = TRUE;
288
289   return TRUE;
290 }
291
292 static gboolean
293 gst_mpeg4vparse_get_vop_coded (GstMpeg4VParse * mp4vparse, const guint8 * data,
294     gint vop_offset, gsize size, gsize frame_size)
295 {
296   if (frame_size > 9) {         /* assuming bigger frame will always have vop_coded (saves some parsing) */
297     return TRUE;
298   } else if (size > vop_offset + 3) {
299     GstBitReader reader;
300     guint8 value;
301
302     gst_bit_reader_init (&reader, data + vop_offset + 1, size - vop_offset);
303     gst_bit_reader_skip (&reader, 2);   /* VOP_coding_type */
304
305     /* modulo_time_base (ends with 0) */
306     while (gst_bit_reader_get_bits_uint8 (&reader, &value, 1) && value);
307
308     /* marker_bit */
309     g_return_val_if_fail (gst_bit_reader_get_bits_uint8 (&reader, &value, 1)
310         && value, TRUE);
311
312     /* VOP_time_increment */
313     gst_bit_reader_skip (&reader, mp4vparse->vol.vop_time_increment_bits);
314
315     /* marker_bit */
316     g_return_val_if_fail (gst_bit_reader_get_bits_uint8 (&reader, &value, 1)
317         && value, TRUE);
318
319     /* VOP_coded */
320     if (!gst_bit_reader_get_bits_uint8 (&reader, &value, 1)) {
321       return FALSE;
322     }
323
324     return value;
325   }
326
327   return FALSE;
328 }
329
330 /* caller guarantees at least start code in @buf at @off */
331 static gboolean
332 gst_mpeg4vparse_process_sc (GstMpeg4VParse * mp4vparse, GstMpeg4Packet * packet,
333     gsize size)
334 {
335
336   GST_LOG_OBJECT (mp4vparse, "process startcode %x", packet->type);
337
338   /* if we found a VOP, next start code ends it,
339    * except for final VOS end sequence code included in last VOP-frame */
340   if (mp4vparse->vop_offset >= 0 &&
341       packet->type != GST_MPEG4_VISUAL_OBJ_SEQ_END) {
342     if (G_LIKELY (size > mp4vparse->vop_offset + 1)) {
343       mp4vparse->intra_frame =
344           ((packet->data[mp4vparse->vop_offset + 1] >> 6 & 0x3) == 0);
345     } else {
346       GST_WARNING_OBJECT (mp4vparse, "no data following VOP startcode");
347       mp4vparse->intra_frame = FALSE;
348     }
349     mp4vparse->vop_coded =
350         gst_mpeg4vparse_get_vop_coded (mp4vparse, packet->data,
351         mp4vparse->vop_offset, size, packet->offset - 3);
352     GST_LOG_OBJECT (mp4vparse,
353         "ending frame of size %d, is intra %d, vop_coded %d",
354         packet->offset - 3, mp4vparse->intra_frame, mp4vparse->vop_coded);
355     return TRUE;
356   }
357
358   if (mp4vparse->vo_offset >= 0) {
359     gst_mpeg4_parse_visual_object (&mp4vparse->vo, NULL,
360         packet->data + mp4vparse->vo_offset,
361         packet->offset - 3 - mp4vparse->vo_offset);
362     mp4vparse->vo_offset = -1;
363     mp4vparse->vo_found = TRUE;
364   }
365
366   switch (packet->type) {
367     case GST_MPEG4_VIDEO_OBJ_PLANE:
368     case GST_MPEG4_GROUP_OF_VOP:
369     case GST_MPEG4_USER_DATA:
370     {
371       if (packet->type == GST_MPEG4_VIDEO_OBJ_PLANE) {
372         GST_LOG_OBJECT (mp4vparse, "startcode is VOP");
373         mp4vparse->vop_offset = packet->offset;
374       } else if (packet->type == GST_MPEG4_GROUP_OF_VOP) {
375         GST_LOG_OBJECT (mp4vparse, "startcode is GOP");
376       } else {
377         GST_LOG_OBJECT (mp4vparse, "startcode is User Data");
378       }
379       /* parse config data ending here if proper startcodes found earlier;
380        * we should have received a visual object before. */
381       if (mp4vparse->config_found) {
382         /*Do not take care startcode into account */
383         gst_mpeg4vparse_process_config (mp4vparse,
384             packet->data, packet->offset, packet->offset - 3);
385         mp4vparse->vo_found = FALSE;
386       }
387       break;
388     }
389     case GST_MPEG4_VISUAL_OBJ_SEQ_START:
390       GST_LOG_OBJECT (mp4vparse, "Visual Sequence Start");
391       mp4vparse->config_found = TRUE;
392       mp4vparse->profile = gst_codec_utils_mpeg4video_get_profile (packet->data
393           + packet->offset + 1, packet->offset);
394       mp4vparse->level = gst_codec_utils_mpeg4video_get_level (packet->data
395           + packet->offset + 1, packet->offset);
396       break;
397     case GST_MPEG4_VISUAL_OBJ:
398       GST_LOG_OBJECT (mp4vparse, "Visual Object");
399       mp4vparse->vo_offset = packet->offset;
400       break;
401     default:
402       if (packet->type >= GST_MPEG4_VIDEO_LAYER_FIRST &&
403           packet->type <= GST_MPEG4_VIDEO_LAYER_LAST) {
404
405         GST_LOG_OBJECT (mp4vparse, "Video Object Layer");
406
407         /*  wee keep track of the offset to parse later on */
408         if (mp4vparse->vol_offset < 0)
409           mp4vparse->vol_offset = packet->offset;
410
411         /* VO (video object) cases */
412       } else if (packet->type <= GST_MPEG4_VIDEO_OBJ_LAST) {
413         GST_LOG_OBJECT (mp4vparse, "Video object");
414         mp4vparse->config_found = TRUE;
415       }
416       break;
417   }
418
419   /* at least need to have a VOP in a frame */
420   return FALSE;
421 }
422
423 static GstFlowReturn
424 gst_mpeg4vparse_handle_frame (GstBaseParse * parse,
425     GstBaseParseFrame * frame, gint * skipsize)
426 {
427   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
428   GstMpeg4Packet packet;
429   GstMapInfo map;
430   guint8 *data = NULL;
431   gsize size;
432   gint off = 0;
433   gboolean ret = FALSE;
434   guint framesize;
435
436   gst_buffer_map (frame->buffer, &map, GST_MAP_READ);
437   data = map.data;
438   size = map.size;
439
440 retry:
441   /* at least start code and subsequent byte */
442   if (G_UNLIKELY (size - off < 5)) {
443     *skipsize = 1;
444     goto out;
445   }
446
447   /* avoid stale cached parsing state */
448   if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_NEW_FRAME) {
449     GST_LOG_OBJECT (mp4vparse, "parsing new frame");
450     gst_mpeg4vparse_reset_frame (mp4vparse);
451   } else {
452     GST_LOG_OBJECT (mp4vparse, "resuming frame parsing");
453   }
454
455   /* if already found a previous start code, e.g. start of frame, go for next */
456   if (mp4vparse->last_sc >= 0) {
457     off = mp4vparse->last_sc;
458     goto next;
459   }
460
461   /* didn't find anything that looks like a sync word, skip */
462   switch (gst_mpeg4_parse (&packet, FALSE, NULL, data, off, size)) {
463     case (GST_MPEG4_PARSER_NO_PACKET):
464     case (GST_MPEG4_PARSER_ERROR):
465       *skipsize = size - 3;
466       goto out;
467     default:
468       break;
469   }
470   off = packet.offset;
471
472   /* possible frame header, but not at offset 0? skip bytes before sync */
473   if (G_UNLIKELY (off > 3)) {
474     *skipsize = off - 3;
475     goto out;
476   }
477
478   switch (packet.type) {
479     case GST_MPEG4_GROUP_OF_VOP:
480     case GST_MPEG4_VISUAL_OBJ_SEQ_START:
481     case GST_MPEG4_VIDEO_OBJ_PLANE:
482       break;
483     default:
484       if (packet.type <= GST_MPEG4_VIDEO_OBJ_LAST)
485         break;
486       /* undesirable sc */
487       GST_LOG_OBJECT (mp4vparse, "start code is no VOS, VO, VOP or GOP");
488       goto retry;
489   }
490
491   /* found sc */
492   mp4vparse->last_sc = 0;
493
494   /* examine start code, which should not end frame at present */
495   gst_mpeg4vparse_process_sc (mp4vparse, &packet, size);
496
497 next:
498   GST_LOG_OBJECT (mp4vparse, "Looking for frame end");
499
500   /* start is fine as of now */
501   *skipsize = 0;
502   /* position a bit further than last sc */
503   off++;
504
505   /* so now we have start code at start of data; locate next packet */
506   switch (gst_mpeg4_parse (&packet, FALSE, NULL, data, off, size)) {
507     case (GST_MPEG4_PARSER_NO_PACKET_END):
508       ret = gst_mpeg4vparse_process_sc (mp4vparse, &packet, size);
509       if (ret)
510         break;
511     case (GST_MPEG4_PARSER_NO_PACKET):
512     case (GST_MPEG4_PARSER_ERROR):
513       /* if draining, take all */
514       if (GST_BASE_PARSE_DRAINING (parse)) {
515         framesize = size;
516         ret = TRUE;
517       } else {
518         /* resume scan where we left it */
519         mp4vparse->last_sc = size - 3;
520       }
521       goto out;
522       break;
523     default:
524       /* decide whether this startcode ends a frame */
525       ret = gst_mpeg4vparse_process_sc (mp4vparse, &packet, size);
526       break;
527   }
528
529   off = packet.offset;
530
531   if (ret) {
532     framesize = off - 3;
533   } else {
534     goto next;
535   }
536
537 out:
538   gst_buffer_unmap (frame->buffer, &map);
539
540   if (ret) {
541     GstFlowReturn res;
542
543     g_assert (framesize <= map.size);
544     res = gst_mpeg4vparse_parse_frame (parse, frame);
545     if (res == GST_BASE_PARSE_FLOW_DROPPED)
546       frame->flags |= GST_BASE_PARSE_FRAME_FLAG_DROP;
547     return gst_base_parse_finish_frame (parse, frame, framesize);
548   }
549
550   return GST_FLOW_OK;
551 }
552
553 static void
554 gst_mpeg4vparse_update_src_caps (GstMpeg4VParse * mp4vparse)
555 {
556   GstCaps *caps = NULL;
557   GstStructure *s = NULL;
558
559   GST_LOG_OBJECT (mp4vparse, "Updating caps");
560
561   /* only update if no src caps yet or explicitly triggered */
562   if (G_LIKELY (gst_pad_has_current_caps (GST_BASE_PARSE_SRC_PAD (mp4vparse)) &&
563           !mp4vparse->update_caps))
564     return;
565
566   /* carry over input caps as much as possible; override with our own stuff */
567   caps = gst_pad_get_current_caps (GST_BASE_PARSE_SINK_PAD (mp4vparse));
568   if (caps) {
569     GstCaps *tmp = gst_caps_copy (caps);
570     gst_caps_unref (caps);
571     caps = tmp;
572     s = gst_caps_get_structure (caps, 0);
573   } else {
574     caps = gst_caps_new_simple ("video/mpeg",
575         "mpegversion", G_TYPE_INT, 4,
576         "systemstream", G_TYPE_BOOLEAN, FALSE, NULL);
577   }
578
579   gst_caps_set_simple (caps, "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
580
581   if (mp4vparse->profile && mp4vparse->level) {
582     gst_caps_set_simple (caps, "profile", G_TYPE_STRING, mp4vparse->profile,
583         "level", G_TYPE_STRING, mp4vparse->level, NULL);
584   }
585
586   if (mp4vparse->config != NULL) {
587     gst_caps_set_simple (caps, "codec_data",
588         GST_TYPE_BUFFER, mp4vparse->config, NULL);
589   }
590
591   if (mp4vparse->vol.width > 0 && mp4vparse->vol.height > 0) {
592     gst_caps_set_simple (caps, "width", G_TYPE_INT, mp4vparse->vol.width,
593         "height", G_TYPE_INT, mp4vparse->vol.height, NULL);
594   }
595
596   /* perhaps we have a framerate */
597   {
598     gint fps_num = mp4vparse->vol.vop_time_increment_resolution;
599     gint fps_den = mp4vparse->vol.fixed_vop_time_increment;
600     GstClockTime latency;
601
602     /* upstream overrides */
603     if (s && gst_structure_has_field (s, "framerate"))
604       gst_structure_get_fraction (s, "framerate", &fps_num, &fps_den);
605
606     if (fps_den > 0 && fps_num > 0) {
607       gst_caps_set_simple (caps, "framerate",
608           GST_TYPE_FRACTION, fps_num, fps_den, NULL);
609       gst_base_parse_set_frame_rate (GST_BASE_PARSE (mp4vparse),
610           fps_num, fps_den, 0, 0);
611       latency = gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
612       gst_base_parse_set_latency (GST_BASE_PARSE (mp4vparse), latency, latency);
613     }
614   }
615
616   /* or pixel-aspect-ratio */
617   if (mp4vparse->vol.par_width > 0 && mp4vparse->vol.par_height > 0 &&
618       (!s || !gst_structure_has_field (s, "pixel-aspect-ratio"))) {
619     gst_caps_set_simple (caps, "pixel-aspect-ratio",
620         GST_TYPE_FRACTION, mp4vparse->vol.par_width,
621         mp4vparse->vol.par_height, NULL);
622   }
623
624   gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (mp4vparse), caps);
625   gst_caps_unref (caps);
626
627   mp4vparse->update_caps = FALSE;
628 }
629
630 static GstFlowReturn
631 gst_mpeg4vparse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
632 {
633   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
634   GstBuffer *buffer = frame->buffer;
635
636   gst_mpeg4vparse_update_src_caps (mp4vparse);
637
638   if (mp4vparse->intra_frame)
639     GST_BUFFER_FLAG_UNSET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
640   else
641     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
642
643   if (!mp4vparse->vop_coded)    /* buffer without VOP_coded has no data */
644     GST_BUFFER_DURATION (buffer) = 0;
645
646   if (G_UNLIKELY (mp4vparse->drop && !mp4vparse->config)) {
647     GST_LOG_OBJECT (mp4vparse, "dropping frame as no config yet");
648     return GST_BASE_PARSE_FLOW_DROPPED;
649   } else
650     return GST_FLOW_OK;
651 }
652
653 static GstEvent *
654 check_pending_key_unit_event (GstEvent * pending_event, GstSegment * segment,
655     GstClockTime timestamp, guint flags, GstClockTime pending_key_unit_ts)
656 {
657   GstClockTime running_time, stream_time;
658   gboolean all_headers;
659   guint count;
660   GstEvent *event = NULL;
661
662   g_return_val_if_fail (segment != NULL, NULL);
663
664   if (pending_event == NULL)
665     goto out;
666
667   if (GST_CLOCK_TIME_IS_VALID (pending_key_unit_ts) &&
668       timestamp == GST_CLOCK_TIME_NONE)
669     goto out;
670
671   running_time = gst_segment_to_running_time (segment,
672       GST_FORMAT_TIME, timestamp);
673
674   GST_INFO ("now %" GST_TIME_FORMAT " wanted %" GST_TIME_FORMAT,
675       GST_TIME_ARGS (running_time), GST_TIME_ARGS (pending_key_unit_ts));
676   if (GST_CLOCK_TIME_IS_VALID (pending_key_unit_ts) &&
677       running_time < pending_key_unit_ts)
678     goto out;
679
680   if (flags & GST_BUFFER_FLAG_DELTA_UNIT) {
681     GST_DEBUG ("pending force key unit, waiting for keyframe");
682     goto out;
683   }
684
685   stream_time = gst_segment_to_stream_time (segment,
686       GST_FORMAT_TIME, timestamp);
687
688   gst_video_event_parse_upstream_force_key_unit (pending_event,
689       NULL, &all_headers, &count);
690
691   event =
692       gst_video_event_new_downstream_force_key_unit (timestamp, stream_time,
693       running_time, all_headers, count);
694   gst_event_set_seqnum (event, gst_event_get_seqnum (pending_event));
695
696 out:
697   return event;
698 }
699
700 static void
701 gst_mpeg4vparse_prepare_key_unit (GstMpeg4VParse * parse, GstEvent * event)
702 {
703   GstClockTime running_time;
704   guint count;
705
706   parse->pending_key_unit_ts = GST_CLOCK_TIME_NONE;
707   gst_event_replace (&parse->force_key_unit_event, NULL);
708
709   gst_video_event_parse_downstream_force_key_unit (event,
710       NULL, NULL, &running_time, NULL, &count);
711
712   GST_INFO_OBJECT (parse, "pushing downstream force-key-unit event %d "
713       "%" GST_TIME_FORMAT " count %d", gst_event_get_seqnum (event),
714       GST_TIME_ARGS (running_time), count);
715   gst_pad_push_event (GST_BASE_PARSE_SRC_PAD (parse), event);
716 }
717
718
719 static GstFlowReturn
720 gst_mpeg4vparse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
721 {
722   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
723   GstBuffer *buffer = frame->buffer;
724   gboolean push_codec = FALSE;
725   GstEvent *event = NULL;
726
727   if ((event = check_pending_key_unit_event (mp4vparse->force_key_unit_event,
728               &parse->segment, GST_BUFFER_TIMESTAMP (buffer),
729               GST_BUFFER_FLAGS (buffer), mp4vparse->pending_key_unit_ts))) {
730     gst_mpeg4vparse_prepare_key_unit (mp4vparse, event);
731     push_codec = TRUE;
732   }
733
734   /* periodic config sending */
735   if (mp4vparse->interval > 0 || push_codec) {
736     GstClockTime timestamp = GST_BUFFER_TIMESTAMP (buffer);
737     guint64 diff;
738
739     /* init */
740     if (!GST_CLOCK_TIME_IS_VALID (mp4vparse->last_report)) {
741       mp4vparse->last_report = timestamp;
742     }
743
744     if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
745       if (timestamp > mp4vparse->last_report)
746         diff = timestamp - mp4vparse->last_report;
747       else
748         diff = 0;
749
750       GST_LOG_OBJECT (mp4vparse,
751           "now %" GST_TIME_FORMAT ", last config %" GST_TIME_FORMAT,
752           GST_TIME_ARGS (timestamp), GST_TIME_ARGS (mp4vparse->last_report));
753
754       GST_LOG_OBJECT (mp4vparse,
755           "interval since last config %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
756
757       if (GST_TIME_AS_SECONDS (diff) >= mp4vparse->interval || push_codec) {
758         GstMapInfo cmap;
759         gsize csize;
760         gboolean diffconf;
761
762         /* we need to send config now first */
763         GST_INFO_OBJECT (parse, "inserting config in stream");
764         gst_buffer_map (mp4vparse->config, &cmap, GST_MAP_READ);
765         diffconf = (gst_buffer_get_size (buffer) < cmap.size)
766             || gst_buffer_memcmp (buffer, 0, cmap.data, cmap.size);
767         csize = cmap.size;
768         gst_buffer_unmap (mp4vparse->config, &cmap);
769
770         /* avoid inserting duplicate config */
771         if (diffconf) {
772           GstBuffer *superbuf;
773
774           /* insert header */
775           superbuf =
776               gst_buffer_append (gst_buffer_ref (mp4vparse->config),
777               gst_buffer_ref (buffer));
778           gst_buffer_copy_into (superbuf, buffer, GST_BUFFER_COPY_METADATA, 0,
779               csize);
780           gst_buffer_replace (&frame->out_buffer, superbuf);
781           gst_buffer_unref (superbuf);
782         } else {
783           GST_INFO_OBJECT (parse, "... but avoiding duplication");
784         }
785
786         if (G_UNLIKELY (timestamp != -1)) {
787           mp4vparse->last_report = timestamp;
788         }
789       }
790     }
791   }
792
793   return GST_FLOW_OK;
794 }
795
796 static gboolean
797 gst_mpeg4vparse_set_caps (GstBaseParse * parse, GstCaps * caps)
798 {
799   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
800   GstStructure *s;
801   const GValue *value;
802   GstBuffer *buf;
803   GstMapInfo map;
804   guint8 *data;
805   gsize size;
806
807   GstMpeg4Packet packet;
808   GstMpeg4ParseResult res;
809
810   GST_DEBUG_OBJECT (parse, "setcaps called with %" GST_PTR_FORMAT, caps);
811
812   s = gst_caps_get_structure (caps, 0);
813
814   if ((value = gst_structure_get_value (s, "codec_data")) != NULL
815       && (buf = gst_value_get_buffer (value))) {
816     /* best possible parse attempt,
817      * src caps are based on sink caps so it will end up in there
818      * whether sucessful or not */
819     gst_buffer_map (buf, &map, GST_MAP_READ);
820     data = map.data;
821     size = map.size;
822     res = gst_mpeg4_parse (&packet, FALSE, NULL, data, 0, size);
823
824     while (res == GST_MPEG4_PARSER_OK || res == GST_MPEG4_PARSER_NO_PACKET_END) {
825
826       if (packet.type >= GST_MPEG4_VIDEO_LAYER_FIRST &&
827           packet.type <= GST_MPEG4_VIDEO_LAYER_LAST)
828         mp4vparse->vol_offset = packet.offset;
829
830       else if (packet.type == GST_MPEG4_VISUAL_OBJ) {
831         gst_mpeg4_parse_visual_object (&mp4vparse->vo, NULL,
832             data + packet.offset, MIN (packet.size, size));
833         mp4vparse->vo_found = TRUE;
834       }
835
836       res = gst_mpeg4_parse (&packet, FALSE, NULL, data, packet.offset, size);
837     }
838
839     /* And take it as config */
840     gst_mpeg4vparse_process_config (mp4vparse, data, 3, size);
841     gst_buffer_unmap (buf, &map);
842     gst_mpeg4vparse_reset_frame (mp4vparse);
843   }
844
845   /* let's not interfere and accept regardless of config parsing success */
846   return TRUE;
847 }
848
849
850 static GstCaps *
851 gst_mpeg4vparse_get_caps (GstBaseParse * parse, GstCaps * filter)
852 {
853   GstCaps *peercaps, *templ;
854   GstCaps *res;
855
856   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
857   peercaps = gst_pad_get_allowed_caps (GST_BASE_PARSE_SRC_PAD (parse));
858
859   if (peercaps) {
860     guint i, n;
861
862     /* Remove the parsed field */
863     peercaps = gst_caps_make_writable (peercaps);
864     n = gst_caps_get_size (peercaps);
865     for (i = 0; i < n; i++) {
866       GstStructure *s = gst_caps_get_structure (peercaps, i);
867
868       gst_structure_remove_field (s, "parsed");
869     }
870
871     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
872     gst_caps_unref (peercaps);
873
874     /* Append the template caps because we still want to accept
875      * caps without any fields in the case upstream does not
876      * know anything.
877      */
878     gst_caps_append (res, templ);
879   } else {
880     res = templ;
881   }
882
883   if (filter) {
884     GstCaps *tmp = gst_caps_intersect_full (res, filter,
885         GST_CAPS_INTERSECT_FIRST);
886     gst_caps_unref (res);
887     res = tmp;
888   }
889
890
891   return res;
892 }
893
894 static gboolean
895 gst_mpeg4vparse_event (GstBaseParse * parse, GstEvent * event)
896 {
897   gboolean res;
898   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
899
900   switch (GST_EVENT_TYPE (event)) {
901     case GST_EVENT_CUSTOM_DOWNSTREAM:
902     {
903       GstClockTime timestamp, stream_time, running_time;
904       gboolean all_headers;
905       guint count;
906
907       if (gst_video_event_is_force_key_unit (event)) {
908         gst_video_event_parse_downstream_force_key_unit (event,
909             &timestamp, &stream_time, &running_time, &all_headers, &count);
910
911         GST_INFO_OBJECT (mp4vparse, "received downstream force key unit event, "
912             "seqnum %d running_time %" GST_TIME_FORMAT
913             " all_headers %d count %d", gst_event_get_seqnum (event),
914             GST_TIME_ARGS (running_time), all_headers, count);
915
916         if (mp4vparse->force_key_unit_event) {
917           GST_INFO_OBJECT (mp4vparse, "ignoring force key unit event "
918               "as one is already queued");
919         } else {
920           mp4vparse->pending_key_unit_ts = running_time;
921           gst_event_replace (&mp4vparse->force_key_unit_event, event);
922         }
923         gst_event_unref (event);
924         res = TRUE;
925       } else {
926         res = GST_BASE_PARSE_CLASS (parent_class)->sink_event (parse, event);
927       }
928       break;
929     }
930     default:
931       res = GST_BASE_PARSE_CLASS (parent_class)->sink_event (parse, event);
932       break;
933   }
934   return res;
935 }
936
937 static gboolean
938 gst_mpeg4vparse_src_event (GstBaseParse * parse, GstEvent * event)
939 {
940   gboolean res;
941   GstMpeg4VParse *mp4vparse = GST_MPEG4VIDEO_PARSE (parse);
942
943   switch (GST_EVENT_TYPE (event)) {
944     case GST_EVENT_CUSTOM_UPSTREAM:
945     {
946       GstClockTime running_time;
947       gboolean all_headers;
948       guint count;
949
950       if (gst_video_event_is_force_key_unit (event)) {
951         gst_video_event_parse_upstream_force_key_unit (event,
952             &running_time, &all_headers, &count);
953
954         GST_INFO_OBJECT (mp4vparse, "received upstream force-key-unit event, "
955             "seqnum %d running_time %" GST_TIME_FORMAT
956             " all_headers %d count %d", gst_event_get_seqnum (event),
957             GST_TIME_ARGS (running_time), all_headers, count);
958
959         if (all_headers) {
960           mp4vparse->pending_key_unit_ts = running_time;
961           gst_event_replace (&mp4vparse->force_key_unit_event, event);
962         }
963       }
964       res = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
965       break;
966     }
967     default:
968       res = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
969       break;
970   }
971
972   return res;
973 }