forked from zhouyuchong/gst-nvinfer-custom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gstnvinfer.cpp
2920 lines (2542 loc) · 107 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-2022, 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 <iostream>
#include <cmath>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#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_yaml_parser.h"
#include "gstnvinfer_property_parser.h"
#include "gstnvinfer_impl.h"
using namespace gstnvinfer;
using namespace nvdsinfer;
// ==========================ALIGN PREPROCESS=========================
// ========================== PART 1 =========================
// default_array use the norm landmarks arcface_src from
// https://github.com/deepinsight/insightface/blob/master/python-package/insightface/utils/face_align.py
float default_array[5][2] = {
{38.2946f+8.0f, 51.6963f},
{73.5318f+8.0f, 51.5014f},
{56.0252f+8.0f, 71.7366f},
{41.5493f+8.0f, 92.3655f},
{70.7299f+8.0f, 92.2041f}
};
float detect[5][2]={0};
// FacePreprocess defines some basic functions
// to generate the similar-transform matrix
namespace FacePreprocess {
cv::Mat meanAxis0(const cv::Mat &src)
{
int num = src.rows;
int dim = src.cols;
// x1 y1
// x2 y2
cv::Mat output(1,dim,CV_32F);
for(int i = 0 ; i < dim; i ++)
{
float sum = 0 ;
for(int j = 0 ; j < num ; j++)
{
sum+=src.at<float>(j,i);
}
output.at<float>(0,i) = sum/num;
}
return output;
}
cv::Mat elementwiseMinus(const cv::Mat &A,const cv::Mat &B)
{
cv::Mat output(A.rows,A.cols,A.type());
assert(B.cols == A.cols);
if(B.cols == A.cols)
{
for(int i = 0 ; i < A.rows; i ++)
{
for(int j = 0 ; j < B.cols; j++)
{
output.at<float>(i,j) = A.at<float>(i,j) - B.at<float>(0,j);
}
}
}
return output;
}
cv::Mat varAxis0(const cv::Mat &src) {
cv::Mat temp_ = elementwiseMinus(src,meanAxis0(src));
cv::multiply(temp_ ,temp_ ,temp_ );
return meanAxis0(temp_);
}
int MatrixRank(cv::Mat M)
{
cv::Mat w, u, vt;
cv::SVD::compute(M, w, u, vt);
cv::Mat1b nonZeroSingularValues = w > 0.0001;
int rank = countNonZero(nonZeroSingularValues);
return rank;
}
cv::Mat similarTransform(cv::Mat src,cv::Mat dst) {
int num = src.rows;
int dim = src.cols;
cv::Mat src_mean = meanAxis0(src);
cv::Mat dst_mean = meanAxis0(dst);
cv::Mat src_demean = elementwiseMinus(src, src_mean);
cv::Mat dst_demean = elementwiseMinus(dst, dst_mean);
cv::Mat A = (dst_demean.t() * src_demean) / static_cast<float>(num);
cv::Mat d(dim, 1, CV_32F);
d.setTo(1.0f);
if (cv::determinant(A) < 0) {
d.at<float>(dim - 1, 0) = -1;
}
cv::Mat T = cv::Mat::eye(dim + 1, dim + 1, CV_32F);
cv::Mat U, S, V;
// the SVD function in opencv differ from scipy .
cv::SVD::compute(A, S,U, V);
int rank = MatrixRank(A);
if (rank == 0) {
assert(rank == 0);
} else if (rank == dim - 1) {
if (cv::determinant(U) * cv::determinant(V) > 0) {
T.rowRange(0, dim).colRange(0, dim) = U * V;
} else {
// s = d[dim - 1]
// d[dim - 1] = -1
// T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V))
// d[dim - 1] = s
int s = d.at<float>(dim - 1, 0) = -1;
d.at<float>(dim - 1, 0) = -1;
T.rowRange(0, dim).colRange(0, dim) = U * V;
cv::Mat diag_ = cv::Mat::diag(d);
cv::Mat twp = diag_*V; //np.dot(np.diag(d), V.T)
cv::Mat B = cv::Mat::zeros(3, 3, CV_8UC1);
cv::Mat C = B.diag(0);
T.rowRange(0, dim).colRange(0, dim) = U* twp;
d.at<float>(dim - 1, 0) = s;
}
}
else{
cv::Mat diag_ = cv::Mat::diag(d);
cv::Mat twp = diag_*V.t(); //np.dot(np.diag(d), V.T)
cv::Mat res = U* twp; // U
T.rowRange(0, dim).colRange(0, dim) = -U.t()* twp;
}
cv::Mat var_ = varAxis0(src_demean);
float val = cv::sum(var_).val[0];
cv::Mat res;
cv::multiply(d,S,res);
float scale = 1.0/val*cv::sum(res).val[0];
T.rowRange(0, dim).colRange(0, dim) = - T.rowRange(0, dim).colRange(0, dim).t();
cv::Mat temp1 = T.rowRange(0, dim).colRange(0, dim); // T[:dim, :dim]
cv::Mat temp2 = src_mean.t(); //src_mean.T
cv::Mat temp3 = temp1*temp2; // np.dot(T[:dim, :dim], src_mean.T)
cv::Mat temp4 = scale*temp3;
T.rowRange(0, dim).colRange(dim, dim+1)= -(temp4 - dst_mean.t()) ;
T.rowRange(0, dim).colRange(0, dim) *= scale;
return T;
}
}
// ====================================================================
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_ALIGNMENT -1
#define DEFAULT_USER_META -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_ALIGNMENT,
g_param_spec_int ("alignment-preprocess", "alignment",
"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_ALIGNMENT,
(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
GST_PARAM_MUTABLE_READY)));
g_object_class_install_property (gobject_class, PROP_USER_META,
g_param_spec_int ("usermeta", "tensor-output",
"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_USER_META,
(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->alignment = DEFAULT_ALIGNMENT;
nvinfer->user_meta = DEFAULT_USER_META;
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. */
if (g_str_has_suffix(nvinfer->config_file_path, ".yml") ||
g_str_has_suffix(nvinfer->config_file_path, ".yaml")) {
nvinfer->config_file_parse_successful =
gst_nvinfer_parse_config_file_yaml (nvinfer, impl->m_InitParams.get(),
nvinfer->config_file_path);
} else {
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_ALIGNMENT:
nvinfer->alignment = g_value_get_int (value);
break;
case PROP_USER_META:
nvinfer->user_meta = 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_ALIGNMENT:
g_value_set_int (value, nvinfer->alignment);
break;
case PROP_USER_META:
g_value_set_int (value, nvinfer->user_meta);
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);