mpeg2: fix size calculation from sequence_extension().
[platform/upstream/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_priv.h"
34 #include "gstvaapidisplay_priv.h"
35 #include "gstvaapiobject_priv.h"
36
37 #define DEBUG 1
38 #include "gstvaapidebug.h"
39
40 G_DEFINE_TYPE(GstVaapiDecoderMpeg2,
41               gst_vaapi_decoder_mpeg2,
42               GST_VAAPI_TYPE_DECODER);
43
44 #define GST_VAAPI_DECODER_MPEG2_GET_PRIVATE(obj)                \
45     (G_TYPE_INSTANCE_GET_PRIVATE((obj),                         \
46                                  GST_VAAPI_TYPE_DECODER_MPEG2,  \
47                                  GstVaapiDecoderMpeg2Private))
48
49 #define READ_UINT8(br, val, nbits) G_STMT_START {  \
50   if (!gst_bit_reader_get_bits_uint8 (br, &val, nbits)) { \
51     GST_WARNING ("failed to read uint8, nbits: %d", nbits); \
52     goto failed; \
53   } \
54 } G_STMT_END
55
56 #define SKIP(reader, nbits) G_STMT_START { \
57   if (!gst_bit_reader_skip (reader, nbits)) { \
58     GST_WARNING ("failed to skip nbits: %d", nbits); \
59     goto failed; \
60   } \
61 } G_STMT_END
62
63 struct _GstVaapiDecoderMpeg2Private {
64     GstVaapiProfile             profile;
65     guint                       width;
66     guint                       height;
67     guint                       fps_n;
68     guint                       fps_d;
69     GstMpegVideoSequenceHdr     seq_hdr;
70     GstMpegVideoSequenceExt     seq_ext;
71     GstMpegVideoPictureHdr      pic_hdr;
72     GstMpegVideoPictureExt      pic_ext;
73     GstMpegVideoQuantMatrixExt  quant_matrix_ext;
74     GstVaapiPicture            *current_picture;
75     GstVaapiPicture            *next_picture;
76     GstVaapiPicture            *prev_picture;
77     GstAdapter                 *adapter;
78     GstClockTime                seq_pts;
79     GstClockTime                gop_pts;
80     GstClockTime                pts_diff;
81     guint                       is_constructed          : 1;
82     guint                       is_opened               : 1;
83     guint                       is_first_field          : 1;
84     guint                       has_seq_ext             : 1;
85     guint                       has_seq_scalable_ext    : 1;
86     guint                       has_pic_ext             : 1;
87     guint                       has_quant_matrix_ext    : 1;
88     guint                       size_changed            : 1;
89     guint                       profile_changed         : 1;
90     guint                       quant_matrix_changed    : 1;
91     guint                       progressive_sequence    : 1;
92     guint                       closed_gop              : 1;
93     guint                       broken_link             : 1;
94 };
95
96 /* VLC decoder from gst-plugins-bad */
97 typedef struct _VLCTable VLCTable;
98 struct _VLCTable {
99     gint  value;
100     guint cword;
101     guint cbits;
102 };
103
104 static gboolean
105 decode_vlc(GstBitReader *br, gint *res, const VLCTable *table, guint length)
106 {
107     guint8 i;
108     guint cbits = 0;
109     guint32 value = 0;
110
111     for (i = 0; i < length; i++) {
112         if (cbits != table[i].cbits) {
113             cbits = table[i].cbits;
114             if (!gst_bit_reader_peek_bits_uint32(br, &value, cbits)) {
115                 goto failed;
116             }
117         }
118
119         if (value == table[i].cword) {
120             SKIP(br, cbits);
121             if (res)
122                 *res = table[i].value;
123             return TRUE;
124         }
125     }
126     GST_DEBUG("failed to find VLC code");
127
128 failed:
129     GST_WARNING("failed to decode VLC, returning");
130     return FALSE;
131 }
132
133 enum {
134     GST_MPEG_VIDEO_MACROBLOCK_ESCAPE = -1,
135 };
136
137 /* Table B-1: Variable length codes for macroblock_address_increment */
138 static const VLCTable mpeg2_mbaddr_vlc_table[] = {
139     {  1, 0x01,  1 },
140     {  2, 0x03,  3 },
141     {  3, 0x02,  3 },
142     {  4, 0x03,  4 },
143     {  5, 0x02,  4 },
144     {  6, 0x03,  5 },
145     {  7, 0x02,  5 },
146     {  8, 0x07,  7 },
147     {  9, 0x06,  7 },
148     { 10, 0x0b,  8 },
149     { 11, 0x0a,  8 },
150     { 12, 0x09,  8 },
151     { 13, 0x08,  8 },
152     { 14, 0x07,  8 },
153     { 15, 0x06,  8 },
154     { 16, 0x17, 10 },
155     { 17, 0x16, 10 },
156     { 18, 0x15, 10 },
157     { 19, 0x14, 10 },
158     { 20, 0x13, 10 },
159     { 21, 0x12, 10 },
160     { 22, 0x23, 11 },
161     { 23, 0x22, 11 },
162     { 24, 0x21, 11 },
163     { 25, 0x20, 11 },
164     { 26, 0x1f, 11 },
165     { 27, 0x1e, 11 },
166     { 28, 0x1d, 11 },
167     { 29, 0x1c, 11 },
168     { 30, 0x1b, 11 },
169     { 31, 0x1a, 11 },
170     { 32, 0x19, 11 },
171     { 33, 0x18, 11 },
172     { GST_MPEG_VIDEO_MACROBLOCK_ESCAPE, 0x08, 11 }
173 };
174
175 static void
176 gst_vaapi_decoder_mpeg2_close(GstVaapiDecoderMpeg2 *decoder)
177 {
178     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
179
180     gst_vaapi_picture_replace(&priv->current_picture, NULL);
181     gst_vaapi_picture_replace(&priv->next_picture,    NULL);
182     gst_vaapi_picture_replace(&priv->prev_picture,    NULL);
183
184     if (priv->adapter) {
185         gst_adapter_clear(priv->adapter);
186         g_object_unref(priv->adapter);
187         priv->adapter = NULL;
188     }
189 }
190
191 static gboolean
192 gst_vaapi_decoder_mpeg2_open(GstVaapiDecoderMpeg2 *decoder, GstBuffer *buffer)
193 {
194     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
195
196     gst_vaapi_decoder_mpeg2_close(decoder);
197
198     priv->adapter = gst_adapter_new();
199     if (!priv->adapter)
200         return FALSE;
201     return TRUE;
202 }
203
204 static void
205 gst_vaapi_decoder_mpeg2_destroy(GstVaapiDecoderMpeg2 *decoder)
206 {
207     gst_vaapi_decoder_mpeg2_close(decoder);
208 }
209
210 static gboolean
211 gst_vaapi_decoder_mpeg2_create(GstVaapiDecoderMpeg2 *decoder)
212 {
213     if (!GST_VAAPI_DECODER_CODEC(decoder))
214         return FALSE;
215     return TRUE;
216 }
217
218 static inline void
219 copy_quant_matrix(guint8 dst[64], const guint8 src[64])
220 {
221     memcpy(dst, src, 64);
222 }
223
224 static GstVaapiDecoderStatus
225 ensure_context(GstVaapiDecoderMpeg2 *decoder)
226 {
227     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
228     GstVaapiProfile profiles[2];
229     GstVaapiEntrypoint entrypoint = GST_VAAPI_ENTRYPOINT_VLD;
230     guint i, n_profiles = 0;
231     gboolean reset_context = FALSE;
232
233     if (priv->profile_changed) {
234         GST_DEBUG("profile changed");
235         priv->profile_changed = FALSE;
236         reset_context         = TRUE;
237
238         profiles[n_profiles++] = priv->profile;
239         if (priv->profile == GST_VAAPI_PROFILE_MPEG2_SIMPLE)
240             profiles[n_profiles++] = GST_VAAPI_PROFILE_MPEG2_MAIN;
241
242         for (i = 0; i < n_profiles; i++) {
243             if (gst_vaapi_display_has_decoder(GST_VAAPI_DECODER_DISPLAY(decoder),
244                                               profiles[i], entrypoint))
245                 break;
246         }
247         if (i == n_profiles)
248             return GST_VAAPI_DECODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
249         priv->profile = profiles[i];
250     }
251
252     if (priv->size_changed) {
253         GST_DEBUG("size changed");
254         priv->size_changed = FALSE;
255         reset_context      = TRUE;
256     }
257
258     if (reset_context) {
259         reset_context = gst_vaapi_decoder_ensure_context(
260             GST_VAAPI_DECODER(decoder),
261             priv->profile,
262             entrypoint,
263             priv->width, priv->height
264         );
265         if (!reset_context)
266             return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
267     }
268     return GST_VAAPI_DECODER_STATUS_SUCCESS;
269 }
270
271 static GstVaapiDecoderStatus
272 ensure_quant_matrix(GstVaapiDecoderMpeg2 *decoder, GstVaapiPicture *picture)
273 {
274     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
275     VAIQMatrixBufferMPEG2 *iq_matrix;
276     guint8 *intra_quant_matrix = NULL;
277     guint8 *non_intra_quant_matrix = NULL;
278     guint8 *chroma_intra_quant_matrix = NULL;
279     guint8 *chroma_non_intra_quant_matrix = NULL;
280
281     if (!priv->quant_matrix_changed)
282         return GST_VAAPI_DECODER_STATUS_SUCCESS;
283
284     priv->quant_matrix_changed = FALSE;
285
286     picture->iq_matrix = GST_VAAPI_IQ_MATRIX_NEW(MPEG2, decoder);
287     if (!picture->iq_matrix) {
288         GST_DEBUG("failed to allocate IQ matrix");
289         return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
290     }
291     iq_matrix = picture->iq_matrix->param;
292
293     intra_quant_matrix     = priv->seq_hdr.intra_quantizer_matrix;
294     non_intra_quant_matrix = priv->seq_hdr.non_intra_quantizer_matrix;
295     if (priv->has_quant_matrix_ext) {
296         if (priv->quant_matrix_ext.load_intra_quantiser_matrix)
297             intra_quant_matrix = priv->quant_matrix_ext.intra_quantiser_matrix;
298         if (priv->quant_matrix_ext.load_non_intra_quantiser_matrix)
299             non_intra_quant_matrix = priv->quant_matrix_ext.non_intra_quantiser_matrix;
300         if (priv->quant_matrix_ext.load_chroma_intra_quantiser_matrix)
301             chroma_intra_quant_matrix = priv->quant_matrix_ext.chroma_intra_quantiser_matrix;
302         if (priv->quant_matrix_ext.load_chroma_non_intra_quantiser_matrix)
303             chroma_non_intra_quant_matrix = priv->quant_matrix_ext.chroma_non_intra_quantiser_matrix;
304     }
305
306     iq_matrix->load_intra_quantiser_matrix = intra_quant_matrix != NULL;
307     if (intra_quant_matrix)
308         copy_quant_matrix(iq_matrix->intra_quantiser_matrix,
309                           intra_quant_matrix);
310
311     iq_matrix->load_non_intra_quantiser_matrix = non_intra_quant_matrix != NULL;
312     if (non_intra_quant_matrix)
313         copy_quant_matrix(iq_matrix->non_intra_quantiser_matrix,
314                           non_intra_quant_matrix);
315
316     iq_matrix->load_chroma_intra_quantiser_matrix = chroma_intra_quant_matrix != NULL;
317     if (chroma_intra_quant_matrix)
318         copy_quant_matrix(iq_matrix->chroma_intra_quantiser_matrix,
319                           chroma_intra_quant_matrix);
320
321     iq_matrix->load_chroma_non_intra_quantiser_matrix = chroma_non_intra_quant_matrix != NULL;
322     if (chroma_non_intra_quant_matrix)
323         copy_quant_matrix(iq_matrix->chroma_non_intra_quantiser_matrix,
324                           chroma_non_intra_quant_matrix);
325     return GST_VAAPI_DECODER_STATUS_SUCCESS;
326 }
327
328 static inline GstVaapiDecoderStatus
329 render_picture(GstVaapiDecoderMpeg2 *decoder, GstVaapiPicture *picture)
330 {
331     if (!gst_vaapi_picture_output(picture))
332         return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
333     return GST_VAAPI_DECODER_STATUS_SUCCESS;
334 }
335
336 static GstVaapiDecoderStatus
337 decode_current_picture(GstVaapiDecoderMpeg2 *decoder)
338 {
339     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
340     GstVaapiPicture * const picture = priv->current_picture;
341     GstVaapiDecoderStatus status = GST_VAAPI_DECODER_STATUS_SUCCESS;
342
343     if (picture) {
344         if (!gst_vaapi_picture_decode(picture))
345             status = GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
346         if (!GST_VAAPI_PICTURE_IS_REFERENCE(picture)) {
347             if ((priv->prev_picture && priv->next_picture) ||
348                 (priv->closed_gop && priv->next_picture))
349                 status = render_picture(decoder, picture);
350         }
351         gst_vaapi_picture_replace(&priv->current_picture, NULL);
352     }
353     return status;
354 }
355
356 static GstVaapiDecoderStatus
357 decode_sequence(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
358 {
359     GstVaapiDecoder * const base_decoder = GST_VAAPI_DECODER(decoder);
360     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
361     GstMpegVideoSequenceHdr * const seq_hdr = &priv->seq_hdr;
362
363     if (!gst_mpeg_video_parse_sequence_header(seq_hdr, buf, buf_size, 0)) {
364         GST_DEBUG("failed to parse sequence header");
365         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
366     }
367
368     priv->fps_n = seq_hdr->fps_n;
369     priv->fps_d = seq_hdr->fps_d;
370     gst_vaapi_decoder_set_framerate(base_decoder, priv->fps_n, priv->fps_d);
371
372     priv->seq_pts = gst_adapter_prev_timestamp(priv->adapter, NULL);
373
374     priv->width                 = seq_hdr->width;
375     priv->height                = seq_hdr->height;
376     priv->has_seq_ext           = FALSE;
377     priv->size_changed          = TRUE;
378     priv->quant_matrix_changed  = TRUE;
379     priv->progressive_sequence  = TRUE;
380     return GST_VAAPI_DECODER_STATUS_SUCCESS;
381 }
382
383 static GstVaapiDecoderStatus
384 decode_sequence_ext(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
385 {
386     GstVaapiDecoder * const base_decoder = GST_VAAPI_DECODER(decoder);
387     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
388     GstMpegVideoSequenceExt * const seq_ext = &priv->seq_ext;
389     GstVaapiProfile profile;
390     guint width, height;
391
392     if (!gst_mpeg_video_parse_sequence_extension(seq_ext, buf, buf_size, 0)) {
393         GST_DEBUG("failed to parse sequence-extension");
394         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
395     }
396     priv->has_seq_ext = TRUE;
397     priv->progressive_sequence = seq_ext->progressive;
398
399     width  = (priv->width  & 0x0fff) | ((guint32)seq_ext->horiz_size_ext << 12);
400     height = (priv->height & 0x0fff) | ((guint32)seq_ext->vert_size_ext  << 12);
401     GST_DEBUG("video resolution %ux%u", width, height);
402
403     if (seq_ext->fps_n_ext && seq_ext->fps_d_ext) {
404         priv->fps_n *= seq_ext->fps_n_ext + 1;
405         priv->fps_d *= seq_ext->fps_d_ext + 1;
406         gst_vaapi_decoder_set_framerate(base_decoder, priv->fps_n, priv->fps_d);
407     }
408
409     if (priv->width != width) {
410         priv->width = width;
411         priv->size_changed = TRUE;
412     }
413
414     if (priv->height != height) {
415         priv->height = height;
416         priv->size_changed = TRUE;
417     }
418
419     switch (seq_ext->profile) {
420     case GST_MPEG_VIDEO_PROFILE_SIMPLE:
421         profile = GST_VAAPI_PROFILE_MPEG2_SIMPLE;
422         break;
423     case GST_MPEG_VIDEO_PROFILE_MAIN:
424         profile = GST_VAAPI_PROFILE_MPEG2_MAIN;
425         break;
426     default:
427         GST_DEBUG("unsupported profile %d", seq_ext->profile);
428         return GST_VAAPI_DECODER_STATUS_ERROR_UNSUPPORTED_PROFILE;
429     }
430     if (priv->profile != profile) {
431         priv->profile = profile;
432         priv->profile_changed = TRUE;
433     }
434     return GST_VAAPI_DECODER_STATUS_SUCCESS;
435 }
436
437 static GstVaapiDecoderStatus
438 decode_sequence_end(GstVaapiDecoderMpeg2 *decoder)
439 {
440     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
441     GstVaapiDecoderStatus status;
442
443     if (priv->current_picture) {
444         status = decode_current_picture(decoder);
445         if (status != GST_VAAPI_DECODER_STATUS_SUCCESS)
446             return status;
447     }
448
449     if (priv->next_picture) {
450         status = render_picture(decoder, priv->next_picture);
451         if (status != GST_VAAPI_DECODER_STATUS_SUCCESS)
452             return status;
453     }
454     return GST_VAAPI_DECODER_STATUS_END_OF_STREAM;
455 }
456
457 static GstVaapiDecoderStatus
458 decode_quant_matrix_ext(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
459 {
460     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
461     GstMpegVideoQuantMatrixExt * const quant_matrix_ext = &priv->quant_matrix_ext;
462
463     if (!gst_mpeg_video_parse_quant_matrix_extension(quant_matrix_ext, buf, buf_size, 0)) {
464         GST_DEBUG("failed to parse quant-matrix-extension");
465         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
466     }
467     priv->has_quant_matrix_ext = TRUE;
468     priv->quant_matrix_changed = TRUE;
469     return GST_VAAPI_DECODER_STATUS_SUCCESS;
470 }
471
472 static GstVaapiDecoderStatus
473 decode_gop(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
474 {
475     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
476     GstMpegVideoGop gop;
477     GstClockTime pts;
478
479     if (!gst_mpeg_video_parse_gop(&gop, buf, buf_size, 0)) {
480         GST_DEBUG("failed to parse GOP");
481         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
482     }
483
484     priv->closed_gop  = gop.closed_gop;
485     priv->broken_link = gop.broken_link;
486
487     GST_DEBUG("GOP %02u:%02u:%02u:%02u (closed_gop %d, broken_link %d)",
488               gop.hour, gop.minute, gop.second, gop.frame,
489               priv->closed_gop, priv->broken_link);
490
491     pts = GST_SECOND * (gop.hour * 3600 + gop.minute * 60 + gop.second);
492     pts += gst_util_uint64_scale(gop.frame, GST_SECOND * priv->fps_d, priv->fps_n);
493     priv->gop_pts = pts;
494     if (!priv->pts_diff)
495         priv->pts_diff = priv->seq_pts - priv->gop_pts;
496
497     priv->is_first_field = TRUE;
498     return GST_VAAPI_DECODER_STATUS_SUCCESS;
499 }
500
501 static GstVaapiDecoderStatus
502 decode_picture(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
503 {
504     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
505     GstMpegVideoPictureHdr * const pic_hdr = &priv->pic_hdr;
506     GstVaapiPicture *picture;
507     GstVaapiDecoderStatus status;
508     GstClockTime pts;
509
510     status = ensure_context(decoder);
511     if (status != GST_VAAPI_DECODER_STATUS_SUCCESS) {
512         GST_DEBUG("failed to reset context");
513         return status;
514     }
515
516     if (priv->current_picture) {
517         status = decode_current_picture(decoder);
518         if (status != GST_VAAPI_DECODER_STATUS_SUCCESS)
519             return status;
520     }
521
522     priv->current_picture = GST_VAAPI_PICTURE_NEW(MPEG2, decoder);
523     if (!priv->current_picture) {
524         GST_DEBUG("failed to allocate picture");
525         return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
526     }
527     picture = priv->current_picture;
528
529     status = ensure_quant_matrix(decoder, picture);
530     if (status != GST_VAAPI_DECODER_STATUS_SUCCESS) {
531         GST_DEBUG("failed to reset quantizer matrix");
532         return status;
533     }
534
535     if (!gst_mpeg_video_parse_picture_header(pic_hdr, buf, buf_size, 0)) {
536         GST_DEBUG("failed to parse picture header");
537         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
538     }
539     priv->has_pic_ext = FALSE;
540
541     switch (pic_hdr->pic_type) {
542     case GST_MPEG_VIDEO_PICTURE_TYPE_I:
543         picture->type = GST_VAAPI_PICTURE_TYPE_I;
544         break;
545     case GST_MPEG_VIDEO_PICTURE_TYPE_P:
546         picture->type = GST_VAAPI_PICTURE_TYPE_P;
547         break;
548     case GST_MPEG_VIDEO_PICTURE_TYPE_B:
549         picture->type = GST_VAAPI_PICTURE_TYPE_B;
550         break;
551     default:
552         GST_DEBUG("unsupported picture type %d", pic_hdr->pic_type);
553         return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
554     }
555
556     /* Update presentation time */
557     pts = priv->gop_pts;
558     pts += gst_util_uint64_scale(pic_hdr->tsn, GST_SECOND * priv->fps_d, priv->fps_n);
559     picture->pts = pts + priv->pts_diff;
560
561     /* Update reference pictures */
562     if (pic_hdr->pic_type != GST_MPEG_VIDEO_PICTURE_TYPE_B) {
563         GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_REFERENCE);
564         if (priv->next_picture)
565             status = render_picture(decoder, priv->next_picture);
566         gst_vaapi_picture_replace(&priv->prev_picture, priv->next_picture);
567         gst_vaapi_picture_replace(&priv->next_picture, picture);
568     }
569     return status;
570 }
571
572 static GstVaapiDecoderStatus
573 decode_picture_ext(GstVaapiDecoderMpeg2 *decoder, guchar *buf, guint buf_size)
574 {
575     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
576     GstMpegVideoPictureExt * const pic_ext = &priv->pic_ext;
577     GstVaapiPicture * const picture = priv->current_picture;
578
579     if (!gst_mpeg_video_parse_picture_extension(pic_ext, buf, buf_size, 0)) {
580         GST_DEBUG("failed to parse picture-extension");
581         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
582     }
583     priv->has_pic_ext = TRUE;
584
585     switch (pic_ext->picture_structure) {
586     case GST_MPEG_VIDEO_PICTURE_STRUCTURE_TOP_FIELD:
587         GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_TOP_FIELD);
588         break;
589     case GST_MPEG_VIDEO_PICTURE_STRUCTURE_BOTTOM_FIELD:
590         GST_VAAPI_PICTURE_FLAG_SET(picture, GST_VAAPI_PICTURE_FLAG_BOTTOM_FIELD);
591         break;
592     }
593     return GST_VAAPI_DECODER_STATUS_SUCCESS;
594 }
595
596 static inline guint32
597 pack_f_code(guint8 f_code[2][2])
598 {
599     return (((guint32)f_code[0][0] << 12) |
600             ((guint32)f_code[0][1] <<  8) |
601             ((guint32)f_code[1][0] <<  4) |
602             (         f_code[1][1]      ));
603 }
604
605 static gboolean
606 fill_picture(GstVaapiDecoderMpeg2 *decoder, GstVaapiPicture *picture)
607 {
608     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
609     VAPictureParameterBufferMPEG2 * const pic_param = picture->param;
610     GstMpegVideoPictureHdr * const pic_hdr = &priv->pic_hdr;
611     GstMpegVideoPictureExt * const pic_ext = &priv->pic_ext;
612
613     if (!priv->has_pic_ext)
614         return FALSE;
615
616     /* Fill in VAPictureParameterBufferMPEG2 */
617     pic_param->horizontal_size                                          = priv->width;
618     pic_param->vertical_size                                            = priv->height;
619     pic_param->forward_reference_picture                                = VA_INVALID_ID;
620     pic_param->backward_reference_picture                               = VA_INVALID_ID;
621     pic_param->picture_coding_type                                      = pic_hdr->pic_type;
622     pic_param->f_code                                                   = pack_f_code(pic_ext->f_code);
623
624 #define COPY_FIELD(a, b, f) \
625     pic_param->a.b.f = pic_ext->f
626     pic_param->picture_coding_extension.value                           = 0;
627     pic_param->picture_coding_extension.bits.is_first_field             = priv->is_first_field;
628     COPY_FIELD(picture_coding_extension, bits, intra_dc_precision);
629     COPY_FIELD(picture_coding_extension, bits, picture_structure);
630     COPY_FIELD(picture_coding_extension, bits, top_field_first);
631     COPY_FIELD(picture_coding_extension, bits, frame_pred_frame_dct);
632     COPY_FIELD(picture_coding_extension, bits, concealment_motion_vectors);
633     COPY_FIELD(picture_coding_extension, bits, q_scale_type);
634     COPY_FIELD(picture_coding_extension, bits, intra_vlc_format);
635     COPY_FIELD(picture_coding_extension, bits, alternate_scan);
636     COPY_FIELD(picture_coding_extension, bits, repeat_first_field);
637     COPY_FIELD(picture_coding_extension, bits, progressive_frame);
638
639     switch (pic_hdr->pic_type) {
640     case GST_MPEG_VIDEO_PICTURE_TYPE_B:
641         if (priv->next_picture)
642             pic_param->backward_reference_picture = priv->next_picture->surface_id;
643         // fall-through
644     case GST_MPEG_VIDEO_PICTURE_TYPE_P:
645         if (priv->prev_picture)
646             pic_param->forward_reference_picture = priv->prev_picture->surface_id;
647         break;
648     }
649     return TRUE;
650 }
651
652 static GstVaapiDecoderStatus
653 decode_slice(
654     GstVaapiDecoderMpeg2 *decoder,
655     int                   slice_no,
656     guchar               *buf,
657     guint                 buf_size
658 )
659 {
660     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
661     GstVaapiPicture * const picture = priv->current_picture;
662     GstVaapiSlice *slice;
663     VASliceParameterBufferMPEG2 *slice_param;
664     GstBitReader br;
665     gint mb_x, mb_y, mb_inc;
666     guint macroblock_offset;
667     guint8 slice_vertical_position_extension;
668     guint8 quantiser_scale_code;
669     guint8 intra_slice_flag, intra_slice = 0;
670     guint8 extra_bit_slice, junk8;
671
672     GST_DEBUG("slice %d @ %p, %u bytes)", slice_no, buf, buf_size);
673
674     if (picture->slices->len == 0) {
675         if (!fill_picture(decoder, picture))
676             return GST_VAAPI_DECODER_STATUS_ERROR_UNKNOWN;
677
678         if (!priv->pic_ext.progressive_frame)
679             priv->is_first_field ^= 1;
680     }
681
682     slice = GST_VAAPI_SLICE_NEW(MPEG2, decoder, buf, buf_size);
683     if (!slice) {
684         GST_DEBUG("failed to allocate slice");
685         return GST_VAAPI_DECODER_STATUS_ERROR_ALLOCATION_FAILED;
686     }
687     gst_vaapi_picture_add_slice(picture, slice);
688
689     /* Parse slice */
690     gst_bit_reader_init(&br, buf, buf_size);
691     if (priv->height > 2800)
692         READ_UINT8(&br, slice_vertical_position_extension, 3);
693     if (priv->has_seq_scalable_ext) {
694         GST_DEBUG("failed to parse slice %d. Unsupported sequence_scalable_extension()", slice_no);
695         return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
696     }
697     READ_UINT8(&br, quantiser_scale_code, 5);
698     READ_UINT8(&br, extra_bit_slice, 1);
699     if (extra_bit_slice == 1) {
700         READ_UINT8(&br, intra_slice_flag, 1);
701         if (intra_slice_flag) {
702             READ_UINT8(&br, intra_slice, 1);
703             READ_UINT8(&br, junk8, 7);
704         }
705         READ_UINT8(&br, extra_bit_slice, 1);
706         while (extra_bit_slice == 1) {
707             READ_UINT8(&br, junk8, 8);
708             READ_UINT8(&br, extra_bit_slice, 1);
709         }
710     }
711     macroblock_offset = gst_bit_reader_get_pos(&br);
712
713     mb_y = slice_no << !GST_VAAPI_PICTURE_IS_FRAME(picture);
714     if (GST_VAAPI_PICTURE_IS_BOTTOM_FIELD(picture))
715         mb_y++;
716
717     mb_x = -1;
718     do {
719         if (!decode_vlc(&br, &mb_inc, mpeg2_mbaddr_vlc_table,
720                         G_N_ELEMENTS(mpeg2_mbaddr_vlc_table))) {
721             GST_WARNING("failed to decode first macroblock_address_increment");
722             goto failed;
723         }
724         mb_x += mb_inc == GST_MPEG_VIDEO_MACROBLOCK_ESCAPE ? 33 : mb_inc;
725     } while (mb_inc == GST_MPEG_VIDEO_MACROBLOCK_ESCAPE);
726
727     /* Fill in VASliceParameterBufferMPEG2 */
728     slice_param                            = slice->param;
729     slice_param->macroblock_offset         = macroblock_offset;
730     slice_param->slice_horizontal_position = mb_x;
731     slice_param->slice_vertical_position   = mb_y;
732     slice_param->quantiser_scale_code      = quantiser_scale_code;
733     slice_param->intra_slice_flag          = intra_slice;
734     return GST_VAAPI_DECODER_STATUS_SUCCESS;
735
736 failed:
737     return GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
738 }
739
740 static inline gint
741 scan_for_start_code(GstAdapter *adapter, guint ofs, guint size, guint32 *scp)
742 {
743     return (gint)gst_adapter_masked_scan_uint32_peek(adapter,
744                                                      0xffffff00, 0x00000100,
745                                                      ofs, size,
746                                                      scp);
747 }
748
749 static GstVaapiDecoderStatus
750 decode_buffer(GstVaapiDecoderMpeg2 *decoder, GstBuffer *buffer)
751 {
752     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
753     GstVaapiDecoderStatus status;
754     guchar *buf;
755     guint buf_size, size;
756     guint32 start_code;
757     guint8 type;
758     gint ofs;
759
760     buf      = GST_BUFFER_DATA(buffer);
761     buf_size = GST_BUFFER_SIZE(buffer);
762     if (!buf && buf_size == 0)
763         return decode_sequence_end(decoder);
764
765     gst_adapter_push(priv->adapter, gst_buffer_ref(buffer));
766
767     size   = gst_adapter_available(priv->adapter);
768     status = GST_VAAPI_DECODER_STATUS_ERROR_NO_DATA;
769     do {
770         if (size < 8)
771             break;
772         ofs = scan_for_start_code(priv->adapter, 0, size, &start_code);
773         if (ofs < 0)
774             break;
775         gst_adapter_flush(priv->adapter, ofs);
776         size -= ofs;
777
778         status = gst_vaapi_decoder_check_status(GST_VAAPI_DECODER(decoder));
779         if (status != GST_VAAPI_DECODER_STATUS_SUCCESS)
780             break;
781
782         if (size < 8)
783             break;
784         ofs = scan_for_start_code(priv->adapter, 4, size - 4, NULL);
785         if (ofs < 0)
786             break;
787         gst_adapter_flush(priv->adapter, 4);
788         size -= ofs;
789
790         buffer   = gst_adapter_take_buffer(priv->adapter, ofs - 4);
791         buf      = GST_BUFFER_DATA(buffer);
792         buf_size = GST_BUFFER_SIZE(buffer);
793
794         type = start_code & 0xff;
795         switch (type) {
796         case GST_MPEG_VIDEO_PACKET_PICTURE:
797             status = decode_picture(decoder, buf, buf_size);
798             break;
799         case GST_MPEG_VIDEO_PACKET_SEQUENCE:
800             status = decode_sequence(decoder, buf, buf_size);
801             break;
802         case GST_MPEG_VIDEO_PACKET_EXTENSION: {
803             const guchar id = buf[0] >> 4;
804             switch (id) {
805             case GST_MPEG_VIDEO_PACKET_EXT_SEQUENCE:
806                 status = decode_sequence_ext(decoder, buf, buf_size);
807                 break;
808             case GST_MPEG_VIDEO_PACKET_EXT_QUANT_MATRIX:
809                 status = decode_quant_matrix_ext(decoder, buf, buf_size);
810                 break;
811             case GST_MPEG_VIDEO_PACKET_EXT_PICTURE:
812                 status = decode_picture_ext(decoder, buf, buf_size);
813                 break;
814             default:
815                 // Ignore unknown extensions
816                 GST_DEBUG("unsupported start-code extension (0x%02x)", id);
817                 break;
818             }
819             break;
820         }
821         case GST_MPEG_VIDEO_PACKET_SEQUENCE_END:
822             status = decode_sequence_end(decoder);
823             break;
824         case GST_MPEG_VIDEO_PACKET_GOP:
825             status = decode_gop(decoder, buf, buf_size);
826             break;
827         case GST_MPEG_VIDEO_PACKET_USER_DATA:
828             // Ignore user-data packets
829             status = GST_VAAPI_DECODER_STATUS_SUCCESS;
830             break;
831         default:
832             if (type >= GST_MPEG_VIDEO_PACKET_SLICE_MIN &&
833                 type <= GST_MPEG_VIDEO_PACKET_SLICE_MAX) {
834                 status = decode_slice(
835                     decoder,
836                     type - GST_MPEG_VIDEO_PACKET_SLICE_MIN,
837                     buf, buf_size
838                 );
839                 break;
840             }
841             else if (type >= 0xb9 && type <= 0xff) {
842                 // Ignore system start codes (PES headers)
843                 status = GST_VAAPI_DECODER_STATUS_SUCCESS;
844                 break;
845             }
846             GST_DEBUG("unsupported start code (0x%02x)", type);
847             status = GST_VAAPI_DECODER_STATUS_ERROR_BITSTREAM_PARSER;
848             break;
849         }
850         gst_buffer_unref(buffer);
851     } while (status == GST_VAAPI_DECODER_STATUS_SUCCESS);
852     return status;
853 }
854
855 GstVaapiDecoderStatus
856 gst_vaapi_decoder_mpeg2_decode(GstVaapiDecoder *base, GstBuffer *buffer)
857 {
858     GstVaapiDecoderMpeg2 * const decoder = GST_VAAPI_DECODER_MPEG2(base);
859     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
860
861     g_return_val_if_fail(priv->is_constructed,
862                          GST_VAAPI_DECODER_STATUS_ERROR_INIT_FAILED);
863
864     if (!priv->is_opened) {
865         priv->is_opened = gst_vaapi_decoder_mpeg2_open(decoder, buffer);
866         if (!priv->is_opened)
867             return GST_VAAPI_DECODER_STATUS_ERROR_UNSUPPORTED_CODEC;
868     }
869     return decode_buffer(decoder, buffer);
870 }
871
872 static void
873 gst_vaapi_decoder_mpeg2_finalize(GObject *object)
874 {
875     GstVaapiDecoderMpeg2 * const decoder = GST_VAAPI_DECODER_MPEG2(object);
876
877     gst_vaapi_decoder_mpeg2_destroy(decoder);
878
879     G_OBJECT_CLASS(gst_vaapi_decoder_mpeg2_parent_class)->finalize(object);
880 }
881
882 static void
883 gst_vaapi_decoder_mpeg2_constructed(GObject *object)
884 {
885     GstVaapiDecoderMpeg2 * const decoder = GST_VAAPI_DECODER_MPEG2(object);
886     GstVaapiDecoderMpeg2Private * const priv = decoder->priv;
887     GObjectClass *parent_class;
888
889     parent_class = G_OBJECT_CLASS(gst_vaapi_decoder_mpeg2_parent_class);
890     if (parent_class->constructed)
891         parent_class->constructed(object);
892
893     priv->is_constructed = gst_vaapi_decoder_mpeg2_create(decoder);
894 }
895
896 static void
897 gst_vaapi_decoder_mpeg2_class_init(GstVaapiDecoderMpeg2Class *klass)
898 {
899     GObjectClass * const object_class = G_OBJECT_CLASS(klass);
900     GstVaapiDecoderClass * const decoder_class = GST_VAAPI_DECODER_CLASS(klass);
901
902     g_type_class_add_private(klass, sizeof(GstVaapiDecoderMpeg2Private));
903
904     object_class->finalize      = gst_vaapi_decoder_mpeg2_finalize;
905     object_class->constructed   = gst_vaapi_decoder_mpeg2_constructed;
906
907     decoder_class->decode       = gst_vaapi_decoder_mpeg2_decode;
908 }
909
910 static void
911 gst_vaapi_decoder_mpeg2_init(GstVaapiDecoderMpeg2 *decoder)
912 {
913     GstVaapiDecoderMpeg2Private *priv;
914
915     priv                        = GST_VAAPI_DECODER_MPEG2_GET_PRIVATE(decoder);
916     decoder->priv               = priv;
917     priv->width                 = 0;
918     priv->height                = 0;
919     priv->fps_n                 = 0;
920     priv->fps_d                 = 0;
921     priv->profile               = GST_VAAPI_PROFILE_MPEG2_SIMPLE;
922     priv->current_picture       = NULL;
923     priv->next_picture          = NULL;
924     priv->prev_picture          = NULL;
925     priv->adapter               = NULL;
926     priv->seq_pts               = GST_CLOCK_TIME_NONE;
927     priv->gop_pts               = GST_CLOCK_TIME_NONE;
928     priv->pts_diff              = 0;
929     priv->is_constructed        = FALSE;
930     priv->is_opened             = FALSE;
931     priv->is_first_field        = FALSE;
932     priv->has_seq_ext           = FALSE;
933     priv->has_seq_scalable_ext  = FALSE;
934     priv->has_pic_ext           = FALSE;
935     priv->has_quant_matrix_ext  = FALSE;
936     priv->size_changed          = FALSE;
937     priv->profile_changed       = FALSE;
938     priv->quant_matrix_changed  = FALSE;
939     priv->progressive_sequence  = FALSE;
940     priv->closed_gop            = FALSE;
941     priv->broken_link           = FALSE;
942 }
943
944 /**
945  * gst_vaapi_decoder_mpeg2_new:
946  * @display: a #GstVaapiDisplay
947  * @caps: a #GstCaps holding codec information
948  *
949  * Creates a new #GstVaapiDecoder for MPEG-2 decoding.  The @caps can
950  * hold extra information like codec-data and pictured coded size.
951  *
952  * Return value: the newly allocated #GstVaapiDecoder object
953  */
954 GstVaapiDecoder *
955 gst_vaapi_decoder_mpeg2_new(GstVaapiDisplay *display, GstCaps *caps)
956 {
957     GstVaapiDecoderMpeg2 *decoder;
958
959     g_return_val_if_fail(GST_VAAPI_IS_DISPLAY(display), NULL);
960     g_return_val_if_fail(GST_IS_CAPS(caps), NULL);
961
962     decoder = g_object_new(
963         GST_VAAPI_TYPE_DECODER_MPEG2,
964         "display",      display,
965         "caps",         caps,
966         NULL
967     );
968     if (!decoder->priv->is_constructed) {
969         g_object_unref(decoder);
970         return NULL;
971     }
972     return GST_VAAPI_DECODER_CAST(decoder);
973 }