nvdecoder: Fix for HEVC 4:4:4 format decoding
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / nvcodec / gstnvh264dec.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 "gstnvh264dec.h"
78 #include "gstcudautils.h"
79 #include "gstnvdecoder.h"
80
81 #include <string.h>
82
83 GST_DEBUG_CATEGORY_STATIC (gst_nv_h264_dec_debug);
84 #define GST_CAT_DEFAULT gst_nv_h264_dec_debug
85
86 struct _GstNvH264Dec
87 {
88   GstH264Decoder parent;
89
90   GstVideoCodecState *output_state;
91
92   GstCudaContext *context;
93   GstNvDecoder *decoder;
94   CUVIDPICPARAMS params;
95
96   /* slice buffer which will be passed to CUVIDPICPARAMS::pBitstreamData */
97   guint8 *bitstream_buffer;
98   /* allocated memory size of bitstream_buffer */
99   gsize bitstream_buffer_alloc_size;
100   /* current offset of bitstream_buffer (per frame) */
101   gsize bitstream_buffer_offset;
102
103   guint *slice_offsets;
104   guint slice_offsets_alloc_len;
105   guint num_slices;
106
107   guint width, height;
108   guint coded_width, coded_height;
109   guint bitdepth;
110   guint chroma_format_idc;
111   gint max_dpb_size;
112
113   gboolean interlaced;
114
115   GArray *ref_list;
116 };
117
118 struct _GstNvH264DecClass
119 {
120   GstH264DecoderClass parent_class;
121   guint cuda_device_id;
122 };
123
124 #define gst_nv_h264_dec_parent_class parent_class
125 G_DEFINE_TYPE (GstNvH264Dec, gst_nv_h264_dec, GST_TYPE_H264_DECODER);
126
127 static void gst_nv_h264_decoder_dispose (GObject * object);
128 static void gst_nv_h264_decoder_finalize (GObject * object);
129 static void gst_nv_h264_dec_set_context (GstElement * element,
130     GstContext * context);
131 static gboolean gst_nv_h264_dec_open (GstVideoDecoder * decoder);
132 static gboolean gst_nv_h264_dec_close (GstVideoDecoder * decoder);
133 static gboolean gst_nv_h264_dec_negotiate (GstVideoDecoder * decoder);
134 static gboolean gst_nv_h264_dec_decide_allocation (GstVideoDecoder *
135     decoder, GstQuery * query);
136 static gboolean gst_nv_h264_dec_src_query (GstVideoDecoder * decoder,
137     GstQuery * query);
138
139 /* GstH264Decoder */
140 static GstFlowReturn gst_nv_h264_dec_new_sequence (GstH264Decoder * decoder,
141     const GstH264SPS * sps, gint max_dpb_size);
142 static GstFlowReturn gst_nv_h264_dec_new_picture (GstH264Decoder * decoder,
143     GstVideoCodecFrame * frame, GstH264Picture * picture);
144 static GstFlowReturn
145 gst_nv_h264_dec_new_field_picture (GstH264Decoder * decoder,
146     GstH264Picture * first_field, GstH264Picture * second_field);
147 static GstFlowReturn gst_nv_h264_dec_output_picture (GstH264Decoder *
148     decoder, GstVideoCodecFrame * frame, GstH264Picture * picture);
149 static GstFlowReturn gst_nv_h264_dec_start_picture (GstH264Decoder * decoder,
150     GstH264Picture * picture, GstH264Slice * slice, GstH264Dpb * dpb);
151 static GstFlowReturn gst_nv_h264_dec_decode_slice (GstH264Decoder * decoder,
152     GstH264Picture * picture, GstH264Slice * slice, GArray * ref_pic_list0,
153     GArray * ref_pic_list1);
154 static GstFlowReturn gst_nv_h264_dec_end_picture (GstH264Decoder * decoder,
155     GstH264Picture * picture);
156 static guint
157 gst_nv_h264_dec_get_preferred_output_delay (GstH264Decoder * decoder,
158     gboolean live);
159
160 static void
161 gst_nv_h264_dec_class_init (GstNvH264DecClass * klass)
162 {
163   GObjectClass *object_class = G_OBJECT_CLASS (klass);
164   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
165   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_CLASS (klass);
166   GstH264DecoderClass *h264decoder_class = GST_H264_DECODER_CLASS (klass);
167
168   /**
169    * GstNvH264Dec
170    *
171    * Since: 1.18
172    */
173
174   object_class->dispose = gst_nv_h264_decoder_dispose;
175   object_class->finalize = gst_nv_h264_decoder_finalize;
176
177   element_class->set_context = GST_DEBUG_FUNCPTR (gst_nv_h264_dec_set_context);
178
179   decoder_class->open = GST_DEBUG_FUNCPTR (gst_nv_h264_dec_open);
180   decoder_class->close = GST_DEBUG_FUNCPTR (gst_nv_h264_dec_close);
181   decoder_class->negotiate = GST_DEBUG_FUNCPTR (gst_nv_h264_dec_negotiate);
182   decoder_class->decide_allocation =
183       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_decide_allocation);
184   decoder_class->src_query = GST_DEBUG_FUNCPTR (gst_nv_h264_dec_src_query);
185
186   h264decoder_class->new_sequence =
187       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_new_sequence);
188   h264decoder_class->new_picture =
189       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_new_picture);
190   h264decoder_class->new_field_picture =
191       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_new_field_picture);
192   h264decoder_class->output_picture =
193       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_output_picture);
194   h264decoder_class->start_picture =
195       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_start_picture);
196   h264decoder_class->decode_slice =
197       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_decode_slice);
198   h264decoder_class->end_picture =
199       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_end_picture);
200   h264decoder_class->get_preferred_output_delay =
201       GST_DEBUG_FUNCPTR (gst_nv_h264_dec_get_preferred_output_delay);
202
203   GST_DEBUG_CATEGORY_INIT (gst_nv_h264_dec_debug,
204       "nvh264dec", 0, "Nvidia H.264 Decoder");
205
206   gst_type_mark_as_plugin_api (GST_TYPE_NV_H264_DEC, 0);
207 }
208
209 static void
210 gst_nv_h264_dec_init (GstNvH264Dec * self)
211 {
212   self->ref_list = g_array_sized_new (FALSE, TRUE,
213       sizeof (GstH264Picture *), 16);
214   g_array_set_clear_func (self->ref_list,
215       (GDestroyNotify) gst_h264_picture_clear);
216 }
217
218 static void
219 gst_nv_h264_decoder_dispose (GObject * object)
220 {
221   GstNvH264Dec *self = GST_NV_H264_DEC (object);
222
223   g_clear_pointer (&self->ref_list, g_array_unref);
224
225   G_OBJECT_CLASS (parent_class)->dispose (object);
226 }
227
228 static void
229 gst_nv_h264_decoder_finalize (GObject * object)
230 {
231   GstNvH264Dec *self = GST_NV_H264_DEC (object);
232
233   g_free (self->bitstream_buffer);
234   g_free (self->slice_offsets);
235
236   G_OBJECT_CLASS (parent_class)->finalize (object);
237 }
238
239 static void
240 gst_nv_h264_dec_set_context (GstElement * element, GstContext * context)
241 {
242   GstNvH264Dec *self = GST_NV_H264_DEC (element);
243   GstNvH264DecClass *klass = GST_NV_H264_DEC_GET_CLASS (self);
244
245   GST_DEBUG_OBJECT (self, "set context %s",
246       gst_context_get_context_type (context));
247
248   if (gst_cuda_handle_set_context (element, context, klass->cuda_device_id,
249           &self->context)) {
250     goto done;
251   }
252
253   if (self->decoder)
254     gst_nv_decoder_handle_set_context (self->decoder, element, context);
255
256 done:
257   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
258 }
259
260 /* Clear all codec specific (e.g., SPS) data */
261 static void
262 gst_d3d11_h264_dec_reset (GstNvH264Dec * self)
263 {
264   self->width = 0;
265   self->height = 0;
266   self->coded_width = 0;
267   self->coded_height = 0;
268   self->bitdepth = 0;
269   self->chroma_format_idc = 0;
270   self->max_dpb_size = 0;
271   self->interlaced = FALSE;
272 }
273
274 static gboolean
275 gst_nv_h264_dec_open (GstVideoDecoder * decoder)
276 {
277   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
278   GstNvH264DecClass *klass = GST_NV_H264_DEC_GET_CLASS (self);
279
280   if (!gst_cuda_ensure_element_context (GST_ELEMENT (self),
281           klass->cuda_device_id, &self->context)) {
282     GST_ERROR_OBJECT (self, "Required element data is unavailable");
283     return FALSE;
284   }
285
286   self->decoder = gst_nv_decoder_new (self->context);
287   if (!self->decoder) {
288     GST_ERROR_OBJECT (self, "Failed to create decoder object");
289     gst_clear_object (&self->context);
290
291     return FALSE;
292   }
293
294   gst_d3d11_h264_dec_reset (self);
295
296   return TRUE;
297 }
298
299 static gboolean
300 gst_nv_h264_dec_close (GstVideoDecoder * decoder)
301 {
302   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
303
304   g_clear_pointer (&self->output_state, gst_video_codec_state_unref);
305   gst_clear_object (&self->decoder);
306   gst_clear_object (&self->context);
307
308   return TRUE;
309 }
310
311 static gboolean
312 gst_nv_h264_dec_negotiate (GstVideoDecoder * decoder)
313 {
314   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
315   GstH264Decoder *h264dec = GST_H264_DECODER (decoder);
316
317   GST_DEBUG_OBJECT (self, "negotiate");
318
319   gst_nv_decoder_negotiate (self->decoder, decoder, h264dec->input_state,
320       &self->output_state);
321
322   /* TODO: add support D3D11 memory */
323
324   return GST_VIDEO_DECODER_CLASS (parent_class)->negotiate (decoder);
325 }
326
327 static gboolean
328 gst_nv_h264_dec_decide_allocation (GstVideoDecoder * decoder, GstQuery * query)
329 {
330   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
331
332   if (!gst_nv_decoder_decide_allocation (self->decoder, decoder, query)) {
333     GST_WARNING_OBJECT (self, "Failed to handle decide allocation");
334     return FALSE;
335   }
336
337   return GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation
338       (decoder, query);
339 }
340
341 static gboolean
342 gst_nv_h264_dec_src_query (GstVideoDecoder * decoder, GstQuery * query)
343 {
344   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
345
346   switch (GST_QUERY_TYPE (query)) {
347     case GST_QUERY_CONTEXT:
348       if (gst_cuda_handle_context_query (GST_ELEMENT (decoder), query,
349               self->context)) {
350         return TRUE;
351       } else if (self->decoder &&
352           gst_nv_decoder_handle_context_query (self->decoder, decoder, query)) {
353         return TRUE;
354       }
355       break;
356     default:
357       break;
358   }
359
360   return GST_VIDEO_DECODER_CLASS (parent_class)->src_query (decoder, query);
361 }
362
363 static GstFlowReturn
364 gst_nv_h264_dec_new_sequence (GstH264Decoder * decoder, const GstH264SPS * sps,
365     gint max_dpb_size)
366 {
367   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
368   gint crop_width, crop_height;
369   gboolean modified = FALSE;
370   gboolean interlaced;
371
372   GST_LOG_OBJECT (self, "new sequence");
373
374   if (sps->frame_cropping_flag) {
375     crop_width = sps->crop_rect_width;
376     crop_height = sps->crop_rect_height;
377   } else {
378     crop_width = sps->width;
379     crop_height = sps->height;
380   }
381
382   if (self->width != crop_width || self->height != crop_height ||
383       self->coded_width != sps->width || self->coded_height != sps->height) {
384     GST_INFO_OBJECT (self, "resolution changed %dx%d (%dx%d)",
385         crop_width, crop_height, sps->width, sps->height);
386     self->width = crop_width;
387     self->height = crop_height;
388     self->coded_width = sps->width;
389     self->coded_height = sps->height;
390     modified = TRUE;
391   }
392
393   if (self->bitdepth != sps->bit_depth_luma_minus8 + 8) {
394     GST_INFO_OBJECT (self, "bitdepth changed");
395     self->bitdepth = sps->bit_depth_luma_minus8 + 8;
396     modified = TRUE;
397   }
398
399   if (self->chroma_format_idc != sps->chroma_format_idc) {
400     GST_INFO_OBJECT (self, "chroma format changed");
401     self->chroma_format_idc = sps->chroma_format_idc;
402     modified = TRUE;
403   }
404
405   interlaced = !sps->frame_mbs_only_flag;
406   if (self->interlaced != interlaced) {
407     GST_INFO_OBJECT (self, "interlaced sequence changed");
408     self->interlaced = interlaced;
409     modified = TRUE;
410   }
411
412   if (self->max_dpb_size < max_dpb_size) {
413     GST_INFO_OBJECT (self, "Requires larger DPB size (%d -> %d)",
414         self->max_dpb_size, max_dpb_size);
415     modified = TRUE;
416   }
417
418   if (modified || !gst_nv_decoder_is_configured (self->decoder)) {
419     GstVideoInfo info;
420     GstVideoFormat out_format = GST_VIDEO_FORMAT_UNKNOWN;
421
422     if (self->bitdepth == 8) {
423       if (self->chroma_format_idc == 1)
424         out_format = GST_VIDEO_FORMAT_NV12;
425       else {
426         GST_FIXME_OBJECT (self, "Could not support 8bits non-4:2:0 format");
427       }
428     } else if (self->bitdepth == 10) {
429       if (self->chroma_format_idc == 1)
430         out_format = GST_VIDEO_FORMAT_P010_10LE;
431       else {
432         GST_FIXME_OBJECT (self, "Could not support 10bits non-4:2:0 format");
433       }
434     }
435
436     if (out_format == GST_VIDEO_FORMAT_UNKNOWN) {
437       GST_ERROR_OBJECT (self, "Could not support bitdepth/chroma format");
438       return GST_FLOW_NOT_NEGOTIATED;
439     }
440
441     gst_video_info_set_format (&info, out_format, self->width, self->height);
442     if (self->interlaced)
443       GST_VIDEO_INFO_INTERLACE_MODE (&info) = GST_VIDEO_INTERLACE_MODE_MIXED;
444
445     self->max_dpb_size = max_dpb_size;
446     /* FIXME: add support cudaVideoCodec_H264_SVC and cudaVideoCodec_H264_MVC */
447     if (!gst_nv_decoder_configure (self->decoder,
448             cudaVideoCodec_H264, &info, self->coded_width, self->coded_height,
449             self->bitdepth,
450             /* Additional 4 buffers for render delay */
451             max_dpb_size + 4)) {
452       GST_ERROR_OBJECT (self, "Failed to configure decoder");
453       return GST_FLOW_NOT_NEGOTIATED;
454     }
455
456     if (!gst_video_decoder_negotiate (GST_VIDEO_DECODER (self))) {
457       GST_ERROR_OBJECT (self, "Failed to negotiate with downstream");
458       return GST_FLOW_NOT_NEGOTIATED;
459     }
460
461     memset (&self->params, 0, sizeof (CUVIDPICPARAMS));
462   }
463
464   return GST_FLOW_OK;
465 }
466
467 static GstFlowReturn
468 gst_nv_h264_dec_new_picture (GstH264Decoder * decoder,
469     GstVideoCodecFrame * frame, GstH264Picture * picture)
470 {
471   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
472   GstNvDecoderFrame *nv_frame;
473
474   nv_frame = gst_nv_decoder_new_frame (self->decoder);
475   if (!nv_frame) {
476     GST_ERROR_OBJECT (self, "No available decoder frame");
477     return GST_FLOW_ERROR;
478   }
479
480   GST_LOG_OBJECT (self,
481       "New decoder frame %p (index %d)", nv_frame, nv_frame->index);
482
483   gst_h264_picture_set_user_data (picture,
484       nv_frame, (GDestroyNotify) gst_nv_decoder_frame_unref);
485
486   return GST_FLOW_OK;
487 }
488
489 static GstFlowReturn
490 gst_nv_h264_dec_new_field_picture (GstH264Decoder * decoder,
491     GstH264Picture * first_field, GstH264Picture * second_field)
492 {
493   GstNvDecoderFrame *nv_frame;
494
495   nv_frame = (GstNvDecoderFrame *)
496       gst_h264_picture_get_user_data (first_field);
497   if (!nv_frame) {
498     GST_ERROR_OBJECT (decoder,
499         "No decoder frame in the first picture %p", first_field);
500     return GST_FLOW_ERROR;
501   }
502
503   gst_h264_picture_set_user_data (second_field,
504       gst_nv_decoder_frame_ref (nv_frame),
505       (GDestroyNotify) gst_nv_decoder_frame_unref);
506
507   return GST_FLOW_OK;
508 }
509
510 static GstFlowReturn
511 gst_nv_h264_dec_output_picture (GstH264Decoder * decoder,
512     GstVideoCodecFrame * frame, GstH264Picture * picture)
513 {
514   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
515   GstVideoDecoder *vdec = GST_VIDEO_DECODER (decoder);
516   GstNvDecoderFrame *decoder_frame;
517
518   GST_LOG_OBJECT (self,
519       "Outputting picture %p (poc %d)", picture, picture->pic_order_cnt);
520
521   decoder_frame =
522       (GstNvDecoderFrame *) gst_h264_picture_get_user_data (picture);
523   if (!decoder_frame) {
524     GST_ERROR_OBJECT (self, "No decoder frame in picture %p", picture);
525     goto error;
526   }
527
528   if (!gst_nv_decoder_finish_frame (self->decoder, vdec, decoder_frame,
529           &frame->output_buffer)) {
530     GST_ERROR_OBJECT (self, "Failed to handle output picture");
531     goto error;
532   }
533
534   if (picture->buffer_flags != 0) {
535     gboolean interlaced =
536         (picture->buffer_flags & GST_VIDEO_BUFFER_FLAG_INTERLACED) != 0;
537     gboolean tff = (picture->buffer_flags & GST_VIDEO_BUFFER_FLAG_TFF) != 0;
538
539     GST_TRACE_OBJECT (self,
540         "apply buffer flags 0x%x (interlaced %d, top-field-first %d)",
541         picture->buffer_flags, interlaced, tff);
542     GST_BUFFER_FLAG_SET (frame->output_buffer, picture->buffer_flags);
543   }
544
545   gst_h264_picture_unref (picture);
546
547   return gst_video_decoder_finish_frame (vdec, frame);
548
549 error:
550   gst_h264_picture_unref (picture);
551   gst_video_decoder_release_frame (vdec, frame);
552
553   return GST_FLOW_ERROR;
554 }
555
556 static GstNvDecoderFrame *
557 gst_nv_h264_dec_get_decoder_frame_from_picture (GstNvH264Dec * self,
558     GstH264Picture * picture)
559 {
560   GstNvDecoderFrame *frame;
561
562   frame = (GstNvDecoderFrame *) gst_h264_picture_get_user_data (picture);
563
564   if (!frame)
565     GST_DEBUG_OBJECT (self, "current picture does not have decoder frame");
566
567   return frame;
568 }
569
570 static void
571 gst_nv_h264_dec_fill_scaling_list_4x4 (const GstH264PPS * pps,
572     CUVIDH264PICPARAMS * params)
573 {
574   guint i;
575
576   for (i = 0; i < G_N_ELEMENTS (params->WeightScale4x4); i++)
577     gst_h264_quant_matrix_4x4_get_raster_from_zigzag (params->WeightScale4x4[i],
578         pps->scaling_lists_4x4[i]);
579 }
580
581 static void
582 gst_nv_h264_dec_fill_scaling_list_8x8 (const GstH264PPS * pps,
583     CUVIDH264PICPARAMS * params)
584 {
585   guint i;
586
587   for (i = 0; i < G_N_ELEMENTS (params->WeightScale8x8); i++) {
588     gst_h264_quant_matrix_8x8_get_raster_from_zigzag (params->WeightScale8x8[i],
589         pps->scaling_lists_8x8[i]);
590   }
591 }
592
593 static void
594 gst_nv_h264_dec_picture_params_from_sps (GstNvH264Dec * self,
595     const GstH264SPS * sps, gboolean field_pic, CUVIDH264PICPARAMS * params)
596 {
597   params->residual_colour_transform_flag = sps->separate_colour_plane_flag;
598   params->MbaffFrameFlag = sps->mb_adaptive_frame_field_flag && !field_pic;
599
600 #define COPY_FIELD(f) \
601   (params)->f = (sps)->f
602
603   COPY_FIELD (log2_max_frame_num_minus4);
604   COPY_FIELD (pic_order_cnt_type);
605   COPY_FIELD (log2_max_pic_order_cnt_lsb_minus4);
606   COPY_FIELD (delta_pic_order_always_zero_flag);
607   COPY_FIELD (frame_mbs_only_flag);
608   COPY_FIELD (direct_8x8_inference_flag);
609   COPY_FIELD (num_ref_frames);
610   COPY_FIELD (bit_depth_luma_minus8);
611   COPY_FIELD (bit_depth_chroma_minus8);
612   COPY_FIELD (qpprime_y_zero_transform_bypass_flag);
613
614 #undef COPY_FIELD
615 }
616
617 static void
618 gst_nv_h264_dec_picture_params_from_pps (GstNvH264Dec * self,
619     const GstH264PPS * pps, CUVIDH264PICPARAMS * params)
620 {
621   params->second_chroma_qp_index_offset =
622       (gint8) pps->second_chroma_qp_index_offset;
623
624 #define COPY_FIELD(f) \
625   (params)->f = (pps)->f
626
627   COPY_FIELD (entropy_coding_mode_flag);
628   COPY_FIELD (pic_order_present_flag);
629   COPY_FIELD (num_ref_idx_l0_active_minus1);
630   COPY_FIELD (num_ref_idx_l1_active_minus1);
631   COPY_FIELD (pic_init_qp_minus26);
632   COPY_FIELD (weighted_pred_flag);
633   COPY_FIELD (weighted_bipred_idc);
634   COPY_FIELD (pic_init_qp_minus26);
635   COPY_FIELD (deblocking_filter_control_present_flag);
636   COPY_FIELD (redundant_pic_cnt_present_flag);
637   COPY_FIELD (transform_8x8_mode_flag);
638   COPY_FIELD (constrained_intra_pred_flag);
639   COPY_FIELD (chroma_qp_index_offset);
640 #undef COPY_FIELD
641
642   gst_nv_h264_dec_fill_scaling_list_4x4 (pps, params);
643   gst_nv_h264_dec_fill_scaling_list_8x8 (pps, params);
644 }
645
646 static void
647 gst_nv_h264_dec_reset_bitstream_params (GstNvH264Dec * self)
648 {
649   self->bitstream_buffer_offset = 0;
650   self->num_slices = 0;
651
652   self->params.nBitstreamDataLen = 0;
653   self->params.pBitstreamData = NULL;
654   self->params.nNumSlices = 0;
655   self->params.pSliceDataOffsets = NULL;
656 }
657
658 static void
659 gst_nv_h264_dec_fill_dpb (GstNvH264Dec * self, GstH264Picture * ref,
660     CUVIDH264DPBENTRY * dpb)
661 {
662   GstNvDecoderFrame *frame;
663
664   dpb->not_existing = ref->nonexisting;
665   dpb->PicIdx = -1;
666
667   frame = gst_nv_h264_dec_get_decoder_frame_from_picture (self, ref);
668   if (!frame) {
669     dpb->not_existing = 1;
670   } else if (!dpb->not_existing) {
671     dpb->PicIdx = frame->index;
672   }
673
674   if (dpb->not_existing)
675     return;
676
677   if (GST_H264_PICTURE_IS_LONG_TERM_REF (ref)) {
678     dpb->FrameIdx = ref->long_term_frame_idx;
679     dpb->is_long_term = 1;
680   } else {
681     dpb->FrameIdx = ref->frame_num;
682     dpb->is_long_term = 0;
683   }
684
685   switch (ref->field) {
686     case GST_H264_PICTURE_FIELD_FRAME:
687       dpb->FieldOrderCnt[0] = ref->top_field_order_cnt;
688       dpb->FieldOrderCnt[1] = ref->bottom_field_order_cnt;
689       dpb->used_for_reference = 0x3;
690       break;
691     case GST_H264_PICTURE_FIELD_TOP_FIELD:
692       dpb->FieldOrderCnt[0] = ref->top_field_order_cnt;
693       dpb->used_for_reference = 0x1;
694       if (ref->other_field) {
695         dpb->FieldOrderCnt[1] = ref->other_field->bottom_field_order_cnt;
696         dpb->used_for_reference |= 0x2;
697       } else {
698         dpb->FieldOrderCnt[1] = 0;
699       }
700       break;
701     case GST_H264_PICTURE_FIELD_BOTTOM_FIELD:
702       dpb->FieldOrderCnt[1] = ref->bottom_field_order_cnt;
703       dpb->used_for_reference = 0x2;
704       if (ref->other_field) {
705         dpb->FieldOrderCnt[0] = ref->other_field->bottom_field_order_cnt;
706         dpb->used_for_reference |= 0x1;
707       } else {
708         dpb->FieldOrderCnt[0] = 0;
709       }
710       break;
711     default:
712       dpb->FieldOrderCnt[0] = 0;
713       dpb->FieldOrderCnt[1] = 0;
714       dpb->used_for_reference = 0;
715       break;
716   }
717 }
718
719 static GstFlowReturn
720 gst_nv_h264_dec_start_picture (GstH264Decoder * decoder,
721     GstH264Picture * picture, GstH264Slice * slice, GstH264Dpb * dpb)
722 {
723   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
724   CUVIDPICPARAMS *params = &self->params;
725   CUVIDH264PICPARAMS *h264_params = &params->CodecSpecific.h264;
726   const GstH264SliceHdr *slice_header = &slice->header;
727   const GstH264SPS *sps;
728   const GstH264PPS *pps;
729   GstNvDecoderFrame *frame;
730   GArray *ref_list = self->ref_list;
731   guint i, ref_frame_idx;
732
733   g_return_val_if_fail (slice_header->pps != NULL, FALSE);
734   g_return_val_if_fail (slice_header->pps->sequence != NULL, FALSE);
735
736   frame = gst_nv_h264_dec_get_decoder_frame_from_picture (self, picture);
737
738   if (!frame) {
739     GST_ERROR_OBJECT (self,
740         "Couldn't get decoder frame frame picture %p", picture);
741     return GST_FLOW_ERROR;
742   }
743
744   gst_nv_h264_dec_reset_bitstream_params (self);
745
746   sps = slice_header->pps->sequence;
747   pps = slice_header->pps;
748
749   /* FIXME: update sps/pps related params only when it's required */
750   params->PicWidthInMbs = sps->pic_width_in_mbs_minus1 + 1;
751   if (!sps->frame_mbs_only_flag) {
752     params->FrameHeightInMbs = (sps->pic_height_in_map_units_minus1 + 1) << 1;
753   } else {
754     params->FrameHeightInMbs = sps->pic_height_in_map_units_minus1 + 1;
755   }
756   params->CurrPicIdx = frame->index;
757   params->field_pic_flag = slice_header->field_pic_flag;
758   params->bottom_field_flag =
759       picture->field == GST_H264_PICTURE_FIELD_BOTTOM_FIELD;
760   params->second_field = picture->second_field;
761
762   if (picture->field == GST_H264_PICTURE_FIELD_TOP_FIELD) {
763     h264_params->CurrFieldOrderCnt[0] = picture->top_field_order_cnt;
764     h264_params->CurrFieldOrderCnt[1] = 0;
765   } else if (picture->field == GST_H264_PICTURE_FIELD_BOTTOM_FIELD) {
766     h264_params->CurrFieldOrderCnt[0] = 0;
767     h264_params->CurrFieldOrderCnt[1] = picture->bottom_field_order_cnt;
768   } else {
769     h264_params->CurrFieldOrderCnt[0] = picture->top_field_order_cnt;
770     h264_params->CurrFieldOrderCnt[1] = picture->bottom_field_order_cnt;
771   }
772
773   /* nBitstreamDataLen, pBitstreamData, nNumSlices and pSliceDataOffsets
774    * will be set later */
775
776   params->ref_pic_flag = GST_H264_PICTURE_IS_REF (picture);
777   /* will be updated later, if any slices belong to this frame is not
778    * intra slice */
779   params->intra_pic_flag = 1;
780
781   h264_params->frame_num = picture->frame_num;
782   h264_params->ref_pic_flag = GST_H264_PICTURE_IS_REF (picture);
783
784   gst_nv_h264_dec_picture_params_from_sps (self,
785       sps, slice_header->field_pic_flag, h264_params);
786   gst_nv_h264_dec_picture_params_from_pps (self, pps, h264_params);
787
788   ref_frame_idx = 0;
789   g_array_set_size (ref_list, 0);
790
791   memset (&h264_params->dpb, 0, sizeof (h264_params->dpb));
792   gst_h264_dpb_get_pictures_short_term_ref (dpb, FALSE, FALSE, ref_list);
793   for (i = 0; ref_frame_idx < 16 && i < ref_list->len; i++) {
794     GstH264Picture *other = g_array_index (ref_list, GstH264Picture *, i);
795     gst_nv_h264_dec_fill_dpb (self, other, &h264_params->dpb[ref_frame_idx]);
796     ref_frame_idx++;
797   }
798   g_array_set_size (ref_list, 0);
799
800   gst_h264_dpb_get_pictures_long_term_ref (dpb, FALSE, ref_list);
801   for (i = 0; ref_frame_idx < 16 && i < ref_list->len; i++) {
802     GstH264Picture *other = g_array_index (ref_list, GstH264Picture *, i);
803     gst_nv_h264_dec_fill_dpb (self, other, &h264_params->dpb[ref_frame_idx]);
804     ref_frame_idx++;
805   }
806   g_array_set_size (ref_list, 0);
807
808   for (i = ref_frame_idx; i < 16; i++)
809     h264_params->dpb[i].PicIdx = -1;
810
811   return GST_FLOW_OK;
812 }
813
814 static GstFlowReturn
815 gst_nv_h264_dec_decode_slice (GstH264Decoder * decoder,
816     GstH264Picture * picture, GstH264Slice * slice, GArray * ref_pic_list0,
817     GArray * ref_pic_list1)
818 {
819   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
820   gsize new_size;
821
822   GST_LOG_OBJECT (self, "Decode slice, nalu size %u", slice->nalu.size);
823
824   if (self->slice_offsets_alloc_len < self->num_slices + 1) {
825     self->slice_offsets = (guint *) g_realloc_n (self->slice_offsets,
826         self->num_slices + 1, sizeof (guint));
827   }
828   self->slice_offsets[self->num_slices] = self->bitstream_buffer_offset;
829   GST_LOG_OBJECT (self, "Slice offset %u for slice %d",
830       self->slice_offsets[self->num_slices], self->num_slices);
831
832   self->num_slices++;
833
834   new_size = self->bitstream_buffer_offset + slice->nalu.size + 3;
835   if (self->bitstream_buffer_alloc_size < new_size) {
836     self->bitstream_buffer =
837         (guint8 *) g_realloc (self->bitstream_buffer, new_size);
838   }
839
840   self->bitstream_buffer[self->bitstream_buffer_offset] = 0;
841   self->bitstream_buffer[self->bitstream_buffer_offset + 1] = 0;
842   self->bitstream_buffer[self->bitstream_buffer_offset + 2] = 1;
843
844   memcpy (self->bitstream_buffer + self->bitstream_buffer_offset + 3,
845       slice->nalu.data + slice->nalu.offset, slice->nalu.size);
846   self->bitstream_buffer_offset = new_size;
847
848   if (!GST_H264_IS_I_SLICE (&slice->header) &&
849       !GST_H264_IS_SI_SLICE (&slice->header))
850     self->params.intra_pic_flag = 0;
851
852   return GST_FLOW_OK;
853 }
854
855 static GstFlowReturn
856 gst_nv_h264_dec_end_picture (GstH264Decoder * decoder, GstH264Picture * picture)
857 {
858   GstNvH264Dec *self = GST_NV_H264_DEC (decoder);
859   gboolean ret;
860   CUVIDPICPARAMS *params = &self->params;
861
862   params->nBitstreamDataLen = self->bitstream_buffer_offset;
863   params->pBitstreamData = self->bitstream_buffer;
864   params->nNumSlices = self->num_slices;
865   params->pSliceDataOffsets = self->slice_offsets;
866
867   GST_LOG_OBJECT (self, "End picture, bitstream len: %" G_GSIZE_FORMAT
868       ", num slices %d", self->bitstream_buffer_offset, self->num_slices);
869
870   ret = gst_nv_decoder_decode_picture (self->decoder, &self->params);
871
872   if (!ret) {
873     GST_ERROR_OBJECT (self, "Failed to decode picture");
874     return GST_FLOW_ERROR;
875   }
876
877   return GST_FLOW_OK;
878 }
879
880 static guint
881 gst_nv_h264_dec_get_preferred_output_delay (GstH264Decoder * decoder,
882     gboolean live)
883 {
884   /* Prefer to zero latency for live pipeline */
885   if (live)
886     return 0;
887
888   /* NVCODEC SDK uses 4 frame delay for better throughput performance */
889   return 4;
890 }
891
892 typedef struct
893 {
894   GstCaps *sink_caps;
895   GstCaps *src_caps;
896   guint cuda_device_id;
897   gboolean is_default;
898 } GstNvH264DecClassData;
899
900 static void
901 gst_nv_h264_dec_subclass_init (gpointer klass, GstNvH264DecClassData * cdata)
902 {
903   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
904   GstNvH264DecClass *nvdec_class = (GstNvH264DecClass *) (klass);
905   gchar *long_name;
906
907   if (cdata->is_default) {
908     long_name = g_strdup_printf ("NVDEC H.264 Stateless Decoder");
909   } else {
910     long_name = g_strdup_printf ("NVDEC H.264 Stateless Decoder with device %d",
911         cdata->cuda_device_id);
912   }
913
914   gst_element_class_set_metadata (element_class, long_name,
915       "Codec/Decoder/Video/Hardware",
916       "Nvidia H.264 video decoder", "Seungha Yang <seungha@centricular.com>");
917   g_free (long_name);
918
919   gst_element_class_add_pad_template (element_class,
920       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
921           cdata->sink_caps));
922   gst_element_class_add_pad_template (element_class,
923       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
924           cdata->src_caps));
925
926   nvdec_class->cuda_device_id = cdata->cuda_device_id;
927
928   gst_caps_unref (cdata->sink_caps);
929   gst_caps_unref (cdata->src_caps);
930   g_free (cdata);
931 }
932
933 void
934 gst_nv_h264_dec_register (GstPlugin * plugin, guint device_id, guint rank,
935     GstCaps * sink_caps, GstCaps * src_caps, gboolean is_primary)
936 {
937   GTypeQuery type_query;
938   GTypeInfo type_info = { 0, };
939   GType subtype;
940   gchar *type_name;
941   gchar *feature_name;
942   GstNvH264DecClassData *cdata;
943   gboolean is_default = TRUE;
944   const GValue *value;
945   GstStructure *s;
946
947   /**
948    * element-nvh264sldec
949    *
950    * Since: 1.18
951    */
952
953   cdata = g_new0 (GstNvH264DecClassData, 1);
954   cdata->sink_caps = gst_caps_from_string ("video/x-h264, "
955       "stream-format= (string) { avc, avc3, byte-stream }, "
956       "alignment= (string) au, "
957       "profile = (string) { high, main, constrained-high, constrained-baseline, baseline }, "
958       "framerate = " GST_VIDEO_FPS_RANGE);
959
960   s = gst_caps_get_structure (sink_caps, 0);
961   value = gst_structure_get_value (s, "width");
962   gst_caps_set_value (cdata->sink_caps, "width", value);
963
964   value = gst_structure_get_value (s, "height");
965   gst_caps_set_value (cdata->sink_caps, "height", value);
966
967   GST_MINI_OBJECT_FLAG_SET (cdata->sink_caps,
968       GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
969   cdata->src_caps = gst_caps_ref (src_caps);
970   cdata->cuda_device_id = device_id;
971
972   g_type_query (GST_TYPE_NV_H264_DEC, &type_query);
973   memset (&type_info, 0, sizeof (type_info));
974   type_info.class_size = type_query.class_size;
975   type_info.instance_size = type_query.instance_size;
976   type_info.class_init = (GClassInitFunc) gst_nv_h264_dec_subclass_init;
977   type_info.class_data = cdata;
978
979   if (is_primary) {
980     type_name = g_strdup ("GstNvH264StatelessPrimaryDec");
981     feature_name = g_strdup ("nvh264dec");
982   } else {
983     type_name = g_strdup ("GstNvH264StatelessDec");
984     feature_name = g_strdup ("nvh264sldec");
985   }
986
987   if (g_type_from_name (type_name) != 0) {
988     g_free (type_name);
989     g_free (feature_name);
990     if (is_primary) {
991       type_name =
992           g_strdup_printf ("GstNvH264StatelessPrimaryDevice%dDec", device_id);
993       feature_name = g_strdup_printf ("nvh264device%ddec", device_id);
994     } else {
995       type_name = g_strdup_printf ("GstNvH264StatelessDevice%dDec", device_id);
996       feature_name = g_strdup_printf ("nvh264sldevice%ddec", device_id);
997     }
998
999     is_default = FALSE;
1000   }
1001
1002   cdata->is_default = is_default;
1003   subtype = g_type_register_static (GST_TYPE_NV_H264_DEC,
1004       type_name, &type_info, 0);
1005
1006   /* make lower rank than default device */
1007   if (rank > 0 && !is_default)
1008     rank--;
1009
1010   if (!gst_element_register (plugin, feature_name, rank, subtype))
1011     GST_WARNING ("Failed to register plugin '%s'", type_name);
1012
1013   g_free (type_name);
1014   g_free (feature_name);
1015 }