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