-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpyroenc.cpp
More file actions
2753 lines (2266 loc) · 91.9 KB
/
Copy pathpyroenc.cpp
File metadata and controls
2753 lines (2266 loc) · 91.9 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
// Copyright (c) 2024 Arntzen Software AS
// SPDX-License-Identifier: MIT
#include "pyroenc.hpp"
#include <atomic>
#include <utility>
#include <vector>
#include <queue>
#include <assert.h>
#include <stdio.h>
#define VK_CALL(x) table.x
namespace PyroEnc
{
struct VkTable
{
#define INSTANCE_FUNCTION(fun) PFN_vk##fun vk##fun
#define DEVICE_FUNCTION(fun) PFN_vk##fun vk##fun
#define DEVICE_FUNCTION_FALLBACK(fun, fall) PFN_vk##fun vk##fun
#include "pyroenc_vk_table.inl"
#undef INSTANCE_FUNCTION
#undef DEVICE_FUNCTION
#undef DEVICE_FUNCTION_FALLBACK
};
struct ConversionRegisters
{
uint32_t width;
uint32_t height;
float dither_strength;
};
struct Timeline
{
VkSemaphore timeline;
// Represents the highest value submitted to Vulkan.
uint64_t value;
};
struct Pipeline
{
VkPipeline pipeline;
VkPipelineLayout layout;
VkDescriptorSetLayout set_layout;
};
struct Memory
{
VkDeviceMemory memory;
void *mapped;
};
struct Image
{
VkImage image;
VkImageView view;
Memory memory;
};
struct Buffer
{
VkBuffer buffer;
Memory memory;
};
struct Frame
{
uint64_t compute;
uint64_t encode;
VkCommandBuffer convert_cmd;
VkCommandBuffer encode_cmd;
Image image_ycbcr;
Buffer payload;
};
struct VideoProfile
{
VkVideoProfileInfoKHR profile_info = { VK_STRUCTURE_TYPE_VIDEO_PROFILE_INFO_KHR };
VkVideoProfileListInfoKHR profile_list = { VK_STRUCTURE_TYPE_VIDEO_PROFILE_LIST_INFO_KHR };
VkVideoEncodeUsageInfoKHR usage_info = { VK_STRUCTURE_TYPE_VIDEO_ENCODE_USAGE_INFO_KHR };
struct Format
{
VkFormat format = VK_FORMAT_UNDEFINED;
VkFormat luma_format = VK_FORMAT_UNDEFINED;
VkFormat chroma_format = VK_FORMAT_UNDEFINED;
uint32_t subsample_log2[2] = {};
VkImageFormatProperties format_properties = {};
} input, dpb;
union
{
struct
{
VkVideoEncodeH264ProfileInfoKHR profile;
} h264;
struct
{
VkVideoEncodeH265ProfileInfoKHR profile;
} h265;
};
bool setup(Encoder::Impl &impl, Profile profile);
Format get_format_info(Encoder::Impl &impl, VkImageUsageFlags usage);
};
struct VideoEncoderCaps
{
VkVideoCapabilitiesKHR video_caps = { VK_STRUCTURE_TYPE_VIDEO_CAPABILITIES_KHR };
VkVideoEncodeCapabilitiesKHR encode_caps = { VK_STRUCTURE_TYPE_VIDEO_ENCODE_CAPABILITIES_KHR };
union
{
struct
{
VkVideoEncodeH264CapabilitiesKHR caps;
} h264;
struct
{
VkVideoEncodeH265CapabilitiesKHR caps;
} h265;
};
bool setup(Encoder::Impl &impl);
uint32_t get_aligned_width(uint32_t width) const;
uint32_t get_aligned_height(uint32_t height) const;
};
struct VideoSession
{
std::vector<Memory> memory;
VkVideoSessionKHR session = VK_NULL_HANDLE;
bool init(Encoder::Impl &impl);
void destroy(Encoder::Impl &impl);
};
struct VideoSessionParameters
{
VkVideoSessionParametersKHR params = VK_NULL_HANDLE;
VkVideoEncodeQualityLevelInfoKHR quality_level =
{ VK_STRUCTURE_TYPE_VIDEO_ENCODE_QUALITY_LEVEL_INFO_KHR };
VkVideoEncodeQualityLevelPropertiesKHR quality_level_props =
{ VK_STRUCTURE_TYPE_VIDEO_ENCODE_QUALITY_LEVEL_PROPERTIES_KHR };
union
{
struct
{
StdVideoH264SequenceParameterSet sps;
StdVideoH264PictureParameterSet pps;
StdVideoH264SequenceParameterSetVui vui;
VkVideoEncodeH264QualityLevelPropertiesKHR quality_level_props;
} h264;
struct
{
StdVideoH265SequenceParameterSet sps;
StdVideoH265PictureParameterSet pps;
StdVideoH265VideoParameterSet vps;
StdVideoH265SequenceParameterSetVui vui;
VkVideoEncodeH265QualityLevelPropertiesKHR quality_level_props;
} h265;
};
bool init(Encoder::Impl &impl);
void destroy(Encoder::Impl &impl);
std::vector<uint8_t> encoded_parameters;
bool init_h264(Encoder::Impl &impl);
bool init_h265(Encoder::Impl &impl);
};
struct RateControl
{
RateControl();
VkVideoCodingControlInfoKHR ctrl_info =
{ VK_STRUCTURE_TYPE_VIDEO_CODING_CONTROL_INFO_KHR };
VkVideoEncodeRateControlInfoKHR rate_info =
{ VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_INFO_KHR };
VkVideoEncodeRateControlLayerInfoKHR layer =
{ VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_LAYER_INFO_KHR };
union
{
struct
{
VkVideoEncodeH264RateControlInfoKHR rate_control;
VkVideoEncodeH264RateControlLayerInfoKHR layer;
} h264;
struct
{
VkVideoEncodeH265RateControlInfoKHR rate_control;
VkVideoEncodeH265RateControlLayerInfoKHR layer;
} h265;
};
bool init(Encoder::Impl &impl);
uint64_t frame_index = 0;
uint64_t gop_frame_index = 0;
uint32_t idr_pic_id = 0;
bool needs_reset = true;
RateControlInfo info;
};
// This will limit how many EncodedFrames we can have in flight.
// More than or 2 or 3 seems highly unusual.
static constexpr uint32_t FramePoolSize = 4;
// TODO: For B-frames, we might need 3.
static constexpr uint32_t DPBSize = 2;
// TODO: For B-frames, we might need 2.
static constexpr uint32_t MaxActiveReferencePictures = DPBSize - 1;
// Should be enough for everyone.
static constexpr uint32_t MaxPayloadSize = 4 * 1024 * 1024;
struct Encoder::Impl
{
Impl();
~Impl();
bool init_encoder(const EncoderCreateInfo &info);
bool wait(uint64_t compute_timeline, uint64_t encode_timeline, uint64_t timeout) const;
bool wait_frame_pool_index(uint32_t index, uint64_t timeout) const;
void release_frame_pool_index(uint32_t index);
uint32_t allocate_frame_pool_index();
bool submit_conversion(const FrameInfo &input, Frame &frame);
bool submit_encode(Frame &frame, bool &is_idr);
void transition_conversion_dst_images(VkCommandBuffer cmd);
void copy_to_ycbcr(VkCommandBuffer cmd, Frame &frame);
bool record_and_submit_encode(VkCommandBuffer cmd, Frame &frame, bool &is_idr);
bool submit_encode_command_buffer(VkCommandBuffer cmd);
void record_rate_control(VkCommandBuffer cmd);
void record_host_barrier(VkCommandBuffer cmd, Frame &frame);
void record_acquire_barrier(VkCommandBuffer cmd, const Frame &frame);
void record_dpb_barrier(VkCommandBuffer cmd);
Result send_frame(const FrameInfo &input);
Result send_eof();
Result receive_encoded_frame(EncodedFrame &frame);
std::queue<EncodedFrame> encoded_queue;
Timeline compute_timeline = {};
Timeline encode_timeline = {};
Pipeline conversion_pipeline = {};
VkCommandPool convert_cmd_pool = VK_NULL_HANDLE;
VkCommandPool encode_cmd_pool = VK_NULL_HANDLE;
VkQueryPool query_pool = VK_NULL_HANDLE;
VkQueryPool query_pool_timestamp = VK_NULL_HANDLE;
uint32_t encode_timestamp_bits = 0;
VkTable table = {};
bool func_table_is_valid = false;
Frame frame_pool[FramePoolSize] = {};
std::atomic_uint32_t active_frame_pool_indices;
struct Dpb
{
Image dpb[DPBSize];
Image array_dpb;
Image luma;
Image chroma;
bool dpb_inited = false;
} dpb = {};
EncoderCreateInfo info = {};
VkPhysicalDeviceMemoryProperties mem_props = {};
VkPhysicalDeviceProperties vk_props = {};
VkPhysicalDeviceVulkan12Properties vk12_props = {};
LogCallback *cb = nullptr;
template <typename... Ts>
void log(Severity severity, const char *fmt, Ts&&... ts);
bool allocate_memory(Memory &memory, VkMemoryPropertyFlags props, const VkMemoryRequirements &reqs);
bool create_buffer(Buffer &buffer, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags props,
const void *pNext);
bool create_image(Image &image, uint32_t width, uint32_t height, uint32_t layers,
VkFormat format, VkImageUsageFlags usage,
const void *pNext);
bool create_timeline_semaphore(Timeline &timeline);
bool create_compute_pipeline(Pipeline &pipeline, const uint32_t *code, size_t code_size,
const VkDescriptorSetLayoutBinding *binding, uint32_t num_bindings,
const VkPushConstantRange *push_ranges, uint32_t num_push_ranges);
void destroy_image(Image &image);
void destroy_buffer(Buffer &buffer);
void destroy_frame_resources(Frame &frame);
void destroy_dpb();
void destroy_pipeline(Pipeline &pipeline);
void destroy_timeline(Timeline &timeline);
void free_memory(Memory &memory);
bool init_func_table();
bool init_frame_resources();
bool init_command_pools();
bool init_query_pool();
bool init_frame_resource(Frame &frame);
bool init_dpb_resources();
bool init_pipelines();
VideoProfile profile;
VideoEncoderCaps caps;
VideoSession session;
VideoSessionParameters session_params;
RateControl rate;
};
bool Encoder::Impl::create_image(Image &image, uint32_t width, uint32_t height, uint32_t layers, VkFormat format,
VkImageUsageFlags usage, const void *pNext)
{
image = {};
VkImageCreateInfo image_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
image_info.format = format;
image_info.extent = { width, height, 1 };
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.usage = usage;
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.mipLevels = 1;
image_info.arrayLayers = layers;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.pNext = pNext;
if (VK_CALL(vkCreateImage(info.device, &image_info, nullptr, &image.image)) != VK_SUCCESS)
return false;
VkMemoryRequirements reqs;
VK_CALL(vkGetImageMemoryRequirements(info.device, image.image, &reqs));
if (!allocate_memory(image.memory, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, reqs) &&
!allocate_memory(image.memory, 0, reqs))
{
return false;
}
if (VK_CALL(vkBindImageMemory(info.device, image.image, image.memory.memory, 0)) != VK_SUCCESS)
return false;
VkImageViewCreateInfo view_info = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
view_info.format = format;
view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, VK_REMAINING_ARRAY_LAYERS };
view_info.viewType = layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D;
view_info.image = image.image;
if (VK_CALL(vkCreateImageView(info.device, &view_info, nullptr, &image.view)) != VK_SUCCESS)
return false;
return true;
}
bool Encoder::Impl::create_buffer(Buffer &buffer, VkDeviceSize size, VkBufferUsageFlags usage,
VkMemoryPropertyFlags props, const void *pNext)
{
buffer = {};
VkBufferCreateInfo buffer_info = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
buffer_info.size = size;
buffer_info.usage = usage;
buffer_info.pNext = pNext;
const uint32_t family_indices[] = { info.conversion_queue.family_index, info.encode_queue.family_index };
if (family_indices[0] != family_indices[1])
{
buffer_info.sharingMode = VK_SHARING_MODE_CONCURRENT;
buffer_info.queueFamilyIndexCount = 2;
buffer_info.pQueueFamilyIndices = family_indices;
}
else
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (VK_CALL(vkCreateBuffer(info.device, &buffer_info, nullptr, &buffer.buffer)) != VK_SUCCESS)
return false;
VkMemoryRequirements reqs = {};
VK_CALL(vkGetBufferMemoryRequirements(info.device, buffer.buffer, &reqs));
if (!allocate_memory(buffer.memory, props, reqs) ||
VK_CALL(vkBindBufferMemory(info.device, buffer.buffer, buffer.memory.memory, 0)) != VK_SUCCESS)
{
destroy_buffer(buffer);
return false;
}
return true;
}
bool Encoder::Impl::create_compute_pipeline(Pipeline &pipeline, const uint32_t *code, size_t code_size,
const VkDescriptorSetLayoutBinding *binding, uint32_t num_bindings,
const VkPushConstantRange *push_ranges, uint32_t num_push_ranges)
{
pipeline = {};
VkShaderModuleCreateInfo module_info = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
module_info.pCode = code;
module_info.codeSize = code_size;
VkDescriptorSetLayoutCreateInfo set_layout_info = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
set_layout_info.bindingCount = num_bindings;
set_layout_info.pBindings = binding;
set_layout_info.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR;
if (VK_CALL(vkCreateDescriptorSetLayout(info.device, &set_layout_info, nullptr, &pipeline.set_layout)) != VK_SUCCESS)
return false;
VkPipelineLayoutCreateInfo layout_info = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
layout_info.pPushConstantRanges = push_ranges;
layout_info.pushConstantRangeCount = num_push_ranges;
layout_info.setLayoutCount = 1;
layout_info.pSetLayouts = &pipeline.set_layout;
if (VK_CALL(vkCreatePipelineLayout(info.device, &layout_info, nullptr, &pipeline.layout)) != VK_SUCCESS)
{
destroy_pipeline(pipeline);
return false;
}
VkShaderModule module = VK_NULL_HANDLE;
if (VK_CALL(vkCreateShaderModule(info.device, &module_info, nullptr, &module)) != VK_SUCCESS)
{
destroy_pipeline(pipeline);
return false;
}
VkComputePipelineCreateInfo compute_info = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO };
compute_info.layout = pipeline.layout;
compute_info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
compute_info.stage.module = module;
compute_info.stage.pName = "main";
compute_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
VkResult vr = VK_CALL(vkCreateComputePipelines(info.device, VK_NULL_HANDLE,
1, &compute_info, nullptr, &pipeline.pipeline));
VK_CALL(vkDestroyShaderModule(info.device, module, nullptr));
if (vr != VK_SUCCESS)
destroy_pipeline(pipeline);
return vr == VK_SUCCESS;
}
bool Encoder::Impl::create_timeline_semaphore(Timeline &timeline)
{
VkSemaphoreTypeCreateInfo type_info = { VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO };
VkSemaphoreCreateInfo sem_info = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
sem_info.pNext = &type_info;
type_info.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
timeline = {};
return VK_CALL(vkCreateSemaphore(info.device, &sem_info, nullptr, &timeline.timeline)) == VK_SUCCESS;
}
bool Encoder::Impl::allocate_memory(Memory &memory, VkMemoryPropertyFlags props, const VkMemoryRequirements &reqs)
{
for (uint32_t i = 0; i < mem_props.memoryTypeCount; i++)
{
if ((reqs.memoryTypeBits & (1u << i)) == 0)
continue;
if ((props & mem_props.memoryTypes[i].propertyFlags) == props)
{
VkMemoryAllocateInfo alloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
alloc.memoryTypeIndex = i;
alloc.allocationSize = reqs.size;
if (VK_CALL(vkAllocateMemory(info.device, &alloc, nullptr, &memory.memory)) != VK_SUCCESS)
continue;
if ((props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
if (VK_CALL(vkMapMemory(info.device, memory.memory, 0, VK_WHOLE_SIZE, 0, &memory.mapped)) != VK_SUCCESS)
{
VK_CALL(vkFreeMemory(info.device, memory.memory, nullptr));
memory.memory = VK_NULL_HANDLE;
continue;
}
}
return true;
}
}
memory = {};
return false;
}
void Encoder::Impl::free_memory(Memory &memory)
{
// Host memory is automatically unmapped if it is mapped.
VK_CALL(vkFreeMemory(info.device, memory.memory, nullptr));
memory = {};
}
void Encoder::Impl::destroy_image(Image &image)
{
VK_CALL(vkDestroyImageView(info.device, image.view, nullptr));
VK_CALL(vkDestroyImage(info.device, image.image, nullptr));
free_memory(image.memory);
image = {};
}
void Encoder::Impl::destroy_buffer(Buffer &buffer)
{
VK_CALL(vkDestroyBuffer(info.device, buffer.buffer, nullptr));
free_memory(buffer.memory);
}
void Encoder::Impl::destroy_frame_resources(Frame &frame)
{
destroy_image(frame.image_ycbcr);
destroy_buffer(frame.payload);
frame = {};
}
void Encoder::Impl::destroy_pipeline(Pipeline &pipeline)
{
VK_CALL(vkDestroyPipeline(info.device, pipeline.pipeline, nullptr));
VK_CALL(vkDestroyPipelineLayout(info.device, pipeline.layout, nullptr));
VK_CALL(vkDestroyDescriptorSetLayout(info.device, pipeline.set_layout, nullptr));
pipeline = {};
}
void Encoder::Impl::destroy_timeline(Timeline &timeline)
{
VK_CALL(vkDestroySemaphore(info.device, timeline.timeline, nullptr));
timeline = {};
}
struct EncodedFrame::Impl
{
~Impl();
int64_t pts = 0;
int64_t dts = 0;
bool is_idr = false;
const void *payload = nullptr;
uint32_t frame_pool_index = UINT32_MAX;
Encoder::Impl *encoder = nullptr;
struct Query
{
uint32_t offset;
uint32_t size;
VkQueryResultStatusKHR status;
};
bool get_query(Query &query_data) const;
double get_encoding_overhead() const;
};
EncodedFrame::EncodedFrame()
{
impl.reset(new Impl);
}
EncodedFrame::EncodedFrame(PyroEnc::EncodedFrame &&other) noexcept
{
*this = std::move(other);
}
EncodedFrame &EncodedFrame::operator=(EncodedFrame &&other) noexcept
{
if (this != &other)
impl = std::move(other.impl);
return *this;
}
EncodedFrame::Impl &EncodedFrame::get_impl()
{
return *impl;
}
EncodedFrame::~EncodedFrame()
{
}
EncodedFrame::Impl::~Impl()
{
if (encoder)
encoder->release_frame_pool_index(frame_pool_index);
}
int64_t EncodedFrame::get_pts() const
{
return impl->pts;
}
int64_t EncodedFrame::get_dts() const
{
return impl->dts;
}
bool EncodedFrame::Impl::get_query(Query &query_data) const
{
auto &enc = *encoder;
auto &table = enc.table;
if (VK_CALL(vkGetQueryPoolResults(enc.info.device, enc.query_pool, frame_pool_index, 1, sizeof(query_data),
&query_data, sizeof(query_data),
VK_QUERY_RESULT_WITH_STATUS_BIT_KHR)) != VK_SUCCESS)
return false;
return query_data.status == VK_QUERY_RESULT_STATUS_COMPLETE_KHR;
}
double EncodedFrame::Impl::get_encoding_overhead() const
{
auto &enc = *encoder;
auto &table = enc.table;
if (!enc.query_pool_timestamp)
return -1.0;
uint64_t ts[2];
if (VK_CALL(vkGetQueryPoolResults(enc.info.device, enc.query_pool_timestamp, 2 * frame_pool_index, 2, sizeof(ts),
ts, sizeof(ts[0]), VK_QUERY_RESULT_64_BIT)) != VK_SUCCESS)
return -1.0;
uint64_t tick_offset = (ts[1] - ts[0]) & (((1ull << enc.encode_timestamp_bits) - 1) >> 1);
return double(tick_offset) * enc.vk_props.limits.timestampPeriod * 1e-9;
}
size_t EncodedFrame::get_size() const
{
Impl::Query query = {};
if (!impl->get_query(query))
return 0;
else
return query.size;
}
double EncodedFrame::get_encoding_overhead() const
{
return impl->get_encoding_overhead();
}
VkQueryResultStatusKHR EncodedFrame::get_status() const
{
Impl::Query query = {};
if (!impl->get_query(query))
return VK_QUERY_RESULT_STATUS_NOT_READY_KHR;
else
return query.status;
}
bool EncodedFrame::is_idr() const
{
return impl->is_idr;
}
bool EncodedFrame::wait(uint64_t timeout) const
{
return impl->encoder->wait_frame_pool_index(impl->frame_pool_index, timeout);
}
const void *EncodedFrame::get_payload() const
{
Impl::Query query = {};
if (!impl->get_query(query))
return nullptr;
else
return static_cast<const uint8_t *>(impl->payload) + query.offset;
}
bool Encoder::Impl::wait(uint64_t compute, uint64_t encode, uint64_t timeout) const
{
if (!compute_timeline.timeline || !encode_timeline.timeline)
return false;
const VkSemaphore sems[] = { compute_timeline.timeline, encode_timeline.timeline };
const uint64_t values[] = { compute, encode };
VkSemaphoreWaitInfo wait_info = { VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
wait_info.semaphoreCount = 2;
wait_info.pSemaphores = sems;
wait_info.pValues = values;
return VK_CALL(vkWaitSemaphores(info.device, &wait_info, timeout)) == VK_SUCCESS;
}
bool Encoder::Impl::wait_frame_pool_index(uint32_t index, uint64_t timeout) const
{
auto &frame = frame_pool[index];
return wait(frame.compute, frame.encode, timeout);
}
void Encoder::Impl::release_frame_pool_index(uint32_t index)
{
uint32_t mask = 1u << index;
uint32_t old = active_frame_pool_indices.fetch_and(~mask, std::memory_order_release);
(void)old;
assert((old & mask) != 0);
}
uint32_t Encoder::Impl::allocate_frame_pool_index()
{
uint32_t bits = active_frame_pool_indices.load(std::memory_order_acquire);
for (uint32_t i = 0; i < FramePoolSize; i++)
{
uint32_t mask = 1u << i;
if ((bits & mask) == 0)
{
uint32_t old = active_frame_pool_indices.fetch_or(mask, std::memory_order_relaxed);
(void)old;
assert((old & mask) == 0);
return i;
}
}
return UINT32_MAX;
}
Encoder::Impl::Impl()
{
active_frame_pool_indices.store(0, std::memory_order_relaxed);
}
Encoder::Impl::~Impl()
{
// Relevant if we never initialized the encoder.
if (!func_table_is_valid)
return;
while (!encoded_queue.empty())
encoded_queue.pop();
// Hard assertion.
if (active_frame_pool_indices.load() != 0)
std::terminate();
for (uint32_t i = 0; i < FramePoolSize; i++)
wait_frame_pool_index(i, UINT64_MAX);
destroy_dpb();
for (auto &frame : frame_pool)
destroy_frame_resources(frame);
destroy_pipeline(conversion_pipeline);
destroy_timeline(compute_timeline);
destroy_timeline(encode_timeline);
VK_CALL(vkDestroyCommandPool(info.device, convert_cmd_pool, nullptr));
VK_CALL(vkDestroyCommandPool(info.device, encode_cmd_pool, nullptr));
VK_CALL(vkDestroyQueryPool(info.device, query_pool, nullptr));
VK_CALL(vkDestroyQueryPool(info.device, query_pool_timestamp, nullptr));
session_params.destroy(*this);
session.destroy(*this);
}
bool Encoder::Impl::init_func_table()
{
#define INSTANCE_FUNCTION(fun) \
table.vk##fun = (PFN_vk##fun)info.get_instance_proc_addr(info.instance, "vk" #fun); \
if (!table.vk##fun) \
return false
#define DEVICE_FUNCTION(fun)
#define DEVICE_FUNCTION_FALLBACK(fun, fall)
#include "pyroenc_vk_table.inl"
#undef INSTANCE_FUNCTION
#undef DEVICE_FUNCTION
#undef DEVICE_FUNCTION_FALLBACK
#define INSTANCE_FUNCTION(fun)
#define DEVICE_FUNCTION(fun) \
table.vk##fun = (PFN_vk##fun)table.vkGetDeviceProcAddr(info.device, "vk" #fun); \
if (!table.vk##fun) \
return false
#define DEVICE_FUNCTION_FALLBACK(fun, fall) \
table.vk##fun = (PFN_vk##fun)table.vkGetDeviceProcAddr(info.device, "vk" #fun); \
if (!table.vk##fun) \
table.vk##fun = (PFN_vk##fun)table.vkGetDeviceProcAddr(info.device, "vk" #fall); \
if (!table.vk##fun) \
return false
#include "pyroenc_vk_table.inl"
#undef INSTANCE_FUNCTION
#undef DEVICE_FUNCTION
#undef DEVICE_FUNCTION_FALLBACK
func_table_is_valid = true;
return true;
}
bool Encoder::Impl::init_frame_resources()
{
for (auto &frame : frame_pool)
if (!init_frame_resource(frame))
return false;
return true;
}
bool Encoder::Impl::init_dpb_resources()
{
uint32_t aligned_width = caps.get_aligned_width(info.width);
uint32_t aligned_height = caps.get_aligned_height(info.height);
if ((caps.video_caps.flags & VK_VIDEO_CAPABILITY_SEPARATE_REFERENCE_IMAGES_BIT_KHR) != 0)
{
// Could just use the array DPB formulation everywhere, but NV drivers are still bugged as of 570 series :(
for (auto &img: dpb.dpb)
{
if (!create_image(img, aligned_width, aligned_height, 1, profile.dpb.format,
VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR,
&profile.profile_list))
return false;
}
}
else
{
if (!create_image(dpb.array_dpb, aligned_width, aligned_height, DPBSize, profile.dpb.format,
VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR,
&profile.profile_list))
return false;
}
if (!create_image(dpb.luma, aligned_width, aligned_height, 1, profile.input.luma_format,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_STORAGE_BIT, nullptr))
return false;
if (!create_image(dpb.chroma,
aligned_width >> profile.input.subsample_log2[0],
aligned_height >> profile.input.subsample_log2[1],
1,
profile.input.chroma_format,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_STORAGE_BIT, nullptr))
return false;
return true;
}
bool Encoder::Impl::init_pipelines()
{
static const uint32_t code[] =
#include "shaders/rgb_to_yuv.inc"
;
VkDescriptorSetLayoutBinding bindings[3] = {};
VkPushConstantRange push = {};
bindings[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
bindings[0].binding = 0;
bindings[0].descriptorCount = 1;
bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
bindings[1].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
bindings[1].binding = 1;
bindings[1].descriptorCount = 1;
bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
bindings[2].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
bindings[2].binding = 2;
bindings[2].descriptorCount = 1;
bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
push.size = sizeof(ConversionRegisters);
push.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
if (!create_compute_pipeline(conversion_pipeline, code, sizeof(code), bindings, 3, &push, 1))
return false;
return true;
}
void Encoder::Impl::transition_conversion_dst_images(VkCommandBuffer cmd)
{
VkDependencyInfo deps = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO };
VkImageMemoryBarrier2 image_barrier[2];
for (auto &barrier : image_barrier)
{
barrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2 };
barrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
// Wait for previous frame's copy to YCbCr image to complete.
barrier.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
barrier.dstStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT;
barrier.dstAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT;
}
image_barrier[0].image = dpb.luma.image;
image_barrier[1].image = dpb.chroma.image;
deps.imageMemoryBarrierCount = 2;
deps.pImageMemoryBarriers = image_barrier;
VK_CALL(vkCmdPipelineBarrier2(cmd, &deps));
}
void Encoder::Impl::copy_to_ycbcr(VkCommandBuffer cmd, Frame &frame)
{
// This is somewhat unfortunate, but NVIDIA does not expose imageCreateFlags with MUTABLE or EXTENDED_USAGE,
// so we cannot create YCbCr video image with STORAGE + MUTABLE and take per-plane views.
// Just copy into the YCbCr planes instead, which isn't ideal, but could be worse.
VkDependencyInfo deps = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO };
VkImageMemoryBarrier2 image_barrier[3];
for (uint32_t i = 0; i < 3; i++)
{
auto &barrier = image_barrier[i];
barrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2 };
barrier.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
if (i < 2)
{
barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT;
barrier.srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT;
barrier.dstStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
barrier.dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT;
}
else
{
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
// The YCbCr image is idle since we waited for semaphores.
barrier.srcStageMask = VK_PIPELINE_STAGE_NONE;
barrier.srcAccessMask = VK_ACCESS_2_NONE;
barrier.dstStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
barrier.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT;
}
}
image_barrier[0].image = dpb.luma.image;
image_barrier[1].image = dpb.chroma.image;
image_barrier[2].image = frame.image_ycbcr.image;
deps.imageMemoryBarrierCount = 3;
deps.pImageMemoryBarriers = image_barrier;
VK_CALL(vkCmdPipelineBarrier2(cmd, &deps));
VkImageCopy regions[2] = {};
regions[0].extent = { caps.get_aligned_width(info.width), caps.get_aligned_height(info.height), 1 };
regions[0].srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
regions[0].dstSubresource = { VK_IMAGE_ASPECT_PLANE_0_BIT, 0, 0, 1 };
regions[1].extent = {
caps.get_aligned_width(info.width) >> profile.input.subsample_log2[0],
caps.get_aligned_height(info.height) >> profile.input.subsample_log2[1],
1,
};
regions[1].srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 };
regions[1].dstSubresource = { VK_IMAGE_ASPECT_PLANE_1_BIT, 0, 0, 1 };
VK_CALL(vkCmdCopyImage(cmd, dpb.luma.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
frame.image_ycbcr.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, ®ions[0]));
VK_CALL(vkCmdCopyImage(cmd, dpb.chroma.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
frame.image_ycbcr.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, ®ions[1]));
// Transfer ownership to video queue.
auto &barrier = image_barrier[2];
barrier.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
barrier.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT;
barrier.dstStageMask = VK_PIPELINE_STAGE_NONE;
barrier.dstAccessMask = VK_ACCESS_NONE;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_VIDEO_ENCODE_SRC_KHR;
if (info.conversion_queue.family_index != info.encode_queue.family_index)
{
barrier.srcQueueFamilyIndex = info.conversion_queue.family_index;
barrier.dstQueueFamilyIndex = info.encode_queue.family_index;
}
deps.imageMemoryBarrierCount = 1;
deps.pImageMemoryBarriers = &barrier;
VK_CALL(vkCmdPipelineBarrier2(cmd, &deps));
}
bool Encoder::Impl::submit_conversion(const FrameInfo &input, Frame &frame)
{
VkCommandBuffer cmd = frame.convert_cmd;
VK_CALL(vkResetCommandBuffer(cmd, 0));
VkCommandBufferBeginInfo begin_info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
VK_CALL(vkBeginCommandBuffer(cmd, &begin_info));
transition_conversion_dst_images(cmd);
ConversionRegisters params = {};
params.width = input.width;
params.height = input.height;
const float dither_strength = info.profile == Profile::H265_Main10 ? 1.0f / 1023.0f : 1.0f / 255.0f;
params.dither_strength = dither_strength;
VK_CALL(vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, conversion_pipeline.pipeline));