-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathvideo.cpp
More file actions
3696 lines (3223 loc) · 129 KB
/
Copy pathvideo.cpp
File metadata and controls
3696 lines (3223 loc) · 129 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
/**
* @file src/video.cpp
* @brief Definitions for video.
*/
// standard includes
#include <array>
#include <atomic>
#include <bitset>
#include <list>
#include <thread>
#include <utility>
// lib includes
#include <boost/pointer_cast.hpp>
extern "C" {
#include <libavutil/imgutils.h>
#include <libavutil/mastering_display_metadata.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#if !defined(_WIN32) && !defined(__APPLE__)
#include <ffnvcodec/nvEncodeAPI.h>
#endif
}
// local includes
#include "cbs.h"
#include "config.h"
#include "display_device.h"
#include "globals.h"
#include "input.h"
#include "logging.h"
#include "nvenc/nvenc_encoder.h"
#include "platform/common.h"
#include "sync.h"
#include "video.h"
#ifdef _WIN32
extern "C" {
#include <libavutil/hwcontext_d3d11va.h>
}
#endif
using namespace std::literals;
namespace video {
namespace {
/**
* @brief Check if we can allow probing for the encoders.
* @return True if there should be no issues with the probing, false if we should prevent it.
*/
bool allow_encoder_probing() {
const auto devices {display_device::enumerate_devices()};
// If there are no devices, then either the API is not working correctly or OS does not support the lib.
// Either way we should not block the probing in this case as we can't tell what's wrong.
if (devices.empty()) {
return true;
}
// Since Windows 11 24H2, it is possible that there will be no active devices present
// for some reason (probably a bug). Trying to probe encoders in such a state locks/breaks the DXGI
// and also the display device for Windows. So we must have at least 1 active device.
const bool at_least_one_device_is_active = std::any_of(std::begin(devices), std::end(devices), [](const auto &device) {
// If device has additional info, it is active.
return static_cast<bool>(device.m_info);
});
if (at_least_one_device_is_active) {
return true;
}
BOOST_LOG(error) << "No display devices are active at the moment! Cannot probe the encoders.";
return false;
}
} // namespace
/**
* @brief Release context resources.
*/
void free_ctx(AVCodecContext *ctx) {
avcodec_free_context(&ctx);
}
/**
* @brief Release an FFmpeg frame allocated by the capture or conversion backend.
*/
void free_frame(AVFrame *frame) {
av_frame_free(&frame);
}
/**
* @brief Release a backend buffer allocated for capture or conversion.
*/
void free_buffer(AVBufferRef *ref) {
av_buffer_unref(&ref);
}
namespace nv {
/**
* @brief Enumerates supported profile h264 options.
*/
enum class profile_h264_e : int {
high = 2, ///< High profile
high_444p = 3, ///< High 4:4:4 Predictive profile
};
/**
* @brief Enumerates supported profile HEVC options.
*/
enum class profile_hevc_e : int {
main = 0, ///< Main profile
main_10 = 1, ///< Main 10 profile
rext = 2, ///< Rext profile
};
} // namespace nv
namespace qsv {
/**
* @brief Enumerates supported profile h264 options.
*/
enum class profile_h264_e : int {
high = 100, ///< High profile
high_444p = 244, ///< High 4:4:4 Predictive profile
};
/**
* @brief Enumerates supported profile HEVC options.
*/
enum class profile_hevc_e : int {
main = 1, ///< Main profile
main_10 = 2, ///< Main 10 profile
rext = 4, ///< RExt profile
};
/**
* @brief Enumerates supported profile AV1 options.
*/
enum class profile_av1_e : int {
main = 1, ///< Main profile
high = 2, ///< High profile
};
} // namespace qsv
int select_h264_profile(std::string_view encoder_name, const config_t &config, int amd_coder) {
if (config.chromaSamplingType == 1) {
return AV_PROFILE_H264_HIGH_444_PREDICTIVE;
}
if (encoder_name == "h264_amf"sv && amd_coder == std::to_underlying(amf::coder_e::cavlc)) {
return AV_PROFILE_H264_CONSTRAINED_BASELINE;
}
return AV_PROFILE_H264_HIGH;
}
/**
* @brief Create an FFmpeg hardware device buffer for D3D11VA input.
*
* @param encode_device Encode device.
* @return Hardware buffer on success, or an error code on failure.
*/
util::Either<avcodec_buffer_t, int> dxgi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
/**
* @brief Create an FFmpeg hardware device buffer for VA-API input.
*
* @param encode_device Encode device.
* @return Hardware buffer on success, or an error code on failure.
*/
util::Either<avcodec_buffer_t, int> vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
/**
* @brief Create an FFmpeg hardware device buffer for CUDA input.
*
* @param encode_device Encode device.
* @return Hardware buffer on success, or an error code on failure.
*/
util::Either<avcodec_buffer_t, int> cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
/**
* @brief Create an FFmpeg hardware device buffer for VideoToolbox input.
*
* @param encode_device Encode device.
* @return Hardware buffer on success, or an error code on failure.
*/
util::Either<avcodec_buffer_t, int> vt_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
/**
* @brief Create an FFmpeg hardware device buffer for Vulkan input.
*
* @return Hardware buffer on success, or an error code on failure.
*/
util::Either<avcodec_buffer_t, int> vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
/**
* @brief FFmpeg software encode device used when no hardware frames are required.
*/
class avcodec_software_encode_device_t: public platf::avcodec_encode_device_t {
public:
/**
* @brief Accept a software frame without additional hardware conversion.
*
* @param img Image or frame object to read from or populate.
* @return Conversion status.
*/
int convert(platf::img_t &img) override {
// If we need to add aspect ratio padding, we need to scale into an intermediate output buffer
bool requires_padding = (sw_frame->width != sws_output_frame->width || sw_frame->height != sws_output_frame->height);
// Setup the input frame using the caller's img_t
sws_input_frame->data[0] = img.data;
sws_input_frame->linesize[0] = img.row_pitch;
// Perform color conversion and scaling to the final size
auto status = sws_scale_frame(sws.get(), requires_padding ? sws_output_frame.get() : sw_frame.get(), sws_input_frame.get());
if (status < 0) {
char string[AV_ERROR_MAX_STRING_SIZE];
BOOST_LOG(error) << "Couldn't scale frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status);
return -1;
}
// If we require aspect ratio padding, copy the output frame into the final padded frame
if (requires_padding) {
auto fmt_desc = av_pix_fmt_desc_get(static_cast<AVPixelFormat>(sws_output_frame->format));
auto planes = av_pix_fmt_count_planes(static_cast<AVPixelFormat>(sws_output_frame->format));
for (int plane = 0; plane < planes; plane++) {
auto shift_h = plane == 0 ? 0 : fmt_desc->log2_chroma_h;
auto shift_w = plane == 0 ? 0 : fmt_desc->log2_chroma_w;
auto offset = ((offsetW >> shift_w) * fmt_desc->comp[plane].step) + (offsetH >> shift_h) * sw_frame->linesize[plane];
// Copy line-by-line to preserve leading padding for each row
for (int line = 0; line < sws_output_frame->height >> shift_h; line++) {
memcpy(sw_frame->data[plane] + offset + (line * sw_frame->linesize[plane]), sws_output_frame->data[plane] + (line * sws_output_frame->linesize[plane]), static_cast<std::size_t>(sws_output_frame->width >> shift_w) * fmt_desc->comp[plane].step);
}
}
}
// If frame is not a software frame, it means we still need to transfer from main memory
// to vram memory
if (frame->hw_frames_ctx) {
auto status = av_hwframe_transfer_data(frame, sw_frame.get(), 0);
if (status < 0) {
char string[AV_ERROR_MAX_STRING_SIZE];
BOOST_LOG(error) << "Failed to transfer image data to hardware frame: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status);
return -1;
}
}
return 0;
}
/**
* @brief Attach frame resources used by the next conversion or encode operation.
*
* @param frame Video or graphics frame being processed.
* @param hw_frames_ctx FFmpeg hardware frames context associated with the frame.
* @return Status from updating frame.
*/
int set_frame(AVFrame *frame, AVBufferRef *hw_frames_ctx) override {
this->frame = frame;
// If it's a hwframe, allocate buffers for hardware
if (hw_frames_ctx) {
hw_frame.reset(frame);
if (av_hwframe_get_buffer(hw_frames_ctx, frame, 0)) {
return -1;
}
} else {
sw_frame.reset(frame);
}
return 0;
}
/**
* @brief Apply the configured colorspace metadata to the active frame.
*/
void apply_colorspace() override {
auto avcodec_colorspace = avcodec_colorspace_from_sunshine_colorspace(colorspace);
sws_setColorspaceDetails(sws.get(), sws_getCoefficients(SWS_CS_DEFAULT), 0, sws_getCoefficients(avcodec_colorspace.software_format), avcodec_colorspace.range - 1, 0, 1 << 16, 1 << 16);
}
/**
* When preserving aspect ratio, ensure that padding is black
*/
void prefill() {
auto frame = sw_frame ? sw_frame.get() : this->frame;
av_frame_get_buffer(frame, 0);
av_frame_make_writable(frame);
ptrdiff_t linesize[4] = {frame->linesize[0], frame->linesize[1], frame->linesize[2], frame->linesize[3]};
av_image_fill_black(frame->data, linesize, static_cast<AVPixelFormat>(frame->format), frame->color_range, frame->width, frame->height);
}
/**
* @brief Initialize FFmpeg software encoding for the requested codec.
*
* @param in_width In width.
* @param in_height In height.
* @param frame Video or graphics frame being processed.
* @param format Pixel, audio, or protocol format being converted.
* @param hardware Whether the frame is backed by hardware resources.
* @return 0 on success; nonzero or negative platform status on failure.
*/
int init(int in_width, int in_height, AVFrame *frame, AVPixelFormat format, bool hardware) {
// If the device used is hardware, yet the image resides on main memory
if (hardware) {
sw_frame.reset(av_frame_alloc());
sw_frame->width = frame->width;
sw_frame->height = frame->height;
sw_frame->format = format;
} else {
this->frame = frame;
}
// Fill aspect ratio padding in the destination frame
prefill();
auto out_width = frame->width;
auto out_height = frame->height;
// Ensure aspect ratio is maintained
auto scalar = std::fminf(static_cast<float>(out_width) / in_width, static_cast<float>(out_height) / in_height);
out_width = in_width * scalar;
out_height = in_height * scalar;
sws_input_frame.reset(av_frame_alloc());
sws_input_frame->width = in_width;
sws_input_frame->height = in_height;
sws_input_frame->format = AV_PIX_FMT_BGR0;
sws_output_frame.reset(av_frame_alloc());
sws_output_frame->width = out_width;
sws_output_frame->height = out_height;
sws_output_frame->format = format;
// Result is always positive
offsetW = (frame->width - out_width) / 2;
offsetH = (frame->height - out_height) / 2;
sws.reset(sws_alloc_context());
if (!sws) {
return -1;
}
AVDictionary *options {nullptr};
av_dict_set_int(&options, "srcw", sws_input_frame->width, 0);
av_dict_set_int(&options, "srch", sws_input_frame->height, 0);
av_dict_set_int(&options, "src_format", sws_input_frame->format, 0);
av_dict_set_int(&options, "dstw", sws_output_frame->width, 0);
av_dict_set_int(&options, "dsth", sws_output_frame->height, 0);
av_dict_set_int(&options, "dst_format", sws_output_frame->format, 0);
av_dict_set_int(&options, "sws_flags", SWS_LANCZOS | SWS_ACCURATE_RND, 0);
av_dict_set_int(&options, "threads", config::video.min_threads, 0);
auto status = av_opt_set_dict(sws.get(), &options);
av_dict_free(&options);
if (status < 0) {
char string[AV_ERROR_MAX_STRING_SIZE];
BOOST_LOG(error) << "Failed to set SWS options: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status);
return -1;
}
status = sws_init_context(sws.get(), nullptr, nullptr);
if (status < 0) {
char string[AV_ERROR_MAX_STRING_SIZE];
BOOST_LOG(error) << "Failed to initialize SWS: "sv << av_make_error_string(string, AV_ERROR_MAX_STRING_SIZE, status);
return -1;
}
return 0;
}
// Store ownership when frame is hw_frame
avcodec_frame_t hw_frame; ///< Hw frame.
avcodec_frame_t sw_frame; ///< Sw frame.
avcodec_frame_t sws_input_frame; ///< Sws input frame.
avcodec_frame_t sws_output_frame; ///< Sws output frame.
sws_t sws; ///< Software scaler used when frames need CPU-side pixel conversion.
// Offset of input image to output frame in pixels
int offsetW; ///< Offset w.
int offsetH; ///< Offset h.
};
/**
* @brief Enumerates supported flag options.
*/
enum flag_e : uint32_t {
DEFAULT = 0, ///< Default flags
PARALLEL_ENCODING = 1 << 1, ///< Capture and encoding can run concurrently on separate threads
H264_ONLY = 1 << 2, ///< When HEVC is too heavy
LIMITED_GOP_SIZE = 1 << 3, ///< Some encoders don't like it when you have an infinite GOP_SIZE. e.g. VAAPI
SINGLE_SLICE_ONLY = 1 << 4, ///< Never use multiple slices. Older intel iGPU's ruin it for everyone else
CBR_WITH_VBR = 1 << 5, ///< Use a VBR rate control mode to simulate CBR
RELAXED_COMPLIANCE = 1 << 6, ///< Use FF_COMPLIANCE_UNOFFICIAL compliance mode
NO_RC_BUF_LIMIT = 1 << 7, ///< Don't set rc_buffer_size
REF_FRAMES_INVALIDATION = 1 << 8, ///< Support reference frames invalidation
ALWAYS_REPROBE = 1 << 9, ///< This is an encoder of last resort and we want to aggressively probe for a better one
YUV444_SUPPORT = 1 << 10, ///< Encoder may support 4:4:4 chroma sampling depending on hardware
ASYNC_TEARDOWN = 1 << 11, ///< Encoder supports async teardown on a different thread
FIXED_GOP_SIZE = 1 << 12, ///< Use fixed small GOP size (encoder doesn't support on-demand IDR frames)
};
/**
* @brief FFmpeg AVCodec encode session and parameter-set rewriting state.
*/
class avcodec_encode_session_t: public encode_session_t {
public:
avcodec_encode_session_t() = default;
/**
* @brief Initialize an FFmpeg encode session and its hardware encode device.
*
* @param avcodec_ctx Open FFmpeg codec context for the selected encoder.
* @param encode_device Platform encode device that supplies frames to FFmpeg.
* @param inject Whether SPS/VPS replacement data should be injected.
*/
avcodec_encode_session_t(avcodec_ctx_t &&avcodec_ctx, std::unique_ptr<platf::avcodec_encode_device_t> encode_device, int inject):
avcodec_ctx {std::move(avcodec_ctx)},
device {std::move(encode_device)},
inject {inject} {
}
/**
* @brief Move an FFmpeg encode session without duplicating codec/device ownership.
*
* @param other Source object whose state is copied or moved into this object.
*/
avcodec_encode_session_t(avcodec_encode_session_t &&other) noexcept = default;
~avcodec_encode_session_t() {
// Flush any remaining frames in the encoder if the encoder started up (frame num > 0)
if (avcodec_ctx->frame_num > 0 && avcodec_send_frame(avcodec_ctx.get(), nullptr) == 0) {
packet_raw_avcodec pkt;
while (avcodec_receive_packet(avcodec_ctx.get(), pkt.av_packet) == 0);
}
// Order matters here because the context relies on the hwdevice still being valid
avcodec_ctx.reset();
device.reset();
}
// Ensure objects are destroyed in the correct order
/**
* @brief Assign state from another instance while preserving ownership semantics.
*
* @param other Source object whose state is copied or moved into this object.
* @return Reference or value produced by the operator.
*/
avcodec_encode_session_t &operator=(avcodec_encode_session_t &&other) {
device = std::move(other.device);
avcodec_ctx = std::move(other.avcodec_ctx);
replacements = std::move(other.replacements);
sps = std::move(other.sps);
vps = std::move(other.vps);
inject = other.inject;
return *this;
}
/**
* @brief Encode one frame with FFmpeg AVCodec and prepare packet replacements.
*
* @param img Image or frame object to read from or populate.
* @return Conversion status.
*/
int convert(platf::img_t &img) override {
if (!device) {
return -1;
}
return device->convert(img);
}
/**
* @brief Mark the frame as a request for an IDR frame.
*/
void request_idr_frame() override {
if (device && device->frame) {
auto &frame = device->frame;
frame->pict_type = AV_PICTURE_TYPE_I;
frame->flags |= AV_FRAME_FLAG_KEY;
}
}
/**
* @brief Mark the frame as a request for a normal inter frame.
*/
void request_normal_frame() override {
if (device && device->frame) {
auto &frame = device->frame;
frame->pict_type = AV_PICTURE_TYPE_NONE;
frame->flags &= ~AV_FRAME_FLAG_KEY;
}
}
/**
* @brief Mark the frame range whose references must be invalidated.
*
* @param first_frame First frame.
* @param last_frame Last frame.
*/
void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override {
BOOST_LOG(error) << "Encoder doesn't support reference frame invalidation";
request_idr_frame();
}
avcodec_ctx_t avcodec_ctx; ///< FFmpeg codec context owned by the encode session.
std::unique_ptr<platf::avcodec_encode_device_t> device; ///< Platform device used by the FFmpeg hardware encoder.
std::vector<packet_raw_t::replace_t> replacements; ///< NAL-unit byte ranges that must be replaced before packet send.
cbs::nal_t sps; ///< Original and rewritten sequence parameter set for IDR injection.
cbs::nal_t vps; ///< Original and rewritten HEVC video parameter set for IDR injection.
// inject sps/vps data into idr pictures
int inject; ///< Number of upcoming IDR frames that should receive rewritten parameter sets.
};
/**
* @brief NVENC encode session and device state for hardware encoding.
*/
class nvenc_encode_session_t: public encode_session_t {
public:
/**
* @brief Initialize an NVENC encode session and take ownership of its device.
*
* @param encode_device Encode device.
*/
nvenc_encode_session_t(std::unique_ptr<platf::nvenc_encode_device_t> encode_device):
device(std::move(encode_device)) {
}
/**
* @brief Encode one frame with NVENC and return the packet payload.
*
* @param img Image or frame object to read from or populate.
* @return Conversion status.
*/
int convert(platf::img_t &img) override {
if (!device) {
return -1;
}
return device->convert(img);
}
/**
* @brief Mark the frame as a request for an IDR frame.
*/
void request_idr_frame() override {
force_idr = true;
}
/**
* @brief Mark the frame as a request for a normal inter frame.
*/
void request_normal_frame() override {
force_idr = false;
}
/**
* @brief Mark the frame range whose references must be invalidated.
*
* @param first_frame First frame.
* @param last_frame Last frame.
*/
void invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override {
if (!device || !device->nvenc) {
return;
}
if (!device->nvenc->invalidate_ref_frames(first_frame, last_frame)) {
force_idr = true;
}
}
/**
* @brief Submit the next frame to NVENC and return the encoded payload.
*
* @param frame_index Monotonic frame index assigned by the video pipeline.
* @return Encoded NVENC frame payload and frame metadata.
*/
nvenc::nvenc_encoded_frame encode_frame(uint64_t frame_index) {
if (!device || !device->nvenc) {
return {};
}
auto result = device->nvenc->encode_frame(frame_index, force_idr);
force_idr = false;
return result;
}
private:
std::unique_ptr<platf::nvenc_encode_device_t> device;
bool force_idr = false;
};
/**
* @brief Context object used while synchronizing encode sessions.
*/
struct sync_session_ctx_t {
safe::signal_t *join_event; ///< Signal raised when the capture and encode workers should join.
safe::mail_raw_t::event_t<bool> shutdown_event; ///< Event raised when the stream should shut down.
safe::mail_raw_t::queue_t<packet_t> packets; ///< Queue receiving encoded video packets for the stream sender.
safe::mail_raw_t::event_t<bool> idr_events; ///< Event raised when an IDR frame is requested.
safe::mail_raw_t::event_t<hdr_info_t> hdr_events; ///< Event carrying updated HDR metadata.
safe::mail_raw_t::event_t<input::touch_port_t> touch_port_events; ///< Event carrying updated touch viewport metadata.
config_t config; ///< Stream or encoder configuration captured for the worker.
int frame_nr; ///< Next capture-frame number assigned to encoded packets.
void *channel_data; ///< Platform-specific channel data forwarded to packet senders.
};
/**
* @brief Synchronization state for one encode session.
*/
struct sync_session_t {
sync_session_ctx_t *ctx; ///< Shared capture/encode synchronization context.
std::unique_ptr<encode_session_t> session; ///< Active encoder session used by the capture thread.
};
/**
* @brief Queue of encode-session contexts waiting for capture work.
*/
using encode_session_ctx_queue_t = safe::queue_t<sync_session_ctx_t>;
/**
* @brief Platform capture status returned by encode operations.
*/
using encode_e = platf::capture_e;
/**
* @brief Capture thread context shared with the encoder session.
*/
struct capture_ctx_t {
img_event_t images; ///< Queue of captured images waiting for encode.
config_t config; ///< Stream or encoder configuration captured for the worker.
};
/**
* @brief Asynchronous capture thread state.
*/
struct capture_thread_async_ctx_t {
std::shared_ptr<safe::queue_t<capture_ctx_t>> capture_ctx_queue; ///< Capture ctx queue.
std::jthread capture_thread; ///< Capture thread.
safe::signal_t reinit_event; ///< Reinit event.
const encoder_t *encoder_p; ///< Encoder p.
sync_util::sync_t<std::weak_ptr<platf::display_t>> display_wp; ///< Display wp.
};
/**
* @brief Synchronous capture thread state.
*/
struct capture_thread_sync_ctx_t {
encode_session_ctx_queue_t encode_session_ctx_queue {30}; ///< Encode session ctx queue.
};
/**
* @brief Start the synchronous multi-client capture thread.
*
* @param ctx Native context object used by the operation or callback.
* @return 0 when the capture thread is started.
*/
int start_capture_sync(capture_thread_sync_ctx_t &ctx);
/**
* @brief Stop capture sync processing.
*
* @param ctx Native context object used by the operation or callback.
*/
void end_capture_sync(capture_thread_sync_ctx_t &ctx);
/**
* @brief Start the asynchronous capture thread.
*
* @param ctx Native context object used by the operation or callback.
* @return 0 when the capture thread is started; nonzero on setup failure.
*/
int start_capture_async(capture_thread_async_ctx_t &ctx);
/**
* @brief Stop capture async processing.
*
* @param ctx Native context object used by the operation or callback.
*/
void end_capture_async(capture_thread_async_ctx_t &ctx);
// Keep a reference counter to ensure the capture thread only runs when other threads have a reference to the capture thread
auto capture_thread_async = safe::make_shared<capture_thread_async_ctx_t>(start_capture_async, end_capture_async); ///< Capture thread async.
auto capture_thread_sync = safe::make_shared<capture_thread_sync_ctx_t>(start_capture_sync, end_capture_sync); ///< Capture thread sync.
#ifdef _WIN32
/**
* @brief NVENC.
*/
encoder_t nvenc {
"nvenc"sv,
std::make_unique<encoder_platform_formats_nvenc>(
platf::mem_type_e::dxgi,
platf::pix_fmt_e::nv12,
platf::pix_fmt_e::p010,
platf::pix_fmt_e::ayuv,
platf::pix_fmt_e::yuv444p16
),
{
{}, // Common options
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"av1_nvenc"s,
},
{
{}, // Common options
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"hevc_nvenc"s,
},
{
{}, // Common options
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"h264_nvenc"s,
},
PARALLEL_ENCODING | REF_FRAMES_INVALIDATION | YUV444_SUPPORT | ASYNC_TEARDOWN // flags
};
#elif !defined(__APPLE__)
encoder_t nvenc {
"nvenc"sv,
std::make_unique<encoder_platform_formats_avcodec>(
#ifdef _WIN32
AV_HWDEVICE_TYPE_D3D11VA,
AV_HWDEVICE_TYPE_NONE,
AV_PIX_FMT_D3D11,
#else
AV_HWDEVICE_TYPE_CUDA,
AV_HWDEVICE_TYPE_NONE,
AV_PIX_FMT_CUDA,
#endif
AV_PIX_FMT_NV12,
AV_PIX_FMT_P010,
AV_PIX_FMT_YUV444P,
AV_PIX_FMT_YUV444P16,
#ifdef _WIN32
dxgi_init_avcodec_hardware_input_buffer
#else
cuda_init_avcodec_hardware_input_buffer
#endif
),
{
// Common options
{
{"delay"s, 0},
{"forced-idr"s, 1},
{"zerolatency"s, 1},
{"surfaces"s, 1},
{"cbr_padding"s, false},
{"preset"s, &config::video.nv_legacy.preset},
{"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY},
{"rc"s, NV_ENC_PARAMS_RC_CBR},
{"multipass"s, &config::video.nv_legacy.multipass},
{"aq"s, &config::video.nv_legacy.aq},
},
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"av1_nvenc"s,
},
{
// Common options
{
{"delay"s, 0},
{"forced-idr"s, 1},
{"zerolatency"s, 1},
{"surfaces"s, 1},
{"cbr_padding"s, false},
{"preset"s, &config::video.nv_legacy.preset},
{"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY},
{"rc"s, NV_ENC_PARAMS_RC_CBR},
{"multipass"s, &config::video.nv_legacy.multipass},
{"aq"s, &config::video.nv_legacy.aq},
},
{
// SDR-specific options
{"profile"s, std::to_underlying(nv::profile_hevc_e::main)},
},
{
// HDR-specific options
{"profile"s, std::to_underlying(nv::profile_hevc_e::main_10)},
},
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"hevc_nvenc"s,
},
{
{
{"delay"s, 0},
{"forced-idr"s, 1},
{"zerolatency"s, 1},
{"surfaces"s, 1},
{"cbr_padding"s, false},
{"preset"s, &config::video.nv_legacy.preset},
{"tune"s, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY},
{"rc"s, NV_ENC_PARAMS_RC_CBR},
{"coder"s, &config::video.nv_legacy.h264_coder},
{"multipass"s, &config::video.nv_legacy.multipass},
{"aq"s, &config::video.nv_legacy.aq},
},
{
// SDR-specific options
{"profile"s, std::to_underlying(nv::profile_h264_e::high)},
},
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"h264_nvenc"s,
},
PARALLEL_ENCODING | YUV444_SUPPORT
};
#endif
#ifdef _WIN32
/**
* @brief Quicksync.
*/
encoder_t quicksync {
"quicksync"sv,
std::make_unique<encoder_platform_formats_avcodec>(
AV_HWDEVICE_TYPE_D3D11VA,
AV_HWDEVICE_TYPE_QSV,
AV_PIX_FMT_QSV,
AV_PIX_FMT_NV12,
AV_PIX_FMT_P010,
AV_PIX_FMT_VUYX,
AV_PIX_FMT_XV30,
dxgi_init_avcodec_hardware_input_buffer
),
{
// Common options
{
{"preset"s, &config::video.qsv.qsv_preset},
{"forced_idr"s, 1},
{"async_depth"s, 1},
{"low_delay_brc"s, 1},
{"low_power"s, 1},
},
{
// SDR-specific options
{"profile"s, std::to_underlying(qsv::profile_av1_e::main)},
},
{
// HDR-specific options
{"profile"s, std::to_underlying(qsv::profile_av1_e::main)},
},
{
// YUV444 SDR-specific options
{"profile"s, std::to_underlying(qsv::profile_av1_e::high)},
},
{
// YUV444 HDR-specific options
{"profile"s, std::to_underlying(qsv::profile_av1_e::high)},
},
{}, // Fallback options
"av1_qsv"s,
},
{
// Common options
{
{"preset"s, &config::video.qsv.qsv_preset},
{"forced_idr"s, 1},
{"async_depth"s, 1},
{"low_delay_brc"s, 1},
{"low_power"s, 1},
{"recovery_point_sei"s, 0},
{"pic_timing_sei"s, 0},
},
{
// SDR-specific options
{"profile"s, std::to_underlying(qsv::profile_hevc_e::main)},
},
{
// HDR-specific options
{"profile"s, std::to_underlying(qsv::profile_hevc_e::main_10)},
},
{
// YUV444 SDR-specific options
{"profile"s, std::to_underlying(qsv::profile_hevc_e::rext)},
},
{
// YUV444 HDR-specific options
{"profile"s, std::to_underlying(qsv::profile_hevc_e::rext)},
},
{
// Fallback options
{"low_power"s, []() {
return config::video.qsv.qsv_slow_hevc ? 0 : 1;
}},
},
"hevc_qsv"s,
},
{
// Common options
{
{"preset"s, &config::video.qsv.qsv_preset},
{"cavlc"s, &config::video.qsv.qsv_cavlc},
{"forced_idr"s, 1},
{"async_depth"s, 1},
{"low_delay_brc"s, 1},
{"low_power"s, 1},
{"recovery_point_sei"s, 0},
{"vcm"s, 1},
{"pic_timing_sei"s, 0},
{"max_dec_frame_buffering"s, 1},
},
{
// SDR-specific options
{"profile"s, std::to_underlying(qsv::profile_h264_e::high)},
},
{}, // HDR-specific options
{
// YUV444 SDR-specific options
{"profile"s, std::to_underlying(qsv::profile_h264_e::high_444p)},
},
{}, // YUV444 HDR-specific options
{
// Fallback options
{"low_power"s, 0}, // Some old/low-end Intel GPUs don't support low power encoding
},
"h264_qsv"s,
},
PARALLEL_ENCODING | CBR_WITH_VBR | RELAXED_COMPLIANCE | NO_RC_BUF_LIMIT | YUV444_SUPPORT
};
/**
* @brief Amdvce.
*/
encoder_t amdvce {
"amdvce"sv,
std::make_unique<encoder_platform_formats_avcodec>(
AV_HWDEVICE_TYPE_D3D11VA,
AV_HWDEVICE_TYPE_NONE,
AV_PIX_FMT_D3D11,
AV_PIX_FMT_NV12,
AV_PIX_FMT_P010,
AV_PIX_FMT_NONE,
AV_PIX_FMT_NONE,
dxgi_init_avcodec_hardware_input_buffer
),
{
// Common options
{
{"filler_data"s, false},
{"forced_idr"s, 1},
{"latency"s, "lowest_latency"s},
{"async_depth"s, 1},
{"skip_frame"s, 0},
{"log_to_dbg"s, []() {
return config::sunshine.min_log_level < 2 ? 1 : 0;
}},
{"preencode"s, &config::video.amd.amd_preanalysis},
{"quality"s, &config::video.amd.amd_quality_av1},
{"rc"s, &config::video.amd.amd_rc_av1},
{"usage"s, &config::video.amd.amd_usage_av1},
{"enforce_hrd"s, &config::video.amd.amd_enforce_hrd},
},
{}, // SDR-specific options
{}, // HDR-specific options
{}, // YUV444 SDR-specific options
{}, // YUV444 HDR-specific options
{}, // Fallback options
"av1_amf"s,
},
{
// Common options
{
{"filler_data"s, false},
{"forced_idr"s, 1},
{"latency"s, 1},
{"async_depth"s, 1},
{"skip_frame"s, 0},
{"log_to_dbg"s, []() {
return config::sunshine.min_log_level < 2 ? 1 : 0;
}},
{"gops_per_idr"s, 1},
{"header_insertion_mode"s, "idr"s},
{"preencode"s, &config::video.amd.amd_preanalysis},
{"quality"s, &config::video.amd.amd_quality_hevc},