-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAI_S-R_ONNX.cpp
More file actions
2472 lines (2288 loc) · 102 KB
/
Copy pathAI_S-R_ONNX.cpp
File metadata and controls
2472 lines (2288 loc) · 102 KB
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
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <filesystem>
#include <mutex>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <memory>
#include <limits>
#include <thread>
#include <condition_variable>
#include <functional>
#include <fstream>
#include <sstream>
#include <chrono>
#include <robuffer.h>
#include <d3d11.h>
#include <dxgi1_6.h>
#include <windows.graphics.directx.direct3d11.interop.h>
#include "filter2.h"
#include <wrl/client.h>
#include <winrt/base.h>
#include <winrt/Windows.AI.MachineLearning.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Graphics.h>
#include <winrt/Windows.Graphics.DirectX.Direct3D11.h>
#include <winrt/Windows.Storage.Streams.h>
namespace ml = winrt::Windows::AI::MachineLearning;
namespace wfc = winrt::Windows::Foundation::Collections;
namespace wg = winrt::Windows::Graphics;
namespace wgdx11 = winrt::Windows::Graphics::DirectX::Direct3D11;
namespace wss = winrt::Windows::Storage::Streams;
using Microsoft::WRL::ComPtr;
static uint16_t FloatToHalfBits(float value);
static float HalfBitsToFloat(uint16_t value);
struct __declspec(uuid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")) IMemoryBufferByteAccess : ::IUnknown {
virtual HRESULT __stdcall GetBuffer(BYTE** value, UINT32* capacity) = 0;
};
static wchar_t g_backend_label_auto[256] = L"GPU優先(自動)";
static wchar_t g_backend_label_gpu0[256] = L"GPU 0";
static wchar_t g_backend_label_gpu1[256] = L"GPU 1";
static wchar_t g_backend_label_cpu[256] = L"CPU固定";
static FILTER_ITEM_SELECT::ITEM g_backend_items[] = {
{ g_backend_label_auto, 0 },
{ g_backend_label_gpu0, 1 },
{ g_backend_label_gpu1, 2 },
{ g_backend_label_cpu, 3 },
{ nullptr }
};
static auto g_backend = FILTER_ITEM_SELECT(L"推論デバイス", 0, g_backend_items);
static auto g_enable = FILTER_ITEM_CHECK(L"有効", true);
static auto g_model_file = FILTER_ITEM_FILE(L"ONNXファイル", L"", L"ONNX Model (*.onnx)\0*.onnx\0All Files (*.*)\0*.*\0");
static void* g_items[] = {
&g_backend,
&g_enable,
&g_model_file,
nullptr
};
static std::wstring GetPluginLogPath() {
HMODULE hm = nullptr;
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&GetPluginLogPath), &hm)) {
wchar_t module_path[MAX_PATH] = {};
if (GetModuleFileNameW(hm, module_path, MAX_PATH)) {
std::filesystem::path p(module_path);
return (p.parent_path() / L"AI_S-R_ONNX.log").wstring();
}
}
return L"AI_S-R_ONNX.log";
}
static void AppendLogLine(const std::wstring& text) {
(void)text;
}
static void DebugOut(const wchar_t* text) {
#ifdef _DEBUG
OutputDebugStringW(text ? text : L"");
OutputDebugStringW(L"\n");
#else
(void)text;
#endif
if (text) AppendLogLine(text);
}
static void DebugOutHotPath(const wchar_t* text) {
#ifdef _DEBUG
OutputDebugStringW(text ? text : L"");
OutputDebugStringW(L"\n");
#else
(void)text;
#endif
// hot pathでは通常ログファイルへ追記しない
}
static std::wstring TrimNullTerminated(const wchar_t* s) {
if (!s) return {};
return std::wstring(s);
}
static std::wstring GetConfiguredModelPath() {
return TrimNullTerminated(g_model_file.value);
}
static bool FileExists(const std::wstring& path) {
DWORD attr = GetFileAttributesW(path.c_str());
return attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY);
}
static std::wstring HResultErrorToString(const winrt::hresult_error& e) {
std::wstring msg = L"HRESULT 0x";
wchar_t buf[32] = {};
swprintf_s(buf, L"%08X", static_cast<uint32_t>(e.code().value));
msg += buf;
if (!e.message().empty()) {
msg += L": ";
msg += e.message().c_str();
}
return msg;
}
// Lookup tables for lossless 8-bit input normalization and FP16 output restore.
struct ScalarLUTs {
float f32[256];
uint16_t f16[256];
uint8_t half_to_u8[65536];
ScalarLUTs() {
constexpr float kInv255 = 1.0f / 255.0f;
for (int i = 0; i < 256; ++i) {
const float v = static_cast<float>(i) * kInv255;
f32[i] = v;
f16[i] = FloatToHalfBits(v);
}
for (int i = 0; i < 65536; ++i) {
float v = HalfBitsToFloat(static_cast<uint16_t>(i));
v = std::clamp(v, 0.0f, 1.0f) * 255.0f;
half_to_u8[i] = static_cast<uint8_t>(v + 0.5f);
}
}
};
static const ScalarLUTs& GetScalarLUTs() {
static const ScalarLUTs luts;
return luts;
}
static inline uint8_t FastClampToU8(float v) {
if (v <= 0.0f) return 0;
if (v >= 1.0f) return 255;
return static_cast<uint8_t>(v * 255.0f + 0.5f);
}
static inline float Clamp01(float v) {
if (v <= 0.0f) return 0.0f;
if (v >= 1.0f) return 1.0f;
return v;
}
static inline float PixelLuma01(const PIXEL_RGBA& p) {
return (0.299f * static_cast<float>(p.r) + 0.587f * static_cast<float>(p.g) + 0.114f * static_cast<float>(p.b)) * (1.0f / 255.0f);
}
static inline float PixelCb01(const PIXEL_RGBA& p) {
const float y = PixelLuma01(p);
const float b = static_cast<float>(p.b) * (1.0f / 255.0f);
return Clamp01((b - y) / 1.772f + 0.5f);
}
static inline float PixelCr01(const PIXEL_RGBA& p) {
const float y = PixelLuma01(p);
const float r = static_cast<float>(p.r) * (1.0f / 255.0f);
return Clamp01((r - y) / 1.402f + 0.5f);
}
static int ChooseMinRowsPerTask(int w, int h) {
const int pixels = w * h;
if (pixels <= 640 * 480) return 24;
if (pixels <= 960 * 540) return 32;
if (pixels <= 1280 * 720) return 40;
if (pixels <= 1920 * 1080) return 48;
return 64;
}
// Small persistent row-based thread pool to avoid per-frame thread creation overhead.
class RowThreadPool {
public:
static RowThreadPool& Instance() {
static RowThreadPool pool;
return pool;
}
template<class Fn>
void ParallelForRows(int rows, int min_rows_per_task, Fn&& fn) {
if (rows <= 0) return;
if (worker_count_ <= 1 || rows < min_rows_per_task * 2) {
fn(0, rows);
return;
}
std::function<void(int, int)> task = std::forward<Fn>(fn);
{
std::unique_lock<std::mutex> lock(mutex_);
current_task_ = std::move(task);
total_rows_ = rows;
next_row_ = 0;
chunk_rows_ = std::max(min_rows_per_task, rows / static_cast<int>(worker_count_ * 2));
active_workers_ = worker_count_ - 1;
generation_++;
}
cv_start_.notify_all();
RunChunks(current_task_, rows, chunk_rows_);
std::unique_lock<std::mutex> lock(mutex_);
cv_done_.wait(lock, [&]() { return active_workers_ == 0; });
current_task_ = nullptr;
}
private:
RowThreadPool() {
unsigned hc = std::thread::hardware_concurrency();
worker_count_ = hc > 1 ? hc : 1;
if (worker_count_ > 8) worker_count_ = 8;
if (worker_count_ <= 1) return;
threads_.reserve(worker_count_ - 1);
for (unsigned i = 0; i + 1 < worker_count_; ++i) {
threads_.emplace_back([this]() { ThreadMain(); });
}
}
~RowThreadPool() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
generation_++;
}
cv_start_.notify_all();
for (auto& t : threads_) {
if (t.joinable()) t.join();
}
}
void ThreadMain() {
uint64_t seen_generation = 0;
for (;;) {
std::function<void(int, int)> task;
int rows = 0;
int chunk = 0;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_start_.wait(lock, [&]() { return stopping_ || generation_ != seen_generation; });
if (stopping_) return;
seen_generation = generation_;
task = current_task_;
rows = total_rows_;
chunk = chunk_rows_;
}
RunChunks(task, rows, chunk);
{
std::lock_guard<std::mutex> lock(mutex_);
if (--active_workers_ == 0) cv_done_.notify_one();
}
}
}
void RunChunks(const std::function<void(int, int)>& task, int rows, int chunk) {
for (;;) {
int begin = 0;
int end = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
begin = next_row_;
if (begin >= rows) break;
end = std::min(rows, begin + chunk);
next_row_ = end;
}
task(begin, end);
}
}
private:
unsigned worker_count_ = 1;
std::vector<std::thread> threads_;
std::mutex mutex_;
std::condition_variable cv_start_;
std::condition_variable cv_done_;
std::function<void(int, int)> current_task_;
int total_rows_ = 0;
int next_row_ = 0;
int chunk_rows_ = 0;
unsigned active_workers_ = 0;
uint64_t generation_ = 0;
bool stopping_ = false;
};
static uint16_t FloatToHalfBits(float value) {
uint32_t bits = 0;
std::memcpy(&bits, &value, sizeof(bits));
const uint32_t sign = (bits >> 16) & 0x8000u;
int32_t exp = static_cast<int32_t>((bits >> 23) & 0xffu) - 127 + 15;
uint32_t mant = bits & 0x007fffffu;
if (exp <= 0) {
if (exp < -10) return static_cast<uint16_t>(sign);
mant |= 0x00800000u;
const uint32_t shifted = mant >> static_cast<uint32_t>(1 - exp);
return static_cast<uint16_t>(sign | ((shifted + 0x00001000u) >> 13));
}
if (exp >= 31) {
return static_cast<uint16_t>(sign | 0x7c00u | (mant ? 0x0200u : 0u));
}
return static_cast<uint16_t>(sign | (static_cast<uint32_t>(exp) << 10) | ((mant + 0x00001000u) >> 13));
}
static float HalfBitsToFloat(uint16_t value) {
const uint32_t sign = (static_cast<uint32_t>(value & 0x8000u)) << 16;
uint32_t exp = (value >> 10) & 0x1fu;
uint32_t mant = value & 0x03ffu;
uint32_t bits = 0;
if (exp == 0) {
if (mant == 0) {
bits = sign;
} else {
exp = 1;
while ((mant & 0x0400u) == 0) {
mant <<= 1;
--exp;
}
mant &= 0x03ffu;
bits = sign | ((exp + (127 - 15)) << 23) | (mant << 13);
}
} else if (exp == 31) {
bits = sign | 0x7f800000u | (mant << 13);
} else {
bits = sign | ((exp + (127 - 15)) << 23) | (mant << 13);
}
float out = 0.0f;
std::memcpy(&out, &bits, sizeof(out));
return out;
}
static std::wstring GetPluginDirectoryPath() {
HMODULE hm = nullptr;
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&GetPluginDirectoryPath), &hm)) {
wchar_t module_path[MAX_PATH] = {};
if (GetModuleFileNameW(hm, module_path, MAX_PATH)) {
return std::filesystem::path(module_path).parent_path().wstring();
}
}
return std::filesystem::current_path().wstring();
}
static uint64_t HashPathAndTime(const std::wstring& path) {
uint64_t h = 1469598103934665603ull;
auto mix = [&](uint64_t v) {
for (int i = 0; i < 8; ++i) {
h ^= static_cast<uint8_t>((v >> (i * 8)) & 0xffu);
h *= 1099511628211ull;
}
};
for (wchar_t c : path) {
h ^= static_cast<uint16_t>(c);
h *= 1099511628211ull;
}
WIN32_FILE_ATTRIBUTE_DATA fad{};
if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fad)) {
mix((static_cast<uint64_t>(fad.nFileSizeHigh) << 32) | fad.nFileSizeLow);
mix((static_cast<uint64_t>(fad.ftLastWriteTime.dwHighDateTime) << 32) | fad.ftLastWriteTime.dwLowDateTime);
}
return h;
}
static bool ReadFileBytes(const std::wstring& path, std::vector<uint8_t>& out, std::wstring& error) {
try {
std::ifstream ifs(path, std::ios::binary);
if (!ifs) {
error = L"モデルファイルを開けません";
return false;
}
ifs.seekg(0, std::ios::end);
std::streamoff size = ifs.tellg();
if (size < 0) {
error = L"モデルサイズ取得に失敗しました";
return false;
}
ifs.seekg(0, std::ios::beg);
out.resize(static_cast<size_t>(size));
if (!out.empty()) {
ifs.read(reinterpret_cast<char*>(out.data()), size);
if (!ifs) {
error = L"モデル読み込みに失敗しました";
out.clear();
return false;
}
}
return true;
} catch (...) {
error = L"モデル読み込み中に例外が発生しました";
out.clear();
return false;
}
}
static bool WriteFileBytes(const std::wstring& path, const std::vector<uint8_t>& data, std::wstring& error) {
try {
std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
if (!ofs) {
error = L"再焼成モデルを書き込めません";
return false;
}
if (!data.empty()) {
ofs.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
if (!ofs) {
error = L"再焼成モデルの書き込みに失敗しました";
return false;
}
}
return true;
} catch (...) {
error = L"再焼成モデル書き込み中に例外が発生しました";
return false;
}
}
static bool ReadProtoVarint(const uint8_t* data, size_t size, size_t& pos, uint64_t& value) {
value = 0;
int shift = 0;
while (pos < size && shift <= 63) {
const uint8_t b = data[pos++];
value |= static_cast<uint64_t>(b & 0x7fu) << shift;
if ((b & 0x80u) == 0) return true;
shift += 7;
}
return false;
}
static void AppendProtoVarint(std::vector<uint8_t>& out, uint64_t value) {
do {
uint8_t b = static_cast<uint8_t>(value & 0x7fu);
value >>= 7;
if (value) b |= 0x80u;
out.push_back(b);
} while (value);
}
static bool ExtractOpsetDomain(const uint8_t* data, size_t size, std::string& domain, uint64_t& version) {
domain.clear();
version = 0;
size_t pos = 0;
while (pos < size) {
uint64_t key = 0;
if (!ReadProtoVarint(data, size, pos, key)) return false;
const uint32_t field = static_cast<uint32_t>(key >> 3);
const uint32_t wire = static_cast<uint32_t>(key & 7u);
if (wire == 0) {
uint64_t v = 0;
if (!ReadProtoVarint(data, size, pos, v)) return false;
if (field == 2) version = v;
} else if (wire == 2) {
uint64_t len = 0;
if (!ReadProtoVarint(data, size, pos, len)) return false;
if (len > size - pos) return false;
if (field == 1) domain.assign(reinterpret_cast<const char*>(data + pos), static_cast<size_t>(len));
pos += static_cast<size_t>(len);
} else if (wire == 1) {
if (size - pos < 8) return false;
pos += 8;
} else if (wire == 5) {
if (size - pos < 4) return false;
pos += 4;
} else {
return false;
}
}
return true;
}
static bool BuildWinMLCompatibleModelBytes(const std::wstring& model_path, std::vector<uint8_t>& out, bool& changed, std::wstring& error) {
std::vector<uint8_t> src;
if (!ReadFileBytes(model_path, src, error)) return false;
if (src.empty()) {
error = L"ONNXが空です";
return false;
}
out.clear();
out.reserve(src.size());
size_t pos = 0;
changed = false;
bool kept_default = false;
while (pos < src.size()) {
const size_t field_start = pos;
uint64_t key = 0;
if (!ReadProtoVarint(src.data(), src.size(), pos, key)) {
error = L"ONNX解析失敗: key";
return false;
}
const uint32_t field = static_cast<uint32_t>(key >> 3);
const uint32_t wire = static_cast<uint32_t>(key & 7u);
if (wire == 0) {
uint64_t v = 0;
if (!ReadProtoVarint(src.data(), src.size(), pos, v)) {
error = L"ONNX解析失敗: varint";
return false;
}
out.insert(out.end(), src.begin() + field_start, src.begin() + pos);
continue;
}
if (wire == 1) {
if (src.size() - pos < 8) {
error = L"ONNX解析失敗: fixed64";
return false;
}
pos += 8;
out.insert(out.end(), src.begin() + field_start, src.begin() + pos);
continue;
}
if (wire == 5) {
if (src.size() - pos < 4) {
error = L"ONNX解析失敗: fixed32";
return false;
}
pos += 4;
out.insert(out.end(), src.begin() + field_start, src.begin() + pos);
continue;
}
if (wire != 2) {
error = L"ONNX解析失敗: unsupported wire";
return false;
}
uint64_t len64 = 0;
if (!ReadProtoVarint(src.data(), src.size(), pos, len64)) {
error = L"ONNX解析失敗: length";
return false;
}
if (len64 > src.size() - pos) {
error = L"ONNX解析失敗: truncated field";
return false;
}
const size_t payload_pos = pos;
const size_t field_end = payload_pos + static_cast<size_t>(len64);
pos = field_end;
if (field == 8) {
std::string domain;
uint64_t version = 0;
if (!ExtractOpsetDomain(src.data() + payload_pos, static_cast<size_t>(len64), domain, version)) {
error = L"ONNX解析失敗: opset_import";
return false;
}
if (domain.empty()) {
if (!kept_default) {
out.insert(out.end(), src.begin() + field_start, src.begin() + field_end);
kept_default = true;
} else {
changed = true;
}
} else {
changed = true;
}
} else {
out.insert(out.end(), src.begin() + field_start, src.begin() + field_end);
}
}
if (!changed) {
out = std::move(src);
}
return true;
}
static bool LoadLearningModelPossiblyAbsorbed(const std::wstring& model_path, ml::LearningModel& model, std::vector<uint8_t>& absorbed_bytes, std::wstring& error) {
absorbed_bytes.clear();
bool changed = false;
if (!BuildWinMLCompatibleModelBytes(model_path, absorbed_bytes, changed, error)) {
return false;
}
try {
if (!changed) {
model = ml::LearningModel::LoadFromFilePath(model_path);
return true;
}
DebugOut(L"WinML absorb model: in-memory patch");
wss::InMemoryRandomAccessStream stream;
wss::DataWriter writer(stream.GetOutputStreamAt(0));
writer.WriteBytes(winrt::array_view<const uint8_t>(absorbed_bytes));
writer.StoreAsync().get();
writer.FlushAsync().get();
stream.Seek(0);
auto stream_ref = wss::RandomAccessStreamReference::CreateFromStream(stream);
model = ml::LearningModel::LoadFromStream(stream_ref);
return true;
} catch (const winrt::hresult_error& e) {
error = HResultErrorToString(e);
return false;
}
}
enum class ModelMode {
Unknown = 0,
SISR,
VSR,
};
static const wchar_t* ModelModeName(ModelMode mode) {
switch (mode) {
case ModelMode::SISR: return L"SISR";
case ModelMode::VSR: return L"VSR";
default: return L"Unknown";
}
}
struct ModelSpec {
winrt::hstring input_name;
winrt::hstring output_name;
std::vector<int64_t> input_shape;
std::vector<int64_t> output_shape;
int64_t in_c = 0;
int64_t out_c = 0;
int64_t channels_per_frame = 0;
int64_t frame_count = 1;
ml::TensorKind input_kind = ml::TensorKind::Undefined;
ml::TensorKind output_kind = ml::TensorKind::Undefined;
ModelMode mode = ModelMode::Unknown;
bool valid = false;
};
struct PackedFrameCache {
std::vector<float> f32;
std::vector<uint16_t> f16;
};
struct AdapterInfo {
ComPtr<IDXGIAdapter1> adapter;
std::wstring name;
LUID luid{};
};
static std::wstring TrimAdapterName(const wchar_t* s) {
if (!s) return {};
std::wstring name(s);
while (!name.empty() && (name.back() == L' ' || name.back() == L'\0')) {
name.pop_back();
}
return name;
}
static std::vector<AdapterInfo> EnumerateHardwareAdapters() {
std::vector<AdapterInfo> adapters;
ComPtr<IDXGIFactory6> factory6;
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory6)))) {
ComPtr<IDXGIFactory1> factory1;
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory1)))) {
return adapters;
}
for (UINT i = 0;; ++i) {
ComPtr<IDXGIAdapter1> adapter;
if (factory1->EnumAdapters1(i, &adapter) == DXGI_ERROR_NOT_FOUND) break;
DXGI_ADAPTER_DESC1 desc{};
if (FAILED(adapter->GetDesc1(&desc))) continue;
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue;
adapters.push_back(AdapterInfo{ adapter, TrimAdapterName(desc.Description), desc.AdapterLuid });
}
return adapters;
}
for (UINT i = 0;; ++i) {
ComPtr<IDXGIAdapter1> adapter;
if (factory6->EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)) == DXGI_ERROR_NOT_FOUND) break;
DXGI_ADAPTER_DESC1 desc{};
if (FAILED(adapter->GetDesc1(&desc))) continue;
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue;
bool duplicate = false;
for (const auto& existing : adapters) {
if (existing.luid.HighPart == desc.AdapterLuid.HighPart &&
existing.luid.LowPart == desc.AdapterLuid.LowPart) {
duplicate = true;
break;
}
}
if (!duplicate) {
adapters.push_back(AdapterInfo{ adapter, TrimAdapterName(desc.Description), desc.AdapterLuid });
}
}
return adapters;
}
static std::wstring FindAdapterNameByLuid(const LUID& luid) {
const auto adapters = EnumerateHardwareAdapters();
for (const auto& info : adapters) {
if (info.luid.HighPart == luid.HighPart && info.luid.LowPart == luid.LowPart) {
return info.name;
}
}
return {};
}
static void SetWideLabel(wchar_t* dst, size_t dst_count, const std::wstring& text) {
if (!dst || dst_count == 0) return;
wcsncpy_s(dst, dst_count, text.c_str(), _TRUNCATE);
}
static void UpdateBackendLabels() {
SetWideLabel(g_backend_label_auto, std::size(g_backend_label_auto), L"GPU優先(自動)");
SetWideLabel(g_backend_label_gpu0, std::size(g_backend_label_gpu0), L"GPU 0");
SetWideLabel(g_backend_label_gpu1, std::size(g_backend_label_gpu1), L"GPU 1");
SetWideLabel(g_backend_label_cpu, std::size(g_backend_label_cpu), L"CPU固定");
const auto adapters = EnumerateHardwareAdapters();
if (!adapters.empty()) {
SetWideLabel(g_backend_label_auto, std::size(g_backend_label_auto),
L"GPU優先(自動): " + adapters[0].name);
SetWideLabel(g_backend_label_gpu0, std::size(g_backend_label_gpu0),
L"GPU 0: " + adapters[0].name);
}
if (adapters.size() >= 2) {
SetWideLabel(g_backend_label_gpu1, std::size(g_backend_label_gpu1),
L"GPU 1: " + adapters[1].name);
}
}
static wgdx11::IDirect3DDevice CreateInteropDeviceFromAdapter(const AdapterInfo& info, std::wstring& error) {
UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
D3D_FEATURE_LEVEL levels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
D3D_FEATURE_LEVEL actual_level = D3D_FEATURE_LEVEL_10_0;
ComPtr<ID3D11Device> d3d_device;
ComPtr<ID3D11DeviceContext> d3d_context;
HRESULT hr = D3D11CreateDevice(
info.adapter.Get(),
D3D_DRIVER_TYPE_UNKNOWN,
nullptr,
flags,
levels,
static_cast<UINT>(std::size(levels)),
D3D11_SDK_VERSION,
&d3d_device,
&actual_level,
&d3d_context);
if (FAILED(hr) || !d3d_device) {
error = L"D3D11デバイス作成失敗: " + info.name;
return nullptr;
}
ComPtr<IDXGIDevice> dxgi_device;
hr = d3d_device.As(&dxgi_device);
if (FAILED(hr) || !dxgi_device) {
error = L"IDXGIDevice取得失敗: " + info.name;
return nullptr;
}
winrt::com_ptr<IInspectable> inspectable;
hr = CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(), inspectable.put());
if (FAILED(hr) || !inspectable) {
error = L"WinRT D3D11デバイス作成失敗: " + info.name;
return nullptr;
}
try {
return inspectable.as<wgdx11::IDirect3DDevice>();
} catch (const winrt::hresult_error&) {
error = L"IDirect3DDevice変換失敗: " + info.name;
return nullptr;
}
}
// WinML execution engine. Tensor I/O path is kept unchanged for stability.
class WinMLEngine {
public:
bool Load(const std::wstring& model_path, int backend_mode, std::wstring& error) {
Reset();
try {
static std::once_flag init_flag;
std::call_once(init_flag, []() {
winrt::init_apartment(winrt::apartment_type::multi_threaded);
});
DebugOut((L"Load model: " + model_path).c_str());
if (!LoadLearningModelPossiblyAbsorbed(model_path, model_, absorbed_model_bytes_, error)) {
DebugOut((L"LoadLearningModel failed: " + error).c_str());
Reset();
return false;
}
model_path_ = model_path;
model_spec_ = InspectModel(model_);
{
std::wstringstream ss;
ss << L"InspectModel path=" << model_path_
<< L" in_shape=";
for (size_t i = 0; i < model_spec_.input_shape.size(); ++i) {
if (i) ss << L"x";
ss << model_spec_.input_shape[i];
}
ss << L" out_shape=";
for (size_t i = 0; i < model_spec_.output_shape.size(); ++i) {
if (i) ss << L"x";
ss << model_spec_.output_shape[i];
}
ss << L" in_c=" << model_spec_.in_c
<< L" out_c=" << model_spec_.out_c
<< L" valid=" << (model_spec_.valid ? 1 : 0);
DebugOut(ss.str().c_str());
}
if (!model_spec_.valid) {
error = L"対応外モデル: float32/float16 / 1入力1出力 / 4次元NCHWのみ対応";
DebugOut((L"InspectModel rejected: " + error).c_str());
Reset();
return false;
}
if (backend_mode == 3) {
device_ = ml::LearningModelDevice(ml::LearningModelDeviceKind::Cpu);
backend_name_ = L"WinML CPU";
selected_device_name_ = L"CPU";
ml::LearningModelSessionOptions options;
options.CloseModelOnSessionCreation(true);
session_ = ml::LearningModelSession(model_, device_, options);
} else if (backend_mode == 1 || backend_mode == 2) {
const int gpu_index = backend_mode - 1;
const auto adapters = EnumerateHardwareAdapters();
if (gpu_index < 0 || gpu_index >= static_cast<int>(adapters.size())) {
error = (gpu_index == 0) ? L"GPU 0 が見つかりません" : L"GPU 1 が見つかりません";
Reset();
return false;
}
auto d3d_device = CreateInteropDeviceFromAdapter(adapters[gpu_index], error);
if (!d3d_device) {
Reset();
return false;
}
device_ = ml::LearningModelDevice::CreateFromDirect3D11Device(d3d_device);
backend_name_ = L"WinML GPU " + std::to_wstring(gpu_index);
selected_device_name_ = adapters[gpu_index].name;
ml::LearningModelSessionOptions options;
options.CloseModelOnSessionCreation(true);
session_ = ml::LearningModelSession(model_, device_, options);
} else {
try {
device_ = ml::LearningModelDevice(ml::LearningModelDeviceKind::DirectXHighPerformance);
selected_device_name_.clear();
try {
const auto adapter_id = device_.AdapterId();
LUID luid{};
luid.HighPart = adapter_id.HighPart;
luid.LowPart = adapter_id.LowPart;
selected_device_name_ = FindAdapterNameByLuid(luid);
} catch (...) {
}
backend_name_ = selected_device_name_.empty()
? L"WinML GPU (自動)"
: (L"WinML GPU (自動): " + selected_device_name_);
ml::LearningModelSessionOptions options;
options.CloseModelOnSessionCreation(true);
session_ = ml::LearningModelSession(model_, device_, options);
} catch (const winrt::hresult_error& gpu_e) {
DebugOut((L"WinML GPU fallback: " + HResultErrorToString(gpu_e)).c_str());
device_ = ml::LearningModelDevice(ml::LearningModelDeviceKind::Cpu);
backend_name_ = L"WinML CPU";
selected_device_name_ = L"CPU";
ml::LearningModelSessionOptions options;
options.CloseModelOnSessionCreation(true);
session_ = ml::LearningModelSession(model_, device_, options);
error = L"GPU初期化失敗";
}
}
if (!selected_device_name_.empty()) {
DebugOut((L"Selected device: " + selected_device_name_).c_str());
}
loaded_ = true;
return true;
} catch (const winrt::hresult_error& e) {
error = HResultErrorToString(e);
Reset();
return false;
} catch (const std::exception& e) {
error = L"例外: ";
error += winrt::to_hstring(e.what()).c_str();
Reset();
return false;
}
}
void Reset() {
loaded_ = false;
model_ = nullptr;
device_ = nullptr;
session_ = nullptr;
model_spec_ = {};
backend_name_.clear();
selected_device_name_.clear();
model_path_.clear();
absorbed_model_bytes_.clear();
bound_input_shape_.clear();
input_tensor_f32_ = nullptr;
input_tensor_f16_ = nullptr;
bound_output_shape_.clear();
output_tensor_f32_ = nullptr;
output_tensor_f16_ = nullptr;
output_binding_ready_ = false;
cached_binding_ = nullptr;
binding_ready_ = false;
defer_output_binding_for_eval_ = false;
packed_input_f32_.clear();
packed_input_f16_.clear();
frame_scratch_f32_.clear();
frame_scratch_f16_.clear();
last_output_pixels_.clear();
last_output_width_ = 0;
last_output_height_ = 0;
last_window_width_ = 0;
last_window_height_ = 0;
last_sisr_input_width_ = 0;
last_sisr_input_height_ = 0;
has_last_frame_ = false;
last_frame_number_ = std::numeric_limits<int>::min();
last_object_id_ = 0;
last_effect_id_ = 0;
}
bool IsLoaded() const { return loaded_ && session_ != nullptr; }
const ModelSpec& Spec() const { return model_spec_; }
const std::wstring& BackendName() const { return backend_name_; }
const std::wstring& SelectedDeviceName() const { return selected_device_name_; }
const std::wstring& ModelPath() const { return model_path_; }
bool RunPixels(const PIXEL_RGBA* src_pixels, int width, int height,
int object_frame, int64_t object_id, int64_t effect_id,
std::vector<PIXEL_RGBA>& dst_pixels,
int& out_width, int& out_height, std::wstring& error) {
out_width = 0;
out_height = 0;
if (!IsLoaded()) {
error = L"モデル未読込";
return false;
}
if (!src_pixels || width <= 0 || height <= 0) {
error = L"不正サイズ";
return false;
}
if (model_spec_.mode == ModelMode::SISR) {
if (last_sisr_input_width_ > 0 && last_sisr_input_height_ > 0 &&
(last_sisr_input_width_ != width || last_sisr_input_height_ != height)) {
InvalidateSISRExecutionState();
std::wstringstream ss;
ss << L"SISR safe invalidate: input size changed "
<< last_sisr_input_width_ << L"x" << last_sisr_input_height_
<< L" -> " << width << L"x" << height;
DebugOut(ss.str().c_str());
}
last_sisr_input_width_ = width;
last_sisr_input_height_ = height;
}
if (model_spec_.mode == ModelMode::VSR && has_last_frame_ &&