Repository navigation
Expand file tree
/
Copy pathVulkan.cpp
More file actions
994 lines (899 loc) · 40 KB
/
Copy pathVulkan.cpp
File metadata and controls
994 lines (899 loc) · 40 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
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Vulkan.h"
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
namespace gfxstream {
namespace {
constexpr const bool kEnableValidationLayers = false;
static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanDebugCallback(
vkhpp::DebugUtilsMessageSeverityFlagBitsEXT severity,
vkhpp::DebugUtilsMessageTypeFlagsEXT,
const vkhpp::DebugUtilsMessengerCallbackDataEXT* pCallbackData,
void*) {
if (severity == vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose) {
std::cout << pCallbackData->pMessage << std::endl;
} else if (severity == vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eInfo) {
std::cout << pCallbackData->pMessage << std::endl;
} else if (severity == vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eWarning) {
std::cout << pCallbackData->pMessage << std::endl;
} else if (severity == vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eError) {
std::cout << pCallbackData->pMessage << std::endl;
}
return VK_FALSE;
}
uint32_t GetMemoryType(const vkhpp::PhysicalDevice& physical_device,
uint32_t memory_type_mask,
vkhpp::MemoryPropertyFlags memoryProperties) {
const auto props = physical_device.getMemoryProperties();
for (uint32_t i = 0; i < props.memoryTypeCount; i++) {
if (!(memory_type_mask & (1 << i))) {
continue;
}
if ((props.memoryTypes[i].propertyFlags & memoryProperties) != memoryProperties) {
continue;
}
return i;
}
return -1;
}
} // namespace
gfxstream::expected<Vk::BufferWithMemory, vkhpp::Result> DoCreateBuffer(
const vkhpp::PhysicalDevice& physical_device,
const vkhpp::UniqueDevice& device, vkhpp::DeviceSize buffer_size,
vkhpp::BufferUsageFlags buffer_usages,
vkhpp::MemoryPropertyFlags bufferMemoryProperties) {
const vkhpp::BufferCreateInfo bufferCreateInfo = {
.size = static_cast<VkDeviceSize>(buffer_size),
.usage = buffer_usages,
.sharingMode = vkhpp::SharingMode::eExclusive,
};
auto buffer = VK_EXPECT_RV(device->createBufferUnique(bufferCreateInfo));
vkhpp::MemoryRequirements bufferMemoryRequirements{};
device->getBufferMemoryRequirements(*buffer, &bufferMemoryRequirements);
const auto bufferMemoryType =
GetMemoryType(physical_device,
bufferMemoryRequirements.memoryTypeBits,
bufferMemoryProperties);
const vkhpp::MemoryAllocateInfo bufferMemoryAllocateInfo = {
.allocationSize = bufferMemoryRequirements.size,
.memoryTypeIndex = bufferMemoryType,
};
auto bufferMemory = VK_EXPECT_RV(device->allocateMemoryUnique(bufferMemoryAllocateInfo));
VK_EXPECT_RESULT(device->bindBufferMemory(*buffer, *bufferMemory, 0));
return Vk::BufferWithMemory{
.buffer = std::move(buffer),
.bufferMemory = std::move(bufferMemory),
};
}
/*static*/
gfxstream::expected<Vk, vkhpp::Result> Vk::Load(
const std::vector<std::string>& requestedInstanceExtensions,
const std::vector<std::string>& requestedInstanceLayers,
const std::vector<std::string>& requestedDeviceExtensions) {
vkhpp::detail::DynamicLoader loader;
VULKAN_HPP_DEFAULT_DISPATCHER.init(
loader.getProcAddress<PFN_vkGetInstanceProcAddr>(
"vkGetInstanceProcAddr"));
std::vector<const char*> requestedInstanceExtensionsChars;
requestedInstanceExtensionsChars.reserve(requestedInstanceExtensions.size());
for (const auto& e : requestedInstanceExtensions) {
requestedInstanceExtensionsChars.push_back(e.c_str());
}
if (kEnableValidationLayers) {
requestedInstanceExtensionsChars.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
std::vector<const char*> requestedInstanceLayersChars;
requestedInstanceLayersChars.reserve(requestedInstanceLayers.size());
for (const auto& l : requestedInstanceLayers) {
requestedInstanceLayersChars.push_back(l.c_str());
}
const vkhpp::ApplicationInfo applicationInfo = {
.pApplicationName = "Cuttlefish Graphics Detector",
.applicationVersion = 1,
.pEngineName = "Cuttlefish Graphics Detector",
.engineVersion = 1,
.apiVersion = VK_API_VERSION_1_2,
};
const vkhpp::InstanceCreateInfo instanceCreateInfo = {
.pApplicationInfo = &applicationInfo,
.enabledLayerCount = static_cast<uint32_t>(requestedInstanceLayersChars.size()),
.ppEnabledLayerNames = requestedInstanceLayersChars.data(),
.enabledExtensionCount = static_cast<uint32_t>(requestedInstanceExtensionsChars.size()),
.ppEnabledExtensionNames = requestedInstanceExtensionsChars.data(),
};
auto instance = VK_EXPECT_RV(vkhpp::createInstanceUnique(instanceCreateInfo));
VULKAN_HPP_DEFAULT_DISPATCHER.init(*instance);
std::optional<vkhpp::UniqueDebugUtilsMessengerEXT> debugMessenger;
if (kEnableValidationLayers) {
const vkhpp::DebugUtilsMessengerCreateInfoEXT debugCreateInfo = {
.messageSeverity = vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose |
vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vkhpp::DebugUtilsMessageSeverityFlagBitsEXT::eError,
.messageType = vkhpp::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vkhpp::DebugUtilsMessageTypeFlagBitsEXT::eValidation |
vkhpp::DebugUtilsMessageTypeFlagBitsEXT::ePerformance,
.pfnUserCallback = VulkanDebugCallback,
.pUserData = nullptr,
};
debugMessenger = VK_EXPECT_RV(instance->createDebugUtilsMessengerEXTUnique(debugCreateInfo));
}
const auto physicalDevices = VK_EXPECT_RV(instance->enumeratePhysicalDevices());
vkhpp::PhysicalDevice physicalDevice = std::move(physicalDevices[0]);
std::unordered_set<std::string> availableDeviceExtensions;
{
const auto exts = VK_EXPECT_RV(physicalDevice.enumerateDeviceExtensionProperties());
for (const auto& ext : exts) {
availableDeviceExtensions.emplace(ext.extensionName);
}
}
const auto features2 =
physicalDevice
.getFeatures2<vkhpp::PhysicalDeviceFeatures2, //
vkhpp::PhysicalDeviceSamplerYcbcrConversionFeatures>();
bool ycbcr_conversion_needed = false;
std::vector<const char*> requestedDeviceExtensionsChars;
requestedDeviceExtensionsChars.reserve(requestedDeviceExtensions.size());
for (const auto& e : requestedDeviceExtensions) {
if (e == std::string(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME)) {
// The interface of VK_KHR_sampler_ycbcr_conversion was promoted to core
// in Vulkan 1.1 but the feature/functionality is still optional. Check
// here:
const auto& sampler_features =
features2.get<vkhpp::PhysicalDeviceSamplerYcbcrConversionFeatures>();
if (sampler_features.samplerYcbcrConversion == VK_FALSE) {
return gfxstream::unexpected(vkhpp::Result::eErrorExtensionNotPresent);
}
ycbcr_conversion_needed = true;
} else {
if (availableDeviceExtensions.find(e) == availableDeviceExtensions.end()) {
return gfxstream::unexpected(vkhpp::Result::eErrorExtensionNotPresent);
}
requestedDeviceExtensionsChars.push_back(e.c_str());
}
}
uint32_t queueFamilyIndex = -1;
{
const auto props = physicalDevice.getQueueFamilyProperties();
for (uint32_t i = 0; i < props.size(); i++) {
const auto& prop = props[i];
if (prop.queueFlags & vkhpp::QueueFlagBits::eGraphics) {
queueFamilyIndex = i;
break;
}
}
}
const float queue_priority = 1.0f;
const vkhpp::DeviceQueueCreateInfo device_queue_create_info = {
.queueFamilyIndex = queueFamilyIndex,
.queueCount = 1,
.pQueuePriorities = &queue_priority,
};
const vkhpp::PhysicalDeviceVulkan11Features device_enable_features = {
.samplerYcbcrConversion = ycbcr_conversion_needed,
};
const vkhpp::DeviceCreateInfo deviceCreateInfo = {
.pNext = &device_enable_features,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &device_queue_create_info,
.enabledLayerCount = static_cast<uint32_t>(requestedInstanceLayersChars.size()),
.ppEnabledLayerNames = requestedInstanceLayersChars.data(),
.enabledExtensionCount = static_cast<uint32_t>(requestedDeviceExtensionsChars.size()),
.ppEnabledExtensionNames = requestedDeviceExtensionsChars.data(),
};
auto device = VK_EXPECT_RV(physicalDevice.createDeviceUnique(deviceCreateInfo));
auto queue = device->getQueue(queueFamilyIndex, 0);
const vkhpp::CommandPoolCreateInfo commandPoolCreateInfo = {
.queueFamilyIndex = queueFamilyIndex,
};
auto commandPool = VK_EXPECT_RV(device->createCommandPoolUnique(commandPoolCreateInfo));
auto stagingBuffer =
VK_EXPECT(DoCreateBuffer(physicalDevice, device, kStagingBufferSize,
vkhpp::BufferUsageFlagBits::eTransferDst |
vkhpp::BufferUsageFlagBits::eTransferSrc,
vkhpp::MemoryPropertyFlagBits::eHostVisible |
vkhpp::MemoryPropertyFlagBits::eHostCoherent));
return Vk(std::move(loader),
std::move(instance),
std::move(debugMessenger),
std::move(physicalDevice),
std::move(device),
std::move(queue),
queueFamilyIndex,
std::move(commandPool),
std::move(stagingBuffer.buffer),
std::move(stagingBuffer.bufferMemory));
}
gfxstream::expected<Vk::BufferWithMemory, vkhpp::Result> Vk::CreateBuffer(
vkhpp::DeviceSize bufferSize,
vkhpp::BufferUsageFlags bufferUsages,
vkhpp::MemoryPropertyFlags bufferMemoryProperties) {
return DoCreateBuffer(mPhysicalDevice,
mDevice,
bufferSize,
bufferUsages,
bufferMemoryProperties);
}
gfxstream::expected<Vk::BufferWithMemory, vkhpp::Result> Vk::CreateBufferWithData(
vkhpp::DeviceSize bufferSize,
vkhpp::BufferUsageFlags bufferUsages,
vkhpp::MemoryPropertyFlags bufferMemoryProperties,
const uint8_t* buffer_data) {
auto buffer = VK_EXPECT(CreateBuffer(
bufferSize,
bufferUsages | vkhpp::BufferUsageFlagBits::eTransferDst,
bufferMemoryProperties));
void* mapped = VK_EXPECT_RV(mDevice->mapMemory(*mStagingBufferMemory, 0, kStagingBufferSize));
std::memcpy(mapped, buffer_data, bufferSize);
mDevice->unmapMemory(*mStagingBufferMemory);
DoCommandsImmediate([&](vkhpp::UniqueCommandBuffer& cmd) {
const std::vector<vkhpp::BufferCopy> regions = {
vkhpp::BufferCopy{
.srcOffset = 0,
.dstOffset = 0,
.size = bufferSize,
},
};
cmd->copyBuffer(*mStagingBuffer, *buffer.buffer, regions);
return vkhpp::Result::eSuccess;
});
return std::move(buffer);
}
gfxstream::expected<Vk::ImageWithMemory, vkhpp::Result> Vk::CreateImage(
uint32_t width,
uint32_t height,
vkhpp::Format format,
vkhpp::ImageUsageFlags usages,
vkhpp::MemoryPropertyFlags memoryProperties,
vkhpp::ImageLayout returnedLayout) {
const vkhpp::ImageCreateInfo imageCreateInfo = {
.imageType = vkhpp::ImageType::e2D,
.format = format,
.extent = {
.width = width,
.height = height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vkhpp::SampleCountFlagBits::e1,
.tiling = vkhpp::ImageTiling::eOptimal,
.usage = usages,
.sharingMode = vkhpp::SharingMode::eExclusive,
.initialLayout = vkhpp::ImageLayout::eUndefined,
};
auto image = VK_EXPECT_RV(mDevice->createImageUnique(imageCreateInfo));
const auto memoryRequirements = mDevice->getImageMemoryRequirements(*image);
const uint32_t memoryIndex =
GetMemoryType(mPhysicalDevice,
memoryRequirements.memoryTypeBits,
memoryProperties);
const vkhpp::MemoryAllocateInfo imageMemoryAllocateInfo = {
.allocationSize = memoryRequirements.size,
.memoryTypeIndex = memoryIndex,
};
auto imageMemory = VK_EXPECT_RV(mDevice->allocateMemoryUnique(imageMemoryAllocateInfo));
mDevice->bindImageMemory(*image, *imageMemory, 0);
const vkhpp::ImageViewCreateInfo imageViewCreateInfo = {
.image = *image,
.viewType = vkhpp::ImageViewType::e2D,
.format = format,
.components = {
.r = vkhpp::ComponentSwizzle::eIdentity,
.g = vkhpp::ComponentSwizzle::eIdentity,
.b = vkhpp::ComponentSwizzle::eIdentity,
.a = vkhpp::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
auto imageView = VK_EXPECT_RV(mDevice->createImageViewUnique(imageViewCreateInfo));
VK_EXPECT_RESULT(DoCommandsImmediate([&](vkhpp::UniqueCommandBuffer& cmd) {
const std::vector<vkhpp::ImageMemoryBarrier> imageMemoryBarriers = {
vkhpp::ImageMemoryBarrier{
.srcAccessMask = {},
.dstAccessMask = vkhpp::AccessFlagBits::eTransferWrite,
.oldLayout = vkhpp::ImageLayout::eUndefined,
.newLayout = returnedLayout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *image,
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
};
cmd->pipelineBarrier(
/*srcStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dstStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dependencyFlags=*/{},
/*memoryBarriers=*/{},
/*bufferMemoryBarriers=*/{},
/*imageMemoryBarriers=*/imageMemoryBarriers);
return vkhpp::Result::eSuccess;
}));
return ImageWithMemory{
.image = std::move(image),
.imageMemory = std::move(imageMemory),
.imageView = std::move(imageView),
};
}
gfxstream::expected<std::vector<uint8_t>, vkhpp::Result> Vk::DownloadImage(
uint32_t width,
uint32_t height,
const vkhpp::UniqueImage& image,
vkhpp::ImageLayout currentLayout,
vkhpp::ImageLayout returnedLayout) {
VK_EXPECT_RESULT(
DoCommandsImmediate([&](vkhpp::UniqueCommandBuffer& cmd) {
if (currentLayout != vkhpp::ImageLayout::eTransferSrcOptimal) {
const std::vector<vkhpp::ImageMemoryBarrier> imageMemoryBarriers = {
vkhpp::ImageMemoryBarrier{
.srcAccessMask = vkhpp::AccessFlagBits::eMemoryRead |
vkhpp::AccessFlagBits::eMemoryWrite,
.dstAccessMask = vkhpp::AccessFlagBits::eTransferRead,
.oldLayout = currentLayout,
.newLayout = vkhpp::ImageLayout::eTransferSrcOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *image,
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
};
cmd->pipelineBarrier(
/*srcStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dstStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dependencyFlags=*/{},
/*memoryBarriers=*/{},
/*bufferMemoryBarriers=*/{},
/*imageMemoryBarriers=*/imageMemoryBarriers);
}
const std::vector<vkhpp::BufferImageCopy> regions = {
vkhpp::BufferImageCopy{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource =
{
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset =
{
.x = 0,
.y = 0,
.z = 0,
},
.imageExtent =
{
.width = width,
.height = height,
.depth = 1,
},
},
};
cmd->copyImageToBuffer(*image,
vkhpp::ImageLayout::eTransferSrcOptimal,
*mStagingBuffer, regions);
if (returnedLayout != vkhpp::ImageLayout::eTransferSrcOptimal) {
const std::vector<vkhpp::ImageMemoryBarrier> imageMemoryBarriers = {
vkhpp::ImageMemoryBarrier{
.srcAccessMask = vkhpp::AccessFlagBits::eTransferRead,
.dstAccessMask = vkhpp::AccessFlagBits::eMemoryRead |
vkhpp::AccessFlagBits::eMemoryWrite,
.oldLayout = vkhpp::ImageLayout::eTransferSrcOptimal,
.newLayout = returnedLayout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *image,
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
};
cmd->pipelineBarrier(
/*srcStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dstStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dependencyFlags=*/{},
/*memoryBarriers=*/{},
/*bufferMemoryBarriers=*/{},
/*imageMemoryBarriers=*/imageMemoryBarriers);
}
return vkhpp::Result::eSuccess;
}));
auto* mapped = reinterpret_cast<uint8_t*>(
VK_EXPECT_RV(mDevice->mapMemory(*mStagingBufferMemory, 0, kStagingBufferSize)));
std::vector<uint8_t> outPixels;
outPixels.resize(width * height * 4);
std::memcpy(outPixels.data(), mapped, outPixels.size());
mDevice->unmapMemory(*mStagingBufferMemory);
return outPixels;
}
gfxstream::expected<Vk::YuvImageWithMemory, vkhpp::Result> Vk::CreateYuvImage(
uint32_t width,
uint32_t height,
vkhpp::ImageUsageFlags usages,
vkhpp::MemoryPropertyFlags memoryProperties,
vkhpp::ImageLayout layout) {
const vkhpp::SamplerYcbcrConversionCreateInfo conversionCreateInfo = {
.format = vkhpp::Format::eG8B8R83Plane420Unorm,
.ycbcrModel = vkhpp::SamplerYcbcrModelConversion::eYcbcr601,
.ycbcrRange = vkhpp::SamplerYcbcrRange::eItuNarrow,
.components = {
.r = vkhpp::ComponentSwizzle::eIdentity,
.g = vkhpp::ComponentSwizzle::eIdentity,
.b = vkhpp::ComponentSwizzle::eIdentity,
.a = vkhpp::ComponentSwizzle::eIdentity,
},
.xChromaOffset = vkhpp::ChromaLocation::eMidpoint,
.yChromaOffset = vkhpp::ChromaLocation::eMidpoint,
.chromaFilter = vkhpp::Filter::eLinear,
.forceExplicitReconstruction = VK_FALSE,
};
auto imageSamplerConversion = VK_EXPECT_RV(mDevice->createSamplerYcbcrConversionUnique(conversionCreateInfo));
const vkhpp::SamplerYcbcrConversionInfo samplerConversionInfo = {
.conversion = *imageSamplerConversion,
};
const vkhpp::SamplerCreateInfo samplerCreateInfo = {
.pNext = &samplerConversionInfo,
.magFilter = vkhpp::Filter::eLinear,
.minFilter = vkhpp::Filter::eLinear,
.mipmapMode = vkhpp::SamplerMipmapMode::eNearest,
.addressModeU = vkhpp::SamplerAddressMode::eClampToEdge,
.addressModeV = vkhpp::SamplerAddressMode::eClampToEdge,
.addressModeW = vkhpp::SamplerAddressMode::eClampToEdge,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1.0f,
.compareEnable = VK_FALSE,
.compareOp = vkhpp::CompareOp::eLessOrEqual,
.minLod = 0.0f,
.maxLod = 0.25f,
.borderColor = vkhpp::BorderColor::eIntTransparentBlack,
.unnormalizedCoordinates = VK_FALSE,
};
auto imageSampler = VK_EXPECT_RV(mDevice->createSamplerUnique(samplerCreateInfo));
const vkhpp::ImageCreateInfo imageCreateInfo = {
.imageType = vkhpp::ImageType::e2D,
.format = vkhpp::Format::eG8B8R83Plane420Unorm,
.extent = {
.width = width,
.height = height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vkhpp::SampleCountFlagBits::e1,
.tiling = vkhpp::ImageTiling::eOptimal,
.usage = usages,
.sharingMode = vkhpp::SharingMode::eExclusive,
.initialLayout = vkhpp::ImageLayout::eUndefined,
};
auto image = VK_EXPECT_RV(mDevice->createImageUnique(imageCreateInfo));
const auto memoryRequirements = mDevice->getImageMemoryRequirements(*image);
const uint32_t memoryIndex =
GetMemoryType(mPhysicalDevice,
memoryRequirements.memoryTypeBits,
memoryProperties);
const vkhpp::MemoryAllocateInfo imageMemoryAllocateInfo = {
.allocationSize = memoryRequirements.size,
.memoryTypeIndex = memoryIndex,
};
auto imageMemory = VK_EXPECT_RV(mDevice->allocateMemoryUnique(imageMemoryAllocateInfo));
mDevice->bindImageMemory(*image, *imageMemory, 0);
const vkhpp::ImageViewCreateInfo imageViewCreateInfo = {
.pNext = &samplerConversionInfo,
.image = *image,
.viewType = vkhpp::ImageViewType::e2D,
.format = vkhpp::Format::eG8B8R83Plane420Unorm,
.components = {
.r = vkhpp::ComponentSwizzle::eIdentity,
.g = vkhpp::ComponentSwizzle::eIdentity,
.b = vkhpp::ComponentSwizzle::eIdentity,
.a = vkhpp::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
auto imageView = VK_EXPECT_RV(mDevice->createImageViewUnique(imageViewCreateInfo));
VK_EXPECT_RESULT(DoCommandsImmediate([&](vkhpp::UniqueCommandBuffer& cmd) {
const std::vector<vkhpp::ImageMemoryBarrier> imageMemoryBarriers = {
vkhpp::ImageMemoryBarrier{
.srcAccessMask = {},
.dstAccessMask = vkhpp::AccessFlagBits::eTransferWrite,
.oldLayout = vkhpp::ImageLayout::eUndefined,
.newLayout = layout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *image,
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
};
cmd->pipelineBarrier(
/*srcStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dstStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dependencyFlags=*/{},
/*memoryBarriers=*/{},
/*bufferMemoryBarriers=*/{},
/*imageMemoryBarriers=*/imageMemoryBarriers);
return vkhpp::Result::eSuccess;
}));
return YuvImageWithMemory{
.imageSamplerConversion = std::move(imageSamplerConversion),
.imageSampler = std::move(imageSampler),
.imageMemory = std::move(imageMemory),
.image = std::move(image),
.imageView = std::move(imageView),
};
}
vkhpp::Result Vk::LoadYuvImage(
const vkhpp::UniqueImage& image,
uint32_t width,
uint32_t height,
const std::vector<uint8_t>& imageDataY,
const std::vector<uint8_t>& imageDataU,
const std::vector<uint8_t>& imageDataV,
vkhpp::ImageLayout currentLayout,
vkhpp::ImageLayout returnedLayout) {
auto* mapped = reinterpret_cast<uint8_t*>(VK_TRY_RV(mDevice->mapMemory(*mStagingBufferMemory, 0, kStagingBufferSize)));
const VkDeviceSize yOffset = 0;
const VkDeviceSize uOffset = imageDataY.size();
const VkDeviceSize vOffset = imageDataY.size() + imageDataU.size();
std::memcpy(mapped + yOffset, imageDataY.data(), imageDataY.size());
std::memcpy(mapped + uOffset, imageDataU.data(), imageDataU.size());
std::memcpy(mapped + vOffset, imageDataV.data(), imageDataV.size());
mDevice->unmapMemory(*mStagingBufferMemory);
return DoCommandsImmediate([&](vkhpp::UniqueCommandBuffer& cmd) {
if (currentLayout != vkhpp::ImageLayout::eTransferDstOptimal) {
const std::vector<vkhpp::ImageMemoryBarrier> imageMemoryBarriers = {
vkhpp::ImageMemoryBarrier{
.srcAccessMask = vkhpp::AccessFlagBits::eMemoryRead |
vkhpp::AccessFlagBits::eMemoryWrite,
.dstAccessMask = vkhpp::AccessFlagBits::eTransferWrite,
.oldLayout = currentLayout,
.newLayout = vkhpp::ImageLayout::eTransferDstOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *image,
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
};
cmd->pipelineBarrier(
/*srcStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dstStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dependencyFlags=*/{},
/*memoryBarriers=*/{},
/*bufferMemoryBarriers=*/{},
/*imageMemoryBarriers=*/imageMemoryBarriers);
}
const std::vector<vkhpp::BufferImageCopy> imageCopyRegions = {
vkhpp::BufferImageCopy{
.bufferOffset = yOffset,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vkhpp::ImageAspectFlagBits::ePlane0,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {
.x = 0,
.y = 0,
.z = 0,
},
.imageExtent = {
.width = width,
.height = height,
.depth = 1,
},
},
vkhpp::BufferImageCopy{
.bufferOffset = uOffset,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vkhpp::ImageAspectFlagBits::ePlane1,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {
.x = 0,
.y = 0,
.z = 0,
},
.imageExtent = {
.width = width / 2,
.height = height / 2,
.depth = 1,
},
},
vkhpp::BufferImageCopy{
.bufferOffset = vOffset,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vkhpp::ImageAspectFlagBits::ePlane2,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {
.x = 0,
.y = 0,
.z = 0,
},
.imageExtent = {
.width = width / 2,
.height = height / 2,
.depth = 1,
},
},
};
cmd->copyBufferToImage(*mStagingBuffer,
*image,
vkhpp::ImageLayout::eTransferDstOptimal,
imageCopyRegions);
if (returnedLayout != vkhpp::ImageLayout::eTransferDstOptimal) {
const std::vector<vkhpp::ImageMemoryBarrier> imageMemoryBarriers = {
vkhpp::ImageMemoryBarrier{
.srcAccessMask = vkhpp::AccessFlagBits::eTransferWrite,
.dstAccessMask = vkhpp::AccessFlagBits::eMemoryRead |
vkhpp::AccessFlagBits::eMemoryWrite,
.oldLayout = vkhpp::ImageLayout::eTransferDstOptimal,
.newLayout = returnedLayout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *image,
.subresourceRange = {
.aspectMask = vkhpp::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
};
cmd->pipelineBarrier(
/*srcStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dstStageMask=*/vkhpp::PipelineStageFlagBits::eAllCommands,
/*dependencyFlags=*/{},
/*memoryBarriers=*/{},
/*bufferMemoryBarriers=*/{},
/*imageMemoryBarriers=*/imageMemoryBarriers);
}
return vkhpp::Result::eSuccess;
});
}
gfxstream::expected<Vk::FramebufferWithAttachments, vkhpp::Result>
Vk::CreateFramebuffer(
uint32_t width,
uint32_t height,
vkhpp::Format color_format,
vkhpp::Format depth_format) {
std::optional<Vk::ImageWithMemory> colorAttachment;
if (color_format != vkhpp::Format::eUndefined) {
colorAttachment =
GFXSTREAM_EXPECT(CreateImage(width, height, color_format,
vkhpp::ImageUsageFlagBits::eColorAttachment |
vkhpp::ImageUsageFlagBits::eTransferSrc,
vkhpp::MemoryPropertyFlagBits::eDeviceLocal,
vkhpp::ImageLayout::eColorAttachmentOptimal));
}
std::optional<Vk::ImageWithMemory> depthAttachment;
if (depth_format != vkhpp::Format::eUndefined) {
depthAttachment =
GFXSTREAM_EXPECT(CreateImage(width, height, depth_format,
vkhpp::ImageUsageFlagBits::eDepthStencilAttachment |
vkhpp::ImageUsageFlagBits::eTransferSrc,
vkhpp::MemoryPropertyFlagBits::eDeviceLocal,
vkhpp::ImageLayout::eDepthStencilAttachmentOptimal));
}
std::vector<vkhpp::AttachmentDescription> attachments;
std::optional<vkhpp::AttachmentReference> colorAttachment_reference;
if (color_format != vkhpp::Format::eUndefined) {
attachments.push_back(vkhpp::AttachmentDescription{
.format = color_format,
.samples = vkhpp::SampleCountFlagBits::e1,
.loadOp = vkhpp::AttachmentLoadOp::eClear,
.storeOp = vkhpp::AttachmentStoreOp::eStore,
.stencilLoadOp = vkhpp::AttachmentLoadOp::eClear,
.stencilStoreOp = vkhpp::AttachmentStoreOp::eStore,
.initialLayout = vkhpp::ImageLayout::eColorAttachmentOptimal,
.finalLayout = vkhpp::ImageLayout::eColorAttachmentOptimal,
});
colorAttachment_reference = vkhpp::AttachmentReference{
.attachment = static_cast<uint32_t>(attachments.size() - 1),
.layout = vkhpp::ImageLayout::eColorAttachmentOptimal,
};
}
std::optional<vkhpp::AttachmentReference> depthAttachment_reference;
if (depth_format != vkhpp::Format::eUndefined) {
attachments.push_back(vkhpp::AttachmentDescription{
.format = depth_format,
.samples = vkhpp::SampleCountFlagBits::e1,
.loadOp = vkhpp::AttachmentLoadOp::eClear,
.storeOp = vkhpp::AttachmentStoreOp::eStore,
.stencilLoadOp = vkhpp::AttachmentLoadOp::eClear,
.stencilStoreOp = vkhpp::AttachmentStoreOp::eStore,
.initialLayout = vkhpp::ImageLayout::eColorAttachmentOptimal,
.finalLayout = vkhpp::ImageLayout::eColorAttachmentOptimal,
});
depthAttachment_reference = vkhpp::AttachmentReference{
.attachment = static_cast<uint32_t>(attachments.size() - 1),
.layout = vkhpp::ImageLayout::eDepthStencilAttachmentOptimal,
};
}
vkhpp::SubpassDependency dependency = {
.srcSubpass = 0,
.dstSubpass = 0,
.srcStageMask = {},
.dstStageMask = vkhpp::PipelineStageFlagBits::eFragmentShader,
.srcAccessMask = {},
.dstAccessMask = vkhpp::AccessFlagBits::eInputAttachmentRead,
.dependencyFlags = vkhpp::DependencyFlagBits::eByRegion,
};
if (color_format != vkhpp::Format::eUndefined) {
dependency.srcStageMask |=
vkhpp::PipelineStageFlagBits::eColorAttachmentOutput;
dependency.dstStageMask |=
vkhpp::PipelineStageFlagBits::eColorAttachmentOutput;
dependency.srcAccessMask |= vkhpp::AccessFlagBits::eColorAttachmentWrite;
}
if (depth_format != vkhpp::Format::eUndefined) {
dependency.srcStageMask |=
vkhpp::PipelineStageFlagBits::eColorAttachmentOutput;
dependency.dstStageMask |=
vkhpp::PipelineStageFlagBits::eColorAttachmentOutput;
dependency.srcAccessMask |= vkhpp::AccessFlagBits::eColorAttachmentWrite;
}
vkhpp::SubpassDescription subpass = {
.pipelineBindPoint = vkhpp::PipelineBindPoint::eGraphics,
.inputAttachmentCount = 0,
.pInputAttachments = nullptr,
.colorAttachmentCount = 0,
.pColorAttachments = nullptr,
.pResolveAttachments = nullptr,
.pDepthStencilAttachment = nullptr,
.pPreserveAttachments = nullptr,
};
if (color_format != vkhpp::Format::eUndefined) {
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &*colorAttachment_reference;
}
if (depth_format != vkhpp::Format::eUndefined) {
subpass.pDepthStencilAttachment = &*depthAttachment_reference;
}
const vkhpp::RenderPassCreateInfo renderpassCreateInfo = {
.attachmentCount = static_cast<uint32_t>(attachments.size()),
.pAttachments = attachments.data(),
.subpassCount = 1,
.pSubpasses = &subpass,
.dependencyCount = 1,
.pDependencies = &dependency,
};
auto renderpass = VK_EXPECT_RV(mDevice->createRenderPassUnique(renderpassCreateInfo));
std::vector<vkhpp::ImageView> framebufferAttachments;
if (colorAttachment) {
framebufferAttachments.push_back(*colorAttachment->imageView);
}
if (depthAttachment) {
framebufferAttachments.push_back(*depthAttachment->imageView);
}
const vkhpp::FramebufferCreateInfo framebufferCreateInfo = {
.renderPass = *renderpass,
.attachmentCount = static_cast<uint32_t>(framebufferAttachments.size()),
.pAttachments = framebufferAttachments.data(),
.width = width,
.height = height,
.layers = 1,
};
auto framebuffer = VK_EXPECT_RV(mDevice->createFramebufferUnique(framebufferCreateInfo));
return Vk::FramebufferWithAttachments{
.colorAttachment = std::move(colorAttachment),
.depthAttachment = std::move(depthAttachment),
.renderpass = std::move(renderpass),
.framebuffer = std::move(framebuffer),
};
}
vkhpp::Result Vk::DoCommandsImmediate(
const std::function<vkhpp::Result(vkhpp::UniqueCommandBuffer&)>& func,
const std::vector<vkhpp::UniqueSemaphore>& semaphores_wait,
const std::vector<vkhpp::UniqueSemaphore>& semaphores_signal) {
const vkhpp::CommandBufferAllocateInfo commandBufferAllocateInfo = {
.commandPool = *mCommandPool,
.level = vkhpp::CommandBufferLevel::ePrimary,
.commandBufferCount = 1,
};
auto commandBuffers = VK_TRY_RV(mDevice->allocateCommandBuffersUnique(commandBufferAllocateInfo));
auto commandBuffer = std::move(commandBuffers[0]);
const vkhpp::CommandBufferBeginInfo commandBufferBeginInfo = {
.flags = vkhpp::CommandBufferUsageFlagBits::eOneTimeSubmit,
};
commandBuffer->begin(commandBufferBeginInfo);
VK_TRY(func(commandBuffer));
commandBuffer->end();
std::vector<vkhpp::CommandBuffer> commandBufferHandles;
commandBufferHandles.push_back(*commandBuffer);
std::vector<vkhpp::Semaphore> semaphoreHandlesWait;
semaphoreHandlesWait.reserve(semaphores_wait.size());
for (const auto& s : semaphores_wait) {
semaphoreHandlesWait.emplace_back(*s);
}
std::vector<vkhpp::Semaphore> semaphoreHandlesSignal;
semaphoreHandlesSignal.reserve(semaphores_signal.size());
for (const auto& s : semaphores_signal) {
semaphoreHandlesSignal.emplace_back(*s);
}
vkhpp::SubmitInfo submitInfo = {
.commandBufferCount = static_cast<uint32_t>(commandBufferHandles.size()),
.pCommandBuffers = commandBufferHandles.data(),
};
if (!semaphoreHandlesWait.empty()) {
submitInfo.waitSemaphoreCount = static_cast<uint32_t>(semaphoreHandlesWait.size());
submitInfo.pWaitSemaphores = semaphoreHandlesWait.data();
}
if (!semaphoreHandlesSignal.empty()) {
submitInfo.signalSemaphoreCount = static_cast<uint32_t>(semaphoreHandlesSignal.size());
submitInfo.pSignalSemaphores = semaphoreHandlesSignal.data();
}
mQueue.submit(submitInfo);
mQueue.waitIdle();
return vkhpp::Result::eSuccess;
}
} // namespace gfxstream