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