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