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