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