va: Add and use common decode negotiate vmethod.
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / va / gstvah264dec.c
1 /* GStreamer
2  * Copyright (C) 2020 Igalia, S.L.
3  *     Author: Víctor Jáquez <vjaquez@igalia.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 the0
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 /**
22  * SECTION:element-vah264dec
23  * @title: vah264dec
24  * @short_description: A VA-API based H264 video decoder
25  *
26  * vah264dec decodes H264 bitstreams to VA surfaces using the
27  * installed and chosen [VA-API](https://01.org/linuxmedia/vaapi)
28  * driver.
29  *
30  * The decoding surfaces can be mapped onto main memory as video
31  * frames.
32  *
33  * ## Example launch line
34  * ```
35  * gst-launch-1.0 filesrc location=big_buck_bunny.mov ! parsebin ! vah264dec ! autovideosink
36  * ```
37  *
38  * Since: 1.18
39  *
40  */
41
42 /* ToDo:
43  *
44  * + mutiview and stereo profiles
45  */
46
47 #ifdef HAVE_CONFIG_H
48 #include "config.h"
49 #endif
50
51 #include "gstvah264dec.h"
52
53 #include "gstvabasedec.h"
54
55 GST_DEBUG_CATEGORY_STATIC (gst_va_h264dec_debug);
56 #ifndef GST_DISABLE_GST_DEBUG
57 #define GST_CAT_DEFAULT gst_va_h264dec_debug
58 #else
59 #define GST_CAT_DEFAULT NULL
60 #endif
61
62 #define GST_VA_H264_DEC(obj)           ((GstVaH264Dec *) obj)
63 #define GST_VA_H264_DEC_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), G_TYPE_FROM_INSTANCE (obj), GstVaH264DecClass))
64 #define GST_VA_H264_DEC_CLASS(klass)   ((GstVaH264DecClass *) klass)
65
66 typedef struct _GstVaH264Dec GstVaH264Dec;
67 typedef struct _GstVaH264DecClass GstVaH264DecClass;
68
69 struct _GstVaH264DecClass
70 {
71   GstVaBaseDecClass parent_class;
72 };
73
74 struct _GstVaH264Dec
75 {
76   GstVaBaseDec parent;
77
78   gint dpb_size;
79
80   /* Used to fill VAPictureParameterBufferH264.ReferenceFrames */
81   GArray *ref_list;
82
83   gboolean interlaced;
84 };
85
86 static GstElementClass *parent_class = NULL;
87
88 /* *INDENT-OFF* */
89 static const gchar *src_caps_str =
90     GST_VIDEO_CAPS_MAKE_WITH_FEATURES (GST_CAPS_FEATURE_MEMORY_VA,
91         "{ NV12, P010_10LE }") " ;"
92     GST_VIDEO_CAPS_MAKE ("{ NV12, P010_10LE }");
93 /* *INDENT-ON* */
94
95 static const gchar *sink_caps_str = "video/x-h264";
96
97 static GstFlowReturn
98 gst_va_h264_dec_end_picture (GstH264Decoder * decoder, GstH264Picture * picture)
99 {
100   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
101   GstVaDecodePicture *va_pic;
102
103   GST_LOG_OBJECT (base, "end picture %p, (poc %d)",
104       picture, picture->pic_order_cnt);
105
106   va_pic = gst_h264_picture_get_user_data (picture);
107
108   if (!gst_va_decoder_decode (base->decoder, va_pic))
109     return GST_FLOW_ERROR;
110
111   return GST_FLOW_OK;
112 }
113
114 static GstFlowReturn
115 gst_va_h264_dec_output_picture (GstH264Decoder * decoder,
116     GstVideoCodecFrame * frame, GstH264Picture * picture)
117 {
118   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
119   GstVaH264Dec *self = GST_VA_H264_DEC (decoder);
120   GstVideoDecoder *vdec = GST_VIDEO_DECODER (decoder);
121   gboolean ret;
122
123   GST_LOG_OBJECT (self,
124       "Outputting picture %p (poc %d)", picture, picture->pic_order_cnt);
125
126   ret = gst_va_base_dec_process_output (base, frame, picture->buffer_flags);
127   gst_h264_picture_unref (picture);
128
129   if (ret)
130     return gst_video_decoder_finish_frame (vdec, frame);
131   return GST_FLOW_ERROR;
132 }
133
134 static void
135 _init_vaapi_pic (VAPictureH264 * va_picture)
136 {
137   va_picture->picture_id = VA_INVALID_ID;
138   va_picture->frame_idx = 0;
139   va_picture->flags = VA_PICTURE_H264_INVALID;
140   va_picture->TopFieldOrderCnt = 0;
141   va_picture->BottomFieldOrderCnt = 0;
142 }
143
144 static void
145 _fill_vaapi_pic (VAPictureH264 * va_picture, GstH264Picture * picture,
146     gboolean merge_other_field)
147 {
148   GstVaDecodePicture *va_pic;
149
150   va_pic = gst_h264_picture_get_user_data (picture);
151
152   if (!va_pic) {
153     _init_vaapi_pic (va_picture);
154     return;
155   }
156
157   va_picture->picture_id = gst_va_decode_picture_get_surface (va_pic);
158   va_picture->flags = 0;
159
160   if (GST_H264_PICTURE_IS_LONG_TERM_REF (picture)) {
161     va_picture->flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
162     va_picture->frame_idx = picture->long_term_frame_idx;
163   } else {
164     if (GST_H264_PICTURE_IS_SHORT_TERM_REF (picture))
165       va_picture->flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
166     va_picture->frame_idx = picture->frame_num;
167   }
168
169   switch (picture->field) {
170     case GST_H264_PICTURE_FIELD_FRAME:
171       va_picture->TopFieldOrderCnt = picture->top_field_order_cnt;
172       va_picture->BottomFieldOrderCnt = picture->bottom_field_order_cnt;
173       break;
174     case GST_H264_PICTURE_FIELD_TOP_FIELD:
175       if (merge_other_field && picture->other_field) {
176         va_picture->BottomFieldOrderCnt =
177             picture->other_field->bottom_field_order_cnt;
178       } else {
179         va_picture->flags |= VA_PICTURE_H264_TOP_FIELD;
180         va_picture->BottomFieldOrderCnt = 0;
181       }
182       va_picture->TopFieldOrderCnt = picture->top_field_order_cnt;
183       break;
184     case GST_H264_PICTURE_FIELD_BOTTOM_FIELD:
185       if (merge_other_field && picture->other_field) {
186         va_picture->TopFieldOrderCnt =
187             picture->other_field->top_field_order_cnt;
188       } else {
189         va_picture->flags |= VA_PICTURE_H264_BOTTOM_FIELD;
190         va_picture->TopFieldOrderCnt = 0;
191       }
192       va_picture->BottomFieldOrderCnt = picture->bottom_field_order_cnt;
193       break;
194     default:
195       va_picture->TopFieldOrderCnt = 0;
196       va_picture->BottomFieldOrderCnt = 0;
197       break;
198   }
199 }
200
201 /* fill the VA API reference picture lists from the GstCodec reference
202  * picture list */
203 static void
204 _fill_ref_pic_list (VAPictureH264 va_reflist[32], GArray * reflist,
205     GstH264Picture * current_picture)
206 {
207   guint i;
208
209   for (i = 0; i < reflist->len; i++) {
210     GstH264Picture *picture = g_array_index (reflist, GstH264Picture *, i);
211
212     if (picture) {
213       _fill_vaapi_pic (&va_reflist[i], picture,
214           GST_H264_PICTURE_IS_FRAME (current_picture));
215     } else {
216       /* list might include null picture if reference picture was missing */
217       _init_vaapi_pic (&va_reflist[i]);
218     }
219   }
220
221   for (; i < 32; i++)
222     _init_vaapi_pic (&va_reflist[i]);
223 }
224
225 static void
226 _fill_pred_weight_table (GstH264SliceHdr * header,
227     VASliceParameterBufferH264 * slice_param)
228 {
229   GstH264PPS *pps;
230   GstH264SPS *sps;
231   guint num_weight_tables = 0;
232   gint i, j;
233
234   pps = header->pps;
235   sps = pps->sequence;
236
237   if (pps->weighted_pred_flag
238       && (GST_H264_IS_P_SLICE (header) || GST_H264_IS_SP_SLICE (header)))
239     num_weight_tables = 1;
240   else if (pps->weighted_bipred_idc == 1 && GST_H264_IS_B_SLICE (header))
241     num_weight_tables = 2;
242
243   if (num_weight_tables == 0)
244     return;
245
246   slice_param->luma_log2_weight_denom =
247       header->pred_weight_table.luma_log2_weight_denom;
248   slice_param->chroma_log2_weight_denom =
249       header->pred_weight_table.chroma_log2_weight_denom;
250
251   /* VA API also wants the inferred (default) values, not only what is
252    * available in the bitstream (7.4.3.2). */
253
254   slice_param->luma_weight_l0_flag = 1;
255   for (i = 0; i <= slice_param->num_ref_idx_l0_active_minus1; i++) {
256     slice_param->luma_weight_l0[i] =
257         header->pred_weight_table.luma_weight_l0[i];
258     slice_param->luma_offset_l0[i] =
259         header->pred_weight_table.luma_offset_l0[i];
260   }
261
262   slice_param->chroma_weight_l0_flag = sps->chroma_array_type != 0;
263   if (slice_param->chroma_weight_l0_flag) {
264     for (i = 0; i <= slice_param->num_ref_idx_l0_active_minus1; i++) {
265       for (j = 0; j < 2; j++) {
266         slice_param->chroma_weight_l0[i][j] =
267             header->pred_weight_table.chroma_weight_l0[i][j];
268         slice_param->chroma_offset_l0[i][j] =
269             header->pred_weight_table.chroma_offset_l0[i][j];
270       }
271     }
272   }
273
274   if (num_weight_tables == 1)
275     return;
276
277   slice_param->luma_weight_l1_flag = 1;
278   for (i = 0; i <= slice_param->num_ref_idx_l1_active_minus1; i++) {
279     slice_param->luma_weight_l1[i] =
280         header->pred_weight_table.luma_weight_l1[i];
281     slice_param->luma_offset_l1[i] =
282         header->pred_weight_table.luma_offset_l1[i];
283   }
284
285   slice_param->chroma_weight_l1_flag = sps->chroma_array_type != 0;
286   if (slice_param->chroma_weight_l1_flag) {
287     for (i = 0; i <= slice_param->num_ref_idx_l1_active_minus1; i++) {
288       for (j = 0; j < 2; j++) {
289         slice_param->chroma_weight_l1[i][j] =
290             header->pred_weight_table.chroma_weight_l1[i][j];
291         slice_param->chroma_offset_l1[i][j] =
292             header->pred_weight_table.chroma_offset_l1[i][j];
293       }
294     }
295   }
296 }
297
298 static inline guint
299 _get_slice_data_bit_offset (GstH264SliceHdr * header, guint nal_header_bytes)
300 {
301   guint epb_count;
302
303   epb_count = header->n_emulation_prevention_bytes;
304   return 8 * nal_header_bytes + header->header_size - epb_count * 8;
305 }
306
307 static GstFlowReturn
308 gst_va_h264_dec_decode_slice (GstH264Decoder * decoder,
309     GstH264Picture * picture, GstH264Slice * slice, GArray * ref_pic_list0,
310     GArray * ref_pic_list1)
311 {
312   GstH264SliceHdr *header = &slice->header;
313   GstH264NalUnit *nalu = &slice->nalu;
314   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
315   GstVaDecodePicture *va_pic;
316   VASliceParameterBufferH264 slice_param;
317
318   /* *INDENT-OFF* */
319   slice_param = (VASliceParameterBufferH264) {
320     .slice_data_size = nalu->size,
321     .slice_data_offset = 0,
322     .slice_data_flag = VA_SLICE_DATA_FLAG_ALL,
323     .slice_data_bit_offset =
324         _get_slice_data_bit_offset (header, nalu->header_bytes),
325     .first_mb_in_slice = header->first_mb_in_slice,
326     .slice_type = header->type % 5,
327     .direct_spatial_mv_pred_flag = header->direct_spatial_mv_pred_flag,
328     .cabac_init_idc = header->cabac_init_idc,
329     .slice_qp_delta = header->slice_qp_delta,
330     .disable_deblocking_filter_idc = header->disable_deblocking_filter_idc,
331     .slice_alpha_c0_offset_div2 = header->slice_alpha_c0_offset_div2,
332     .slice_beta_offset_div2 = header->slice_beta_offset_div2,
333     .num_ref_idx_l0_active_minus1 = header->num_ref_idx_l0_active_minus1,
334     .num_ref_idx_l1_active_minus1 = header->num_ref_idx_l1_active_minus1,
335   };
336   /* *INDENT-ON* */
337
338   _fill_ref_pic_list (slice_param.RefPicList0, ref_pic_list0, picture);
339   _fill_ref_pic_list (slice_param.RefPicList1, ref_pic_list1, picture);
340
341   _fill_pred_weight_table (header, &slice_param);
342
343   va_pic = gst_h264_picture_get_user_data (picture);
344
345   if (!gst_va_decoder_add_slice_buffer (base->decoder, va_pic, &slice_param,
346           sizeof (slice_param), slice->nalu.data + slice->nalu.offset,
347           slice->nalu.size)) {
348     return GST_FLOW_ERROR;
349   }
350
351   return GST_FLOW_OK;
352 }
353
354 static GstFlowReturn
355 gst_va_h264_dec_start_picture (GstH264Decoder * decoder,
356     GstH264Picture * picture, GstH264Slice * slice, GstH264Dpb * dpb)
357 {
358   GstVaH264Dec *self = GST_VA_H264_DEC (decoder);
359   GstH264PPS *pps;
360   GstH264SPS *sps;
361   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
362   GstVaDecodePicture *va_pic;
363   VAIQMatrixBufferH264 iq_matrix = { 0, };
364   VAPictureParameterBufferH264 pic_param;
365   guint i, n;
366   GArray *ref_list = self->ref_list;
367
368   va_pic = gst_h264_picture_get_user_data (picture);
369
370   pps = slice->header.pps;
371   sps = pps->sequence;
372
373   /* *INDENT-OFF* */
374   pic_param = (VAPictureParameterBufferH264) {
375     /* .CurrPic */
376     /* .ReferenceFrames */
377     .picture_width_in_mbs_minus1 = sps->pic_width_in_mbs_minus1,
378     .picture_height_in_mbs_minus1 =
379         ((sps->pic_height_in_map_units_minus1 + 1) <<
380             !sps->frame_mbs_only_flag) -1,
381     .bit_depth_luma_minus8 = sps->bit_depth_luma_minus8,
382     .bit_depth_chroma_minus8 = sps->bit_depth_chroma_minus8,
383     .num_ref_frames = sps->num_ref_frames,
384     .seq_fields.bits = {
385       .chroma_format_idc = sps->chroma_format_idc,
386       .residual_colour_transform_flag = sps->separate_colour_plane_flag,
387       .gaps_in_frame_num_value_allowed_flag =
388           sps->gaps_in_frame_num_value_allowed_flag,
389       .frame_mbs_only_flag = sps->frame_mbs_only_flag,
390       .mb_adaptive_frame_field_flag = sps->mb_adaptive_frame_field_flag,
391       .direct_8x8_inference_flag = sps->direct_8x8_inference_flag,
392       .MinLumaBiPredSize8x8 = sps->level_idc >= 31, /* A.3.3.2 */
393       .log2_max_frame_num_minus4 = sps->log2_max_frame_num_minus4,
394       .pic_order_cnt_type = sps->pic_order_cnt_type,
395       .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_pic_order_cnt_lsb_minus4,
396       .delta_pic_order_always_zero_flag = sps->delta_pic_order_always_zero_flag,
397     },
398     .pic_init_qp_minus26 = pps->pic_init_qp_minus26,
399     .pic_init_qs_minus26 = pps->pic_init_qs_minus26,
400     .chroma_qp_index_offset = pps->chroma_qp_index_offset,
401     .second_chroma_qp_index_offset = pps->second_chroma_qp_index_offset,
402     .pic_fields.bits = {
403       .entropy_coding_mode_flag = pps->entropy_coding_mode_flag,
404       .weighted_pred_flag = pps->weighted_pred_flag,
405       .weighted_bipred_idc = pps->weighted_bipred_idc,
406       .transform_8x8_mode_flag = pps->transform_8x8_mode_flag,
407       .field_pic_flag = slice->header.field_pic_flag,
408       .constrained_intra_pred_flag = pps->constrained_intra_pred_flag,
409       .pic_order_present_flag = pps->pic_order_present_flag,
410       .deblocking_filter_control_present_flag =
411           pps->deblocking_filter_control_present_flag,
412       .redundant_pic_cnt_present_flag = pps->redundant_pic_cnt_present_flag,
413       .reference_pic_flag = picture->nal_ref_idc != 0,
414     },
415     .frame_num = slice->header.frame_num,
416   };
417   /* *INDENT-ON* */
418
419   _fill_vaapi_pic (&pic_param.CurrPic, picture, FALSE);
420
421   /* reference frames */
422   {
423     guint ref_frame_idx = 0;
424     g_array_set_size (ref_list, 0);
425
426     gst_h264_dpb_get_pictures_short_term_ref (dpb, FALSE, FALSE, ref_list);
427     for (i = 0; ref_frame_idx < 16 && i < ref_list->len; i++) {
428       GstH264Picture *pic = g_array_index (ref_list, GstH264Picture *, i);
429       _fill_vaapi_pic (&pic_param.ReferenceFrames[ref_frame_idx++], pic, TRUE);
430     }
431     g_array_set_size (ref_list, 0);
432
433     gst_h264_dpb_get_pictures_long_term_ref (dpb, FALSE, ref_list);
434     for (i = 0; ref_frame_idx < 16 && i < ref_list->len; i++) {
435       GstH264Picture *pic = g_array_index (ref_list, GstH264Picture *, i);
436       _fill_vaapi_pic (&pic_param.ReferenceFrames[ref_frame_idx++], pic, TRUE);
437     }
438     g_array_set_size (ref_list, 0);
439
440     for (; ref_frame_idx < 16; ref_frame_idx++)
441       _init_vaapi_pic (&pic_param.ReferenceFrames[ref_frame_idx]);
442   }
443
444   if (!gst_va_decoder_add_param_buffer (base->decoder, va_pic,
445           VAPictureParameterBufferType, &pic_param, sizeof (pic_param)))
446     return GST_FLOW_ERROR;
447
448   /* there are always 6 4x4 scaling lists */
449   for (i = 0; i < 6; i++) {
450     gst_h264_quant_matrix_4x4_get_raster_from_zigzag (iq_matrix.ScalingList4x4
451         [i], pps->scaling_lists_4x4[i]);
452   }
453
454   /* We need the first 2 entries (Y intra and Y inter for YCbCr 4:2:2 and
455    * less, and the full 6 entries for 4:4:4, see Table 7-2 of the spec for
456    * more details */
457   n = (pps->sequence->chroma_format_idc == 3) ? 6 : 2;
458   for (i = 0; i < n; i++) {
459     gst_h264_quant_matrix_8x8_get_raster_from_zigzag (iq_matrix.ScalingList8x8
460         [i], pps->scaling_lists_8x8[i]);
461   }
462
463   if (!gst_va_decoder_add_param_buffer (base->decoder, va_pic,
464           VAIQMatrixBufferType, &iq_matrix, sizeof (iq_matrix)))
465     return GST_FLOW_ERROR;
466
467   return GST_FLOW_OK;
468 }
469
470 static GstFlowReturn
471 gst_va_h264_dec_new_picture (GstH264Decoder * decoder,
472     GstVideoCodecFrame * frame, GstH264Picture * picture)
473 {
474   GstVaH264Dec *self = GST_VA_H264_DEC (decoder);
475   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
476   GstVaDecodePicture *pic;
477   GstFlowReturn ret;
478
479   ret = gst_va_base_dec_prepare_output_frame (base, frame);
480   if (ret != GST_FLOW_OK)
481     goto error;
482
483   pic = gst_va_decode_picture_new (base->decoder, frame->output_buffer);
484
485   gst_h264_picture_set_user_data (picture, pic,
486       (GDestroyNotify) gst_va_decode_picture_free);
487
488   GST_LOG_OBJECT (self, "New va decode picture %p - %#x", pic,
489       gst_va_decode_picture_get_surface (pic));
490
491   return GST_FLOW_OK;
492
493 error:
494   {
495     GST_WARNING_OBJECT (self,
496         "Failed to allocated output buffer, return %s",
497         gst_flow_get_name (ret));
498     return ret;
499   }
500 }
501
502 static GstFlowReturn
503 gst_va_h264_dec_new_field_picture (GstH264Decoder * decoder,
504     GstH264Picture * first_field, GstH264Picture * second_field)
505 {
506   GstVaDecodePicture *first_pic, *second_pic;
507   GstVaH264Dec *self = GST_VA_H264_DEC (decoder);
508   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
509
510   first_pic = gst_h264_picture_get_user_data (first_field);
511   if (!first_pic)
512     return GST_FLOW_ERROR;
513
514   second_pic = gst_va_decode_picture_new (base->decoder, first_pic->gstbuffer);
515   gst_h264_picture_set_user_data (second_field, second_pic,
516       (GDestroyNotify) gst_va_decode_picture_free);
517
518   GST_LOG_OBJECT (self, "New va decode picture %p - %#x", second_pic,
519       gst_va_decode_picture_get_surface (second_pic));
520
521   return GST_FLOW_OK;
522 }
523
524 static inline guint
525 _get_num_views (const GstH264SPS * sps)
526 {
527   return 1 + (sps->extension_type == GST_H264_NAL_EXTENSION_MVC ?
528       sps->extension.mvc.num_views_minus1 : 0);
529 }
530
531 static guint
532 _get_rtformat (GstVaH264Dec * self, guint8 bit_depth_luma,
533     guint8 chroma_format_idc)
534 {
535   switch (bit_depth_luma) {
536     case 10:
537       if (chroma_format_idc == 3)
538         return VA_RT_FORMAT_YUV444_10;
539       if (chroma_format_idc == 2)
540         return VA_RT_FORMAT_YUV422_10;
541       else
542         return VA_RT_FORMAT_YUV420_10;
543       break;
544     case 8:
545       if (chroma_format_idc == 3)
546         return VA_RT_FORMAT_YUV444;
547       if (chroma_format_idc == 2)
548         return VA_RT_FORMAT_YUV422;
549       else
550         return VA_RT_FORMAT_YUV420;
551       break;
552     default:
553       GST_ERROR_OBJECT (self, "Unsupported chroma format: %d "
554           "(with depth luma: %d)", chroma_format_idc, bit_depth_luma);
555       return 0;
556   }
557 }
558
559 /* *INDENT-OFF* */
560 static const struct
561 {
562   GstH264Profile profile_idc;
563   VAProfile va_profile;
564 } profile_map[] = {
565 #define P(idc, va) { G_PASTE (GST_H264_PROFILE_, idc), G_PASTE (VAProfileH264, va) }
566   /* P (BASELINE, ), */
567   P (MAIN, Main),
568   /* P (EXTENDED, ), */
569   P (HIGH, High),
570   /* P (HIGH10, ), */
571   /* P (HIGH_422, ), */
572   /* P (HIGH_444, ), */
573   P (MULTIVIEW_HIGH, MultiviewHigh),
574   P (STEREO_HIGH, StereoHigh),
575   /* P (SCALABLE_BASELINE, ), */
576   /* P (SCALABLE_HIGH, ), */
577 #undef P
578 };
579 /* *INDENT-ON* */
580
581 static VAProfile
582 _get_profile (GstVaH264Dec * self, const GstH264SPS * sps, gint max_dpb_size)
583 {
584   GstVaBaseDec *base = GST_VA_BASE_DEC (self);
585   VAProfile profiles[4];
586   gint i = 0, j;
587
588   for (j = 0; j < G_N_ELEMENTS (profile_map); j++) {
589     if (profile_map[j].profile_idc == sps->profile_idc) {
590       profiles[i++] = profile_map[j].va_profile;
591       break;
592     }
593   }
594
595   switch (sps->profile_idc) {
596     case GST_H264_PROFILE_BASELINE:
597     {
598       GstH264DecoderCompliance compliance = GST_H264_DECODER_COMPLIANCE_STRICT;
599
600       g_object_get (G_OBJECT (self), "compliance", &compliance, NULL);
601
602       /* A.2 compliant or not strict */
603       if (sps->constraint_set0_flag || sps->constraint_set1_flag
604           || sps->constraint_set2_flag
605           || compliance != GST_H264_DECODER_COMPLIANCE_STRICT) {
606         profiles[i++] = VAProfileH264ConstrainedBaseline;
607         profiles[i++] = VAProfileH264Main;
608       }
609
610       break;
611     }
612     case GST_H264_PROFILE_EXTENDED:
613       if (sps->constraint_set1_flag) {  /* A.2.2 (main profile) */
614         profiles[i++] = VAProfileH264Main;
615       }
616       break;
617     case GST_H264_PROFILE_MULTIVIEW_HIGH:
618       if (_get_num_views (sps) == 2) {
619         profiles[i++] = VAProfileH264StereoHigh;
620       }
621       if (max_dpb_size <= 16 /* && i965 driver */ ) {
622         profiles[i++] = VAProfileH264MultiviewHigh;
623       }
624     default:
625       break;
626   }
627
628   for (j = 0; j < i && j < G_N_ELEMENTS (profiles); j++) {
629     if (gst_va_decoder_has_profile (base->decoder, profiles[j]))
630       return profiles[j];
631   }
632
633   GST_ERROR_OBJECT (self, "Unsupported profile: %d", sps->profile_idc);
634
635   return VAProfileNone;
636 }
637
638 static GstFlowReturn
639 gst_va_h264_dec_new_sequence (GstH264Decoder * decoder, const GstH264SPS * sps,
640     gint max_dpb_size)
641 {
642   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
643   GstVaH264Dec *self = GST_VA_H264_DEC (decoder);
644   GstVideoInfo *info = &base->output_info;
645   VAProfile profile;
646   gint display_width;
647   gint display_height;
648   gint padding_left, padding_right, padding_top, padding_bottom;
649   guint rt_format;
650   gboolean negotiation_needed = FALSE;
651   gboolean interlaced;
652
653   if (self->dpb_size < max_dpb_size)
654     self->dpb_size = max_dpb_size;
655
656   if (sps->frame_cropping_flag) {
657     display_width = sps->crop_rect_width;
658     display_height = sps->crop_rect_height;
659     padding_left = sps->crop_rect_x;
660     padding_right = sps->width - sps->crop_rect_x - display_width;
661     padding_top = sps->crop_rect_y;
662     padding_bottom = sps->height - sps->crop_rect_y - display_height;
663   } else {
664     display_width = sps->width;
665     display_height = sps->height;
666     padding_left = padding_right = padding_top = padding_bottom = 0;
667   }
668
669   profile = _get_profile (self, sps, max_dpb_size);
670   if (profile == VAProfileNone)
671     return GST_FLOW_NOT_NEGOTIATED;
672
673   rt_format = _get_rtformat (self, sps->bit_depth_luma_minus8 + 8,
674       sps->chroma_format_idc);
675   if (rt_format == 0)
676     return GST_FLOW_NOT_NEGOTIATED;
677
678   if (!gst_va_decoder_config_is_equal (base->decoder, profile,
679           rt_format, sps->width, sps->height)) {
680     base->profile = profile;
681     base->rt_format = rt_format;
682     base->width = sps->width;
683     base->height = sps->height;
684
685     negotiation_needed = TRUE;
686     GST_INFO_OBJECT (self, "Format changed to %s [%x] (%dx%d)",
687         gst_va_profile_name (profile), rt_format, base->width, base->height);
688   }
689
690   if (GST_VIDEO_INFO_WIDTH (info) != display_width ||
691       GST_VIDEO_INFO_HEIGHT (info) != display_height) {
692     GST_VIDEO_INFO_WIDTH (info) = display_width;
693     GST_VIDEO_INFO_HEIGHT (info) = display_height;
694
695     negotiation_needed = TRUE;
696     GST_INFO_OBJECT (self, "Resolution changed to %dx%d",
697         GST_VIDEO_INFO_WIDTH (info), GST_VIDEO_INFO_HEIGHT (info));
698   }
699
700   interlaced = !sps->frame_mbs_only_flag;
701   if (self->interlaced != interlaced) {
702     self->interlaced = interlaced;
703     GST_VIDEO_INFO_INTERLACE_MODE (info) = interlaced ?
704         GST_VIDEO_INTERLACE_MODE_MIXED : GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
705     negotiation_needed = TRUE;
706     GST_INFO_OBJECT (self, "Interlaced mode changed to %d", interlaced);
707   }
708
709   base->need_valign = GST_VIDEO_INFO_WIDTH (info) < base->width ||
710       GST_VIDEO_INFO_HEIGHT (info) < base->height;
711   if (base->need_valign) {
712     /* *INDENT-OFF* */
713     if (base->valign.padding_left != padding_left ||
714         base->valign.padding_right != padding_right ||
715         base->valign.padding_top != padding_top ||
716         base->valign.padding_bottom != padding_bottom) {
717       negotiation_needed = TRUE;
718       GST_INFO_OBJECT (self, "crop rect changed to (%d,%d)-->(%d,%d)",
719           padding_left, padding_top, padding_right, padding_bottom);
720     }
721     base->valign = (GstVideoAlignment) {
722       .padding_left = padding_left,
723       .padding_right = padding_right,
724       .padding_top = padding_top,
725       .padding_bottom = padding_bottom,
726     };
727     /* *INDENT-ON* */
728   }
729
730   base->min_buffers = self->dpb_size + 4;       /* dpb size + scratch surfaces */
731   base->need_negotiation = negotiation_needed;
732   g_clear_pointer (&base->input_state, gst_video_codec_state_unref);
733   base->input_state = gst_video_codec_state_ref (decoder->input_state);
734
735   return GST_FLOW_OK;
736 }
737
738 static inline void
739 _append_str (GValue * list, const gchar * str)
740 {
741   GValue v = G_VALUE_INIT;
742
743   g_value_init (&v, G_TYPE_STRING);
744   g_value_set_string (&v, str);
745   gst_value_list_append_value (list, &v);
746   g_value_unset (&v);
747 }
748
749 static GstCaps *
750 _complete_sink_caps (GstCaps * sinkcaps)
751 {
752   GstCaps *caps = gst_caps_copy (sinkcaps);
753   GValue val = G_VALUE_INIT;
754   const GValue *profiles;
755   GstStructure *st;
756   const gchar *streamformat[] = { "avc", "avc3", "byte-stream" };
757   const gchar *high_synthetic[] = { "progressive-high", "constrained-high" };
758   guint i, j, siz;
759   gboolean baseline = FALSE;
760
761   g_value_init (&val, G_TYPE_STRING);
762   g_value_set_string (&val, "au");
763   gst_caps_set_value (caps, "alignment", &val);
764   g_value_unset (&val);
765
766   gst_value_list_init (&val, G_N_ELEMENTS (streamformat));
767   for (i = 0; i < G_N_ELEMENTS (streamformat); i++)
768     _append_str (&val, streamformat[i]);
769   gst_caps_set_value (caps, "stream-format", &val);
770   g_value_unset (&val);
771
772   /* add synthetic profiles */
773   st = gst_caps_get_structure (caps, 0);
774   profiles = gst_structure_get_value (st, "profile");
775   siz = gst_value_list_get_size (profiles);
776   gst_value_list_init (&val, siz);
777   for (i = 0; i < siz; i++) {
778     const gchar *profile =
779         g_value_get_string (gst_value_list_get_value (profiles, i));
780
781     _append_str (&val, profile);
782
783     if (g_strcmp0 (profile, "high") == 0) {
784       for (j = 0; j < G_N_ELEMENTS (high_synthetic); j++)
785         _append_str (&val, high_synthetic[j]);
786     }
787     if (!baseline && ((g_strcmp0 (profile, "main") == 0)
788             || g_strcmp0 (profile, "constrained-baseline") == 0)) {
789       _append_str (&val, "baseline");
790       baseline = TRUE;
791     }
792   }
793   gst_caps_set_value (caps, "profile", &val);
794   g_value_unset (&val);
795
796   return caps;
797 }
798
799 static GstCaps *
800 gst_va_h264_dec_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
801 {
802   GstCaps *sinkcaps, *caps = NULL, *tmp;
803   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
804
805   if (base->decoder)
806     caps = gst_va_decoder_get_sinkpad_caps (base->decoder);
807
808   if (caps) {
809     sinkcaps = _complete_sink_caps (caps);
810     gst_caps_unref (caps);
811     if (filter) {
812       tmp = gst_caps_intersect_full (filter, sinkcaps,
813           GST_CAPS_INTERSECT_FIRST);
814       gst_caps_unref (sinkcaps);
815       caps = tmp;
816     } else {
817       caps = sinkcaps;
818     }
819     GST_LOG_OBJECT (base, "Returning caps %" GST_PTR_FORMAT, caps);
820   } else {
821     caps = gst_video_decoder_proxy_getcaps (decoder, NULL, filter);
822   }
823
824   return caps;
825 }
826
827 static void
828 gst_va_h264_dec_dispose (GObject * object)
829 {
830   GstVaH264Dec *self = GST_VA_H264_DEC (object);
831
832   gst_va_base_dec_close (GST_VIDEO_DECODER (object));
833   g_clear_pointer (&self->ref_list, g_array_unref);
834
835   G_OBJECT_CLASS (parent_class)->dispose (object);
836 }
837
838 static void
839 gst_va_h264_dec_class_init (gpointer g_class, gpointer class_data)
840 {
841   GstCaps *src_doc_caps, *sink_doc_caps;
842   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
843   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
844   GstH264DecoderClass *h264decoder_class = GST_H264_DECODER_CLASS (g_class);
845   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (g_class);
846   struct CData *cdata = class_data;
847   gchar *long_name;
848
849   if (cdata->description) {
850     long_name = g_strdup_printf ("VA-API H.264 Decoder in %s",
851         cdata->description);
852   } else {
853     long_name = g_strdup ("VA-API H.264 Decoder");
854   }
855
856   gst_element_class_set_metadata (element_class, long_name,
857       "Codec/Decoder/Video/Hardware",
858       "VA-API based H.264 video decoder",
859       "Víctor Jáquez <vjaquez@igalia.com>");
860
861   sink_doc_caps = gst_caps_from_string (sink_caps_str);
862   src_doc_caps = gst_caps_from_string (src_caps_str);
863
864   parent_class = g_type_class_peek_parent (g_class);
865
866   /**
867    * GstVaH264Dec:device-path:
868    *
869    * It shows the DRM device path used for the VA operation, if any.
870    *
871    * Since: 1.22
872    */
873   gst_va_base_dec_class_init (GST_VA_BASE_DEC_CLASS (g_class), H264,
874       cdata->render_device_path, cdata->sink_caps, cdata->src_caps,
875       src_doc_caps, sink_doc_caps);
876
877   gobject_class->dispose = gst_va_h264_dec_dispose;
878
879   decoder_class->getcaps = GST_DEBUG_FUNCPTR (gst_va_h264_dec_getcaps);
880
881   h264decoder_class->new_sequence =
882       GST_DEBUG_FUNCPTR (gst_va_h264_dec_new_sequence);
883   h264decoder_class->decode_slice =
884       GST_DEBUG_FUNCPTR (gst_va_h264_dec_decode_slice);
885
886   h264decoder_class->new_picture =
887       GST_DEBUG_FUNCPTR (gst_va_h264_dec_new_picture);
888   h264decoder_class->output_picture =
889       GST_DEBUG_FUNCPTR (gst_va_h264_dec_output_picture);
890   h264decoder_class->start_picture =
891       GST_DEBUG_FUNCPTR (gst_va_h264_dec_start_picture);
892   h264decoder_class->end_picture =
893       GST_DEBUG_FUNCPTR (gst_va_h264_dec_end_picture);
894   h264decoder_class->new_field_picture =
895       GST_DEBUG_FUNCPTR (gst_va_h264_dec_new_field_picture);
896
897   g_free (long_name);
898   g_free (cdata->description);
899   g_free (cdata->render_device_path);
900   gst_caps_unref (cdata->src_caps);
901   gst_caps_unref (cdata->sink_caps);
902   g_free (cdata);
903 }
904
905 static void
906 gst_va_h264_dec_init (GTypeInstance * instance, gpointer g_class)
907 {
908   GstVaH264Dec *self = GST_VA_H264_DEC (instance);
909
910   gst_va_base_dec_init (GST_VA_BASE_DEC (instance), GST_CAT_DEFAULT);
911   gst_h264_decoder_set_process_ref_pic_lists (GST_H264_DECODER (instance),
912       TRUE);
913
914   self->ref_list = g_array_sized_new (FALSE, TRUE,
915       sizeof (GstH264Picture *), 16);
916   g_array_set_clear_func (self->ref_list,
917       (GDestroyNotify) gst_clear_h264_picture);
918 }
919
920 static gpointer
921 _register_debug_category (gpointer data)
922 {
923   GST_DEBUG_CATEGORY_INIT (gst_va_h264dec_debug, "vah264dec", 0,
924       "VA h264 decoder");
925
926   return NULL;
927 }
928
929 gboolean
930 gst_va_h264_dec_register (GstPlugin * plugin, GstVaDevice * device,
931     GstCaps * sink_caps, GstCaps * src_caps, guint rank)
932 {
933   static GOnce debug_once = G_ONCE_INIT;
934   GType type;
935   GTypeInfo type_info = {
936     .class_size = sizeof (GstVaH264DecClass),
937     .class_init = gst_va_h264_dec_class_init,
938     .instance_size = sizeof (GstVaH264Dec),
939     .instance_init = gst_va_h264_dec_init,
940   };
941   struct CData *cdata;
942   gboolean ret;
943   gchar *type_name, *feature_name;
944
945   g_return_val_if_fail (GST_IS_PLUGIN (plugin), FALSE);
946   g_return_val_if_fail (GST_IS_VA_DEVICE (device), FALSE);
947   g_return_val_if_fail (GST_IS_CAPS (sink_caps), FALSE);
948   g_return_val_if_fail (GST_IS_CAPS (src_caps), FALSE);
949
950   cdata = g_new (struct CData, 1);
951   cdata->description = NULL;
952   cdata->render_device_path = g_strdup (device->render_device_path);
953   cdata->sink_caps = _complete_sink_caps (sink_caps);
954   cdata->src_caps = gst_caps_ref (src_caps);
955
956   /* class data will be leaked if the element never gets instantiated */
957   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
958       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
959   GST_MINI_OBJECT_FLAG_SET (src_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
960
961   type_info.class_data = cdata;
962
963   /* The first decoder to be registered should use a constant name,
964    * like vah264dec, for any additional decoders, we create unique
965    * names, using inserting the render device name. */
966   if (device->index == 0) {
967     type_name = g_strdup ("GstVaH264Dec");
968     feature_name = g_strdup ("vah264dec");
969   } else {
970     gchar *basename = g_path_get_basename (device->render_device_path);
971     type_name = g_strdup_printf ("GstVa%sH264Dec", basename);
972     feature_name = g_strdup_printf ("va%sh264dec", basename);
973     cdata->description = basename;
974
975     /* lower rank for non-first device */
976     if (rank > 0)
977       rank--;
978   }
979
980   g_once (&debug_once, _register_debug_category, NULL);
981
982   type = g_type_register_static (GST_TYPE_H264_DECODER,
983       type_name, &type_info, 0);
984
985   ret = gst_element_register (plugin, feature_name, rank, type);
986
987   g_free (type_name);
988   g_free (feature_name);
989
990   return ret;
991 }