Move files from gst-plugins-bad into the "subprojects/gst-plugins-bad/" subdir
[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 gboolean gst_nv_h265_dec_new_sequence (GstH265Decoder * decoder,
138     const GstH265SPS * sps, gint max_dpb_size);
139 static gboolean 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 gboolean gst_nv_h265_dec_start_picture (GstH265Decoder * decoder,
144     GstH265Picture * picture, GstH265Slice * slice, GstH265Dpb * dpb);
145 static gboolean gst_nv_h265_dec_decode_slice (GstH265Decoder * decoder,
146     GstH265Picture * picture, GstH265Slice * slice,
147     GArray * ref_pic_list0, GArray * ref_pic_list1);
148 static gboolean 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 gboolean
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 {
368         GST_FIXME_OBJECT (self, "Could not support 8bits non-4:2:0 format");
369       }
370     } else if (self->bitdepth == 10) {
371       if (self->chroma_format_idc == 1)
372         out_format = GST_VIDEO_FORMAT_P010_10LE;
373       else {
374         GST_FIXME_OBJECT (self, "Could not support 10bits non-4:2:0 format");
375       }
376     }
377
378     if (out_format == GST_VIDEO_FORMAT_UNKNOWN) {
379       GST_ERROR_OBJECT (self, "Could not support bitdepth/chroma format");
380       return FALSE;
381     }
382
383     gst_video_info_set_format (&info, out_format, self->width, self->height);
384
385     if (!gst_nv_decoder_configure (self->decoder,
386             cudaVideoCodec_HEVC, &info, self->coded_width, self->coded_height,
387             /* Additional 2 buffers for margin */
388             max_dpb_size + 2)) {
389       GST_ERROR_OBJECT (self, "Failed to configure decoder");
390       return FALSE;
391     }
392
393     if (!gst_video_decoder_negotiate (GST_VIDEO_DECODER (self))) {
394       GST_ERROR_OBJECT (self, "Failed to negotiate with downstream");
395       return FALSE;
396     }
397
398     self->last_sps = NULL;
399     self->last_pps = NULL;
400     memset (&self->params, 0, sizeof (CUVIDPICPARAMS));
401   }
402
403   return TRUE;
404 }
405
406 static gboolean
407 gst_nv_h265_dec_new_picture (GstH265Decoder * decoder,
408     GstVideoCodecFrame * cframe, GstH265Picture * picture)
409 {
410   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
411   GstNvDecoderFrame *frame;
412
413   frame = gst_nv_decoder_new_frame (self->decoder);
414   if (!frame) {
415     GST_ERROR_OBJECT (self, "No available decoder frame");
416     return FALSE;
417   }
418
419   GST_LOG_OBJECT (self, "New decoder frame %p (index %d)", frame, frame->index);
420
421   gst_h265_picture_set_user_data (picture,
422       frame, (GDestroyNotify) gst_nv_decoder_frame_unref);
423
424   return TRUE;
425 }
426
427 static GstFlowReturn
428 gst_nv_h265_dec_output_picture (GstH265Decoder * decoder,
429     GstVideoCodecFrame * frame, GstH265Picture * picture)
430 {
431   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
432   GstVideoDecoder *vdec = GST_VIDEO_DECODER (decoder);
433   GstNvDecoderFrame *decoder_frame;
434
435   GST_LOG_OBJECT (self,
436       "Outputting picture %p (poc %d)", picture, picture->pic_order_cnt);
437
438   decoder_frame =
439       (GstNvDecoderFrame *) gst_h265_picture_get_user_data (picture);
440   if (!decoder_frame) {
441     GST_ERROR_OBJECT (self, "No decoder frame in picture %p", picture);
442     goto error;
443   }
444
445   if (!gst_nv_decoder_finish_frame (self->decoder, vdec, decoder_frame,
446           &frame->output_buffer)) {
447     GST_ERROR_OBJECT (self, "Failed to handle output picture");
448     goto error;
449   }
450
451   gst_h265_picture_unref (picture);
452
453   return gst_video_decoder_finish_frame (GST_VIDEO_DECODER (self), frame);
454
455 error:
456   gst_video_decoder_drop_frame (vdec, frame);
457   gst_h265_picture_unref (picture);
458
459   return GST_FLOW_ERROR;
460 }
461
462 static GstNvDecoderFrame *
463 gst_nv_h265_dec_get_decoder_frame_from_picture (GstNvH265Dec * self,
464     GstH265Picture * picture)
465 {
466   GstNvDecoderFrame *frame;
467
468   frame = (GstNvDecoderFrame *) gst_h265_picture_get_user_data (picture);
469
470   if (!frame)
471     GST_DEBUG_OBJECT (self, "current picture does not have decoder frame");
472
473   return frame;
474 }
475
476 static void
477 gst_nv_h265_dec_picture_params_from_sps (GstNvH265Dec * self,
478     const GstH265SPS * sps, CUVIDHEVCPICPARAMS * params)
479 {
480 #define COPY_FIELD(f) \
481   (params)->f = (sps)->f
482 #define COPY_FIELD_WITH_PREFIX(f) \
483   (params)->G_PASTE(sps_,f) = (sps)->f
484 #define COPY_FIELD_EXTENSION(f) \
485   (params)->f = (sps)->sps_extnsion_params.f
486
487   params->pic_width_in_luma_samples = sps->width;
488   params->pic_height_in_luma_samples = sps->height;
489   COPY_FIELD (log2_min_luma_coding_block_size_minus3);
490   COPY_FIELD (log2_diff_max_min_luma_coding_block_size);
491   COPY_FIELD (log2_min_transform_block_size_minus2);
492   COPY_FIELD (log2_diff_max_min_transform_block_size);
493   COPY_FIELD (pcm_enabled_flag);
494   COPY_FIELD (log2_min_pcm_luma_coding_block_size_minus3);
495   COPY_FIELD (log2_diff_max_min_pcm_luma_coding_block_size);
496   COPY_FIELD (pcm_sample_bit_depth_luma_minus1);
497   COPY_FIELD (pcm_sample_bit_depth_chroma_minus1);
498   COPY_FIELD (pcm_loop_filter_disabled_flag);
499   COPY_FIELD (strong_intra_smoothing_enabled_flag);
500   COPY_FIELD (max_transform_hierarchy_depth_intra);
501   COPY_FIELD (max_transform_hierarchy_depth_inter);
502   COPY_FIELD (max_transform_hierarchy_depth_inter);
503   COPY_FIELD (amp_enabled_flag);
504   COPY_FIELD (separate_colour_plane_flag);
505   COPY_FIELD (log2_max_pic_order_cnt_lsb_minus4);
506   COPY_FIELD (num_short_term_ref_pic_sets);
507   COPY_FIELD (long_term_ref_pics_present_flag);
508   COPY_FIELD (num_long_term_ref_pics_sps);
509   COPY_FIELD_WITH_PREFIX (temporal_mvp_enabled_flag);
510   COPY_FIELD (sample_adaptive_offset_enabled_flag);
511
512   params->scaling_list_enable_flag = sps->scaling_list_enabled_flag;
513
514   COPY_FIELD (bit_depth_luma_minus8);
515   COPY_FIELD (bit_depth_chroma_minus8);
516
517   /* Extension fields */
518   COPY_FIELD (sps_range_extension_flag);
519   if (sps->sps_range_extension_flag) {
520     COPY_FIELD_EXTENSION (high_precision_offsets_enabled_flag);
521     COPY_FIELD_EXTENSION (transform_skip_rotation_enabled_flag);
522     COPY_FIELD_EXTENSION (implicit_rdpcm_enabled_flag);
523     COPY_FIELD_EXTENSION (explicit_rdpcm_enabled_flag);
524     COPY_FIELD_EXTENSION (extended_precision_processing_flag);
525     COPY_FIELD_EXTENSION (intra_smoothing_disabled_flag);
526     COPY_FIELD_EXTENSION (persistent_rice_adaptation_enabled_flag);
527     COPY_FIELD_EXTENSION (cabac_bypass_alignment_enabled_flag);
528   }
529 #undef COPY_FIELD
530 #undef COPY_FIELD_WITH_PREFIX
531 #undef COPY_FIELD_EXTENSION
532 }
533
534 static gboolean
535 gst_nv_h265_dec_picture_params_from_pps (GstNvH265Dec * self,
536     const GstH265PPS * pps, CUVIDHEVCPICPARAMS * params)
537 {
538   gint i;
539
540 #define COPY_FIELD(f) \
541   (params)->f = (pps)->f
542 #define COPY_FIELD_WITH_PREFIX(f) \
543   (params)->G_PASTE(pps_,f) = (pps)->f
544 #define COPY_FIELD_EXTENSION(f) \
545   (params)->f = (pps)->pps_extension_params.f
546
547   COPY_FIELD (dependent_slice_segments_enabled_flag);
548   COPY_FIELD (slice_segment_header_extension_present_flag);
549   COPY_FIELD (sign_data_hiding_enabled_flag);
550   COPY_FIELD (cu_qp_delta_enabled_flag);
551   COPY_FIELD (diff_cu_qp_delta_depth);
552   COPY_FIELD (init_qp_minus26);
553   COPY_FIELD_WITH_PREFIX (cb_qp_offset);
554   COPY_FIELD_WITH_PREFIX (cr_qp_offset);
555   COPY_FIELD (constrained_intra_pred_flag);
556   COPY_FIELD (weighted_pred_flag);
557   COPY_FIELD (weighted_bipred_flag);
558   COPY_FIELD (transform_skip_enabled_flag);
559   COPY_FIELD (transquant_bypass_enabled_flag);
560   COPY_FIELD (entropy_coding_sync_enabled_flag);
561   COPY_FIELD (log2_parallel_merge_level_minus2);
562   COPY_FIELD (num_extra_slice_header_bits);
563   COPY_FIELD (loop_filter_across_tiles_enabled_flag);
564   COPY_FIELD (loop_filter_across_slices_enabled_flag);
565   COPY_FIELD (output_flag_present_flag);
566   COPY_FIELD (num_ref_idx_l0_default_active_minus1);
567   COPY_FIELD (num_ref_idx_l1_default_active_minus1);
568   COPY_FIELD (lists_modification_present_flag);
569   COPY_FIELD (cabac_init_present_flag);
570   COPY_FIELD_WITH_PREFIX (slice_chroma_qp_offsets_present_flag);
571   COPY_FIELD (deblocking_filter_override_enabled_flag);
572   COPY_FIELD_WITH_PREFIX (deblocking_filter_disabled_flag);
573   COPY_FIELD_WITH_PREFIX (beta_offset_div2);
574   COPY_FIELD_WITH_PREFIX (tc_offset_div2);
575   COPY_FIELD (tiles_enabled_flag);
576   COPY_FIELD (uniform_spacing_flag);
577
578   if (pps->tiles_enabled_flag) {
579     guint num_tile_columns;
580     guint num_tile_rows;
581
582     COPY_FIELD (num_tile_columns_minus1);
583     COPY_FIELD (num_tile_rows_minus1);
584
585     if (pps->num_tile_columns_minus1 >
586         G_N_ELEMENTS (params->column_width_minus1)) {
587       GST_ERROR_OBJECT (self,
588           "Too large column_width_minus1 %d", pps->num_tile_columns_minus1);
589       return FALSE;
590     }
591
592     if (pps->num_tile_rows_minus1 > G_N_ELEMENTS (params->row_height_minus1)) {
593       GST_ERROR_OBJECT (self,
594           "Too large num_tile_rows_minus1 %d", pps->num_tile_rows_minus1);
595       return FALSE;
596     }
597
598     /* XXX: The size of column_width_minus1 array in CUVIDHEVCPICPARAMS struct
599      * is 21 which is inconsistent with the spec.
600      * Just copy values as many as possible */
601     num_tile_columns = MIN (pps->num_tile_columns_minus1,
602         G_N_ELEMENTS (pps->column_width_minus1));
603     num_tile_rows = MIN (pps->num_tile_rows_minus1,
604         G_N_ELEMENTS (pps->row_height_minus1));
605
606     for (i = 0; i < num_tile_columns; i++)
607       COPY_FIELD (column_width_minus1[i]);
608
609     for (i = 0; i < num_tile_rows; i++)
610       COPY_FIELD (row_height_minus1[i]);
611   }
612
613   COPY_FIELD (pps_range_extension_flag);
614   if (pps->pps_range_extension_flag) {
615     COPY_FIELD_EXTENSION (cross_component_prediction_enabled_flag);
616     COPY_FIELD_EXTENSION (chroma_qp_offset_list_enabled_flag);
617     COPY_FIELD_EXTENSION (diff_cu_chroma_qp_offset_depth);
618     COPY_FIELD_EXTENSION (chroma_qp_offset_list_len_minus1);
619     for (i = 0; i < G_N_ELEMENTS (params->cb_qp_offset_list); i++)
620       COPY_FIELD_EXTENSION (cb_qp_offset_list[i]);
621     for (i = 0; i < G_N_ELEMENTS (params->cr_qp_offset_list); i++)
622       COPY_FIELD_EXTENSION (cr_qp_offset_list[i]);
623     COPY_FIELD_EXTENSION (log2_sao_offset_scale_luma);
624     COPY_FIELD_EXTENSION (log2_sao_offset_scale_chroma);
625   }
626 #undef COPY_FIELD
627 #undef COPY_FIELD_WITH_PREFIX
628 #undef COPY_FIELD_EXTENSION
629
630   return TRUE;
631 }
632
633 static void
634 gst_nv_h265_dec_reset_bitstream_params (GstNvH265Dec * self)
635 {
636   self->bitstream_buffer_offset = 0;
637   self->num_slices = 0;
638
639   self->params.nBitstreamDataLen = 0;
640   self->params.pBitstreamData = NULL;
641   self->params.nNumSlices = 0;
642   self->params.pSliceDataOffsets = NULL;
643 }
644
645 static gboolean
646 gst_nv_h265_dec_start_picture (GstH265Decoder * decoder,
647     GstH265Picture * picture, GstH265Slice * slice, GstH265Dpb * dpb)
648 {
649   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
650   CUVIDPICPARAMS *params = &self->params;
651   CUVIDHEVCPICPARAMS *h265_params = &params->CodecSpecific.hevc;
652   const GstH265SliceHdr *slice_header = &slice->header;
653   const GstH265SPS *sps;
654   const GstH265PPS *pps;
655   GstNvDecoderFrame *frame;
656   GArray *dpb_array;
657   gint num_ref_pic;
658   gint i, j;
659   const GstH265ScalingList *scaling_list = NULL;
660
661   /* both NVDEC and h265parser are using the same order */
662   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_4x4) ==
663       sizeof (h265_params->ScalingList4x4));
664   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_8x8) ==
665       sizeof (h265_params->ScalingList8x8));
666   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_16x16) ==
667       sizeof (h265_params->ScalingList16x16));
668   G_STATIC_ASSERT (sizeof (scaling_list->scaling_lists_32x32) ==
669       sizeof (h265_params->ScalingList32x32));
670
671   g_return_val_if_fail (slice_header->pps != NULL, FALSE);
672   g_return_val_if_fail (slice_header->pps->sps != NULL, FALSE);
673
674   frame = gst_nv_h265_dec_get_decoder_frame_from_picture (self, picture);
675
676   if (!frame) {
677     GST_ERROR_OBJECT (self,
678         "Couldn't get decoder frame frame picture %p", picture);
679     return FALSE;
680   }
681
682   gst_nv_h265_dec_reset_bitstream_params (self);
683
684   pps = slice_header->pps;
685   sps = pps->sps;
686
687   /* FIXME: update sps/pps related params only when it's required */
688   params->PicWidthInMbs = sps->pic_width_in_luma_samples / 16;
689   params->FrameHeightInMbs = sps->pic_height_in_luma_samples / 16;
690   params->CurrPicIdx = frame->index;
691
692   /* nBitstreamDataLen, pBitstreamData, nNumSlices and pSliceDataOffsets
693    * will be set later */
694   params->ref_pic_flag = picture->ref;
695   params->intra_pic_flag = GST_H265_IS_NAL_TYPE_IRAP (slice->nalu.type);
696
697   h265_params->IrapPicFlag = GST_H265_IS_NAL_TYPE_IRAP (slice->nalu.type);
698   h265_params->IdrPicFlag = GST_H265_IS_NAL_TYPE_IDR (slice->nalu.type);
699
700   if (!self->last_sps || self->last_sps != sps) {
701     GST_DEBUG_OBJECT (self, "Update params from SPS and PPS");
702     gst_nv_h265_dec_picture_params_from_sps (self, sps, h265_params);
703     if (!gst_nv_h265_dec_picture_params_from_pps (self, pps, h265_params)) {
704       GST_ERROR_OBJECT (self, "Couldn't copy pps");
705       return FALSE;
706     }
707     self->last_sps = sps;
708     self->last_pps = pps;
709   } else if (!self->last_pps || self->last_pps != pps) {
710     GST_DEBUG_OBJECT (self, "Update params from PPS");
711     if (!gst_nv_h265_dec_picture_params_from_pps (self, pps, h265_params)) {
712       GST_ERROR_OBJECT (self, "Couldn't copy pps");
713       return FALSE;
714     }
715     self->last_pps = pps;
716   } else {
717     GST_TRACE_OBJECT (self, "SPS and PPS were not updated");
718   }
719
720   /* Fill reference */
721   if (decoder->NumPocStCurrBefore >
722       G_N_ELEMENTS (h265_params->RefPicSetStCurrBefore)) {
723     GST_ERROR_OBJECT (self, "Too many RefPicSetStCurrBefore");
724     return FALSE;
725   }
726
727   if (decoder->NumPocStCurrAfter >
728       G_N_ELEMENTS (h265_params->RefPicSetStCurrAfter)) {
729     GST_ERROR_OBJECT (self, "Too many RefPicSetStCurrAfter");
730     return FALSE;
731   }
732
733   if (decoder->NumPocLtCurr > G_N_ELEMENTS (h265_params->RefPicSetLtCurr)) {
734     GST_ERROR_OBJECT (self, "Too many RefPicSetLtCurr");
735     return FALSE;
736   }
737
738   /* Fill ref list */
739   h265_params->NumBitsForShortTermRPSInSlice =
740       slice_header->short_term_ref_pic_set_size;
741   h265_params->NumDeltaPocsOfRefRpsIdx =
742       slice_header->short_term_ref_pic_sets.NumDeltaPocsOfRefRpsIdx;
743   h265_params->NumPocTotalCurr = decoder->NumPicTotalCurr;
744   h265_params->NumPocStCurrBefore = decoder->NumPocStCurrBefore;
745   h265_params->NumPocStCurrAfter = decoder->NumPocStCurrAfter;
746   h265_params->NumPocLtCurr = decoder->NumPocLtCurr;
747   h265_params->CurrPicOrderCntVal = picture->pic_order_cnt;
748
749   dpb_array = gst_h265_dpb_get_pictures_all (dpb);
750   /* count only referenced frame */
751   num_ref_pic = 0;
752   for (i = 0; i < dpb_array->len; i++) {
753     GstH265Picture *other = g_array_index (dpb_array, GstH265Picture *, i);
754     GstNvDecoderFrame *other_frame;
755     gint picture_index = -1;
756
757     if (!other->ref)
758       continue;
759
760     if (num_ref_pic >= G_N_ELEMENTS (h265_params->RefPicIdx)) {
761       GST_ERROR_OBJECT (self, "Too many reference frames");
762       return FALSE;
763     }
764
765     other_frame = gst_nv_h265_dec_get_decoder_frame_from_picture (self, other);
766
767     if (other_frame)
768       picture_index = other_frame->index;
769
770     h265_params->RefPicIdx[num_ref_pic] = picture_index;
771     h265_params->PicOrderCntVal[num_ref_pic] = other->pic_order_cnt;
772     h265_params->IsLongTerm[num_ref_pic] = other->long_term;
773
774     num_ref_pic++;
775   }
776
777   g_array_unref (dpb_array);
778
779   for (i = num_ref_pic; i < G_N_ELEMENTS (h265_params->RefPicIdx); i++)
780     h265_params->RefPicIdx[i] = -1;
781
782   for (i = 0; i < decoder->NumPocStCurrBefore; i++) {
783     GstH265Picture *other;
784
785     if (!decoder->RefPicSetStCurrBefore[i]) {
786       GST_ERROR_OBJECT (self, "Empty RefPicSetStCurrBefore[%d]", i);
787       return FALSE;
788     }
789
790     other = decoder->RefPicSetStCurrBefore[i];
791
792     for (j = 0; j < num_ref_pic; j++) {
793       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
794         h265_params->RefPicSetStCurrBefore[i] = j;
795         break;
796       }
797     }
798   }
799
800   for (i = 0; i < decoder->NumPocStCurrAfter; i++) {
801     GstH265Picture *other;
802
803     if (!decoder->RefPicSetStCurrAfter[i]) {
804       GST_ERROR_OBJECT (self, "Empty RefPicSetStCurrAfter[%d]", i);
805       return FALSE;
806     }
807
808     other = decoder->RefPicSetStCurrAfter[i];
809
810     for (j = 0; j < num_ref_pic; j++) {
811       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
812         h265_params->RefPicSetStCurrAfter[i] = j;
813         break;
814       }
815     }
816   }
817
818   for (i = 0; i < decoder->NumPocLtCurr; i++) {
819     GstH265Picture *other;
820
821     if (!decoder->RefPicSetLtCurr[i]) {
822       GST_ERROR_OBJECT (self, "Empty RefPicSetLtCurr[%d]", i);
823       return FALSE;
824     }
825
826     other = decoder->RefPicSetLtCurr[i];
827
828     for (j = 0; j < num_ref_pic; j++) {
829       if (h265_params->PicOrderCntVal[j] == other->pic_order_cnt) {
830         h265_params->RefPicSetLtCurr[i] = j;
831         break;
832       }
833     }
834   }
835
836   /* Fill scaling list */
837   if (pps->scaling_list_data_present_flag ||
838       (sps->scaling_list_enabled_flag
839           && !sps->scaling_list_data_present_flag)) {
840     scaling_list = &pps->scaling_list;
841   } else {
842     scaling_list = &sps->scaling_list;
843   }
844
845   memcpy (h265_params->ScalingList4x4, scaling_list->scaling_lists_4x4,
846       sizeof (scaling_list->scaling_lists_4x4));
847   memcpy (h265_params->ScalingList8x8, scaling_list->scaling_lists_8x8,
848       sizeof (scaling_list->scaling_lists_8x8));
849   memcpy (h265_params->ScalingList16x16, scaling_list->scaling_lists_16x16,
850       sizeof (scaling_list->scaling_lists_16x16));
851   memcpy (h265_params->ScalingList32x32, scaling_list->scaling_lists_32x32,
852       sizeof (scaling_list->scaling_lists_32x32));
853
854   for (i = 0; i < G_N_ELEMENTS (h265_params->ScalingListDCCoeff16x16); i++) {
855     h265_params->ScalingListDCCoeff16x16[i] =
856         scaling_list->scaling_list_dc_coef_minus8_16x16[i] + 8;
857   }
858
859   for (i = 0; i < G_N_ELEMENTS (h265_params->ScalingListDCCoeff32x32); i++) {
860     h265_params->ScalingListDCCoeff32x32[i] =
861         scaling_list->scaling_list_dc_coef_minus8_32x32[i] + 8;
862   }
863
864   return TRUE;
865 }
866
867 static gboolean
868 gst_nv_h265_dec_decode_slice (GstH265Decoder * decoder,
869     GstH265Picture * picture, GstH265Slice * slice,
870     GArray * ref_pic_list0, GArray * ref_pic_list1)
871 {
872   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
873   gsize new_size;
874
875   GST_LOG_OBJECT (self, "Decode slice, nalu size %u", slice->nalu.size);
876
877   if (self->slice_offsets_alloc_len < self->num_slices + 1) {
878     self->slice_offsets = (guint *) g_realloc_n (self->slice_offsets,
879         self->num_slices + 1, sizeof (guint));
880   }
881   self->slice_offsets[self->num_slices] = self->bitstream_buffer_offset;
882   GST_LOG_OBJECT (self, "Slice offset %u for slice %d",
883       self->slice_offsets[self->num_slices], self->num_slices);
884
885   self->num_slices++;
886
887   new_size = self->bitstream_buffer_offset + slice->nalu.size + 3;
888   if (self->bitstream_buffer_alloc_size < new_size) {
889     self->bitstream_buffer =
890         (guint8 *) g_realloc (self->bitstream_buffer, new_size);
891   }
892
893   self->bitstream_buffer[self->bitstream_buffer_offset] = 0;
894   self->bitstream_buffer[self->bitstream_buffer_offset + 1] = 0;
895   self->bitstream_buffer[self->bitstream_buffer_offset + 2] = 1;
896
897   memcpy (self->bitstream_buffer + self->bitstream_buffer_offset + 3,
898       slice->nalu.data + slice->nalu.offset, slice->nalu.size);
899   self->bitstream_buffer_offset = new_size;
900
901   return TRUE;
902 }
903
904 static gboolean
905 gst_nv_h265_dec_end_picture (GstH265Decoder * decoder, GstH265Picture * picture)
906 {
907   GstNvH265Dec *self = GST_NV_H265_DEC (decoder);
908   gboolean ret;
909   CUVIDPICPARAMS *params = &self->params;
910
911   params->nBitstreamDataLen = self->bitstream_buffer_offset;
912   params->pBitstreamData = self->bitstream_buffer;
913   params->nNumSlices = self->num_slices;
914   params->pSliceDataOffsets = self->slice_offsets;
915
916   GST_LOG_OBJECT (self, "End picture, bitstream len: %" G_GSIZE_FORMAT
917       ", num slices %d", self->bitstream_buffer_offset, self->num_slices);
918
919   ret = gst_nv_decoder_decode_picture (self->decoder, &self->params);
920
921   if (!ret)
922     GST_ERROR_OBJECT (self, "Failed to decode picture");
923
924   return ret;
925 }
926
927 typedef struct
928 {
929   GstCaps *sink_caps;
930   GstCaps *src_caps;
931   guint cuda_device_id;
932   gboolean is_default;
933 } GstNvH265DecClassData;
934
935 static void
936 gst_nv_h265_dec_subclass_init (gpointer klass, GstNvH265DecClassData * cdata)
937 {
938   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
939   GstNvH265DecClass *nvdec_class = (GstNvH265DecClass *) (klass);
940   gchar *long_name;
941
942   if (cdata->is_default) {
943     long_name = g_strdup_printf ("NVDEC H.265 Stateless Decoder");
944   } else {
945     long_name = g_strdup_printf ("NVDEC H.265 Stateless Decoder with device %d",
946         cdata->cuda_device_id);
947   }
948
949   gst_element_class_set_metadata (element_class, long_name,
950       "Codec/Decoder/Video/Hardware",
951       "Nvidia H.265 video decoder", "Seungha Yang <seungha@centricular.com>");
952   g_free (long_name);
953
954   gst_element_class_add_pad_template (element_class,
955       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
956           cdata->sink_caps));
957   gst_element_class_add_pad_template (element_class,
958       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
959           cdata->src_caps));
960
961   nvdec_class->cuda_device_id = cdata->cuda_device_id;
962
963   gst_caps_unref (cdata->sink_caps);
964   gst_caps_unref (cdata->src_caps);
965   g_free (cdata);
966 }
967
968 void
969 gst_nv_h265_dec_register (GstPlugin * plugin, guint device_id, guint rank,
970     GstCaps * sink_caps, GstCaps * src_caps, gboolean is_primary)
971 {
972   GTypeQuery type_query;
973   GTypeInfo type_info = { 0, };
974   GType subtype;
975   gchar *type_name;
976   gchar *feature_name;
977   GstNvH265DecClassData *cdata;
978   gboolean is_default = TRUE;
979   GValue value_list = G_VALUE_INIT;
980   GValue value = G_VALUE_INIT;
981
982   /**
983    * element-nvh265sldec
984    *
985    * Since: 1.18
986    */
987
988   cdata = g_new0 (GstNvH265DecClassData, 1);
989   cdata->sink_caps = gst_caps_copy (sink_caps);
990
991   /* Update stream-format since we support packetized format as well */
992   g_value_init (&value_list, GST_TYPE_LIST);
993   g_value_init (&value, G_TYPE_STRING);
994
995   g_value_set_static_string (&value, "hev1");
996   gst_value_list_append_value (&value_list, &value);
997
998   g_value_set_static_string (&value, "hvc1");
999   gst_value_list_append_value (&value_list, &value);
1000
1001   g_value_set_static_string (&value, "byte-stream");
1002   gst_value_list_append_value (&value_list, &value);
1003
1004   gst_caps_set_value (cdata->sink_caps, "stream-format", &value_list);
1005   g_value_unset (&value);
1006   g_value_unset (&value_list);
1007
1008   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
1009       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
1010   cdata->src_caps = gst_caps_ref (src_caps);
1011   cdata->cuda_device_id = device_id;
1012
1013   g_type_query (GST_TYPE_NV_H265_DEC, &type_query);
1014   memset (&type_info, 0, sizeof (type_info));
1015   type_info.class_size = type_query.class_size;
1016   type_info.instance_size = type_query.instance_size;
1017   type_info.class_init = (GClassInitFunc) gst_nv_h265_dec_subclass_init;
1018   type_info.class_data = cdata;
1019
1020   if (is_primary) {
1021     type_name = g_strdup ("GstNvH265StatelessPrimaryDec");
1022     feature_name = g_strdup ("nvh265dec");
1023   } else {
1024     type_name = g_strdup ("GstNvH265StatelessDec");
1025     feature_name = g_strdup ("nvh265sldec");
1026   }
1027
1028   if (g_type_from_name (type_name) != 0) {
1029     g_free (type_name);
1030     g_free (feature_name);
1031     if (is_primary) {
1032       type_name =
1033           g_strdup_printf ("GstNvH265StatelessPrimaryDevice%dDec", device_id);
1034       feature_name = g_strdup_printf ("nvh265device%ddec", device_id);
1035     } else {
1036       type_name = g_strdup_printf ("GstNvH265StatelessDevice%dDec", device_id);
1037       feature_name = g_strdup_printf ("nvh265sldevice%ddec", device_id);
1038     }
1039
1040     is_default = FALSE;
1041   }
1042
1043   cdata->is_default = is_default;
1044   subtype = g_type_register_static (GST_TYPE_NV_H265_DEC,
1045       type_name, &type_info, 0);
1046
1047   /* make lower rank than default device */
1048   if (rank > 0 && !is_default)
1049     rank--;
1050
1051   if (!gst_element_register (plugin, feature_name, rank, subtype))
1052     GST_WARNING ("Failed to register plugin '%s'", type_name);
1053
1054   g_free (type_name);
1055   g_free (feature_name);
1056 }