File: gstnvdecobject.cpp

package info (click to toggle)
gst-plugins-bad1.0 1.28.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 72,252 kB
  • sloc: ansic: 744,658; cpp: 300,297; objc: 3,559; xml: 3,351; sh: 1,095; python: 565; makefile: 181; java: 75
file content (622 lines) | stat: -rw-r--r-- 16,426 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/* GStreamer
 * Copyright (C) 2023 Seungha Yang <seungha@centricular.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstnvdecobject.h"
#include <vector>
#include <mutex>
#include <condition_variable>
#include <map>
#include <memory>
#include <string.h>
#include <algorithm>
#include <gst/cuda/gstcuda-private.h>

extern "C"
{
  GST_DEBUG_CATEGORY_EXTERN (gst_nv_decoder_debug);
}

#define GST_CAT_DEFAULT gst_nv_decoder_debug

GST_DEFINE_MINI_OBJECT_TYPE (GstNvDecSurface, gst_nv_dec_surface);
static GstNvDecSurface *gst_nv_dec_surface_new (guint seq_num);

/* *INDENT-OFF* */
struct GstNvDecOutput
{
  GstNvDecObject *self = nullptr;
  CUdeviceptr devptr = 0;
  guint seq_num = 0;
};

struct GstNvDecObjectPrivate
{
  std::vector < GstNvDecSurface * >surface_queue;
  std::map < CUdeviceptr, GstMemory *> output_map;
  std::map < CUdeviceptr, GstMemory *> free_output_map;

  std::mutex lock;
  std::condition_variable cond;
};
/* *INDENT-ON* */

struct _GstNvDecObject
{
  GstObject parent;

  GstNvDecObjectPrivate *priv;

  CUvideodecoder handle;
  CUVIDDECODECREATEINFO create_info;

  GstVideoInfo video_info;

  GstCudaContext *context;

  gboolean flushing;

  guint pool_size;
  guint num_mapped;
  gboolean alloc_aux_frame;
  guint plane_height;
  guint seq_num;
};

static void gst_nv_dec_object_finalize (GObject * object);

#define gst_nv_dec_object_parent_class parent_class
G_DEFINE_TYPE (GstNvDecObject, gst_nv_dec_object, GST_TYPE_OBJECT);

static void
gst_nv_dec_object_class_init (GstNvDecObjectClass * klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = gst_nv_dec_object_finalize;
}

static void
gst_nv_dec_object_init (GstNvDecObject * self)
{
  self->priv = new GstNvDecObjectPrivate ();
}

