-
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathvideo.cpp
More file actions
4668 lines (4046 loc) · 175 KB
/
Copy pathvideo.cpp
File metadata and controls
4668 lines (4046 loc) · 175 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 <algorithm>
#include <array>
#include <iterator>
#include <atomic>
#include <bitset>
#include <functional>
#include <list>
#include <limits>
#include <map>
#include <mutex>
#include <optional>
#include <thread>
#include <boost/pointer_cast.hpp>
extern "C" {
#include <libavutil/hdr_dynamic_metadata.h>
#include <libavutil/hdr_dynamic_vivid_metadata.h>
#include <libavutil/imgutils.h>
#include <libavutil/mastering_display_metadata.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
}
// lib includes
#include "cbs.h"
#include "config.h"
#include "display_device/display_device.h"
#include "globals.h"
#include "input.h"
#include "logging.h"
#include "nvenc/nvenc_encoder.h"
#include "amf/amf_encoder.h"
#include "platform/common.h"
#include "sync.h"
#include "video.h"
#include "video_hdr_metadata.h"
#include "video_probe.h"
#ifdef _WIN32
extern "C" {
#include <libavutil/hwcontext_d3d11va.h>
}
#include "platform/windows/display_device/windows_utils.h"
#endif
using namespace std::literals;
namespace video {
namespace {
std::mutex hdr_pipeline_status_mutex;
std::map<std::uint64_t, hdr_pipeline_status_t> hdr_pipeline_statuses;
std::atomic<std::uint64_t> next_hdr_pipeline_status_id { 1 };
std::optional<std::string>
capture_override_for_encoder_probe() {
#ifdef _WIN32
// VDD shared-texture producer may not be ready (metadata mapping / KeyedMutex
// not yet published) at encoder-probe time. Probing the real VDD backend
// therefore tends to fail on cold start, even though runtime capture works
// fine once the producer comes up. Fall back to ddx for the probe only;
// this override is injected per-display via config_t::capture_backend_override
// so it does not mutate the global config::video.capture used at runtime.
if (config::video.capture == "vdd") {
return std::string { "ddx" };
}
#endif
return std::nullopt;
}
/**
* @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::enum_available_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 device.second.device_state == display_device::device_state_e::active ||
device.second.device_state == display_device::device_state_e::primary;
});
if (at_least_one_device_is_active) {
return true;
}
BOOST_LOG(error) << "No display devices are active at the moment! Cannot probe the encoders.";
last_encoder_probe_result = {
probe_error_e::no_active_display,
"No active display devices are available for capture.",
"Turn on a physical display, enable a virtual display, or set Sunshine display/VDD options to Auto and try again."
};
return false;
}
} // namespace
std::uint64_t
register_hdr_pipeline_status(const hdr_pipeline_status_t &status) {
const auto id = next_hdr_pipeline_status_id.fetch_add(1, std::memory_order_relaxed);
auto registered = status;
registered.id = id;
std::lock_guard lock { hdr_pipeline_status_mutex };
hdr_pipeline_statuses[id] = std::move(registered);
return id;
}
void
update_hdr_pipeline_status(std::uint64_t id, const hdr_pipeline_status_t &status) {
if (id == 0) {
return;
}
auto updated = status;
updated.id = id;
std::lock_guard lock { hdr_pipeline_status_mutex };
if (hdr_pipeline_statuses.contains(id)) {
hdr_pipeline_statuses[id] = std::move(updated);
}
}
void
unregister_hdr_pipeline_status(std::uint64_t id) {
if (id == 0) {
return;
}
std::lock_guard lock { hdr_pipeline_status_mutex };
hdr_pipeline_statuses.erase(id);
}
std::vector<hdr_pipeline_status_t>
get_hdr_pipeline_statuses() {
std::lock_guard lock { hdr_pipeline_status_mutex };
std::vector<hdr_pipeline_status_t> statuses;
statuses.reserve(hdr_pipeline_statuses.size());
for (const auto &[id, status] : hdr_pipeline_statuses) {
statuses.push_back(status);
}
return statuses;
}
int
encoder_bitrate_from_total_bitrate(int total_bitrate_kbps, int fec_percentage) {
if (fec_percentage > 0 && fec_percentage <= 80) {
return total_bitrate_kbps * (100 - fec_percentage) / 100;
}
return total_bitrate_kbps;
}
int
encoder_bitrate_for_total_request(int requested_total_bitrate_kbps, int max_total_bitrate_kbps, int fec_percentage) {
auto capped_total_bitrate_kbps = requested_total_bitrate_kbps;
if (max_total_bitrate_kbps > 0) {
capped_total_bitrate_kbps = std::min(capped_total_bitrate_kbps, max_total_bitrate_kbps);
}
return encoder_bitrate_from_total_bitrate(capped_total_bitrate_kbps, fec_percentage);
}
int
cap_initial_encoder_bitrate(int initial_encoder_bitrate_kbps, int max_total_bitrate_kbps, int fec_percentage) {
if (max_total_bitrate_kbps <= 0) {
return initial_encoder_bitrate_kbps;
}
return std::min(
initial_encoder_bitrate_kbps,
encoder_bitrate_from_total_bitrate(max_total_bitrate_kbps, fec_percentage)
);
}
std::chrono::duration<double, std::milli>
minimum_frame_time_for_vrr(int stream_fps, int minimum_fps_target) {
if (minimum_fps_target > 0) {
return std::chrono::duration<double, std::milli> { 1000.0 / minimum_fps_target };
}
return std::chrono::duration<double, std::milli> { 2000.0 / std::max(stream_fps, 1) };
}
input_activity_boost_policy_t
make_input_activity_boost_policy(const input_activity_boost_config_t &config) {
input_activity_boost_policy_t policy {};
policy.configured =
config.variable_refresh_rate &&
config.enabled &&
config.boost_fps > 0 &&
config.window_ms > 0;
if (!policy.configured) {
return policy;
}
policy.fps = std::min(config.boost_fps, std::max(config.stream_fps, 1));
policy.frame_time = std::chrono::duration<double, std::milli> { 1000.0 / policy.fps };
policy.useful = config.minimum_fps_target == 0 || policy.fps > config.minimum_fps_target;
return policy;
}
std::chrono::duration<double, std::milli>
effective_minimum_frame_time(
const std::chrono::duration<double, std::milli> &base_minimum_frame_time,
const input_activity_boost_policy_t &input_activity_boost_policy,
bool input_boost_active,
int minimum_fps_target) {
if (!input_boost_active || !input_activity_boost_policy.useful) {
return base_minimum_frame_time;
}
if (minimum_fps_target > 0) {
return std::min(base_minimum_frame_time, input_activity_boost_policy.frame_time);
}
return input_activity_boost_policy.frame_time;
}
void
free_ctx(AVCodecContext *ctx) {
avcodec_free_context(&ctx);
}
void
free_frame(AVFrame *frame) {
av_frame_free(&frame);
}
void
free_buffer(AVBufferRef *ref) {
av_buffer_unref(&ref);
}
namespace nv {
enum class profile_h264_e : int {
high = 2, ///< High profile
high_444p = 3, ///< High 4:4:4 Predictive profile
};
enum class profile_hevc_e : int {
main = 0, ///< Main profile
main_10 = 1, ///< Main 10 profile
rext = 2, ///< Rext profile
};
} // namespace nv
namespace qsv {
enum class profile_h264_e : int {
high = 100, ///< High profile
high_444p = 244, ///< High 4:4:4 Predictive profile
};
enum class profile_hevc_e : int {
main = 1, ///< Main profile
main_10 = 2, ///< Main 10 profile
rext = 4, ///< RExt profile
};
enum class profile_av1_e : int {
main = 1, ///< Main profile
high = 2, ///< High profile
};
} // namespace qsv
util::Either<avcodec_buffer_t, int>
dxgi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
util::Either<avcodec_buffer_t, int>
vaapi_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
util::Either<avcodec_buffer_t, int>
cuda_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
util::Either<avcodec_buffer_t, int>
vt_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
util::Either<avcodec_buffer_t, int>
vulkan_init_avcodec_hardware_input_buffer(platf::avcodec_encode_device_t *);
class avcodec_software_encode_device_t: public platf::avcodec_encode_device_t {
public:
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((AVPixelFormat) sws_output_frame->format);
auto planes = av_pix_fmt_count_planes((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]),
(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;
}
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;
}
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, (AVPixelFormat) frame->format, frame->color_range, frame->width, frame->height);
}
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((float) out_width / in_width, (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;
avcodec_frame_t sw_frame;
avcodec_frame_t sws_input_frame;
avcodec_frame_t sws_output_frame;
sws_t sws;
// Offset of input image to output frame in pixels
int offsetW;
int offsetH;
};
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
};
class frame_timestamp_ring_t {
public:
void
store(
uint64_t frame_index,
std::optional<std::chrono::steady_clock::time_point> timestamp,
std::optional<platf::frame_pipeline_trace_t> pipeline_trace) {
auto &entry = entries[frame_index % entries.size()];
entry.frame_index = frame_index;
entry.timestamp = timestamp;
entry.pipeline_trace = std::move(pipeline_trace);
}
std::optional<std::chrono::steady_clock::time_point>
lookup(uint64_t frame_index) const {
const auto &entry = entries[frame_index % entries.size()];
if (entry.frame_index != frame_index) {
return std::nullopt;
}
return entry.timestamp;
}
std::optional<platf::frame_pipeline_trace_t>
lookup_trace(uint64_t frame_index) const {
const auto &entry = entries[frame_index % entries.size()];
if (entry.frame_index != frame_index) {
return std::nullopt;
}
return entry.pipeline_trace;
}
private:
// Encoder output can lag submission; keep recent per-frame timing data without heap churn.
struct entry_t {
uint64_t frame_index = std::numeric_limits<uint64_t>::max();
std::optional<std::chrono::steady_clock::time_point> timestamp;
std::optional<platf::frame_pipeline_trace_t> pipeline_trace;
};
std::array<entry_t, 256> entries {};
};
class avcodec_encode_session_t: public encode_session_t {
public:
avcodec_encode_session_t() = default;
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 } {}
avcodec_encode_session_t(avcodec_encode_session_t &&other) noexcept = default;
~avcodec_encode_session_t() {
// Flush any remaining frames in the encoder
if (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
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);
frame_timestamps = std::move(other.frame_timestamps);
hdr_ema = other.hdr_ema;
sps = std::move(other.sps);
vps = std::move(other.vps);
inject = other.inject;
return *this;
}
int
convert(platf::img_t &img) override {
if (!device) return -1;
return device->convert(img);
}
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;
}
}
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;
}
}
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();
}
void
set_bitrate(int bitrate_kbps) override {
if (!avcodec_ctx) return;
const auto adjusted_bitrate_kbps = encoder_bitrate_for_total_request(
bitrate_kbps,
config::video.max_bitrate,
config::stream.fec_percentage
);
auto bitrate = static_cast<int64_t>(adjusted_bitrate_kbps) * 1000; // Convert to bps
// Update AVCodecContext fields (for software encoders and as fallback).
// Note: dynamic bitrate changes for the AMF path are handled inside the
// native amf_d3d11 encoder via amf_d3d11::set_bitrate(), so the legacy
// FFmpeg-AMF reach-into-priv_data hack has been removed.
avcodec_ctx->bit_rate = bitrate;
avcodec_ctx->rc_max_rate = bitrate;
avcodec_ctx->rc_min_rate = bitrate;
BOOST_LOG(info) << "AVCodec encoder bitrate set to: " << adjusted_bitrate_kbps
<< " Kbps (requested: " << bitrate_kbps << " Kbps, FEC: "
<< config::stream.fec_percentage << "%)";
}
void
set_dynamic_param(const dynamic_param_t ¶m) override {
if (!avcodec_ctx) return;
switch (param.type) {
case dynamic_param_type_e::RESOLUTION:
// 分辨率变更需要重新初始化编码器
BOOST_LOG(info) << "AVCodec encoder: Resolution change requested (requires encoder reinitialization)";
break;
case dynamic_param_type_e::FPS:
// FPS变更需要重新配置编码器
BOOST_LOG(info) << "AVCodec encoder: FPS change requested: " << param.value.float_value
<< " fps (requires encoder reconfiguration)";
break;
case dynamic_param_type_e::BITRATE: {
// 码率调整通过set_bitrate处理
set_bitrate(param.value.int_value);
break;
}
case dynamic_param_type_e::QP: {
// 设置量化参数
if (param.value.int_value >= 0 && param.value.int_value <= 51) {
avcodec_ctx->qmin = param.value.int_value;
avcodec_ctx->qmax = param.value.int_value;
BOOST_LOG(info) << "AVCodec encoder QP changed to: " << param.value.int_value;
}
else {
BOOST_LOG(warning) << "Invalid QP value: " << param.value.int_value << " (must be 0-51)";
}
break;
}
case dynamic_param_type_e::VBV_BUFFER_SIZE: {
// 设置VBV缓冲区大小
if (param.value.int_value > 0) {
avcodec_ctx->rc_buffer_size = param.value.int_value * 1000; // 转换为bps
BOOST_LOG(info) << "AVCodec encoder VBV buffer size changed to: " << param.value.int_value << " Kbps";
}
break;
}
default:
BOOST_LOG(warning) << "AVCodec encoder: Unsupported dynamic parameter type: " << (int) param.type;
break;
}
}
avcodec_ctx_t avcodec_ctx;
std::unique_ptr<platf::avcodec_encode_device_t> device;
std::vector<packet_raw_t::replace_t> replacements;
frame_timestamp_ring_t frame_timestamps;
// Temporal filters are session-local so a new stream cannot inherit metadata
// history from the previous stream.
hdr_metadata::hdr_luminance_ema_t hdr_ema;
hdr_metadata::vivid_temporal_filter_t vivid_filter;
cbs::nal_t sps;
cbs::nal_t vps;
// inject sps/vps data into idr pictures
int inject;
};
/**
* Whether the HDR luminance analyzer can be trusted to produce samples for this
* encode device: the user has not turned it off and the capture backend actually
* implements it.
*/
inline bool
hdr_luminance_analysis_usable(bool device_supports_analysis) {
return config::video.hdr_luminance_analysis != "off" && device_supports_analysis;
}
/**
* Report a vivid_startup_gate_t transition. Shared so the two native encoder
* paths cannot drift into describing the same decision differently in the log.
*/
void
log_vivid_gate_transition(
const char *encoder_name,
hdr_metadata::vivid_startup_gate_t::transition_e transition,
const hdr_metadata::vivid_startup_gate_t &gate,
const platf::hdr_frame_luminance_stats_t &stats) {
using transition_e = hdr_metadata::vivid_startup_gate_t::transition_e;
switch (transition) {
case transition_e::ready:
BOOST_LOG(info) << encoder_name << ": HDR Vivid startup guard ready after "
<< gate.consecutive_samples()
<< " independent samples; first encoded HLG frame will be IDR with Vivid"
<< " (avg=" << stats.avg_maxrgb
<< " nits, max=" << stats.max_maxrgb
<< " nits, P10=" << stats.percentile_10_pq
<< ", P90=" << stats.percentile_90_pq << ')';
break;
case transition_e::timed_out:
BOOST_LOG(warning) << encoder_name << ": HDR Vivid startup guard timed out after "
<< hdr_metadata::vivid_startup_gate_t::PREROLL_TIMEOUT.count()
<< " ms; starting this session as pure HLG without dynamic metadata";
break;
case transition_e::none:
break;
}
}
class nvenc_encode_session_t: public encode_session_t {
public:
nvenc_encode_session_t(std::unique_ptr<platf::nvenc_encode_device_t> encode_device, int video_format):
device(std::move(encode_device)),
vivid_gate(
device ? device->colorspace : sunshine_colorspace_t {},
video_format,
device && hdr_luminance_analysis_usable(device->hdr_luminance_analysis_available)) {
if (vivid_gate.prerolling()) {
BOOST_LOG(info) << "NVENC: holding HLG startup for stable HDR Vivid metadata ("
<< hdr_metadata::vivid_startup_guard_t::REQUIRED_SAMPLES
<< " independent samples, "
<< hdr_metadata::vivid_startup_gate_t::PREROLL_TIMEOUT.count()
<< " ms timeout)";
}
}
int
convert(platf::img_t &img) override {
if (!device) return -1;
return device->convert(img);
}
void
request_idr_frame() override {
force_idr = true;
}
void
request_normal_frame() override {
force_idr = false;
}
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;
}
}
void
set_bitrate(int bitrate_kbps) override {
if (device && device->nvenc) {
// 考虑FEC影响,调整编码码率
// 当FEC百分比为X%时,实际编码码率需要调整为原始码率的(100-X)%
const auto adjusted_bitrate_kbps = encoder_bitrate_for_total_request(
bitrate_kbps,
config::video.max_bitrate,
config::stream.fec_percentage
);
device->nvenc->set_bitrate(adjusted_bitrate_kbps);
BOOST_LOG(info) << "NVENC encoder bitrate changed to: " << adjusted_bitrate_kbps
<< " Kbps (requested: " << bitrate_kbps << " Kbps, FEC: "
<< config::stream.fec_percentage << "%)";
}
}
void
set_dynamic_param(const dynamic_param_t ¶m) override {
if (!device || !device->nvenc) return;
switch (param.type) {
case dynamic_param_type_e::RESOLUTION:
// 分辨率变更需要重新初始化编码器,这里只记录日志
BOOST_LOG(info) << "NVENC encoder: Resolution change requested (requires encoder reinitialization)";
break;
case dynamic_param_type_e::FPS:
// FPS变更需要重新配置编码器
BOOST_LOG(info) << "NVENC encoder: FPS change requested: " << param.value.float_value
<< " fps (requires encoder reconfiguration)";
break;
case dynamic_param_type_e::BITRATE: {
// 码率调整通过set_bitrate处理
set_bitrate(param.value.int_value);
break;
}
case dynamic_param_type_e::QP: {
// NVENC的QP调整需要通过重新配置编码器
BOOST_LOG(info) << "NVENC encoder QP change requested: " << param.value.int_value
<< " (requires encoder reconfiguration)";
break;
}
case dynamic_param_type_e::ADAPTIVE_QUANTIZATION: {
// 自适应量化开关
BOOST_LOG(info) << "NVENC encoder adaptive quantization change requested: " << param.value.bool_value;
break;
}
case dynamic_param_type_e::MULTI_PASS: {
// 多遍编码设置
BOOST_LOG(info) << "NVENC encoder multi-pass change requested: " << param.value.int_value;
break;
}
case dynamic_param_type_e::VBV_BUFFER_SIZE: {
// VBV缓冲区大小
BOOST_LOG(info) << "NVENC encoder VBV buffer size change requested: " << param.value.int_value << " Kbps";
break;
}
default:
BOOST_LOG(warning) << "NVENC encoder: Unsupported dynamic parameter type: " << (int) param.type;
break;
}
}
nvenc::nvenc_encoded_frame
encode_frame(uint64_t frame_index) {
if (!device || !device->nvenc) return {};
using decision_e = hdr_metadata::vivid_startup_gate_t::decision_e;
const auto gated = vivid_gate.observe(device->hdr_luminance_stats, std::chrono::steady_clock::now());
if (gated.transition != hdr_metadata::vivid_startup_gate_t::transition_e::none) {
// The stream's metadata content changes here, so the client needs a fresh
// IDR rather than a P frame that references pre-transition pictures.
force_idr = true;
log_vivid_gate_transition("NVENC", gated.transition, vivid_gate, device->hdr_luminance_stats);
}
if (gated.decision == decision_e::hold) {
// Keep converting capture frames so the asynchronous GPU analyzer can
// produce independent samples, but do not let the client see a plain-HLG
// IDR followed by a mid-stream transition into HDR Vivid.
return { {}, frame_index, false, false };
}
// Pass per-frame HDR luminance stats to NVENC for dynamic metadata injection
if (gated.decision == decision_e::emit && device->hdr_luminance_stats.valid) {
device->nvenc->set_luminance_stats(device->hdr_luminance_stats);
}
auto result = device->nvenc->encode_frame(frame_index, force_idr);
force_idr = false;
return result;
}
void
track_frame_timestamp(
uint64_t frame_index,
std::optional<std::chrono::steady_clock::time_point> frame_timestamp,
std::optional<platf::frame_pipeline_trace_t> pipeline_trace) {
frame_timestamps.store(frame_index, frame_timestamp, std::move(pipeline_trace));
}
std::optional<std::chrono::steady_clock::time_point>
resolve_frame_timestamp(uint64_t frame_index) const {
return frame_timestamps.lookup(frame_index);
}
std::optional<platf::frame_pipeline_trace_t>
resolve_frame_trace(uint64_t frame_index) const {
return frame_timestamps.lookup_trace(frame_index);
}
private:
std::unique_ptr<platf::nvenc_encode_device_t> device;
frame_timestamp_ring_t frame_timestamps;
hdr_metadata::vivid_startup_gate_t vivid_gate;
bool force_idr = false;
};
class amf_encode_session_t: public encode_session_t {
public:
amf_encode_session_t(std::unique_ptr<platf::amf_encode_device_t> encode_device, int video_format):
device(std::move(encode_device)),
vivid_gate(
device ? device->colorspace : sunshine_colorspace_t {},
video_format,
device && hdr_luminance_analysis_usable(device->hdr_luminance_analysis_available)) {
if (vivid_gate.prerolling()) {
BOOST_LOG(info) << "AMF: holding HLG startup for stable HDR Vivid metadata ("
<< hdr_metadata::vivid_startup_guard_t::REQUIRED_SAMPLES
<< " independent samples, "
<< hdr_metadata::vivid_startup_gate_t::PREROLL_TIMEOUT.count()
<< " ms timeout)";
}
}
int
convert(platf::img_t &img) override {
if (!device) return -1;
return device->convert(img);
}
void
request_idr_frame() override {
force_idr = true;
}
void
request_normal_frame() override {
force_idr = false;
}
void
invalidate_ref_frames(int64_t first_frame, int64_t last_frame) override {
if (!device || !device->amf) return;
if (!device->amf->invalidate_ref_frames(first_frame, last_frame)) {
force_idr = true;
}
}
void
set_bitrate(int bitrate_kbps) override {
if (device && device->amf) {
const auto adjusted_bitrate_kbps = encoder_bitrate_for_total_request(
bitrate_kbps,
config::video.max_bitrate,
config::stream.fec_percentage
);
device->amf->set_bitrate(adjusted_bitrate_kbps);
BOOST_LOG(info) << "AMF standalone encoder bitrate changed to: " << adjusted_bitrate_kbps
<< " Kbps (requested: " << bitrate_kbps << " Kbps, FEC: "
<< config::stream.fec_percentage << "%)";
}
}
void
set_dynamic_param(const dynamic_param_t ¶m) override {
if (!device || !device->amf) return;
switch (param.type) {
case dynamic_param_type_e::BITRATE:
set_bitrate(param.value.int_value);
break;
default:
break;
}
}
amf::amf_encoded_frame
encode_frame(uint64_t frame_index) {
if (!device || !device->amf) return {};
using decision_e = hdr_metadata::vivid_startup_gate_t::decision_e;
const auto gated = vivid_gate.observe(device->hdr_luminance_stats, std::chrono::steady_clock::now());
if (gated.transition != hdr_metadata::vivid_startup_gate_t::transition_e::none) {
force_idr = true;
log_vivid_gate_transition("AMF", gated.transition, vivid_gate, device->hdr_luminance_stats);
}
if (gated.decision == decision_e::hold) {
// Same reasoning as NVENC: keep converting so the analyzer converges, but
// do not let the client see plain HLG before the switch into Vivid.
amf::amf_encoded_frame held;
held.frame_index = frame_index;
return held;
}
if (gated.decision == decision_e::emit && device->hdr_luminance_stats.valid) {
device->amf->set_luminance_stats(device->hdr_luminance_stats);
}
auto result = device->amf->encode_frame(frame_index, force_idr);
force_idr = false;
return result;
}
void
track_frame_timestamp(
uint64_t frame_index,
std::optional<std::chrono::steady_clock::time_point> frame_timestamp,
std::optional<platf::frame_pipeline_trace_t> pipeline_trace) {
frame_timestamps.store(frame_index, frame_timestamp, std::move(pipeline_trace));
}
std::optional<std::chrono::steady_clock::time_point>
resolve_frame_timestamp(uint64_t frame_index) const {
return frame_timestamps.lookup(frame_index);
}
std::optional<platf::frame_pipeline_trace_t>
resolve_frame_trace(uint64_t frame_index) const {
return frame_timestamps.lookup_trace(frame_index);
}
private:
std::unique_ptr<platf::amf_encode_device_t> device;