nvcodec: Add AV1 decoder
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / nvcodec / gstnvh265dec.c
1 /* GStreamer
2  * Copyright (C) 2017 Ericsson AB. All rights reserved.
3  * Copyright (C) 2019 Seungha Yang <seungha.yang@navercorp.com>
4  * Copyright (C) 2020 Seungha Yang <seungha@centricular.com>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer
14  *    in the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * This library is free software; you can redistribute it and/or
30  * modify it under the terms of the GNU Library General Public
31  * License as published by the Free Software Foundation; either
32  * version 2 of the License, or (at your option) any later version.
33  *
34  * This library is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
37  * Library General Public License for more details.
38  *
39  * You should have received a copy of the GNU Library General Public
40  * License along with this library; if not, write to the
41  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
42  * Boston, MA 02110-1301, USA.
43  *
44  * Copyright 2015 The Chromium Authors. All rights reserved.
45  *
46  * Redistribution and use in source and binary forms, with or without
47  * modification, are permitted provided that the following conditions are
48  * met:
49  *
50  *    * Redistributions of source code must retain the above copyright
51  * notice, this list of conditions and the following disclaimer.
52  *    * Redistributions in binary form must reproduce the above
53  * copyright notice, this list of conditions and the following disclaimer
54  * in the documentation and/or other materials provided with the
55  * distribution.
56  *    * Neither the name of Google Inc. nor the names of its
57  * contributors may be used to endorse or promote products derived from
58  * this software without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
61  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
62  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
63  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
64  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
65  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
66  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
67  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
68  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
69  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
70  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71  */
72
73 #ifdef HAVE_CONFIG_H
74 #include "config.h"
75 #endif
76
77 #include <gst/cuda/gstcudautils.h>
78 #include "gstnvh265dec.h"
79 #include "gstnvdecoder.h"
80
81 #include <string.h>
82
83 GST_DEBUG_CATEGORY_STATIC (gst_nv_h265_dec_debug);
84 #define GST_CAT_DEFAULT gst_nv_h265_dec_debug
85
86 struct _GstNvH265Dec
87 {
88   GstH265Decoder parent;
89
90   GstVideoCodecState *output_state;
91
92   GstCudaContext *context;
93   GstNvDecoder *decoder;
94   CUVIDPICPARAMS params;
95
96   /* slice buffer which will be passed to CUVIDPICPARAMS::pBitstreamData */
97   guint8 *bitstream_buffer;
98   /* allocated memory size of bitstream_buffer */
99   gsize bitstream_buffer_alloc_size;
100   /* current offset of bitstream_buffer (per frame) */
101   gsize bitstream_buffer_offset;
102
103   guint *slice_offsets;
104   guint slice_offsets_alloc_len;
105   guint num_slices;
106
107   guint width, height;
108   guint coded_width, coded_height;
109   guint bitdepth;
110   guint chroma_format_idc;
111 };
112
113 struct _GstNvH265DecClass
114 {
115   GstH265DecoderClass parent_class;
116   guint cuda_device_id;
117 };
118
119 #define gst_nv_h265_dec_parent_class parent_class
120 G_DEFINE_TYPE (GstNvH265Dec, gst_nv_h265_dec, GST_TYPE_H265_DECODER);
121
122 static void gst_nv_h265_decoder_finalize (GObject * object);
123 static void gst_nv_h265_dec_set_context (GstElement * element,
124     GstContext * context);
125 static gboolean gst_nv_h265_dec_open (GstVideoDecoder * decoder);
126 static gboolean gst_nv_h265_dec_close (GstVideoDecoder * decoder);
127 static gboolean gst_nv_h265_dec_negotiate (GstVideoDecoder * decoder);
128 static gboolean gst_nv_h265_dec_decide_allocation (GstVideoDecoder *
129     decoder, GstQuery * query);
130 static gboolean gst_nv_h265_dec_src_query (GstVideoDecoder * decoder,
131     GstQuery * query);
132
133 /* GstH265Decoder */
134 static GstFlowReturn gst_nv_h265_dec_new_sequence (GstH265Decoder * decoder,
135     const GstH265SPS * sps, gint max_dpb_size);
136 static GstFlowReturn gst_nv_h265_dec_new_picture (GstH265Decoder * decoder,
137     GstVideoCodecFrame * frame, GstH265Picture * picture);
138 static GstFlowReturn gst_nv_h265_dec_output_picture (GstH265Decoder *
139     decoder, GstVideoCodecFrame * frame, GstH265Picture * picture);
140 static GstFlowReturn gst_nv_h265_dec_start_picture (GstH265Decoder * decoder,
141     GstH265Picture * picture, GstH265Slice * slice, GstH265Dpb * dpb);
142 static GstFlowReturn gst_nv_h265_dec_decode_slice (GstH265Decoder * decoder,
143     GstH265Picture * picture, GstH265Slice * slice,
144     GArray * ref_pic_list0, GArray * ref_pic_list1);
145 static GstFlowReturn gst_nv_h265_dec_end_picture (GstH265Decoder * decoder,
146     GstH265Picture * picture);
147 static guint
148 gst_nv_h265_dec_get_preferred_output_delay (GstH265Decoder * decoder,
149     gboolean live);
150
151 static void
152 gst_nv_h265_dec_class_init (GstNvH265DecClass * klass)
153 {
154   GObjectClass *object_class = G_OBJECT_CLASS (klass);
155   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
156   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (klass);
157   GstH265DecoderClass *h265decoder_class = GST_H265_DECODER_CLASS (klass);
158
159   /**
160    * GstNvH265Dec
161    *
162    * Since: 1.18
163    */
164
165   object_class->finalize = gst_nv_h265_decoder_finalize;
166
167   element_class->set_context = GST_DEBUG_FUNCPTR (gst_nv_h265_dec_set_context);
168
169   decoder_class->open = GST_DEBUG_FUNCPTR (gst_nv_h265_dec_open);
170   decoder_class->close = GST_DEBUG_FUNCPTR (gst_nv_h265_dec_close);
171   decoder_class->negotiate = GST_DEBUG_FUNCPTR (gst_nv_h265_dec_negotiate);
172   decoder_class->decide_allocation =
173       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_decide_allocation);
174   decoder_class->src_query = GST_DEBUG_FUNCPTR (gst_nv_h265_dec_src_query);
175
176   h265decoder_class->new_sequence =
177       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_new_sequence);
178   h265decoder_class->new_picture =
179       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_new_picture);
180   h265decoder_class->output_picture =
181       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_output_picture);
182   h265decoder_class->start_picture =
183       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_start_picture);
184   h265decoder_class->decode_slice =
185       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_decode_slice);
186   h265decoder_class->end_picture =
187       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_end_picture);
188   h265decoder_class->get_preferred_output_delay =
189       GST_DEBUG_FUNCPTR (gst_nv_h265_dec_get_preferred_output_delay);
190
191   GST_DEBUG_CATEGORY_INIT (gst_nv_h265_dec_debug,
192       "nvh265dec", 0, "Nvidia H.265 Decoder");
193
194   gst_type_mark_as_plugin_api (GST_TYPE_NV_H265_DEC, 0);
195 }
196
197 static void
198 gst_nv_h265_dec_init (GstNvH265Dec * self)
199 {
200 }
201
202 static void
203 gst_nv_h265_decoder_finalize (GObject * object)
204 {
205   GstNvH265Dec *self = GST_NV_H265_DEC (object);
206
207   g_free (self->bitstream_buffer);
208   g_free (self->slice_offsets);
209
210   G_OBJECT_CLASS (parent_class)->finalize (object);
211 }
212
213 static void
214 gst_nv_h265_dec_set_context (GstElement * element, GstContext * context)
215 {
216   GstNvH265Dec *self = GST_NV_H265_DEC (element);
217   GstNvH265DecClass *klass = GST_NV_H265_DEC_GET_CLASS (self);
218
219   GST_DEBUG_OBJECT (self, "set context %s",
220       gst_context_get_context_type (context));
221
222   if (gst_cuda_handle_set_context (element, context, klass->cuda_device_id,
223           &self->context)) {
224     goto done;
225   }
226
227   if (self->decoder)
228     gst_nv_decoder_handle_set_context (self->decoder, element, context);
229
230 done:
231   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
232 }
233
234 static gboolean
235 gst_nv_h265_dec_open (GstVideoDecoder * decoder)
236 {
237   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
238   GstNvH265DecClass *klass = GST_NV_H265_DEC_GET_CLASS (self);
239
240   if (!gst_cuda_ensure_element_context (GST_ELEMENT (self),
241           klass->cuda_device_id, &self->context)) {
242     GST_ERROR_OBJECT (self, "Required element data is unavailable");
243     return FALSE;
244   }
245
246   self->decoder = gst_nv_decoder_new (self->context);
247   if (!self->decoder) {
248     GST_ERROR_OBJECT (self, "Failed to create decoder object");
249     gst_clear_object (&self->context);
250
251     return FALSE;
252   }
253
254   return TRUE;
255 }
256
257 static gboolean
258 gst_nv_h265_dec_close (GstVideoDecoder * decoder)
259 {
260   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
261
262   g_clear_pointer (&self->output_state, gst_video_codec_state_unref);
263   gst_clear_object (&self->decoder);
264   gst_clear_object (&self->context);
265
266   return TRUE;
267 }
268
269 static gboolean
270 gst_nv_h265_dec_negotiate (GstVideoDecoder * decoder)
271 {
272   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
273   GstH265Decoder *h265dec = GST_H265_DECODER (decoder);
274
275   GST_DEBUG_OBJECT (self, "negotiate");
276
277   gst_nv_decoder_negotiate (self->decoder, decoder, h265dec->input_state,
278       &self->output_state);
279
280   /* TODO: add support D3D11 memory */
281
282   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
283 }
284
285 static gboolean
286 gst_nv_h265_dec_decide_allocation (GstVideoDecoder * decoder, GstQuery * query)
287 {
288   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
289
290   if (!gst_nv_decoder_decide_allocation (self->decoder, decoder, query)) {
291     GST_WARNING_OBJECT (self, "Failed to handle decide allocation");
292     return FALSE;
293   }
294
295   return GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation
296       (decoder, query);
297 }
298
299 static gboolean
300 gst_nv_h265_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
301 {
302   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
303
304   switch (GST_QUERY_TYPE (query)) {
305     case GST_QUERY_CONTEXT:
306       if (gst_cuda_handle_context_query (GST_ELEMENT (decoder), query,
307               self->context)) {
308         return TRUE;
309       } else if (self->decoder &&
310           gst_nv_decoder_handle_context_query (self->decoder, decoder, query)) {
311         return TRUE;
312       }
313       break;
314     default:
315       break;
316   }
317
318   return GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
319 }
320
321 static GstFlowReturn
322 gst_nv_h265_dec_new_sequence (GstH265Decoder * decoder, const GstH265SPS * sps,
323     gint max_dpb_size)
324 {
325   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
326   gint crop_width, crop_height;
327   gboolean modified = FALSE;
328
329   GST_LOG_OBJECT (self, "new sequence");
330
331   if (sps->conformance_window_flag) {
332     crop_width = sps->crop_rect_width;
333     crop_height = sps->crop_rect_height;
334   } else {
335     crop_width = sps->width;
336     crop_height = sps->height;
337   }
338
339   if (self->width != crop_width || self->height != crop_height ||
340       self->coded_width != sps->width || self->coded_height != sps->height) {
341     GST_INFO_OBJECT (self, "resolution changed %dx%d (%dx%d)",
342         crop_width, crop_height, sps->width, sps->height);
343     self->width = crop_width;
344     self->height = crop_height;
345     self->coded_width = sps->width;
346     self->coded_height = sps->height;
347     modified = TRUE;
348   }
349
350   if (self->bitdepth != sps->bit_depth_luma_minus8 + 8) {
351     GST_INFO_OBJECT (self, "bitdepth changed");
352     self->bitdepth = sps->bit_depth_luma_minus8 + 8;
353     modified = TRUE;
354   }
355
356   if (self->chroma_format_idc != sps->chroma_format_idc) {
357     GST_INFO_OBJECT (self, "chroma format changed");
358     self->chroma_format_idc = sps->chroma_format_idc;
359     modified = TRUE;
360   }
361
362   if (modified || !gst_nv_decoder_is_configured (self->decoder)) {
363     GstVideoInfo info;
364     GstVideoFormat out_format = GST_VIDEO_FORMAT_UNKNOWN;
365
366     if (self->bitdepth == 8) {
367       if (self->chroma_format_idc == 1) {
368         out_format = GST_VIDEO_FORMAT_NV12;
369       } else if (self->chroma_format_idc == 3) {
370         out_format = GST_VIDEO_FORMAT_Y444;
371       } else {
372         GST_FIXME_OBJECT (self, "8 bits supports only 4:2:0 or 4:4:4 format");
373       }
374     } else if (self->bitdepth == 10) {
375       if (self->chroma_format_idc == 1) {
376         out_format = GST_VIDEO_FORMAT_P010_10LE;
377       } else if (self->chroma_format_idc == 3) {
378         out_format = GST_VIDEO_FORMAT_Y444_16LE;
379       } else {
380         GST_FIXME_OBJECT (self, "10 bits supports only 4:2:0 or 4:4:4 format");
381       }
382     } else if (self->bitdepth == 12 || self->bitdepth == 16) {
383       if (self->chroma_format_idc == 1) {
384         out_format = GST_VIDEO_FORMAT_P016_LE;
385       } else if (self->chroma_format_idc == 3) {
386         out_format = GST_VIDEO_FORMAT_Y444_16LE;
387       } else {
388         GST_FIXME_OBJECT (self, "%d bits supports only 4:2:0 or 4:4:4 format",
389             self->bitdepth);
390       }
391     }
392
393     if (out_format == GST_VIDEO_FORMAT_UNKNOWN) {
394       GST_ERROR_OBJECT (self, "Could not support bitdepth/chroma format");
395       return GST_FLOW_NOT_NEGOTIATED;
396     }
397
398     gst_video_info_set_format (&info, out_format, self->width, self->height);
399
400     if (!gst_nv_decoder_configure (self->decoder,
401             cudaVideoCodec_HEVC, &info, self->coded_width, self->coded_height,
402             self->bitdepth, max_dpb_size, FALSE)) {
403       GST_ERROR_OBJECT (self, "Failed to configure decoder");
404       return GST_FLOW_NOT_NEGOTIATED;
405     }
406
407     if (!gst_video_decoder_negotiate (GST_VIDEO_DECODER (self))) {
408       GST_ERROR_OBJECT (self, "Failed to negotiate with downstream");
409       return GST_FLOW_NOT_NEGOTIATED;
410     }
411
412     memset (&self->params, 0, sizeof (CUVIDPICPARAMS));
413   }
414
415   return GST_FLOW_OK;
416 }
417
418 static GstFlowReturn
419 gst_nv_h265_dec_new_picture (GstH265Decoder * decoder,
420     GstVideoCodecFrame * cframe, GstH265Picture * picture)
421 {
422   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
423   GstNvDecoderFrame *frame;
424
425   frame = gst_nv_decoder_new_frame (self->decoder);
426   if (!frame) {
427     GST_ERROR_OBJECT (self, "No available decoder frame");
428     return GST_FLOW_ERROR;
429   }
430
431   GST_LOG_OBJECT (self, "New decoder frame %p (index %d)", frame, frame->index);
432
433   gst_h265_picture_set_user_data (picture,
434       frame, (GDestroyNotify) gst_nv_decoder_frame_unref);
435
436   return GST_FLOW_OK;
437 }
438
439 static GstFlowReturn
440 gst_nv_h265_dec_output_picture (GstH265Decoder * decoder,
441     GstVideoCodecFrame * frame, GstH265Picture * picture)
442 {
443   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
444   GstVideoDecoder *vdec = GST_VIDEO_DECODER (decoder);
445   GstNvDecoderFrame *decoder_frame;
446
447   GST_LOG_OBJECT (self,
448       "Outputting picture %p (poc %d)", picture, picture->pic_order_cnt);
449
450   decoder_frame =
451       (GstNvDecoderFrame *) gst_h265_picture_get_user_data (picture);
452   if (!decoder_frame) {
453     GST_ERROR_OBJECT (self, "No decoder frame in picture %p", picture);
454     goto error;
455   }
456
457   if (!gst_nv_decoder_finish_frame (self->decoder, vdec, decoder_frame,
458           &frame->output_buffer)) {
459     GST_ERROR_OBJECT (self, "Failed to handle output picture");
460     goto error;
461   }
462
463   gst_h265_picture_unref (picture);
464
465   return gst_video_decoder_finish_frame (GST_VIDEO_DECODER (self), frame);
466
467 error:
468   gst_video_decoder_drop_frame (vdec, frame);
469   gst_h265_picture_unref (picture);
470
471   return GST_FLOW_ERROR;
472 }
473
474 static GstNvDecoderFrame *
475 gst_nv_h265_dec_get_decoder_frame_from_picture (GstNvH265Dec * self,
476     GstH265Picture * picture)
477 {
478   GstNvDecoderFrame *frame;
479
480   frame = (GstNvDecoderFrame *) gst_h265_picture_get_user_data (picture);
481
482   if (!frame)
483     GST_DEBUG_OBJECT (self, "current picture does not have decoder frame");
484
485   return frame;
486 }
487
488 static void
489 gst_nv_h265_dec_picture_params_from_sps (GstNvH265Dec * self,
490     const GstH265SPS * sps, CUVIDHEVCPICPARAMS * params)
491 {
492 #define COPY_FIELD(f) \
493   (params)->f = (sps)->f
494 #define COPY_FIELD_WITH_PREFIX(f) \
495   (params)->G_PASTE(sps_,f) = (sps)->f
496 #define COPY_FIELD_EXTENSION(f) \
497   (params)->f = (sps)->sps_extnsion_params.f
498
499   params->pic_width_in_luma_samples = sps->width;
500   params->pic_height_in_luma_samples = sps->height;
501   COPY_FIELD (log2_min_luma_coding_block_size_minus3);
502   COPY_FIELD (log2_diff_max_min_luma_coding_block_size);
503   COPY_FIELD (log2_min_transform_block_size_minus2);
504   COPY_FIELD (log2_diff_max_min_transform_block_size);
505   COPY_FIELD (pcm_enabled_flag);
506   COPY_FIELD (log2_min_pcm_luma_coding_block_size_minus3);
507   COPY_FIELD (log2_diff_max_min_pcm_luma_coding_block_size);
508   COPY_FIELD (pcm_sample_bit_depth_luma_minus1);
509   COPY_FIELD (pcm_sample_bit_depth_chroma_minus1);
510   COPY_FIELD (pcm_loop_filter_disabled_flag);
511   COPY_FIELD (strong_intra_smoothing_enabled_flag);
512   COPY_FIELD (max_transform_hierarchy_depth_intra);
513   COPY_FIELD (max_transform_hierarchy_depth_inter);
514   COPY_FIELD (max_transform_hierarchy_depth_inter);
515   COPY_FIELD (amp_enabled_flag);
516   COPY_FIELD (separate_colour_plane_flag);
517   COPY_FIELD (log2_max_pic_order_cnt_lsb_minus4);
518   COPY_FIELD (num_short_term_ref_pic_sets);
519   COPY_FIELD (long_term_ref_pics_present_flag);
520   COPY_FIELD (num_long_term_ref_pics_sps);
521   COPY_FIELD_WITH_PREFIX (temporal_mvp_enabled_flag);
522   COPY_FIELD (sample_adaptive_offset_enabled_flag);
523
524   params->scaling_list_enable_flag = sps->scaling_list_enabled_flag;
525
526   COPY_FIELD (bit_depth_luma_minus8);
527   COPY_FIELD (bit_depth_chroma_minus8);
528
529   /* Extension fields */
530   COPY_FIELD (sps_range_extension_flag);
531   if (sps->sps_range_extension_flag) {
532     COPY_FIELD_EXTENSION (high_precision_offsets_enabled_flag);
533     COPY_FIELD_EXTENSION (transform_skip_rotation_enabled_flag);
534     COPY_FIELD_EXTENSION (implicit_rdpcm_enabled_flag);
535     COPY_FIELD_EXTENSION (explicit_rdpcm_enabled_flag);
536     COPY_FIELD_EXTENSION (extended_precision_processing_flag);
537     COPY_FIELD_EXTENSION (intra_smoothing_disabled_flag);
538     COPY_FIELD_EXTENSION (persistent_rice_adaptation_enabled_flag);
539     COPY_FIELD_EXTENSION (cabac_bypass_alignment_enabled_flag);
540   }
541 #undef COPY_FIELD
542 #undef COPY_FIELD_WITH_PREFIX
543 #undef COPY_FIELD_EXTENSION
544 }
545
546 static gboolean
547 gst_nv_h265_dec_picture_params_from_pps (GstNvH265Dec * self,
548     const GstH265PPS * pps, CUVIDHEVCPICPARAMS * params)
549 {
550   gint i;
551
552 #define COPY_FIELD(f) \
553   (params)->f = (pps)->f
554 #define COPY_FIELD_WITH_PREFIX(f) \
555   (params)->G_PASTE(pps_,f) = (pps)->f
556 #define COPY_FIELD_EXTENSION(f) \
557   (params)->f = (pps)->pps_extension_params.f
558
559   COPY_FIELD (dependent_slice_segments_enabled_flag);
560   COPY_FIELD (slice_segment_header_extension_present_flag);
561   COPY_FIELD (sign_data_hiding_enabled_flag);
562   COPY_FIELD (cu_qp_delta_enabled_flag);
563   COPY_FIELD (diff_cu_qp_delta_depth);
564   COPY_FIELD (init_qp_minus26);
565   COPY_FIELD_WITH_PREFIX (cb_qp_offset);
566   COPY_FIELD_WITH_PREFIX (cr_qp_offset);
567   COPY_FIELD (constrained_intra_pred_flag);
568   COPY_FIELD (weighted_pred_flag);
569   COPY_FIELD (weighted_bipred_flag);
570   COPY_FIELD (transform_skip_enabled_flag);
571   COPY_FIELD (transquant_bypass_enabled_flag);
572   COPY_FIELD (entropy_coding_sync_enabled_flag);
573   COPY_FIELD (log2_parallel_merge_level_minus2);
574   COPY_FIELD (num_extra_slice_header_bits);
575   COPY_FIELD (loop_filter_across_tiles_enabled_flag);
576   COPY_FIELD (loop_filter_across_slices_enabled_flag);
577   COPY_FIELD (output_flag_present_flag);
578   COPY_FIELD (num_ref_idx_l0_default_active_minus1);
579   COPY_FIELD (num_ref_idx_l1_default_active_minus1);
580   COPY_FIELD (lists_modification_present_flag);
581   COPY_FIELD (cabac_init_present_flag);
582   COPY_FIELD_WITH_PREFIX (slice_chroma_qp_offsets_present_flag);
583   COPY_FIELD (deblocking_filter_override_enabled_flag);
584   COPY_FIELD_WITH_PREFIX (deblocking_filter_disabled_flag);
585   COPY_FIELD_WITH_PREFIX (beta_offset_div2);
586   COPY_FIELD_WITH_PREFIX (tc_offset_div2);
587   COPY_FIELD (tiles_enabled_flag);
588   COPY_FIELD (uniform_spacing_flag);
589
590   if (pps->tiles_enabled_flag) {
591     guint num_tile_columns;
592     guint num_tile_rows;
593
594     COPY_FIELD (num_tile_columns_minus1);
595     COPY_FIELD (num_tile_rows_minus1);
596
597     if (pps->num_tile_columns_minus1 >
598         G_N_ELEMENTS (params->column_width_minus1)) {
599       GST_ERROR_OBJECT (self,
600           "Too large column_width_minus1 %d", pps->num_tile_columns_minus1);
601       return FALSE;
602     }
603
604     if (pps->num_tile_rows_minus1 > G_N_ELEMENTS (params->row_height_minus1)) {
605       GST_ERROR_OBJECT (self,
606           "Too large num_tile_rows_minus1 %d", pps->num_tile_rows_minus1);
607       return FALSE;
608     }
609
610     /* XXX: The size of column_width_minus1 array in CUVIDHEVCPICPARAMS struct
611      * is 21 which is inconsistent with the spec.
612      * Just copy values as many as possible */
613     num_tile_columns = MIN (pps->num_tile_columns_minus1,
614         G_N_ELEMENTS (pps->column_width_minus1));
615     num_tile_rows = MIN (pps->num_tile_rows_minus1,
616         G_N_ELEMENTS (pps->row_height_minus1));
617
618     for (i = 0; i < num_tile_columns; i++)
619       COPY_FIELD (column_width_minus1[i]);
620
621     for (i = 0; i < num_tile_rows; i++)
622       COPY_FIELD (row_height_minus1[i]);
623   }
624
625   COPY_FIELD (pps_range_extension_flag);
626   if (pps->pps_range_extension_flag) {
627     COPY_FIELD_EXTENSION (cross_component_prediction_enabled_flag);
628     COPY_FIELD_EXTENSION (chroma_qp_offset_list_enabled_flag);
629     COPY_FIELD_EXTENSION (diff_cu_chroma_qp_offset_depth);
630     COPY_FIELD_EXTENSION (chroma_qp_offset_list_len_minus1);
631     for (i = 0; i < G_N_ELEMENTS (params->cb_qp_offset_list); i++)
632       COPY_FIELD_EXTENSION (cb_qp_offset_list[i]);
633     for (i = 0; i < G_N_ELEMENTS (params->cr_qp_offset_list); i++)
634       COPY_FIELD_EXTENSION (cr_qp_offset_list[i]);
635     COPY_FIELD_EXTENSION (log2_sao_offset_scale_luma);
636     COPY_FIELD_EXTENSION (log2_sao_offset_scale_chroma);
637   }
638 #undef COPY_FIELD
639 #undef COPY_FIELD_WITH_PREFIX
640 #undef COPY_FIELD_EXTENSION
641
642   return TRUE;
643 }
644
645 static void
646 gst_nv_h265_dec_reset_bitstream_params (GstNvH265Dec * self)
647 {
648   self->bitstream_buffer_offset = 0;
649   self->num_slices = 0;
650
651   self->params.nBitstreamDataLen = 0;
652   self->params.pBitstreamData = NULL;
653   self->params.nNumSlices = 0;
654   self->params.pSliceDataOffsets = NULL;
655 }
656
657 static GstFlowReturn
658 gst_nv_h265_dec_start_picture (GstH265Decoder * decoder,
659     GstH265Picture * picture, GstH265Slice * slice, GstH265Dpb * dpb)
660 {
661   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
662   CUVIDPICPARAMS *params = &self->params;
663   CUVIDHEVCPICPARAMS *h265_params = &params->CodecSpecific.hevc;
664   const GstH265SliceHdr *slice_header = &slice->header;
665   const GstH265SPS *sps;
666   const GstH265PPS *pps;
667   GstNvDecoderFrame *frame;
668   GArray *dpb_array;
669   gint num_ref_pic;
670   gint i, j;
671   const GstH265ScalingList *scaling_list = NULL;
672
673   /* both NVDEC and h265parser are using the same order */
674   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_4x4) ==
675       sizeof (h265_params->ScalingList4x4));
676   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_8x8) ==
677       sizeof (h265_params->ScalingList8x8));
678   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_16x16) ==
679       sizeof (h265_params->ScalingList16x16));
680   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_32x32) ==
681       sizeof (h265_params->ScalingList32x32));
682
683   g_return_val_if_fail (slice_header->pps != NULL, GST_FLOW_ERROR);
684   g_return_val_if_fail (slice_header->pps->sps != NULL, GST_FLOW_ERROR);
685
686   frame = gst_nv_h265_dec_get_decoder_frame_from_picture (self, picture);
687
688   if (!frame) {
689     GST_ERROR_OBJECT (self,
690         "Couldn't get decoder frame frame picture %p", picture);
691     return GST_FLOW_ERROR;
692   }
693
694   gst_nv_h265_dec_reset_bitstream_params (self);
695
696   pps = slice_header->pps;
697   sps = pps->sps;
698
699   /* FIXME: update sps/pps related params only when it's required */
700   params->PicWidthInMbs = sps->pic_width_in_luma_samples / 16;
701   params->FrameHeightInMbs = sps->pic_height_in_luma_samples / 16;
702   params->CurrPicIdx = frame->index;
703
704   /* nBitstreamDataLen, pBitstreamData, nNumSlices and pSliceDataOffsets
705    * will be set later */
706   params->ref_pic_flag = picture->ref;
707   params->intra_pic_flag = GST_H265_IS_NAL_TYPE_IRAP (slice->nalu.type);
708
709   h265_params->IrapPicFlag = GST_H265_IS_NAL_TYPE_IRAP (slice->nalu.type);
710   h265_params->IdrPicFlag = GST_H265_IS_NAL_TYPE_IDR (slice->nalu.type);
711
712   gst_nv_h265_dec_picture_params_from_sps (self, sps, h265_params);
713   if (!gst_nv_h265_dec_picture_params_from_pps (self, pps, h265_params)) {
714     GST_ERROR_OBJECT (self, "Couldn't copy pps");
715     return GST_FLOW_ERROR;
716   }
717
718   /* Fill reference */
719   if (decoder->NumPocStCurrBefore >
720       G_N_ELEMENTS (h265_params->RefPicSetStCurrBefore)) {
721     GST_ERROR_OBJECT (self, "Too many RefPicSetStCurrBefore");
722     return GST_FLOW_ERROR;
723   }
724
725   if (decoder->NumPocStCurrAfter >
726       G_N_ELEMENTS (h265_params->RefPicSetStCurrAfter)) {
727     GST_ERROR_OBJECT (self, "Too many RefPicSetStCurrAfter");
728     return GST_FLOW_ERROR;
729   }
730
731   if (decoder->NumPocLtCurr > G_N_ELEMENTS (h265_params->RefPicSetLtCurr)) {
732     GST_ERROR_OBJECT (self, "Too many RefPicSetLtCurr");
733     return GST_FLOW_ERROR;
734   }
735
736   /* Fill ref list */
737   h265_params->NumBitsForShortTermRPSInSlice =
738       slice_header->short_term_ref_pic_set_size;
739   h265_params->NumDeltaPocsOfRefRpsIdx =
740       slice_header->short_term_ref_pic_sets.NumDeltaPocsOfRefRpsIdx;
741   h265_params->NumPocTotalCurr = decoder->NumPicTotalCurr;
742   h265_params->NumPocStCurrBefore = decoder->NumPocStCurrBefore;
743   h265_params->NumPocStCurrAfter = decoder->NumPocStCurrAfter;
744   h265_params->NumPocLtCurr = decoder->NumPocLtCurr;
745   h265_params->CurrPicOrderCntVal = picture->pic_order_cnt;
746
747   dpb_array = gst_h265_dpb_get_pictures_all (dpb);
748   /* count only referenced frame */
749   num_ref_pic = 0;
750   for (i = 0; i < dpb_array->len; i++) {
751     GstH265Picture *other = g_array_index (dpb_array, GstH265Picture *, i);
752     GstNvDecoderFrame *other_frame;
753     gint picture_index = -1;
754
755     if (!other->ref)
756       continue;
757
758     if (num_ref_pic >= G_N_ELEMENTS (h265_params->RefPicIdx)) {
759       GST_ERROR_OBJECT (self, "Too many reference frames");
760       return GST_FLOW_ERROR;
761     }
762
763     other_frame = gst_nv_h265_dec_get_decoder_frame_from_picture (self, other);
764
765     if (other_frame)
766       picture_index = other_frame->index;
767
768     h265_params->RefPicIdx[num_ref_pic] = picture_index;
769     h265_params->PicOrderCntVal[num_ref_pic] = other->pic_order_cnt;
770     h265_params->IsLongTerm[num_ref_pic] = other->long_term;
771
772     num_ref_pic++;
773   }
774
775   g_array_unref (dpb_array);
776
777   for (i = num_ref_pic; i < G_N_ELEMENTS (h265_params->RefPicIdx); i++)
778     h265_params->RefPicIdx[i] = -1;
779
780   for (i = 0; i < decoder->NumPocStCurrBefore; i++) {
781     GstH265Picture *other;
782
783     if (!decoder->RefPicSetStCurrBefore[i]) {
784       GST_ERROR_OBJECT (self, "Empty RefPicSetStCurrBefore[%d]", i);
785       return GST_FLOW_ERROR;
786     }
787
788     other = decoder->RefPicSetStCurrBefore[i];
789
790     for (j = 0; j < num_ref_pic; j++) {
791       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
792         h265_params->RefPicSetStCurrBefore[i] = j;
793         break;
794       }
795     }
796   }
797
798   for (i = 0; i < decoder->NumPocStCurrAfter; i++) {
799     GstH265Picture *other;
800
801     if (!decoder->RefPicSetStCurrAfter[i]) {
802       GST_ERROR_OBJECT (self, "Empty RefPicSetStCurrAfter[%d]", i);
803       return GST_FLOW_ERROR;
804     }
805
806     other = decoder->RefPicSetStCurrAfter[i];
807
808     for (j = 0; j < num_ref_pic; j++) {
809       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
810         h265_params->RefPicSetStCurrAfter[i] = j;
811         break;
812       }
813     }
814   }
815
816   for (i = 0; i < decoder->NumPocLtCurr; i++) {
817     GstH265Picture *other;
818
819     if (!decoder->RefPicSetLtCurr[i]) {
820       GST_ERROR_OBJECT (self, "Empty RefPicSetLtCurr[%d]", i);
821       return GST_FLOW_ERROR;
822     }
823
824     other = decoder->RefPicSetLtCurr[i];
825
826     for (j = 0; j < num_ref_pic; j++) {
827       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
828         h265_params->RefPicSetLtCurr[i] = j;
829         break;
830       }
831     }
832   }
833
834   /* Fill scaling list */
835   if (pps->scaling_list_data_present_flag ||
836       (sps->scaling_list_enabled_flag
837           && !sps->scaling_list_data_present_flag)) {
838     scaling_list = &pps->scaling_list;
839   } else {
840     scaling_list = &sps->scaling_list;
841   }
842
843   memcpy (h265_params->ScalingList4x4, scaling_list->scaling_lists_4x4,
844       sizeof (scaling_list->scaling_lists_4x4));
845   memcpy (h265_params->ScalingList8x8, scaling_list->scaling_lists_8x8,
846       sizeof (scaling_list->scaling_lists_8x8));
847   memcpy (h265_params->ScalingList16x16, scaling_list->scaling_lists_16x16,
848       sizeof (scaling_list->scaling_lists_16x16));
849   memcpy (h265_params->ScalingList32x32, scaling_list->scaling_lists_32x32,
850       sizeof (scaling_list->scaling_lists_32x32));
851
852   for (i = 0; i < G_N_ELEMENTS (h265_params->ScalingListDCCoeff16x16); i++) {
853     h265_params->ScalingListDCCoeff16x16[i] =
854         scaling_list->scaling_list_dc_coef_minus8_16x16[i] + 8;
855   }
856
857   for (i = 0; i < G_N_ELEMENTS (h265_params->ScalingListDCCoeff32x32); i++) {
858     h265_params->ScalingListDCCoeff32x32[i] =
859         scaling_list->scaling_list_dc_coef_minus8_32x32[i] + 8;
860   }
861
862   return GST_FLOW_OK;
863 }
864
865 static GstFlowReturn
866 gst_nv_h265_dec_decode_slice (GstH265Decoder * decoder,
867     GstH265Picture * picture, GstH265Slice * slice,
868     GArray * ref_pic_list0, GArray * ref_pic_list1)
869 {
870   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
871   gsize new_size;
872
873   GST_LOG_OBJECT (self, "Decode slice, nalu size %u", slice->nalu.size);
874
875   if (self->slice_offsets_alloc_len < self->num_slices + 1) {
876     self->slice_offsets = (guint *) g_realloc_n (self->slice_offsets,
877         self->num_slices + 1, sizeof (guint));
878   }
879   self->slice_offsets[self->num_slices] = self->bitstream_buffer_offset;
880   GST_LOG_OBJECT (self, "Slice offset %u for slice %d",
881       self->slice_offsets[self->num_slices], self->num_slices);
882
883   self->num_slices++;
884
885   new_size = self->bitstream_buffer_offset + slice->nalu.size + 3;
886   if (self->bitstream_buffer_alloc_size < new_size) {
887     self->bitstream_buffer =
888         (guint8 *) g_realloc (self->bitstream_buffer, new_size);
889   }
890
891   self->bitstream_buffer[self->bitstream_buffer_offset] = 0;
892   self->bitstream_buffer[self->bitstream_buffer_offset + 1] = 0;
893   self->bitstream_buffer[self->bitstream_buffer_offset + 2] = 1;
894
895   memcpy (self->bitstream_buffer + self->bitstream_buffer_offset + 3,
896       slice->nalu.data + slice->nalu.offset, slice->nalu.size);
897   self->bitstream_buffer_offset = new_size;
898
899   return GST_FLOW_OK;
900 }
901
902 static GstFlowReturn
903 gst_nv_h265_dec_end_picture (GstH265Decoder * decoder, GstH265Picture * picture)
904 {
905   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
906   gboolean ret;
907   CUVIDPICPARAMS *params = &self->params;
908
909   params->nBitstreamDataLen = self->bitstream_buffer_offset;
910   params->pBitstreamData = self->bitstream_buffer;
911   params->nNumSlices = self->num_slices;
912   params->pSliceDataOffsets = self->slice_offsets;
913
914   GST_LOG_OBJECT (self, "End picture, bitstream len: %" G_GSIZE_FORMAT
915       ", num slices %d", self->bitstream_buffer_offset, self->num_slices);
916
917   ret = gst_nv_decoder_decode_picture (self->decoder, &self->params);
918
919   if (!ret) {
920     GST_ERROR_OBJECT (self, "Failed to decode picture");
921     return GST_FLOW_ERROR;
922   }
923
924   return GST_FLOW_OK;
925 }
926
927 static guint
928 gst_nv_h265_dec_get_preferred_output_delay (GstH265Decoder * decoder,
929     gboolean live)
930 {
931   /* Prefer to zero latency for live pipeline */
932   if (live)
933     return 0;
934
935   /* NVCODEC SDK uses 4 frame delay for better throughput performance */
936   return 4;
937 }
938
939 typedef struct
940 {
941   GstCaps *sink_caps;
942   GstCaps *src_caps;
943   guint cuda_device_id;
944   gboolean is_default;
945 } GstNvH265DecClassData;
946
947 static void
948 gst_nv_h265_dec_subclass_init (gpointer klass, GstNvH265DecClassData * cdata)
949 {
950   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
951   GstNvH265DecClass *nvdec_class = (GstNvH265DecClass *) (klass);
952   gchar *long_name;
953
954   if (cdata->is_default) {
955     long_name = g_strdup_printf ("NVDEC H.265 Stateless Decoder");
956   } else {
957     long_name = g_strdup_printf ("NVDEC H.265 Stateless Decoder with device %d",
958         cdata->cuda_device_id);
959   }
960
961   gst_element_class_set_metadata (element_class, long_name,
962       "Codec/Decoder/Video/Hardware",
963       "Nvidia H.265 video decoder", "Seungha Yang <seungha@centricular.com>");
964   g_free (long_name);
965
966   gst_element_class_add_pad_template (element_class,
967       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
968           cdata->sink_caps));
969   gst_element_class_add_pad_template (element_class,
970       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
971           cdata->src_caps));
972
973   nvdec_class->cuda_device_id = cdata->cuda_device_id;
974
975   gst_caps_unref (cdata->sink_caps);
976   gst_caps_unref (cdata->src_caps);
977   g_free (cdata);
978 }
979
980 void
981 gst_nv_h265_dec_register (GstPlugin * plugin, guint device_id, guint rank,
982     GstCaps * sink_caps, GstCaps * src_caps, gboolean is_primary)
983 {
984   GTypeQuery type_query;
985   GTypeInfo type_info = { 0, };
986   GType subtype;
987   gchar *type_name;
988   gchar *feature_name;
989   GstNvH265DecClassData *cdata;
990   gboolean is_default = TRUE;
991   GValue value_list = G_VALUE_INIT;
992   GValue value = G_VALUE_INIT;
993
994   /**
995    * element-nvh265sldec
996    *
997    * Since: 1.18
998    */
999
1000   cdata = g_new0 (GstNvH265DecClassData, 1);
1001   cdata->sink_caps = gst_caps_copy (sink_caps);
1002
1003   /* Update stream-format since we support packetized format as well */
1004   g_value_init (&value_list, GST_TYPE_LIST);
1005   g_value_init (&value, G_TYPE_STRING);
1006
1007   g_value_set_static_string (&value, "hev1");
1008   gst_value_list_append_value (&value_list, &value);
1009
1010   g_value_set_static_string (&value, "hvc1");
1011   gst_value_list_append_value (&value_list, &value);
1012
1013   g_value_set_static_string (&value, "byte-stream");
1014   gst_value_list_append_value (&value_list, &value);
1015
1016   gst_caps_set_value (cdata->sink_caps, "stream-format", &value_list);
1017   g_value_unset (&value);
1018   g_value_unset (&value_list);
1019
1020   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
1021       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1022   cdata->src_caps = gst_caps_ref (src_caps);
1023   cdata->cuda_device_id = device_id;
1024
1025   g_type_query (GST_TYPE_NV_H265_DEC, &type_query);
1026   memset (&type_info, 0, sizeof (type_info));
1027   type_info.class_size = type_query.class_size;
1028   type_info.instance_size = type_query.instance_size;
1029   type_info.class_init = (GClassInitFunc) gst_nv_h265_dec_subclass_init;
1030   type_info.class_data = cdata;
1031
1032   if (is_primary) {
1033     type_name = g_strdup ("GstNvH265StatelessPrimaryDec");
1034     feature_name = g_strdup ("nvh265dec");
1035   } else {
1036     type_name = g_strdup ("GstNvH265StatelessDec");
1037     feature_name = g_strdup ("nvh265sldec");
1038   }
1039
1040   if (g_type_from_name (type_name) != 0) {
1041     g_free (type_name);
1042     g_free (feature_name);
1043     if (is_primary) {
1044       type_name =
1045           g_strdup_printf ("GstNvH265StatelessPrimaryDevice%dDec", device_id);
1046       feature_name = g_strdup_printf ("nvh265device%ddec", device_id);
1047     } else {
1048       type_name = g_strdup_printf ("GstNvH265StatelessDevice%dDec", device_id);
1049       feature_name = g_strdup_printf ("nvh265sldevice%ddec", device_id);
1050     }
1051
1052     is_default = FALSE;
1053   }
1054
1055   cdata->is_default = is_default;
1056   subtype = g_type_register_static (GST_TYPE_NV_H265_DEC,
1057       type_name, &type_info, 0);
1058
1059   /* make lower rank than default device */
1060   if (rank > 0 && !is_default)
1061     rank--;
1062
1063   if (!gst_element_register (plugin, feature_name, rank, subtype))
1064     GST_WARNING ("Failed to register plugin '%s'", type_name);
1065
1066   g_free (type_name);
1067   g_free (feature_name);
1068 }