-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathvs_onnxruntime.cpp
1510 lines (1251 loc) · 47.5 KB
/
vs_onnxruntime.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
#include <array>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_set>
#include <variant>
#include <vector>
#if not __cpp_lib_atomic_wait
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
#endif
#include <VapourSynth.h>
#include <VSHelper.h>
#include <onnx/common/version.h>
#include <onnx/onnx_pb.h>
#define NOMINMAX
#include <onnxruntime_c_api.h>
#include <onnxruntime_run_options_config_keys.h>
#ifdef ENABLE_CUDA
#include <cuda_runtime.h>
#endif // ENABLE_CUDA
#ifdef ENABLE_DML
#include <dml_provider_factory.h>
#endif // ENABLE_DML
#include "../common/convert_float_to_float16.h"
#include "../common/onnx_utils.h"
#include "config.h"
#ifdef ENABLE_COREML
extern "C" OrtStatusPtr OrtSessionOptionsAppendExecutionProvider_CoreML(OrtSessionOptions *so, int flags);
#endif // ENABLE_COREML
#define checkError(expr) do { \
OrtStatusPtr __err = expr; \
if (__err) { \
const std::string message = ortapi->GetErrorMessage(__err); \
ortapi->ReleaseStatus(__err); \
return set_error("'"s + # expr + "' failed: " + message); \
} \
} while(0)
#ifdef ENABLE_CUDA
#define checkCUDAError(expr) do { \
if (cudaError_t result = expr; result != cudaSuccess) { \
const char * error_str = cudaGetErrorString(result); \
return set_error("'"s + # expr + "' failed: " + error_str); \
} \
} while(0)
#endif // ENABLE_CUDA
using namespace std::string_literals;
static const VSPlugin * myself = nullptr;
static const OrtApi * ortapi = nullptr;
static std::atomic<int64_t> logger_id = 0;
#if defined(ENABLE_CUDA) || defined(ENABLE_DML)
static std::mutex capture_lock;
#endif
// rename GridSample to com.microsoft::GridSample
// onnxruntime has support for CUDA-accelerated GridSample only in its own opset domain
static void rename(ONNX_NAMESPACE::ModelProto & model) {
#if ORT_API_VERSION < 18
constexpr auto ms_domain = "com.microsoft";
bool has_ms_opset = false;
for (const auto & opset : model.opset_import()) {
if (opset.has_domain() && opset.domain() == ms_domain) {
has_ms_opset = true;
break;
}
}
if (!has_ms_opset) {
ONNX_NAMESPACE::OperatorSetIdProto opset_id;
*opset_id.mutable_domain() = ms_domain;
opset_id.set_version(1);
*model.add_opset_import() = std::move(opset_id);
}
for (auto & node : *model.mutable_graph()->mutable_node()) {
if (node.has_op_type() && node.op_type() == "GridSample") {
*node.mutable_domain() = ms_domain;
}
}
#endif // ORT_API_VERSION < 18
}
[[nodiscard]]
static std::optional<std::string> ortInit() noexcept {
static std::once_flag ort_init_flag;
std::call_once(ort_init_flag, []() {
auto p = OrtGetApiBase();
if (p)
ortapi = p->GetApi(ORT_API_VERSION);
});
if (ortapi) {
return {};
} else {
return "ONNX Runtime initialization failed";
}
}
[[nodiscard]]
static std::variant<std::string, std::array<int64_t, 4>> getShape(
const OrtTensorTypeAndShapeInfo* tensor_info
) noexcept {
const auto set_error = [](const std::string & error_message) {
return error_message;
};
std::array<int64_t, 4> shape;
checkError(ortapi->GetDimensions(tensor_info, std::data(shape), std::size(shape)));
return shape;
}
[[nodiscard]]
static std::variant<std::string, std::array<int64_t, 4>> getShape(
const OrtSession * session,
bool input
) noexcept {
const auto set_error = [](const std::string & error_message) {
return error_message;
};
OrtTypeInfo * typeinfo;
if (input) {
checkError(ortapi->SessionGetInputTypeInfo(session, 0, &typeinfo));
} else {
checkError(ortapi->SessionGetOutputTypeInfo(session, 0, &typeinfo));
}
const OrtTensorTypeAndShapeInfo* tensor_info;
checkError(ortapi->CastTypeInfoToTensorInfo(typeinfo, &tensor_info));
auto maybe_shape = getShape(tensor_info);
ortapi->ReleaseTypeInfo(typeinfo);
if (std::holds_alternative<std::string>(maybe_shape)) {
return set_error(std::get<std::string>(maybe_shape));
}
return std::get<std::array<int64_t, 4>>(maybe_shape);
}
static size_t getNumBytes(int32_t type) {
using namespace ONNX_NAMESPACE;
switch (type) {
case TensorProto::FLOAT:
return 4;
case TensorProto::FLOAT16:
return 2;
default:
return 0;
}
}
static int numPlanes(
const std::vector<const VSVideoInfo *> & vis
) noexcept {
int num_planes = 0;
for (const auto & vi : vis) {
num_planes += vi->format->numPlanes;
}
return num_planes;
}
[[nodiscard]]
static std::optional<std::string> checkNodes(
const std::vector<const VSVideoInfo *> & vis
) noexcept {
for (const auto & vi : vis) {
if (vi->format->sampleType != stFloat) {
return "expects clip with floating-point type";
}
if (vi->format->bitsPerSample != 32 && vi->format->bitsPerSample != 16) {
return "expects clip with type fp32 or fp16";
}
if (vi->width != vis[0]->width || vi->height != vis[0]->height) {
return "dimensions of clips mismatch";
}
if (vi->numFrames != vis[0]->numFrames) {
return "number of frames mismatch";
}
if (vi->format->subSamplingH != 0 || vi->format->subSamplingW != 0) {
return "clip must not be sub-sampled";
}
}
return {};
}
[[nodiscard]]
static std::optional<std::string> checkIOInfo(
const OrtTypeInfo * info,
bool is_output,
bool flexible_output
) noexcept {
const auto set_error = [](const std::string & error_message) {
return error_message;
};
const OrtTensorTypeAndShapeInfo * tensor_info;
checkError(ortapi->CastTypeInfoToTensorInfo(info, &tensor_info));
ONNXTensorElementDataType element_type;
checkError(ortapi->GetTensorElementType(tensor_info, &element_type));
if (element_type != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT && element_type != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) {
return set_error("expects network IO with type fp32 or fp16");
}
size_t num_dims;
checkError(ortapi->GetDimensionsCount(tensor_info, &num_dims));
if (num_dims != 4) {
return set_error("expects network with 4-D IO");
}
auto maybe_shape = getShape(tensor_info);
if (std::holds_alternative<std::string>(maybe_shape)) {
return set_error(std::get<std::string>(maybe_shape));
}
auto shape = std::get<std::array<int64_t, 4>>(maybe_shape);
if (shape[0] != 1) {
return set_error("batch size of network must be 1");
}
if (is_output) {
int64_t out_channels = shape[1];
if (out_channels != 1 && out_channels != 3 && !flexible_output) {
return "output dimensions must be 1 or 3, or enable \"flexible_output\"";
}
}
return {};
}
[[nodiscard]]
static std::optional<std::string> checkSession(
const OrtSession * session,
bool flexible_output
) noexcept {
const auto set_error = [](const std::string & error_message) {
return error_message;
};
size_t num_inputs;
checkError(ortapi->SessionGetInputCount(session, &num_inputs));
if (num_inputs != 1) {
return set_error("network input count must be 1, got " + std::to_string(num_inputs));
}
OrtTypeInfo * input_type_info;
checkError(ortapi->SessionGetInputTypeInfo(session, 0, &input_type_info));
if (auto err = checkIOInfo(input_type_info, false, flexible_output); err.has_value()) {
return set_error(err.value());
}
ortapi->ReleaseTypeInfo(input_type_info);
size_t num_outputs;
checkError(ortapi->SessionGetOutputCount(session, &num_outputs));
if (num_outputs != 1) {
return "network output count must be 1, got " + std::to_string(num_outputs);
}
OrtTypeInfo * output_type_info;
checkError(ortapi->SessionGetOutputTypeInfo(session, 0, &output_type_info));
if (auto err = checkIOInfo(output_type_info, true, flexible_output); err.has_value()) {
return set_error(err.value());
}
ortapi->ReleaseTypeInfo(output_type_info);
return {};
}
[[nodiscard]]
static std::optional<std::string> checkNodesAndNetwork(
const OrtSession * session,
const std::vector<const VSVideoInfo *> & vis
) noexcept {
const auto set_error = [](const std::string & error_message) {
return error_message;
};
OrtTypeInfo * input_type_info;
checkError(ortapi->SessionGetInputTypeInfo(session, 0, &input_type_info));
const OrtTensorTypeAndShapeInfo * input_tensor_info;
checkError(ortapi->CastTypeInfoToTensorInfo(input_type_info, &input_tensor_info));
auto network_in_dims = std::get<std::array<int64_t, 4>>(getShape(input_tensor_info));
int network_in_channels = static_cast<int>(network_in_dims[1]);
int num_planes = numPlanes(vis);
if (network_in_channels != num_planes) {
return set_error("expects " + std::to_string(network_in_channels) + " input planes");
}
auto network_in_height = network_in_dims[2];
auto network_in_width = network_in_dims[3];
auto clip_in_height = vis.front()->height;
auto clip_in_width = vis.front()->width;
if (network_in_height > clip_in_height || network_in_width > clip_in_width) {
return set_error("tile size larger than clip dimension");
}
OrtTypeInfo * output_type_info;
checkError(ortapi->SessionGetOutputTypeInfo(session, 0, &output_type_info));
const OrtTensorTypeAndShapeInfo * output_tensor_info;
checkError(ortapi->CastTypeInfoToTensorInfo(output_type_info, &output_tensor_info));
auto network_out_dims = std::get<std::array<int64_t, 4>>(getShape(output_tensor_info));
auto network_out_height = network_out_dims[2];
auto network_out_width = network_out_dims[3];
if (network_out_height % network_in_height != 0 || network_out_width % network_in_width != 0) {
return set_error("output dimensions must be divisible by input dimensions");
}
ortapi->ReleaseTypeInfo(output_type_info);
ortapi->ReleaseTypeInfo(input_type_info);
return {};
}
static void setDimensions(
std::unique_ptr<VSVideoInfo> & vi,
const std::array<int64_t, 4> & input_shape,
const std::array<int64_t, 4> & output_shape,
VSCore * core,
const VSAPI * vsapi,
int32_t onnx_output_type,
bool flexible_output
) noexcept {
vi->height *= output_shape[2] / input_shape[2];
vi->width *= output_shape[3] / input_shape[3];
if (output_shape[1] == 1 || flexible_output) {
vi->format = vsapi->registerFormat(cmGray, stFloat, 8 * getNumBytes(onnx_output_type), 0, 0, core);
} else if (output_shape[1] == 3) {
vi->format = vsapi->registerFormat(cmRGB, stFloat, 8 * getNumBytes(onnx_output_type), 0, 0, core);
}
}
struct TicketSemaphore {
std::atomic<intptr_t> ticket {};
std::atomic<intptr_t> current {};
void acquire() noexcept {
intptr_t tk { ticket.fetch_add(1, std::memory_order_acquire) };
while (true) {
intptr_t curr { current.load(std::memory_order_acquire) };
if (tk <= curr) {
return;
}
#if __cpp_lib_atomic_wait
current.wait(curr, std::memory_order::relaxed);
#else // __cpp_lib_atomic_wait
std::this_thread::sleep_for(10ms);
#endif // __cpp_lib_atomic_wait
}
}
void release() noexcept {
current.fetch_add(1, std::memory_order_release);
#if __cpp_lib_atomic_wait
current.notify_all();
#endif // __cpp_lib_atomic_wait
}
};
enum class Backend {
CPU = 0,
CUDA = 1,
COREML = 2,
DML = 3
};
#ifdef ENABLE_CUDA
struct CUDA_Resource_t {
uint8_t * h_data;
uint8_t * d_data;
size_t size;
};
#endif // ENABLE_CUDA
// per-stream context
struct Resource {
OrtSession * session;
OrtValue * input_tensor;
OrtValue * output_tensor;
OrtIoBinding * binding;
char * input_name;
char * output_name;
#ifdef ENABLE_CUDA
cudaStream_t stream;
CUDA_Resource_t input;
CUDA_Resource_t output;
#endif // ENABLE_CUDA
#if defined(ENABLE_CUDA) || defined(ENABLE_DML)
bool require_replay;
#endif
};
struct vsOrtData {
std::vector<VSNodeRef *> nodes;
std::unique_ptr<VSVideoInfo> out_vi;
#ifdef ENABLE_COREML
bool ml_program;
#endif //ENABLE_COREML
int overlap_w, overlap_h;
OrtEnv * environment;
Backend backend;
int device_id;
std::vector<Resource> resources;
std::vector<int> tickets;
std::mutex ticket_lock;
TicketSemaphore semaphore;
std::string flexible_output_prop;
int acquire() noexcept {
semaphore.acquire();
{
std::lock_guard<std::mutex> lock(ticket_lock);
int ticket = tickets.back();
tickets.pop_back();
return ticket;
}
}
void release(int ticket) noexcept {
{
std::lock_guard<std::mutex> lock(ticket_lock);
tickets.push_back(ticket);
}
semaphore.release();
}
};
static void VS_CC vsOrtInit(
VSMap *in,
VSMap *out,
void **instanceData,
VSNode *node,
VSCore *core,
const VSAPI *vsapi
) noexcept {
auto d = static_cast<vsOrtData *>(*instanceData);
vsapi->setVideoInfo(d->out_vi.get(), 1, node);
}
static const VSFrameRef *VS_CC vsOrtGetFrame(
int n,
int activationReason,
void **instanceData,
void **frameData,
VSFrameContext *frameCtx,
VSCore *core,
const VSAPI *vsapi
) noexcept {
auto d = static_cast<vsOrtData *>(*instanceData);
if (activationReason == arInitial) {
for (const auto & node : d->nodes) {
vsapi->requestFrameFilter(n, node, frameCtx);
}
} else if (activationReason == arAllFramesReady) {
std::vector<const VSVideoInfo *> in_vis;
in_vis.reserve(std::size(d->nodes));
for (const auto & node : d->nodes) {
in_vis.emplace_back(vsapi->getVideoInfo(node));
}
std::vector<const VSFrameRef *> src_frames;
src_frames.reserve(std::size(d->nodes));
for (const auto & node : d->nodes) {
src_frames.emplace_back(vsapi->getFrameFilter(n, node, frameCtx));
}
auto src_stride = vsapi->getStride(src_frames.front(), 0);
auto src_width = vsapi->getFrameWidth(src_frames.front(), 0);
auto src_height = vsapi->getFrameHeight(src_frames.front(), 0);
auto src_bytes = vsapi->getFrameFormat(src_frames.front())->bytesPerSample;
VSFrameRef * const dst_frame = vsapi->newVideoFrame(
d->out_vi->format, d->out_vi->width, d->out_vi->height,
src_frames.front(), core
);
std::vector<VSFrameRef *> dst_frames;
auto dst_stride = vsapi->getStride(dst_frame, 0);
auto dst_bytes = vsapi->getFrameFormat(dst_frame)->bytesPerSample;
auto ticket = d->acquire();
Resource & resource = d->resources[ticket];
auto src_tile_shape = std::get<std::array<int64_t, 4>>(getShape(resource.session, true));
auto src_tile_h = src_tile_shape[2];
auto src_tile_w = src_tile_shape[3];
auto src_tile_w_bytes = src_tile_w * src_bytes;
auto src_tile_bytes = src_tile_h * src_tile_w_bytes;
std::vector<const uint8_t *> src_ptrs;
src_ptrs.reserve(src_tile_shape[1]);
for (unsigned i = 0; i < std::size(d->nodes); ++i) {
for (int j = 0; j < in_vis[i]->format->numPlanes; ++j) {
src_ptrs.emplace_back(vsapi->getReadPtr(src_frames[i], j));
}
}
auto step_w = src_tile_w - 2 * d->overlap_w;
auto step_h = src_tile_h - 2 * d->overlap_h;
auto dst_tile_shape = std::get<std::array<int64_t, 4>>(getShape(resource.session, false));
auto dst_tile_h = dst_tile_shape[2];
auto dst_tile_w = dst_tile_shape[3];
auto dst_tile_w_bytes = dst_tile_w * dst_bytes;
auto dst_tile_bytes = dst_tile_h * dst_tile_w_bytes;
auto dst_planes = dst_tile_shape[1];
std::vector<uint8_t *> dst_ptrs;
if (d->flexible_output_prop.empty()) {
for (int i = 0; i < dst_planes; ++i) {
dst_ptrs.emplace_back(vsapi->getWritePtr(dst_frame, i));
}
} else {
for (int i = 0; i < dst_planes; ++i) {
auto frame { vsapi->newVideoFrame(
d->out_vi->format, d->out_vi->width, d->out_vi->height,
src_frames[0], core
)};
dst_frames.emplace_back(frame);
dst_ptrs.emplace_back(vsapi->getWritePtr(frame, 0));
}
}
auto h_scale = dst_tile_h / src_tile_h;
auto w_scale = dst_tile_w / src_tile_w;
const auto set_error = [&](const std::string & error_message) {
vsapi->setFilterError(
(__func__ + ": "s + error_message).c_str(),
frameCtx
);
d->release(ticket);
for (const auto & frame : dst_frames) {
vsapi->freeFrame(frame);
}
vsapi->freeFrame(dst_frame);
for (const auto & frame : src_frames) {
vsapi->freeFrame(frame);
}
return nullptr;
};
OrtRunOptions * run_options {};
#ifdef ENABLE_CUDA
if (d->backend == Backend::CUDA) {
checkCUDAError(cudaSetDevice(d->device_id));
#if ORT_API_VERSION >= 16
checkError(ortapi->CreateRunOptions(&run_options));
if (run_options == nullptr) {
return set_error("create run_options failed");
}
checkError(ortapi->AddRunConfigEntry(
run_options,
kOrtRunOptionsConfigDisableSynchronizeExecutionProviders,
"1"
));
#endif // ORT_API_VERSION >= 16
}
#endif // ENABLE_CUDA
int y = 0;
while (true) {
int y_crop_start = (y == 0) ? 0 : d->overlap_h;
int y_crop_end = (y == src_height - src_tile_h) ? 0 : d->overlap_h;
int x = 0;
while (true) {
int x_crop_start = (x == 0) ? 0 : d->overlap_w;
int x_crop_end = (x == src_width - src_tile_w) ? 0 : d->overlap_w;
{
uint8_t * input_buffer;
#ifdef ENABLE_CUDA
uint8_t * h_input_buffer = resource.input.h_data;
#endif // ENABLE_CUDA
checkError(ortapi->GetTensorMutableData(
resource.input_tensor,
reinterpret_cast<void **>(&input_buffer)
));
for (const auto & _src_ptr : src_ptrs) {
const uint8_t * src_ptr { _src_ptr +
y * src_stride + x * src_bytes
};
#ifdef ENABLE_CUDA
if (d->backend == Backend::CUDA) {
vs_bitblt(
h_input_buffer, src_tile_w_bytes,
src_ptr, src_stride,
src_tile_w_bytes, src_tile_h
);
h_input_buffer += src_tile_bytes;
} else
#endif // ENABLE_CUDA
{
vs_bitblt(
input_buffer, src_tile_w_bytes,
src_ptr, src_stride,
src_tile_w_bytes, src_tile_h
);
input_buffer += src_tile_bytes;
}
}
}
#ifdef ENABLE_CUDA
if (d->backend == Backend::CUDA) {
checkCUDAError(cudaMemcpyAsync(
resource.input.d_data,
resource.input.h_data,
resource.input.size,
cudaMemcpyHostToDevice,
resource.stream
));
#if ORT_API_VERSION < 16
checkCUDAError(cudaStreamSynchronize(resource.stream));
#endif // ORT_API_VERSION < 16
}
#endif // ENABLE_CUDA
#if defined(ENABLE_CUDA) || defined(ENABLE_DML)
if (resource.require_replay) [[unlikely]] {
resource.require_replay = false;
// runs it under a global lock
// onnxruntime uses global-mode stream capture on a private stream
// this lock prevents concurrent capture sequences in other threads
//
// note that this applies only to stream capture from the ort library
// this fails when another plugin also uses global-mode stream capture
std::lock_guard _ { capture_lock };
if (d->backend == Backend::CUDA) {
checkError(ortapi->RunWithBinding(resource.session, run_options, resource.binding));
} else if (d->backend == Backend::DML) {
for (int i = 0; i < 2; i++) {
checkError(ortapi->Run(
resource.session,
run_options,
&resource.input_name,
&resource.input_tensor,
1,
&resource.output_name,
1,
&resource.output_tensor
));
}
}
// onnxruntime replays the graph itself in CUDAExecutionProvider::OnRunEnd
} else
#endif // defined(ENABLE_CUDA) || defined(ENABLE_DML)
if (d->backend == Backend::CPU || d->backend == Backend::CUDA) {
checkError(ortapi->RunWithBinding(resource.session, run_options, resource.binding));
} else {
checkError(ortapi->Run(
resource.session,
run_options,
&resource.input_name,
&resource.input_tensor,
1,
&resource.output_name,
1,
&resource.output_tensor
));
}
#ifdef ENABLE_CUDA
if (d->backend == Backend::CUDA) {
checkCUDAError(cudaMemcpyAsync(
resource.output.h_data,
resource.output.d_data,
resource.output.size,
cudaMemcpyDeviceToHost,
resource.stream
));
checkCUDAError(cudaStreamSynchronize(resource.stream));
}
#endif // ENABLE_CUDA
{
uint8_t * output_buffer;
#ifdef ENABLE_CUDA
uint8_t * h_output_buffer = resource.output.h_data;
#endif // ENABLE_CUDA
checkError(ortapi->GetTensorMutableData(
resource.output_tensor,
reinterpret_cast<void **>(&output_buffer)
));
for (int plane = 0; plane < dst_planes; ++plane) {
auto dst_ptr = (dst_ptrs[plane] +
h_scale * y * dst_stride + w_scale * x * dst_bytes
);
#ifdef ENABLE_CUDA
if (d->backend == Backend::CUDA) {
vs_bitblt(
dst_ptr + (y_crop_start * dst_stride + x_crop_start * dst_bytes),
dst_stride,
h_output_buffer + (y_crop_start * dst_tile_w_bytes + x_crop_start * dst_bytes),
dst_tile_w_bytes,
dst_tile_w_bytes - (x_crop_start + x_crop_end) * dst_bytes,
dst_tile_h - (y_crop_start + y_crop_end)
);
h_output_buffer += dst_tile_bytes;
} else
#endif // ENABLE_CUDA
{
vs_bitblt(
dst_ptr + (y_crop_start * dst_stride + x_crop_start * dst_bytes),
dst_stride,
output_buffer + (y_crop_start * dst_tile_w_bytes + x_crop_start * dst_bytes),
dst_tile_w_bytes,
dst_tile_w_bytes - (x_crop_start + x_crop_end) * dst_bytes,
dst_tile_h - (y_crop_start + y_crop_end)
);
output_buffer += dst_tile_bytes;
}
}
}
if (x + src_tile_w == src_width) {
break;
}
x = std::min(x + step_w, src_width - src_tile_w);
}
if (y + src_tile_h == src_height) {
break;
}
y = std::min(y + step_h, src_height - src_tile_h);
}
if (run_options) {
ortapi->ReleaseRunOptions(run_options);
}
d->release(ticket);
for (const auto & frame : src_frames) {
vsapi->freeFrame(frame);
}
if (!d->flexible_output_prop.empty()) {
auto prop = vsapi->getFramePropsRW(dst_frame);
for (int i = 0; i < dst_planes; i++) {
auto key { d->flexible_output_prop + std::to_string(i) };
vsapi->propSetFrame(prop, key.c_str(), dst_frames[i], paReplace);
vsapi->freeFrame(dst_frames[i]);
}
}
return dst_frame;
}
return nullptr;
}
static void VS_CC vsOrtFree(
void *instanceData,
VSCore *core,
const VSAPI *vsapi
) noexcept {
auto d = static_cast<vsOrtData *>(instanceData);
for (const auto & node : d->nodes) {
vsapi->freeNode(node);
}
for (const auto & resource : d->resources) {
ortapi->ReleaseIoBinding(resource.binding);
ortapi->ReleaseValue(resource.output_tensor);
ortapi->ReleaseValue(resource.input_tensor);
ortapi->ReleaseSession(resource.session);
#ifdef ENABLE_CUDA
if (d->backend == Backend::CUDA) {
cudaStreamDestroy(resource.stream);
cudaFreeHost(resource.input.h_data);
cudaFree(resource.input.d_data);
cudaFreeHost(resource.output.h_data);
cudaFree(resource.output.d_data);
}
#endif // ENABLE_CUDA
}
ortapi->ReleaseEnv(d->environment);
delete d;
}
static void VS_CC vsOrtCreate(
const VSMap *in,
VSMap *out,
void *userData,
VSCore *core,
const VSAPI *vsapi
) noexcept {
auto d { std::make_unique<vsOrtData>() };
int num_nodes = vsapi->propNumElements(in, "clips");
d->nodes.reserve(num_nodes);
for (int i = 0; i < num_nodes; ++i) {
d->nodes.emplace_back(vsapi->propGetNode(in, "clips", i, nullptr));
}
auto set_error = [&](const std::string & error_message) {
vsapi->setError(out, (__func__ + ": "s + error_message).c_str());
for (const auto & node : d->nodes) {
vsapi->freeNode(node);
}
};
std::vector<const VSVideoInfo *> in_vis;
in_vis.reserve(std::size(d->nodes));
for (const auto & node : d->nodes) {
in_vis.emplace_back(vsapi->getVideoInfo(node));
}
if (auto err = checkNodes(in_vis); err.has_value()) {
return set_error(err.value());
}
d->out_vi = std::make_unique<VSVideoInfo>(*in_vis.front()); // mutable
int error;
d->device_id = int64ToIntS(vsapi->propGetInt(in, "device_id", 0, &error));
if (error) {
d->device_id = 0;
}
auto verbosity = static_cast<OrtLoggingLevel>(
vsapi->propGetInt(in, "verbosity", 0, &error)
);
if (error) {
verbosity = ORT_LOGGING_LEVEL_WARNING;
}
#ifdef ENABLE_COREML
auto ml_program = vsapi->propGetInt(in, "ml_program", 0, &error);
if (error) {
d->ml_program = false;
} else if (ml_program == 0) {
d->ml_program = false;
} else if (ml_program == 1) {
d->ml_program = true;
} else {
return set_error("\"ml_program\" must be 0 or 1");
}
#endif //ENABLE_COREML
// match verbosity of vs-trt
verbosity = static_cast<OrtLoggingLevel>(4 - static_cast<int>(verbosity));
int error1, error2;
d->overlap_w = int64ToIntS(vsapi->propGetInt(in, "overlap", 0, &error1));
d->overlap_h = int64ToIntS(vsapi->propGetInt(in, "overlap", 1, &error2));
if (!error1) {
if (error2) {
d->overlap_h = d->overlap_w;
}
if (d->overlap_w < 0 || d->overlap_h < 0) {
return set_error("\"overlap\" must be non-negative");
}
} else {
d->overlap_w = 0;
d->overlap_h = 0;
}
size_t tile_w = static_cast<size_t>(vsapi->propGetInt(in, "tilesize", 0, &error1));
size_t tile_h = static_cast<size_t>(vsapi->propGetInt(in, "tilesize", 1, &error2));
if (!error1) { // manual specification triggered
if (error2) {
tile_h = tile_w;
}
} else {
if (d->overlap_w != 0 || d->overlap_h != 0) {
return set_error("\"tilesize\" must be specified");
}
// set tile size to video dimensions
tile_w = in_vis.front()->width;
tile_h = in_vis.front()->height;
}
if (tile_w - 2 * d->overlap_w <= 0 || tile_h - 2 * d->overlap_h <= 0) {
return set_error("\"overlap\" too large");
}
const char * provider = vsapi->propGetData(in, "provider", 0, &error);
if (error) {
provider = "";
}
if (strlen(provider) == 0 || strcmp(provider, "CPU") == 0) {
d->backend = Backend::CPU;
#ifdef ENABLE_CUDA
} else if (strcmp(provider, "CUDA") == 0) {
checkCUDAError(cudaSetDevice(d->device_id));
d->backend = Backend::CUDA;
#endif // ENABLE_CUDA
#ifdef ENABLE_COREML