mpeg2decoder: fail early if no input caps have been provided
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / codecs / gstmpeg2decoder.c
1 /* GStreamer
2  * Copyright (C) 2020 Intel Corporation
3  *     Author: He Junyan <junyan.he@intel.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 /**
21  * SECTION:gstmpeg2decoder
22  * @title: GstMpeg2Decoder
23  * @short_description: Base class to implement stateless MPEG2 decoders
24  * @sources:
25  * - gstmpeg2picture.h
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #include <config.h>
30 #endif
31
32 #include <gst/base/base.h>
33 #include "gstmpeg2decoder.h"
34
35 GST_DEBUG_CATEGORY (gst_mpeg2_decoder_debug);
36 #define GST_CAT_DEFAULT gst_mpeg2_decoder_debug
37
38 /* ------------------------------------------------------------------------- */
39 /* --- PTS Generator                                                     --- */
40 /* ------------------------------------------------------------------------- */
41 typedef struct _PTSGenerator PTSGenerator;
42 struct _PTSGenerator
43 {
44   /* The current GOP PTS */
45   GstClockTime gop_pts;
46   /* Max picture PTS */
47   GstClockTime max_pts;
48   /* Absolute GOP TSN */
49   guint gop_tsn;
50   /* Max picture TSN, relative to last GOP TSN */
51   guint max_tsn;
52   /* How many times TSN overflowed since GOP */
53   guint ovl_tsn;
54   /* Last picture TSN */
55   guint lst_tsn;
56   guint fps_n;
57   guint fps_d;
58 };
59
60 static void
61 _pts_init (PTSGenerator * tsg)
62 {
63   tsg->gop_pts = GST_CLOCK_TIME_NONE;
64   tsg->max_pts = GST_CLOCK_TIME_NONE;
65   tsg->gop_tsn = 0;
66   tsg->max_tsn = 0;
67   tsg->ovl_tsn = 0;
68   tsg->lst_tsn = 0;
69   tsg->fps_n = 0;
70   tsg->fps_d = 0;
71 }
72
73 static inline GstClockTime
74 _pts_get_duration (PTSGenerator * tsg, guint num_frames)
75 {
76   return gst_util_uint64_scale (num_frames, GST_SECOND * tsg->fps_d,
77       tsg->fps_n);
78 }
79
80 static inline guint
81 _pts_get_poc (PTSGenerator * tsg)
82 {
83   return tsg->gop_tsn + tsg->ovl_tsn * 1024 + tsg->lst_tsn;
84 }
85
86 static void
87 _pts_set_framerate (PTSGenerator * tsg, guint fps_n, guint fps_d)
88 {
89   tsg->fps_n = fps_n;
90   tsg->fps_d = fps_d;
91 }
92
93 static void
94 _pts_sync (PTSGenerator * tsg, GstClockTime gop_pts)
95 {
96   guint gop_tsn;
97
98   if (!GST_CLOCK_TIME_IS_VALID (gop_pts) ||
99       (GST_CLOCK_TIME_IS_VALID (tsg->max_pts) && tsg->max_pts >= gop_pts)) {
100     /* Invalid GOP PTS, interpolate from the last known picture PTS */
101     if (GST_CLOCK_TIME_IS_VALID (tsg->max_pts)) {
102       gop_pts = tsg->max_pts + _pts_get_duration (tsg, 1);
103       gop_tsn = tsg->gop_tsn + tsg->ovl_tsn * 1024 + tsg->max_tsn + 1;
104     } else {
105       gop_pts = 0;
106       gop_tsn = 0;
107     }
108   } else {
109     /* Interpolate GOP TSN from this valid PTS */
110     if (GST_CLOCK_TIME_IS_VALID (tsg->gop_pts))
111       gop_tsn = tsg->gop_tsn + gst_util_uint64_scale (gop_pts - tsg->gop_pts +
112           _pts_get_duration (tsg, 1) - 1, tsg->fps_n, GST_SECOND * tsg->fps_d);
113     else
114       gop_tsn = 0;
115   }
116
117   tsg->gop_pts = gop_pts;
118   tsg->gop_tsn = gop_tsn;
119   tsg->max_tsn = 0;
120   tsg->ovl_tsn = 0;
121   tsg->lst_tsn = 0;
122 }
123
124 static GstClockTime
125 _pts_eval (PTSGenerator * tsg, GstClockTime pic_pts, guint pic_tsn)
126 {
127   GstClockTime pts;
128
129   if (!GST_CLOCK_TIME_IS_VALID (tsg->gop_pts))
130     tsg->gop_pts = _pts_get_duration (tsg, pic_tsn);
131
132   pts = pic_pts;
133   if (!GST_CLOCK_TIME_IS_VALID (pts))
134     pts = tsg->gop_pts + _pts_get_duration (tsg, tsg->ovl_tsn * 1024 + pic_tsn);
135   else if (pts == tsg->gop_pts) {
136     /* The picture following the GOP header shall be an I-frame.
137        So we can compensate for the GOP start time from here */
138     tsg->gop_pts -= _pts_get_duration (tsg, pic_tsn);
139   }
140
141   if (!GST_CLOCK_TIME_IS_VALID (tsg->max_pts) || tsg->max_pts < pts)
142     tsg->max_pts = pts;
143
144   if (tsg->max_tsn < pic_tsn)
145     tsg->max_tsn = pic_tsn;
146   else if (tsg->max_tsn == 1023 && pic_tsn < tsg->lst_tsn) {    /* TSN wrapped */
147     tsg->max_tsn = pic_tsn;
148     tsg->ovl_tsn++;
149   }
150   tsg->lst_tsn = pic_tsn;
151
152   return pts;
153 }
154
155 static inline gboolean
156 _seq_hdr_is_valid (GstMpegVideoSequenceHdr * hdr)
157 {
158   return hdr->width > 0 && hdr->height > 0;
159 }
160
161 #define SEQ_HDR_INIT (GstMpegVideoSequenceHdr) { 0, }
162
163 static inline gboolean
164 _seq_ext_is_valid (GstMpegVideoSequenceExt * ext)
165 {
166   return ext->profile >= GST_MPEG_VIDEO_PROFILE_422
167       && ext->profile <= GST_MPEG_VIDEO_PROFILE_SIMPLE;
168 }
169
170 #define SEQ_EXT_INIT (GstMpegVideoSequenceExt) { 0xff, 0, }
171
172 static inline gboolean
173 _seq_display_ext_is_valid (GstMpegVideoSequenceDisplayExt * ext)
174 {
175   return ext->video_format != 0xff;
176 }
177
178 #define SEQ_DISPLAY_EXT_INIT (GstMpegVideoSequenceDisplayExt) { 0xff, 0, }
179
180 static inline gboolean
181 _seq_scalable_ext_is_valid (GstMpegVideoSequenceScalableExt * ext)
182 {
183   return ext->scalable_mode != 0xff;
184 }
185
186 #define SEQ_SCALABLE_EXT_INIT (GstMpegVideoSequenceScalableExt) { 0xff, 0, }
187
188 static inline gboolean
189 _quant_matrix_ext_is_valid (GstMpegVideoQuantMatrixExt * ext)
190 {
191   return ext->load_intra_quantiser_matrix != 0xff;
192 }
193
194 #define QUANT_MATRIX_EXT_INIT (GstMpegVideoQuantMatrixExt) { 0xff, { 0, } }
195
196 static inline gboolean
197 _pic_hdr_is_valid (GstMpegVideoPictureHdr * hdr)
198 {
199   return hdr->tsn != 0xffff;
200 }
201
202 #define PIC_HDR_INIT (GstMpegVideoPictureHdr) { 0xffff, 0, }
203
204 static inline gboolean
205 _pic_hdr_ext_is_valid (GstMpegVideoPictureExt * ext)
206 {
207   return ext->f_code[0][0] != 0xff;
208 }
209
210 #define PIC_HDR_EXT_INIT                                        \
211     (GstMpegVideoPictureExt) { { { 0xff, 0, }, { 0, } }, 0, }
212
213 typedef enum
214 {
215   GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR = 1 << 0,
216   GST_MPEG2_DECODER_STATE_GOT_SEQ_EXT = 1 << 1,
217   GST_MPEG2_DECODER_STATE_GOT_PIC_HDR = 1 << 2,
218   GST_MPEG2_DECODER_STATE_GOT_PIC_EXT = 1 << 3,
219   GST_MPEG2_DECODER_STATE_GOT_SLICE = 1 << 4,
220
221   GST_MPEG2_DECODER_STATE_VALID_SEQ_HEADERS =
222       (GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR |
223       GST_MPEG2_DECODER_STATE_GOT_SEQ_EXT),
224   GST_MPEG2_DECODER_STATE_VALID_PIC_HEADERS =
225       (GST_MPEG2_DECODER_STATE_GOT_PIC_HDR |
226       GST_MPEG2_DECODER_STATE_GOT_PIC_EXT),
227   GST_MPEG2_DECODER_STATE_VALID_PICTURE =
228       (GST_MPEG2_DECODER_STATE_VALID_SEQ_HEADERS |
229       GST_MPEG2_DECODER_STATE_VALID_PIC_HEADERS |
230       GST_MPEG2_DECODER_STATE_GOT_SLICE)
231 } GstMpeg2DecoderState;
232
233 struct _GstMpeg2DecoderPrivate
234 {
235   gint width;
236   gint height;
237   gint display_width;
238   gint display_height;
239   GstMpegVideoProfile profile;
240   gboolean progressive;
241
242   GstMpegVideoSequenceHdr seq_hdr;
243   GstMpegVideoSequenceExt seq_ext;
244   GstMpegVideoSequenceDisplayExt seq_display_ext;
245   GstMpegVideoSequenceScalableExt seq_scalable_ext;
246
247   /* some sequence info changed after last new_sequence () */
248   gboolean seq_changed;
249   /* whether we need to drain before new_sequence () */
250   gboolean need_to_drain;
251   GstMpegVideoGop gop;
252   GstMpegVideoQuantMatrixExt quant_matrix;
253   GstMpegVideoPictureHdr pic_hdr;
254   GstMpegVideoPictureExt pic_ext;
255
256   GstMpeg2Dpb *dpb;
257   GstMpeg2DecoderState state;
258   PTSGenerator tsg;
259   GstClockTime current_pts;
260
261   GstMpeg2Picture *current_picture;
262   GstVideoCodecFrame *current_frame;
263   GstMpeg2Picture *first_field;
264
265   guint preferred_output_delay;
266   /* for delayed output */
267   GstQueueArray *output_queue;
268   /* used for low-latency vs. high throughput mode decision */
269   gboolean is_live;
270
271   gboolean input_state_changed;
272 };
273
274 #define UPDATE_FLOW_RETURN(ret,new_ret) G_STMT_START { \
275   if (*(ret) == GST_FLOW_OK) \
276     *(ret) = new_ret; \
277 } G_STMT_END
278
279 typedef struct
280 {
281   GstVideoCodecFrame *frame;
282   GstMpeg2Picture *picture;
283   GstMpeg2Decoder *self;
284 } GstMpeg2DecoderOutputFrame;
285
286
287 #define parent_class gst_mpeg2_decoder_parent_class
288 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GstMpeg2Decoder, gst_mpeg2_decoder,
289     GST_TYPE_VIDEO_DECODER,
290     G_ADD_PRIVATE (GstMpeg2Decoder);
291     GST_DEBUG_CATEGORY_INIT (gst_mpeg2_decoder_debug, "mpeg2decoder", 0,
292         "MPEG2 Video Decoder"));
293
294 static gboolean gst_mpeg2_decoder_start (GstVideoDecoder * decoder);
295 static gboolean gst_mpeg2_decoder_stop (GstVideoDecoder * decoder);
296 static gboolean gst_mpeg2_decoder_set_format (GstVideoDecoder * decoder,
297     GstVideoCodecState * state);
298 static gboolean gst_mpeg2_decoder_negotiate (GstVideoDecoder * decoder);
299 static GstFlowReturn gst_mpeg2_decoder_finish (GstVideoDecoder * decoder);
300 static gboolean gst_mpeg2_decoder_flush (GstVideoDecoder * decoder);
301 static GstFlowReturn gst_mpeg2_decoder_drain (GstVideoDecoder * decoder);
302 static GstFlowReturn gst_mpeg2_decoder_handle_frame (GstVideoDecoder * decoder,
303     GstVideoCodecFrame * frame);
304 static void gst_mpeg2_decoder_do_output_picture (GstMpeg2Decoder * self,
305     GstMpeg2Picture * picture, GstFlowReturn * ret);
306 static void gst_mpeg2_decoder_clear_output_frame (GstMpeg2DecoderOutputFrame *
307     output_frame);
308 static void gst_mpeg2_decoder_drain_output_queue (GstMpeg2Decoder *
309     self, guint num, GstFlowReturn * ret);
310
311
312 static void
313 gst_mpeg2_decoder_class_init (GstMpeg2DecoderClass * klass)
314 {
315   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (klass);
316
317   decoder_class->start = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_start);
318   decoder_class->stop = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_stop);
319   decoder_class->set_format = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_set_format);
320   decoder_class->negotiate = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_negotiate);
321   decoder_class->finish = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_finish);
322   decoder_class->flush = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_flush);
323   decoder_class->drain = GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_drain);
324   decoder_class->handle_frame =
325       GST_DEBUG_FUNCPTR (gst_mpeg2_decoder_handle_frame);
326 }
327
328 static void
329 gst_mpeg2_decoder_init (GstMpeg2Decoder * self)
330 {
331   gst_video_decoder_set_packetized (GST_VIDEO_DECODER (self), TRUE);
332   gst_video_decoder_set_needs_format (GST_VIDEO_DECODER (self), TRUE);
333
334   self->priv = gst_mpeg2_decoder_get_instance_private (self);
335
336   self->priv->seq_hdr = SEQ_HDR_INIT;
337   self->priv->seq_ext = SEQ_EXT_INIT;
338   self->priv->seq_display_ext = SEQ_DISPLAY_EXT_INIT;
339   self->priv->seq_scalable_ext = SEQ_SCALABLE_EXT_INIT;
340   self->priv->quant_matrix = QUANT_MATRIX_EXT_INIT;
341   self->priv->pic_hdr = PIC_HDR_INIT;
342   self->priv->pic_ext = PIC_HDR_EXT_INIT;
343 }
344
345 static gboolean
346 gst_mpeg2_decoder_start (GstVideoDecoder * decoder)
347 {
348   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
349   GstMpeg2DecoderPrivate *priv = self->priv;
350
351   _pts_init (&priv->tsg);
352   priv->dpb = gst_mpeg2_dpb_new ();
353   priv->profile = -1;
354   priv->progressive = TRUE;
355
356   priv->output_queue =
357       gst_queue_array_new_for_struct (sizeof (GstMpeg2DecoderOutputFrame), 1);
358   gst_queue_array_set_clear_func (priv->output_queue,
359       (GDestroyNotify) gst_mpeg2_decoder_clear_output_frame);
360
361   return TRUE;
362 }
363
364 static gboolean
365 gst_mpeg2_decoder_stop (GstVideoDecoder * decoder)
366 {
367   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
368   GstMpeg2DecoderPrivate *priv = self->priv;
369
370   g_clear_pointer (&self->input_state, gst_video_codec_state_unref);
371   g_clear_pointer (&priv->dpb, gst_mpeg2_dpb_free);
372   gst_queue_array_free (priv->output_queue);
373
374   return TRUE;
375 }
376
377 static gboolean
378 gst_mpeg2_decoder_set_format (GstVideoDecoder * decoder,
379     GstVideoCodecState * state)
380 {
381   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
382   GstMpeg2DecoderPrivate *priv = self->priv;
383   GstQuery *query;
384
385   GST_DEBUG_OBJECT (decoder, "Set format");
386
387   priv->input_state_changed = TRUE;
388
389   if (self->input_state)
390     gst_video_codec_state_unref (self->input_state);
391
392   self->input_state = gst_video_codec_state_ref (state);
393
394   priv->width = GST_VIDEO_INFO_WIDTH (&state->info);
395   priv->height = GST_VIDEO_INFO_HEIGHT (&state->info);
396
397   query = gst_query_new_latency ();
398   if (gst_pad_peer_query (GST_VIDEO_DECODER_SINK_PAD (self), query))
399     gst_query_parse_latency (query, &priv->is_live, NULL, NULL);
400   gst_query_unref (query);
401
402   return TRUE;
403 }
404
405 static gboolean
406 gst_mpeg2_decoder_negotiate (GstVideoDecoder * decoder)
407 {
408   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
409
410   /* output state must be updated by subclass using new input state already */
411   self->priv->input_state_changed = FALSE;
412
413   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
414 }
415
416 static GstFlowReturn
417 gst_mpeg2_decoder_drain (GstVideoDecoder * decoder)
418 {
419   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
420   GstMpeg2DecoderPrivate *priv = self->priv;
421   GstMpeg2Picture *picture;
422   GstFlowReturn ret = GST_FLOW_OK;
423
424   while ((picture = gst_mpeg2_dpb_bump (priv->dpb)) != NULL) {
425     gst_mpeg2_decoder_do_output_picture (self, picture, &ret);
426   }
427
428   gst_mpeg2_decoder_drain_output_queue (self, 0, &ret);
429   gst_queue_array_clear (priv->output_queue);
430   gst_mpeg2_dpb_clear (priv->dpb);
431
432   return ret;
433 }
434
435 static GstFlowReturn
436 gst_mpeg2_decoder_finish (GstVideoDecoder * decoder)
437 {
438   return gst_mpeg2_decoder_drain (decoder);
439 }
440
441 static gboolean
442 gst_mpeg2_decoder_flush (GstVideoDecoder * decoder)
443 {
444   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
445   GstMpeg2DecoderPrivate *priv = self->priv;
446
447   gst_mpeg2_dpb_clear (priv->dpb);
448   gst_queue_array_clear (priv->output_queue);
449   priv->state &= GST_MPEG2_DECODER_STATE_VALID_SEQ_HEADERS;
450   priv->pic_hdr = PIC_HDR_INIT;
451   priv->pic_ext = PIC_HDR_EXT_INIT;
452
453   return TRUE;
454 }
455
456 static inline gboolean
457 _is_valid_state (GstMpeg2Decoder * decoder, GstMpeg2DecoderState state)
458 {
459   GstMpeg2DecoderPrivate *priv = decoder->priv;
460
461   return (priv->state & state) == state;
462 }
463
464 static void
465 gst_mpeg2_decoder_set_latency (GstMpeg2Decoder * decoder)
466 {
467   GstCaps *caps;
468   GstClockTime min, max;
469   GstMpeg2DecoderPrivate *priv = decoder->priv;
470   GstStructure *structure;
471   gint fps_d = 1, fps_n = 0;
472
473   if (priv->tsg.fps_d > 0 && priv->tsg.fps_n > 0) {
474     fps_n = priv->tsg.fps_n;
475     fps_d = priv->tsg.fps_d;
476   } else {
477     caps = gst_pad_get_current_caps (GST_VIDEO_DECODER_SINK_PAD (decoder));
478     if (caps) {
479       structure = gst_caps_get_structure (caps, 0);
480       if (gst_structure_get_fraction (structure, "framerate", &fps_n, &fps_d)) {
481         if (fps_n == 0) {
482           /* variable framerate: see if we have a max-framerate */
483           gst_structure_get_fraction (structure, "max-framerate", &fps_n,
484               &fps_d);
485         }
486       }
487       gst_caps_unref (caps);
488     }
489   }
490
491   /* if no fps or variable, then 25/1 */
492   if (fps_n == 0) {
493     fps_n = 25;
494     fps_d = 1;
495   }
496
497   max = gst_util_uint64_scale (2 * GST_SECOND, fps_d, fps_n);
498   min = gst_util_uint64_scale (1 * GST_SECOND, fps_d, fps_n);
499
500   GST_LOG_OBJECT (decoder,
501       "latency min %" G_GUINT64_FORMAT " max %" G_GUINT64_FORMAT, min, max);
502
503   gst_video_decoder_set_latency (GST_VIDEO_DECODER (decoder), min, max);
504 }
505
506 static GstFlowReturn
507 gst_mpeg2_decoder_handle_sequence (GstMpeg2Decoder * decoder,
508     GstMpegVideoPacket * packet)
509 {
510   GstMpeg2DecoderPrivate *priv = decoder->priv;
511   GstMpegVideoSequenceHdr seq_hdr = { 0, };
512
513   if (!gst_mpeg_video_packet_parse_sequence_header (packet, &seq_hdr)) {
514     GST_ERROR_OBJECT (decoder, "failed to parse sequence header");
515     return GST_FLOW_ERROR;
516   }
517
518   /* 6.1.1.6 Sequence header
519      The quantisation matrices may be redefined each time that a sequence
520      header occurs in the bitstream */
521   priv->quant_matrix = QUANT_MATRIX_EXT_INIT;
522
523   if (_seq_hdr_is_valid (&priv->seq_hdr) &&
524       memcmp (&priv->seq_hdr, &seq_hdr, sizeof (seq_hdr)) == 0)
525     return GST_FLOW_OK;
526
527   priv->seq_ext = SEQ_EXT_INIT;
528   priv->seq_display_ext = SEQ_DISPLAY_EXT_INIT;
529   priv->seq_scalable_ext = SEQ_SCALABLE_EXT_INIT;
530   priv->pic_ext = PIC_HDR_EXT_INIT;
531
532   priv->seq_hdr = seq_hdr;
533   priv->seq_changed = TRUE;
534
535   if (priv->width != seq_hdr.width || priv->height != seq_hdr.height) {
536     priv->need_to_drain = TRUE;
537     priv->width = seq_hdr.width;
538     priv->height = seq_hdr.height;
539   }
540   priv->display_width = priv->width;
541   priv->display_height = priv->height;
542
543   _pts_set_framerate (&priv->tsg, seq_hdr.fps_n, seq_hdr.fps_d);
544
545   gst_mpeg2_decoder_set_latency (decoder);
546
547   priv->state = GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR;
548
549   return GST_FLOW_OK;
550 }
551
552 static GstFlowReturn
553 gst_mpeg2_decoder_handle_sequence_ext (GstMpeg2Decoder * decoder,
554     GstMpegVideoPacket * packet)
555 {
556   GstMpeg2DecoderPrivate *priv = decoder->priv;
557   GstMpegVideoSequenceExt seq_ext = { 0, };
558   guint width, height;
559
560   if (!_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR)) {
561     GST_ERROR_OBJECT (decoder, "no sequence before parsing sequence-extension");
562     return GST_FLOW_ERROR;
563   }
564
565   if (!gst_mpeg_video_packet_parse_sequence_extension (packet, &seq_ext)) {
566     GST_ERROR_OBJECT (decoder, "failed to parse sequence-extension");
567     return GST_FLOW_ERROR;
568   }
569
570   if (_seq_ext_is_valid (&priv->seq_ext) &&
571       memcmp (&priv->seq_ext, &seq_ext, sizeof (seq_ext)) == 0)
572     return GST_FLOW_OK;
573
574   priv->seq_ext = seq_ext;
575   priv->seq_changed = TRUE;
576
577   if (seq_ext.fps_n_ext && seq_ext.fps_d_ext) {
578     guint fps_n = priv->tsg.fps_n;
579     guint fps_d = priv->tsg.fps_d;
580     fps_n *= seq_ext.fps_n_ext + 1;
581     fps_d *= seq_ext.fps_d_ext + 1;
582     _pts_set_framerate (&priv->tsg, fps_n, fps_d);
583     gst_mpeg2_decoder_set_latency (decoder);
584   }
585
586   width = (priv->width & 0x0fff) | ((guint32) seq_ext.horiz_size_ext << 12);
587   height = (priv->height & 0x0fff) | ((guint32) seq_ext.vert_size_ext << 12);
588
589   if (priv->width != width || priv->height != height ||
590       priv->profile != seq_ext.profile ||
591       priv->progressive != seq_ext.progressive) {
592     priv->need_to_drain = TRUE;
593     priv->width = width;
594     priv->height = height;
595     priv->profile = seq_ext.profile;
596     priv->progressive = seq_ext.progressive;
597
598     GST_DEBUG_OBJECT (decoder, "video resolution %ux%u, profile %d,"
599         " progressive %d", priv->width, priv->height, priv->profile,
600         priv->progressive);
601   }
602
603   priv->state |= GST_MPEG2_DECODER_STATE_GOT_SEQ_EXT;
604
605   return GST_FLOW_OK;
606 }
607
608 static GstFlowReturn
609 gst_mpeg2_decoder_handle_sequence_display_ext (GstMpeg2Decoder * decoder,
610     GstMpegVideoPacket * packet)
611 {
612   GstMpeg2DecoderPrivate *priv = decoder->priv;
613   GstMpegVideoSequenceDisplayExt seq_display_ext = { 0, };
614
615   if (!_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR)) {
616     GST_ERROR_OBJECT (decoder,
617         "no sequence before parsing sequence-display-extension");
618     return GST_FLOW_ERROR;
619   }
620
621   if (!gst_mpeg_video_packet_parse_sequence_display_extension (packet,
622           &seq_display_ext)) {
623     GST_ERROR_OBJECT (decoder, "failed to parse sequence-display-extension");
624     return GST_FLOW_ERROR;
625   }
626
627   if (_seq_display_ext_is_valid (&priv->seq_display_ext) &&
628       memcmp (&priv->seq_display_ext, &seq_display_ext,
629           sizeof (seq_display_ext)) == 0)
630     return GST_FLOW_OK;
631
632   priv->seq_display_ext = seq_display_ext;
633   priv->seq_changed = TRUE;
634
635   priv->display_width = seq_display_ext.display_horizontal_size;
636   priv->display_height = seq_display_ext.display_vertical_size;
637
638   return GST_FLOW_OK;
639 }
640
641 static GstFlowReturn
642 gst_mpeg2_decoder_handle_sequence_scalable_ext (GstMpeg2Decoder * decoder,
643     GstMpegVideoPacket * packet)
644 {
645   GstMpeg2DecoderPrivate *priv = decoder->priv;
646   GstMpegVideoSequenceScalableExt seq_scalable_ext = { 0, };
647
648   if (!_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR)) {
649     GST_ERROR_OBJECT (decoder,
650         "no sequence before parsing sequence-scalable-extension");
651     return GST_FLOW_ERROR;
652   }
653
654   if (!gst_mpeg_video_packet_parse_sequence_scalable_extension (packet,
655           &seq_scalable_ext)) {
656     GST_ERROR_OBJECT (decoder, "failed to parse sequence-scalable-extension");
657     return GST_FLOW_ERROR;
658   }
659
660   if (_seq_scalable_ext_is_valid (&priv->seq_scalable_ext) &&
661       memcmp (&priv->seq_scalable_ext, &seq_scalable_ext,
662           sizeof (seq_scalable_ext)) == 0)
663     return GST_FLOW_OK;
664
665   priv->seq_scalable_ext = seq_scalable_ext;
666   priv->seq_changed = TRUE;
667
668   return GST_FLOW_OK;
669 }
670
671 static GstFlowReturn
672 gst_mpeg2_decoder_handle_quant_matrix_ext (GstMpeg2Decoder * decoder,
673     GstMpegVideoPacket * packet)
674 {
675   GstMpeg2DecoderPrivate *priv = decoder->priv;
676   GstMpegVideoQuantMatrixExt matrix_ext = { 0, };
677
678   if (!gst_mpeg_video_packet_parse_quant_matrix_extension (packet, &matrix_ext)) {
679     GST_ERROR_OBJECT (decoder, "failed to parse sequence-scalable-extension");
680     return GST_FLOW_ERROR;
681   }
682
683   priv->quant_matrix = matrix_ext;
684
685   return GST_FLOW_OK;
686 }
687
688 static GstFlowReturn
689 gst_mpeg2_decoder_handle_picture_ext (GstMpeg2Decoder * decoder,
690     GstMpegVideoPacket * packet)
691 {
692   GstMpeg2DecoderPrivate *priv = decoder->priv;
693   GstMpegVideoPictureExt pic_ext = { {{0,},}, };
694
695   if (!_is_valid_state (decoder,
696           GST_MPEG2_DECODER_STATE_VALID_SEQ_HEADERS |
697           GST_MPEG2_DECODER_STATE_GOT_PIC_HDR)) {
698     GST_ERROR_OBJECT (decoder,
699         "no sequence before parsing sequence-scalable-extension");
700     return GST_FLOW_ERROR;
701   }
702
703   if (!gst_mpeg_video_packet_parse_picture_extension (packet, &pic_ext)) {
704     GST_ERROR_OBJECT (decoder, "failed to parse picture-extension");
705     return GST_FLOW_ERROR;
706   }
707
708   if (priv->progressive && !pic_ext.progressive_frame) {
709     GST_WARNING_OBJECT (decoder,
710         "invalid interlaced frame in progressive sequence, fixing");
711     pic_ext.progressive_frame = 1;
712   }
713
714   if (pic_ext.picture_structure == 0 ||
715       (pic_ext.progressive_frame &&
716           pic_ext.picture_structure !=
717           GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME)) {
718     GST_WARNING_OBJECT (decoder,
719         "invalid picture_structure %d, replacing with \"frame\"",
720         pic_ext.picture_structure);
721     pic_ext.picture_structure = GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME;
722   }
723
724   priv->pic_ext = pic_ext;
725
726   priv->state |= GST_MPEG2_DECODER_STATE_GOT_PIC_EXT;
727
728   return GST_FLOW_OK;
729 }
730
731 static GstFlowReturn
732 gst_mpeg2_decoder_handle_gop (GstMpeg2Decoder * decoder,
733     GstMpegVideoPacket * packet)
734 {
735   GstMpeg2DecoderPrivate *priv = decoder->priv;
736   GstMpegVideoGop gop = { 0, };
737
738   if (!gst_mpeg_video_packet_parse_gop (packet, &gop)) {
739     GST_ERROR_OBJECT (decoder, "failed to parse GOP");
740     return GST_FLOW_ERROR;
741   }
742
743   GST_DEBUG_OBJECT (decoder,
744       "GOP %02u:%02u:%02u:%02u (closed_gop %d, broken_link %d)", gop.hour,
745       gop.minute, gop.second, gop.frame, gop.closed_gop, gop.broken_link);
746
747   priv->gop = gop;
748
749   _pts_sync (&priv->tsg, priv->current_frame->pts);
750
751   return GST_FLOW_OK;
752 }
753
754 static GstFlowReturn
755 gst_mpeg2_decoder_handle_picture (GstMpeg2Decoder * decoder,
756     GstMpegVideoPacket * packet)
757 {
758   GstMpeg2DecoderPrivate *priv = decoder->priv;
759   GstMpegVideoPictureHdr pic_hdr = { 0, };
760   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (decoder);
761
762   g_assert (klass->new_sequence);
763
764   if (!_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_VALID_SEQ_HEADERS)) {
765     GST_ERROR_OBJECT (decoder, "no sequence before parsing picture header");
766     return GST_FLOW_ERROR;
767   }
768
769   /* If need_to_drain, we must have sequence changed. */
770   g_assert (priv->need_to_drain ? priv->seq_changed : TRUE);
771
772   /* 6.1.1.6: Conversely if no sequence_xxx_extension() occurs between
773      the first sequence_header() and the first picture_header() then
774      sequence_xxx_extension() shall not occur in the bitstream. */
775   if (priv->seq_changed) {
776     GstFlowReturn ret;
777
778     /* There are a lot of info in the mpeg2's sequence(also including ext
779        display_ext and scalable_ext). We need to notify the subclass about
780        its change, but not all the changes should trigger a drain(), which
781        may change the output picture order. */
782     if (priv->need_to_drain) {
783       ret = gst_mpeg2_decoder_drain (GST_VIDEO_DECODER (decoder));
784       if (ret != GST_FLOW_OK)
785         return ret;
786
787       priv->need_to_drain = FALSE;
788     }
789
790     if (klass->get_preferred_output_delay) {
791       priv->preferred_output_delay =
792           klass->get_preferred_output_delay (decoder, priv->is_live);
793     } else {
794       priv->preferred_output_delay = 0;
795     }
796
797     priv->seq_changed = FALSE;
798
799     ret = klass->new_sequence (decoder, &priv->seq_hdr,
800         _seq_ext_is_valid (&priv->seq_ext) ? &priv->seq_ext : NULL,
801         _seq_display_ext_is_valid (&priv->seq_display_ext) ?
802         &priv->seq_display_ext : NULL,
803         _seq_scalable_ext_is_valid (&priv->seq_scalable_ext) ?
804         &priv->seq_scalable_ext : NULL,
805         /* previous/next 2 pictures */
806         2 + priv->preferred_output_delay);
807
808     if (ret != GST_FLOW_OK) {
809       GST_WARNING_OBJECT (decoder, "new sequence error");
810       return ret;
811     }
812   }
813
814   priv->state &= (GST_MPEG2_DECODER_STATE_GOT_SEQ_HDR |
815       GST_MPEG2_DECODER_STATE_GOT_SEQ_EXT);
816
817   if (!gst_mpeg_video_packet_parse_picture_header (packet, &pic_hdr)) {
818     GST_ERROR_OBJECT (decoder, "failed to parse picture header");
819     return GST_FLOW_ERROR;
820   }
821
822   priv->pic_hdr = pic_hdr;
823
824   priv->state |= GST_MPEG2_DECODER_STATE_GOT_PIC_HDR;
825
826   return GST_FLOW_OK;
827 }
828
829 static GstFlowReturn
830 gst_mpeg2_decoder_start_current_picture (GstMpeg2Decoder * decoder,
831     GstMpeg2Slice * slice)
832 {
833   GstMpeg2DecoderPrivate *priv = decoder->priv;
834   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (decoder);
835   GstMpeg2Picture *prev_picture, *next_picture;
836   GstFlowReturn ret;
837
838   /* If subclass didn't update output state at this point,
839    * marking this picture as a discont and stores current input state */
840   if (priv->input_state_changed) {
841     priv->current_picture->discont_state =
842         gst_video_codec_state_ref (decoder->input_state);
843     priv->input_state_changed = FALSE;
844   }
845
846   if (!klass->start_picture)
847     return GST_FLOW_OK;
848
849   gst_mpeg2_dpb_get_neighbours (priv->dpb, priv->current_picture,
850       &prev_picture, &next_picture);
851
852   if (priv->current_picture->type == GST_MPEG_VIDEO_PICTURE_TYPE_B
853       && !prev_picture && !priv->gop.closed_gop) {
854     GST_VIDEO_CODEC_FRAME_FLAG_SET (priv->current_frame,
855         GST_VIDEO_CODEC_FRAME_FLAG_DECODE_ONLY);
856   }
857
858   ret = klass->start_picture (decoder, priv->current_picture, slice,
859       prev_picture, next_picture);
860
861   if (ret != GST_FLOW_OK) {
862     GST_WARNING_OBJECT (decoder, "subclass does not want to start picture");
863     return ret;
864   }
865
866   return GST_FLOW_OK;
867 }
868
869 static GstFlowReturn
870 gst_mpeg2_decoder_ensure_current_picture (GstMpeg2Decoder * decoder,
871     GstMpeg2Slice * slice)
872 {
873   GstMpeg2DecoderPrivate *priv = decoder->priv;
874   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (decoder);
875   GstMpeg2Picture *picture = NULL;
876   GstFlowReturn ret = GST_FLOW_OK;
877
878   if (priv->current_picture) {
879     g_assert (_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_GOT_SLICE));
880     return GST_FLOW_OK;
881   }
882
883   if (priv->progressive ||
884       priv->pic_ext.picture_structure ==
885       GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME) {
886     g_assert (!_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_GOT_SLICE));
887
888     if (priv->first_field) {
889       GST_WARNING_OBJECT (decoder, "An unmatched first field");
890       gst_clear_mpeg2_picture (&priv->first_field);
891     }
892
893     picture = gst_mpeg2_picture_new ();
894     if (klass->new_picture)
895       ret = klass->new_picture (decoder, priv->current_frame, picture);
896
897     if (ret != GST_FLOW_OK) {
898       GST_WARNING_OBJECT (decoder, "subclass does not want accept new picture");
899       gst_mpeg2_picture_unref (picture);
900       return ret;
901     }
902
903     picture->structure = GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME;
904   } else {
905     if (!priv->first_field) {
906       picture = gst_mpeg2_picture_new ();
907       if (klass->new_picture)
908         ret = klass->new_picture (decoder, priv->current_frame, picture);
909
910       if (ret != GST_FLOW_OK) {
911         GST_WARNING_OBJECT (decoder,
912             "subclass does not want accept new picture");
913         gst_mpeg2_picture_unref (picture);
914         return ret;
915       }
916     } else {
917       picture = gst_mpeg2_picture_new ();
918
919       if (klass->new_field_picture)
920         ret = klass->new_field_picture (decoder, priv->first_field, picture);
921
922       if (ret != GST_FLOW_OK) {
923         GST_WARNING_OBJECT (decoder,
924             "Subclass couldn't handle new field picture");
925         gst_mpeg2_picture_unref (picture);
926         return ret;
927       }
928
929       picture->first_field = gst_mpeg2_picture_ref (priv->first_field);
930
931       /* At this moment, this picture should be interlaced */
932       picture->buffer_flags |= GST_VIDEO_BUFFER_FLAG_INTERLACED;
933       if (priv->pic_ext.top_field_first)
934         picture->buffer_flags |= GST_VIDEO_BUFFER_FLAG_TFF;
935     }
936
937     picture->structure = priv->pic_ext.picture_structure;
938   }
939
940   picture->needed_for_output = TRUE;
941   /* This allows accessing the frame from the picture. */
942   picture->system_frame_number = priv->current_frame->system_frame_number;
943   picture->type = priv->pic_hdr.pic_type;
944   picture->tsn = priv->pic_hdr.tsn;
945   priv->current_pts =
946       _pts_eval (&priv->tsg, priv->current_frame->pts, picture->tsn);
947   picture->pic_order_cnt = _pts_get_poc (&priv->tsg);
948
949   priv->current_picture = picture;
950   GST_LOG_OBJECT (decoder,
951       "Create new picture %p(%s), system number: %d, poc: %d,"
952       " type: 0x%d, first field %p",
953       picture,
954       (picture->structure == GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME) ?
955       "frame" : "field",
956       picture->system_frame_number, picture->pic_order_cnt, picture->type,
957       picture->first_field);
958
959   return gst_mpeg2_decoder_start_current_picture (decoder, slice);
960 }
961
962 static GstFlowReturn
963 gst_mpeg2_decoder_finish_current_field (GstMpeg2Decoder * decoder)
964 {
965   GstMpeg2DecoderPrivate *priv = decoder->priv;
966   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (decoder);
967   GstFlowReturn ret;
968
969   if (priv->current_picture == NULL)
970     return GST_FLOW_OK;
971
972   ret = klass->end_picture (decoder, priv->current_picture);
973   if (ret != GST_FLOW_OK) {
974     GST_WARNING_OBJECT (decoder, "subclass end_picture failed");
975     return ret;
976   }
977
978   if (priv->current_picture->structure !=
979       GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME &&
980       !priv->current_picture->first_field) {
981     priv->first_field = priv->current_picture;
982     priv->current_picture = NULL;
983   } else {
984     GST_WARNING_OBJECT (decoder, "The current picture %p is not %s, should not "
985         "begin another picture. Just discard this.",
986         priv->current_picture, priv->current_picture->structure ==
987         GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME ?
988         " a field" : "the first field");
989     gst_clear_mpeg2_picture (&priv->current_picture);
990   }
991
992   return GST_FLOW_OK;
993 }
994
995 static GstFlowReturn
996 gst_mpeg2_decoder_finish_current_picture (GstMpeg2Decoder * decoder)
997 {
998   GstMpeg2DecoderPrivate *priv = decoder->priv;
999   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (decoder);
1000   GstFlowReturn ret;
1001
1002   g_assert (priv->current_picture != NULL);
1003
1004   ret = klass->end_picture (decoder, priv->current_picture);
1005   if (ret != GST_FLOW_OK) {
1006     GST_WARNING_OBJECT (decoder, "subclass end_picture failed");
1007     return ret;
1008   }
1009
1010   if (priv->current_picture->structure !=
1011       GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME &&
1012       !priv->current_picture->first_field) {
1013     priv->first_field = priv->current_picture;
1014     priv->current_picture = NULL;
1015   }
1016
1017   return GST_FLOW_OK;
1018 }
1019
1020 static GstFlowReturn
1021 gst_mpeg2_decoder_handle_slice (GstMpeg2Decoder * decoder,
1022     GstMpegVideoPacket * packet)
1023 {
1024   GstMpeg2DecoderPrivate *priv = decoder->priv;
1025   GstMpegVideoSliceHdr slice_hdr;
1026   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (decoder);
1027   GstMpeg2Slice slice;
1028   GstFlowReturn ret;
1029
1030   if (!_is_valid_state (decoder, GST_MPEG2_DECODER_STATE_VALID_PIC_HEADERS)) {
1031     GST_ERROR_OBJECT (decoder,
1032         "no sequence or picture header before parsing picture header");
1033     return GST_FLOW_ERROR;
1034   }
1035
1036   if (!gst_mpeg_video_packet_parse_slice_header (packet, &slice_hdr,
1037           &priv->seq_hdr,
1038           _seq_scalable_ext_is_valid (&priv->seq_scalable_ext) ?
1039           &priv->seq_scalable_ext : NULL)) {
1040     GST_ERROR_OBJECT (decoder, "failed to parse slice header");
1041     return GST_FLOW_ERROR;
1042   }
1043
1044   slice.header = slice_hdr;
1045   slice.packet = *packet;
1046   slice.quant_matrix = _quant_matrix_ext_is_valid (&priv->quant_matrix) ?
1047       &priv->quant_matrix : NULL;
1048   g_assert (_pic_hdr_is_valid (&priv->pic_hdr));
1049   slice.pic_hdr = &priv->pic_hdr;
1050   slice.pic_ext = _pic_hdr_ext_is_valid (&priv->pic_ext) ?
1051       &priv->pic_ext : NULL;
1052   slice.sc_offset = slice.packet.offset - 4;
1053   slice.size = slice.packet.size + 4;
1054
1055   ret = gst_mpeg2_decoder_ensure_current_picture (decoder, &slice);
1056   if (ret != GST_FLOW_OK) {
1057     GST_WARNING_OBJECT (decoder, "failed to start current picture");
1058     return ret;
1059   }
1060
1061   g_assert (klass->decode_slice);
1062   ret = klass->decode_slice (decoder, priv->current_picture, &slice);
1063   if (ret != GST_FLOW_OK) {
1064     GST_WARNING_OBJECT (decoder,
1065         "Subclass didn't want to decode picture %p (frame_num %d, poc %d)",
1066         priv->current_picture, priv->current_picture->system_frame_number,
1067         priv->current_picture->pic_order_cnt);
1068     return ret;
1069   }
1070
1071   priv->state |= GST_MPEG2_DECODER_STATE_GOT_SLICE;
1072
1073   return GST_FLOW_OK;
1074 }
1075
1076 static GstFlowReturn
1077 gst_mpeg2_decoder_decode_packet (GstMpeg2Decoder * decoder,
1078     GstMpegVideoPacket * packet)
1079 {
1080   GstMpegVideoPacketExtensionCode ext_type;
1081   GstFlowReturn ret = GST_FLOW_OK;
1082
1083   GST_LOG_OBJECT (decoder, "Parsing the packet 0x%x, size %d",
1084       packet->type, packet->size);
1085   switch (packet->type) {
1086     case GST_MPEG_VIDEO_PACKET_PICTURE:{
1087       ret = gst_mpeg2_decoder_finish_current_field (decoder);
1088       if (ret != GST_FLOW_OK)
1089         break;
1090
1091       ret = gst_mpeg2_decoder_handle_picture (decoder, packet);
1092       break;
1093     }
1094     case GST_MPEG_VIDEO_PACKET_SEQUENCE:
1095       ret = gst_mpeg2_decoder_handle_sequence (decoder, packet);
1096       break;
1097     case GST_MPEG_VIDEO_PACKET_EXTENSION:
1098       ext_type = packet->data[packet->offset] >> 4;
1099       GST_LOG_OBJECT (decoder, "  Parsing the ext packet 0x%x", ext_type);
1100       switch (ext_type) {
1101         case GST_MPEG_VIDEO_PACKET_EXT_SEQUENCE:
1102           ret = gst_mpeg2_decoder_handle_sequence_ext (decoder, packet);
1103           break;
1104         case GST_MPEG_VIDEO_PACKET_EXT_SEQUENCE_DISPLAY:
1105           ret = gst_mpeg2_decoder_handle_sequence_display_ext (decoder, packet);
1106           break;
1107         case GST_MPEG_VIDEO_PACKET_EXT_SEQUENCE_SCALABLE:
1108           ret =
1109               gst_mpeg2_decoder_handle_sequence_scalable_ext (decoder, packet);
1110           break;
1111         case GST_MPEG_VIDEO_PACKET_EXT_QUANT_MATRIX:
1112           ret = gst_mpeg2_decoder_handle_quant_matrix_ext (decoder, packet);
1113           break;
1114         case GST_MPEG_VIDEO_PACKET_EXT_PICTURE:
1115           ret = gst_mpeg2_decoder_handle_picture_ext (decoder, packet);
1116           break;
1117         default:
1118           /* Ignore unknown start-code extensions */
1119           break;
1120       }
1121       break;
1122     case GST_MPEG_VIDEO_PACKET_SEQUENCE_END:
1123       break;
1124     case GST_MPEG_VIDEO_PACKET_GOP:
1125       ret = gst_mpeg2_decoder_handle_gop (decoder, packet);
1126       break;
1127     case GST_MPEG_VIDEO_PACKET_USER_DATA:
1128       break;
1129     default:
1130       if (packet->type >= GST_MPEG_VIDEO_PACKET_SLICE_MIN &&
1131           packet->type <= GST_MPEG_VIDEO_PACKET_SLICE_MAX) {
1132         ret = gst_mpeg2_decoder_handle_slice (decoder, packet);
1133         break;
1134       }
1135       GST_WARNING_OBJECT (decoder, "unsupported packet type 0x%02x, ignore",
1136           packet->type);
1137       break;
1138   }
1139
1140   return ret;
1141 }
1142
1143 static void
1144 gst_mpeg2_decoder_do_output_picture (GstMpeg2Decoder * decoder,
1145     GstMpeg2Picture * to_output, GstFlowReturn * ret)
1146 {
1147   GstVideoCodecFrame *frame = NULL;
1148   GstMpeg2DecoderPrivate *priv = decoder->priv;
1149   GstMpeg2DecoderOutputFrame output_frame;
1150
1151   g_assert (ret != NULL);
1152
1153   frame =
1154       gst_video_decoder_get_frame (GST_VIDEO_DECODER (decoder),
1155       to_output->system_frame_number);
1156
1157   if (!frame) {
1158     GST_ERROR_OBJECT (decoder,
1159         "No available codec frame with frame number %d",
1160         to_output->system_frame_number);
1161     UPDATE_FLOW_RETURN (ret, GST_FLOW_ERROR);
1162
1163     gst_mpeg2_picture_unref (to_output);
1164
1165     return;
1166   }
1167
1168   output_frame.frame = frame;
1169   output_frame.picture = to_output;
1170   output_frame.self = decoder;
1171   gst_queue_array_push_tail_struct (priv->output_queue, &output_frame);
1172   gst_mpeg2_decoder_drain_output_queue (decoder, priv->preferred_output_delay,
1173       ret);
1174 }
1175
1176 static GstFlowReturn
1177 gst_mpeg2_decoder_output_current_picture (GstMpeg2Decoder * decoder)
1178 {
1179   GstMpeg2DecoderPrivate *priv = decoder->priv;
1180   GstMpeg2Picture *picture = priv->current_picture;
1181   GstFlowReturn ret = GST_FLOW_OK;
1182
1183   if (!picture && priv->first_field) {
1184     GST_WARNING_OBJECT (decoder, "Missing the second field");
1185     picture = priv->first_field;
1186   }
1187
1188   g_assert (picture);
1189
1190   /* Update the presentation time */
1191   priv->current_frame->pts = priv->current_pts;
1192
1193   gst_mpeg2_dpb_add (priv->dpb, picture);
1194
1195   GST_LOG_OBJECT (decoder,
1196       "Add picture %p (frame_num %d, poc %d, type 0x%x), into DPB", picture,
1197       picture->system_frame_number, picture->pic_order_cnt, picture->type);
1198
1199   while (gst_mpeg2_dpb_need_bump (priv->dpb)) {
1200     GstMpeg2Picture *to_output;
1201
1202     to_output = gst_mpeg2_dpb_bump (priv->dpb);
1203     g_assert (to_output);
1204
1205     gst_mpeg2_decoder_do_output_picture (decoder, to_output, &ret);
1206     if (ret != GST_FLOW_OK)
1207       break;
1208   }
1209
1210   return ret;
1211 }
1212
1213 static void
1214 gst_mpeg2_decoder_clear_output_frame (GstMpeg2DecoderOutputFrame * output_frame)
1215 {
1216   if (!output_frame)
1217     return;
1218
1219   if (output_frame->frame) {
1220     gst_video_decoder_release_frame (GST_VIDEO_DECODER (output_frame->self),
1221         output_frame->frame);
1222     output_frame->frame = NULL;
1223   }
1224
1225   gst_clear_mpeg2_picture (&output_frame->picture);
1226 }
1227
1228 static GstFlowReturn
1229 gst_mpeg2_decoder_handle_frame (GstVideoDecoder * decoder,
1230     GstVideoCodecFrame * frame)
1231 {
1232   GstMpeg2Decoder *self = GST_MPEG2_DECODER (decoder);
1233   GstMpeg2DecoderPrivate *priv = self->priv;
1234   GstBuffer *in_buf = frame->input_buffer;
1235   GstMapInfo map_info;
1236   GstMpegVideoPacket packet;
1237   GstFlowReturn ret = GST_FLOW_OK;
1238   guint offset;
1239   gboolean last_one;
1240
1241   GST_LOG_OBJECT (self, "handle frame, PTS: %" GST_TIME_FORMAT
1242       ", DTS: %" GST_TIME_FORMAT " system frame number is %d",
1243       GST_TIME_ARGS (GST_BUFFER_PTS (in_buf)),
1244       GST_TIME_ARGS (GST_BUFFER_DTS (in_buf)), frame->system_frame_number);
1245
1246   priv->state &= ~GST_MPEG2_DECODER_STATE_GOT_SLICE;
1247
1248   priv->current_frame = frame;
1249   gst_buffer_map (in_buf, &map_info, GST_MAP_READ);
1250
1251   offset = 0;
1252   last_one = FALSE;
1253   while (gst_mpeg_video_parse (&packet, map_info.data, map_info.size, offset)) {
1254     /* The packet is the last one */
1255     if (packet.size == -1) {
1256       if (packet.offset < map_info.size) {
1257         packet.size = map_info.size - packet.offset;
1258         last_one = TRUE;
1259       } else {
1260         GST_WARNING_OBJECT (decoder, "Get a packet with wrong size");
1261         break;
1262       }
1263     }
1264
1265     ret = gst_mpeg2_decoder_decode_packet (self, &packet);
1266     if (ret != GST_FLOW_OK) {
1267       gst_buffer_unmap (in_buf, &map_info);
1268       GST_WARNING_OBJECT (decoder, "failed to handle the packet type 0x%x",
1269           packet.type);
1270       goto failed;
1271     }
1272
1273     if (last_one)
1274       break;
1275
1276     offset = packet.offset;
1277   }
1278
1279   gst_buffer_unmap (in_buf, &map_info);
1280
1281   if (!priv->current_picture) {
1282     GST_ERROR_OBJECT (decoder, "no valid picture created");
1283     goto failed;
1284   }
1285
1286   ret = gst_mpeg2_decoder_finish_current_picture (self);
1287   if (ret != GST_FLOW_OK) {
1288     GST_ERROR_OBJECT (decoder, "failed to decode the current picture");
1289     goto failed;
1290   }
1291
1292   ret = gst_mpeg2_decoder_output_current_picture (self);
1293   gst_clear_mpeg2_picture (&priv->current_picture);
1294   gst_clear_mpeg2_picture (&priv->first_field);
1295   gst_video_codec_frame_unref (priv->current_frame);
1296   priv->current_frame = NULL;
1297   return ret;
1298
1299 failed:
1300   {
1301     if (ret == GST_FLOW_ERROR) {
1302       GST_VIDEO_DECODER_ERROR (decoder, 1, STREAM, DECODE,
1303           ("failed to handle the frame %d", frame->system_frame_number), (NULL),
1304           ret);
1305     }
1306
1307     gst_video_decoder_drop_frame (decoder, frame);
1308     gst_clear_mpeg2_picture (&priv->current_picture);
1309     gst_clear_mpeg2_picture (&priv->first_field);
1310     priv->current_frame = NULL;
1311
1312     return ret;
1313   }
1314 }
1315
1316 static void
1317 gst_mpeg2_decoder_drain_output_queue (GstMpeg2Decoder * self, guint num,
1318     GstFlowReturn * ret)
1319 {
1320   GstMpeg2DecoderPrivate *priv = self->priv;
1321   GstMpeg2DecoderClass *klass = GST_MPEG2_DECODER_GET_CLASS (self);
1322   GstFlowReturn flow_ret;
1323
1324   g_assert (klass->output_picture);
1325
1326   while (gst_queue_array_get_length (priv->output_queue) > num) {
1327     GstMpeg2DecoderOutputFrame *output_frame = (GstMpeg2DecoderOutputFrame *)
1328         gst_queue_array_pop_head_struct (priv->output_queue);
1329     GST_LOG_OBJECT (self,
1330         "Output picture %p (frame_num %d, poc %d, pts: %" GST_TIME_FORMAT
1331         "), from DPB",
1332         output_frame->picture, output_frame->picture->system_frame_number,
1333         output_frame->picture->pic_order_cnt,
1334         GST_TIME_ARGS (output_frame->frame->pts));
1335
1336     flow_ret =
1337         klass->output_picture (self, output_frame->frame,
1338         output_frame->picture);
1339
1340     UPDATE_FLOW_RETURN (ret, flow_ret);
1341   }
1342 }