nvh265sldec: Fix for decoding 12bits stream
[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 "gstnvh265dec.h"
78 #include "gstcudautils.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   const GstH265SPS *last_sps;
93   const GstH265PPS *last_pps;
94
95   GstCudaContext *context;
96   GstNvDecoder *decoder;
97   CUVIDPICPARAMS params;
98
99   /* slice buffer which will be passed to CUVIDPICPARAMS::pBitstreamData */
100   guint8 *bitstream_buffer;
101   /* allocated memory size of bitstream_buffer */
102   gsize bitstream_buffer_alloc_size;
103   /* current offset of bitstream_buffer (per frame) */
104   gsize bitstream_buffer_offset;
105
106   guint *slice_offsets;
107   guint slice_offsets_alloc_len;
108   guint num_slices;
109
110   guint width, height;
111   guint coded_width, coded_height;
112   guint bitdepth;
113   guint chroma_format_idc;
114 };
115
116 struct _GstNvH265DecClass
117 {
118   GstH265DecoderClass parent_class;
119   guint cuda_device_id;
120 };
121
122 #define gst_nv_h265_dec_parent_class parent_class
123 G_DEFINE_TYPE (GstNvH265Dec, gst_nv_h265_dec, GST_TYPE_H265_DECODER);
124
125 static void gst_nv_h265_decoder_finalize (GObject * object);
126 static void gst_nv_h265_dec_set_context (GstElement * element,
127     GstContext * context);
128 static gboolean gst_nv_h265_dec_open (GstVideoDecoder * decoder);
129 static gboolean gst_nv_h265_dec_close (GstVideoDecoder * decoder);
130 static gboolean gst_nv_h265_dec_negotiate (GstVideoDecoder * decoder);
131 static gboolean gst_nv_h265_dec_decide_allocation (GstVideoDecoder *
132     decoder, GstQuery * query);
133 static gboolean gst_nv_h265_dec_src_query (GstVideoDecoder * decoder,
134     GstQuery * query);
135
136 /* GstH265Decoder */
137 static GstFlowReturn gst_nv_h265_dec_new_sequence (GstH265Decoder * decoder,
138     const GstH265SPS * sps, gint max_dpb_size);
139 static GstFlowReturn gst_nv_h265_dec_new_picture (GstH265Decoder * decoder,
140     GstVideoCodecFrame * frame, GstH265Picture * picture);
141 static GstFlowReturn gst_nv_h265_dec_output_picture (GstH265Decoder *
142     decoder, GstVideoCodecFrame * frame, GstH265Picture * picture);
143 static GstFlowReturn gst_nv_h265_dec_start_picture (GstH265Decoder * decoder,
144     GstH265Picture * picture, GstH265Slice * slice, GstH265Dpb * dpb);
145 static GstFlowReturn gst_nv_h265_dec_decode_slice (GstH265Decoder * decoder,
146     GstH265Picture * picture, GstH265Slice * slice,
147     GArray * ref_pic_list0, GArray * ref_pic_list1);
148 static GstFlowReturn gst_nv_h265_dec_end_picture (GstH265Decoder * decoder,
149     GstH265Picture * picture);
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
189   GST_DEBUG_CATEGORY_INIT (gst_nv_h265_dec_debug,
190       "nvh265dec", 0, "Nvidia H.265 Decoder");
191
192   gst_type_mark_as_plugin_api (GST_TYPE_NV_H265_DEC, 0);
193 }
194
195 static void
196 gst_nv_h265_dec_init (GstNvH265Dec * self)
197 {
198 }
199
200 static void
201 gst_nv_h265_decoder_finalize (GObject * object)
202 {
203   GstNvH265Dec *self = GST_NV_H265_DEC (object);
204
205   g_free (self->bitstream_buffer);
206   g_free (self->slice_offsets);
207
208   G_OBJECT_CLASS (parent_class)->finalize (object);
209 }
210
211 static void
212 gst_nv_h265_dec_set_context (GstElement * element, GstContext * context)
213 {
214   GstNvH265Dec *self = GST_NV_H265_DEC (element);
215   GstNvH265DecClass *klass = GST_NV_H265_DEC_GET_CLASS (self);
216
217   GST_DEBUG_OBJECT (self, "set context %s",
218       gst_context_get_context_type (context));
219
220   if (gst_cuda_handle_set_context (element, context, klass->cuda_device_id,
221           &self->context)) {
222     goto done;
223   }
224
225   if (self->decoder)
226     gst_nv_decoder_handle_set_context (self->decoder, element, context);
227
228 done:
229   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
230 }
231
232 static gboolean
233 gst_nv_h265_dec_open (GstVideoDecoder * decoder)
234 {
235   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
236   GstNvH265DecClass *klass = GST_NV_H265_DEC_GET_CLASS (self);
237
238   if (!gst_cuda_ensure_element_context (GST_ELEMENT (self),
239           klass->cuda_device_id, &self->context)) {
240     GST_ERROR_OBJECT (self, "Required element data is unavailable");
241     return FALSE;
242   }
243
244   self->decoder = gst_nv_decoder_new (self->context);
245   if (!self->decoder) {
246     GST_ERROR_OBJECT (self, "Failed to create decoder object");
247     gst_clear_object (&self->context);
248
249     return FALSE;
250   }
251
252   return TRUE;
253 }
254
255 static gboolean
256 gst_nv_h265_dec_close (GstVideoDecoder * decoder)
257 {
258   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
259
260   g_clear_pointer (&self->output_state, gst_video_codec_state_unref);
261   gst_clear_object (&self->decoder);
262   gst_clear_object (&self->context);
263
264   return TRUE;
265 }
266
267 static gboolean
268 gst_nv_h265_dec_negotiate (GstVideoDecoder * decoder)
269 {
270   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
271   GstH265Decoder *h265dec = GST_H265_DECODER (decoder);
272
273   GST_DEBUG_OBJECT (self, "negotiate");
274
275   gst_nv_decoder_negotiate (self->decoder, decoder, h265dec->input_state,
276       &self->output_state);
277
278   /* TODO: add support D3D11 memory */
279
280   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
281 }
282
283 static gboolean
284 gst_nv_h265_dec_decide_allocation (GstVideoDecoder * decoder, GstQuery * query)
285 {
286   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
287
288   if (!gst_nv_decoder_decide_allocation (self->decoder, decoder, query)) {
289     GST_WARNING_OBJECT (self, "Failed to handle decide allocation");
290     return FALSE;
291   }
292
293   return GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation
294       (decoder, query);
295 }
296
297 static gboolean
298 gst_nv_h265_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
299 {
300   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
301
302   switch (GST_QUERY_TYPE (query)) {
303     case GST_QUERY_CONTEXT:
304       if (gst_cuda_handle_context_query (GST_ELEMENT (decoder), query,
305               self->context)) {
306         return TRUE;
307       } else if (self->decoder &&
308           gst_nv_decoder_handle_context_query (self->decoder, decoder, query)) {
309         return TRUE;
310       }
311       break;
312     default:
313       break;
314   }
315
316   return GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
317 }
318
319 static GstFlowReturn
320 gst_nv_h265_dec_new_sequence (GstH265Decoder * decoder, const GstH265SPS * sps,
321     gint max_dpb_size)
322 {
323   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
324   gint crop_width, crop_height;
325   gboolean modified = FALSE;
326
327   GST_LOG_OBJECT (self, "new sequence");
328
329   if (sps->conformance_window_flag) {
330     crop_width = sps->crop_rect_width;
331     crop_height = sps->crop_rect_height;
332   } else {
333     crop_width = sps->width;
334     crop_height = sps->height;
335   }
336
337   if (self->width != crop_width || self->height != crop_height ||
338       self->coded_width != sps->width || self->coded_height != sps->height) {
339     GST_INFO_OBJECT (self, "resolution changed %dx%d (%dx%d)",
340         crop_width, crop_height, sps->width, sps->height);
341     self->width = crop_width;
342     self->height = crop_height;
343     self->coded_width = sps->width;
344     self->coded_height = sps->height;
345     modified = TRUE;
346   }
347
348   if (self->bitdepth != sps->bit_depth_luma_minus8 + 8) {
349     GST_INFO_OBJECT (self, "bitdepth changed");
350     self->bitdepth = sps->bit_depth_luma_minus8 + 8;
351     modified = TRUE;
352   }
353
354   if (self->chroma_format_idc != sps->chroma_format_idc) {
355     GST_INFO_OBJECT (self, "chroma format changed");
356     self->chroma_format_idc = sps->chroma_format_idc;
357     modified = TRUE;
358   }
359
360   if (modified || !gst_nv_decoder_is_configured (self->decoder)) {
361     GstVideoInfo info;
362     GstVideoFormat out_format = GST_VIDEO_FORMAT_UNKNOWN;
363
364     if (self->bitdepth == 8) {
365       if (self->chroma_format_idc == 1) {
366         out_format = GST_VIDEO_FORMAT_NV12;
367       } else if (self->chroma_format_idc == 3) {
368         out_format = GST_VIDEO_FORMAT_Y444;
369       } else {
370         GST_FIXME_OBJECT (self, "8 bits supports only 4:2:0 or 4:4:4 format");
371       }
372     } else if (self->bitdepth == 10) {
373       if (self->chroma_format_idc == 1) {
374         out_format = GST_VIDEO_FORMAT_P010_10LE;
375       } else if (self->chroma_format_idc == 3) {
376         out_format = GST_VIDEO_FORMAT_Y444_16LE;
377       } else {
378         GST_FIXME_OBJECT (self, "10 bits supports only 4:2:0 or 4:4:4 format");
379       }
380     } else if (self->bitdepth == 12 || self->bitdepth == 16) {
381       if (self->chroma_format_idc == 1) {
382         out_format = GST_VIDEO_FORMAT_P016_LE;
383       } else if (self->chroma_format_idc == 3) {
384         out_format = GST_VIDEO_FORMAT_Y444_16LE;
385       } else {
386         GST_FIXME_OBJECT (self, "%d bits supports only 4:2:0 or 4:4:4 format",
387             self->bitdepth);
388       }
389     }
390
391     if (out_format == GST_VIDEO_FORMAT_UNKNOWN) {
392       GST_ERROR_OBJECT (self, "Could not support bitdepth/chroma format");
393       return GST_FLOW_NOT_NEGOTIATED;
394     }
395
396     gst_video_info_set_format (&info, out_format, self->width, self->height);
397
398     if (!gst_nv_decoder_configure (self->decoder,
399             cudaVideoCodec_HEVC, &info, self->coded_width, self->coded_height,
400             self->bitdepth,
401             /* Additional 2 buffers for margin */
402             max_dpb_size + 2)) {
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     self->last_sps = NULL;
413     self->last_pps = NULL;
414     memset (&self->params, 0, sizeof (CUVIDPICPARAMS));
415   }
416
417   return GST_FLOW_OK;
418 }
419
420 static GstFlowReturn
421 gst_nv_h265_dec_new_picture (GstH265Decoder * decoder,
422     GstVideoCodecFrame * cframe, GstH265Picture * picture)
423 {
424   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
425   GstNvDecoderFrame *frame;
426
427   frame = gst_nv_decoder_new_frame (self->decoder);
428   if (!frame) {
429     GST_ERROR_OBJECT (self, "No available decoder frame");
430     return GST_FLOW_ERROR;
431   }
432
433   GST_LOG_OBJECT (self, "New decoder frame %p (index %d)", frame, frame->index);
434
435   gst_h265_picture_set_user_data (picture,
436       frame, (GDestroyNotify) gst_nv_decoder_frame_unref);
437
438   return GST_FLOW_OK;
439 }
440
441 static GstFlowReturn
442 gst_nv_h265_dec_output_picture (GstH265Decoder * decoder,
443     GstVideoCodecFrame * frame, GstH265Picture * picture)
444 {
445   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
446   GstVideoDecoder *vdec = GST_VIDEO_DECODER (decoder);
447   GstNvDecoderFrame *decoder_frame;
448
449   GST_LOG_OBJECT (self,
450       "Outputting picture %p (poc %d)", picture, picture->pic_order_cnt);
451
452   decoder_frame =
453       (GstNvDecoderFrame *) gst_h265_picture_get_user_data (picture);
454   if (!decoder_frame) {
455     GST_ERROR_OBJECT (self, "No decoder frame in picture %p", picture);
456     goto error;
457   }
458
459   if (!gst_nv_decoder_finish_frame (self->decoder, vdec, decoder_frame,
460           &frame->output_buffer)) {
461     GST_ERROR_OBJECT (self, "Failed to handle output picture");
462     goto error;
463   }
464
465   gst_h265_picture_unref (picture);
466
467   return gst_video_decoder_finish_frame (GST_VIDEO_DECODER (self), frame);
468
469 error:
470   gst_video_decoder_drop_frame (vdec, frame);
471   gst_h265_picture_unref (picture);
472
473   return GST_FLOW_ERROR;
474 }
475
476 static GstNvDecoderFrame *
477 gst_nv_h265_dec_get_decoder_frame_from_picture (GstNvH265Dec * self,
478     GstH265Picture * picture)
479 {
480   GstNvDecoderFrame *frame;
481
482   frame = (GstNvDecoderFrame *) gst_h265_picture_get_user_data (picture);
483
484   if (!frame)
485     GST_DEBUG_OBJECT (self, "current picture does not have decoder frame");
486
487   return frame;
488 }
489
490 static void
491 gst_nv_h265_dec_picture_params_from_sps (GstNvH265Dec * self,
492     const GstH265SPS * sps, CUVIDHEVCPICPARAMS * params)
493 {
494 #define COPY_FIELD(f) \
495   (params)->f = (sps)->f
496 #define COPY_FIELD_WITH_PREFIX(f) \
497   (params)->G_PASTE(sps_,f) = (sps)->f
498 #define COPY_FIELD_EXTENSION(f) \
499   (params)->f = (sps)->sps_extnsion_params.f
500
501   params->pic_width_in_luma_samples = sps->width;
502   params->pic_height_in_luma_samples = sps->height;
503   COPY_FIELD (log2_min_luma_coding_block_size_minus3);
504   COPY_FIELD (log2_diff_max_min_luma_coding_block_size);
505   COPY_FIELD (log2_min_transform_block_size_minus2);
506   COPY_FIELD (log2_diff_max_min_transform_block_size);
507   COPY_FIELD (pcm_enabled_flag);
508   COPY_FIELD (log2_min_pcm_luma_coding_block_size_minus3);
509   COPY_FIELD (log2_diff_max_min_pcm_luma_coding_block_size);
510   COPY_FIELD (pcm_sample_bit_depth_luma_minus1);
511   COPY_FIELD (pcm_sample_bit_depth_chroma_minus1);
512   COPY_FIELD (pcm_loop_filter_disabled_flag);
513   COPY_FIELD (strong_intra_smoothing_enabled_flag);
514   COPY_FIELD (max_transform_hierarchy_depth_intra);
515   COPY_FIELD (max_transform_hierarchy_depth_inter);
516   COPY_FIELD (max_transform_hierarchy_depth_inter);
517   COPY_FIELD (amp_enabled_flag);
518   COPY_FIELD (separate_colour_plane_flag);
519   COPY_FIELD (log2_max_pic_order_cnt_lsb_minus4);
520   COPY_FIELD (num_short_term_ref_pic_sets);
521   COPY_FIELD (long_term_ref_pics_present_flag);
522   COPY_FIELD (num_long_term_ref_pics_sps);
523   COPY_FIELD_WITH_PREFIX (temporal_mvp_enabled_flag);
524   COPY_FIELD (sample_adaptive_offset_enabled_flag);
525
526   params->scaling_list_enable_flag = sps->scaling_list_enabled_flag;
527
528   COPY_FIELD (bit_depth_luma_minus8);
529   COPY_FIELD (bit_depth_chroma_minus8);
530
531   /* Extension fields */
532   COPY_FIELD (sps_range_extension_flag);
533   if (sps->sps_range_extension_flag) {
534     COPY_FIELD_EXTENSION (high_precision_offsets_enabled_flag);
535     COPY_FIELD_EXTENSION (transform_skip_rotation_enabled_flag);
536     COPY_FIELD_EXTENSION (implicit_rdpcm_enabled_flag);
537     COPY_FIELD_EXTENSION (explicit_rdpcm_enabled_flag);
538     COPY_FIELD_EXTENSION (extended_precision_processing_flag);
539     COPY_FIELD_EXTENSION (intra_smoothing_disabled_flag);
540     COPY_FIELD_EXTENSION (persistent_rice_adaptation_enabled_flag);
541     COPY_FIELD_EXTENSION (cabac_bypass_alignment_enabled_flag);
542   }
543 #undef COPY_FIELD
544 #undef COPY_FIELD_WITH_PREFIX
545 #undef COPY_FIELD_EXTENSION
546 }
547
548 static gboolean
549 gst_nv_h265_dec_picture_params_from_pps (GstNvH265Dec * self,
550     const GstH265PPS * pps, CUVIDHEVCPICPARAMS * params)
551 {
552   gint i;
553
554 #define COPY_FIELD(f) \
555   (params)->f = (pps)->f
556 #define COPY_FIELD_WITH_PREFIX(f) \
557   (params)->G_PASTE(pps_,f) = (pps)->f
558 #define COPY_FIELD_EXTENSION(f) \
559   (params)->f = (pps)->pps_extension_params.f
560
561   COPY_FIELD (dependent_slice_segments_enabled_flag);
562   COPY_FIELD (slice_segment_header_extension_present_flag);
563   COPY_FIELD (sign_data_hiding_enabled_flag);
564   COPY_FIELD (cu_qp_delta_enabled_flag);
565   COPY_FIELD (diff_cu_qp_delta_depth);
566   COPY_FIELD (init_qp_minus26);
567   COPY_FIELD_WITH_PREFIX (cb_qp_offset);
568   COPY_FIELD_WITH_PREFIX (cr_qp_offset);
569   COPY_FIELD (constrained_intra_pred_flag);
570   COPY_FIELD (weighted_pred_flag);
571   COPY_FIELD (weighted_bipred_flag);
572   COPY_FIELD (transform_skip_enabled_flag);
573   COPY_FIELD (transquant_bypass_enabled_flag);
574   COPY_FIELD (entropy_coding_sync_enabled_flag);
575   COPY_FIELD (log2_parallel_merge_level_minus2);
576   COPY_FIELD (num_extra_slice_header_bits);
577   COPY_FIELD (loop_filter_across_tiles_enabled_flag);
578   COPY_FIELD (loop_filter_across_slices_enabled_flag);
579   COPY_FIELD (output_flag_present_flag);
580   COPY_FIELD (num_ref_idx_l0_default_active_minus1);
581   COPY_FIELD (num_ref_idx_l1_default_active_minus1);
582   COPY_FIELD (lists_modification_present_flag);
583   COPY_FIELD (cabac_init_present_flag);
584   COPY_FIELD_WITH_PREFIX (slice_chroma_qp_offsets_present_flag);
585   COPY_FIELD (deblocking_filter_override_enabled_flag);
586   COPY_FIELD_WITH_PREFIX (deblocking_filter_disabled_flag);
587   COPY_FIELD_WITH_PREFIX (beta_offset_div2);
588   COPY_FIELD_WITH_PREFIX (tc_offset_div2);
589   COPY_FIELD (tiles_enabled_flag);
590   COPY_FIELD (uniform_spacing_flag);
591
592   if (pps->tiles_enabled_flag) {
593     guint num_tile_columns;
594     guint num_tile_rows;
595
596     COPY_FIELD (num_tile_columns_minus1);
597     COPY_FIELD (num_tile_rows_minus1);
598
599     if (pps->num_tile_columns_minus1 >
600         G_N_ELEMENTS (params->column_width_minus1)) {
601       GST_ERROR_OBJECT (self,
602           "Too large column_width_minus1 %d", pps->num_tile_columns_minus1);
603       return FALSE;
604     }
605
606     if (pps->num_tile_rows_minus1 > G_N_ELEMENTS (params->row_height_minus1)) {
607       GST_ERROR_OBJECT (self,
608           "Too large num_tile_rows_minus1 %d", pps->num_tile_rows_minus1);
609       return FALSE;
610     }
611
612     /* XXX: The size of column_width_minus1 array in CUVIDHEVCPICPARAMS struct
613      * is 21 which is inconsistent with the spec.
614      * Just copy values as many as possible */
615     num_tile_columns = MIN (pps->num_tile_columns_minus1,
616         G_N_ELEMENTS (pps->column_width_minus1));
617     num_tile_rows = MIN (pps->num_tile_rows_minus1,
618         G_N_ELEMENTS (pps->row_height_minus1));
619
620     for (i = 0; i < num_tile_columns; i++)
621       COPY_FIELD (column_width_minus1[i]);
622
623     for (i = 0; i < num_tile_rows; i++)
624       COPY_FIELD (row_height_minus1[i]);
625   }
626
627   COPY_FIELD (pps_range_extension_flag);
628   if (pps->pps_range_extension_flag) {
629     COPY_FIELD_EXTENSION (cross_component_prediction_enabled_flag);
630     COPY_FIELD_EXTENSION (chroma_qp_offset_list_enabled_flag);
631     COPY_FIELD_EXTENSION (diff_cu_chroma_qp_offset_depth);
632     COPY_FIELD_EXTENSION (chroma_qp_offset_list_len_minus1);
633     for (i = 0; i < G_N_ELEMENTS (params->cb_qp_offset_list); i++)
634       COPY_FIELD_EXTENSION (cb_qp_offset_list[i]);
635     for (i = 0; i < G_N_ELEMENTS (params->cr_qp_offset_list); i++)
636       COPY_FIELD_EXTENSION (cr_qp_offset_list[i]);
637     COPY_FIELD_EXTENSION (log2_sao_offset_scale_luma);
638     COPY_FIELD_EXTENSION (log2_sao_offset_scale_chroma);
639   }
640 #undef COPY_FIELD
641 #undef COPY_FIELD_WITH_PREFIX
642 #undef COPY_FIELD_EXTENSION
643
644   return TRUE;
645 }
646
647 static void
648 gst_nv_h265_dec_reset_bitstream_params (GstNvH265Dec * self)
649 {
650   self->bitstream_buffer_offset = 0;
651   self->num_slices = 0;
652
653   self->params.nBitstreamDataLen = 0;
654   self->params.pBitstreamData = NULL;
655   self->params.nNumSlices = 0;
656   self->params.pSliceDataOffsets = NULL;
657 }
658
659 static GstFlowReturn
660 gst_nv_h265_dec_start_picture (GstH265Decoder * decoder,
661     GstH265Picture * picture, GstH265Slice * slice, GstH265Dpb * dpb)
662 {
663   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
664   CUVIDPICPARAMS *params = &self->params;
665   CUVIDHEVCPICPARAMS *h265_params = &params->CodecSpecific.hevc;
666   const GstH265SliceHdr *slice_header = &slice->header;
667   const GstH265SPS *sps;
668   const GstH265PPS *pps;
669   GstNvDecoderFrame *frame;
670   GArray *dpb_array;
671   gint num_ref_pic;
672   gint i, j;
673   const GstH265ScalingList *scaling_list = NULL;
674
675   /* both NVDEC and h265parser are using the same order */
676   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_4x4) ==
677       sizeof (h265_params->ScalingList4x4));
678   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_8x8) ==
679       sizeof (h265_params->ScalingList8x8));
680   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_16x16) ==
681       sizeof (h265_params->ScalingList16x16));
682   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_32x32) ==
683       sizeof (h265_params->ScalingList32x32));
684
685   g_return_val_if_fail (slice_header->pps != NULL, GST_FLOW_ERROR);
686   g_return_val_if_fail (slice_header->pps->sps != NULL, GST_FLOW_ERROR);
687
688   frame = gst_nv_h265_dec_get_decoder_frame_from_picture (self, picture);
689
690   if (!frame) {
691     GST_ERROR_OBJECT (self,
692         "Couldn't get decoder frame frame picture %p", picture);
693     return GST_FLOW_ERROR;
694   }
695
696   gst_nv_h265_dec_reset_bitstream_params (self);
697
698   pps = slice_header->pps;
699   sps = pps->sps;
700
701   /* FIXME: update sps/pps related params only when it's required */
702   params->PicWidthInMbs = sps->pic_width_in_luma_samples / 16;
703   params->FrameHeightInMbs = sps->pic_height_in_luma_samples / 16;
704   params->CurrPicIdx = frame->index;
705
706   /* nBitstreamDataLen, pBitstreamData, nNumSlices and pSliceDataOffsets
707    * will be set later */
708   params->ref_pic_flag = picture->ref;
709   params->intra_pic_flag = GST_H265_IS_NAL_TYPE_IRAP (slice->nalu.type);
710
711   h265_params->IrapPicFlag = GST_H265_IS_NAL_TYPE_IRAP (slice->nalu.type);
712   h265_params->IdrPicFlag = GST_H265_IS_NAL_TYPE_IDR (slice->nalu.type);
713
714   if (!self->last_sps || self->last_sps != sps) {
715     GST_DEBUG_OBJECT (self, "Update params from SPS and PPS");
716     gst_nv_h265_dec_picture_params_from_sps (self, sps, h265_params);
717     if (!gst_nv_h265_dec_picture_params_from_pps (self, pps, h265_params)) {
718       GST_ERROR_OBJECT (self, "Couldn't copy pps");
719       return GST_FLOW_ERROR;
720     }
721     self->last_sps = sps;
722     self->last_pps = pps;
723   } else if (!self->last_pps || self->last_pps != pps) {
724     GST_DEBUG_OBJECT (self, "Update params from PPS");
725     if (!gst_nv_h265_dec_picture_params_from_pps (self, pps, h265_params)) {
726       GST_ERROR_OBJECT (self, "Couldn't copy pps");
727       return GST_FLOW_ERROR;
728     }
729     self->last_pps = pps;
730   } else {
731     GST_TRACE_OBJECT (self, "SPS and PPS were not updated");
732   }
733
734   /* Fill reference */
735   if (decoder->NumPocStCurrBefore >
736       G_N_ELEMENTS (h265_params->RefPicSetStCurrBefore)) {
737     GST_ERROR_OBJECT (self, "Too many RefPicSetStCurrBefore");
738     return GST_FLOW_ERROR;
739   }
740
741   if (decoder->NumPocStCurrAfter >
742       G_N_ELEMENTS (h265_params->RefPicSetStCurrAfter)) {
743     GST_ERROR_OBJECT (self, "Too many RefPicSetStCurrAfter");
744     return GST_FLOW_ERROR;
745   }
746
747   if (decoder->NumPocLtCurr > G_N_ELEMENTS (h265_params->RefPicSetLtCurr)) {
748     GST_ERROR_OBJECT (self, "Too many RefPicSetLtCurr");
749     return GST_FLOW_ERROR;
750   }
751
752   /* Fill ref list */
753   h265_params->NumBitsForShortTermRPSInSlice =
754       slice_header->short_term_ref_pic_set_size;
755   h265_params->NumDeltaPocsOfRefRpsIdx =
756       slice_header->short_term_ref_pic_sets.NumDeltaPocsOfRefRpsIdx;
757   h265_params->NumPocTotalCurr = decoder->NumPicTotalCurr;
758   h265_params->NumPocStCurrBefore = decoder->NumPocStCurrBefore;
759   h265_params->NumPocStCurrAfter = decoder->NumPocStCurrAfter;
760   h265_params->NumPocLtCurr = decoder->NumPocLtCurr;
761   h265_params->CurrPicOrderCntVal = picture->pic_order_cnt;
762
763   dpb_array = gst_h265_dpb_get_pictures_all (dpb);
764   /* count only referenced frame */
765   num_ref_pic = 0;
766   for (i = 0; i < dpb_array->len; i++) {
767     GstH265Picture *other = g_array_index (dpb_array, GstH265Picture *, i);
768     GstNvDecoderFrame *other_frame;
769     gint picture_index = -1;
770
771     if (!other->ref)
772       continue;
773
774     if (num_ref_pic >= G_N_ELEMENTS (h265_params->RefPicIdx)) {
775       GST_ERROR_OBJECT (self, "Too many reference frames");
776       return GST_FLOW_ERROR;
777     }
778
779     other_frame = gst_nv_h265_dec_get_decoder_frame_from_picture (self, other);
780
781     if (other_frame)
782       picture_index = other_frame->index;
783
784     h265_params->RefPicIdx[num_ref_pic] = picture_index;
785     h265_params->PicOrderCntVal[num_ref_pic] = other->pic_order_cnt;
786     h265_params->IsLongTerm[num_ref_pic] = other->long_term;
787
788     num_ref_pic++;
789   }
790
791   g_array_unref (dpb_array);
792
793   for (i = num_ref_pic; i < G_N_ELEMENTS (h265_params->RefPicIdx); i++)
794     h265_params->RefPicIdx[i] = -1;
795
796   for (i = 0; i < decoder->NumPocStCurrBefore; i++) {
797     GstH265Picture *other;
798
799     if (!decoder->RefPicSetStCurrBefore[i]) {
800       GST_ERROR_OBJECT (self, "Empty RefPicSetStCurrBefore[%d]", i);
801       return GST_FLOW_ERROR;
802     }
803
804     other = decoder->RefPicSetStCurrBefore[i];
805
806     for (j = 0; j < num_ref_pic; j++) {
807       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
808         h265_params->RefPicSetStCurrBefore[i] = j;
809         break;
810       }
811     }
812   }
813
814   for (i = 0; i < decoder->NumPocStCurrAfter; i++) {
815     GstH265Picture *other;
816
817     if (!decoder->RefPicSetStCurrAfter[i]) {
818       GST_ERROR_OBJECT (self, "Empty RefPicSetStCurrAfter[%d]", i);
819       return GST_FLOW_ERROR;
820     }
821
822     other = decoder->RefPicSetStCurrAfter[i];
823
824     for (j = 0; j < num_ref_pic; j++) {
825       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
826         h265_params->RefPicSetStCurrAfter[i] = j;
827         break;
828       }
829     }
830   }
831
832   for (i = 0; i < decoder->NumPocLtCurr; i++) {
833     GstH265Picture *other;
834
835     if (!decoder->RefPicSetLtCurr[i]) {
836       GST_ERROR_OBJECT (self, "Empty RefPicSetLtCurr[%d]", i);
837       return GST_FLOW_ERROR;
838     }
839
840     other = decoder->RefPicSetLtCurr[i];
841
842     for (j = 0; j < num_ref_pic; j++) {
843       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
844         h265_params->RefPicSetLtCurr[i] = j;
845         break;
846       }
847     }
848   }
849
850   /* Fill scaling list */
851   if (pps->scaling_list_data_present_flag ||
852       (sps->scaling_list_enabled_flag
853           && !sps->scaling_list_data_present_flag)) {
854     scaling_list = &pps->scaling_list;
855   } else {
856     scaling_list = &sps->scaling_list;
857   }
858
859   memcpy (h265_params->ScalingList4x4, scaling_list->scaling_lists_4x4,
860       sizeof (scaling_list->scaling_lists_4x4));
861   memcpy (h265_params->ScalingList8x8, scaling_list->scaling_lists_8x8,
862       sizeof (scaling_list->scaling_lists_8x8));
863   memcpy (h265_params->ScalingList16x16, scaling_list->scaling_lists_16x16,
864       sizeof (scaling_list->scaling_lists_16x16));
865   memcpy (h265_params->ScalingList32x32, scaling_list->scaling_lists_32x32,
866       sizeof (scaling_list->scaling_lists_32x32));
867
868   for (i = 0; i < G_N_ELEMENTS (h265_params->ScalingListDCCoeff16x16); i++) {
869     h265_params->ScalingListDCCoeff16x16[i] =
870         scaling_list->scaling_list_dc_coef_minus8_16x16[i] + 8;
871   }
872
873   for (i = 0; i < G_N_ELEMENTS (h265_params->ScalingListDCCoeff32x32); i++) {
874     h265_params->ScalingListDCCoeff32x32[i] =
875         scaling_list->scaling_list_dc_coef_minus8_32x32[i] + 8;
876   }
877
878   return GST_FLOW_OK;
879 }
880
881 static GstFlowReturn
882 gst_nv_h265_dec_decode_slice (GstH265Decoder * decoder,
883     GstH265Picture * picture, GstH265Slice * slice,
884     GArray * ref_pic_list0, GArray * ref_pic_list1)
885 {
886   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
887   gsize new_size;
888
889   GST_LOG_OBJECT (self, "Decode slice, nalu size %u", slice->nalu.size);
890
891   if (self->slice_offsets_alloc_len < self->num_slices + 1) {
892     self->slice_offsets = (guint *) g_realloc_n (self->slice_offsets,
893         self->num_slices + 1, sizeof (guint));
894   }
895   self->slice_offsets[self->num_slices] = self->bitstream_buffer_offset;
896   GST_LOG_OBJECT (self, "Slice offset %u for slice %d",
897       self->slice_offsets[self->num_slices], self->num_slices);
898
899   self->num_slices++;
900
901   new_size = self->bitstream_buffer_offset + slice->nalu.size + 3;
902   if (self->bitstream_buffer_alloc_size < new_size) {
903     self->bitstream_buffer =
904         (guint8 *) g_realloc (self->bitstream_buffer, new_size);
905   }
906
907   self->bitstream_buffer[self->bitstream_buffer_offset] = 0;
908   self->bitstream_buffer[self->bitstream_buffer_offset + 1] = 0;
909   self->bitstream_buffer[self->bitstream_buffer_offset + 2] = 1;
910
911   memcpy (self->bitstream_buffer + self->bitstream_buffer_offset + 3,
912       slice->nalu.data + slice->nalu.offset, slice->nalu.size);
913   self->bitstream_buffer_offset = new_size;
914
915   return GST_FLOW_OK;
916 }
917
918 static GstFlowReturn
919 gst_nv_h265_dec_end_picture (GstH265Decoder * decoder, GstH265Picture * picture)
920 {
921   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
922   gboolean ret;
923   CUVIDPICPARAMS *params = &self->params;
924
925   params->nBitstreamDataLen = self->bitstream_buffer_offset;
926   params->pBitstreamData = self->bitstream_buffer;
927   params->nNumSlices = self->num_slices;
928   params->pSliceDataOffsets = self->slice_offsets;
929
930   GST_LOG_OBJECT (self, "End picture, bitstream len: %" G_GSIZE_FORMAT
931       ", num slices %d", self->bitstream_buffer_offset, self->num_slices);
932
933   ret = gst_nv_decoder_decode_picture (self->decoder, &self->params);
934
935   if (!ret) {
936     GST_ERROR_OBJECT (self, "Failed to decode picture");
937     return GST_FLOW_ERROR;
938   }
939
940   return GST_FLOW_OK;
941 }
942
943 typedef struct
944 {
945   GstCaps *sink_caps;
946   GstCaps *src_caps;
947   guint cuda_device_id;
948   gboolean is_default;
949 } GstNvH265DecClassData;
950
951 static void
952 gst_nv_h265_dec_subclass_init (gpointer klass, GstNvH265DecClassData * cdata)
953 {
954   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
955   GstNvH265DecClass *nvdec_class = (GstNvH265DecClass *) (klass);
956   gchar *long_name;
957
958   if (cdata->is_default) {
959     long_name = g_strdup_printf ("NVDEC H.265 Stateless Decoder");
960   } else {
961     long_name = g_strdup_printf ("NVDEC H.265 Stateless Decoder with device %d",
962         cdata->cuda_device_id);
963   }
964
965   gst_element_class_set_metadata (element_class, long_name,
966       "Codec/Decoder/Video/Hardware",
967       "Nvidia H.265 video decoder", "Seungha Yang <seungha@centricular.com>");
968   g_free (long_name);
969
970   gst_element_class_add_pad_template (element_class,
971       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
972           cdata->sink_caps));
973   gst_element_class_add_pad_template (element_class,
974       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
975           cdata->src_caps));
976
977   nvdec_class->cuda_device_id = cdata->cuda_device_id;
978
979   gst_caps_unref (cdata->sink_caps);
980   gst_caps_unref (cdata->src_caps);
981   g_free (cdata);
982 }
983
984 void
985 gst_nv_h265_dec_register (GstPlugin * plugin, guint device_id, guint rank,
986     GstCaps * sink_caps, GstCaps * src_caps, gboolean is_primary)
987 {
988   GTypeQuery type_query;
989   GTypeInfo type_info = { 0, };
990   GType subtype;
991   gchar *type_name;
992   gchar *feature_name;
993   GstNvH265DecClassData *cdata;
994   gboolean is_default = TRUE;
995   GValue value_list = G_VALUE_INIT;
996   GValue value = G_VALUE_INIT;
997
998   /**
999    * element-nvh265sldec
1000    *
1001    * Since: 1.18
1002    */
1003
1004   cdata = g_new0 (GstNvH265DecClassData, 1);
1005   cdata->sink_caps = gst_caps_copy (sink_caps);
1006
1007   /* Update stream-format since we support packetized format as well */
1008   g_value_init (&value_list, GST_TYPE_LIST);
1009   g_value_init (&value, G_TYPE_STRING);
1010
1011   g_value_set_static_string (&value, "hev1");
1012   gst_value_list_append_value (&value_list, &value);
1013
1014   g_value_set_static_string (&value, "hvc1");
1015   gst_value_list_append_value (&value_list, &value);
1016
1017   g_value_set_static_string (&value, "byte-stream");
1018   gst_value_list_append_value (&value_list, &value);
1019
1020   gst_caps_set_value (cdata->sink_caps, "stream-format", &value_list);
1021   g_value_unset (&value);
1022   g_value_unset (&value_list);
1023
1024   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
1025       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1026   cdata->src_caps = gst_caps_ref (src_caps);
1027   cdata->cuda_device_id = device_id;
1028
1029   g_type_query (GST_TYPE_NV_H265_DEC, &type_query);
1030   memset (&type_info, 0, sizeof (type_info));
1031   type_info.class_size = type_query.class_size;
1032   type_info.instance_size = type_query.instance_size;
1033   type_info.class_init = (GClassInitFunc) gst_nv_h265_dec_subclass_init;
1034   type_info.class_data = cdata;
1035
1036   if (is_primary) {
1037     type_name = g_strdup ("GstNvH265StatelessPrimaryDec");
1038     feature_name = g_strdup ("nvh265dec");
1039   } else {
1040     type_name = g_strdup ("GstNvH265StatelessDec");
1041     feature_name = g_strdup ("nvh265sldec");
1042   }
1043
1044   if (g_type_from_name (type_name) != 0) {
1045     g_free (type_name);
1046     g_free (feature_name);
1047     if (is_primary) {
1048       type_name =
1049           g_strdup_printf ("GstNvH265StatelessPrimaryDevice%dDec", device_id);
1050       feature_name = g_strdup_printf ("nvh265device%ddec", device_id);
1051     } else {
1052       type_name = g_strdup_printf ("GstNvH265StatelessDevice%dDec", device_id);
1053       feature_name = g_strdup_printf ("nvh265sldevice%ddec", device_id);
1054     }
1055
1056     is_default = FALSE;
1057   }
1058
1059   cdata->is_default = is_default;
1060   subtype = g_type_register_static (GST_TYPE_NV_H265_DEC,
1061       type_name, &type_info, 0);
1062
1063   /* make lower rank than default device */
1064   if (rank > 0 && !is_default)
1065     rank--;
1066
1067   if (!gst_element_register (plugin, feature_name, rank, subtype))
1068     GST_WARNING ("Failed to register plugin '%s'", type_name);
1069
1070   g_free (type_name);
1071   g_free (feature_name);
1072 }