-
Notifications
You must be signed in to change notification settings - Fork 3
/
gstnvinfer.cpp
2440 lines (2119 loc) · 89.4 KB
/
gstnvinfer.cpp
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA Corporation is strictly prohibited.
*
*/
#include <string.h>
#include <sstream>
#include <sys/time.h>
#include <algorithm>
#include <cassert>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <list>
#include <thread>
#include <vector>
#include "gst-nvevent.h"
#include "gstnvdsmeta.h"
#include "nvdspreprocess_meta.h"
#include "gstnvinfer.h"
#include "gstnvinfer_allocator.h"
#include "gstnvinfer_meta_utils.h"
#include "gstnvinfer_property_parser.h"
#include "gstnvinfer_impl.h"
using namespace gstnvinfer;
using namespace nvdsinfer;
GST_DEBUG_CATEGORY (gst_nvinfer_debug);
#define GST_CAT_DEFAULT gst_nvinfer_debug
#define INTERNAL_BUF_POOL_SIZE 3
#define NVDSINFER_CTX_OUT_POOL_SIZE_FLOW_META 6
/* Tracked objects will be reinferred only when their area in terms of pixels
* increase by this ratio. */
#define REINFER_AREA_THRESHOLD 0.2
/* Tracked objects in the infer history map will be removed if they have not
* been accessed for at least this number of frames. The tracker would definitely
* have dropped references to an unseen object by 150 frames. */
#define CLEANUP_ACCESS_CRITERIA 150
/* Object history map cleanup interval. 1800 frames is a minute with a 30fps input */
#define MAP_CLEANUP_INTERVAL 1800
#define PROCESS_MODEL_FULL_FRAME 1
#define PROCESS_MODEL_OBJECTS 2
/* Warn about untracked objects in async mode every 5 minutes. */
#define UNTRACKED_OBJECT_WARN_INTERVAL (GST_SECOND * 60 * 5)
#define MIN_INPUT_OBJECT_WIDTH 16
#define MIN_INPUT_OBJECT_HEIGHT 16
extern const int DEFAULT_REINFER_INTERVAL = G_MAXINT;
#define DS_NVINFER_IMPL(gst_nvinfer) reinterpret_cast<DsNvInferImpl*>((gst_nvinfer)->impl)
#define IS_DETECTOR_INSTANCE(nvinfer) \
(DS_NVINFER_IMPL(nvinfer)->m_InitParams->networkType == NvDsInferNetworkType_Detector)
#define IS_CLASSIFIER_INSTANCE(nvinfer) \
(DS_NVINFER_IMPL(nvinfer)->m_InitParams->networkType == NvDsInferNetworkType_Classifier)
#define IS_SEGMENTATION_INSTANCE(nvinfer) \
(DS_NVINFER_IMPL(nvinfer)->m_InitParams->networkType == NvDsInferNetworkType_Segmentation)
#define IS_INSTANCE_SEGMENTATION_INSTANCE(nvinfer) \
(DS_NVINFER_IMPL(nvinfer)->m_InitParams->networkType == NvDsInferNetworkType_InstanceSegmentation)
static GQuark _dsmeta_quark = 0;
/* Gst-nvinfer supports runtime model updates. Refer to gstnvinfer_impl.h
* for details. */
/* Default values for properties */
#define DEFAULT_UNIQUE_ID 15
#define DEFAULT_PROCESS_MODE PROCESS_MODEL_FULL_FRAME
#define DEFAULT_CONFIG_FILE_PATH ""
#define DEFAULT_BATCH_SIZE 1
#define DEFAULT_INTERVAL 0
#define DEFAULT_OPERATE_ON_GIE_ID -1
#define DEFAULT_GPU_DEVICE_ID 0
#define DEFAULT_OUTPUT_WRITE_TO_FILE FALSE
#define DEFAULT_OUTPUT_TENSOR_META FALSE
#define DEFAULT_OUTPUT_INSTANCE_MASK FALSE
#define DEFAULT_INPUT_TENSOR_META FALSE
/* By default NVIDIA Hardware allocated memory flows through the pipeline. We
* will be processing on this type of memory only. */
#define GST_CAPS_FEATURE_MEMORY_NVMM "memory:NVMM"
static GstStaticPadTemplate gst_nvinfer_sink_template =
GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE_WITH_FEATURES
(GST_CAPS_FEATURE_MEMORY_NVMM, "{ NV12, RGBA }")));
static GstStaticPadTemplate gst_nvinfer_src_template =
GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE_WITH_FEATURES
(GST_CAPS_FEATURE_MEMORY_NVMM, "{ NV12, RGBA }")));
guint gst_nvinfer_signals[LAST_SIGNAL] = { 0 };
/* Define our element type. Standard GObject/GStreamer boilerplate stuff */
#define gst_nvinfer_parent_class parent_class
G_DEFINE_TYPE (GstNvInfer, gst_nvinfer, GST_TYPE_BASE_TRANSFORM);
/* Implementation of the GObject/GstBaseTransform interfaces. */
static void gst_nvinfer_finalize (GObject * object);
static void gst_nvinfer_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_nvinfer_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_nvinfer_start (GstBaseTransform * btrans);
static gboolean gst_nvinfer_stop (GstBaseTransform * btrans);
static gboolean gst_nvinfer_sink_event (GstBaseTransform * trans,
GstEvent * event);
static GstFlowReturn gst_nvinfer_submit_input_buffer (GstBaseTransform *
btrans, gboolean discont, GstBuffer * inbuf);
static GstFlowReturn gst_nvinfer_generate_output (GstBaseTransform *
btrans, GstBuffer ** outbuf);
static gpointer gst_nvinfer_input_queue_loop (gpointer data);
static gpointer gst_nvinfer_output_loop (gpointer data);
static void gst_nvinfer_reset_init_params (GstNvInfer * nvinfer);
/* Create enum type for the process mode property. */
#define GST_TYPE_NVDSINFER_PROCESS_MODE (gst_nvinfer_process_mode_get_type ())
static GType
gst_nvinfer_process_mode_get_type (void)
{
static volatile gsize process_mode_type = 0;
static const GEnumValue process_mode[] = {
{PROCESS_MODEL_FULL_FRAME, "Primary (Full Frame)", "primary"},
{PROCESS_MODEL_OBJECTS, "Secondary (Objects)", "secondary"},
{0, nullptr, nullptr}
};
if (g_once_init_enter (&process_mode_type)) {
GType tmp = g_enum_register_static ("GstNvInferProcessModeType",
process_mode);
g_once_init_leave (&process_mode_type, tmp);
}
return (GType) process_mode_type;
}
static inline int
get_element_size (NvDsInferDataType data_type)
{
switch (data_type) {
case FLOAT:
return 4;
case HALF:
return 2;
case INT32:
return 4;
case INT8:
return 1;
default:
return 0;
}
}
/* Install properties, set sink and src pad capabilities, override the required
* functions of the base class, These are common to all instances of the
* element.
*/
static void
gst_nvinfer_class_init (GstNvInferClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
GstBaseTransformClass *gstbasetransform_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gstbasetransform_class = (GstBaseTransformClass *) klass;
/* Overide base class functions */
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_nvinfer_finalize);
gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_nvinfer_set_property);
gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_nvinfer_get_property);
gstbasetransform_class->start = GST_DEBUG_FUNCPTR (gst_nvinfer_start);
gstbasetransform_class->stop = GST_DEBUG_FUNCPTR (gst_nvinfer_stop);
gstbasetransform_class->sink_event =
GST_DEBUG_FUNCPTR (gst_nvinfer_sink_event);
gstbasetransform_class->submit_input_buffer =
GST_DEBUG_FUNCPTR (gst_nvinfer_submit_input_buffer);
gstbasetransform_class->generate_output =
GST_DEBUG_FUNCPTR (gst_nvinfer_generate_output);
/* Install properties. Values set through these properties override the ones in
* the config file. */
g_object_class_install_property (gobject_class, PROP_UNIQUE_ID,
g_param_spec_uint ("unique-id", "Unique ID",
"Unique ID for the element. Can be used to "
"identify output of the element", 0, G_MAXUINT, DEFAULT_UNIQUE_ID,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_PROCESS_MODE,
g_param_spec_enum ("process-mode", "Process Mode",
"Infer processing mode", GST_TYPE_NVDSINFER_PROCESS_MODE,
DEFAULT_PROCESS_MODE,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_CONFIG_FILE_PATH,
g_param_spec_string ("config-file-path", "Config File Path",
"Path to the configuration file for this instance of nvinfer",
DEFAULT_CONFIG_FILE_PATH,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_PLAYING)));
g_object_class_install_property (gobject_class, PROP_BATCH_SIZE,
g_param_spec_uint ("batch-size", "Batch Size",
"Maximum batch size for inference",
1, NVDSINFER_MAX_BATCH_SIZE, DEFAULT_BATCH_SIZE,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_INTERVAL,
g_param_spec_uint ("interval", "Interval",
"Specifies number of consecutive batches to be skipped for inference",
0, G_MAXINT, DEFAULT_INTERVAL,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OPERATE_ON_GIE_ID,
g_param_spec_int ("infer-on-gie-id", "Infer on Gie ID",
"Infer on metadata generated by GIE with this unique ID.\n"
"\t\t\tSet to -1 to infer on all metadata.",
-1, G_MAXINT, DEFAULT_OPERATE_ON_GIE_ID,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OPERATE_ON_CLASS_IDS,
g_param_spec_string ("infer-on-class-ids", "Operate on Class ids",
"Operate on objects with specified class ids\n"
"\t\t\tUse string with values of class ids in ClassID (int) to set the property.\n"
"\t\t\t e.g. 0:2:3",
"",
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property(gobject_class, PROP_FILTER_OUT_CLASS_IDS,
g_param_spec_string ("filter-out-class-ids", "Ignore metadata for class ids",
"Ignore metadata for objects of specified class ids\n"
"\t\t\tUse string with values of class ids in ClassID (int) to set the property.\n"
"\t\t\t e.g. 0;2;3",
"",
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_MODEL_ENGINEFILE,
g_param_spec_string ("model-engine-file", "Model Engine File",
"Absolute path to the pre-generated serialized engine file for the model",
"",
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_PLAYING)));
g_object_class_install_property (gobject_class, PROP_GPU_DEVICE_ID,
g_param_spec_uint ("gpu-id", "Set GPU Device ID",
"Set GPU Device ID",
0, G_MAXUINT, DEFAULT_GPU_DEVICE_ID,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OUTPUT_WRITE_TO_FILE,
g_param_spec_boolean ("raw-output-file-write", "Raw Output File Write",
"Write raw inference output to file",
DEFAULT_OUTPUT_WRITE_TO_FILE,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OUTPUT_CALLBACK,
g_param_spec_pointer ("raw-output-generated-callback",
"Raw Output Generated Callback",
"Pointer to the raw output generated callback funtion\n"
"\t\t\t(type: gst_nvinfer_raw_output_generated_callback in 'gstnvdsinfer.h')",
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OUTPUT_CALLBACK_USERDATA,
g_param_spec_pointer ("raw-output-generated-userdata",
"Raw Output Generated UserData",
"Pointer to the userdata to be supplied with raw output generated callback",
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OUTPUT_TENSOR_META,
g_param_spec_boolean ("output-tensor-meta", "Output Tensor Meta",
"Attach inference tensor outputs as buffer metadata",
DEFAULT_OUTPUT_TENSOR_META,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_OUTPUT_INSTANCE_MASK,
g_param_spec_boolean ("output-instance-mask", "Output Instance Mask",
"Instance mask expected in network output and attach it to metadata",
DEFAULT_OUTPUT_INSTANCE_MASK,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_INPUT_TENSOR_META,
g_param_spec_boolean ("input-tensor-meta", "Input Tensor Meta",
"Use preprocessed input tensors attached as metadata instead of preprocessing inside the plugin",
DEFAULT_INPUT_TENSOR_META,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
/** install signal MODEL_UPDATED */
gst_nvinfer_signals[SIGNAL_MODEL_UPDATED] =
g_signal_new ("model-updated",
G_TYPE_FROM_CLASS (klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GstNvInferClass, model_updated),
NULL, NULL, NULL,
G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_STRING);
/* Set sink and src pad capabilities */
gst_element_class_add_pad_template (gstelement_class,
gst_static_pad_template_get (&gst_nvinfer_src_template));
gst_element_class_add_pad_template (gstelement_class,
gst_static_pad_template_get (&gst_nvinfer_sink_template));
/* Set metadata describing the element */
gst_element_class_set_details_simple (gstelement_class, "NvInfer plugin",
"NvInfer Plugin",
"Nvidia DeepStreamSDK TensorRT plugin",
"NVIDIA Corporation. Deepstream for Tesla forum: "
"https://devtalk.nvidia.com/default/board/209");
}
static void
gst_nvinfer_init (GstNvInfer * nvinfer)
{
GstBaseTransform *btrans = GST_BASE_TRANSFORM (nvinfer);
/* We will not be generating a new buffer. Just adding / updating
* metadata. */
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (btrans), TRUE);
/* We do not want to change the input caps. Set to passthrough. transform_ip
* is still called. */
gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (btrans), TRUE);
nvinfer->impl = reinterpret_cast<GstNvInferImpl*>(new DsNvInferImpl(nvinfer));
DsNvInferImpl *impl = DS_NVINFER_IMPL (nvinfer);
/* Initialize all property variables to default values */
nvinfer->unique_id = DEFAULT_UNIQUE_ID;
nvinfer->process_full_frame = DEFAULT_PROCESS_MODE;
nvinfer->config_file_path = g_strdup (DEFAULT_CONFIG_FILE_PATH);
nvinfer->operate_on_class_ids = new std::vector < gboolean >;
nvinfer->filter_out_class_ids = new std::set<uint>;
nvinfer->output_tensor_meta = DEFAULT_OUTPUT_TENSOR_META;
nvinfer->output_instance_mask = DEFAULT_OUTPUT_INSTANCE_MASK;
nvinfer->max_batch_size = impl->m_InitParams->maxBatchSize =
DEFAULT_BATCH_SIZE;
nvinfer->interval = DEFAULT_INTERVAL;
nvinfer->operate_on_gie_id = DEFAULT_OPERATE_ON_GIE_ID;
nvinfer->gpu_id = impl->m_InitParams->gpuID = DEFAULT_GPU_DEVICE_ID;
nvinfer->is_prop_set = new std::vector < gboolean > (PROP_LAST, FALSE);
nvinfer->untracked_object_warn_pts = GST_CLOCK_TIME_NONE;
/* Set the default pre-processing transform params. */
nvinfer->transform_config_params.compute_mode = NvBufSurfTransformCompute_Default;
nvinfer->transform_params.transform_filter = NvBufSurfTransformInter_Default;
/* Create processing lock and condition for synchronization.*/
g_mutex_init (&nvinfer->process_lock);
g_cond_init (&nvinfer->process_cond);
/* This quark is required to identify NvDsMeta when iterating through
* the buffer metadatas */
if (!_dsmeta_quark)
_dsmeta_quark = g_quark_from_static_string (NVDS_META_STRING);
}
/* Free resources allocated during init. */
static void
gst_nvinfer_finalize (GObject * object)
{
GstNvInfer *nvinfer = GST_NVINFER (object);
g_mutex_clear (&nvinfer->process_lock);
g_cond_clear (&nvinfer->process_cond);
delete nvinfer->perClassDetectionFilterParams;
delete nvinfer->perClassColorParams;
delete nvinfer->is_prop_set;
g_free (nvinfer->config_file_path);
delete nvinfer->operate_on_class_ids;
delete nvinfer->filter_out_class_ids;
delete DS_NVINFER_IMPL(nvinfer);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
/* Function called when a property of the element is set. Standard boilerplate.
*/
static void
gst_nvinfer_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstNvInfer *nvinfer = GST_NVINFER (object);
DsNvInferImpl *impl = DS_NVINFER_IMPL (nvinfer);
if (prop_id < PROP_LAST) {
/* Mark the property as being set through g_object_set. */
(*nvinfer->is_prop_set)[prop_id] = TRUE;
}
switch (prop_id) {
case PROP_UNIQUE_ID:
impl->m_InitParams->uniqueID = nvinfer->unique_id =
g_value_get_uint (value);
break;
case PROP_PROCESS_MODE:
{
guint val = g_value_get_enum (value);
nvinfer->process_full_frame = (val == PROCESS_MODEL_FULL_FRAME);
}
break;
case PROP_CONFIG_FILE_PATH:
{
LockGMutex lock (nvinfer->process_lock);
const std::string cfg_path (g_value_get_string (value));
if (impl->isContextReady ()) {
/* A NvDsInferContext is being used. Trigger a new model update. */
impl->triggerNewModel (cfg_path, MODEL_LOAD_FROM_CONFIG);
break;
}
g_free (nvinfer->config_file_path);
nvinfer->config_file_path = g_value_dup_string (value);
gst_nvinfer_reset_init_params (nvinfer);
/* Parse the initialization parameters from the config file. This function
* gives preference to values set through the set_property function over
* the values set in the config file. */
nvinfer->config_file_parse_successful =
gst_nvinfer_parse_config_file (nvinfer, impl->m_InitParams.get(),
nvinfer->config_file_path);
}
break;
case PROP_OPERATE_ON_GIE_ID:
nvinfer->operate_on_gie_id = g_value_get_int (value);
break;
case PROP_OPERATE_ON_CLASS_IDS:
{
std::stringstream str (g_value_get_string (value));
std::vector < gint > class_ids;
gint max_class_id = -1;
while (str.peek () != EOF) {
gint class_id;
str >> class_id;
class_ids.push_back (class_id);
max_class_id = MAX (max_class_id, class_id);
str.get ();
}
nvinfer->operate_on_class_ids->assign (max_class_id + 1, FALSE);
for (auto & cid:class_ids)
nvinfer->operate_on_class_ids->at (cid) = TRUE;
}
break;
case PROP_FILTER_OUT_CLASS_IDS:
{
std::stringstream str(g_value_get_string(value));
nvinfer->filter_out_class_ids->clear();
while(str.peek() != EOF) {
gint class_id;
str >> class_id;
nvinfer->filter_out_class_ids->insert(class_id);
str.get();
}
}
break;
case PROP_BATCH_SIZE:
nvinfer->max_batch_size = impl->m_InitParams->maxBatchSize =
g_value_get_uint (value);
break;
case PROP_INTERVAL:
nvinfer->interval = g_value_get_uint (value);
break;
case PROP_MODEL_ENGINEFILE:
{
LockGMutex lock (nvinfer->process_lock);
const std::string engine_path (g_value_get_string (value));
if (impl->isContextReady ()) {
/* A NvDsInferContext is being used. Trigger a new model update. */
impl->triggerNewModel (engine_path, MODEL_LOAD_FROM_ENGINE);
break;
}
g_strlcpy (impl->m_InitParams->modelEngineFilePath,
g_value_get_string (value), _PATH_MAX);
}
break;
case PROP_GPU_DEVICE_ID:
nvinfer->gpu_id = impl->m_InitParams->gpuID = g_value_get_uint (value);
break;
case PROP_OUTPUT_WRITE_TO_FILE:
nvinfer->write_raw_buffers_to_file = g_value_get_boolean (value);
break;
case PROP_OUTPUT_CALLBACK:
nvinfer->output_generated_callback =
(gst_nvinfer_raw_output_generated_callback)
g_value_get_pointer (value);
break;
case PROP_OUTPUT_CALLBACK_USERDATA:
nvinfer->output_generated_userdata = g_value_get_pointer (value);
break;
case PROP_OUTPUT_TENSOR_META:
nvinfer->output_tensor_meta = g_value_get_boolean (value);
break;
case PROP_OUTPUT_INSTANCE_MASK:
nvinfer->output_instance_mask = g_value_get_boolean (value);
break;
case PROP_INPUT_TENSOR_META:
nvinfer->input_tensor_from_meta = g_value_get_boolean (value);
impl->m_InitParams->inputFromPreprocessedTensor =
g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* Function called when a property of the element is requested. Standard
* boilerplate.
*/
static void
gst_nvinfer_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
GstNvInfer *nvinfer = GST_NVINFER (object);
DsNvInferImpl *impl = DS_NVINFER_IMPL (nvinfer);
switch (prop_id) {
case PROP_UNIQUE_ID:
g_value_set_uint (value, nvinfer->unique_id);
break;
case PROP_PROCESS_MODE:
g_value_set_enum (value,
nvinfer->process_full_frame ? PROCESS_MODEL_FULL_FRAME :
PROCESS_MODEL_OBJECTS);
break;
case PROP_CONFIG_FILE_PATH:
g_value_set_string (value, nvinfer->config_file_path);
break;
case PROP_OPERATE_ON_GIE_ID:
g_value_set_int (value, nvinfer->operate_on_gie_id);
break;
case PROP_OPERATE_ON_CLASS_IDS:
{
std::stringstream str;
for (size_t i = 0; i < nvinfer->operate_on_class_ids->size (); i++) {
if (nvinfer->operate_on_class_ids->at (i))
str << i << ":";
}
g_value_set_string (value, str.str ().c_str ());
}
break;
case PROP_FILTER_OUT_CLASS_IDS:
{
std::stringstream str;
for(const auto id : *nvinfer->filter_out_class_ids)
str << id << ";";
g_value_set_string (value, str.str ().c_str ());
}
break;
case PROP_MODEL_ENGINEFILE:
g_value_set_string (value, impl->m_InitParams->modelEngineFilePath);
break;
case PROP_BATCH_SIZE:
g_value_set_uint (value, nvinfer->max_batch_size);
break;
case PROP_INTERVAL:
g_value_set_uint (value, nvinfer->interval);
break;
case PROP_GPU_DEVICE_ID:
g_value_set_uint (value, nvinfer->gpu_id);
break;
case PROP_OUTPUT_WRITE_TO_FILE:
g_value_set_boolean (value, nvinfer->write_raw_buffers_to_file);
break;
case PROP_OUTPUT_CALLBACK:
g_value_set_pointer (value,
(gpointer) nvinfer->output_generated_callback);
break;
case PROP_OUTPUT_CALLBACK_USERDATA:
g_value_set_pointer (value, nvinfer->output_generated_userdata);
break;
case PROP_OUTPUT_TENSOR_META:
g_value_set_boolean (value, nvinfer->output_tensor_meta);
break;
case PROP_OUTPUT_INSTANCE_MASK:
g_value_set_boolean (value, nvinfer->output_instance_mask);
break;
case PROP_INPUT_TENSOR_META:
g_value_set_boolean (value, nvinfer->input_tensor_from_meta);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
void gst_nvinfer_logger(NvDsInferContextHandle handle, unsigned int unique_id, NvDsInferLogLevel log_level,
const char* log_message, void* user_ctx) {
GstNvInfer* nvinfer = GST_NVINFER(user_ctx);
switch (log_level) {
case NVDSINFER_LOG_ERROR:
GST_ERROR_OBJECT(nvinfer, "NvDsInferContext[UID %d]: %s", unique_id, log_message);
return;
case NVDSINFER_LOG_WARNING:
GST_WARNING_OBJECT(nvinfer, "NvDsInferContext[UID %d]: %s", unique_id, log_message);
return;
case NVDSINFER_LOG_INFO:
GST_INFO_OBJECT(nvinfer, "NvDsInferContext[UID %d]: %s", unique_id, log_message);
return;
case NVDSINFER_LOG_DEBUG:
GST_DEBUG_OBJECT(nvinfer, "NvDsInferContext[UID %d]: %s", unique_id, log_message);
return;
}
}
/**
* Reset m_InitParams structure while preserving property values set through
* GObject set method. */
static void
gst_nvinfer_reset_init_params (GstNvInfer * nvinfer)
{
DsNvInferImpl *impl = DS_NVINFER_IMPL(nvinfer);
auto prev_params = std::move(impl->m_InitParams);
impl->m_InitParams.reset (new NvDsInferContextInitParams);
assert (impl->m_InitParams);
NvDsInferContext_ResetInitParams (impl->m_InitParams.get ());
if (nvinfer->is_prop_set->at (PROP_MODEL_ENGINEFILE))
g_strlcpy (impl->m_InitParams->modelEngineFilePath,
prev_params->modelEngineFilePath, _PATH_MAX);
if (nvinfer->is_prop_set->at (PROP_BATCH_SIZE))
impl->m_InitParams->maxBatchSize = prev_params->maxBatchSize;
if (nvinfer->is_prop_set->at (PROP_GPU_DEVICE_ID))
impl->m_InitParams->gpuID = prev_params->gpuID;
if (nvinfer->is_prop_set->at (PROP_UNIQUE_ID))
impl->m_InitParams->uniqueID = prev_params->uniqueID;
if (nvinfer->is_prop_set->at (PROP_INPUT_TENSOR_META))
impl->m_InitParams->inputFromPreprocessedTensor =
prev_params->inputFromPreprocessedTensor;
delete prev_params->perClassDetectionParams;
g_strfreev (prev_params->outputLayerNames);
g_strfreev (prev_params->outputIOFormats);
g_strfreev (prev_params->layerDevicePrecisions);
}
/**
* Called when an event is recieved on the sink pad. We need to make sure
* serialized events and buffers are pushed downstream while maintaining the order.
* To ensure this, we push all the buffers in the internal queue to the
* downstream element before forwarding the serialized event to the downstream element.
*/
static gboolean
gst_nvinfer_sink_event (GstBaseTransform * trans, GstEvent * event)
{
GstNvInfer *nvinfer = GST_NVINFER (trans);
gboolean ignore_serialized_event = FALSE;
/** The TAG event is sent many times leading to drop in performance because of
* buffer/event serialization. We can ignore such events which won't cause
* issues if we don't serialize the events. */
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_TAG:
ignore_serialized_event = TRUE;
break;
default:
break;
}
/* Serialize events. Wait for pending buffers to be processed and pushed
* downstream. No need to wait in case of classifier async mode since all
* the buffers are already pushed downstream. */
if (GST_EVENT_IS_SERIALIZED (event) && !ignore_serialized_event &&
!nvinfer->classifier_async_mode) {
GstNvInferBatch *batch = new GstNvInferBatch;
batch->event_marker = TRUE;
g_mutex_lock (&nvinfer->process_lock);
/* Push the event marker batch in the processing queue. */
if (nvinfer->input_queue_thread)
g_queue_push_tail (nvinfer->input_queue, batch);
else
g_queue_push_tail (nvinfer->process_queue, batch);
g_cond_broadcast (&nvinfer->process_cond);
/* Wait for all the remaining batches in the queue including the event
* marker to be processed. */
while (!g_queue_is_empty (nvinfer->input_queue)) {
g_cond_wait (&nvinfer->process_cond, &nvinfer->process_lock);
}
while (!g_queue_is_empty (nvinfer->process_queue)) {
g_cond_wait (&nvinfer->process_cond, &nvinfer->process_lock);
}
g_mutex_unlock (&nvinfer->process_lock);
}
if ((GstNvEventType) GST_EVENT_TYPE (event) == GST_NVEVENT_PAD_ADDED) {
/* New source added in the pipeline. Create a source info instance for it. */
guint source_id;
gst_nvevent_parse_pad_added (event, &source_id);
nvinfer->source_info->emplace (source_id, GstNvInferSourceInfo ());
}
if ((GstNvEventType) GST_EVENT_TYPE (event) == GST_NVEVENT_PAD_DELETED) {
/* Source removed from the pipeline. Remove the related structure. */
guint source_id;
gst_nvevent_parse_pad_deleted (event, &source_id);
nvinfer->source_info->erase (source_id);
}
if ((GstNvEventType) GST_EVENT_TYPE (event) == GST_NVEVENT_STREAM_EOS) {
/* Got EOS from a source. Clean up the object history map. */
guint source_id;
gst_nvevent_parse_stream_eos (event, &source_id);
auto result = nvinfer->source_info->find (source_id);
if (result != nvinfer->source_info->end ())
result->second.object_history_map.clear ();
}
if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
nvinfer->interval_counter = 0;
}
/* Call the sink event handler of the base class. */
return GST_BASE_TRANSFORM_CLASS (parent_class)->sink_event (trans, event);
}
/**
* Initialize all resources and start the output thread
*/
static gboolean
gst_nvinfer_start (GstBaseTransform * btrans)
{
GstNvInfer *nvinfer = GST_NVINFER (btrans);
GstAllocationParams allocation_params;
cudaError_t cudaReturn;
NvBufSurfaceColorFormat color_format;
NvDsInferStatus status;
std::string nvtx_str;
DsNvInferImpl *impl = DS_NVINFER_IMPL (nvinfer);
NvDsInferContextHandle infer_context = nullptr;
LockGMutex lock (nvinfer->process_lock);
NvDsInferContextInitParams *init_params = impl->m_InitParams.get ();
assert (init_params);
nvtx_str = "GstNvInfer: UID=" + std::to_string(nvinfer->unique_id);
auto nvtx_deleter = [](nvtxDomainHandle_t d) { nvtxDomainDestroy (d); };
std::unique_ptr<nvtxDomainRegistration, decltype(nvtx_deleter)> nvtx_domain_ptr (
nvtxDomainCreate(nvtx_str.c_str()), nvtx_deleter);
/* Providing a valid config file is mandatory. */
if (!nvinfer->config_file_path || strlen (nvinfer->config_file_path) == 0) {
GST_ELEMENT_ERROR (nvinfer, LIBRARY, SETTINGS,
("Configuration file not provided"), (nullptr));
return FALSE;
}
if (nvinfer->config_file_parse_successful == FALSE) {
GST_ELEMENT_ERROR (nvinfer, LIBRARY, SETTINGS,
("Configuration file parsing failed"),
("Config file path: %s", nvinfer->config_file_path));
return FALSE;
}
if (nvinfer->output_instance_mask == TRUE &&
init_params->clusterMode != NVDSINFER_CLUSTER_NONE)
{
GST_ELEMENT_ERROR (nvinfer, LIBRARY, SETTINGS,
("Instance mask output not supported with cluster mode %d",
init_params->clusterMode), (nullptr));
return FALSE;
}
nvinfer->interval_counter = 0;
/* Should not infer on objects smaller than MIN_INPUT_OBJECT_WIDTH x MIN_INPUT_OBJECT_HEIGHT
* since it will cause hardware scaling issues. */
nvinfer->min_input_object_width =
MAX(MIN_INPUT_OBJECT_WIDTH, nvinfer->min_input_object_width);
nvinfer->min_input_object_height =
MAX(MIN_INPUT_OBJECT_HEIGHT, nvinfer->min_input_object_height);
/* Ask NvDsInferContext to copy the input layer contents to host memory if
* CPU needs to access it. */
init_params->copyInputToHostBuffers =
(nvinfer->write_raw_buffers_to_file ||
(nvinfer->output_generated_callback != nullptr));
/* Set the number of output buffers that should be allocated by NvDsInferContext.
* Should allocate more buffers if the output tensor buffers will be attached
* as meta to GstBuffers and pushed downstream. */
init_params->outputBufferPoolSize = std::max<uint>(init_params->outputBufferPoolSize,
NVDSINFER_MIN_OUTPUT_BUFFERPOOL_SIZE);
if (nvinfer->output_tensor_meta || IS_SEGMENTATION_INSTANCE (nvinfer))
init_params->outputBufferPoolSize = std::max<uint>(init_params->outputBufferPoolSize,
NVDSINFER_CTX_OUT_POOL_SIZE_FLOW_META);
/* Create the NvDsInferContext instance. */
status =
createNvDsInferContext (&infer_context, *init_params,
nvinfer, gst_nvinfer_logger);
if (status != NVDSINFER_SUCCESS) {
GST_ELEMENT_ERROR (nvinfer, RESOURCE, FAILED,
("Failed to create NvDsInferContext instance"),
("Config file path: %s, NvDsInfer Error: %s", nvinfer->config_file_path,
NvDsInferStatus2Str (status)));
return FALSE;
}
std::unique_ptr<INvDsInferContext> ctx_ptr (infer_context);
/* Get the network resolution. */
ctx_ptr->getNetworkInfo (nvinfer->network_info);
nvinfer->network_width = nvinfer->network_info.width;
nvinfer->network_height = nvinfer->network_info.height;
/* Get information on all the bound layers. */
nvinfer->layers_info = new std::vector < NvDsInferLayerInfo > ();
ctx_ptr->fillLayersInfo (*nvinfer->layers_info);
nvinfer->output_layers_info = new std::vector < NvDsInferLayerInfo > ();
for (auto & layer:*(nvinfer->layers_info)) {
if (!layer.isInput)
nvinfer->output_layers_info->push_back (layer);
}
nvinfer->file_write_batch_num = 0;
/* Create process queue and input queue to transfer data between threads.
* We will be using this queue to maintain the list of frames/objects
* currently given to the algorithm for processing. */
nvinfer->process_queue = g_queue_new ();
nvinfer->input_queue = g_queue_new ();
/* Set the NvBufSurfTransform config parameters. */
nvinfer->transform_config_params.gpu_id = nvinfer->gpu_id;
nvinfer->transform_config_params.cuda_stream = nvinfer->convertStream;
NvBufSurfTransformSetSessionParams (&nvinfer->transform_config_params);
/* Based on the network input requirements decide the buffer pool color format. */
switch (init_params->networkInputFormat) {
case NvDsInferFormat_RGB:
case NvDsInferFormat_BGR:
if(nvinfer->transform_config_params.compute_mode == NvBufSurfTransformCompute_VIC) {
color_format = NVBUF_COLOR_FORMAT_RGBA;
}
else {
color_format = NVBUF_COLOR_FORMAT_RGB;
}
break;
case NvDsInferFormat_GRAY:
if(nvinfer->transform_config_params.compute_mode == NvBufSurfTransformCompute_VIC) {
color_format = NVBUF_COLOR_FORMAT_NV12;
}
else {
color_format = NVBUF_COLOR_FORMAT_GRAY8;
}
break;
default:
GST_ELEMENT_ERROR (nvinfer, LIBRARY, SETTINGS,
("Unsupported network input format: %d",
init_params->networkInputFormat), (nullptr));
return FALSE;
}
if (!nvinfer->input_tensor_from_meta) {
/* Create a buffer pool for internal memory required for scaling frames to
* network resolution / cropping objects. The pool allocates
* INTERNAL_BUF_POOL_SIZE buffers at start and keeps reusing them. */
auto pool_deleter = [](GstBufferPool *p) { if (p) gst_object_unref (p); };
std::unique_ptr<GstBufferPool, decltype(pool_deleter)> pool_ptr (
gst_buffer_pool_new (), pool_deleter);
auto config_deleter = [](GstStructure *s) { if (s) gst_structure_free (s); };
std::unique_ptr<GstStructure, decltype(config_deleter)> config_ptr (
gst_buffer_pool_get_config (pool_ptr.get()), config_deleter);
gst_buffer_pool_config_set_params (config_ptr.get(), nullptr,
sizeof (GstNvInferMemory), INTERNAL_BUF_POOL_SIZE, INTERNAL_BUF_POOL_SIZE);
/* Create a new GstNvInferAllocator instance. Allocator has methods to allocate
* and free custom memories. */
auto allocator_deleter = [](GstAllocator *a) { if (a) gst_object_unref (a); };
std::unique_ptr<GstAllocator, decltype(allocator_deleter)> allocator_ptr (
gst_nvinfer_allocator_new (nvinfer->network_width,
nvinfer->network_height, color_format, nvinfer->max_batch_size,
nvinfer->gpu_id),
allocator_deleter);
memset (&allocation_params, 0, sizeof (allocation_params));
gst_buffer_pool_config_set_allocator (config_ptr.get (), allocator_ptr.get (),
&allocation_params);
if (!gst_buffer_pool_set_config (pool_ptr.get(), config_ptr.get())) {
GST_ELEMENT_ERROR (nvinfer, RESOURCE, FAILED,
("Failed to set config on buffer pool"), (nullptr));
return FALSE;
}
config_ptr.release ();
/* Start the buffer pool and allocate all internal buffers. */
if (!gst_buffer_pool_set_active (pool_ptr.get(), TRUE)) {
GST_ELEMENT_ERROR (nvinfer, RESOURCE, FAILED,
("Failed to set buffer pool to active"), (nullptr));
return FALSE;
}
nvinfer->pool = pool_ptr.release ();
}
cudaReturn = cudaSetDevice (nvinfer->gpu_id);
if (cudaReturn != cudaSuccess) {
GST_ELEMENT_ERROR (nvinfer, RESOURCE, FAILED,
("Failed to set cuda device %d", nvinfer->gpu_id),
("cudaSetDevice failed with error %s", cudaGetErrorName (cudaReturn)));
return FALSE;
}
cudaReturn =
cudaStreamCreateWithFlags (&nvinfer->convertStream,
cudaStreamNonBlocking);
if (cudaReturn != cudaSuccess) {
GST_ELEMENT_ERROR (nvinfer, RESOURCE, FAILED,
("Failed to create cuda stream"),
("cudaStreamCreateWithFlags failed with error %s",
cudaGetErrorName (cudaReturn)));
return FALSE;
}
/* Create the intermediate NvBufSurface structure for holding an array of input
* NvBufSurfaceParams for batched transforms. */
nvinfer->tmp_surf.surfaceList = new NvBufSurfaceParams[nvinfer->max_batch_size];
nvinfer->tmp_surf.batchSize = nvinfer->max_batch_size;
nvinfer->tmp_surf.gpuId = nvinfer->gpu_id;
/* Set up the NvBufSurfTransformParams structure for batched transforms. */
nvinfer->transform_params.src_rect =
new NvBufSurfTransformRect[nvinfer->max_batch_size];
nvinfer->transform_params.dst_rect =
new NvBufSurfTransformRect[nvinfer->max_batch_size];
nvinfer->transform_params.transform_flag =
NVBUFSURF_TRANSFORM_FILTER | NVBUFSURF_TRANSFORM_CROP_SRC |
NVBUFSURF_TRANSFORM_CROP_DST;
nvinfer->transform_params.transform_flip = NvBufSurfTransform_None;
/* Initialize the object history map for source 0. */
nvinfer->source_info = new std::unordered_map < gint, GstNvInferSourceInfo >;
nvinfer->source_info->emplace (0, GstNvInferSourceInfo {
GstNvInferObjectHistoryMap (), 0}
);
if (nvinfer->classifier_async_mode) {
if (nvinfer->process_full_frame || !IS_CLASSIFIER_INSTANCE (nvinfer)) {
GST_ELEMENT_WARNING (nvinfer, LIBRARY, SETTINGS,
("NvInfer asynchronous mode is applicable for secondary"
"classifiers only. Turning off asynchronous mode"), (nullptr));
nvinfer->classifier_async_mode = FALSE;
}
}
/* Start a thread which will pop output from the algorithm, form NvDsMeta and
* push buffers to the next element. */
nvinfer->output_thread =
g_thread_new ("nvinfer-output-thread", gst_nvinfer_output_loop, nvinfer);
/* Start a thread which will queue input to the NvDsInfer context since
* queueInputBatch is a blocking function. This is done to parallelize
* input conversion and queueInputBatch. */