10f34323d0c4454d086fe6656326dfa591bf84de
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / va / gstvaav1dec.c
1 /* GStreamer
2  *  Copyright (C) 2020 Intel Corporation
3  *     Author: He Junyan <junyan.he@intel.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the0
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 /**
22  * SECTION:element-vaav1dec
23  * @title: vaav1dec
24  * @short_description: A VA-API based AV1 video decoder
25  *
26  * vaav1dec decodes AV1 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=sample.av1 ! ivfparse ! av1parse ! vaav1dec ! autovideosink
36  * ```
37  *
38  * Since: 1.20
39  *
40  */
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 #include <gst/va/gstva.h>
47
48 #include "gstvaav1dec.h"
49 #include "gstvabasedec.h"
50
51 GST_DEBUG_CATEGORY_STATIC (gst_va_av1dec_debug);
52 #ifndef GST_DISABLE_GST_DEBUG
53 #define GST_CAT_DEFAULT gst_va_av1dec_debug
54 #else
55 #define GST_CAT_DEFAULT NULL
56 #endif
57
58 #define GST_VA_AV1_DEC(obj)           ((GstVaAV1Dec *) obj)
59 #define GST_VA_AV1_DEC_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), G_TYPE_FROM_INSTANCE (obj), GstVaAV1DecClass))
60 #define GST_VA_AV1_DEC_CLASS(klass)   ((GstVaAV1DecClass *) klass)
61
62 typedef struct _GstVaAV1Dec GstVaAV1Dec;
63 typedef struct _GstVaAV1DecClass GstVaAV1DecClass;
64
65 struct _GstVaAV1DecClass
66 {
67   GstVaBaseDecClass parent_class;
68 };
69
70 struct _GstVaAV1Dec
71 {
72   GstVaBaseDec parent;
73
74   GstFlowReturn last_ret;
75
76   GstAV1SequenceHeaderOBU seq;
77   gint max_width;
78   gint max_height;
79   GstVideoFormat preferred_format;
80   /* Used for layers not output. */
81   GstBufferPool *internal_pool;
82 };
83
84 static GstElementClass *parent_class = NULL;
85
86 /* *INDENT-OFF* */
87 static const gchar *src_caps_str =
88     GST_VIDEO_CAPS_MAKE_WITH_FEATURES (GST_CAPS_FEATURE_MEMORY_VA,
89         "{ NV12, P010_10LE }") " ;"
90     GST_VIDEO_CAPS_MAKE ("{ NV12, P010_10LE }");
91 /* *INDENT-ON* */
92
93 static const gchar *sink_caps_str = "video/x-av1";
94
95 static gboolean
96 gst_va_av1_dec_negotiate (GstVideoDecoder * decoder)
97 {
98   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
99   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
100   GstAV1Decoder *av1dec = GST_AV1_DECODER (decoder);
101   GstVideoFormat format = GST_VIDEO_FORMAT_UNKNOWN;
102   GstCapsFeatures *capsfeatures = NULL;
103
104   /* Ignore downstream renegotiation request. */
105   if (!base->need_negotiation)
106     return TRUE;
107
108   base->need_negotiation = FALSE;
109
110   /* Do not re-create the context if only the frame size changes */
111   if (!gst_va_decoder_config_is_equal (base->decoder, base->profile,
112           base->rt_format, self->max_width, self->max_height)) {
113     if (gst_va_decoder_is_open (base->decoder)
114         && !gst_va_decoder_close (base->decoder))
115       return FALSE;
116
117     if (!gst_va_decoder_open (base->decoder, base->profile, base->rt_format))
118       return FALSE;
119
120     if (!gst_va_decoder_set_frame_size (base->decoder, self->max_width,
121             self->max_height))
122       return FALSE;
123   }
124
125   if (base->output_state)
126     gst_video_codec_state_unref (base->output_state);
127
128   gst_va_base_dec_get_preferred_format_and_caps_features (base, &format,
129       &capsfeatures);
130   if (format == GST_VIDEO_FORMAT_UNKNOWN)
131     return FALSE;
132
133   if (self->preferred_format != GST_VIDEO_FORMAT_UNKNOWN &&
134       self->preferred_format != format) {
135     GST_WARNING_OBJECT (self, "The preferred_format is different from"
136         " the last result");
137     return FALSE;
138   }
139   self->preferred_format = format;
140
141   base->output_state = gst_video_decoder_set_output_state (decoder, format,
142       base->width, base->height, av1dec->input_state);
143
144   base->output_state->caps = gst_video_info_to_caps (&base->output_state->info);
145   if (capsfeatures)
146     gst_caps_set_features_simple (base->output_state->caps, capsfeatures);
147
148   GST_INFO_OBJECT (self, "Negotiated caps %" GST_PTR_FORMAT,
149       base->output_state->caps);
150
151   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
152 }
153
154 static GstCaps *
155 _complete_sink_caps (GstCaps * sinkcaps)
156 {
157   GstCaps *caps = gst_caps_copy (sinkcaps);
158   GValue val = G_VALUE_INIT;
159
160   g_value_init (&val, G_TYPE_STRING);
161   g_value_set_string (&val, "frame");
162   gst_caps_set_value (caps, "alignment", &val);
163   g_value_unset (&val);
164
165   return caps;
166 }
167
168 static VAProfile
169 _get_profile (GstVaAV1Dec * self, const GstAV1SequenceHeaderOBU * seq_hdr)
170 {
171   GstVaBaseDec *base = GST_VA_BASE_DEC (self);
172   VAProfile profile = VAProfileNone;
173
174   switch (seq_hdr->seq_profile) {
175     case GST_AV1_PROFILE_0:
176       profile = VAProfileAV1Profile0;
177       break;
178     case GST_AV1_PROFILE_1:
179       profile = VAProfileAV1Profile1;
180       break;
181     default:
182       GST_ERROR_OBJECT (self, "Unsupported av1 profile value %d",
183           seq_hdr->seq_profile);
184       return VAProfileNone;
185   }
186
187   if (!gst_va_decoder_has_profile (base->decoder, profile)) {
188     GST_ERROR_OBJECT (self, "Profile %s is not supported by HW",
189         gst_va_profile_name (profile));
190     return VAProfileNone;
191   }
192
193   return profile;
194 }
195
196 static guint
197 _get_rtformat (GstVaAV1Dec * self, VAProfile profile,
198     const GstAV1SequenceHeaderOBU * seq_header)
199 {
200   /* 6.4.1:
201      seq_profile  Bit depth  Monochrome support  Chroma subsampling
202      0            8 or 10    Yes                 YUV 4:2:0
203      1            8 or 10    No                  YUV 4:4:4
204      2            8 or 10    Yes                 YUV 4:2:2
205      2            12         Yes                 YUV 4:2:0,YUV 4:2:2,YUV 4:4:4
206    */
207
208   /* TODO: consider Monochrome case. Just return 4:2:0 for Monochrome now. */
209   switch (profile) {
210     case VAProfileAV1Profile0:
211       if (seq_header->bit_depth == 8) {
212         return VA_RT_FORMAT_YUV420;
213       } else if (seq_header->bit_depth == 10) {
214         return VA_RT_FORMAT_YUV420_10;
215       }
216       break;
217     case VAProfileAV1Profile1:
218       if (seq_header->bit_depth == 8) {
219         return VA_RT_FORMAT_YUV444;
220       } else if (seq_header->bit_depth == 10) {
221         return VA_RT_FORMAT_YUV444_10;
222       }
223       break;
224     default:
225       break;
226   }
227
228   GST_ERROR_OBJECT (self, "Fail to find rtformat for profile:%s, bit_depth:%d",
229       gst_va_profile_name (profile), seq_header->bit_depth);
230   return 0;
231 }
232
233 static GstCaps *
234 gst_va_av1_dec_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
235 {
236   GstCaps *sinkcaps, *caps = NULL, *tmp;
237   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
238
239   if (base->decoder)
240     caps = gst_va_decoder_get_sinkpad_caps (base->decoder);
241
242   if (caps) {
243     sinkcaps = _complete_sink_caps (caps);
244     gst_caps_unref (caps);
245     if (filter) {
246       tmp = gst_caps_intersect_full (filter, sinkcaps,
247           GST_CAPS_INTERSECT_FIRST);
248       gst_caps_unref (sinkcaps);
249       caps = tmp;
250     } else {
251       caps = sinkcaps;
252     }
253     GST_LOG_OBJECT (base, "Returning caps %" GST_PTR_FORMAT, caps);
254   } else if (!caps) {
255     caps = gst_video_decoder_proxy_getcaps (decoder, NULL, filter);
256   }
257
258   return caps;
259 }
260
261 static void
262 _clear_internal_pool (GstVaAV1Dec * self)
263 {
264   if (self->internal_pool)
265     gst_buffer_pool_set_active (self->internal_pool, FALSE);
266
267   gst_clear_object (&self->internal_pool);
268 }
269
270 static GstBufferPool *
271 _create_internal_pool (GstVaAV1Dec * self, gint width, gint height)
272 {
273   GstVaBaseDec *base = GST_VA_BASE_DEC (self);
274   GstVideoInfo info;
275   GArray *surface_formats;
276   GstAllocator *allocator;
277   GstCaps *caps = NULL;
278   GstBufferPool *pool;
279   GstAllocationParams params = { 0, };
280
281   gst_allocation_params_init (&params);
282
283   /* We may come here before the negotiation, make sure all pools
284      use the same video format. */
285   if (self->preferred_format == GST_VIDEO_FORMAT_UNKNOWN) {
286     GstVideoFormat format;
287
288     gst_va_base_dec_get_preferred_format_and_caps_features (base,
289         &format, NULL);
290     if (format == GST_VIDEO_FORMAT_UNKNOWN) {
291       GST_WARNING_OBJECT (self, "Failed to get format for internal pool");
292       return NULL;
293     }
294
295     self->preferred_format = format;
296   }
297
298   gst_video_info_set_format (&info, self->preferred_format, width, height);
299
300   caps = gst_video_info_to_caps (&info);
301   if (caps == NULL) {
302     GST_WARNING_OBJECT (self, "Failed to create caps for internal pool");
303     return NULL;
304   }
305
306   gst_caps_set_features_simple (caps,
307       gst_caps_features_from_string (GST_CAPS_FEATURE_MEMORY_VA));
308
309   surface_formats = gst_va_decoder_get_surface_formats (base->decoder);
310   allocator = gst_va_allocator_new (base->display, surface_formats);
311
312   pool = gst_va_pool_new_with_config (caps, GST_VIDEO_INFO_SIZE (&info),
313       1, 0, VA_SURFACE_ATTRIB_USAGE_HINT_DECODER, GST_VA_FEATURE_AUTO,
314       allocator, &params);
315   if (!pool) {
316     GST_WARNING_OBJECT (self, "Failed to create internal pool");
317     gst_object_unref (allocator);
318     gst_clear_caps (&caps);
319     return NULL;
320   }
321
322   gst_object_unref (allocator);
323
324   gst_buffer_pool_set_active (pool, TRUE);
325
326   return pool;
327 }
328
329 static GstFlowReturn
330 gst_va_av1_dec_new_sequence (GstAV1Decoder * decoder,
331     const GstAV1SequenceHeaderOBU * seq_hdr, gint max_dpb_size)
332 {
333   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
334   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
335   VAProfile profile;
336   guint rt_format;
337
338   GST_LOG_OBJECT (self, "new sequence");
339
340   profile = _get_profile (self, seq_hdr);
341   if (profile == VAProfileNone)
342     return GST_FLOW_NOT_NEGOTIATED;
343
344   rt_format = _get_rtformat (self, profile, seq_hdr);
345   if (!rt_format)
346     return GST_FLOW_NOT_NEGOTIATED;
347
348   self->seq = *seq_hdr;
349
350   if (!gst_va_decoder_config_is_equal (base->decoder, profile,
351           rt_format, seq_hdr->max_frame_width_minus_1 + 1,
352           seq_hdr->max_frame_height_minus_1 + 1)) {
353     _clear_internal_pool (self);
354     self->preferred_format = GST_VIDEO_FORMAT_UNKNOWN;
355
356     base->profile = profile;
357     base->rt_format = rt_format;
358     self->max_width = seq_hdr->max_frame_width_minus_1 + 1;
359     self->max_height = seq_hdr->max_frame_height_minus_1 + 1;
360     base->need_negotiation = TRUE;
361
362     base->min_buffers = 7 + 4;  /* dpb size + scratch surfaces */
363
364     /* May be changed by frame header */
365     base->width = self->max_width;
366     base->height = self->max_height;
367     base->need_valign = FALSE;
368   }
369
370   return GST_FLOW_OK;
371 }
372
373 static GstFlowReturn
374 gst_va_av1_dec_new_picture (GstAV1Decoder * decoder,
375     GstVideoCodecFrame * frame, GstAV1Picture * picture)
376 {
377   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
378   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
379   GstVaDecodePicture *pic;
380   GstVideoDecoder *vdec = GST_VIDEO_DECODER (decoder);
381   GstAV1FrameHeaderOBU *frame_hdr = &picture->frame_hdr;
382
383   /* Only output the highest spatial layer. For non output pictures,
384      we just use internal pool, then no negotiation needed. */
385   if (picture->spatial_id < decoder->highest_spatial_layer) {
386     if (!self->internal_pool) {
387       self->internal_pool =
388           _create_internal_pool (self, self->max_width, self->max_height);
389       if (!self->internal_pool)
390         return GST_FLOW_ERROR;
391     }
392   } else {
393     if (frame_hdr->upscaled_width != base->width
394         || frame_hdr->frame_height != base->height) {
395       base->width = frame_hdr->upscaled_width;
396       base->height = frame_hdr->frame_height;
397
398       if (base->width < self->max_width || base->height < self->max_height) {
399         base->need_valign = TRUE;
400         /* *INDENT-OFF* */
401         base->valign = (GstVideoAlignment){
402           .padding_bottom = self->max_height - base->height,
403           .padding_right = self->max_width - base->width,
404         };
405         /* *INDENT-ON* */
406       }
407
408       base->need_negotiation = TRUE;
409     }
410   }
411
412   if (base->need_negotiation) {
413     if (!gst_video_decoder_negotiate (GST_VIDEO_DECODER (self))) {
414       GST_ERROR_OBJECT (self, "Failed to negotiate with downstream");
415       return GST_FLOW_NOT_NEGOTIATED;
416     }
417   }
418
419   if (picture->spatial_id < decoder->highest_spatial_layer) {
420     self->last_ret = gst_buffer_pool_acquire_buffer (self->internal_pool,
421         &frame->output_buffer, NULL);
422     if (self->last_ret != GST_FLOW_OK) {
423       GST_WARNING_OBJECT (self,
424           "Failed to allocated output buffer from internal pool, return %s",
425           gst_flow_get_name (self->last_ret));
426       return self->last_ret;
427     }
428   } else {
429     self->last_ret = gst_video_decoder_allocate_output_frame (vdec, frame);
430     if (self->last_ret != GST_FLOW_OK) {
431       GST_WARNING_OBJECT (self,
432           "Failed to allocated output buffer, return %s",
433           gst_flow_get_name (self->last_ret));
434       return self->last_ret;
435     }
436   }
437
438   if (picture->apply_grain) {
439     if (!gst_va_buffer_create_aux_surface (frame->output_buffer)) {
440       GST_WARNING_OBJECT (self,
441           "Failed to allocated aux surface for buffer %p",
442           frame->output_buffer);
443       return GST_FLOW_ERROR;
444     }
445   }
446
447   pic = gst_va_decode_picture_new (base->decoder, frame->output_buffer);
448
449   gst_av1_picture_set_user_data (picture, pic,
450       (GDestroyNotify) gst_va_decode_picture_free);
451
452   if (picture->apply_grain) {
453     GST_LOG_OBJECT (self, "New va decode picture %p - %#x(aux: %#x)", pic,
454         gst_va_decode_picture_get_surface (pic),
455         gst_va_decode_picture_get_aux_surface (pic));
456   } else {
457     GST_LOG_OBJECT (self, "New va decode picture %p - %#x", pic,
458         gst_va_decode_picture_get_surface (pic));
459   }
460
461   return GST_FLOW_OK;
462 }
463
464 static GstAV1Picture *
465 gst_va_av1_dec_duplicate_picture (GstAV1Decoder * decoder,
466     GstVideoCodecFrame * frame, GstAV1Picture * picture)
467 {
468   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
469   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
470   GstVaDecodePicture *pic;
471   GstVaDecodePicture *new_pic;
472   GstAV1Picture *new_picture;
473
474   pic = gst_av1_picture_get_user_data (picture);
475   if (!pic) {
476     GST_ERROR_OBJECT (self, "Parent picture does not have a va picture");
477     return NULL;
478   }
479
480   new_picture = gst_av1_picture_new ();
481   g_assert (pic->gstbuffer);
482   new_pic = gst_va_decode_picture_new (base->decoder, pic->gstbuffer);
483
484   GST_LOG_OBJECT (self, "Duplicate output with buffer %" GST_PTR_FORMAT
485       " (surface %#x)", pic, gst_va_decode_picture_get_surface (pic));
486
487   gst_av1_picture_set_user_data (new_picture, new_pic,
488       (GDestroyNotify) gst_va_decode_picture_free);
489
490   return new_picture;
491 }
492
493 static void
494 _setup_segment_info (VADecPictureParameterBufferAV1 * pic_param,
495     GstAV1FrameHeaderOBU * frame_header)
496 {
497   guint i, j;
498   uint8_t feature_mask;
499
500   for (i = 0; i < GST_AV1_MAX_SEGMENTS; i++)
501     for (j = 0; j < GST_AV1_SEG_LVL_MAX; j++)
502       pic_param->seg_info.feature_data[i][j] =
503           frame_header->segmentation_params.feature_data[i][j];
504
505   for (i = 0; i < GST_AV1_MAX_SEGMENTS; i++) {
506     feature_mask = 0;
507     for (j = 0; j < GST_AV1_SEG_LVL_MAX; j++) {
508       if (frame_header->segmentation_params.feature_enabled[i][j])
509         feature_mask |= 1 << j;
510     }
511     pic_param->seg_info.feature_mask[i] = feature_mask;
512   }
513 }
514
515 static void
516 _setup_film_grain_info (VADecPictureParameterBufferAV1 * pic_param,
517     GstAV1FrameHeaderOBU * frame_header)
518 {
519   guint i;
520
521   if (!frame_header->film_grain_params.apply_grain)
522     return;
523
524   pic_param->film_grain_info.num_y_points =
525       frame_header->film_grain_params.num_y_points;
526   for (i = 0; i < frame_header->film_grain_params.num_y_points; i++) {
527     pic_param->film_grain_info.point_y_value[i] =
528         frame_header->film_grain_params.point_y_value[i];
529     pic_param->film_grain_info.point_y_scaling[i] =
530         frame_header->film_grain_params.point_y_scaling[i];
531   }
532
533   pic_param->film_grain_info.num_cb_points =
534       frame_header->film_grain_params.num_cb_points;
535   for (i = 0; i < frame_header->film_grain_params.num_cb_points; i++) {
536     pic_param->film_grain_info.point_cb_value[i] =
537         frame_header->film_grain_params.point_cb_value[i];
538     pic_param->film_grain_info.point_cb_scaling[i] =
539         frame_header->film_grain_params.point_cb_scaling[i];
540   }
541
542   pic_param->film_grain_info.num_cr_points =
543       frame_header->film_grain_params.num_cr_points;
544   for (i = 0; i < frame_header->film_grain_params.num_cr_points; i++) {
545     pic_param->film_grain_info.point_cr_value[i] =
546         frame_header->film_grain_params.point_cr_value[i];
547     pic_param->film_grain_info.point_cr_scaling[i] =
548         frame_header->film_grain_params.point_cr_scaling[i];
549   }
550
551
552   if (pic_param->film_grain_info.num_y_points) {
553     for (i = 0; i < 24; i++) {
554       pic_param->film_grain_info.ar_coeffs_y[i] =
555           frame_header->film_grain_params.ar_coeffs_y_plus_128[i] - 128;
556     }
557   }
558   if (frame_header->film_grain_params.chroma_scaling_from_luma
559       || pic_param->film_grain_info.num_cb_points) {
560     for (i = 0; i < GST_AV1_MAX_NUM_POS_LUMA; i++) {
561       pic_param->film_grain_info.ar_coeffs_cb[i] =
562           frame_header->film_grain_params.ar_coeffs_cb_plus_128[i] - 128;
563     }
564   }
565   if (frame_header->film_grain_params.chroma_scaling_from_luma
566       || pic_param->film_grain_info.num_cr_points) {
567     for (i = 0; i < GST_AV1_MAX_NUM_POS_LUMA; i++) {
568       pic_param->film_grain_info.ar_coeffs_cr[i] =
569           frame_header->film_grain_params.ar_coeffs_cr_plus_128[i] - 128;
570     }
571   }
572 }
573
574 static void
575 _setup_loop_filter_info (VADecPictureParameterBufferAV1 * pic_param,
576     GstAV1FrameHeaderOBU * frame_header)
577 {
578   guint i;
579
580   pic_param->filter_level[0] =
581       frame_header->loop_filter_params.loop_filter_level[0];
582   pic_param->filter_level[1] =
583       frame_header->loop_filter_params.loop_filter_level[1];
584   pic_param->filter_level_u =
585       frame_header->loop_filter_params.loop_filter_level[2];
586   pic_param->filter_level_v =
587       frame_header->loop_filter_params.loop_filter_level[3];
588
589   for (i = 0; i < GST_AV1_TOTAL_REFS_PER_FRAME; i++)
590     pic_param->ref_deltas[i] =
591         frame_header->loop_filter_params.loop_filter_ref_deltas[i];
592   for (i = 0; i < 2; i++)
593     pic_param->mode_deltas[i] =
594         frame_header->loop_filter_params.loop_filter_mode_deltas[i];
595 }
596
597 static void
598 _setup_quantization_info (VADecPictureParameterBufferAV1 * pic_param,
599     GstAV1FrameHeaderOBU * frame_header)
600 {
601   pic_param->qmatrix_fields.bits.using_qmatrix =
602       frame_header->quantization_params.using_qmatrix;
603   if (frame_header->quantization_params.using_qmatrix) {
604     pic_param->qmatrix_fields.bits.qm_y =
605         frame_header->quantization_params.qm_y;
606     pic_param->qmatrix_fields.bits.qm_u =
607         frame_header->quantization_params.qm_u;
608     pic_param->qmatrix_fields.bits.qm_v =
609         frame_header->quantization_params.qm_v;
610   } else {
611     pic_param->qmatrix_fields.bits.qm_y = 0;
612     pic_param->qmatrix_fields.bits.qm_u = 0;
613     pic_param->qmatrix_fields.bits.qm_v = 0;
614   }
615 }
616
617 static void
618 _setup_cdef_info (VADecPictureParameterBufferAV1 * pic_param,
619     GstAV1FrameHeaderOBU * frame_header, guint8 num_planes)
620 {
621   guint8 sec_strength;
622   guint i;
623
624   pic_param->cdef_damping_minus_3 = frame_header->cdef_params.cdef_damping - 3;
625   pic_param->cdef_bits = frame_header->cdef_params.cdef_bits;
626   for (i = 0; i < GST_AV1_CDEF_MAX; i++) {
627     sec_strength = frame_header->cdef_params.cdef_y_sec_strength[i];
628     g_assert (sec_strength <= 4);
629     /* may need to minus 1 in order to merge with primary value. */
630     if (sec_strength == 4)
631       sec_strength--;
632
633     pic_param->cdef_y_strengths[i] =
634         ((frame_header->cdef_params.cdef_y_pri_strength[i] & 0xf) << 2) |
635         (sec_strength & 0x03);
636   }
637   if (num_planes > 1) {
638     for (i = 0; i < GST_AV1_CDEF_MAX; i++) {
639       sec_strength = frame_header->cdef_params.cdef_uv_sec_strength[i];
640       g_assert (sec_strength <= 4);
641       /* may need to minus 1 in order to merge with primary value. */
642       if (sec_strength == 4)
643         sec_strength--;
644
645       pic_param->cdef_uv_strengths[i] =
646           ((frame_header->cdef_params.cdef_uv_pri_strength[i] & 0xf) << 2) |
647           (sec_strength & 0x03);
648     }
649   } else {
650     for (i = 0; i < GST_AV1_CDEF_MAX; i++) {
651       pic_param->cdef_uv_strengths[i] = 0;
652     }
653   }
654 }
655
656 static void
657 _setup_global_motion_info (VADecPictureParameterBufferAV1 * pic_param,
658     GstAV1FrameHeaderOBU * frame_header)
659 {
660   guint i, j;
661
662   for (i = 0; i < 7; i++) {
663     /* assuming VAAV1TransformationType and GstAV1WarpModelType are
664      * equivalent */
665     pic_param->wm[i].wmtype = (VAAV1TransformationType)
666         frame_header->global_motion_params.gm_type[GST_AV1_REF_LAST_FRAME + i];
667
668     for (j = 0; j < 6; j++)
669       pic_param->wm[i].wmmat[j] =
670           frame_header->global_motion_params.gm_params
671           [GST_AV1_REF_LAST_FRAME + i][j];
672
673     pic_param->wm[i].wmmat[6] = 0;
674     pic_param->wm[i].wmmat[7] = 0;
675
676     pic_param->wm[i].invalid =
677         frame_header->global_motion_params.invalid[GST_AV1_REF_LAST_FRAME + i];
678   }
679 }
680
681 static GstFlowReturn
682 gst_va_av1_dec_start_picture (GstAV1Decoder * decoder, GstAV1Picture * picture,
683     GstAV1Dpb * dpb)
684 {
685   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
686   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
687   GstAV1FrameHeaderOBU *frame_header = &picture->frame_hdr;
688   GstAV1SequenceHeaderOBU *seq_header = &self->seq;
689   VADecPictureParameterBufferAV1 pic_param = { };
690   GstVaDecodePicture *va_pic;
691   guint i;
692
693   va_pic = gst_av1_picture_get_user_data (picture);
694   g_assert (va_pic);
695
696   /* *INDENT-OFF* */
697   pic_param = (VADecPictureParameterBufferAV1){
698     .profile = seq_header->seq_profile,
699     .order_hint_bits_minus_1 = seq_header->order_hint_bits_minus_1,
700     .matrix_coefficients = seq_header->color_config.matrix_coefficients,
701     .seq_info_fields.fields = {
702       .still_picture = seq_header->still_picture,
703       .use_128x128_superblock = seq_header->use_128x128_superblock,
704       .enable_filter_intra = seq_header->enable_filter_intra,
705       .enable_intra_edge_filter = seq_header->enable_intra_edge_filter,
706       .enable_interintra_compound = seq_header->enable_interintra_compound,
707       .enable_masked_compound = seq_header->enable_masked_compound,
708       .enable_dual_filter = seq_header->enable_dual_filter,
709       .enable_order_hint = seq_header->enable_order_hint,
710       .enable_jnt_comp = seq_header->enable_jnt_comp,
711       .enable_cdef = seq_header->enable_cdef,
712       .mono_chrome = seq_header->color_config.mono_chrome,
713       .color_range = seq_header->color_config.color_range,
714       .subsampling_x = seq_header->color_config.subsampling_x,
715       .subsampling_y = seq_header->color_config.subsampling_y,
716       .film_grain_params_present = seq_header->film_grain_params_present,
717     },
718     .anchor_frames_num = 0,
719     .anchor_frames_list = NULL,
720     .frame_width_minus1 = frame_header->upscaled_width - 1,
721     .frame_height_minus1 = frame_header->frame_height - 1,
722     .output_frame_width_in_tiles_minus_1 = 0,
723     .output_frame_height_in_tiles_minus_1 = 0,
724     .order_hint = frame_header->order_hint,
725     /* Segmentation */
726     .seg_info.segment_info_fields.bits = {
727       .enabled = frame_header->segmentation_params.segmentation_enabled,
728       .update_map = frame_header->segmentation_params.segmentation_update_map,
729       .temporal_update =
730         frame_header->segmentation_params.segmentation_temporal_update,
731       .update_data =
732         frame_header->segmentation_params.segmentation_update_data,
733     },
734     /* FilmGrain */
735     .film_grain_info = {
736       .film_grain_info_fields.bits = {
737         .apply_grain = frame_header->film_grain_params.apply_grain,
738         .chroma_scaling_from_luma =
739           frame_header->film_grain_params.chroma_scaling_from_luma,
740         .grain_scaling_minus_8 =
741           frame_header->film_grain_params.grain_scaling_minus_8,
742         .ar_coeff_lag = frame_header->film_grain_params.ar_coeff_lag,
743         .ar_coeff_shift_minus_6 =
744           frame_header->film_grain_params.ar_coeff_shift_minus_6,
745         .grain_scale_shift = frame_header->film_grain_params.grain_scale_shift,
746         .overlap_flag = frame_header->film_grain_params.overlap_flag,
747         .clip_to_restricted_range =
748           frame_header->film_grain_params.clip_to_restricted_range,
749       },
750       .grain_seed = frame_header->film_grain_params.grain_seed,
751       .cb_mult = frame_header->film_grain_params.cb_mult,
752       .cb_luma_mult = frame_header->film_grain_params.cb_luma_mult,
753       .cb_offset = frame_header->film_grain_params.cb_offset,
754       .cr_mult = frame_header->film_grain_params.cr_mult,
755       .cr_luma_mult = frame_header->film_grain_params.cr_luma_mult,
756       .cr_offset = frame_header->film_grain_params.cr_offset,
757     },
758     .tile_cols = frame_header->tile_info.tile_cols,
759     .tile_rows = frame_header->tile_info.tile_rows,
760     .context_update_tile_id = frame_header->tile_info.context_update_tile_id,
761     .pic_info_fields.bits = {
762       .frame_type = frame_header->frame_type,
763       .show_frame = frame_header->show_frame,
764       .showable_frame = frame_header->showable_frame,
765       .error_resilient_mode = frame_header->error_resilient_mode,
766       .disable_cdf_update = frame_header->disable_cdf_update,
767       .allow_screen_content_tools = frame_header->allow_screen_content_tools,
768       .force_integer_mv = frame_header->force_integer_mv,
769       .allow_intrabc = frame_header->allow_intrabc,
770       .use_superres = frame_header->use_superres,
771       .allow_high_precision_mv = frame_header->allow_high_precision_mv,
772       .is_motion_mode_switchable = frame_header->is_motion_mode_switchable,
773       .use_ref_frame_mvs = frame_header->use_ref_frame_mvs,
774       .disable_frame_end_update_cdf =
775         frame_header->disable_frame_end_update_cdf,
776       .uniform_tile_spacing_flag =
777         frame_header->tile_info.uniform_tile_spacing_flag,
778       .allow_warped_motion = frame_header->allow_warped_motion,
779     },
780     .superres_scale_denominator = frame_header->superres_denom,
781     .interp_filter = frame_header->interpolation_filter,
782     /* loop filter */
783     .loop_filter_info_fields.bits = {
784       .sharpness_level =
785         frame_header->loop_filter_params.loop_filter_sharpness,
786       .mode_ref_delta_enabled =
787         frame_header->loop_filter_params.loop_filter_delta_enabled,
788       .mode_ref_delta_update =
789         frame_header->loop_filter_params.loop_filter_delta_update,
790     },
791     .mode_control_fields.bits = {
792       .delta_lf_present_flag =
793         frame_header->loop_filter_params.delta_lf_present,
794       .log2_delta_lf_res = frame_header->loop_filter_params.delta_lf_res,
795       .delta_lf_multi = frame_header->loop_filter_params.delta_lf_multi,
796       .delta_q_present_flag =
797         frame_header->quantization_params.delta_q_present,
798       .log2_delta_q_res = frame_header->quantization_params.delta_q_res,
799       .tx_mode = frame_header->tx_mode,
800       .reference_select = frame_header->reference_select,
801       .reduced_tx_set_used = frame_header->reduced_tx_set,
802       .skip_mode_present = frame_header->skip_mode_present,
803     },
804     /* quantization */
805     .base_qindex = frame_header->quantization_params.base_q_idx,
806     .y_dc_delta_q = frame_header->quantization_params.delta_q_y_dc,
807     .u_dc_delta_q = frame_header->quantization_params.delta_q_u_dc,
808     .u_ac_delta_q = frame_header->quantization_params.delta_q_u_ac,
809     .v_dc_delta_q = frame_header->quantization_params.delta_q_v_dc,
810     .v_ac_delta_q = frame_header->quantization_params.delta_q_v_ac,
811     /* loop restoration */
812     .loop_restoration_fields.bits = {
813       .yframe_restoration_type =
814         frame_header->loop_restoration_params.frame_restoration_type[0],
815       .cbframe_restoration_type =
816         frame_header->loop_restoration_params.frame_restoration_type[1],
817       .crframe_restoration_type =
818         frame_header->loop_restoration_params.frame_restoration_type[2],
819       .lr_unit_shift = frame_header->loop_restoration_params.lr_unit_shift,
820       .lr_uv_shift = frame_header->loop_restoration_params.lr_uv_shift,
821     },
822   };
823   /* *INDENT-ON* */
824
825   if (seq_header->bit_depth == 8) {
826     pic_param.bit_depth_idx = 0;
827   } else if (seq_header->bit_depth == 10) {
828     pic_param.bit_depth_idx = 1;
829   } else if (seq_header->bit_depth == 12) {
830     pic_param.bit_depth_idx = 2;
831   } else {
832     g_assert_not_reached ();
833   }
834
835   if (frame_header->film_grain_params.apply_grain) {
836     pic_param.current_frame = gst_va_decode_picture_get_aux_surface (va_pic);
837     pic_param.current_display_picture =
838         gst_va_decode_picture_get_surface (va_pic);
839   } else {
840     pic_param.current_frame = gst_va_decode_picture_get_surface (va_pic);
841     pic_param.current_display_picture = VA_INVALID_SURFACE;
842   }
843
844   for (i = 0; i < GST_AV1_NUM_REF_FRAMES; i++) {
845     if (dpb->pic_list[i]) {
846       if (dpb->pic_list[i]->apply_grain) {
847         pic_param.ref_frame_map[i] = gst_va_decode_picture_get_aux_surface
848             (gst_av1_picture_get_user_data (dpb->pic_list[i]));
849       } else {
850         pic_param.ref_frame_map[i] = gst_va_decode_picture_get_surface
851             (gst_av1_picture_get_user_data (dpb->pic_list[i]));
852       }
853     } else {
854       pic_param.ref_frame_map[i] = VA_INVALID_SURFACE;
855     }
856   }
857   for (i = 0; i < GST_AV1_REFS_PER_FRAME; i++) {
858     pic_param.ref_frame_idx[i] = frame_header->ref_frame_idx[i];
859   }
860   pic_param.primary_ref_frame = frame_header->primary_ref_frame;
861
862   _setup_segment_info (&pic_param, frame_header);
863   _setup_film_grain_info (&pic_param, frame_header);
864
865   for (i = 0; i < 63; i++) {
866     pic_param.width_in_sbs_minus_1[i] =
867         frame_header->tile_info.width_in_sbs_minus_1[i];
868     pic_param.height_in_sbs_minus_1[i] =
869         frame_header->tile_info.height_in_sbs_minus_1[i];
870   }
871
872   _setup_loop_filter_info (&pic_param, frame_header);
873   _setup_quantization_info (&pic_param, frame_header);
874   _setup_cdef_info (&pic_param, frame_header, seq_header->num_planes);
875   _setup_global_motion_info (&pic_param, frame_header);
876
877   if (!gst_va_decoder_add_param_buffer (base->decoder, va_pic,
878           VAPictureParameterBufferType, &pic_param, sizeof (pic_param)))
879     return GST_FLOW_ERROR;
880
881   return GST_FLOW_OK;
882 }
883
884 static GstFlowReturn
885 gst_va_av1_dec_decode_tile (GstAV1Decoder * decoder, GstAV1Picture * picture,
886     GstAV1Tile * tile)
887 {
888   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
889   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
890   GstAV1TileGroupOBU *tile_group = &tile->tile_group;
891   GstVaDecodePicture *va_pic;
892   guint i;
893   VASliceParameterBufferAV1 slice_param[GST_AV1_MAX_TILE_COUNT];
894
895   GST_TRACE_OBJECT (self, "-");
896
897   for (i = 0; i < tile_group->tg_end - tile_group->tg_start + 1; i++) {
898     slice_param[i] = (VASliceParameterBufferAV1) {
899     };
900     slice_param[i].slice_data_size =
901         tile_group->entry[tile_group->tg_start + i].tile_size;
902     slice_param[i].slice_data_offset =
903         tile_group->entry[tile_group->tg_start + i].tile_offset;
904     slice_param[i].tile_row =
905         tile_group->entry[tile_group->tg_start + i].tile_row;
906     slice_param[i].tile_column =
907         tile_group->entry[tile_group->tg_start + i].tile_col;
908     slice_param[i].slice_data_flag = 0;
909   }
910
911   va_pic = gst_av1_picture_get_user_data (picture);
912
913   if (!gst_va_decoder_add_slice_buffer_with_n_params (base->decoder, va_pic,
914           slice_param, sizeof (VASliceParameterBufferAV1), i, tile->obu.data,
915           tile->obu.obu_size)) {
916     return GST_FLOW_ERROR;
917   }
918
919   return GST_FLOW_OK;
920 }
921
922 static GstFlowReturn
923 gst_va_av1_dec_end_picture (GstAV1Decoder * decoder, GstAV1Picture * picture)
924 {
925   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
926   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
927   GstVaDecodePicture *va_pic;
928
929   GST_LOG_OBJECT (self, "end picture %p, (system_frame_number %d)",
930       picture, picture->system_frame_number);
931
932   va_pic = gst_av1_picture_get_user_data (picture);
933
934   if (!gst_va_decoder_decode_with_aux_surface (base->decoder, va_pic,
935           picture->apply_grain)) {
936     return GST_FLOW_ERROR;
937   }
938
939   return GST_FLOW_OK;
940 }
941
942 static GstFlowReturn
943 gst_va_av1_dec_output_picture (GstAV1Decoder * decoder,
944     GstVideoCodecFrame * frame, GstAV1Picture * picture)
945 {
946   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
947   GstVaBaseDec *base = GST_VA_BASE_DEC (decoder);
948
949   g_assert (picture->frame_hdr.show_frame ||
950       picture->frame_hdr.show_existing_frame);
951
952   GST_LOG_OBJECT (self,
953       "Outputting picture %p (system_frame_number %d)",
954       picture, picture->system_frame_number);
955
956   if (self->last_ret != GST_FLOW_OK) {
957     gst_av1_picture_unref (picture);
958     gst_video_decoder_drop_frame (GST_VIDEO_DECODER (self), frame);
959     return self->last_ret;
960   }
961
962   if (picture->frame_hdr.show_existing_frame) {
963     GstVaDecodePicture *pic;
964
965     g_assert (!frame->output_buffer);
966     pic = gst_av1_picture_get_user_data (picture);
967     frame->output_buffer = gst_buffer_ref (pic->gstbuffer);
968   }
969
970   if (base->copy_frames)
971     gst_va_base_dec_copy_output_buffer (base, frame);
972
973   gst_av1_picture_unref (picture);
974
975   return gst_video_decoder_finish_frame (GST_VIDEO_DECODER (self), frame);
976 }
977
978 static gboolean
979 gst_va_av1_dec_start (GstVideoDecoder * decoder)
980 {
981   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
982
983   self->preferred_format = GST_VIDEO_FORMAT_UNKNOWN;
984
985   return GST_VIDEO_DECODER_CLASS (parent_class)->start (decoder);
986 }
987
988 static gboolean
989 gst_va_av1_dec_close (GstVideoDecoder * decoder)
990 {
991   GstVaAV1Dec *self = GST_VA_AV1_DEC (decoder);
992
993   _clear_internal_pool (self);
994
995   return gst_va_base_dec_close (GST_VIDEO_DECODER (decoder));
996 }
997
998 static void
999 gst_va_av1_dec_init (GTypeInstance * instance, gpointer g_class)
1000 {
1001   gst_va_base_dec_init (GST_VA_BASE_DEC (instance), GST_CAT_DEFAULT);
1002 }
1003
1004 static void
1005 gst_va_av1_dec_dispose (GObject * object)
1006 {
1007   gst_va_base_dec_close (GST_VIDEO_DECODER (object));
1008   G_OBJECT_CLASS (parent_class)->dispose (object);
1009 }
1010
1011 static void
1012 gst_va_av1_dec_class_init (gpointer g_class, gpointer class_data)
1013 {
1014   GstCaps *src_doc_caps, *sink_doc_caps;
1015   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1016   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1017   GstAV1DecoderClass *av1decoder_class = GST_AV1_DECODER_CLASS (g_class);
1018   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (g_class);
1019   struct CData *cdata = class_data;
1020   gchar *long_name;
1021
1022   if (cdata->description) {
1023     long_name = g_strdup_printf ("VA-API AV1 Decoder in %s",
1024         cdata->description);
1025   } else {
1026     long_name = g_strdup ("VA-API AV1 Decoder");
1027   }
1028
1029   gst_element_class_set_metadata (element_class, long_name,
1030       "Codec/Decoder/Video/Hardware",
1031       "VA-API based AV1 video decoder", "He Junyan <junyan.he@intel.com>");
1032
1033   sink_doc_caps = gst_caps_from_string (sink_caps_str);
1034   src_doc_caps = gst_caps_from_string (src_caps_str);
1035
1036   parent_class = g_type_class_peek_parent (g_class);
1037
1038   /**
1039    * GstVaAV1Dec:device-path:
1040    *
1041    * It shows the DRM device path used for the VA operation, if any.
1042    *
1043    * Since: 1.22
1044    */
1045   gst_va_base_dec_class_init (GST_VA_BASE_DEC_CLASS (g_class), AV1,
1046       cdata->render_device_path, cdata->sink_caps, cdata->src_caps,
1047       src_doc_caps, sink_doc_caps);
1048
1049   gobject_class->dispose = gst_va_av1_dec_dispose;
1050
1051   decoder_class->getcaps = GST_DEBUG_FUNCPTR (gst_va_av1_dec_getcaps);
1052   decoder_class->negotiate = GST_DEBUG_FUNCPTR (gst_va_av1_dec_negotiate);
1053   decoder_class->close = GST_DEBUG_FUNCPTR (gst_va_av1_dec_close);
1054   decoder_class->start = GST_DEBUG_FUNCPTR (gst_va_av1_dec_start);
1055
1056   av1decoder_class->new_sequence =
1057       GST_DEBUG_FUNCPTR (gst_va_av1_dec_new_sequence);
1058   av1decoder_class->new_picture =
1059       GST_DEBUG_FUNCPTR (gst_va_av1_dec_new_picture);
1060   av1decoder_class->duplicate_picture =
1061       GST_DEBUG_FUNCPTR (gst_va_av1_dec_duplicate_picture);
1062   av1decoder_class->start_picture =
1063       GST_DEBUG_FUNCPTR (gst_va_av1_dec_start_picture);
1064   av1decoder_class->decode_tile =
1065       GST_DEBUG_FUNCPTR (gst_va_av1_dec_decode_tile);
1066   av1decoder_class->end_picture =
1067       GST_DEBUG_FUNCPTR (gst_va_av1_dec_end_picture);
1068   av1decoder_class->output_picture =
1069       GST_DEBUG_FUNCPTR (gst_va_av1_dec_output_picture);
1070
1071   g_free (long_name);
1072   g_free (cdata->description);
1073   g_free (cdata->render_device_path);
1074   gst_caps_unref (cdata->src_caps);
1075   gst_caps_unref (cdata->sink_caps);
1076   g_free (cdata);
1077 }
1078
1079 static gpointer
1080 _register_debug_category (gpointer data)
1081 {
1082   GST_DEBUG_CATEGORY_INIT (gst_va_av1dec_debug, "vaav1dec", 0,
1083       "VA AV1 decoder");
1084
1085   return NULL;
1086 }
1087
1088 gboolean
1089 gst_va_av1_dec_register (GstPlugin * plugin, GstVaDevice * device,
1090     GstCaps * sink_caps, GstCaps * src_caps, guint rank)
1091 {
1092   static GOnce debug_once = G_ONCE_INIT;
1093   GType type;
1094   GTypeInfo type_info = {
1095     .class_size = sizeof (GstVaAV1DecClass),
1096     .class_init = gst_va_av1_dec_class_init,
1097     .instance_size = sizeof (GstVaAV1Dec),
1098     .instance_init = gst_va_av1_dec_init,
1099   };
1100   struct CData *cdata;
1101   gboolean ret;
1102   gchar *type_name, *feature_name;
1103
1104   g_return_val_if_fail (GST_IS_PLUGIN (plugin), FALSE);
1105   g_return_val_if_fail (GST_IS_VA_DEVICE (device), FALSE);
1106   g_return_val_if_fail (GST_IS_CAPS (sink_caps), FALSE);
1107   g_return_val_if_fail (GST_IS_CAPS (src_caps), FALSE);
1108
1109   cdata = g_new (struct CData, 1);
1110   cdata->description = NULL;
1111   cdata->render_device_path = g_strdup (device->render_device_path);
1112   cdata->sink_caps = _complete_sink_caps (sink_caps);
1113   cdata->src_caps = gst_caps_ref (src_caps);
1114
1115   /* class data will be leaked if the element never gets instantiated */
1116   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
1117       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1118   GST_MINI_OBJECT_FLAG_SET (src_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1119
1120   type_info.class_data = cdata;
1121
1122   /* The first decoder to be registered should use a constant name,
1123    * like vaav1dec, for any additional decoders, we create unique
1124    * names, using inserting the render device name. */
1125   if (device->index == 0) {
1126     type_name = g_strdup ("GstVaAV1Dec");
1127     feature_name = g_strdup ("vaav1dec");
1128   } else {
1129     gchar *basename = g_path_get_basename (device->render_device_path);
1130     type_name = g_strdup_printf ("GstVa%sAV1Dec", basename);
1131     feature_name = g_strdup_printf ("va%sav1dec", basename);
1132     cdata->description = basename;
1133
1134     /* lower rank for non-first device */
1135     if (rank > 0)
1136       rank--;
1137   }
1138
1139   g_once (&debug_once, _register_debug_category, NULL);
1140
1141   type = g_type_register_static (GST_TYPE_AV1_DECODER,
1142       type_name, &type_info, 0);
1143
1144   ret = gst_element_register (plugin, feature_name, rank, type);
1145
1146   g_free (type_name);
1147   g_free (feature_name);
1148
1149   return ret;
1150 }