-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
rtc_video_encoder.cc
2091 lines (1858 loc) · 81.3 KB
/
rtc_video_encoder.cc
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 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.h"
#include <memory>
#include <numeric>
#include <vector>
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/system/sys_info.h"
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/thread_annotations.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "media/base/bitrate.h"
#include "media/base/bitstream_buffer.h"
#include "media/base/media_switches.h"
#include "media/base/media_util.h"
#include "media/base/video_bitrate_allocation.h"
#include "media/base/video_frame.h"
#include "media/base/video_util.h"
#include "media/capture/capture_switches.h"
#include "media/media_buildflags.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "media/video/h264_parser.h"
#include "media/video/video_encode_accelerator.h"
#include "third_party/blink/public/common/buildflags.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/platform/allow_discouraged_type.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/webrtc/convert_to_webrtc_video_frame_buffer.h"
#include "third_party/blink/renderer/platform/webrtc/webrtc_video_frame_adapter.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_base.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_gfx.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_std.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "third_party/libyuv/include/libyuv.h"
#include "third_party/webrtc/modules/video_coding/codecs/h264/include/h264.h"
#include "third_party/webrtc/modules/video_coding/include/video_error_codes.h"
#include "third_party/webrtc/rtc_base/time_utils.h"
namespace {
// Enabled-by-default: only used as a kill-switch.
BASE_FEATURE(kForceSoftwareForLowResolutions,
"ForceSoftwareForLowResolutions",
base::FEATURE_ENABLED_BY_DEFAULT);
#if BUILDFLAG(IS_CHROMEOS_ASH) && defined(ARCH_CPU_ARM_FAMILY)
bool IsRK3399Board() {
const std::string board = base::SysInfo::GetLsbReleaseBoard();
const char* kRK3399Boards[] = {
"bob",
"kevin",
"rainier",
"scarlet",
};
for (const char* b : kRK3399Boards) {
if (board.find(b) == 0u) { // if |board| starts with |b|.
return true;
}
}
return false;
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH) && defined(ARCH_CPU_ARM_FAMILY)
#if BUILDFLAG(IS_CHROMEOS_ASH)
bool IsZeroCopyTabCaptureEnabled() {
// If you change this function, please change the code of the same function
// in
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_content.cc.
#if defined(ARCH_CPU_ARM_FAMILY)
// The GL driver used on RK3399 has a problem to enable zero copy tab capture.
// See b/267966835.
// TODO(b/239503724): Remove this code when RK3399 reaches EOL.
static bool kIsRK3399Board = IsRK3399Board();
if (kIsRK3399Board) {
return false;
}
#endif // defined(ARCH_CPU_ARM_FAMILY)
return base::FeatureList::IsEnabled(blink::features::kZeroCopyTabCapture);
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
bool IsNV12GpuMemoryBufferVideoFrame(const webrtc::VideoFrame& input_image) {
rtc::scoped_refptr<webrtc::VideoFrameBuffer> video_frame_buffer =
input_image.video_frame_buffer();
if (video_frame_buffer->type() != webrtc::VideoFrameBuffer::Type::kNative) {
return false;
}
const scoped_refptr<media::VideoFrame> frame =
static_cast<blink::WebRtcVideoFrameAdapter*>(video_frame_buffer.get())
->getMediaVideoFrame();
CHECK(frame);
return frame->format() == media::PIXEL_FORMAT_NV12 &&
frame->storage_type() == media::VideoFrame::STORAGE_GPU_MEMORY_BUFFER;
}
class SignaledValue {
public:
SignaledValue() : event(nullptr), val(nullptr) {}
SignaledValue(base::WaitableEvent* event, int32_t* val)
: event(event), val(val) {
DCHECK(event);
}
~SignaledValue() {
if (IsValid() && !event->IsSignaled()) {
NOTREACHED() << "never signaled";
event->Signal();
}
}
// Move-only.
SignaledValue(const SignaledValue&) = delete;
SignaledValue& operator=(const SignaledValue&) = delete;
SignaledValue(SignaledValue&& other) : event(other.event), val(other.val) {
other.event = nullptr;
other.val = nullptr;
}
SignaledValue& operator=(SignaledValue&& other) {
event = other.event;
val = other.val;
other.event = nullptr;
other.val = nullptr;
return *this;
}
void Signal() {
if (!IsValid())
return;
event->Signal();
event = nullptr;
}
void Set(int32_t v) {
if (!val)
return;
*val = v;
}
bool IsValid() { return event; }
private:
base::WaitableEvent* event;
int32_t* val;
};
class ScopedSignaledValue {
public:
ScopedSignaledValue() = default;
ScopedSignaledValue(base::WaitableEvent* event, int32_t* val)
: sv(event, val) {}
explicit ScopedSignaledValue(SignaledValue sv) : sv(std::move(sv)) {}
~ScopedSignaledValue() { sv.Signal(); }
ScopedSignaledValue(const ScopedSignaledValue&) = delete;
ScopedSignaledValue& operator=(const ScopedSignaledValue&) = delete;
ScopedSignaledValue(ScopedSignaledValue&& other) : sv(std::move(other.sv)) {
DCHECK(!other.sv.IsValid());
}
ScopedSignaledValue& operator=(ScopedSignaledValue&& other) {
sv.Signal();
sv = std::move(other.sv);
DCHECK(!other.sv.IsValid());
return *this;
}
// Set |v|, signal |sv|, and invalidate |sv|. If |sv| is already invalidated
// at the call, this has no effect.
void SetAndReset(int32_t v) {
sv.Set(v);
reset();
}
// Invalidate |sv|. The invalidated value will be set by move assignment
// operator.
void reset() { *this = ScopedSignaledValue(); }
private:
SignaledValue sv;
};
// TODO(https://crbug.com/1448809): Move to base/memory/ref_counted_memory.h
class RefCountedWritableSharedMemoryMapping
: public base::RefCountedThreadSafe<RefCountedWritableSharedMemoryMapping> {
public:
explicit RefCountedWritableSharedMemoryMapping(
base::WritableSharedMemoryMapping mapping)
: mapping_(std::move(mapping)) {}
RefCountedWritableSharedMemoryMapping(
const RefCountedWritableSharedMemoryMapping&) = delete;
RefCountedWritableSharedMemoryMapping& operator=(
const RefCountedWritableSharedMemoryMapping&) = delete;
const unsigned char* front() const {
return static_cast<unsigned char*>(mapping_.memory());
}
unsigned char* front() {
return static_cast<unsigned char*>(mapping_.memory());
}
size_t size() const { return mapping_.size(); }
private:
friend class base::RefCountedThreadSafe<
RefCountedWritableSharedMemoryMapping>;
~RefCountedWritableSharedMemoryMapping() = default;
const base::WritableSharedMemoryMapping mapping_;
};
class EncodedDataWrapper : public webrtc::EncodedImageBufferInterface {
public:
EncodedDataWrapper(
const scoped_refptr<RefCountedWritableSharedMemoryMapping>&& mapping,
size_t size,
base::OnceClosure reuse_buffer_callback)
: mapping_(std::move(mapping)),
size_(size),
reuse_buffer_callback_(std::move(reuse_buffer_callback)) {}
~EncodedDataWrapper() override {
DCHECK(reuse_buffer_callback_);
std::move(reuse_buffer_callback_).Run();
}
const uint8_t* data() const override { return mapping_->front(); }
uint8_t* data() override { return mapping_->front(); }
size_t size() const override { return size_; }
private:
const scoped_refptr<RefCountedWritableSharedMemoryMapping> mapping_;
const size_t size_;
base::OnceClosure reuse_buffer_callback_;
};
struct FrameChunk {
FrameChunk(const webrtc::VideoFrame& input_image, bool force_keyframe)
: video_frame_buffer(input_image.video_frame_buffer()),
timestamp(input_image.timestamp()),
timestamp_us(input_image.timestamp_us()),
render_time_ms(input_image.render_time_ms()),
force_keyframe(force_keyframe) {
DCHECK(video_frame_buffer);
}
const rtc::scoped_refptr<webrtc::VideoFrameBuffer> video_frame_buffer;
// TODO(b/241349739): timestamp and timestamp_us should be unified as one
// base::TimeDelta.
const uint32_t timestamp;
const uint64_t timestamp_us;
const int64_t render_time_ms;
const bool force_keyframe;
};
bool ConvertKbpsToBps(uint32_t bitrate_kbps, uint32_t* bitrate_bps) {
if (!base::IsValueInRangeForNumericType<uint32_t>(bitrate_kbps *
UINT64_C(1000))) {
return false;
}
*bitrate_bps = bitrate_kbps * 1000;
return true;
}
} // namespace
namespace WTF {
template <>
struct CrossThreadCopier<webrtc::VideoEncoder::RateControlParameters>
: public CrossThreadCopierPassThrough<
webrtc::VideoEncoder::RateControlParameters> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<
std::vector<media::VideoEncodeAccelerator::Config::SpatialLayer>>
: public CrossThreadCopierPassThrough<
std::vector<media::VideoEncodeAccelerator::Config::SpatialLayer>> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<FrameChunk>
: public CrossThreadCopierPassThrough<FrameChunk> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<media::VideoEncodeAccelerator::Config>
: public CrossThreadCopierPassThrough<
media::VideoEncodeAccelerator::Config> {
STATIC_ONLY(CrossThreadCopier);
};
template <>
struct CrossThreadCopier<SignaledValue> {
static SignaledValue Copy(SignaledValue sv) {
return sv; // this is a move in fact.
}
};
} // namespace WTF
namespace blink {
namespace {
media::VideoEncodeAccelerator::Config::InterLayerPredMode
CopyFromWebRtcInterLayerPredMode(
const webrtc::InterLayerPredMode inter_layer_pred) {
switch (inter_layer_pred) {
case webrtc::InterLayerPredMode::kOff:
return media::VideoEncodeAccelerator::Config::InterLayerPredMode::kOff;
case webrtc::InterLayerPredMode::kOn:
return media::VideoEncodeAccelerator::Config::InterLayerPredMode::kOn;
case webrtc::InterLayerPredMode::kOnKeyPic:
return media::VideoEncodeAccelerator::Config::InterLayerPredMode::
kOnKeyPic;
}
}
// Create VEA::Config::SpatialLayer from |codec_settings|. If some config of
// |codec_settings| is not supported, returns false.
bool CreateSpatialLayersConfig(
const webrtc::VideoCodec& codec_settings,
std::vector<media::VideoEncodeAccelerator::Config::SpatialLayer>*
spatial_layers,
media::VideoEncodeAccelerator::Config::InterLayerPredMode*
inter_layer_pred) {
absl::optional<webrtc::ScalabilityMode> scalability_mode =
codec_settings.GetScalabilityMode();
if (codec_settings.codecType == webrtc::kVideoCodecVP9 &&
codec_settings.VP9().numberOfSpatialLayers > 1 &&
!RTCVideoEncoder::Vp9HwSupportForSpatialLayers()) {
DVLOG(1)
<< "VP9 SVC not yet supported by HW codecs, falling back to software.";
return false;
}
// We fill SpatialLayer only in temporal layer or spatial layer encoding.
switch (codec_settings.codecType) {
case webrtc::kVideoCodecH264:
if (scalability_mode.has_value() &&
*scalability_mode != webrtc::ScalabilityMode::kL1T1) {
DVLOG(1)
<< "H264 temporal layers not yet supported by HW codecs, but use"
<< " HW codecs and leave the fallback decision to a webrtc client"
<< " by seeing metadata in webrtc::CodecSpecificInfo";
return true;
}
break;
case webrtc::kVideoCodecVP8: {
int number_of_temporal_layers = 1;
if (scalability_mode.has_value()) {
switch (*scalability_mode) {
case webrtc::ScalabilityMode::kL1T1:
number_of_temporal_layers = 1;
break;
case webrtc::ScalabilityMode::kL1T2:
number_of_temporal_layers = 2;
break;
case webrtc::ScalabilityMode::kL1T3:
number_of_temporal_layers = 3;
break;
default:
// Other modes not supported.
return false;
}
}
if (number_of_temporal_layers > 1) {
if (codec_settings.mode == webrtc::VideoCodecMode::kScreensharing) {
// This is a VP8 stream with screensharing using temporal layers for
// temporal scalability. Since this implementation does not yet
// implement temporal layers, fall back to software codec, if cfm and
// board is known to have a CPU that can handle it.
if (base::FeatureList::IsEnabled(
features::kWebRtcScreenshareSwEncoding)) {
// TODO(sprang): Add support for temporal layers so we don't need
// fallback. See eg http://crbug.com/702017
DVLOG(1) << "Falling back to software encoder.";
return false;
}
}
// Though there is no SVC in VP8 spec. We allocate 1 element in
// spatial_layers for temporal layer encoding.
spatial_layers->resize(1u);
auto& sl = (*spatial_layers)[0];
sl.width = codec_settings.width;
sl.height = codec_settings.height;
if (!ConvertKbpsToBps(codec_settings.startBitrate, &sl.bitrate_bps))
return false;
sl.framerate = codec_settings.maxFramerate;
sl.max_qp = base::saturated_cast<uint8_t>(codec_settings.qpMax);
sl.num_of_temporal_layers =
base::saturated_cast<uint8_t>(number_of_temporal_layers);
}
break;
}
case webrtc::kVideoCodecVP9:
// Since one TL and one SL can be regarded as one simple stream,
// SpatialLayer is not filled.
if (codec_settings.VP9().numberOfTemporalLayers > 1 ||
codec_settings.VP9().numberOfSpatialLayers > 1) {
spatial_layers->clear();
for (size_t i = 0; i < codec_settings.VP9().numberOfSpatialLayers;
++i) {
const webrtc::SpatialLayer& rtc_sl = codec_settings.spatialLayers[i];
// We ignore non active spatial layer and don't proceed further. There
// must NOT be an active higher spatial layer than non active spatial
// layer.
if (!rtc_sl.active)
break;
spatial_layers->emplace_back();
auto& sl = spatial_layers->back();
sl.width = base::checked_cast<int32_t>(rtc_sl.width);
sl.height = base::checked_cast<int32_t>(rtc_sl.height);
if (!ConvertKbpsToBps(rtc_sl.targetBitrate, &sl.bitrate_bps))
return false;
sl.framerate = base::saturated_cast<int32_t>(rtc_sl.maxFramerate);
sl.max_qp = base::saturated_cast<uint8_t>(rtc_sl.qpMax);
sl.num_of_temporal_layers =
base::saturated_cast<uint8_t>(rtc_sl.numberOfTemporalLayers);
}
if (spatial_layers->size() == 1 &&
spatial_layers->at(0).num_of_temporal_layers == 1) {
// Don't report spatial layers if only the base layer is active and we
// have no temporar layers configured.
spatial_layers->clear();
} else {
*inter_layer_pred = CopyFromWebRtcInterLayerPredMode(
codec_settings.VP9().interLayerPred);
}
}
break;
default:
break;
}
return true;
}
struct FrameInfo {
public:
FrameInfo(const base::TimeDelta& media_timestamp,
int32_t rtp_timestamp,
int64_t capture_time_ms,
const std::vector<gfx::Size>& resolutions)
: media_timestamp_(media_timestamp),
rtp_timestamp_(rtp_timestamp),
capture_time_ms_(capture_time_ms),
resolutions_(resolutions) {}
const base::TimeDelta media_timestamp_;
const int32_t rtp_timestamp_;
const int64_t capture_time_ms_;
const std::vector<gfx::Size> resolutions_ ALLOW_DISCOURAGED_TYPE(
"Matches media::Vp9Metadata::spatial_layer_resolutions etc");
size_t produced_frames_ = 0;
};
webrtc::VideoCodecType ProfileToWebRtcVideoCodecType(
media::VideoCodecProfile profile) {
switch (media::VideoCodecProfileToVideoCodec(profile)) {
case media::VideoCodec::kH264:
return webrtc::kVideoCodecH264;
case media::VideoCodec::kVP8:
return webrtc::kVideoCodecVP8;
case media::VideoCodec::kVP9:
return webrtc::kVideoCodecVP9;
case media::VideoCodec::kAV1:
return webrtc::kVideoCodecAV1;
default:
NOTREACHED() << "Invalid profile " << GetProfileName(profile);
return webrtc::kVideoCodecGeneric;
}
}
void RecordInitEncodeUMA(int32_t init_retval,
media::VideoCodecProfile profile) {
base::UmaHistogramBoolean("Media.RTCVideoEncoderInitEncodeSuccess",
init_retval == WEBRTC_VIDEO_CODEC_OK);
if (init_retval != WEBRTC_VIDEO_CODEC_OK)
return;
UMA_HISTOGRAM_ENUMERATION("Media.RTCVideoEncoderProfile", profile,
media::VIDEO_CODEC_PROFILE_MAX + 1);
}
void RecordEncoderStatusUMA(const media::EncoderStatus& status,
webrtc::VideoCodecType type) {
std::string histogram_name = "Media.RTCVideoEncoderStatus.";
switch (type) {
case webrtc::VideoCodecType::kVideoCodecH264:
histogram_name += "H264";
break;
case webrtc::VideoCodecType::kVideoCodecVP8:
histogram_name += "VP8";
break;
case webrtc::VideoCodecType::kVideoCodecVP9:
histogram_name += "VP9";
break;
case webrtc::VideoCodecType::kVideoCodecAV1:
histogram_name += "AV1";
break;
default:
histogram_name += "Other";
break;
}
base::UmaHistogramEnumeration(histogram_name, status.code());
}
bool SupportGpuMemoryBufferEncoding() {
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kVideoCaptureUseGpuMemoryBuffer);
}
bool IsZeroCopyEnabled(webrtc::VideoContentType content_type) {
if (content_type == webrtc::VideoContentType::SCREENSHARE) {
// Zero copy screen capture.
#if BUILDFLAG(IS_CHROMEOS_ASH)
// The zero-copy capture is available for all sources in ChromeOS
// Ash-chrome.
return IsZeroCopyTabCaptureEnabled();
#else
// Currently, zero copy capture screenshare is available only for tabs.
// Since it is impossible to determine the content source, tab, window or
// monitor, we don't configure VideoEncodeAccelerator with NV12
// GpuMemoryBuffer instead we configure I420 SHMEM as if it is not zero
// copy, and we convert the NV12 GpuMemoryBuffer to I420 SHMEM in
// RtcVideoEncoder::Impl::Encode().
// TODO(b/267995715): Solve this problem by calling Initialize() in the
// first frame.
return false;
#endif
}
// Zero copy video capture from other sources (e.g. camera).
return !base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableVideoCaptureUseGpuMemoryBuffer) &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kVideoCaptureUseGpuMemoryBuffer);
}
} // namespace
namespace features {
// Fallback from hardware encoder (if available) to software, for WebRTC
// screensharing that uses temporal scalability.
BASE_FEATURE(kWebRtcScreenshareSwEncoding,
"WebRtcScreenshareSwEncoding",
base::FEATURE_DISABLED_BY_DEFAULT);
} // namespace features
// This private class of RTCVideoEncoder does the actual work of communicating
// with a media::VideoEncodeAccelerator for handling video encoding. It can
// be created on any thread, but should subsequently be executed on
// |gpu_task_runner| including destructor.
//
// This class separates state related to the thread that RTCVideoEncoder
// operates on from the thread that |gpu_factories_| provides for accelerator
// operations (presently the media thread).
class RTCVideoEncoder::Impl : public media::VideoEncodeAccelerator::Client {
public:
using UpdateEncoderInfoCallback = base::RepeatingCallback<void(
media::VideoEncoderInfo,
std::vector<webrtc::VideoFrameBuffer::Type>)>;
Impl(media::GpuVideoAcceleratorFactories* gpu_factories,
webrtc::VideoCodecType video_codec_type,
webrtc::VideoContentType video_content_type,
UpdateEncoderInfoCallback update_encoder_info_callback,
base::RepeatingClosure execute_software_fallback,
base::WeakPtr<Impl>& weak_this_for_client);
~Impl() override;
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
// Create the VEA and call Initialize() on it. Called once per instantiation,
// and then the instance is bound forevermore to whichever thread made the
// call.
// RTCVideoEncoder expects to be able to call this function synchronously from
// its own thread, hence the |init_event| argument.
void CreateAndInitializeVEA(
const media::VideoEncodeAccelerator::Config& vea_config,
SignaledValue init_event);
// Enqueue a frame from WebRTC for encoding.
// RTCVideoEncoder expects to be able to call this function synchronously from
// its own thread, hence the |encode_event| argument.
void Enqueue(FrameChunk frame_chunk, SignaledValue encode_event);
// Request encoding parameter change for the underlying encoder.
void RequestEncodingParametersChange(
const webrtc::VideoEncoder::RateControlParameters& parameters);
void RegisterEncodeCompleteCallback(webrtc::EncodedImageCallback* callback);
webrtc::VideoCodecType video_codec_type() const { return video_codec_type_; }
// media::VideoEncodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(
int32_t bitstream_buffer_id,
const media::BitstreamBufferMetadata& metadata) override;
void NotifyErrorStatus(const media::EncoderStatus& status) override;
void NotifyEncoderInfoChange(const media::VideoEncoderInfo& info) override;
private:
enum {
kInputBufferExtraCount = 1, // The number of input buffers allocated, more
// than what is requested by
// VEA::RequireBitstreamBuffers().
kOutputBufferCount = 3,
};
// Perform encoding on an input frame from the input queue.
void EncodeOneFrame(FrameChunk frame_chunk);
// Perform encoding on an input frame from the input queue using VEA native
// input mode. The input frame must be backed with GpuMemoryBuffer buffers.
void EncodeOneFrameWithNativeInput(FrameChunk frame_chunk);
// Creates a GpuMemoryBuffer frame filled with black pixels. Returns true if
// the frame is successfully created; false otherwise.
bool CreateBlackGpuMemoryBufferFrame(const gfx::Size& natural_size);
// Notify that an input frame is finished for encoding. |index| is the index
// of the completed frame in |input_buffers_|.
void InputBufferReleased(int index);
// Checks if the frame size is different than hardware accelerator
// requirements.
bool RequiresSizeChange(const media::VideoFrame& frame) const;
// Return an encoded output buffer to WebRTC.
void ReturnEncodedImage(const webrtc::EncodedImage& image,
const webrtc::CodecSpecificInfo& info,
int32_t bitstream_buffer_id);
// Records |failed_timestamp_match_| value after a session.
void RecordTimestampMatchUMA() const;
// Get a list of the spatial layer resolutions that are currently active,
// meaning the are configured, have active=true and have non-zero bandwidth
// allocated to them.
// Returns an empty list is spatial layers are not used.
std::vector<gfx::Size> ActiveSpatialResolutions() const;
// Call VideoEncodeAccelerator::UseOutputBitstreamBuffer() for a buffer whose
// id is |bitstream_buffer_id|.
void UseOutputBitstreamBuffer(int32_t bitstream_buffer_id);
// RTCVideoEncoder is given a buffer to be passed to WebRTC through the
// RTCVideoEncoder::ReturnEncodedImage() function. When that is complete,
// the buffer is returned to Impl by its index using this function.
void BitstreamBufferAvailable(int32_t bitstream_buffer_id);
// This is attached to |gpu_task_runner_|, not the thread class is constructed
// on.
SEQUENCE_CHECKER(sequence_checker_);
// Factory for creating VEAs, shared memory buffers, etc.
media::GpuVideoAcceleratorFactories* gpu_factories_;
// webrtc::VideoEncoder expects InitEncode() and Encode() to be synchronous.
// Do this by waiting on the |async_init_event_| when initialization
// completes, on |async_encode_event_| when encoding completes and on both
// when an error occurs.
ScopedSignaledValue async_init_event_;
ScopedSignaledValue async_encode_event_;
// The underlying VEA to perform encoding on.
std::unique_ptr<media::VideoEncodeAccelerator> video_encoder_;
// Metadata for frames passed to Encode(), matched to encoded frames using
// timestamps.
WTF::Deque<FrameInfo> submitted_frames_;
// Indicates that timestamp match failed and we should no longer attempt
// matching.
bool failed_timestamp_match_{false};
// The pending frames to be encoded with the boolean representing whether the
// frame must be encoded keyframe.
WTF::Deque<FrameChunk> pending_frames_;
// Frame sizes.
gfx::Size input_frame_coded_size_;
gfx::Size input_visible_size_;
// Shared memory buffers for input/output with the VEA.
Vector<std::unique_ptr<base::MappedReadOnlyRegion>> input_buffers_;
Vector<std::pair<base::UnsafeSharedMemoryRegion,
scoped_refptr<RefCountedWritableSharedMemoryMapping>>>
output_buffers_;
// The number of frames that are sent to a hardware video encoder by Encode()
// and the encoder holds them.
size_t frames_in_encoder_count_ = 0;
// Input buffers ready to be filled with input from Encode(). As a LIFO since
// we don't care about ordering.
Vector<int> input_buffers_free_;
// The number of output buffers that have been sent to a hardware video
// encoder by VideoEncodeAccelerator::UseOutputBitstreamBuffer() and the
// encoder holds them.
size_t output_buffers_in_encoder_count_{0};
// The buffer ids that are not sent to a hardware video encoder and this holds
// them. UseOutputBitstreamBuffer() is called for them on the next Encode().
Vector<int32_t> pending_output_buffers_;
// Whether to send the frames to VEA as native buffer. Native buffer allows
// VEA to pass the buffer to the encoder directly without further processing.
bool use_native_input_{false};
// A black GpuMemoryBuffer frame used when the video track is disabled.
scoped_refptr<media::VideoFrame> black_gmb_frame_;
// The video codec type, as reported to WebRTC.
const webrtc::VideoCodecType video_codec_type_;
// The content type, as reported to WebRTC (screenshare vs realtime video).
const webrtc::VideoContentType video_content_type_;
// This has the same information as |encoder_info_.preferred_pixel_formats|
// but can be used on |sequence_checker_| without acquiring the lock.
absl::InlinedVector<webrtc::VideoFrameBuffer::Type,
webrtc::kMaxPreferredPixelFormats>
preferred_pixel_formats_;
UpdateEncoderInfoCallback update_encoder_info_callback_;
// Calling this causes a software encoder fallback.
base::RepeatingClosure execute_software_fallback_;
// The reslutions of active spatial layer, only used when |Vp9Metadata| is
// contained in |BitstreamBufferMetadata|. it will be updated when key frame
// is produced.
std::vector<gfx::Size> current_spatial_layer_resolutions_
ALLOW_DISCOURAGED_TYPE(
"Matches media::Vp9Metadata::spatial_layer_resolutions etc");
// Index of the highest spatial layer with bandwidth allocated for it.
size_t highest_active_spatial_index_{0};
// We cannot immediately return error conditions to the WebRTC user of this
// class, as there is no error callback in the webrtc::VideoEncoder interface.
// Instead, we cache an error status here and return it the next time an
// interface entry point is called.
int32_t status_ GUARDED_BY_CONTEXT(sequence_checker_){
WEBRTC_VIDEO_CODEC_UNINITIALIZED};
// Protect |encoded_image_callback_|. |encoded_image_callback_| is read on
// media thread and written in webrtc encoder thread.
mutable base::Lock lock_;
// webrtc::VideoEncoder encode complete callback.
// TODO(b/257021675): Don't guard this by |lock_|
webrtc::EncodedImageCallback* encoded_image_callback_ GUARDED_BY(lock_){
nullptr};
// They are bound to |gpu_task_runner_|, which is sequence checked by
// |sequence_checker|.
base::WeakPtr<Impl> weak_this_;
base::WeakPtrFactory<Impl> weak_this_factory_{this};
};
RTCVideoEncoder::Impl::Impl(
media::GpuVideoAcceleratorFactories* gpu_factories,
webrtc::VideoCodecType video_codec_type,
webrtc::VideoContentType video_content_type,
UpdateEncoderInfoCallback update_encoder_info_callback,
base::RepeatingClosure execute_software_fallback,
base::WeakPtr<Impl>& weak_this_for_client)
: gpu_factories_(gpu_factories),
video_codec_type_(video_codec_type),
video_content_type_(video_content_type),
update_encoder_info_callback_(std::move(update_encoder_info_callback)),
execute_software_fallback_(std::move(execute_software_fallback)) {
DETACH_FROM_SEQUENCE(sequence_checker_);
preferred_pixel_formats_ = {webrtc::VideoFrameBuffer::Type::kI420};
weak_this_ = weak_this_factory_.GetWeakPtr();
weak_this_for_client = weak_this_;
}
void RTCVideoEncoder::Impl::CreateAndInitializeVEA(
const media::VideoEncodeAccelerator::Config& vea_config,
SignaledValue init_event) {
TRACE_EVENT0("webrtc", "RTCVideoEncoder::Impl::CreateAndInitializeVEA");
DVLOG(3) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
status_ = WEBRTC_VIDEO_CODEC_UNINITIALIZED;
async_init_event_ = ScopedSignaledValue(std::move(init_event));
async_encode_event_.reset();
video_encoder_ = gpu_factories_->CreateVideoEncodeAccelerator();
if (!video_encoder_) {
NotifyErrorStatus({media::EncoderStatus::Codes::kEncoderInitializationError,
"Failed to create VideoEncodeAccelerato"});
return;
}
input_visible_size_ = vea_config.input_visible_size;
// The valid config is NV12+kGpuMemoryBuffer and I420+kShmem.
CHECK_EQ(
vea_config.input_format == media::PIXEL_FORMAT_NV12,
vea_config.storage_type ==
media::VideoEncodeAccelerator::Config::StorageType::kGpuMemoryBuffer);
if (vea_config.storage_type ==
media::VideoEncodeAccelerator::Config::StorageType::kGpuMemoryBuffer) {
use_native_input_ = true;
preferred_pixel_formats_ = {webrtc::VideoFrameBuffer::Type::kNV12};
}
// When we don't have built in H264 software encoding, allow usage of any
// software encoders provided by the platform.
#if !BUILDFLAG(ENABLE_OPENH264) && BUILDFLAG(RTC_USE_H264)
if (profile >= media::H264PROFILE_MIN && profile <= media::H264PROFILE_MAX) {
vea_config.required_encoder_type =
media::VideoEncodeAccelerator::Config::EncoderType::kNoPreference;
}
#endif
if (!video_encoder_->Initialize(vea_config, this,
std::make_unique<media::NullMediaLog>())) {
NotifyErrorStatus({media::EncoderStatus::Codes::kEncoderInitializationError,
"Failed to initialize VideoEncodeAccelerator"});
return;
}
current_spatial_layer_resolutions_.clear();
for (const auto& layer : vea_config.spatial_layers) {
current_spatial_layer_resolutions_.emplace_back(layer.width, layer.height);
}
highest_active_spatial_index_ = vea_config.spatial_layers.empty()
? 0u
: vea_config.spatial_layers.size() - 1;
// RequireBitstreamBuffers or NotifyError will be called and the waiter will
// be signaled.
}
void RTCVideoEncoder::Impl::NotifyEncoderInfoChange(
const media::VideoEncoderInfo& info) {
update_encoder_info_callback_.Run(
info,
std::vector<webrtc::VideoFrameBuffer::Type>(
preferred_pixel_formats_.begin(), preferred_pixel_formats_.end()));
}
void RTCVideoEncoder::Impl::Enqueue(FrameChunk frame_chunk,
SignaledValue encode_event) {
TRACE_EVENT1("webrtc", "RTCVideoEncoder::Impl::Enqueue", "timestamp",
frame_chunk.timestamp);
DVLOG(3) << __func__;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (status_ != WEBRTC_VIDEO_CODEC_OK) {
encode_event.Set(status_);
encode_event.Signal();
return;
}
// If there are no free input and output buffers, drop the frame to avoid a
// deadlock. If there is a free input buffer and |use_native_input_| is false,
// EncodeOneFrame will run and unblock Encode(). If there are no free input
// buffers but there is a free output buffer, InputBufferReleased() will be
// called later to unblock Encode().
//
// The caller of Encode() holds a webrtc lock. The deadlock happens when:
// (1) Encode() is waiting for the frame to be encoded in EncodeOneFrame().
// (2) There are no free input buffers and they cannot be freed because
// the encoder has no output buffers.
// (3) Output buffers cannot be freed because OnEncodedImage() is queued
// on libjingle worker thread to be run. But the worker thread is waiting
// for the same webrtc lock held by the caller of Encode().
//
// Dropping a frame is fine. The encoder has been filled with all input
// buffers. Returning an error in Encode() is not fatal and WebRTC will just
// continue. If this is a key frame, WebRTC will request a key frame again.
// Besides, webrtc will drop a frame if Encode() blocks too long.
if (!use_native_input_ && input_buffers_free_.empty() &&
output_buffers_in_encoder_count_ == 0u) {
DVLOG(2) << "Run out of input and output buffers. Drop the frame.";
encode_event.Set(WEBRTC_VIDEO_CODEC_ERROR);
encode_event.Signal();
return;
}
async_encode_event_ = ScopedSignaledValue(std::move(encode_event));
if (use_native_input_) {
DCHECK(pending_frames_.empty());
EncodeOneFrameWithNativeInput(std::move(frame_chunk));
return;
}
pending_frames_.push_back(std::move(frame_chunk));
// When |input_buffers_free_| is empty, EncodeOneFrame() for the frame in
// |pending_frames_| will be invoked from InputBufferReleased().
while (!pending_frames_.empty() && !input_buffers_free_.empty()) {
auto chunk = std::move(pending_frames_.front());
pending_frames_.pop_front();
EncodeOneFrame(std::move(chunk));
}
}
void RTCVideoEncoder::Impl::BitstreamBufferAvailable(
int32_t bitstream_buffer_id) {
TRACE_EVENT0("webrtc", "RTCVideoEncoder::Impl::BitstreamBufferAvailable");
DVLOG(3) << __func__ << " bitstream_buffer_id=" << bitstream_buffer_id;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// If there is no frame in a hardware video encoder,
// UseOutputBitstreamBuffer() call for this buffer id is postponed in the next
// Encode() call. This avoids unnecessary thread wake up in GPU process.
if (frames_in_encoder_count_ == 0) {
pending_output_buffers_.push_back(bitstream_buffer_id);
return;
}
UseOutputBitstreamBuffer(bitstream_buffer_id);
}
void RTCVideoEncoder::Impl::UseOutputBitstreamBuffer(
int32_t bitstream_buffer_id) {
TRACE_EVENT0("webrtc", "RTCVideoEncoder::Impl::UseOutputBitstreamBuffer");
DVLOG(3) << __func__ << " bitstream_buffer_id=" << bitstream_buffer_id;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (video_encoder_) {
video_encoder_->UseOutputBitstreamBuffer(media::BitstreamBuffer(
bitstream_buffer_id,
output_buffers_[bitstream_buffer_id].first.Duplicate(),
output_buffers_[bitstream_buffer_id].first.GetSize()));
output_buffers_in_encoder_count_++;
}
}
void RTCVideoEncoder::Impl::RequestEncodingParametersChange(
const webrtc::VideoEncoder::RateControlParameters& parameters) {
DVLOG(3) << __func__ << " bitrate=" << parameters.bitrate.ToString()
<< ", framerate=" << parameters.framerate_fps;
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (status_ != WEBRTC_VIDEO_CODEC_OK)
return;
// NotfiyError() has been called. Don't proceed the change request.
if (!video_encoder_)
return;
// This is a workaround to zero being temporarily provided, as part of the
// initial setup, by WebRTC.
media::VideoBitrateAllocation allocation;
if (parameters.bitrate.get_sum_bps() == 0u) {
allocation.SetBitrate(0, 0, 1u);
}
uint32_t framerate =
std::max(1u, static_cast<uint32_t>(parameters.framerate_fps + 0.5));
highest_active_spatial_index_ = 0;
for (size_t spatial_id = 0;
spatial_id < media::VideoBitrateAllocation::kMaxSpatialLayers;
++spatial_id) {
bool spatial_layer_active = false;
for (size_t temporal_id = 0;
temporal_id < media::VideoBitrateAllocation::kMaxTemporalLayers;
++temporal_id) {
// TODO(sprang): Clean this up if/when webrtc struct moves to int.
uint32_t temporal_layer_bitrate = base::checked_cast<int>(
parameters.bitrate.GetBitrate(spatial_id, temporal_id));
if (!allocation.SetBitrate(spatial_id, temporal_id,
temporal_layer_bitrate)) {
LOG(WARNING) << "Overflow in bitrate allocation: "
<< parameters.bitrate.ToString();