mpeg2: fix end-of-stream conditions (flush).
[vaapi:gstreamer-vaapi.git] / gst-libs / gst / vaapi / gstvaapidecoder_mpeg2.c
1 /*
2  *  gstvaapidecoder_mpeg2.c - MPEG-2 decoder
3  *
4  *  Copyright (C) 2011 Intel Corporation
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public License
8  *  as published by the Free Software Foundation; either version 2.1
9  *  of the License, or (at your option) any later version.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free
18  *  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  *  Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * SECTION:gstvaapidecoder_mpeg2
24  * @short_description: MPEG-2 decoder
25  */
26
27 #include "sysdeps.h"
28 #include <string.h>
29 #include <gst/base/gstbitreader.h>
30 #include <gst/codecparsers/gstmpegvideoparser.h>
31 #include "gstvaapidecoder_mpeg2.h"
32 #include "gstvaapidecoder_objects.h"
33 #include "gstvaapidecoder_dpb.h"
34 #include "gstvaapidecoder_priv.h"
35 #include "gstvaapidisplay_priv.h"
36 #include "gstvaapiobject_priv.h"
37
38 #define DEBUG 1
39 #include "gstvaapidebug.h"
40
41 G_DEFINE_TYPE(GstVaapiDecoderMpeg2,
42               gst_vaapi_decoder_mpeg2,
43               GST_VAAPI_TYPE_DECODER)
44
45 #define GST_VAAPI_DECODER_MPEG2_GET_PRIVATE(obj)                \
46     (G_TYPE_INSTANCE_GET_PRIVATE((obj),                         \
47                                  GST_VAAPI_TYPE_DECODER_MPEG2,  \
48                                  GstVaapiDecoderMpeg2Private))
49
50 #define READ_UINT8(br, val, nbits) G_STMT_START {  \
51   if (!gst_bit_reader_get_bits_uint8 (br, &val, nbits)) { \
52     GST_WARNING ("failed to read uint8, nbits: %d", nbits); \
53     goto failed; \
54   } \
55 } G_STMT_END
56
57 #define SKIP(reader, nbits) G_STMT_START { \
58   if (!gst_bit_reader_skip (reader, nbits)) { \
59     GST_WARNING ("failed to skip nbits: %d", nbits); \
60     goto failed; \
61   } \
62 } G_STMT_END
63
64 /* PTS Generator */
65 typedef struct _PTSGenerator PTSGenerator;
66 struct _PTSGenerator {
67     GstClockTime        gop_pts; // Current GOP PTS
68     GstClockTime        max_pts; // Max picture PTS
69     guint               gop_tsn; // Absolute GOP TSN
70     guint               max_tsn; // Max picture TSN, relative to last GOP TSN
71     guint               ovl_tsn; // How many times TSN overflowed since GOP
72     guint               lst_tsn; // Last picture TSN
73     guint               fps_n;
74     guint               fps_d;
75 };
76
77 static void
78 pts_init(PTSGenerator *tsg)
79 {
80     tsg->gop_pts = GST_CLOCK_TIME_NONE;
81     tsg->max_pts = GST_CLOCK_TIME_NONE;
82     tsg->gop_tsn = 0;
83     tsg->max_tsn = 0;
84     tsg->ovl_tsn = 0;
85     tsg->lst_tsn = 0;
86     tsg->fps_n   = 0;
87     tsg->fps_d   = 0;
88 }
89
90 static inline GstClockTime
91 pts_get_duration(PTSGenerator *tsg, guint num_frames)
92 {
93     return gst_util_uint64_scale(num_frames,
94                                  GST_SECOND * tsg->fps_d, tsg->fps_n);
95 }
96
97 static inline guint
98 pts_get_poc(PTSGenerator *tsg)
99 {
100     return tsg->gop_tsn + tsg->ovl_tsn * 1024 + tsg->lst_tsn;
101 }
102
103 static void
104 pts_set_framerate(PTSGenerator *tsg, guint fps_n, guint fps_d)
105 {
106     tsg->fps_n = fps_n;
107     tsg->fps_d = fps_d;
108 }
109
110 static void
111 pts_sync(PTSGenerator *tsg, GstClockTime gop_pts)
112 {
113     guint gop_tsn;
114
115     if (!GST_CLOCK_TIME_IS_VALID(gop_pts) ||
116         (GST_CLOCK_TIME_IS_VALID(tsg->max_pts) && tsg->max_pts >= gop_pts)) {
117         /* Invalid GOP PTS, interpolate from the last known picture PTS */
118         if (GST_CLOCK_TIME_IS_VALID(tsg->max_pts)) {
119             gop_pts = tsg->max_pts + pts_get_duration(tsg, 1);
120             gop_tsn = tsg->gop_tsn + tsg->ovl_tsn * 1024 + tsg->max_tsn + 1;
121         }
122         else {
123             gop_pts = 0;
124             gop_tsn = 0;
125         }
126     }
127     else {
128         /* Interpolate GOP TSN from this valid PTS */
129         if (GST_CLOCK_TIME_IS_VALID(tsg->gop_pts))
130             gop_tsn = tsg->gop_tsn + gst_util_uint64_scale(
131                 gop_pts - tsg->gop_pts + pts_get_duration(tsg, 1) - 1,
132                 tsg->fps_n, GST_SECOND * tsg->fps_d);
133         else
134             gop_tsn = 0;
135     }
136
137     tsg->gop_pts = gop_pts;
138     tsg->gop_tsn = gop_tsn;
139     tsg->max_tsn = 0;
140     tsg->ovl_tsn = 0;
141     tsg->lst_tsn = 0;
142 }
143
144 static GstClockTime
145 pts_eval(PTSGenerator *tsg, GstClockTime pic_pts, guint pic_tsn)
146 {
147     GstClockTime pts;
148
149     if (!GST_CLOCK_TIME_IS_VALID(tsg->gop_pts))
150         tsg->gop_pts = 0;
151
152     pts = tsg->gop_pts + pts_get_duration(tsg, tsg->ovl_tsn * 1024 + pic_tsn);
153
154     if (!GST_CLOCK_TIME_IS_VALID(tsg->max_pts) || tsg->max_pts < pts)
155         tsg->max_pts = pts;
156
157     if (tsg->max_tsn < pic_tsn)
158         tsg->max_tsn = pic_tsn;
159     else if (tsg->max_tsn == 1023 && pic_tsn < tsg->lst_tsn) { /* TSN wrapped */
160         tsg->max_tsn = pic_tsn;
161         tsg->ovl_tsn++;
162     }
163     tsg->lst_tsn = pic_tsn;
164     return pts;
165 }
166
167 struct _GstVaapiDecoderMpeg2Private {
168     GstVaapiProfile             profile;
169     GstVaapiProfile             hw_profile;
170     guint                       width;
171     guint                       height;
172     guint                       fps_n;
173     guint                       fps_d;
174     GstMpegVideoSequenceHdr     seq_hdr;
175     GstMpegVideoSequenceExt     seq_ext;
176     GstMpegVideoPictureHdr      pic_hdr;
177     GstMpegVideoPictureExt      pic_ext;
178     GstMpegVideoQuantMatrixExt  quant_matrix_ext;
179     GstVaapiPicture            *current_picture;
180     GstVaapiDpb                *dpb;
181     GstAdapter                 *adapter;
182     PTSGenerator                tsg;
183     guint                       is_constructed          : 1;
184     guint                       is_opened               : 1;
185     guint                       has_seq_ext             : 1;
186     guint                       has_seq_scalable_ext    : 1;
187     guint                       has_pic_ext             : 1;
188     guint                       has_quant_matrix_ext    : 1;
189     guint                       size_changed            : 1;
190     guint                       profile_changed         : 1;
191     guint                       quant_matrix_changed    : 1;
192     guint                       progressive_sequence    : 1;
193     guint                       closed_gop              : 1;
194     guint                       broken_link             : 1;
195 };
196
197 /* VLC decoder from gst-plugins-bad */
198 typedef struct _VLCTable VLCTable;
199 struct _VLCTable {
200     gint  value;
201     guint cword;
202     guint cbits;
203 };
204
205 static gboolean
206 decode_vlc(GstBitReader *br, gint *res, const VLCTable *table, guint length)
207 {
208     guint8 i;
209     guint cbits = 0;
210     guint32 value = 0;
211
212     for (i = 0; i < length; i++) {
213         if (cbits != table[i].cbits) {
214             cbits = table[i].cbits;
215             if (!gst_bit_reader_peek_bits_uint32(br, &value, cbits)) {
216                 goto failed;
217             }
218         }
219
220         if (value == table[i].cword) {
221             SKIP(br, cbits);
222             if (res)
223                 *res = table[i].value;
224             return TRUE;
225         }
226     }
227     GST_DEBUG("failed to find VLC code");
228
229 failed:
230     GST_WARNING("failed to decode VLC, returning");
231     return FALSE;
232 }
233
234 enum {
235     GST_MPEG_VIDEO_MACROBLOCK_ESCAPE = -1,
236 };
237
238 /* Table B-1: Variable length codes for macroblock_address_increment */
239 static const VLCTable mpeg2_mbaddr_vlc_table[] = {
240     {  1, 0x01,  1 },
241     {  2, 0x03,  3 },
242     {  3, 0x02,  3 },
243     {  4, 0x03,  4 },
244     {  5, 0x02,  4 },
245     {  6, 0x03,  5 },
246     {  7, 0x02,  5 },
247     {  8, 0x07,  7 },
248     {  9, 0x06,  7 },
249     { 10, 0x0b,  8 },
250     { 11, 0x0a,  8 },
251     { 12, 0x09,  8 },
252     { 13, 0x08,  8 },
253     { 14, 0x07,  8 },
254     { 15, 0x06,  8 },
255     { 16, 0x17, 10 },
256     { 17, 0x16, 10 },
257     { 18, 0x15, 10 },
258     { 19, 0x14, 10 },
259     { 20, 0x13, 10 },
260     { 21, 0x12, 10 },
261     { 22, 0x23, 11 },
262     { 23, 0x22, 11 },
263     { 24, 0x21, 11 },
264     { 25, 0x20, 11 },
265     { 26, 0x1f, 11 },
266     { 27, 0x1e, 11 },
267     { 28, 0x1d, 11 },
268     { 29, 0x1c, 11 },
269     { 30, 0x1b, 11 },
270     { 31, 0x1a, 11 },
271     { 32, 0x19, 11 },
272     { 33, 0x18, 11 },
273     { GST_MPEG_VIDEO_MACROBLOCK_ESCAPE, 0x08, 11 }
274 };
275
276 static void
277 gst_vaapi_decoder_mpeg2_close(GstVaapiDecoderMpeg2 *decoder)
278 {
279     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
280
281     gst_vaapi_picture_replace(&priv->current_picture, NULL);
282
283     if (priv->dpb) {
284         gst_vaapi_dpb_unref(priv->dpb);
285         priv->dpb = NULL;
286     }
287
288     if (priv->adapter) {
289         gst_adapter_clear(priv->adapter);
290         g_object_unref(priv->adapter);
291         priv->adapter = NULL;
292     }
293 }
294
295 static gboolean
296 gst_vaapi_decoder_mpeg2_open(GstVaapiDecoderMpeg2 *decoder, GstBuffer *buffer)
297 {
298     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
299
300     gst_vaapi_decoder_mpeg2_close(decoder);
301
302     priv->adapter = gst_adapter_new();
303     if (!priv->adapter)
304         return FALSE;
305
306     priv->dpb = gst_vaapi_dpb_mpeg2_new();
307     if (!priv->dpb)
308         return FALSE;
309
310     pts_init(&priv->tsg);
311     return TRUE;
312 }
313
314 static void
315 gst_vaapi_decoder_mpeg2_destroy(GstVaapiDecoderMpeg2 *decoder)
316 {
317     gst_vaapi_decoder_mpeg2_close(decoder);
318 }
319
320 static gboolean
321 gst_vaapi_decoder_mpeg2_create(GstVaapiDecoderMpeg2 *decoder)
322 {
323     if (!GST_VAAPI_DECODER_CODEC(decoder))
324         return FALSE;
325     return TRUE;
326 }
327
328 static inline void
329 copy_quant_matrix(guint8 dst[64], const guint8 src[64])
330 {
331     memcpy(dst, src, 64);
332 }
333
334 static const char *
335 get_profile_str(GstVaapiProfile profile)
336 {
337     char *str;
338
339     switch (profile) {
340     case GST_VAAPI_PROFILE_MPEG2_SIMPLE:    str = "simple";     break;
341     case GST_VAAPI_PROFILE_MPEG2_MAIN:      str = "main";       break;
342     case GST_VAAPI_PROFILE_MPEG2_HIGH:      str = "high";       break;
343     default:                                str = "<unknown>";  break;
344     }
345     return str;
346 }
347
348 static GstVaapiProfile
349 get_profile(GstVaapiDecoderMpeg2 *decoder, GstVaapiEntrypoint entrypoint)
350 {
351     GstVaapiDisplay * const va_display = GST_VAAPI_DECODER_DISPLAY(decoder);
352     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
353     GstVaapiProfile profile = priv->profile;
354
355     do {
356         /* Return immediately if the exact same profile was found */
357         if (gst_vaapi_display_has_decoder(va_display, profile, entrypoint))
358             break;
359
360         /* Otherwise, try to map to a higher profile */
361         switch (profile) {
362         case GST_VAAPI_PROFILE_MPEG2_SIMPLE:
363             profile = GST_VAAPI_PROFILE_MPEG2_MAIN;
364             break;
365         case GST_VAAPI_PROFILE_MPEG2_MAIN:
366             profile = GST_VAAPI_PROFILE_MPEG2_HIGH;
367             break;
368         case GST_VAAPI_PROFILE_MPEG2_HIGH:
369             // Try to map to main profile if no high profile specific bits used
370             if (priv->profile == profile    &&
371                 !priv->has_seq_scalable_ext &&
372                 (priv->has_seq_ext && priv->seq_ext.chroma_format == 1)) {
373                 profile = GST_VAAPI_PROFILE_MPEG2_MAIN;
374                 break;
375             }
376             // fall-through
377         default:
378             profile = GST_VAAPI_PROFILE_UNKNOWN;
379             break;
380         }
381     } while (profile != GST_VAAPI_PROFILE_UNKNOWN);
382
383     if (profile != priv->profile)
384         GST_INFO("forced %s profile to %s profile",
385                  get_profile_str(priv->profile), get_profile_str(profile));
386     return profile;
387 }
388
389 static GstVaapiDecoderStatus
390 ensure_context(GstVaapiDecoderMpeg2 *decoder)
391 {
392     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
393     GstVaapiEntrypoint entrypoint = GST_VAAPI_ENTRYPOINT_VLD;
394     gboolean reset_context = FALSE;
395
396     if (priv->profile_changed) {
397         GST_DEBUG("profile changed");
398         priv->profile_changed = FALSE;
399         reset_context         = TRUE;
400
401         priv->hw_profile = get_profile(decoder, entrypoint);
402         if (priv->hw_profile == GST_VAAPI_PROFILE_UNKNOWN)
403             return GST_VAAPI_DECODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
404     }
405
406     if (priv->size_changed) {
407         GST_DEBUG("size changed");
408         priv->size_changed = FALSE;
409         reset_context      = TRUE;
410     }
411
412     if (reset_context) {
413         GstVaapiContextInfo info;
414
415         info.profile    = priv->hw_profile;
416         info.entrypoint = entrypoint;
417         info.width      = priv->width;
418         info.height     = priv->height;
419         info.ref_frames = 2;
420         reset_context   = gst_vaapi_decoder_ensure_context(
421             GST_VAAPI_DECODER(decoder),
422             &info
423         );
424         if (!reset_context)
425             return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
426     }
427     return GST_VAAPI_DECODER_STATUS_SUCCESS;
428 }
429
430 static GstVaapiDecoderStatus
431 ensure_quant_matrix(GstVaapiDecoderMpeg2 *decoder, GstVaapiPicture *picture)
432 {
433     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
434     VAIQMatrixBufferMPEG2 *iq_matrix;
435     guint8 *intra_quant_matrix = NULL;
436     guint8 *non_intra_quant_matrix = NULL;
437     guint8 *chroma_intra_quant_matrix = NULL;
438     guint8 *chroma_non_intra_quant_matrix = NULL;
439
440     if (!priv->quant_matrix_changed)
441         return GST_VAAPI_DECODER_STATUS_SUCCESS;
442
443     priv->quant_matrix_changed = FALSE;
444
445     picture->iq_matrix = GST_VAAPI_IQ_MATRIX_NEW(MPEG2, decoder);
446     if (!picture->iq_matrix) {
447         GST_ERROR("failed to allocate IQ matrix");
448         return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
449     }
450     iq_matrix = picture->iq_matrix->param;
451
452     intra_quant_matrix     = priv->seq_hdr.intra_quantizer_matrix;
453     non_intra_quant_matrix = priv->seq_hdr.non_intra_quantizer_matrix;
454     if (priv->has_quant_matrix_ext) {
455         if (priv->quant_matrix_ext.load_intra_quantiser_matrix)
456             intra_quant_matrix = priv->quant_matrix_ext.intra_quantiser_matrix;
457         if (priv->quant_matrix_ext.load_non_intra_quantiser_matrix)
458             non_intra_quant_matrix = priv->quant_matrix_ext.non_intra_quantiser_matrix;
459         if (priv->quant_matrix_ext.load_chroma_intra_quantiser_matrix)
460             chroma_intra_quant_matrix = priv->quant_matrix_ext.chroma_intra_quantiser_matrix;
461         if (priv->quant_matrix_ext.load_chroma_non_intra_quantiser_matrix)
462             chroma_non_intra_quant_matrix = priv->quant_matrix_ext.chroma_non_intra_quantiser_matrix;
463     }
464
465     iq_matrix->load_intra_quantiser_matrix = intra_quant_matrix != NULL;
466     if (intra_quant_matrix)
467         copy_quant_matrix(iq_matrix->intra_quantiser_matrix,
468                           intra_quant_matrix);
469
470     iq_matrix->load_non_intra_quantiser_matrix = non_intra_quant_matrix != NULL;
471     if (non_intra_quant_matrix)
472         copy_quant_matrix(iq_matrix->non_intra_quantiser_matrix,
473                           non_intra_quant_matrix);
474
475     iq_matrix->load_chroma_intra_quantiser_matrix = chroma_intra_quant_matrix != NULL;
476     if (chroma_intra_quant_matrix)
477         copy_quant_matrix(iq_matrix->chroma_intra_quantiser_matrix,
478                           chroma_intra_quant_matrix);
479
480     iq_matrix->load_chroma_non_intra_quantiser_matrix = chroma_non_intra_quant_matrix != NULL;
481     if (chroma_non_intra_quant_matrix)
482         copy_quant_matrix(iq_matrix->chroma_non_intra_quantiser_matrix,
483                           chroma_non_intra_quant_matrix);
484     return GST_VAAPI_DECODER_STATUS_SUCCESS;
485 }
486
487 static gboolean
488 decode_current_picture(GstVaapiDecoderMpeg2 *decoder)
489 {
490     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
491     GstVaapiPicture * const picture = priv->current_picture;
492
493     if (picture) {
494         if (!gst_vaapi_picture_decode(picture))
495             return FALSE;
496         if (GST_VAAPI_PICTURE_IS_COMPLETE(picture)) {
497             if (!gst_vaapi_dpb_add(priv->dpb, picture))
498                 return FALSE;
499             gst_vaapi_picture_replace(&priv->current_picture, NULL);
500         }
501     }
502     return TRUE;
503 }
504
505 static GstVaapiDecoderStatus
506 decode_sequence(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
507 {
508     GstVaapiDecoder * const base_decoder = GST_VAAPI_DECODER(decoder);
509     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
510     GstMpegVideoSequenceHdr * const seq_hdr = &priv->seq_hdr;
511
512     if (!gst_mpeg_video_parse_sequence_header(seq_hdr, buf, buf_size, 4)) {
513         GST_ERROR("failed to parse sequence header");
514         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
515     }
516
517     priv->fps_n = seq_hdr->fps_n;
518     priv->fps_d = seq_hdr->fps_d;
519     pts_set_framerate(&priv->tsg, priv->fps_n, priv->fps_d);
520     gst_vaapi_decoder_set_framerate(base_decoder, priv->fps_n, priv->fps_d);
521
522     priv->width                 = seq_hdr->width;
523     priv->height                = seq_hdr->height;
524     priv->has_seq_ext           = FALSE;
525     priv->size_changed          = TRUE;
526     priv->quant_matrix_changed  = TRUE;
527     priv->progressive_sequence  = TRUE;
528     return GST_VAAPI_DECODER_STATUS_SUCCESS;
529 }
530
531 static GstVaapiDecoderStatus
532 decode_sequence_ext(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
533 {
534     GstVaapiDecoder * const base_decoder = GST_VAAPI_DECODER(decoder);
535     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
536     GstMpegVideoSequenceExt * const seq_ext = &priv->seq_ext;
537     GstVaapiProfile profile;
538     guint width, height;
539
540     if (!gst_mpeg_video_parse_sequence_extension(seq_ext, buf, buf_size, 4)) {
541         GST_ERROR("failed to parse sequence-extension");
542         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
543     }
544     priv->has_seq_ext = TRUE;
545     priv->progressive_sequence = seq_ext->progressive;
546     gst_vaapi_decoder_set_interlaced(base_decoder, !priv->progressive_sequence);
547
548     width  = (priv->width  & 0x0fff) | ((guint32)seq_ext->horiz_size_ext << 12);
549     height = (priv->height & 0x0fff) | ((guint32)seq_ext->vert_size_ext  << 12);
550     GST_DEBUG("video resolution %ux%u", width, height);
551
552     if (seq_ext->fps_n_ext && seq_ext->fps_d_ext) {
553         priv->fps_n *= seq_ext->fps_n_ext + 1;
554         priv->fps_d *= seq_ext->fps_d_ext + 1;
555         pts_set_framerate(&priv->tsg, priv->fps_n, priv->fps_d);
556         gst_vaapi_decoder_set_framerate(base_decoder, priv->fps_n, priv->fps_d);
557     }
558
559     if (priv->width != width) {
560         priv->width = width;
561         priv->size_changed = TRUE;
562     }
563
564     if (priv->height != height) {
565         priv->height = height;
566         priv->size_changed = TRUE;
567     }
568
569     switch (seq_ext->profile) {
570     case GST_MPEG_VIDEO_PROFILE_SIMPLE:
571         profile = GST_VAAPI_PROFILE_MPEG2_SIMPLE;
572         break;
573     case GST_MPEG_VIDEO_PROFILE_MAIN:
574         profile = GST_VAAPI_PROFILE_MPEG2_MAIN;
575         break;
576     case GST_MPEG_VIDEO_PROFILE_HIGH:
577         profile = GST_VAAPI_PROFILE_MPEG2_HIGH;
578         break;
579     default:
580         GST_ERROR("unsupported profile %d", seq_ext->profile);
581         return GST_VAAPI_DECODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
582     }
583     if (priv->profile != profile) {
584         priv->profile = profile;
585         priv->profile_changed = TRUE;
586     }
587     return GST_VAAPI_DECODER_STATUS_SUCCESS;
588 }
589
590 static GstVaapiDecoderStatus
591 decode_sequence_end(GstVaapiDecoderMpeg2 *decoder)
592 {
593     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
594
595     if (priv->current_picture && !decode_current_picture(decoder))
596         return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
597
598     gst_vaapi_dpb_flush(priv->dpb);
599     return GST_VAAPI_DECODER_STATUS_END_OF_STREAM;
600 }
601
602 static GstVaapiDecoderStatus
603 decode_quant_matrix_ext(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
604 {
605     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
606     GstMpegVideoQuantMatrixExt * const quant_matrix_ext = &priv->quant_matrix_ext;
607
608     if (!gst_mpeg_video_parse_quant_matrix_extension(quant_matrix_ext, buf, buf_size, 4)) {
609         GST_ERROR("failed to parse quant-matrix-extension");
610         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
611     }
612     priv->has_quant_matrix_ext = TRUE;
613     priv->quant_matrix_changed = TRUE;
614     return GST_VAAPI_DECODER_STATUS_SUCCESS;
615 }
616
617 static GstVaapiDecoderStatus
618 decode_gop(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
619 {
620     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
621     GstMpegVideoGop gop;
622     GstClockTime pts;
623
624     if (!gst_mpeg_video_parse_gop(&gop, buf, buf_size, 4)) {
625         GST_ERROR("failed to parse GOP");
626         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
627     }
628
629     priv->closed_gop  = gop.closed_gop;
630     priv->broken_link = gop.broken_link;
631
632     GST_DEBUG("GOP %02u:%02u:%02u:%02u (closed_gop %d, broken_link %d)",
633               gop.hour, gop.minute, gop.second, gop.frame,
634               priv->closed_gop, priv->broken_link);
635
636     pts = gst_adapter_prev_timestamp(priv->adapter, NULL);
637     pts_sync(&priv->tsg, pts);
638     return GST_VAAPI_DECODER_STATUS_SUCCESS;
639 }
640
641 static GstVaapiDecoderStatus
642 decode_picture(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
643 {
644     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
645     GstMpegVideoPictureHdr * const pic_hdr = &priv->pic_hdr;
646     GstVaapiPicture *picture;
647     GstVaapiDecoderStatus status;
648     GstClockTime pts;
649
650     status = ensure_context(decoder);
651     if (status != GST_VAAPI_DECODER_STATUS_SUCCESS) {
652         GST_ERROR("failed to reset context");
653         return status;
654     }
655
656     if (priv->current_picture && !decode_current_picture(decoder))
657         return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
658
659     if (priv->current_picture) {
660         /* Re-use current picture where the first field was decoded */
661         picture = gst_vaapi_picture_new_field(priv->current_picture);
662         if (!picture) {
663             GST_ERROR("failed to allocate field picture");
664             return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
665         }
666     }
667     else {
668         /* Create new picture */
669         picture = GST_VAAPI_PICTURE_NEW(MPEG2, decoder);
670         if (!picture) {
671             GST_ERROR("failed to allocate picture");
672             return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
673         }
674     }
675     gst_vaapi_picture_replace(&priv->current_picture, picture);
676     gst_vaapi_picture_unref(picture);
677
678     status = ensure_quant_matrix(decoder, picture);
679     if (status != GST_VAAPI_DECODER_STATUS_SUCCESS) {
680         GST_ERROR("failed to reset quantizer matrix");
681         return status;
682     }
683
684     if (!gst_mpeg_video_parse_picture_header(pic_hdr, buf, buf_size, 4)) {
685         GST_ERROR("failed to parse picture header");
686         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
687     }
688     priv->has_pic_ext = FALSE;
689
690     switch (pic_hdr->pic_type) {
691     case GST_MPEG_VIDEO_PICTURE_TYPE_I:
692         GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_REFERENCE);
693         picture->type = GST_VAAPI_PICTURE_TYPE_I;
694         break;
695     case GST_MPEG_VIDEO_PICTURE_TYPE_P:
696         GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_REFERENCE);
697         picture->type = GST_VAAPI_PICTURE_TYPE_P;
698         break;
699     case GST_MPEG_VIDEO_PICTURE_TYPE_B:
700         picture->type = GST_VAAPI_PICTURE_TYPE_B;
701         break;
702     default:
703         GST_ERROR("unsupported picture type %d", pic_hdr->pic_type);
704         return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
705     }
706
707     /* Update presentation time */
708     pts = gst_adapter_prev_timestamp(priv->adapter, NULL);
709     picture->pts = pts_eval(&priv->tsg, pts, pic_hdr->tsn);
710     picture->poc = pts_get_poc(&priv->tsg);
711     return status;
712 }
713
714 static GstVaapiDecoderStatus
715 decode_picture_ext(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
716 {
717     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
718     GstMpegVideoPictureExt * const pic_ext = &priv->pic_ext;
719     GstVaapiPicture * const picture = priv->current_picture;
720
721     if (!gst_mpeg_video_parse_picture_extension(pic_ext, buf, buf_size, 4)) {
722         GST_ERROR("failed to parse picture-extension");
723         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
724     }
725     priv->has_pic_ext = TRUE;
726
727     if (priv->progressive_sequence && !pic_ext->progressive_frame) {
728         GST_WARNING("invalid interlaced frame in progressive sequence, fixing");
729         pic_ext->progressive_frame = 1;
730     }
731
732     if (pic_ext->picture_structure == 0 ||
733         (pic_ext->progressive_frame &&
734          pic_ext->picture_structure != GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME)) {
735         GST_WARNING("invalid picture_structure %d, replacing with \"frame\"",
736                     pic_ext->picture_structure);
737         pic_ext->picture_structure = GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME;
738     }
739
740     if (!priv->progressive_sequence && !pic_ext->progressive_frame) {
741         GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_INTERLACED);
742         if (pic_ext->top_field_first)
743             GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_TFF);
744     }
745
746     switch (pic_ext->picture_structure) {
747     case GST_MPEG_VIDEO_PICTURE_STRUCTURE_TOP_FIELD:
748         picture->structure = GST_VAAPI_PICTURE_STRUCTURE_TOP_FIELD;
749         break;
750     case GST_MPEG_VIDEO_PICTURE_STRUCTURE_BOTTOM_FIELD:
751         picture->structure = GST_VAAPI_PICTURE_STRUCTURE_BOTTOM_FIELD;
752         break;
753     case GST_MPEG_VIDEO_PICTURE_STRUCTURE_FRAME:
754         picture->structure = GST_VAAPI_PICTURE_STRUCTURE_FRAME;
755         break;
756     }
757
758     /* Allocate dummy picture for first field based I-frame */
759     if (picture->type == GST_VAAPI_PICTURE_TYPE_I &&
760         !GST_VAAPI_PICTURE_IS_FRAME(picture) &&
761         gst_vaapi_dpb_size(priv->dpb) == 0) {
762         GstVaapiPicture *dummy_picture;
763         gboolean success;
764
765         dummy_picture = GST_VAAPI_PICTURE_NEW(MPEG2, decoder);
766         if (!dummy_picture) {
767             GST_ERROR("failed to allocate dummy picture");
768             return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
769         }
770
771         dummy_picture->type      = GST_VAAPI_PICTURE_TYPE_I;
772         dummy_picture->pts       = GST_CLOCK_TIME_NONE;
773         dummy_picture->poc       = -1;
774         dummy_picture->structure = GST_VAAPI_PICTURE_STRUCTURE_FRAME;
775
776         GST_VAAPI_PICTURE_FLAG_SET(
777             dummy_picture,
778             (GST_VAAPI_PICTURE_FLAG_SKIPPED |
779              GST_VAAPI_PICTURE_FLAG_REFERENCE)
780         );
781
782         success = gst_vaapi_dpb_add(priv->dpb, dummy_picture);
783         gst_vaapi_picture_unref(dummy_picture);
784         if (!success) {
785             GST_ERROR("failed to add dummy picture into DPB");
786             return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
787         }
788         GST_INFO("allocated dummy picture for first field based I-frame");
789     }
790     return GST_VAAPI_DECODER_STATUS_SUCCESS;
791 }
792
793 static inline guint32
794 pack_f_code(guint8 f_code[2][2])
795 {
796     return (((guint32)f_code[0][0] << 12) |
797             ((guint32)f_code[0][1] <<  8) |
798             ((guint32)f_code[1][0] <<  4) |
799             (         f_code[1][1]      ));
800 }
801
802 static gboolean
803 fill_picture(GstVaapiDecoderMpeg2 *decoder, GstVaapiPicture *picture)
804 {
805     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
806     VAPictureParameterBufferMPEG2 * const pic_param = picture->param;
807     GstMpegVideoPictureHdr * const pic_hdr = &priv->pic_hdr;
808     GstMpegVideoPictureExt * const pic_ext = &priv->pic_ext;
809     GstVaapiPicture *prev_picture, *next_picture;
810
811     if (!priv->has_pic_ext)
812         return FALSE;
813
814     /* Fill in VAPictureParameterBufferMPEG2 */
815     pic_param->horizontal_size                                          = priv->width;
816     pic_param->vertical_size                                            = priv->height;
817     pic_param->forward_reference_picture                                = VA_INVALID_ID;
818     pic_param->backward_reference_picture                               = VA_INVALID_ID;
819     pic_param->picture_coding_type                                      = pic_hdr->pic_type;
820     pic_param->f_code                                                   = pack_f_code(pic_ext->f_code);
821
822 #define COPY_FIELD(a, b, f) \
823     pic_param->a.b.f = pic_ext->f
824     pic_param->picture_coding_extension.value                           = 0;
825     pic_param->picture_coding_extension.bits.is_first_field             = GST_VAAPI_PICTURE_IS_FIRST_FIELD(picture);
826     COPY_FIELD(picture_coding_extension, bits, intra_dc_precision);
827     COPY_FIELD(picture_coding_extension, bits, picture_structure);
828     COPY_FIELD(picture_coding_extension, bits, top_field_first);
829     COPY_FIELD(picture_coding_extension, bits, frame_pred_frame_dct);
830     COPY_FIELD(picture_coding_extension, bits, concealment_motion_vectors);
831     COPY_FIELD(picture_coding_extension, bits, q_scale_type);
832     COPY_FIELD(picture_coding_extension, bits, intra_vlc_format);
833     COPY_FIELD(picture_coding_extension, bits, alternate_scan);
834     COPY_FIELD(picture_coding_extension, bits, repeat_first_field);
835     COPY_FIELD(picture_coding_extension, bits, progressive_frame);
836
837     gst_vaapi_dpb_mpeg2_get_references(
838         priv->dpb,
839         picture,
840         &prev_picture,
841         &next_picture
842     );
843
844     switch (pic_hdr->pic_type) {
845     case GST_MPEG_VIDEO_PICTURE_TYPE_B:
846         if (next_picture)
847             pic_param->backward_reference_picture = next_picture->surface_id;
848         if (prev_picture)
849             pic_param->forward_reference_picture = prev_picture->surface_id;
850         else if (!priv->closed_gop)
851             GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_SKIPPED);
852         break;
853     case GST_MPEG_VIDEO_PICTURE_TYPE_P:
854         if (prev_picture)
855             pic_param->forward_reference_picture = prev_picture->surface_id;
856         break;
857     }
858     return TRUE;
859 }
860
861 static GstVaapiDecoderStatus
862 decode_slice(
863     GstVaapiDecoderMpeg2 *decoder,
864     int                   slice_no,
865     guchar               *buf,
866     guint                 buf_size
867 )
868 {
869     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
870     GstVaapiPicture * const picture = priv->current_picture;
871     GstVaapiSlice *slice;
872     VASliceParameterBufferMPEG2 *slice_param;
873     GstBitReader br;
874     gint mb_x, mb_y, mb_inc;
875     guint macroblock_offset;
876     guint8 slice_vertical_position_extension;
877     guint8 quantiser_scale_code;
878     guint8 intra_slice = 0;
879     guint8 extra_bit_slice, junk8;
880
881     GST_DEBUG("slice %d @ %p, %u bytes)", slice_no, buf, buf_size);
882
883     if (picture->slices->len == 0 && !fill_picture(decoder, picture))
884         return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
885
886     slice = GST_VAAPI_SLICE_NEW(MPEG2, decoder, buf, buf_size);
887     if (!slice) {
888         GST_ERROR("failed to allocate slice");
889         return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
890     }
891     gst_vaapi_picture_add_slice(picture, slice);
892
893     /* Parse slice */
894     gst_bit_reader_init(&br, buf, buf_size);
895     SKIP(&br, 32); /* slice_start_code */
896     if (priv->height > 2800)
897         READ_UINT8(&br, slice_vertical_position_extension, 3);
898     if (priv->has_seq_scalable_ext) {
899         GST_ERROR("failed to parse slice %d. Unsupported sequence_scalable_extension()", slice_no);
900         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
901     }
902     READ_UINT8(&br, quantiser_scale_code, 5);
903     READ_UINT8(&br, extra_bit_slice, 1);
904     if (extra_bit_slice == 1) {
905         READ_UINT8(&br, intra_slice, 1);
906         READ_UINT8(&br, junk8, 7);
907         READ_UINT8(&br, extra_bit_slice, 1);
908         while (extra_bit_slice == 1) {
909             READ_UINT8(&br, junk8, 8);
910             READ_UINT8(&br, extra_bit_slice, 1);
911         }
912     }
913     macroblock_offset = gst_bit_reader_get_pos(&br);
914
915     mb_y = slice_no;
916     mb_x = -1;
917     do {
918         if (!decode_vlc(&br, &mb_inc, mpeg2_mbaddr_vlc_table,
919                         G_N_ELEMENTS(mpeg2_mbaddr_vlc_table))) {
920             GST_WARNING("failed to decode first macroblock_address_increment");
921             goto failed;
922         }
923         mb_x += mb_inc == GST_MPEG_VIDEO_MACROBLOCK_ESCAPE ? 33 : mb_inc;
924     } while (mb_inc == GST_MPEG_VIDEO_MACROBLOCK_ESCAPE);
925
926     /* Fill in VASliceParameterBufferMPEG2 */
927     slice_param                            = slice->param;
928     slice_param->macroblock_offset         = macroblock_offset;
929     slice_param->slice_horizontal_position = mb_x;
930     slice_param->slice_vertical_position   = mb_y;
931     slice_param->quantiser_scale_code      = quantiser_scale_code;
932     slice_param->intra_slice_flag          = intra_slice;
933     return GST_VAAPI_DECODER_STATUS_SUCCESS;
934
935 failed:
936     return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
937 }
938
939 static inline gint
940 scan_for_start_code(GstAdapter *adapter, guint ofs, guint size, guint32 *scp)
941 {
942     return (gint)gst_adapter_masked_scan_uint32_peek(adapter,
943                                                      0xffffff00, 0x00000100,
944                                                      ofs, size,
945                                                      scp);
946 }
947
948 static GstVaapiDecoderStatus
949 decode_buffer(GstVaapiDecoderMpeg2 *decoder, GstBuffer *buffer)
950 {
951     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
952     GstVaapiDecoderStatus status;
953     gboolean is_eos;
954     guchar *buf;
955     guint buf_size, size;
956     guint32 start_code;
957     guint8 type;
958     gint ofs;
959
960     buf      = GST_BUFFER_DATA(buffer);
961     buf_size = GST_BUFFER_SIZE(buffer);
962     is_eos   = GST_BUFFER_IS_EOS(buffer);
963     if (buf && buf_size > 0)
964         gst_adapter_push(priv->adapter, gst_buffer_ref(buffer));
965
966     size = gst_adapter_available(priv->adapter);
967     do {
968         if (size == 0) {
969             status = GST_VAAPI_DECODER_STATUS_SUCCESS;
970             break;
971         }
972
973         status = GST_VAAPI_DECODER_STATUS_ERROR_NO_DATA;
974         if (size < 4)
975             break;
976         ofs = scan_for_start_code(priv->adapter, 0, size, &start_code);
977         if (ofs < 0)
978             break;
979         gst_adapter_flush(priv->adapter, ofs);
980         size -= ofs;
981
982         status = gst_vaapi_decoder_check_status(GST_VAAPI_DECODER(decoder));
983         if (status != GST_VAAPI_DECODER_STATUS_SUCCESS)
984             break;
985
986         status = GST_VAAPI_DECODER_STATUS_ERROR_NO_DATA;
987         if (size < 8)
988             break;
989         ofs = scan_for_start_code(priv->adapter, 4, size - 4, NULL);
990         if (ofs < 0) {
991             // Assume the whole packet is present if end-of-stream
992             if (!is_eos)
993                 break;
994             ofs = size;
995         }
996         buffer = gst_adapter_take_buffer(priv->adapter, ofs);
997         size -= ofs;
998
999         buf      = GST_BUFFER_DATA(buffer);
1000         buf_size = GST_BUFFER_SIZE(buffer);
1001
1002         type = start_code & 0xff;
1003         switch (type) {
1004         case GST_MPEG_VIDEO_PACKET_PICTURE:
1005             if (priv->width > 0 && priv->height > 0) {
1006                 status = decode_picture(decoder, buf, buf_size);
1007                 break;
1008             }
1009
1010             // Ignore packet while picture size is undefined
1011             // i.e. missing sequence headers, or not parsed correctly
1012         skip_picture_unknown_size:
1013             GST_WARNING("failed to parse picture of unknown size");
1014             status = GST_VAAPI_DECODER_STATUS_SUCCESS;
1015             break;
1016         case GST_MPEG_VIDEO_PACKET_SEQUENCE:
1017             status = decode_sequence(decoder, buf, buf_size);
1018             break;
1019         case GST_MPEG_VIDEO_PACKET_EXTENSION: {
1020             const guchar id = buf[4] >> 4;
1021             switch (id) {
1022             case GST_MPEG_VIDEO_PACKET_EXT_SEQUENCE:
1023                 status = decode_sequence_ext(decoder, buf, buf_size);
1024                 break;
1025             case GST_MPEG_VIDEO_PACKET_EXT_QUANT_MATRIX:
1026                 status = decode_quant_matrix_ext(decoder, buf, buf_size);
1027                 break;
1028             case GST_MPEG_VIDEO_PACKET_EXT_PICTURE:
1029                 if (priv->width > 0 && priv->height > 0) {
1030                     status = decode_picture_ext(decoder, buf, buf_size);
1031                     break;
1032                 }
1033                 goto skip_picture_unknown_size;
1034             default:
1035                 // Ignore unknown extensions
1036                 GST_WARNING("unsupported start-code extension (0x%02x)", id);
1037                 status = GST_VAAPI_DECODER_STATUS_SUCCESS;
1038                 break;
1039             }
1040             break;
1041         }
1042         case GST_MPEG_VIDEO_PACKET_SEQUENCE_END:
1043             status = decode_sequence_end(decoder);
1044             break;
1045         case GST_MPEG_VIDEO_PACKET_GOP:
1046             status = decode_gop(decoder, buf, buf_size);
1047             break;
1048         case GST_MPEG_VIDEO_PACKET_USER_DATA:
1049             // Ignore user-data packets
1050             status = GST_VAAPI_DECODER_STATUS_SUCCESS;
1051             break;
1052         default:
1053             if (type >= GST_MPEG_VIDEO_PACKET_SLICE_MIN &&
1054                 type <= GST_MPEG_VIDEO_PACKET_SLICE_MAX) {
1055                 if (!priv->current_picture) {
1056                     // Ignore packet while picture is undefined
1057                     // i.e. missing picture headers, or not parsed correctly
1058                     status = GST_VAAPI_DECODER_STATUS_SUCCESS;
1059                     break;
1060                 }
1061                 status = decode_slice(
1062                     decoder,
1063                     type - GST_MPEG_VIDEO_PACKET_SLICE_MIN,
1064                     buf, buf_size
1065                 );
1066                 break;
1067             }
1068             else if (type >= 0xb9 && type <= 0xff) {
1069                 // Ignore system start codes (PES headers)
1070                 status = GST_VAAPI_DECODER_STATUS_SUCCESS;
1071                 break;
1072             }
1073             GST_WARNING("unsupported start code (0x%02x)", type);
1074             status = GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
1075             break;
1076         }
1077         gst_buffer_unref(buffer);
1078     } while (status == GST_VAAPI_DECODER_STATUS_SUCCESS);
1079
1080     if (is_eos && (status == GST_VAAPI_DECODER_STATUS_SUCCESS ||
1081                    status == GST_VAAPI_DECODER_STATUS_ERROR_NO_DATA))
1082         status = decode_sequence_end(decoder);
1083     return status;
1084 }
1085
1086 GstVaapiDecoderStatus
1087 gst_vaapi_decoder_mpeg2_decode(GstVaapiDecoder *base, GstBuffer *buffer)
1088 {
1089     GstVaapiDecoderMpeg2 * const decoder = GST_VAAPI_DECODER_MPEG2(base);
1090     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
1091
1092     g_return_val_if_fail(priv->is_constructed,
1093                          GST_VAAPI_DECODER_STATUS_ERROR_INIT_FAILED);
1094
1095     if (!priv->is_opened) {
1096         priv->is_opened = gst_vaapi_decoder_mpeg2_open(decoder, buffer);
1097         if (!priv->is_opened)
1098             return GST_VAAPI_DECODER_STATUS_ERROR_UNSUPPORTED_CODEC;
1099     }
1100     return decode_buffer(decoder, buffer);
1101 }
1102
1103 static void
1104 gst_vaapi_decoder_mpeg2_finalize(GObject *object)
1105 {
1106     GstVaapiDecoderMpeg2 * const decoder = GST_VAAPI_DECODER_MPEG2(object);
1107
1108     gst_vaapi_decoder_mpeg2_destroy(decoder);
1109
1110     G_OBJECT_CLASS(gst_vaapi_decoder_mpeg2_parent_class)->finalize(object);
1111 }
1112
1113 static void
1114 gst_vaapi_decoder_mpeg2_constructed(GObject *object)
1115 {
1116     GstVaapiDecoderMpeg2 * const decoder = GST_VAAPI_DECODER_MPEG2(object);
1117     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
1118     GObjectClass *parent_class;
1119
1120     parent_class = G_OBJECT_CLASS(gst_vaapi_decoder_mpeg2_parent_class);
1121     if (parent_class->constructed)
1122         parent_class->constructed(object);
1123
1124     priv->is_constructed = gst_vaapi_decoder_mpeg2_create(decoder);
1125 }
1126
1127 static void
1128 gst_vaapi_decoder_mpeg2_class_init(GstVaapiDecoderMpeg2Class *klass)
1129 {
1130     GObjectClass * const object_class = G_OBJECT_CLASS(klass);
1131     GstVaapiDecoderClass * const decoder_class = GST_VAAPI_DECODER_CLASS(klass);
1132
1133     g_type_class_add_private(klass, sizeof(GstVaapiDecoderMpeg2Private));
1134
1135     object_class->finalize      = gst_vaapi_decoder_mpeg2_finalize;
1136     object_class->constructed   = gst_vaapi_decoder_mpeg2_constructed;
1137
1138     decoder_class->decode       = gst_vaapi_decoder_mpeg2_decode;
1139 }
1140
1141 static void
1142 gst_vaapi_decoder_mpeg2_init(GstVaapiDecoderMpeg2 *decoder)
1143 {
1144     GstVaapiDecoderMpeg2Private *priv;
1145
1146     priv                        = GST_VAAPI_DECODER_MPEG2_GET_PRIVATE(decoder);
1147     decoder->priv               = priv;
1148     priv->width                 = 0;
1149     priv->height                = 0;
1150     priv->fps_n                 = 0;
1151     priv->fps_d                 = 0;
1152     priv->hw_profile            = GST_VAAPI_PROFILE_UNKNOWN;
1153     priv->profile               = GST_VAAPI_PROFILE_MPEG2_SIMPLE;
1154     priv->current_picture       = NULL;
1155     priv->adapter               = NULL;
1156     priv->is_constructed        = FALSE;
1157     priv->is_opened             = FALSE;
1158     priv->has_seq_ext           = FALSE;
1159     priv->has_seq_scalable_ext  = FALSE;
1160     priv->has_pic_ext           = FALSE;
1161     priv->has_quant_matrix_ext  = FALSE;
1162     priv->size_changed          = FALSE;
1163     priv->profile_changed       = TRUE; /* Allow fallbacks to work */
1164     priv->quant_matrix_changed  = FALSE;
1165     priv->progressive_sequence  = FALSE;
1166     priv->closed_gop            = FALSE;
1167     priv->broken_link           = FALSE;
1168 }
1169
1170 /**
1171  * gst_vaapi_decoder_mpeg2_new:
1172  * @display: a #GstVaapiDisplay
1173  * @caps: a #GstCaps holding codec information
1174  *
1175  * Creates a new #GstVaapiDecoder for MPEG-2 decoding.  The @caps can
1176  * hold extra information like codec-data and pictured coded size.
1177  *
1178  * Return value: the newly allocated #GstVaapiDecoder object
1179  */
1180 GstVaapiDecoder *
1181 gst_vaapi_decoder_mpeg2_new(GstVaapiDisplay *display, GstCaps *caps)
1182 {
1183     GstVaapiDecoderMpeg2 *decoder;
1184
1185     g_return_val_if_fail(GST_VAAPI_IS_DISPLAY(display), NULL);
1186     g_return_val_if_fail(GST_IS_CAPS(caps), NULL);
1187
1188     decoder = g_object_new(
1189         GST_VAAPI_TYPE_DECODER_MPEG2,
1190         "display",      display,
1191         "caps",         caps,
1192         NULL
1193     );
1194     if (!decoder->priv->is_constructed) {
1195         g_object_unref(decoder);
1196         return NULL;
1197     }
1198     return GST_VAAPI_DECODER_CAST(decoder);
1199 }