static void
gst_nv_dec_object_finalize (GObject * object)
{
  GstNvDecObject *self = GST_NV_DEC_OBJECT (object);
  GstNvDecObjectPrivate *priv = self->priv;

  GST_DEBUG_OBJECT (self, "Finalize");

  gst_cuda_context_push (self->context);
  /* *INDENT-OFF* */
  for (auto it : priv->surface_queue)
    gst_nv_dec_surface_unref (it);

  /* *INDENT-OFF* */
  for (auto it : priv->free_output_map)
    gst_memory_unref (it.second);
  /* *INDENT-ON* */

  delete self->priv;

  CuvidDestroyDecoder (self->handle);
  gst_cuda_context_pop (nullptr);

  gst_object_unref (self->context);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

GstNvDecObject *
gst_nv_dec_object_new (GstCudaContext * context,
    CUVIDDECODECREATEINFO * create_info, const GstVideoInfo * video_info,
    gboolean alloc_aux_frame)
{
  GstNvDecObject *self;
  CUresult ret;
  CUvideodecoder handle = nullptr;
  guint pool_size;

  if (!gst_cuda_context_push (context)) {
    GST_ERROR_OBJECT (context, "Failed to push context");
    return nullptr;
  }

  ret = CuvidCreateDecoder (&handle, create_info);
  gst_cuda_context_pop (nullptr);

  if (!gst_cuda_result (ret)) {
    GST_ERROR_OBJECT (context, "Could not create decoder instance");
    return nullptr;
  }

  pool_size = create_info->ulNumDecodeSurfaces;
  if (alloc_aux_frame)
    pool_size /= 2;

  self = (GstNvDecObject *)
      g_object_new (GST_TYPE_NV_DEC_OBJECT, nullptr);
  gst_object_ref_sink (self);
  self->context = (GstCudaContext *) gst_object_ref (context);
  self->handle = handle;
  self->create_info = *create_info;
  self->video_info = *video_info;
  self->pool_size = pool_size;
  self->plane_height = create_info->ulTargetHeight;

  for (guint i = 0; i < pool_size; i++) {
    GstNvDecSurface *surf = gst_nv_dec_surface_new (0);

    surf->index = i;

    /* [0, pool_size - 1]: output picture
     * [pool_size, pool_size * 2 - 1]: decoder output without film-grain,
     * used for reference picture */
    if (alloc_aux_frame)
      surf->decode_frame_index = i + pool_size;
    else
      surf->decode_frame_index = i;

    self->priv->surface_queue.push_back (surf);
  }

  return self;
}

gboolean
gst_nv_dec_object_reconfigure (GstNvDecObject * object,
    CUVIDRECONFIGUREDECODERINFO * reconfigure_info,
    const GstVideoInfo * video_info, gboolean alloc_aux_frame)
{
  GstNvDecObjectPrivate *priv = object->priv;
  CUresult ret;
  guint pool_size;

  if (!gst_cuvid_can_reconfigure ())
    return FALSE;

  pool_size = reconfigure_info->ulNumDecodeSurfaces;
  if (alloc_aux_frame)
    pool_size /= 2;

  std::lock_guard < std::mutex > lk (priv->lock);
  if (!gst_cuda_context_push (object->context)) {
    GST_ERROR_OBJECT (object, "Couldn't push context");
    return FALSE;
  }

  ret = CuvidReconfigureDecoder (object->handle, reconfigure_info);
  gst_cuda_context_pop (nullptr);

  if (!gst_cuda_result (ret)) {
    GST_ERROR_OBJECT (object, "Couldn't reconfigure decoder");
    return FALSE;
  }

  if ((guint) priv->surface_queue.size () != object->pool_size) {
    GST_WARNING_OBJECT (object, "Unused surfaces %u != pool size %u",
        (guint) priv->surface_queue.size (), object->pool_size);
  }

  /* Release old surfaces and create new ones */
  /* *INDENT-OFF* */
  for (auto it : priv->surface_queue)
    gst_nv_dec_surface_unref (it);
  /* *INDENT-ON* */

  priv->surface_queue.clear ();

  object->pool_size = pool_size;
  object->video_info = *video_info;
  object->seq_num++;
  object->plane_height = reconfigure_info->ulTargetHeight;

  for (guint i = 0; i < pool_size; i++) {
    GstNvDecSurface *surf = gst_nv_dec_surface_new (object->seq_num);

    surf->index = i;

    /* [0, pool_size - 1]: output picture
     * [pool_size, pool_size * 2 - 1]: decoder output without film-grain,
     * used for reference picture */
    if (alloc_aux_frame)
      surf->decode_frame_index = i + pool_size;
    else
      surf->decode_frame_index = i;

    object->priv->surface_queue.push_back (surf);
  }

  return TRUE;
}

void
gst_nv_dec_object_set_flushing (GstNvDecObject * object, gboolean flushing)
{
  GstNvDecObjectPrivate *priv = object->priv;
  std::lock_guard < std::mutex > lk (priv->lock);
  object->flushing = flushing;
  priv->cond.notify_all ();
}

static gboolean
gst_nv_dec_object_unmap_surface_unlocked (GstNvDecObject * self,
    GstNvDecSurface * surface)
{
  gboolean ret = TRUE;

  if (!gst_cuda_result (CuvidUnmapVideoFrame (self->handle, surface->devptr))) {
    GST_ERROR_OBJECT (self, "Couldn't unmap surface %d", surface->index);
    ret = FALSE;
  } else {
    surface->devptr = 0;
    self->num_mapped--;

    GST_LOG_OBJECT (self, "Surface %d is unmapped, num-mapped %d",
        surface->index, self->num_mapped);
  }
  self->priv->cond.notify_all ();

  return ret;
}

GstFlowReturn
gst_nv_dec_object_acquire_surface (GstNvDecObject * object,
    GstNvDecSurface ** surface)
{
  GstNvDecObjectPrivate *priv = object->priv;
  GstNvDecSurface *surf = nullptr;
  std::unique_lock < std::mutex > lk (priv->lock);

  do {
    if (object->flushing) {
      GST_DEBUG_OBJECT (object, "We are flushing");
      return GST_FLOW_FLUSHING;
    }

    if (!priv->surface_queue.empty ()) {
      surf = priv->surface_queue[0];
      priv->surface_queue.erase (priv->surface_queue.begin ());
      break;
    }

    GST_LOG_OBJECT (object, "No available surface, waiting for release");
    priv->cond.wait (lk);
  } while (true);

  g_assert (surf);
  g_assert (!surf->object);

  surf->object = (GstNvDecObject *) gst_object_ref (object);

  *surface = surf;

  return GST_FLOW_OK;
}

gboolean
gst_nv_dec_object_decode (GstNvDecObject * object, CUVIDPICPARAMS * params)
{
  gboolean ret = TRUE;

  GST_LOG_OBJECT (object, "picture index: %u", params->CurrPicIdx);

  if (!gst_cuda_context_push (object->context)) {
    GST_ERROR_OBJECT (object, "Failed to push CUDA context");
    return FALSE;
  }

  if (!gst_cuda_result (CuvidDecodePicture (object->handle, params))) {
    GST_ERROR_OBJECT (object, "Failed to decode picture");
    ret = FALSE;
  }

  if (!gst_cuda_context_pop (nullptr))
    GST_WARNING_OBJECT (object, "Failed to pop CUDA context");

  return ret;
}

GstFlowReturn
gst_nv_dec_object_map_surface (GstNvDecObject * object,
    GstNvDecSurface * surface, GstCudaStream * stream)
{
  GstNvDecObjectPrivate *priv = object->priv;

  if (surface->devptr) {
    GST_ERROR_OBJECT (object, "Mapped Surface %d was not cleared",
        surface->index);
    return GST_FLOW_ERROR;
  }

  std::unique_lock < std::mutex > lk (priv->lock);
  do {
    if (object->flushing) {
      GST_DEBUG_OBJECT (object, "We are flushing");
      return GST_FLOW_FLUSHING;
    }

    if (object->num_mapped < (guint) object->create_info.ulNumOutputSurfaces) {
      CUVIDPROCPARAMS params = { 0 };

      params.progressive_frame = 1;
      params.output_stream = gst_cuda_stream_get_handle (stream);

      if (!gst_cuda_result (CuvidMapVideoFrame (object->handle, surface->index,
                  &surface->devptr, &surface->pitch, &params))) {
        GST_ERROR_OBJECT (object, "Couldn't map picture");
        return GST_FLOW_ERROR;
      }

      object->num_mapped++;
      GST_LOG_OBJECT (object, "Surface %d is mapped, num-mapped %d",
          surface->index, object->num_mapped);
      break;
    }

    GST_LOG_OBJECT (object, "No available output surface, waiting for release");
    priv->cond.wait (lk);
  } while (true);

  return GST_FLOW_OK;
}

gboolean
gst_nv_dec_object_unmap_surface (GstNvDecObject * object,
    GstNvDecSurface * surface)
{
  GstNvDecObjectPrivate *priv = object->priv;
  std::lock_guard < std::mutex > lk (priv->lock);

  return gst_nv_dec_object_unmap_surface_unlocked (object, surface);
}

static gboolean
gst_nv_dec_output_release (GstCudaMemory * mem)
{
  GstNvDecOutput *output = (GstNvDecOutput *)
      gst_cuda_memory_get_user_data (mem);
  GstNvDecObject *self = output->self;
  GstNvDecObjectPrivate *priv = self->priv;

  GST_LOG_OBJECT (self, "Release memory %p", mem);

  gst_memory_ref (GST_MEMORY_CAST (mem));
  GST_MINI_OBJECT_CAST (mem)->dispose = nullptr;

  output->self = nullptr;

  {
    std::lock_guard < std::mutex > lk (priv->lock);

    self->num_mapped--;
    gst_cuda_context_push (self->context);
    if (!gst_cuda_result (CuvidUnmapVideoFrame (self->handle, output->devptr))) {
      GST_ERROR_OBJECT (self, "Couldn't unmap frame");
    } else {
      GST_LOG_OBJECT (self, "Exported surface is freed, num-mapped %d",
          self->num_mapped);
    }
    gst_cuda_context_pop (nullptr);

    priv->free_output_map[output->devptr] = GST_MEMORY_CAST (mem);
    priv->cond.notify_all ();
  }

  gst_object_unref (self);

  return FALSE;
}

static void
gst_nv_dec_output_free (GstNvDecOutput * output)
{
  delete output;
}

GstFlowReturn
gst_nv_dec_object_export_surface (GstNvDecObject * object,
    GstNvDecSurface * surface, GstCudaStream * stream, GstMemory ** memory)
{
  GstNvDecObjectPrivate *priv = object->priv;
  GstVideoInfo info;
  gsize offset;
  GstMemory *mem = nullptr;
  GstNvDecOutput *output;

  if (!surface->devptr) {
    GST_ERROR_OBJECT (object, "Surface %d is not mapped", surface->index);
    return GST_FLOW_ERROR;
  }

  GST_LOG_OBJECT (object, "Exporting surface %d", surface->index);

  offset = surface->pitch * object->plane_height;

  info = object->video_info;
  switch (GST_VIDEO_INFO_FORMAT (&info)) {
    case GST_VIDEO_FORMAT_NV12:
    case GST_VIDEO_FORMAT_P010_10LE:
    case GST_VIDEO_FORMAT_P012_LE:
    case GST_VIDEO_FORMAT_P016_LE:
      info.stride[0] = surface->pitch;
      info.stride[1] = surface->pitch;
      info.offset[0] = 0;
      info.offset[1] = offset;
      info.size = offset + offset / 2;
      break;
    case GST_VIDEO_FORMAT_Y444:
    case GST_VIDEO_FORMAT_Y444_16LE:
    case GST_VIDEO_FORMAT_GBR:
    case GST_VIDEO_FORMAT_GBR_16LE:
      info.stride[0] = surface->pitch;
      info.stride[1] = surface->pitch;
      info.stride[2] = surface->pitch;
      info.offset[0] = 0;
      info.offset[1] = offset;
      info.offset[2] = offset * 2;
      info.size = offset * 3;
      break;
    default:
      GST_ERROR_OBJECT (object, "Unexpected format %s",
          gst_video_format_to_string (GST_VIDEO_INFO_FORMAT (&info)));
      return GST_FLOW_ERROR;
  }

  std::unique_lock < std::mutex > lk (priv->lock);
  auto output_iter = priv->output_map.find (surface->devptr);
  if (output_iter != priv->output_map.end ())
    mem = output_iter->second;

  if (mem) {
    do {
      if (object->flushing) {
        GST_DEBUG_OBJECT (object, "We are flushing");
        return GST_FLOW_FLUSHING;
      }

      auto iter = priv->free_output_map.find (surface->devptr);
      if (iter != priv->free_output_map.end ()) {
        priv->free_output_map.erase (iter);
        break;
      }

      GST_LOG_OBJECT (object, "Waiting for output release");
      priv->cond.wait (lk);
    } while (true);

    output = (GstNvDecOutput *)
        gst_cuda_memory_get_user_data (GST_CUDA_MEMORY_CAST (mem));
    if (output->seq_num != object->seq_num) {
      GST_DEBUG_OBJECT (object,
          "output belongs to previous sequence, need new memory");
      gst_memory_unref (mem);
      mem = nullptr;
    }
  }

  if (!mem) {
    output = new GstNvDecOutput ();
    output->devptr = surface->devptr;
    output->seq_num = object->seq_num;

    GST_LOG_OBJECT (object, "New output, allocating memory");

    mem = gst_cuda_allocator_alloc_wrapped (nullptr, object->context,
        stream, &info, output->devptr, output,
        (GDestroyNotify) gst_nv_dec_output_free);
    gst_cuda_memory_set_from_fixed_pool (mem);

    priv->output_map[output->devptr] = mem;
  } else {
    GST_LOG_OBJECT (object, "Reuse memory");
  }

  GST_MINI_OBJECT_CAST (mem)->dispose =
      (GstMiniObjectDisposeFunction) gst_nv_dec_output_release;

  output = (GstNvDecOutput *)
      gst_cuda_memory_get_user_data (GST_CUDA_MEMORY_CAST (mem));

  g_assert (!output->self);

  output->self = (GstNvDecObject *) gst_object_ref (object);
  surface->devptr = 0;

  *memory = mem;

  return GST_FLOW_OK;
}

guint
gst_nv_dec_object_get_num_free_surfaces (GstNvDecObject * object)
{
  GstNvDecObjectPrivate *priv = object->priv;
  std::lock_guard < std::mutex > lk (priv->lock);

  if (object->num_mapped >= object->create_info.ulNumOutputSurfaces)
    return 0;

  return object->create_info.ulNumOutputSurfaces - object->num_mapped;
}

static gboolean
gst_nv_dec_surface_dispose (GstNvDecSurface * surf)
{
  GstNvDecObject *object;
  GstNvDecObjectPrivate *priv;
  gboolean ret = FALSE;

  if (!surf->object)
    return TRUE;

  object = (GstNvDecObject *) g_steal_pointer (&surf->object);
  priv = object->priv;

  /* *INDENT-OFF* */
  {
    std::lock_guard < std::mutex > lk (priv->lock);

    if (surf->seq_num == object->seq_num) {
      /* Back to surface queue */
      gst_nv_dec_surface_ref (surf);

      /* Keep sorted order */
      priv->surface_queue.insert (
          std::upper_bound (priv->surface_queue.begin (),
          priv->surface_queue.end(), surf,
              [] (const GstNvDecSurface * a, const GstNvDecSurface * b)
              {
                return a->index < b->index;
              }), surf);
      priv->cond.notify_all ();
    } else {
      GST_WARNING_OBJECT (object, "Releasing surface %p of previous sequence",
          surf);
      /* Shouldn't happen (e.g., surfaces were not flushed before reconfigure) */
      ret = TRUE;
    }
  }
  /* *INDENT-ON* */

  gst_object_unref (object);

  return ret;
}

static GstNvDecSurface *
gst_nv_dec_surface_new (guint seq_num)
{
  GstNvDecSurface *surf = g_new0 (GstNvDecSurface, 1);

  surf->seq_num = seq_num;

  gst_mini_object_init (GST_MINI_OBJECT_CAST (surf),
      0, GST_TYPE_NV_DEC_SURFACE, nullptr,
      (GstMiniObjectDisposeFunction) gst_nv_dec_surface_dispose,
      (GstMiniObjectFreeFunction) g_free);

  return surf;
}