qsv: Update SDK version to v2022.2.4
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / sys / qsv / gstqsvh264dec.cpp
1 /* GStreamer
2  * Copyright (C) 2022 Seungha Yang <seungha@centricular.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include "gstqsvh264dec.h"
25 #include <gst/codecparsers/gsth264parser.h>
26 #include <string>
27 #include <string.h>
28
29 #ifdef G_OS_WIN32
30 #include <gst/d3d11/gstd3d11.h>
31 #else
32 #include <gst/va/gstva.h>
33 #endif
34
35 GST_DEBUG_CATEGORY_STATIC (gst_qsv_h264_dec_debug);
36 #define GST_CAT_DEFAULT gst_qsv_h264_dec_debug
37
38 typedef struct _GstQsvH264Dec
39 {
40   GstQsvDecoder parent;
41   GstH264NalParser *parser;
42   gboolean packetized;
43   gboolean nal_length_size;
44
45   GstBuffer *sps_nals[GST_H264_MAX_SPS_COUNT];
46   GstBuffer *pps_nals[GST_H264_MAX_PPS_COUNT];
47 } GstQsvH264Dec;
48
49 typedef struct _GstQsvH264DecClass
50 {
51   GstQsvDecoderClass parent_class;
52 } GstQsvH264DecClass;
53
54 static GTypeClass *parent_class = nullptr;
55
56 #define GST_QSV_H264_DEC(object) ((GstQsvH264Dec *) (object))
57 #define GST_QSV_H264_DEC_GET_CLASS(object) \
58     (G_TYPE_INSTANCE_GET_CLASS ((object),G_TYPE_FROM_INSTANCE (object),GstQsvH264DecClass))
59
60 static gboolean gst_qsv_h264_dec_start (GstVideoDecoder * decoder);
61 static gboolean gst_qsv_h264_dec_stop (GstVideoDecoder * decoder);
62 static gboolean gst_qsv_h264_dec_set_format (GstQsvDecoder * decoder,
63     GstVideoCodecState * state);
64 static GstBuffer *gst_qsv_h264_dec_process_input (GstQsvDecoder * decoder,
65     gboolean need_codec_data, GstBuffer * buffer);
66
67 static void
68 gst_qsv_h264_dec_class_init (GstQsvH264DecClass * klass, gpointer data)
69 {
70   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
71   GstVideoDecoderClass *videodec_class = GST_VIDEO_DECODER_CLASS (klass);
72   GstQsvDecoderClass *qsvdec_class = GST_QSV_DECODER_CLASS (klass);
73   GstQsvDecoderClassData *cdata = (GstQsvDecoderClassData *) data;
74
75   parent_class = (GTypeClass *) g_type_class_peek_parent (klass);
76
77 #ifdef G_OS_WIN32
78   std::string long_name = "Intel Quick Sync Video " +
79       std::string (cdata->description) + " H.264 Decoder";
80
81   gst_element_class_set_metadata (element_class, long_name.c_str (),
82       "Codec/Decoder/Video/Hardware",
83       "Intel Quick Sync Video H.264 Decoder",
84       "Seungha Yang <seungha@centricular.com>");
85 #else
86   gst_element_class_set_static_metadata (element_class,
87       "Intel Quick Sync Video H.264 Decoder",
88       "Codec/Decoder/Video/Hardware",
89       "Intel Quick Sync Video H.264 Decoder",
90       "Seungha Yang <seungha@centricular.com>");
91 #endif
92
93   gst_element_class_add_pad_template (element_class,
94       gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
95           cdata->sink_caps));
96   gst_element_class_add_pad_template (element_class,
97       gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
98           cdata->src_caps));
99
100   videodec_class->start = GST_DEBUG_FUNCPTR (gst_qsv_h264_dec_start);
101   videodec_class->stop = GST_DEBUG_FUNCPTR (gst_qsv_h264_dec_stop);
102
103   qsvdec_class->set_format = GST_DEBUG_FUNCPTR (gst_qsv_h264_dec_set_format);
104   qsvdec_class->process_input =
105       GST_DEBUG_FUNCPTR (gst_qsv_h264_dec_process_input);
106
107   qsvdec_class->codec_id = MFX_CODEC_AVC;
108   qsvdec_class->impl_index = cdata->impl_index;
109   qsvdec_class->adapter_luid = cdata->adapter_luid;
110   qsvdec_class->display_path = cdata->display_path;
111
112   gst_caps_unref (cdata->sink_caps);
113   gst_caps_unref (cdata->src_caps);
114   g_free (cdata->description);
115   g_free (cdata);
116 }
117
118 static void
119 gst_qsv_h264_dec_init (GstQsvH264Dec * self)
120 {
121 }
122
123 static gboolean
124 gst_qsv_h264_dec_start (GstVideoDecoder * decoder)
125 {
126   GstQsvH264Dec *self = GST_QSV_H264_DEC (decoder);
127
128   self->parser = gst_h264_nal_parser_new ();
129
130   return TRUE;
131 }
132
133 static void
134 gst_qsv_h264_dec_clear_codec_data (GstQsvH264Dec * self)
135 {
136   guint i;
137
138   for (i = 0; i < G_N_ELEMENTS (self->sps_nals); i++)
139     gst_clear_buffer (&self->sps_nals[i]);
140
141   for (i = 0; i < G_N_ELEMENTS (self->pps_nals); i++)
142     gst_clear_buffer (&self->pps_nals[i]);
143 }
144
145 static gboolean
146 gst_qsv_h264_dec_stop (GstVideoDecoder * decoder)
147 {
148   GstQsvH264Dec *self = GST_QSV_H264_DEC (decoder);
149
150   gst_qsv_h264_dec_clear_codec_data (self);
151
152   return GST_VIDEO_DECODER_CLASS (parent_class)->stop (decoder);
153 }
154
155 static void
156 gst_qsv_h264_dec_store_nal (GstQsvH264Dec * self, guint id,
157     GstH264NalUnitType nal_type, GstH264NalUnit * nalu)
158 {
159   GstBuffer *buf, **store;
160   guint size = nalu->size, store_size;
161   static const guint8 start_code[] = { 0, 0, 1 };
162
163   if (nal_type == GST_H264_NAL_SPS || nal_type == GST_H264_NAL_SUBSET_SPS) {
164     store_size = GST_H264_MAX_SPS_COUNT;
165     store = self->sps_nals;
166     GST_DEBUG_OBJECT (self, "storing sps %u", id);
167   } else if (nal_type == GST_H264_NAL_PPS) {
168     store_size = GST_H264_MAX_PPS_COUNT;
169     store = self->pps_nals;
170     GST_DEBUG_OBJECT (self, "storing pps %u", id);
171   } else {
172     return;
173   }
174
175   if (id >= store_size) {
176     GST_DEBUG_OBJECT (self, "unable to store nal, id out-of-range %d", id);
177     return;
178   }
179
180   buf = gst_buffer_new_allocate (nullptr, size + sizeof (start_code), nullptr);
181   gst_buffer_fill (buf, 0, start_code, sizeof (start_code));
182   gst_buffer_fill (buf, sizeof (start_code), nalu->data + nalu->offset, size);
183
184   if (store[id])
185     gst_buffer_unref (store[id]);
186
187   store[id] = buf;
188 }
189
190 static gboolean
191 gst_qsv_h264_dec_parse_codec_data (GstQsvH264Dec * self, const guint8 * data,
192     gsize size)
193 {
194   GstH264NalParser *parser = self->parser;
195   GstH264DecoderConfigRecord *config = nullptr;
196   GstH264NalUnit *nalu;
197   GstH264ParserResult pres = GST_H264_PARSER_OK;
198   gboolean ret = TRUE;
199   guint i;
200
201   if (gst_h264_parser_parse_decoder_config_record (parser, data, size,
202           &config) != GST_H264_PARSER_OK) {
203     GST_WARNING_OBJECT (self, "Failed to parse codec-data");
204     return FALSE;
205   }
206
207   self->nal_length_size = config->length_size_minus_one + 1;
208   for (i = 0; i < config->sps->len; i++) {
209     GstH264SPS sps;
210     nalu = &g_array_index (config->sps, GstH264NalUnit, i);
211
212     if (nalu->type == GST_H264_NAL_SPS)
213       pres = gst_h264_parser_parse_sps (parser, nalu, &sps);
214     else if (nalu->type == GST_H264_NAL_SUBSET_SPS)
215       pres = gst_h264_parser_parse_subset_sps (parser, nalu, &sps);
216     else
217       continue;
218
219     if (pres != GST_H264_PARSER_OK) {
220       GST_WARNING_OBJECT (self, "Failed to parse SPS");
221       ret = FALSE;
222       goto out;
223     }
224
225     gst_qsv_h264_dec_store_nal (self,
226         sps.id, (GstH264NalUnitType) nalu->type, nalu);
227     gst_h264_sps_clear (&sps);
228   }
229
230   for (i = 0; i < config->pps->len; i++) {
231     GstH264PPS pps;
232
233     nalu = &g_array_index (config->pps, GstH264NalUnit, i);
234     if (nalu->type != GST_H264_NAL_PPS)
235       continue;
236
237     pres = gst_h264_parser_parse_pps (parser, nalu, &pps);
238     if (pres != GST_H264_PARSER_OK) {
239       GST_WARNING_OBJECT (self, "Failed to parse PPS nalu");
240       ret = FALSE;
241       goto out;
242     }
243
244     gst_qsv_h264_dec_store_nal (self, pps.id, GST_H264_NAL_PPS, nalu);
245     gst_h264_pps_clear (&pps);
246   }
247
248 out:
249   gst_h264_decoder_config_record_free (config);
250   return ret;
251 }
252
253 static gboolean
254 gst_qsv_h264_dec_set_format (GstQsvDecoder * decoder,
255     GstVideoCodecState * state)
256 {
257   GstQsvH264Dec *self = GST_QSV_H264_DEC (decoder);
258   GstStructure *s;
259   const gchar *str;
260   GstMapInfo map;
261
262   gst_qsv_h264_dec_clear_codec_data (self);
263   self->packetized = FALSE;
264
265   s = gst_caps_get_structure (state->caps, 0);
266   str = gst_structure_get_string (s, "stream-format");
267   if ((g_strcmp0 (str, "avc") == 0 || g_strcmp0 (str, "avc3")) &&
268       state->codec_data) {
269     self->packetized = TRUE;
270     /* Will be updated */
271     self->nal_length_size = 4;
272   }
273
274   if (!self->packetized)
275     return TRUE;
276
277   if (!gst_buffer_map (state->codec_data, &map, GST_MAP_READ)) {
278     GST_ERROR_OBJECT (self, "Failed to map codec data");
279     return FALSE;
280   }
281
282   gst_qsv_h264_dec_parse_codec_data (self, map.data, map.size);
283   gst_buffer_unmap (state->codec_data, &map);
284
285   return TRUE;
286 }
287
288 static GstBuffer *
289 gst_qsv_h264_dec_process_input (GstQsvDecoder * decoder,
290     gboolean need_codec_data, GstBuffer * buffer)
291 {
292   GstQsvH264Dec *self = GST_QSV_H264_DEC (decoder);
293   GstH264NalParser *parser = self->parser;
294   GstH264NalUnit nalu;
295   GstH264ParserResult pres;
296   GstMapInfo map;
297   gboolean have_sps = FALSE;
298   gboolean have_pps = FALSE;
299   guint i;
300   GstBuffer *new_buf;
301   static const guint8 start_code[] = { 0, 0, 1 };
302
303   if (!self->packetized)
304     return gst_buffer_ref (buffer);
305
306   if (!gst_buffer_map (buffer, &map, GST_MAP_READ)) {
307     GST_ERROR_OBJECT (self, "Failed to map input buffer");
308     return nullptr;
309   }
310
311   memset (&nalu, 0, sizeof (GstH264NalUnit));
312   new_buf = gst_buffer_new ();
313
314   do {
315     GstMemory *mem;
316     guint8 *data;
317     gsize size;
318
319     pres = gst_h264_parser_identify_nalu_avc (parser, map.data,
320         nalu.offset + nalu.size, map.size, self->nal_length_size, &nalu);
321
322     if (pres == GST_H264_PARSER_NO_NAL_END)
323       pres = GST_H264_PARSER_OK;
324
325     switch (nalu.type) {
326       case GST_H264_NAL_SPS:
327       case GST_H264_NAL_SUBSET_SPS:{
328         GstH264SPS sps;
329
330         if (nalu.type == GST_H264_NAL_SPS) {
331           pres = gst_h264_parser_parse_sps (parser, &nalu, &sps);
332         } else {
333           pres = gst_h264_parser_parse_subset_sps (parser, &nalu, &sps);
334         }
335
336         if (pres != GST_H264_PARSER_OK)
337           break;
338
339         have_sps = TRUE;
340         gst_qsv_h264_dec_store_nal (self,
341             sps.id, (GstH264NalUnitType) nalu.type, &nalu);
342         gst_h264_sps_clear (&sps);
343         break;
344       }
345       case GST_H264_NAL_PPS:{
346         GstH264PPS pps;
347
348         pres = gst_h264_parser_parse_pps (parser, &nalu, &pps);
349         if (pres != GST_H264_PARSER_OK)
350           break;
351
352         have_pps = TRUE;
353         gst_qsv_h264_dec_store_nal (self,
354             pps.id, (GstH264NalUnitType) nalu.type, &nalu);
355         gst_h264_pps_clear (&pps);
356         break;
357       }
358       default:
359         break;
360     }
361
362     size = sizeof (start_code) + nalu.size;
363     data = (guint8 *) g_malloc (size);
364     memcpy (data, start_code, sizeof (start_code));
365     memcpy (data + sizeof (start_code), nalu.data + nalu.offset, nalu.size);
366
367     mem = gst_memory_new_wrapped ((GstMemoryFlags) 0, data, size, 0, size,
368         nullptr, (GDestroyNotify) g_free);
369     gst_buffer_append_memory (new_buf, mem);
370   } while (pres == GST_H264_PARSER_OK);
371
372   gst_buffer_unmap (buffer, &map);
373
374   if (need_codec_data) {
375     GstBuffer *tmp = gst_buffer_new ();
376
377     if (!have_sps) {
378       for (i = 0; i < GST_H264_MAX_SPS_COUNT; i++) {
379         if (!self->sps_nals[i])
380           continue;
381
382         tmp = gst_buffer_append (tmp, gst_buffer_ref (self->sps_nals[i]));
383       }
384     }
385
386     if (!have_pps) {
387       for (i = 0; i < GST_H264_MAX_PPS_COUNT; i++) {
388         if (!self->pps_nals[i])
389           continue;
390
391         tmp = gst_buffer_append (tmp, gst_buffer_ref (self->pps_nals[i]));
392       }
393     }
394
395     new_buf = gst_buffer_append (tmp, new_buf);
396   }
397
398   return new_buf;
399 }
400
401 typedef struct
402 {
403   guint width;
404   guint height;
405 } Resolution;
406
407 void
408 gst_qsv_h264_dec_register (GstPlugin * plugin, guint rank, guint impl_index,
409     GstObject * device, mfxSession session)
410 {
411   mfxVideoParam param;
412   mfxInfoMFX *mfx;
413   static const Resolution resolutions_to_check[] = {
414     {1280, 720}, {1920, 1088}, {2560, 1440}, {3840, 2160}, {4096, 2160},
415     {7680, 4320}, {8192, 4320}
416   };
417   Resolution max_resolution;
418
419   GST_DEBUG_CATEGORY_INIT (gst_qsv_h264_dec_debug,
420       "qsvh264dec", 0, "qsvh264dec");
421
422   memset (&param, 0, sizeof (mfxVideoParam));
423   memset (&max_resolution, 0, sizeof (Resolution));
424
425   param.AsyncDepth = 4;
426   param.IOPattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
427
428   mfx = &param.mfx;
429   mfx->CodecId = MFX_CODEC_AVC;
430
431   mfx->FrameInfo.FrameRateExtN = 30;
432   mfx->FrameInfo.FrameRateExtD = 1;
433   mfx->FrameInfo.AspectRatioW = 1;
434   mfx->FrameInfo.AspectRatioH = 1;
435   mfx->FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
436   mfx->FrameInfo.FourCC = MFX_FOURCC_NV12;
437   mfx->FrameInfo.BitDepthLuma = 8;
438   mfx->FrameInfo.BitDepthChroma = 8;
439   mfx->FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
440   mfx->CodecProfile = MFX_PROFILE_AVC_MAIN;
441
442   /* Check max-resolution */
443   for (guint i = 0; i < G_N_ELEMENTS (resolutions_to_check); i++) {
444     mfx->FrameInfo.Width = GST_ROUND_UP_16 (resolutions_to_check[i].width);
445     mfx->FrameInfo.Height = GST_ROUND_UP_16 (resolutions_to_check[i].height);
446     mfx->FrameInfo.CropW = resolutions_to_check[i].width;
447     mfx->FrameInfo.CropH = resolutions_to_check[i].height;
448
449     if (MFXVideoDECODE_Query (session, &param, &param) != MFX_ERR_NONE)
450       break;
451
452     max_resolution.width = resolutions_to_check[i].width;
453     max_resolution.height = resolutions_to_check[i].height;
454   }
455
456   if (max_resolution.width == 0 || max_resolution.height == 0)
457     return;
458
459   GST_INFO ("Maximum supported resolution: %dx%d",
460       max_resolution.width, max_resolution.height);
461
462   /* To cover both landscape and portrait,
463    * select max value (width in this case) */
464   guint resolution = MAX (max_resolution.width, max_resolution.height);
465   std::string src_caps_str = "video/x-raw, format=(string) NV12";
466
467   src_caps_str += ", width=(int) [ 16, " + std::to_string (resolution) + " ]";
468   src_caps_str += ", height=(int) [ 16, " + std::to_string (resolution) + " ]";
469
470   GstCaps *src_caps = gst_caps_from_string (src_caps_str.c_str ());
471
472   /* TODO: Add support for VA */
473 #ifdef G_OS_WIN32
474   GstCaps *d3d11_caps = gst_caps_copy (src_caps);
475   GstCapsFeatures *caps_features =
476       gst_caps_features_new (GST_CAPS_FEATURE_MEMORY_D3D11_MEMORY, nullptr);
477   gst_caps_set_features_simple (d3d11_caps, caps_features);
478   gst_caps_append (d3d11_caps, src_caps);
479   src_caps = d3d11_caps;
480 #endif
481
482   std::string sink_caps_str = "video/x-h264";
483   sink_caps_str += ", width=(int) [ 16, " + std::to_string (resolution) + " ]";
484   sink_caps_str += ", height=(int) [ 16, " + std::to_string (resolution) + " ]";
485
486   sink_caps_str += ", stream-format=(string) { byte-stream, avc, avc3 }";
487   sink_caps_str += ", alignment=(string) au";
488   sink_caps_str += ", profile=(string) { high, progressive-high, "
489       "constrained-high, main, constrained-baseline, baseline } ";
490
491   GstCaps *sink_caps = gst_caps_from_string (sink_caps_str.c_str ());
492
493   GST_MINI_OBJECT_FLAG_SET (sink_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
494   GST_MINI_OBJECT_FLAG_SET (src_caps, GST_MINI_OBJECT_FLAG_MAY_BE_LEAKED);
495
496   GstQsvDecoderClassData *cdata = g_new0 (GstQsvDecoderClassData, 1);
497   cdata->sink_caps = sink_caps;
498   cdata->src_caps = src_caps;
499   cdata->impl_index = impl_index;
500
501 #ifdef G_OS_WIN32
502   g_object_get (device, "adapter-luid", &cdata->adapter_luid,
503       "description", &cdata->description, nullptr);
504 #else
505   g_object_get (device, "path", &cdata->display_path, nullptr);
506 #endif
507
508   GType type;
509   gchar *type_name;
510   gchar *feature_name;
511   GTypeInfo type_info = {
512     sizeof (GstQsvH264DecClass),
513     nullptr,
514     nullptr,
515     (GClassInitFunc) gst_qsv_h264_dec_class_init,
516     nullptr,
517     cdata,
518     sizeof (GstQsvH264Dec),
519     0,
520     (GInstanceInitFunc) gst_qsv_h264_dec_init,
521   };
522
523   type_name = g_strdup ("GstQsvH264Dec");
524   feature_name = g_strdup ("qsvh264dec");
525
526   gint index = 0;
527   while (g_type_from_name (type_name)) {
528     index++;
529     g_free (type_name);
530     g_free (feature_name);
531     type_name = g_strdup_printf ("GstQsvH264Device%dDec", index);
532     feature_name = g_strdup_printf ("qsvh264device%ddec", index);
533   }
534
535   type = g_type_register_static (GST_TYPE_QSV_DECODER, type_name, &type_info,
536       (GTypeFlags) 0);
537
538   if (rank > 0 && index != 0)
539     rank--;
540
541   if (!gst_element_register (plugin, feature_name, rank, type))
542     GST_WARNING ("Failed to register plugin '%s'", type_name);
543
544   g_free (type_name);
545   g_free (feature_name);
546 }