Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1)

Side by Side Diff: talk/media/webrtc/webrtcvideoengine2.cc

Issue 1587193006: Move talk/media to webrtc/media (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Rebased to b647aca12a884a13c1728118586245399b55fa3d (#11493) Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * libjingle
3 * Copyright 2014 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #ifdef HAVE_WEBRTC_VIDEO
29 #include "talk/media/webrtc/webrtcvideoengine2.h"
30
31 #include <algorithm>
32 #include <set>
33 #include <string>
34
35 #include "talk/media/base/videocapturer.h"
36 #include "talk/media/base/videorenderer.h"
37 #include "talk/media/webrtc/constants.h"
38 #include "talk/media/webrtc/simulcast.h"
39 #include "talk/media/webrtc/webrtcmediaengine.h"
40 #include "talk/media/webrtc/webrtcvideoencoderfactory.h"
41 #include "talk/media/webrtc/webrtcvideoframe.h"
42 #include "talk/media/webrtc/webrtcvoiceengine.h"
43 #include "webrtc/base/buffer.h"
44 #include "webrtc/base/logging.h"
45 #include "webrtc/base/stringutils.h"
46 #include "webrtc/base/timeutils.h"
47 #include "webrtc/base/trace_event.h"
48 #include "webrtc/call.h"
49 #include "webrtc/modules/video_coding/codecs/h264/include/h264.h"
50 #include "webrtc/modules/video_coding/codecs/vp8/simulcast_encoder_adapter.h"
51 #include "webrtc/system_wrappers/include/field_trial.h"
52 #include "webrtc/video_decoder.h"
53 #include "webrtc/video_encoder.h"
54
55 namespace cricket {
56 namespace {
57
58 // Wrap cricket::WebRtcVideoEncoderFactory as a webrtc::VideoEncoderFactory.
59 class EncoderFactoryAdapter : public webrtc::VideoEncoderFactory {
60 public:
61 // EncoderFactoryAdapter doesn't take ownership of |factory|, which is owned
62 // by e.g. PeerConnectionFactory.
63 explicit EncoderFactoryAdapter(cricket::WebRtcVideoEncoderFactory* factory)
64 : factory_(factory) {}
65 virtual ~EncoderFactoryAdapter() {}
66
67 // Implement webrtc::VideoEncoderFactory.
68 webrtc::VideoEncoder* Create() override {
69 return factory_->CreateVideoEncoder(webrtc::kVideoCodecVP8);
70 }
71
72 void Destroy(webrtc::VideoEncoder* encoder) override {
73 return factory_->DestroyVideoEncoder(encoder);
74 }
75
76 private:
77 cricket::WebRtcVideoEncoderFactory* const factory_;
78 };
79
80 webrtc::Call::Config::BitrateConfig GetBitrateConfigForCodec(
81 const VideoCodec& codec) {
82 webrtc::Call::Config::BitrateConfig config;
83 int bitrate_kbps;
84 if (codec.GetParam(kCodecParamMinBitrate, &bitrate_kbps) &&
85 bitrate_kbps > 0) {
86 config.min_bitrate_bps = bitrate_kbps * 1000;
87 } else {
88 config.min_bitrate_bps = 0;
89 }
90 if (codec.GetParam(kCodecParamStartBitrate, &bitrate_kbps) &&
91 bitrate_kbps > 0) {
92 config.start_bitrate_bps = bitrate_kbps * 1000;
93 } else {
94 // Do not reconfigure start bitrate unless it's specified and positive.
95 config.start_bitrate_bps = -1;
96 }
97 if (codec.GetParam(kCodecParamMaxBitrate, &bitrate_kbps) &&
98 bitrate_kbps > 0) {
99 config.max_bitrate_bps = bitrate_kbps * 1000;
100 } else {
101 config.max_bitrate_bps = -1;
102 }
103 return config;
104 }
105
106 // An encoder factory that wraps Create requests for simulcastable codec types
107 // with a webrtc::SimulcastEncoderAdapter. Non simulcastable codec type
108 // requests are just passed through to the contained encoder factory.
109 class WebRtcSimulcastEncoderFactory
110 : public cricket::WebRtcVideoEncoderFactory {
111 public:
112 // WebRtcSimulcastEncoderFactory doesn't take ownership of |factory|, which is
113 // owned by e.g. PeerConnectionFactory.
114 explicit WebRtcSimulcastEncoderFactory(
115 cricket::WebRtcVideoEncoderFactory* factory)
116 : factory_(factory) {}
117
118 static bool UseSimulcastEncoderFactory(
119 const std::vector<VideoCodec>& codecs) {
120 // If any codec is VP8, use the simulcast factory. If asked to create a
121 // non-VP8 codec, we'll just return a contained factory encoder directly.
122 for (const auto& codec : codecs) {
123 if (codec.type == webrtc::kVideoCodecVP8) {
124 return true;
125 }
126 }
127 return false;
128 }
129
130 webrtc::VideoEncoder* CreateVideoEncoder(
131 webrtc::VideoCodecType type) override {
132 RTC_DCHECK(factory_ != NULL);
133 // If it's a codec type we can simulcast, create a wrapped encoder.
134 if (type == webrtc::kVideoCodecVP8) {
135 return new webrtc::SimulcastEncoderAdapter(
136 new EncoderFactoryAdapter(factory_));
137 }
138 webrtc::VideoEncoder* encoder = factory_->CreateVideoEncoder(type);
139 if (encoder) {
140 non_simulcast_encoders_.push_back(encoder);
141 }
142 return encoder;
143 }
144
145 const std::vector<VideoCodec>& codecs() const override {
146 return factory_->codecs();
147 }
148
149 bool EncoderTypeHasInternalSource(
150 webrtc::VideoCodecType type) const override {
151 return factory_->EncoderTypeHasInternalSource(type);
152 }
153
154 void DestroyVideoEncoder(webrtc::VideoEncoder* encoder) override {
155 // Check first to see if the encoder wasn't wrapped in a
156 // SimulcastEncoderAdapter. In that case, ask the factory to destroy it.
157 if (std::remove(non_simulcast_encoders_.begin(),
158 non_simulcast_encoders_.end(),
159 encoder) != non_simulcast_encoders_.end()) {
160 factory_->DestroyVideoEncoder(encoder);
161 return;
162 }
163
164 // Otherwise, SimulcastEncoderAdapter can be deleted directly, and will call
165 // DestroyVideoEncoder on the factory for individual encoder instances.
166 delete encoder;
167 }
168
169 private:
170 cricket::WebRtcVideoEncoderFactory* factory_;
171 // A list of encoders that were created without being wrapped in a
172 // SimulcastEncoderAdapter.
173 std::vector<webrtc::VideoEncoder*> non_simulcast_encoders_;
174 };
175
176 bool CodecIsInternallySupported(const std::string& codec_name) {
177 if (CodecNamesEq(codec_name, kVp8CodecName)) {
178 return true;
179 }
180 if (CodecNamesEq(codec_name, kVp9CodecName)) {
181 return true;
182 }
183 if (CodecNamesEq(codec_name, kH264CodecName)) {
184 return webrtc::H264Encoder::IsSupported() &&
185 webrtc::H264Decoder::IsSupported();
186 }
187 return false;
188 }
189
190 void AddDefaultFeedbackParams(VideoCodec* codec) {
191 codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamCcm, kRtcpFbCcmParamFir));
192 codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamNack, kParamValueEmpty));
193 codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamNack, kRtcpFbNackParamPli));
194 codec->AddFeedbackParam(FeedbackParam(kRtcpFbParamRemb, kParamValueEmpty));
195 codec->AddFeedbackParam(
196 FeedbackParam(kRtcpFbParamTransportCc, kParamValueEmpty));
197 }
198
199 static VideoCodec MakeVideoCodecWithDefaultFeedbackParams(int payload_type,
200 const char* name) {
201 VideoCodec codec(payload_type, name, kDefaultVideoMaxWidth,
202 kDefaultVideoMaxHeight, kDefaultVideoMaxFramerate, 0);
203 AddDefaultFeedbackParams(&codec);
204 return codec;
205 }
206
207 static std::string CodecVectorToString(const std::vector<VideoCodec>& codecs) {
208 std::stringstream out;
209 out << '{';
210 for (size_t i = 0; i < codecs.size(); ++i) {
211 out << codecs[i].ToString();
212 if (i != codecs.size() - 1) {
213 out << ", ";
214 }
215 }
216 out << '}';
217 return out.str();
218 }
219
220 static bool ValidateCodecFormats(const std::vector<VideoCodec>& codecs) {
221 bool has_video = false;
222 for (size_t i = 0; i < codecs.size(); ++i) {
223 if (!codecs[i].ValidateCodecFormat()) {
224 return false;
225 }
226 if (codecs[i].GetCodecType() == VideoCodec::CODEC_VIDEO) {
227 has_video = true;
228 }
229 }
230 if (!has_video) {
231 LOG(LS_ERROR) << "Setting codecs without a video codec is invalid: "
232 << CodecVectorToString(codecs);
233 return false;
234 }
235 return true;
236 }
237
238 static bool ValidateStreamParams(const StreamParams& sp) {
239 if (sp.ssrcs.empty()) {
240 LOG(LS_ERROR) << "No SSRCs in stream parameters: " << sp.ToString();
241 return false;
242 }
243
244 std::vector<uint32_t> primary_ssrcs;
245 sp.GetPrimarySsrcs(&primary_ssrcs);
246 std::vector<uint32_t> rtx_ssrcs;
247 sp.GetFidSsrcs(primary_ssrcs, &rtx_ssrcs);
248 for (uint32_t rtx_ssrc : rtx_ssrcs) {
249 bool rtx_ssrc_present = false;
250 for (uint32_t sp_ssrc : sp.ssrcs) {
251 if (sp_ssrc == rtx_ssrc) {
252 rtx_ssrc_present = true;
253 break;
254 }
255 }
256 if (!rtx_ssrc_present) {
257 LOG(LS_ERROR) << "RTX SSRC '" << rtx_ssrc
258 << "' missing from StreamParams ssrcs: " << sp.ToString();
259 return false;
260 }
261 }
262 if (!rtx_ssrcs.empty() && primary_ssrcs.size() != rtx_ssrcs.size()) {
263 LOG(LS_ERROR)
264 << "RTX SSRCs exist, but don't cover all SSRCs (unsupported): "
265 << sp.ToString();
266 return false;
267 }
268
269 return true;
270 }
271
272 inline bool ContainsHeaderExtension(
273 const std::vector<webrtc::RtpExtension>& extensions,
274 const std::string& name) {
275 for (const auto& kv : extensions) {
276 if (kv.name == name) {
277 return true;
278 }
279 }
280 return false;
281 }
282
283 // Merges two fec configs and logs an error if a conflict arises
284 // such that merging in different order would trigger a different output.
285 static void MergeFecConfig(const webrtc::FecConfig& other,
286 webrtc::FecConfig* output) {
287 if (other.ulpfec_payload_type != -1) {
288 if (output->ulpfec_payload_type != -1 &&
289 output->ulpfec_payload_type != other.ulpfec_payload_type) {
290 LOG(LS_WARNING) << "Conflict merging ulpfec_payload_type configs: "
291 << output->ulpfec_payload_type << " and "
292 << other.ulpfec_payload_type;
293 }
294 output->ulpfec_payload_type = other.ulpfec_payload_type;
295 }
296 if (other.red_payload_type != -1) {
297 if (output->red_payload_type != -1 &&
298 output->red_payload_type != other.red_payload_type) {
299 LOG(LS_WARNING) << "Conflict merging red_payload_type configs: "
300 << output->red_payload_type << " and "
301 << other.red_payload_type;
302 }
303 output->red_payload_type = other.red_payload_type;
304 }
305 if (other.red_rtx_payload_type != -1) {
306 if (output->red_rtx_payload_type != -1 &&
307 output->red_rtx_payload_type != other.red_rtx_payload_type) {
308 LOG(LS_WARNING) << "Conflict merging red_rtx_payload_type configs: "
309 << output->red_rtx_payload_type << " and "
310 << other.red_rtx_payload_type;
311 }
312 output->red_rtx_payload_type = other.red_rtx_payload_type;
313 }
314 }
315
316 // Returns true if the given codec is disallowed from doing simulcast.
317 bool IsCodecBlacklistedForSimulcast(const std::string& codec_name) {
318 return CodecNamesEq(codec_name, kH264CodecName) ||
319 CodecNamesEq(codec_name, kVp9CodecName);
320 }
321
322 // The selected thresholds for QVGA and VGA corresponded to a QP around 10.
323 // The change in QP declined above the selected bitrates.
324 static int GetMaxDefaultVideoBitrateKbps(int width, int height) {
325 if (width * height <= 320 * 240) {
326 return 600;
327 } else if (width * height <= 640 * 480) {
328 return 1700;
329 } else if (width * height <= 960 * 540) {
330 return 2000;
331 } else {
332 return 2500;
333 }
334 }
335 } // namespace
336
337 // Constants defined in talk/media/webrtc/constants.h
338 // TODO(pbos): Move these to a separate constants.cc file.
339 const int kMinVideoBitrate = 30;
340 const int kStartVideoBitrate = 300;
341
342 const int kVideoMtu = 1200;
343 const int kVideoRtpBufferSize = 65536;
344
345 // This constant is really an on/off, lower-level configurable NACK history
346 // duration hasn't been implemented.
347 static const int kNackHistoryMs = 1000;
348
349 static const int kDefaultQpMax = 56;
350
351 static const int kDefaultRtcpReceiverReportSsrc = 1;
352
353 std::vector<VideoCodec> DefaultVideoCodecList() {
354 std::vector<VideoCodec> codecs;
355 codecs.push_back(MakeVideoCodecWithDefaultFeedbackParams(kDefaultVp8PlType,
356 kVp8CodecName));
357 if (CodecIsInternallySupported(kVp9CodecName)) {
358 codecs.push_back(MakeVideoCodecWithDefaultFeedbackParams(kDefaultVp9PlType,
359 kVp9CodecName));
360 }
361 if (CodecIsInternallySupported(kH264CodecName)) {
362 codecs.push_back(MakeVideoCodecWithDefaultFeedbackParams(kDefaultH264PlType,
363 kH264CodecName));
364 }
365 codecs.push_back(
366 VideoCodec::CreateRtxCodec(kDefaultRtxVp8PlType, kDefaultVp8PlType));
367 if (CodecIsInternallySupported(kVp9CodecName)) {
368 codecs.push_back(
369 VideoCodec::CreateRtxCodec(kDefaultRtxVp9PlType, kDefaultVp9PlType));
370 }
371 codecs.push_back(VideoCodec(kDefaultRedPlType, kRedCodecName));
372 codecs.push_back(
373 VideoCodec::CreateRtxCodec(kDefaultRtxRedPlType, kDefaultRedPlType));
374 codecs.push_back(VideoCodec(kDefaultUlpfecType, kUlpfecCodecName));
375 return codecs;
376 }
377
378 std::vector<webrtc::VideoStream>
379 WebRtcVideoChannel2::WebRtcVideoSendStream::CreateSimulcastVideoStreams(
380 const VideoCodec& codec,
381 const VideoOptions& options,
382 int max_bitrate_bps,
383 size_t num_streams) {
384 int max_qp = kDefaultQpMax;
385 codec.GetParam(kCodecParamMaxQuantization, &max_qp);
386
387 return GetSimulcastConfig(
388 num_streams, codec.width, codec.height, max_bitrate_bps, max_qp,
389 codec.framerate != 0 ? codec.framerate : kDefaultVideoMaxFramerate);
390 }
391
392 std::vector<webrtc::VideoStream>
393 WebRtcVideoChannel2::WebRtcVideoSendStream::CreateVideoStreams(
394 const VideoCodec& codec,
395 const VideoOptions& options,
396 int max_bitrate_bps,
397 size_t num_streams) {
398 int codec_max_bitrate_kbps;
399 if (codec.GetParam(kCodecParamMaxBitrate, &codec_max_bitrate_kbps)) {
400 max_bitrate_bps = codec_max_bitrate_kbps * 1000;
401 }
402 if (num_streams != 1) {
403 return CreateSimulcastVideoStreams(codec, options, max_bitrate_bps,
404 num_streams);
405 }
406
407 // For unset max bitrates set default bitrate for non-simulcast.
408 if (max_bitrate_bps <= 0) {
409 max_bitrate_bps =
410 GetMaxDefaultVideoBitrateKbps(codec.width, codec.height) * 1000;
411 }
412
413 webrtc::VideoStream stream;
414 stream.width = codec.width;
415 stream.height = codec.height;
416 stream.max_framerate =
417 codec.framerate != 0 ? codec.framerate : kDefaultVideoMaxFramerate;
418
419 stream.min_bitrate_bps = kMinVideoBitrate * 1000;
420 stream.target_bitrate_bps = stream.max_bitrate_bps = max_bitrate_bps;
421
422 int max_qp = kDefaultQpMax;
423 codec.GetParam(kCodecParamMaxQuantization, &max_qp);
424 stream.max_qp = max_qp;
425 std::vector<webrtc::VideoStream> streams;
426 streams.push_back(stream);
427 return streams;
428 }
429
430 void* WebRtcVideoChannel2::WebRtcVideoSendStream::ConfigureVideoEncoderSettings(
431 const VideoCodec& codec,
432 const VideoOptions& options,
433 bool is_screencast) {
434 // No automatic resizing when using simulcast or screencast.
435 bool automatic_resize =
436 !is_screencast && parameters_.config.rtp.ssrcs.size() == 1;
437 bool frame_dropping = !is_screencast;
438 bool denoising;
439 bool codec_default_denoising = false;
440 if (is_screencast) {
441 denoising = false;
442 } else {
443 // Use codec default if video_noise_reduction is unset.
444 codec_default_denoising = !options.video_noise_reduction;
445 denoising = options.video_noise_reduction.value_or(false);
446 }
447
448 if (CodecNamesEq(codec.name, kH264CodecName)) {
449 encoder_settings_.h264 = webrtc::VideoEncoder::GetDefaultH264Settings();
450 encoder_settings_.h264.frameDroppingOn = frame_dropping;
451 return &encoder_settings_.h264;
452 }
453 if (CodecNamesEq(codec.name, kVp8CodecName)) {
454 encoder_settings_.vp8 = webrtc::VideoEncoder::GetDefaultVp8Settings();
455 encoder_settings_.vp8.automaticResizeOn = automatic_resize;
456 // VP8 denoising is enabled by default.
457 encoder_settings_.vp8.denoisingOn =
458 codec_default_denoising ? true : denoising;
459 encoder_settings_.vp8.frameDroppingOn = frame_dropping;
460 return &encoder_settings_.vp8;
461 }
462 if (CodecNamesEq(codec.name, kVp9CodecName)) {
463 encoder_settings_.vp9 = webrtc::VideoEncoder::GetDefaultVp9Settings();
464 // VP9 denoising is disabled by default.
465 encoder_settings_.vp9.denoisingOn =
466 codec_default_denoising ? false : denoising;
467 encoder_settings_.vp9.frameDroppingOn = frame_dropping;
468 return &encoder_settings_.vp9;
469 }
470 return NULL;
471 }
472
473 DefaultUnsignalledSsrcHandler::DefaultUnsignalledSsrcHandler()
474 : default_recv_ssrc_(0), default_sink_(NULL) {}
475
476 UnsignalledSsrcHandler::Action DefaultUnsignalledSsrcHandler::OnUnsignalledSsrc(
477 WebRtcVideoChannel2* channel,
478 uint32_t ssrc) {
479 if (default_recv_ssrc_ != 0) { // Already one default stream.
480 LOG(LS_WARNING) << "Unknown SSRC, but default receive stream already set.";
481 return kDropPacket;
482 }
483
484 StreamParams sp;
485 sp.ssrcs.push_back(ssrc);
486 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
487 if (!channel->AddRecvStream(sp, true)) {
488 LOG(LS_WARNING) << "Could not create default receive stream.";
489 }
490
491 channel->SetSink(ssrc, default_sink_);
492 default_recv_ssrc_ = ssrc;
493 return kDeliverPacket;
494 }
495
496 rtc::VideoSinkInterface<VideoFrame>*
497 DefaultUnsignalledSsrcHandler::GetDefaultSink() const {
498 return default_sink_;
499 }
500
501 void DefaultUnsignalledSsrcHandler::SetDefaultSink(
502 VideoMediaChannel* channel,
503 rtc::VideoSinkInterface<VideoFrame>* sink) {
504 default_sink_ = sink;
505 if (default_recv_ssrc_ != 0) {
506 channel->SetSink(default_recv_ssrc_, default_sink_);
507 }
508 }
509
510 WebRtcVideoEngine2::WebRtcVideoEngine2()
511 : initialized_(false),
512 external_decoder_factory_(NULL),
513 external_encoder_factory_(NULL) {
514 LOG(LS_INFO) << "WebRtcVideoEngine2::WebRtcVideoEngine2()";
515 video_codecs_ = GetSupportedCodecs();
516 }
517
518 WebRtcVideoEngine2::~WebRtcVideoEngine2() {
519 LOG(LS_INFO) << "WebRtcVideoEngine2::~WebRtcVideoEngine2";
520 }
521
522 void WebRtcVideoEngine2::Init() {
523 LOG(LS_INFO) << "WebRtcVideoEngine2::Init";
524 initialized_ = true;
525 }
526
527 WebRtcVideoChannel2* WebRtcVideoEngine2::CreateChannel(
528 webrtc::Call* call,
529 const VideoOptions& options) {
530 RTC_DCHECK(initialized_);
531 LOG(LS_INFO) << "CreateChannel. Options: " << options.ToString();
532 return new WebRtcVideoChannel2(call, options, video_codecs_,
533 external_encoder_factory_, external_decoder_factory_);
534 }
535
536 const std::vector<VideoCodec>& WebRtcVideoEngine2::codecs() const {
537 return video_codecs_;
538 }
539
540 RtpCapabilities WebRtcVideoEngine2::GetCapabilities() const {
541 RtpCapabilities capabilities;
542 capabilities.header_extensions.push_back(
543 RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
544 kRtpTimestampOffsetHeaderExtensionDefaultId));
545 capabilities.header_extensions.push_back(
546 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
547 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
548 capabilities.header_extensions.push_back(
549 RtpHeaderExtension(kRtpVideoRotationHeaderExtension,
550 kRtpVideoRotationHeaderExtensionDefaultId));
551 if (webrtc::field_trial::FindFullName("WebRTC-SendSideBwe") == "Enabled") {
552 capabilities.header_extensions.push_back(RtpHeaderExtension(
553 kRtpTransportSequenceNumberHeaderExtension,
554 kRtpTransportSequenceNumberHeaderExtensionDefaultId));
555 }
556 return capabilities;
557 }
558
559 void WebRtcVideoEngine2::SetExternalDecoderFactory(
560 WebRtcVideoDecoderFactory* decoder_factory) {
561 RTC_DCHECK(!initialized_);
562 external_decoder_factory_ = decoder_factory;
563 }
564
565 void WebRtcVideoEngine2::SetExternalEncoderFactory(
566 WebRtcVideoEncoderFactory* encoder_factory) {
567 RTC_DCHECK(!initialized_);
568 if (external_encoder_factory_ == encoder_factory)
569 return;
570
571 // No matter what happens we shouldn't hold on to a stale
572 // WebRtcSimulcastEncoderFactory.
573 simulcast_encoder_factory_.reset();
574
575 if (encoder_factory &&
576 WebRtcSimulcastEncoderFactory::UseSimulcastEncoderFactory(
577 encoder_factory->codecs())) {
578 simulcast_encoder_factory_.reset(
579 new WebRtcSimulcastEncoderFactory(encoder_factory));
580 encoder_factory = simulcast_encoder_factory_.get();
581 }
582 external_encoder_factory_ = encoder_factory;
583
584 video_codecs_ = GetSupportedCodecs();
585 }
586
587 std::vector<VideoCodec> WebRtcVideoEngine2::GetSupportedCodecs() const {
588 std::vector<VideoCodec> supported_codecs = DefaultVideoCodecList();
589
590 if (external_encoder_factory_ == NULL) {
591 return supported_codecs;
592 }
593
594 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
595 external_encoder_factory_->codecs();
596 for (size_t i = 0; i < codecs.size(); ++i) {
597 // Don't add internally-supported codecs twice.
598 if (CodecIsInternallySupported(codecs[i].name)) {
599 continue;
600 }
601
602 // External video encoders are given payloads 120-127. This also means that
603 // we only support up to 8 external payload types.
604 const int kExternalVideoPayloadTypeBase = 120;
605 size_t payload_type = kExternalVideoPayloadTypeBase + i;
606 RTC_DCHECK(payload_type < 128);
607 VideoCodec codec(static_cast<int>(payload_type),
608 codecs[i].name,
609 codecs[i].max_width,
610 codecs[i].max_height,
611 codecs[i].max_fps,
612 0);
613
614 AddDefaultFeedbackParams(&codec);
615 supported_codecs.push_back(codec);
616 }
617 return supported_codecs;
618 }
619
620 WebRtcVideoChannel2::WebRtcVideoChannel2(
621 webrtc::Call* call,
622 const VideoOptions& options,
623 const std::vector<VideoCodec>& recv_codecs,
624 WebRtcVideoEncoderFactory* external_encoder_factory,
625 WebRtcVideoDecoderFactory* external_decoder_factory)
626 : call_(call),
627 unsignalled_ssrc_handler_(&default_unsignalled_ssrc_handler_),
628 external_encoder_factory_(external_encoder_factory),
629 external_decoder_factory_(external_decoder_factory) {
630 RTC_DCHECK(thread_checker_.CalledOnValidThread());
631 SetDefaultOptions();
632 options_.SetAll(options);
633 if (options_.cpu_overuse_detection)
634 signal_cpu_adaptation_ = *options_.cpu_overuse_detection;
635 rtcp_receiver_report_ssrc_ = kDefaultRtcpReceiverReportSsrc;
636 sending_ = false;
637 default_send_ssrc_ = 0;
638 RTC_DCHECK(ValidateCodecFormats(recv_codecs));
639 recv_codecs_ = FilterSupportedCodecs(MapCodecs(recv_codecs));
640 }
641
642 void WebRtcVideoChannel2::SetDefaultOptions() {
643 options_.cpu_overuse_detection = rtc::Optional<bool>(true);
644 options_.dscp = rtc::Optional<bool>(false);
645 options_.suspend_below_min_bitrate = rtc::Optional<bool>(false);
646 options_.screencast_min_bitrate_kbps = rtc::Optional<int>(0);
647 }
648
649 WebRtcVideoChannel2::~WebRtcVideoChannel2() {
650 for (auto& kv : send_streams_)
651 delete kv.second;
652 for (auto& kv : receive_streams_)
653 delete kv.second;
654 }
655
656 bool WebRtcVideoChannel2::CodecIsExternallySupported(
657 const std::string& name) const {
658 if (external_encoder_factory_ == NULL) {
659 return false;
660 }
661
662 const std::vector<WebRtcVideoEncoderFactory::VideoCodec> external_codecs =
663 external_encoder_factory_->codecs();
664 for (size_t c = 0; c < external_codecs.size(); ++c) {
665 if (CodecNamesEq(name, external_codecs[c].name)) {
666 return true;
667 }
668 }
669 return false;
670 }
671
672 std::vector<WebRtcVideoChannel2::VideoCodecSettings>
673 WebRtcVideoChannel2::FilterSupportedCodecs(
674 const std::vector<WebRtcVideoChannel2::VideoCodecSettings>& mapped_codecs)
675 const {
676 std::vector<VideoCodecSettings> supported_codecs;
677 for (size_t i = 0; i < mapped_codecs.size(); ++i) {
678 const VideoCodecSettings& codec = mapped_codecs[i];
679 if (CodecIsInternallySupported(codec.codec.name) ||
680 CodecIsExternallySupported(codec.codec.name)) {
681 supported_codecs.push_back(codec);
682 }
683 }
684 return supported_codecs;
685 }
686
687 bool WebRtcVideoChannel2::ReceiveCodecsHaveChanged(
688 std::vector<VideoCodecSettings> before,
689 std::vector<VideoCodecSettings> after) {
690 if (before.size() != after.size()) {
691 return true;
692 }
693 // The receive codec order doesn't matter, so we sort the codecs before
694 // comparing. This is necessary because currently the
695 // only way to change the send codec is to munge SDP, which causes
696 // the receive codec list to change order, which causes the streams
697 // to be recreates which causes a "blink" of black video. In order
698 // to support munging the SDP in this way without recreating receive
699 // streams, we ignore the order of the received codecs so that
700 // changing the order doesn't cause this "blink".
701 auto comparison =
702 [](const VideoCodecSettings& codec1, const VideoCodecSettings& codec2) {
703 return codec1.codec.id > codec2.codec.id;
704 };
705 std::sort(before.begin(), before.end(), comparison);
706 std::sort(after.begin(), after.end(), comparison);
707 for (size_t i = 0; i < before.size(); ++i) {
708 // For the same reason that we sort the codecs, we also ignore the
709 // preference. We don't want a preference change on the receive
710 // side to cause recreation of the stream.
711 before[i].codec.preference = 0;
712 after[i].codec.preference = 0;
713 if (before[i] != after[i]) {
714 return true;
715 }
716 }
717 return false;
718 }
719
720 bool WebRtcVideoChannel2::GetChangedSendParameters(
721 const VideoSendParameters& params,
722 ChangedSendParameters* changed_params) const {
723 if (!ValidateCodecFormats(params.codecs) ||
724 !ValidateRtpExtensions(params.extensions)) {
725 return false;
726 }
727
728 // Handle send codec.
729 const std::vector<VideoCodecSettings> supported_codecs =
730 FilterSupportedCodecs(MapCodecs(params.codecs));
731
732 if (supported_codecs.empty()) {
733 LOG(LS_ERROR) << "No video codecs supported.";
734 return false;
735 }
736
737 if (!send_codec_ || supported_codecs.front() != *send_codec_) {
738 changed_params->codec =
739 rtc::Optional<VideoCodecSettings>(supported_codecs.front());
740 }
741
742 // Handle RTP header extensions.
743 std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(
744 params.extensions, webrtc::RtpExtension::IsSupportedForVideo, true);
745 if (send_rtp_extensions_ != filtered_extensions) {
746 changed_params->rtp_header_extensions =
747 rtc::Optional<std::vector<webrtc::RtpExtension>>(filtered_extensions);
748 }
749
750 // Handle max bitrate.
751 if (params.max_bandwidth_bps != bitrate_config_.max_bitrate_bps &&
752 params.max_bandwidth_bps >= 0) {
753 // 0 uncaps max bitrate (-1).
754 changed_params->max_bandwidth_bps = rtc::Optional<int>(
755 params.max_bandwidth_bps == 0 ? -1 : params.max_bandwidth_bps);
756 }
757
758 // Handle options.
759 // TODO(pbos): Require VideoSendParameters to contain a full set of options
760 // and check if params.options != options_ instead of applying a delta.
761 VideoOptions new_options = options_;
762 new_options.SetAll(params.options);
763 if (!(new_options == options_)) {
764 changed_params->options = rtc::Optional<VideoOptions>(new_options);
765 }
766
767 // Handle RTCP mode.
768 if (params.rtcp.reduced_size != send_params_.rtcp.reduced_size) {
769 changed_params->rtcp_mode = rtc::Optional<webrtc::RtcpMode>(
770 params.rtcp.reduced_size ? webrtc::RtcpMode::kReducedSize
771 : webrtc::RtcpMode::kCompound);
772 }
773
774 return true;
775 }
776
777 bool WebRtcVideoChannel2::SetSendParameters(const VideoSendParameters& params) {
778 TRACE_EVENT0("webrtc", "WebRtcVideoChannel2::SetSendParameters");
779 LOG(LS_INFO) << "SetSendParameters: " << params.ToString();
780 ChangedSendParameters changed_params;
781 if (!GetChangedSendParameters(params, &changed_params)) {
782 return false;
783 }
784
785 bool bitrate_config_changed = false;
786
787 if (changed_params.codec) {
788 const VideoCodecSettings& codec_settings = *changed_params.codec;
789 send_codec_ = rtc::Optional<VideoCodecSettings>(codec_settings);
790
791 LOG(LS_INFO) << "Using codec: " << codec_settings.codec.ToString();
792 // TODO(holmer): Changing the codec parameters shouldn't necessarily mean
793 // that we change the min/max of bandwidth estimation. Reevaluate this.
794 bitrate_config_ = GetBitrateConfigForCodec(codec_settings.codec);
795 bitrate_config_changed = true;
796 }
797
798 if (changed_params.rtp_header_extensions) {
799 send_rtp_extensions_ = *changed_params.rtp_header_extensions;
800 }
801
802 if (changed_params.max_bandwidth_bps) {
803 // TODO(pbos): Figure out whether b=AS means max bitrate for this
804 // WebRtcVideoChannel2 (in which case we're good), or per sender (SSRC), in
805 // which case this should not set a Call::BitrateConfig but rather
806 // reconfigure all senders.
807 int max_bitrate_bps = *changed_params.max_bandwidth_bps;
808 bitrate_config_.start_bitrate_bps = -1;
809 bitrate_config_.max_bitrate_bps = max_bitrate_bps;
810 if (max_bitrate_bps > 0 &&
811 bitrate_config_.min_bitrate_bps > max_bitrate_bps) {
812 bitrate_config_.min_bitrate_bps = max_bitrate_bps;
813 }
814 bitrate_config_changed = true;
815 }
816
817 if (bitrate_config_changed) {
818 call_->SetBitrateConfig(bitrate_config_);
819 }
820
821 if (changed_params.options) {
822 options_.SetAll(*changed_params.options);
823 {
824 rtc::CritScope lock(&capturer_crit_);
825 if (options_.cpu_overuse_detection) {
826 signal_cpu_adaptation_ = *options_.cpu_overuse_detection;
827 }
828 }
829 rtc::DiffServCodePoint dscp =
830 options_.dscp.value_or(false) ? rtc::DSCP_AF41 : rtc::DSCP_DEFAULT;
831 MediaChannel::SetDscp(dscp);
832 }
833
834 {
835 rtc::CritScope stream_lock(&stream_crit_);
836 for (auto& kv : send_streams_) {
837 kv.second->SetSendParameters(changed_params);
838 }
839 if (changed_params.codec) {
840 // Update receive feedback parameters from new codec.
841 LOG(LS_INFO)
842 << "SetFeedbackOptions on all the receive streams because the send "
843 "codec has changed.";
844 for (auto& kv : receive_streams_) {
845 RTC_DCHECK(kv.second != nullptr);
846 kv.second->SetFeedbackParameters(HasNack(send_codec_->codec),
847 HasRemb(send_codec_->codec),
848 HasTransportCc(send_codec_->codec));
849 }
850 }
851 }
852 send_params_ = params;
853 return true;
854 }
855
856 bool WebRtcVideoChannel2::GetChangedRecvParameters(
857 const VideoRecvParameters& params,
858 ChangedRecvParameters* changed_params) const {
859 if (!ValidateCodecFormats(params.codecs) ||
860 !ValidateRtpExtensions(params.extensions)) {
861 return false;
862 }
863
864 // Handle receive codecs.
865 const std::vector<VideoCodecSettings> mapped_codecs =
866 MapCodecs(params.codecs);
867 if (mapped_codecs.empty()) {
868 LOG(LS_ERROR) << "SetRecvParameters called without any video codecs.";
869 return false;
870 }
871
872 std::vector<VideoCodecSettings> supported_codecs =
873 FilterSupportedCodecs(mapped_codecs);
874
875 if (mapped_codecs.size() != supported_codecs.size()) {
876 LOG(LS_ERROR) << "SetRecvParameters called with unsupported video codecs.";
877 return false;
878 }
879
880 if (ReceiveCodecsHaveChanged(recv_codecs_, supported_codecs)) {
881 changed_params->codec_settings =
882 rtc::Optional<std::vector<VideoCodecSettings>>(supported_codecs);
883 }
884
885 // Handle RTP header extensions.
886 std::vector<webrtc::RtpExtension> filtered_extensions = FilterRtpExtensions(
887 params.extensions, webrtc::RtpExtension::IsSupportedForVideo, false);
888 if (filtered_extensions != recv_rtp_extensions_) {
889 changed_params->rtp_header_extensions =
890 rtc::Optional<std::vector<webrtc::RtpExtension>>(filtered_extensions);
891 }
892
893 // Handle RTCP mode.
894 if (params.rtcp.reduced_size != recv_params_.rtcp.reduced_size) {
895 changed_params->rtcp_mode = rtc::Optional<webrtc::RtcpMode>(
896 params.rtcp.reduced_size ? webrtc::RtcpMode::kReducedSize
897 : webrtc::RtcpMode::kCompound);
898 }
899
900 return true;
901 }
902
903 bool WebRtcVideoChannel2::SetRecvParameters(const VideoRecvParameters& params) {
904 TRACE_EVENT0("webrtc", "WebRtcVideoChannel2::SetRecvParameters");
905 LOG(LS_INFO) << "SetRecvParameters: " << params.ToString();
906 ChangedRecvParameters changed_params;
907 if (!GetChangedRecvParameters(params, &changed_params)) {
908 return false;
909 }
910 if (changed_params.rtp_header_extensions) {
911 recv_rtp_extensions_ = *changed_params.rtp_header_extensions;
912 }
913 if (changed_params.codec_settings) {
914 LOG(LS_INFO) << "Changing recv codecs from "
915 << CodecSettingsVectorToString(recv_codecs_) << " to "
916 << CodecSettingsVectorToString(*changed_params.codec_settings);
917 recv_codecs_ = *changed_params.codec_settings;
918 }
919
920 {
921 rtc::CritScope stream_lock(&stream_crit_);
922 for (auto& kv : receive_streams_) {
923 kv.second->SetRecvParameters(changed_params);
924 }
925 }
926 recv_params_ = params;
927 return true;
928 }
929
930 std::string WebRtcVideoChannel2::CodecSettingsVectorToString(
931 const std::vector<VideoCodecSettings>& codecs) {
932 std::stringstream out;
933 out << '{';
934 for (size_t i = 0; i < codecs.size(); ++i) {
935 out << codecs[i].codec.ToString();
936 if (i != codecs.size() - 1) {
937 out << ", ";
938 }
939 }
940 out << '}';
941 return out.str();
942 }
943
944 bool WebRtcVideoChannel2::GetSendCodec(VideoCodec* codec) {
945 if (!send_codec_) {
946 LOG(LS_VERBOSE) << "GetSendCodec: No send codec set.";
947 return false;
948 }
949 *codec = send_codec_->codec;
950 return true;
951 }
952
953 bool WebRtcVideoChannel2::SetSend(bool send) {
954 LOG(LS_VERBOSE) << "SetSend: " << (send ? "true" : "false");
955 if (send && !send_codec_) {
956 LOG(LS_ERROR) << "SetSend(true) called before setting codec.";
957 return false;
958 }
959 if (send) {
960 StartAllSendStreams();
961 } else {
962 StopAllSendStreams();
963 }
964 sending_ = send;
965 return true;
966 }
967
968 bool WebRtcVideoChannel2::SetVideoSend(uint32_t ssrc, bool enable,
969 const VideoOptions* options) {
970 TRACE_EVENT0("webrtc", "SetVideoSend");
971 LOG(LS_INFO) << "SetVideoSend (ssrc= " << ssrc << ", enable = " << enable
972 << "options: " << (options ? options->ToString() : "nullptr")
973 << ").";
974
975 // TODO(solenberg): The state change should be fully rolled back if any one of
976 // these calls fail.
977 if (!MuteStream(ssrc, !enable)) {
978 return false;
979 }
980 if (enable && options) {
981 VideoSendParameters new_params = send_params_;
982 new_params.options.SetAll(*options);
983 SetSendParameters(send_params_);
984 }
985 return true;
986 }
987
988 bool WebRtcVideoChannel2::ValidateSendSsrcAvailability(
989 const StreamParams& sp) const {
990 for (uint32_t ssrc: sp.ssrcs) {
991 if (send_ssrcs_.find(ssrc) != send_ssrcs_.end()) {
992 LOG(LS_ERROR) << "Send stream with SSRC '" << ssrc << "' already exists.";
993 return false;
994 }
995 }
996 return true;
997 }
998
999 bool WebRtcVideoChannel2::ValidateReceiveSsrcAvailability(
1000 const StreamParams& sp) const {
1001 for (uint32_t ssrc: sp.ssrcs) {
1002 if (receive_ssrcs_.find(ssrc) != receive_ssrcs_.end()) {
1003 LOG(LS_ERROR) << "Receive stream with SSRC '" << ssrc
1004 << "' already exists.";
1005 return false;
1006 }
1007 }
1008 return true;
1009 }
1010
1011 bool WebRtcVideoChannel2::AddSendStream(const StreamParams& sp) {
1012 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
1013 if (!ValidateStreamParams(sp))
1014 return false;
1015
1016 rtc::CritScope stream_lock(&stream_crit_);
1017
1018 if (!ValidateSendSsrcAvailability(sp))
1019 return false;
1020
1021 for (uint32_t used_ssrc : sp.ssrcs)
1022 send_ssrcs_.insert(used_ssrc);
1023
1024 webrtc::VideoSendStream::Config config(this);
1025 config.overuse_callback = this;
1026
1027 WebRtcVideoSendStream* stream = new WebRtcVideoSendStream(
1028 call_, sp, config, external_encoder_factory_, options_,
1029 bitrate_config_.max_bitrate_bps, send_codec_, send_rtp_extensions_,
1030 send_params_);
1031
1032 uint32_t ssrc = sp.first_ssrc();
1033 RTC_DCHECK(ssrc != 0);
1034 send_streams_[ssrc] = stream;
1035
1036 if (rtcp_receiver_report_ssrc_ == kDefaultRtcpReceiverReportSsrc) {
1037 rtcp_receiver_report_ssrc_ = ssrc;
1038 LOG(LS_INFO) << "SetLocalSsrc on all the receive streams because we added "
1039 "a send stream.";
1040 for (auto& kv : receive_streams_)
1041 kv.second->SetLocalSsrc(ssrc);
1042 }
1043 if (default_send_ssrc_ == 0) {
1044 default_send_ssrc_ = ssrc;
1045 }
1046 if (sending_) {
1047 stream->Start();
1048 }
1049
1050 return true;
1051 }
1052
1053 bool WebRtcVideoChannel2::RemoveSendStream(uint32_t ssrc) {
1054 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
1055
1056 if (ssrc == 0) {
1057 if (default_send_ssrc_ == 0) {
1058 LOG(LS_ERROR) << "No default send stream active.";
1059 return false;
1060 }
1061
1062 LOG(LS_VERBOSE) << "Removing default stream: " << default_send_ssrc_;
1063 ssrc = default_send_ssrc_;
1064 }
1065
1066 WebRtcVideoSendStream* removed_stream;
1067 {
1068 rtc::CritScope stream_lock(&stream_crit_);
1069 std::map<uint32_t, WebRtcVideoSendStream*>::iterator it =
1070 send_streams_.find(ssrc);
1071 if (it == send_streams_.end()) {
1072 return false;
1073 }
1074
1075 for (uint32_t old_ssrc : it->second->GetSsrcs())
1076 send_ssrcs_.erase(old_ssrc);
1077
1078 removed_stream = it->second;
1079 send_streams_.erase(it);
1080
1081 // Switch receiver report SSRCs, the one in use is no longer valid.
1082 if (rtcp_receiver_report_ssrc_ == ssrc) {
1083 rtcp_receiver_report_ssrc_ = send_streams_.empty()
1084 ? kDefaultRtcpReceiverReportSsrc
1085 : send_streams_.begin()->first;
1086 LOG(LS_INFO) << "SetLocalSsrc on all the receive streams because the "
1087 "previous local SSRC was removed.";
1088
1089 for (auto& kv : receive_streams_) {
1090 kv.second->SetLocalSsrc(rtcp_receiver_report_ssrc_);
1091 }
1092 }
1093 }
1094
1095 delete removed_stream;
1096
1097 if (ssrc == default_send_ssrc_) {
1098 default_send_ssrc_ = 0;
1099 }
1100
1101 return true;
1102 }
1103
1104 void WebRtcVideoChannel2::DeleteReceiveStream(
1105 WebRtcVideoChannel2::WebRtcVideoReceiveStream* stream) {
1106 for (uint32_t old_ssrc : stream->GetSsrcs())
1107 receive_ssrcs_.erase(old_ssrc);
1108 delete stream;
1109 }
1110
1111 bool WebRtcVideoChannel2::AddRecvStream(const StreamParams& sp) {
1112 return AddRecvStream(sp, false);
1113 }
1114
1115 bool WebRtcVideoChannel2::AddRecvStream(const StreamParams& sp,
1116 bool default_stream) {
1117 RTC_DCHECK(thread_checker_.CalledOnValidThread());
1118
1119 LOG(LS_INFO) << "AddRecvStream" << (default_stream ? " (default stream)" : "")
1120 << ": " << sp.ToString();
1121 if (!ValidateStreamParams(sp))
1122 return false;
1123
1124 uint32_t ssrc = sp.first_ssrc();
1125 RTC_DCHECK(ssrc != 0); // TODO(pbos): Is this ever valid?
1126
1127 rtc::CritScope stream_lock(&stream_crit_);
1128 // Remove running stream if this was a default stream.
1129 auto prev_stream = receive_streams_.find(ssrc);
1130 if (prev_stream != receive_streams_.end()) {
1131 if (default_stream || !prev_stream->second->IsDefaultStream()) {
1132 LOG(LS_ERROR) << "Receive stream for SSRC '" << ssrc
1133 << "' already exists.";
1134 return false;
1135 }
1136 DeleteReceiveStream(prev_stream->second);
1137 receive_streams_.erase(prev_stream);
1138 }
1139
1140 if (!ValidateReceiveSsrcAvailability(sp))
1141 return false;
1142
1143 for (uint32_t used_ssrc : sp.ssrcs)
1144 receive_ssrcs_.insert(used_ssrc);
1145
1146 webrtc::VideoReceiveStream::Config config(this);
1147 ConfigureReceiverRtp(&config, sp);
1148
1149 // Set up A/V sync group based on sync label.
1150 config.sync_group = sp.sync_label;
1151
1152 config.rtp.remb = send_codec_ ? HasRemb(send_codec_->codec) : false;
1153 config.rtp.transport_cc =
1154 send_codec_ ? HasTransportCc(send_codec_->codec) : false;
1155
1156 receive_streams_[ssrc] = new WebRtcVideoReceiveStream(
1157 call_, sp, config, external_decoder_factory_, default_stream,
1158 recv_codecs_, options_.disable_prerenderer_smoothing.value_or(false));
1159
1160 return true;
1161 }
1162
1163 void WebRtcVideoChannel2::ConfigureReceiverRtp(
1164 webrtc::VideoReceiveStream::Config* config,
1165 const StreamParams& sp) const {
1166 uint32_t ssrc = sp.first_ssrc();
1167
1168 config->rtp.remote_ssrc = ssrc;
1169 config->rtp.local_ssrc = rtcp_receiver_report_ssrc_;
1170
1171 config->rtp.extensions = recv_rtp_extensions_;
1172 config->rtp.rtcp_mode = recv_params_.rtcp.reduced_size
1173 ? webrtc::RtcpMode::kReducedSize
1174 : webrtc::RtcpMode::kCompound;
1175
1176 // TODO(pbos): This protection is against setting the same local ssrc as
1177 // remote which is not permitted by the lower-level API. RTCP requires a
1178 // corresponding sender SSRC. Figure out what to do when we don't have
1179 // (receive-only) or know a good local SSRC.
1180 if (config->rtp.remote_ssrc == config->rtp.local_ssrc) {
1181 if (config->rtp.local_ssrc != kDefaultRtcpReceiverReportSsrc) {
1182 config->rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc;
1183 } else {
1184 config->rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc + 1;
1185 }
1186 }
1187
1188 for (size_t i = 0; i < recv_codecs_.size(); ++i) {
1189 MergeFecConfig(recv_codecs_[i].fec, &config->rtp.fec);
1190 }
1191
1192 for (size_t i = 0; i < recv_codecs_.size(); ++i) {
1193 uint32_t rtx_ssrc;
1194 if (recv_codecs_[i].rtx_payload_type != -1 &&
1195 sp.GetFidSsrc(ssrc, &rtx_ssrc)) {
1196 webrtc::VideoReceiveStream::Config::Rtp::Rtx& rtx =
1197 config->rtp.rtx[recv_codecs_[i].codec.id];
1198 rtx.ssrc = rtx_ssrc;
1199 rtx.payload_type = recv_codecs_[i].rtx_payload_type;
1200 }
1201 }
1202 }
1203
1204 bool WebRtcVideoChannel2::RemoveRecvStream(uint32_t ssrc) {
1205 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
1206 if (ssrc == 0) {
1207 LOG(LS_ERROR) << "RemoveRecvStream with 0 ssrc is not supported.";
1208 return false;
1209 }
1210
1211 rtc::CritScope stream_lock(&stream_crit_);
1212 std::map<uint32_t, WebRtcVideoReceiveStream*>::iterator stream =
1213 receive_streams_.find(ssrc);
1214 if (stream == receive_streams_.end()) {
1215 LOG(LS_ERROR) << "Stream not found for ssrc: " << ssrc;
1216 return false;
1217 }
1218 DeleteReceiveStream(stream->second);
1219 receive_streams_.erase(stream);
1220
1221 return true;
1222 }
1223
1224 bool WebRtcVideoChannel2::SetSink(uint32_t ssrc,
1225 rtc::VideoSinkInterface<VideoFrame>* sink) {
1226 LOG(LS_INFO) << "SetSink: ssrc:" << ssrc << " " << (sink ? "(ptr)" : "NULL");
1227 if (ssrc == 0) {
1228 default_unsignalled_ssrc_handler_.SetDefaultSink(this, sink);
1229 return true;
1230 }
1231
1232 rtc::CritScope stream_lock(&stream_crit_);
1233 std::map<uint32_t, WebRtcVideoReceiveStream*>::iterator it =
1234 receive_streams_.find(ssrc);
1235 if (it == receive_streams_.end()) {
1236 return false;
1237 }
1238
1239 it->second->SetSink(sink);
1240 return true;
1241 }
1242
1243 bool WebRtcVideoChannel2::GetStats(VideoMediaInfo* info) {
1244 info->Clear();
1245 FillSenderStats(info);
1246 FillReceiverStats(info);
1247 webrtc::Call::Stats stats = call_->GetStats();
1248 FillBandwidthEstimationStats(stats, info);
1249 if (stats.rtt_ms != -1) {
1250 for (size_t i = 0; i < info->senders.size(); ++i) {
1251 info->senders[i].rtt_ms = stats.rtt_ms;
1252 }
1253 }
1254 return true;
1255 }
1256
1257 void WebRtcVideoChannel2::FillSenderStats(VideoMediaInfo* video_media_info) {
1258 rtc::CritScope stream_lock(&stream_crit_);
1259 for (std::map<uint32_t, WebRtcVideoSendStream*>::iterator it =
1260 send_streams_.begin();
1261 it != send_streams_.end(); ++it) {
1262 video_media_info->senders.push_back(it->second->GetVideoSenderInfo());
1263 }
1264 }
1265
1266 void WebRtcVideoChannel2::FillReceiverStats(VideoMediaInfo* video_media_info) {
1267 rtc::CritScope stream_lock(&stream_crit_);
1268 for (std::map<uint32_t, WebRtcVideoReceiveStream*>::iterator it =
1269 receive_streams_.begin();
1270 it != receive_streams_.end(); ++it) {
1271 video_media_info->receivers.push_back(it->second->GetVideoReceiverInfo());
1272 }
1273 }
1274
1275 void WebRtcVideoChannel2::FillBandwidthEstimationStats(
1276 const webrtc::Call::Stats& stats,
1277 VideoMediaInfo* video_media_info) {
1278 BandwidthEstimationInfo bwe_info;
1279 bwe_info.available_send_bandwidth = stats.send_bandwidth_bps;
1280 bwe_info.available_recv_bandwidth = stats.recv_bandwidth_bps;
1281 bwe_info.bucket_delay = stats.pacer_delay_ms;
1282
1283 // Get send stream bitrate stats.
1284 rtc::CritScope stream_lock(&stream_crit_);
1285 for (std::map<uint32_t, WebRtcVideoSendStream*>::iterator stream =
1286 send_streams_.begin();
1287 stream != send_streams_.end(); ++stream) {
1288 stream->second->FillBandwidthEstimationInfo(&bwe_info);
1289 }
1290 video_media_info->bw_estimations.push_back(bwe_info);
1291 }
1292
1293 bool WebRtcVideoChannel2::SetCapturer(uint32_t ssrc, VideoCapturer* capturer) {
1294 LOG(LS_INFO) << "SetCapturer: " << ssrc << " -> "
1295 << (capturer != NULL ? "(capturer)" : "NULL");
1296 RTC_DCHECK(ssrc != 0);
1297 {
1298 rtc::CritScope stream_lock(&stream_crit_);
1299 if (send_streams_.find(ssrc) == send_streams_.end()) {
1300 LOG(LS_ERROR) << "No sending stream on ssrc " << ssrc;
1301 return false;
1302 }
1303 if (!send_streams_[ssrc]->SetCapturer(capturer)) {
1304 return false;
1305 }
1306 }
1307
1308 if (capturer) {
1309 capturer->SetApplyRotation(!ContainsHeaderExtension(
1310 send_rtp_extensions_, kRtpVideoRotationHeaderExtension));
1311 }
1312 {
1313 rtc::CritScope lock(&capturer_crit_);
1314 capturers_[ssrc] = capturer;
1315 }
1316 return true;
1317 }
1318
1319 void WebRtcVideoChannel2::OnPacketReceived(
1320 rtc::Buffer* packet,
1321 const rtc::PacketTime& packet_time) {
1322 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
1323 packet_time.not_before);
1324 const webrtc::PacketReceiver::DeliveryStatus delivery_result =
1325 call_->Receiver()->DeliverPacket(
1326 webrtc::MediaType::VIDEO,
1327 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
1328 webrtc_packet_time);
1329 switch (delivery_result) {
1330 case webrtc::PacketReceiver::DELIVERY_OK:
1331 return;
1332 case webrtc::PacketReceiver::DELIVERY_PACKET_ERROR:
1333 return;
1334 case webrtc::PacketReceiver::DELIVERY_UNKNOWN_SSRC:
1335 break;
1336 }
1337
1338 uint32_t ssrc = 0;
1339 if (!GetRtpSsrc(packet->data(), packet->size(), &ssrc)) {
1340 return;
1341 }
1342
1343 int payload_type = 0;
1344 if (!GetRtpPayloadType(packet->data(), packet->size(), &payload_type)) {
1345 return;
1346 }
1347
1348 // See if this payload_type is registered as one that usually gets its own
1349 // SSRC (RTX) or at least is safe to drop either way (ULPFEC). If it is, and
1350 // it wasn't handled above by DeliverPacket, that means we don't know what
1351 // stream it associates with, and we shouldn't ever create an implicit channel
1352 // for these.
1353 for (auto& codec : recv_codecs_) {
1354 if (payload_type == codec.rtx_payload_type ||
1355 payload_type == codec.fec.red_rtx_payload_type ||
1356 payload_type == codec.fec.ulpfec_payload_type) {
1357 return;
1358 }
1359 }
1360
1361 switch (unsignalled_ssrc_handler_->OnUnsignalledSsrc(this, ssrc)) {
1362 case UnsignalledSsrcHandler::kDropPacket:
1363 return;
1364 case UnsignalledSsrcHandler::kDeliverPacket:
1365 break;
1366 }
1367
1368 if (call_->Receiver()->DeliverPacket(
1369 webrtc::MediaType::VIDEO,
1370 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
1371 webrtc_packet_time) != webrtc::PacketReceiver::DELIVERY_OK) {
1372 LOG(LS_WARNING) << "Failed to deliver RTP packet on re-delivery.";
1373 return;
1374 }
1375 }
1376
1377 void WebRtcVideoChannel2::OnRtcpReceived(
1378 rtc::Buffer* packet,
1379 const rtc::PacketTime& packet_time) {
1380 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
1381 packet_time.not_before);
1382 // TODO(pbos): Check webrtc::PacketReceiver::DELIVERY_OK once we deliver
1383 // for both audio and video on the same path. Since BundleFilter doesn't
1384 // filter RTCP anymore incoming RTCP packets could've been going to audio (so
1385 // logging failures spam the log).
1386 call_->Receiver()->DeliverPacket(
1387 webrtc::MediaType::VIDEO,
1388 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
1389 webrtc_packet_time);
1390 }
1391
1392 void WebRtcVideoChannel2::OnReadyToSend(bool ready) {
1393 LOG(LS_VERBOSE) << "OnReadyToSend: " << (ready ? "Ready." : "Not ready.");
1394 call_->SignalNetworkState(ready ? webrtc::kNetworkUp : webrtc::kNetworkDown);
1395 }
1396
1397 bool WebRtcVideoChannel2::MuteStream(uint32_t ssrc, bool mute) {
1398 LOG(LS_VERBOSE) << "MuteStream: " << ssrc << " -> "
1399 << (mute ? "mute" : "unmute");
1400 RTC_DCHECK(ssrc != 0);
1401 rtc::CritScope stream_lock(&stream_crit_);
1402 if (send_streams_.find(ssrc) == send_streams_.end()) {
1403 LOG(LS_ERROR) << "No sending stream on ssrc " << ssrc;
1404 return false;
1405 }
1406
1407 send_streams_[ssrc]->MuteStream(mute);
1408 return true;
1409 }
1410
1411 // TODO(pbos): Remove SetOptions in favor of SetSendParameters.
1412 void WebRtcVideoChannel2::SetOptions(const VideoOptions& options) {
1413 VideoSendParameters new_params = send_params_;
1414 new_params.options.SetAll(options);
1415 SetSendParameters(send_params_);
1416 }
1417
1418 void WebRtcVideoChannel2::SetInterface(NetworkInterface* iface) {
1419 MediaChannel::SetInterface(iface);
1420 // Set the RTP recv/send buffer to a bigger size
1421 MediaChannel::SetOption(NetworkInterface::ST_RTP,
1422 rtc::Socket::OPT_RCVBUF,
1423 kVideoRtpBufferSize);
1424
1425 // Speculative change to increase the outbound socket buffer size.
1426 // In b/15152257, we are seeing a significant number of packets discarded
1427 // due to lack of socket buffer space, although it's not yet clear what the
1428 // ideal value should be.
1429 MediaChannel::SetOption(NetworkInterface::ST_RTP,
1430 rtc::Socket::OPT_SNDBUF,
1431 kVideoRtpBufferSize);
1432 }
1433
1434 void WebRtcVideoChannel2::OnLoadUpdate(Load load) {
1435 // OnLoadUpdate can not take any locks that are held while creating streams
1436 // etc. Doing so establishes lock-order inversions between the webrtc process
1437 // thread on stream creation and locks such as stream_crit_ while calling out.
1438 rtc::CritScope stream_lock(&capturer_crit_);
1439 if (!signal_cpu_adaptation_)
1440 return;
1441 // Do not adapt resolution for screen content as this will likely result in
1442 // blurry and unreadable text.
1443 for (auto& kv : capturers_) {
1444 if (kv.second != nullptr
1445 && !kv.second->IsScreencast()
1446 && kv.second->video_adapter() != nullptr) {
1447 kv.second->video_adapter()->OnCpuResolutionRequest(
1448 load == kOveruse ? CoordinatedVideoAdapter::DOWNGRADE
1449 : CoordinatedVideoAdapter::UPGRADE);
1450 }
1451 }
1452 }
1453
1454 bool WebRtcVideoChannel2::SendRtp(const uint8_t* data,
1455 size_t len,
1456 const webrtc::PacketOptions& options) {
1457 rtc::Buffer packet(data, len, kMaxRtpPacketLen);
1458 rtc::PacketOptions rtc_options;
1459 rtc_options.packet_id = options.packet_id;
1460 return MediaChannel::SendPacket(&packet, rtc_options);
1461 }
1462
1463 bool WebRtcVideoChannel2::SendRtcp(const uint8_t* data, size_t len) {
1464 rtc::Buffer packet(data, len, kMaxRtpPacketLen);
1465 return MediaChannel::SendRtcp(&packet, rtc::PacketOptions());
1466 }
1467
1468 void WebRtcVideoChannel2::StartAllSendStreams() {
1469 rtc::CritScope stream_lock(&stream_crit_);
1470 for (std::map<uint32_t, WebRtcVideoSendStream*>::iterator it =
1471 send_streams_.begin();
1472 it != send_streams_.end(); ++it) {
1473 it->second->Start();
1474 }
1475 }
1476
1477 void WebRtcVideoChannel2::StopAllSendStreams() {
1478 rtc::CritScope stream_lock(&stream_crit_);
1479 for (std::map<uint32_t, WebRtcVideoSendStream*>::iterator it =
1480 send_streams_.begin();
1481 it != send_streams_.end(); ++it) {
1482 it->second->Stop();
1483 }
1484 }
1485
1486 WebRtcVideoChannel2::WebRtcVideoSendStream::VideoSendStreamParameters::
1487 VideoSendStreamParameters(
1488 const webrtc::VideoSendStream::Config& config,
1489 const VideoOptions& options,
1490 int max_bitrate_bps,
1491 const rtc::Optional<VideoCodecSettings>& codec_settings)
1492 : config(config),
1493 options(options),
1494 max_bitrate_bps(max_bitrate_bps),
1495 codec_settings(codec_settings) {}
1496
1497 WebRtcVideoChannel2::WebRtcVideoSendStream::AllocatedEncoder::AllocatedEncoder(
1498 webrtc::VideoEncoder* encoder,
1499 webrtc::VideoCodecType type,
1500 bool external)
1501 : encoder(encoder),
1502 external_encoder(nullptr),
1503 type(type),
1504 external(external) {
1505 if (external) {
1506 external_encoder = encoder;
1507 this->encoder =
1508 new webrtc::VideoEncoderSoftwareFallbackWrapper(type, encoder);
1509 }
1510 }
1511
1512 WebRtcVideoChannel2::WebRtcVideoSendStream::WebRtcVideoSendStream(
1513 webrtc::Call* call,
1514 const StreamParams& sp,
1515 const webrtc::VideoSendStream::Config& config,
1516 WebRtcVideoEncoderFactory* external_encoder_factory,
1517 const VideoOptions& options,
1518 int max_bitrate_bps,
1519 const rtc::Optional<VideoCodecSettings>& codec_settings,
1520 const std::vector<webrtc::RtpExtension>& rtp_extensions,
1521 // TODO(deadbeef): Don't duplicate information between send_params,
1522 // rtp_extensions, options, etc.
1523 const VideoSendParameters& send_params)
1524 : ssrcs_(sp.ssrcs),
1525 ssrc_groups_(sp.ssrc_groups),
1526 call_(call),
1527 external_encoder_factory_(external_encoder_factory),
1528 stream_(NULL),
1529 parameters_(config, options, max_bitrate_bps, codec_settings),
1530 pending_encoder_reconfiguration_(false),
1531 allocated_encoder_(NULL, webrtc::kVideoCodecUnknown, false),
1532 capturer_(NULL),
1533 sending_(false),
1534 muted_(false),
1535 old_adapt_changes_(0),
1536 first_frame_timestamp_ms_(0),
1537 last_frame_timestamp_ms_(0) {
1538 parameters_.config.rtp.max_packet_size = kVideoMtu;
1539
1540 sp.GetPrimarySsrcs(&parameters_.config.rtp.ssrcs);
1541 sp.GetFidSsrcs(parameters_.config.rtp.ssrcs,
1542 &parameters_.config.rtp.rtx.ssrcs);
1543 parameters_.config.rtp.c_name = sp.cname;
1544 parameters_.config.rtp.extensions = rtp_extensions;
1545 parameters_.config.rtp.rtcp_mode = send_params.rtcp.reduced_size
1546 ? webrtc::RtcpMode::kReducedSize
1547 : webrtc::RtcpMode::kCompound;
1548
1549 if (codec_settings) {
1550 SetCodecAndOptions(*codec_settings, parameters_.options);
1551 }
1552 }
1553
1554 WebRtcVideoChannel2::WebRtcVideoSendStream::~WebRtcVideoSendStream() {
1555 DisconnectCapturer();
1556 if (stream_ != NULL) {
1557 call_->DestroyVideoSendStream(stream_);
1558 }
1559 DestroyVideoEncoder(&allocated_encoder_);
1560 }
1561
1562 static void CreateBlackFrame(webrtc::VideoFrame* video_frame,
1563 int width,
1564 int height) {
1565 video_frame->CreateEmptyFrame(width, height, width, (width + 1) / 2,
1566 (width + 1) / 2);
1567 memset(video_frame->buffer(webrtc::kYPlane), 16,
1568 video_frame->allocated_size(webrtc::kYPlane));
1569 memset(video_frame->buffer(webrtc::kUPlane), 128,
1570 video_frame->allocated_size(webrtc::kUPlane));
1571 memset(video_frame->buffer(webrtc::kVPlane), 128,
1572 video_frame->allocated_size(webrtc::kVPlane));
1573 }
1574
1575 void WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame(
1576 VideoCapturer* capturer,
1577 const VideoFrame* frame) {
1578 TRACE_EVENT0("webrtc", "WebRtcVideoSendStream::InputFrame");
1579 webrtc::VideoFrame video_frame(frame->GetVideoFrameBuffer(), 0, 0,
1580 frame->GetVideoRotation());
1581 rtc::CritScope cs(&lock_);
1582 if (stream_ == NULL) {
1583 // Frame input before send codecs are configured, dropping frame.
1584 return;
1585 }
1586
1587 // Not sending, abort early to prevent expensive reconfigurations while
1588 // setting up codecs etc.
1589 if (!sending_)
1590 return;
1591
1592 if (format_.width == 0) { // Dropping frames.
1593 RTC_DCHECK(format_.height == 0);
1594 LOG(LS_VERBOSE) << "VideoFormat 0x0 set, Dropping frame.";
1595 return;
1596 }
1597 if (muted_) {
1598 // Create a black frame to transmit instead.
1599 CreateBlackFrame(&video_frame,
1600 static_cast<int>(frame->GetWidth()),
1601 static_cast<int>(frame->GetHeight()));
1602 }
1603
1604 int64_t frame_delta_ms = frame->GetTimeStamp() / rtc::kNumNanosecsPerMillisec;
1605 // frame->GetTimeStamp() is essentially a delta, align to webrtc time
1606 if (first_frame_timestamp_ms_ == 0) {
1607 first_frame_timestamp_ms_ = rtc::Time() - frame_delta_ms;
1608 }
1609
1610 last_frame_timestamp_ms_ = first_frame_timestamp_ms_ + frame_delta_ms;
1611 video_frame.set_render_time_ms(last_frame_timestamp_ms_);
1612 // Reconfigure codec if necessary.
1613 SetDimensions(
1614 video_frame.width(), video_frame.height(), capturer->IsScreencast());
1615
1616 stream_->Input()->IncomingCapturedFrame(video_frame);
1617 }
1618
1619 bool WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer(
1620 VideoCapturer* capturer) {
1621 TRACE_EVENT0("webrtc", "WebRtcVideoSendStream::SetCapturer");
1622 if (!DisconnectCapturer() && capturer == NULL) {
1623 return false;
1624 }
1625
1626 {
1627 rtc::CritScope cs(&lock_);
1628
1629 // Reset timestamps to realign new incoming frames to a webrtc timestamp. A
1630 // new capturer may have a different timestamp delta than the previous one.
1631 first_frame_timestamp_ms_ = 0;
1632
1633 if (capturer == NULL) {
1634 if (stream_ != NULL) {
1635 LOG(LS_VERBOSE) << "Disabling capturer, sending black frame.";
1636 webrtc::VideoFrame black_frame;
1637
1638 CreateBlackFrame(&black_frame, last_dimensions_.width,
1639 last_dimensions_.height);
1640
1641 // Force this black frame not to be dropped due to timestamp order
1642 // check. As IncomingCapturedFrame will drop the frame if this frame's
1643 // timestamp is less than or equal to last frame's timestamp, it is
1644 // necessary to give this black frame a larger timestamp than the
1645 // previous one.
1646 last_frame_timestamp_ms_ +=
1647 format_.interval / rtc::kNumNanosecsPerMillisec;
1648 black_frame.set_render_time_ms(last_frame_timestamp_ms_);
1649 stream_->Input()->IncomingCapturedFrame(black_frame);
1650 }
1651
1652 capturer_ = NULL;
1653 return true;
1654 }
1655
1656 capturer_ = capturer;
1657 }
1658 // Lock cannot be held while connecting the capturer to prevent lock-order
1659 // violations.
1660 capturer->SignalVideoFrame.connect(this, &WebRtcVideoSendStream::InputFrame);
1661 return true;
1662 }
1663
1664 void WebRtcVideoChannel2::WebRtcVideoSendStream::MuteStream(bool mute) {
1665 rtc::CritScope cs(&lock_);
1666 muted_ = mute;
1667 }
1668
1669 bool WebRtcVideoChannel2::WebRtcVideoSendStream::DisconnectCapturer() {
1670 cricket::VideoCapturer* capturer;
1671 {
1672 rtc::CritScope cs(&lock_);
1673 if (capturer_ == NULL)
1674 return false;
1675
1676 if (capturer_->video_adapter() != nullptr)
1677 old_adapt_changes_ += capturer_->video_adapter()->adaptation_changes();
1678
1679 capturer = capturer_;
1680 capturer_ = NULL;
1681 }
1682 capturer->SignalVideoFrame.disconnect(this);
1683 return true;
1684 }
1685
1686 const std::vector<uint32_t>&
1687 WebRtcVideoChannel2::WebRtcVideoSendStream::GetSsrcs() const {
1688 return ssrcs_;
1689 }
1690
1691 void WebRtcVideoChannel2::WebRtcVideoSendStream::SetOptions(
1692 const VideoOptions& options) {
1693 rtc::CritScope cs(&lock_);
1694 if (parameters_.codec_settings) {
1695 LOG(LS_INFO) << "SetCodecAndOptions because of SetOptions; options="
1696 << options.ToString();
1697 SetCodecAndOptions(*parameters_.codec_settings, options);
1698 } else {
1699 parameters_.options = options;
1700 }
1701 }
1702
1703 webrtc::VideoCodecType CodecTypeFromName(const std::string& name) {
1704 if (CodecNamesEq(name, kVp8CodecName)) {
1705 return webrtc::kVideoCodecVP8;
1706 } else if (CodecNamesEq(name, kVp9CodecName)) {
1707 return webrtc::kVideoCodecVP9;
1708 } else if (CodecNamesEq(name, kH264CodecName)) {
1709 return webrtc::kVideoCodecH264;
1710 }
1711 return webrtc::kVideoCodecUnknown;
1712 }
1713
1714 WebRtcVideoChannel2::WebRtcVideoSendStream::AllocatedEncoder
1715 WebRtcVideoChannel2::WebRtcVideoSendStream::CreateVideoEncoder(
1716 const VideoCodec& codec) {
1717 webrtc::VideoCodecType type = CodecTypeFromName(codec.name);
1718
1719 // Do not re-create encoders of the same type.
1720 if (type == allocated_encoder_.type && allocated_encoder_.encoder != NULL) {
1721 return allocated_encoder_;
1722 }
1723
1724 if (external_encoder_factory_ != NULL) {
1725 webrtc::VideoEncoder* encoder =
1726 external_encoder_factory_->CreateVideoEncoder(type);
1727 if (encoder != NULL) {
1728 return AllocatedEncoder(encoder, type, true);
1729 }
1730 }
1731
1732 if (type == webrtc::kVideoCodecVP8) {
1733 return AllocatedEncoder(
1734 webrtc::VideoEncoder::Create(webrtc::VideoEncoder::kVp8), type, false);
1735 } else if (type == webrtc::kVideoCodecVP9) {
1736 return AllocatedEncoder(
1737 webrtc::VideoEncoder::Create(webrtc::VideoEncoder::kVp9), type, false);
1738 } else if (type == webrtc::kVideoCodecH264) {
1739 return AllocatedEncoder(
1740 webrtc::VideoEncoder::Create(webrtc::VideoEncoder::kH264), type, false);
1741 }
1742
1743 // This shouldn't happen, we should not be trying to create something we don't
1744 // support.
1745 RTC_DCHECK(false);
1746 return AllocatedEncoder(NULL, webrtc::kVideoCodecUnknown, false);
1747 }
1748
1749 void WebRtcVideoChannel2::WebRtcVideoSendStream::DestroyVideoEncoder(
1750 AllocatedEncoder* encoder) {
1751 if (encoder->external) {
1752 external_encoder_factory_->DestroyVideoEncoder(encoder->external_encoder);
1753 }
1754 delete encoder->encoder;
1755 }
1756
1757 void WebRtcVideoChannel2::WebRtcVideoSendStream::SetCodecAndOptions(
1758 const VideoCodecSettings& codec_settings,
1759 const VideoOptions& options) {
1760 parameters_.encoder_config =
1761 CreateVideoEncoderConfig(last_dimensions_, codec_settings.codec);
1762 RTC_DCHECK(!parameters_.encoder_config.streams.empty());
1763
1764 format_ = VideoFormat(codec_settings.codec.width,
1765 codec_settings.codec.height,
1766 VideoFormat::FpsToInterval(30),
1767 FOURCC_I420);
1768
1769 AllocatedEncoder new_encoder = CreateVideoEncoder(codec_settings.codec);
1770 parameters_.config.encoder_settings.encoder = new_encoder.encoder;
1771 parameters_.config.encoder_settings.payload_name = codec_settings.codec.name;
1772 parameters_.config.encoder_settings.payload_type = codec_settings.codec.id;
1773 if (new_encoder.external) {
1774 webrtc::VideoCodecType type = CodecTypeFromName(codec_settings.codec.name);
1775 parameters_.config.encoder_settings.internal_source =
1776 external_encoder_factory_->EncoderTypeHasInternalSource(type);
1777 }
1778 parameters_.config.rtp.fec = codec_settings.fec;
1779
1780 // Set RTX payload type if RTX is enabled.
1781 if (!parameters_.config.rtp.rtx.ssrcs.empty()) {
1782 if (codec_settings.rtx_payload_type == -1) {
1783 LOG(LS_WARNING) << "RTX SSRCs configured but there's no configured RTX "
1784 "payload type. Ignoring.";
1785 parameters_.config.rtp.rtx.ssrcs.clear();
1786 } else {
1787 parameters_.config.rtp.rtx.payload_type = codec_settings.rtx_payload_type;
1788 }
1789 }
1790
1791 parameters_.config.rtp.nack.rtp_history_ms =
1792 HasNack(codec_settings.codec) ? kNackHistoryMs : 0;
1793
1794 RTC_CHECK(options.suspend_below_min_bitrate);
1795 parameters_.config.suspend_below_min_bitrate =
1796 *options.suspend_below_min_bitrate;
1797
1798 parameters_.codec_settings =
1799 rtc::Optional<WebRtcVideoChannel2::VideoCodecSettings>(codec_settings);
1800 parameters_.options = options;
1801
1802 LOG(LS_INFO)
1803 << "RecreateWebRtcStream (send) because of SetCodecAndOptions; options="
1804 << options.ToString();
1805 RecreateWebRtcStream();
1806 if (allocated_encoder_.encoder != new_encoder.encoder) {
1807 DestroyVideoEncoder(&allocated_encoder_);
1808 allocated_encoder_ = new_encoder;
1809 }
1810 }
1811
1812 void WebRtcVideoChannel2::WebRtcVideoSendStream::SetSendParameters(
1813 const ChangedSendParameters& params) {
1814 rtc::CritScope cs(&lock_);
1815 // |recreate_stream| means construction-time parameters have changed and the
1816 // sending stream needs to be reset with the new config.
1817 bool recreate_stream = false;
1818 if (params.rtcp_mode) {
1819 parameters_.config.rtp.rtcp_mode = *params.rtcp_mode;
1820 recreate_stream = true;
1821 }
1822 if (params.rtp_header_extensions) {
1823 parameters_.config.rtp.extensions = *params.rtp_header_extensions;
1824 if (capturer_) {
1825 capturer_->SetApplyRotation(!ContainsHeaderExtension(
1826 *params.rtp_header_extensions, kRtpVideoRotationHeaderExtension));
1827 }
1828 recreate_stream = true;
1829 }
1830 if (params.max_bandwidth_bps) {
1831 // Max bitrate has changed, reconfigure encoder settings on the next frame
1832 // or stream recreation.
1833 parameters_.max_bitrate_bps = *params.max_bandwidth_bps;
1834 pending_encoder_reconfiguration_ = true;
1835 }
1836 // Set codecs and options.
1837 if (params.codec) {
1838 SetCodecAndOptions(*params.codec,
1839 params.options ? *params.options : parameters_.options);
1840 return;
1841 } else if (params.options) {
1842 // Reconfigure if codecs are already set.
1843 if (parameters_.codec_settings) {
1844 SetCodecAndOptions(*parameters_.codec_settings, *params.options);
1845 return;
1846 } else {
1847 parameters_.options = *params.options;
1848 }
1849 }
1850 if (recreate_stream) {
1851 LOG(LS_INFO) << "RecreateWebRtcStream (send) because of SetSendParameters";
1852 RecreateWebRtcStream();
1853 }
1854 }
1855
1856 webrtc::VideoEncoderConfig
1857 WebRtcVideoChannel2::WebRtcVideoSendStream::CreateVideoEncoderConfig(
1858 const Dimensions& dimensions,
1859 const VideoCodec& codec) const {
1860 webrtc::VideoEncoderConfig encoder_config;
1861 if (dimensions.is_screencast) {
1862 RTC_CHECK(parameters_.options.screencast_min_bitrate_kbps);
1863 encoder_config.min_transmit_bitrate_bps =
1864 *parameters_.options.screencast_min_bitrate_kbps * 1000;
1865 encoder_config.content_type =
1866 webrtc::VideoEncoderConfig::ContentType::kScreen;
1867 } else {
1868 encoder_config.min_transmit_bitrate_bps = 0;
1869 encoder_config.content_type =
1870 webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo;
1871 }
1872
1873 // Restrict dimensions according to codec max.
1874 int width = dimensions.width;
1875 int height = dimensions.height;
1876 if (!dimensions.is_screencast) {
1877 if (codec.width < width)
1878 width = codec.width;
1879 if (codec.height < height)
1880 height = codec.height;
1881 }
1882
1883 VideoCodec clamped_codec = codec;
1884 clamped_codec.width = width;
1885 clamped_codec.height = height;
1886
1887 // By default, the stream count for the codec configuration should match the
1888 // number of negotiated ssrcs. But if the codec is blacklisted for simulcast
1889 // or a screencast, only configure a single stream.
1890 size_t stream_count = parameters_.config.rtp.ssrcs.size();
1891 if (IsCodecBlacklistedForSimulcast(codec.name) || dimensions.is_screencast) {
1892 stream_count = 1;
1893 }
1894
1895 encoder_config.streams =
1896 CreateVideoStreams(clamped_codec, parameters_.options,
1897 parameters_.max_bitrate_bps, stream_count);
1898
1899 // Conference mode screencast uses 2 temporal layers split at 100kbit.
1900 if (parameters_.options.conference_mode.value_or(false) &&
1901 dimensions.is_screencast && encoder_config.streams.size() == 1) {
1902 ScreenshareLayerConfig config = ScreenshareLayerConfig::GetDefault();
1903
1904 // For screenshare in conference mode, tl0 and tl1 bitrates are piggybacked
1905 // on the VideoCodec struct as target and max bitrates, respectively.
1906 // See eg. webrtc::VP8EncoderImpl::SetRates().
1907 encoder_config.streams[0].target_bitrate_bps =
1908 config.tl0_bitrate_kbps * 1000;
1909 encoder_config.streams[0].max_bitrate_bps = config.tl1_bitrate_kbps * 1000;
1910 encoder_config.streams[0].temporal_layer_thresholds_bps.clear();
1911 encoder_config.streams[0].temporal_layer_thresholds_bps.push_back(
1912 config.tl0_bitrate_kbps * 1000);
1913 }
1914 return encoder_config;
1915 }
1916
1917 void WebRtcVideoChannel2::WebRtcVideoSendStream::SetDimensions(
1918 int width,
1919 int height,
1920 bool is_screencast) {
1921 if (last_dimensions_.width == width && last_dimensions_.height == height &&
1922 last_dimensions_.is_screencast == is_screencast &&
1923 !pending_encoder_reconfiguration_) {
1924 // Configured using the same parameters, do not reconfigure.
1925 return;
1926 }
1927 LOG(LS_INFO) << "SetDimensions: " << width << "x" << height
1928 << (is_screencast ? " (screencast)" : " (not screencast)");
1929
1930 last_dimensions_.width = width;
1931 last_dimensions_.height = height;
1932 last_dimensions_.is_screencast = is_screencast;
1933
1934 RTC_DCHECK(!parameters_.encoder_config.streams.empty());
1935
1936 RTC_CHECK(parameters_.codec_settings);
1937 VideoCodecSettings codec_settings = *parameters_.codec_settings;
1938
1939 webrtc::VideoEncoderConfig encoder_config =
1940 CreateVideoEncoderConfig(last_dimensions_, codec_settings.codec);
1941
1942 encoder_config.encoder_specific_settings = ConfigureVideoEncoderSettings(
1943 codec_settings.codec, parameters_.options, is_screencast);
1944
1945 bool stream_reconfigured = stream_->ReconfigureVideoEncoder(encoder_config);
1946
1947 encoder_config.encoder_specific_settings = NULL;
1948 pending_encoder_reconfiguration_ = false;
1949
1950 if (!stream_reconfigured) {
1951 LOG(LS_WARNING) << "Failed to reconfigure video encoder for dimensions: "
1952 << width << "x" << height;
1953 return;
1954 }
1955
1956 parameters_.encoder_config = encoder_config;
1957 }
1958
1959 void WebRtcVideoChannel2::WebRtcVideoSendStream::Start() {
1960 rtc::CritScope cs(&lock_);
1961 RTC_DCHECK(stream_ != NULL);
1962 stream_->Start();
1963 sending_ = true;
1964 }
1965
1966 void WebRtcVideoChannel2::WebRtcVideoSendStream::Stop() {
1967 rtc::CritScope cs(&lock_);
1968 if (stream_ != NULL) {
1969 stream_->Stop();
1970 }
1971 sending_ = false;
1972 }
1973
1974 VideoSenderInfo
1975 WebRtcVideoChannel2::WebRtcVideoSendStream::GetVideoSenderInfo() {
1976 VideoSenderInfo info;
1977 webrtc::VideoSendStream::Stats stats;
1978 {
1979 rtc::CritScope cs(&lock_);
1980 for (uint32_t ssrc : parameters_.config.rtp.ssrcs)
1981 info.add_ssrc(ssrc);
1982
1983 if (parameters_.codec_settings)
1984 info.codec_name = parameters_.codec_settings->codec.name;
1985 for (size_t i = 0; i < parameters_.encoder_config.streams.size(); ++i) {
1986 if (i == parameters_.encoder_config.streams.size() - 1) {
1987 info.preferred_bitrate +=
1988 parameters_.encoder_config.streams[i].max_bitrate_bps;
1989 } else {
1990 info.preferred_bitrate +=
1991 parameters_.encoder_config.streams[i].target_bitrate_bps;
1992 }
1993 }
1994
1995 if (stream_ == NULL)
1996 return info;
1997
1998 stats = stream_->GetStats();
1999
2000 info.adapt_changes = old_adapt_changes_;
2001 info.adapt_reason = CoordinatedVideoAdapter::ADAPTREASON_NONE;
2002
2003 if (capturer_ != NULL) {
2004 if (!capturer_->IsMuted()) {
2005 VideoFormat last_captured_frame_format;
2006 capturer_->GetStats(&info.adapt_frame_drops, &info.effects_frame_drops,
2007 &info.capturer_frame_time,
2008 &last_captured_frame_format);
2009 info.input_frame_width = last_captured_frame_format.width;
2010 info.input_frame_height = last_captured_frame_format.height;
2011 }
2012 if (capturer_->video_adapter() != nullptr) {
2013 info.adapt_changes += capturer_->video_adapter()->adaptation_changes();
2014 info.adapt_reason = capturer_->video_adapter()->adapt_reason();
2015 }
2016 }
2017 }
2018
2019 // Get bandwidth limitation info from stream_->GetStats().
2020 // Input resolution (output from video_adapter) can be further scaled down or
2021 // higher video layer(s) can be dropped due to bitrate constraints.
2022 // Note, adapt_changes only include changes from the video_adapter.
2023 if (stats.bw_limited_resolution)
2024 info.adapt_reason |= CoordinatedVideoAdapter::ADAPTREASON_BANDWIDTH;
2025
2026 info.encoder_implementation_name = stats.encoder_implementation_name;
2027 info.ssrc_groups = ssrc_groups_;
2028 info.framerate_input = stats.input_frame_rate;
2029 info.framerate_sent = stats.encode_frame_rate;
2030 info.avg_encode_ms = stats.avg_encode_time_ms;
2031 info.encode_usage_percent = stats.encode_usage_percent;
2032
2033 info.nominal_bitrate = stats.media_bitrate_bps;
2034
2035 info.send_frame_width = 0;
2036 info.send_frame_height = 0;
2037 for (std::map<uint32_t, webrtc::VideoSendStream::StreamStats>::iterator it =
2038 stats.substreams.begin();
2039 it != stats.substreams.end(); ++it) {
2040 // TODO(pbos): Wire up additional stats, such as padding bytes.
2041 webrtc::VideoSendStream::StreamStats stream_stats = it->second;
2042 info.bytes_sent += stream_stats.rtp_stats.transmitted.payload_bytes +
2043 stream_stats.rtp_stats.transmitted.header_bytes +
2044 stream_stats.rtp_stats.transmitted.padding_bytes;
2045 info.packets_sent += stream_stats.rtp_stats.transmitted.packets;
2046 info.packets_lost += stream_stats.rtcp_stats.cumulative_lost;
2047 if (stream_stats.width > info.send_frame_width)
2048 info.send_frame_width = stream_stats.width;
2049 if (stream_stats.height > info.send_frame_height)
2050 info.send_frame_height = stream_stats.height;
2051 info.firs_rcvd += stream_stats.rtcp_packet_type_counts.fir_packets;
2052 info.nacks_rcvd += stream_stats.rtcp_packet_type_counts.nack_packets;
2053 info.plis_rcvd += stream_stats.rtcp_packet_type_counts.pli_packets;
2054 }
2055
2056 if (!stats.substreams.empty()) {
2057 // TODO(pbos): Report fraction lost per SSRC.
2058 webrtc::VideoSendStream::StreamStats first_stream_stats =
2059 stats.substreams.begin()->second;
2060 info.fraction_lost =
2061 static_cast<float>(first_stream_stats.rtcp_stats.fraction_lost) /
2062 (1 << 8);
2063 }
2064
2065 return info;
2066 }
2067
2068 void WebRtcVideoChannel2::WebRtcVideoSendStream::FillBandwidthEstimationInfo(
2069 BandwidthEstimationInfo* bwe_info) {
2070 rtc::CritScope cs(&lock_);
2071 if (stream_ == NULL) {
2072 return;
2073 }
2074 webrtc::VideoSendStream::Stats stats = stream_->GetStats();
2075 for (std::map<uint32_t, webrtc::VideoSendStream::StreamStats>::iterator it =
2076 stats.substreams.begin();
2077 it != stats.substreams.end(); ++it) {
2078 bwe_info->transmit_bitrate += it->second.total_bitrate_bps;
2079 bwe_info->retransmit_bitrate += it->second.retransmit_bitrate_bps;
2080 }
2081 bwe_info->target_enc_bitrate += stats.target_media_bitrate_bps;
2082 bwe_info->actual_enc_bitrate += stats.media_bitrate_bps;
2083 }
2084
2085 void WebRtcVideoChannel2::WebRtcVideoSendStream::RecreateWebRtcStream() {
2086 if (stream_ != NULL) {
2087 call_->DestroyVideoSendStream(stream_);
2088 }
2089
2090 RTC_CHECK(parameters_.codec_settings);
2091 parameters_.encoder_config.encoder_specific_settings =
2092 ConfigureVideoEncoderSettings(
2093 parameters_.codec_settings->codec, parameters_.options,
2094 parameters_.encoder_config.content_type ==
2095 webrtc::VideoEncoderConfig::ContentType::kScreen);
2096
2097 webrtc::VideoSendStream::Config config = parameters_.config;
2098 if (!config.rtp.rtx.ssrcs.empty() && config.rtp.rtx.payload_type == -1) {
2099 LOG(LS_WARNING) << "RTX SSRCs configured but there's no configured RTX "
2100 "payload type the set codec. Ignoring RTX.";
2101 config.rtp.rtx.ssrcs.clear();
2102 }
2103 stream_ = call_->CreateVideoSendStream(config, parameters_.encoder_config);
2104
2105 parameters_.encoder_config.encoder_specific_settings = NULL;
2106 pending_encoder_reconfiguration_ = false;
2107
2108 if (sending_) {
2109 stream_->Start();
2110 }
2111 }
2112
2113 WebRtcVideoChannel2::WebRtcVideoReceiveStream::WebRtcVideoReceiveStream(
2114 webrtc::Call* call,
2115 const StreamParams& sp,
2116 const webrtc::VideoReceiveStream::Config& config,
2117 WebRtcVideoDecoderFactory* external_decoder_factory,
2118 bool default_stream,
2119 const std::vector<VideoCodecSettings>& recv_codecs,
2120 bool disable_prerenderer_smoothing)
2121 : call_(call),
2122 ssrcs_(sp.ssrcs),
2123 ssrc_groups_(sp.ssrc_groups),
2124 stream_(NULL),
2125 default_stream_(default_stream),
2126 config_(config),
2127 external_decoder_factory_(external_decoder_factory),
2128 disable_prerenderer_smoothing_(disable_prerenderer_smoothing),
2129 sink_(NULL),
2130 last_width_(-1),
2131 last_height_(-1),
2132 first_frame_timestamp_(-1),
2133 estimated_remote_start_ntp_time_ms_(0) {
2134 config_.renderer = this;
2135 std::vector<AllocatedDecoder> old_decoders;
2136 ConfigureCodecs(recv_codecs, &old_decoders);
2137 RecreateWebRtcStream();
2138 RTC_DCHECK(old_decoders.empty());
2139 }
2140
2141 WebRtcVideoChannel2::WebRtcVideoReceiveStream::AllocatedDecoder::
2142 AllocatedDecoder(webrtc::VideoDecoder* decoder,
2143 webrtc::VideoCodecType type,
2144 bool external)
2145 : decoder(decoder),
2146 external_decoder(nullptr),
2147 type(type),
2148 external(external) {
2149 if (external) {
2150 external_decoder = decoder;
2151 this->decoder =
2152 new webrtc::VideoDecoderSoftwareFallbackWrapper(type, external_decoder);
2153 }
2154 }
2155
2156 WebRtcVideoChannel2::WebRtcVideoReceiveStream::~WebRtcVideoReceiveStream() {
2157 call_->DestroyVideoReceiveStream(stream_);
2158 ClearDecoders(&allocated_decoders_);
2159 }
2160
2161 const std::vector<uint32_t>&
2162 WebRtcVideoChannel2::WebRtcVideoReceiveStream::GetSsrcs() const {
2163 return ssrcs_;
2164 }
2165
2166 WebRtcVideoChannel2::WebRtcVideoReceiveStream::AllocatedDecoder
2167 WebRtcVideoChannel2::WebRtcVideoReceiveStream::CreateOrReuseVideoDecoder(
2168 std::vector<AllocatedDecoder>* old_decoders,
2169 const VideoCodec& codec) {
2170 webrtc::VideoCodecType type = CodecTypeFromName(codec.name);
2171
2172 for (size_t i = 0; i < old_decoders->size(); ++i) {
2173 if ((*old_decoders)[i].type == type) {
2174 AllocatedDecoder decoder = (*old_decoders)[i];
2175 (*old_decoders)[i] = old_decoders->back();
2176 old_decoders->pop_back();
2177 return decoder;
2178 }
2179 }
2180
2181 if (external_decoder_factory_ != NULL) {
2182 webrtc::VideoDecoder* decoder =
2183 external_decoder_factory_->CreateVideoDecoder(type);
2184 if (decoder != NULL) {
2185 return AllocatedDecoder(decoder, type, true);
2186 }
2187 }
2188
2189 if (type == webrtc::kVideoCodecVP8) {
2190 return AllocatedDecoder(
2191 webrtc::VideoDecoder::Create(webrtc::VideoDecoder::kVp8), type, false);
2192 }
2193
2194 if (type == webrtc::kVideoCodecVP9) {
2195 return AllocatedDecoder(
2196 webrtc::VideoDecoder::Create(webrtc::VideoDecoder::kVp9), type, false);
2197 }
2198
2199 if (type == webrtc::kVideoCodecH264) {
2200 return AllocatedDecoder(
2201 webrtc::VideoDecoder::Create(webrtc::VideoDecoder::kH264), type, false);
2202 }
2203
2204 return AllocatedDecoder(
2205 webrtc::VideoDecoder::Create(webrtc::VideoDecoder::kUnsupportedCodec),
2206 webrtc::kVideoCodecUnknown, false);
2207 }
2208
2209 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::ConfigureCodecs(
2210 const std::vector<VideoCodecSettings>& recv_codecs,
2211 std::vector<AllocatedDecoder>* old_decoders) {
2212 *old_decoders = allocated_decoders_;
2213 allocated_decoders_.clear();
2214 config_.decoders.clear();
2215 for (size_t i = 0; i < recv_codecs.size(); ++i) {
2216 AllocatedDecoder allocated_decoder =
2217 CreateOrReuseVideoDecoder(old_decoders, recv_codecs[i].codec);
2218 allocated_decoders_.push_back(allocated_decoder);
2219
2220 webrtc::VideoReceiveStream::Decoder decoder;
2221 decoder.decoder = allocated_decoder.decoder;
2222 decoder.payload_type = recv_codecs[i].codec.id;
2223 decoder.payload_name = recv_codecs[i].codec.name;
2224 config_.decoders.push_back(decoder);
2225 }
2226
2227 // TODO(pbos): Reconfigure RTX based on incoming recv_codecs.
2228 config_.rtp.fec = recv_codecs.front().fec;
2229 config_.rtp.nack.rtp_history_ms =
2230 HasNack(recv_codecs.begin()->codec) ? kNackHistoryMs : 0;
2231 }
2232
2233 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetLocalSsrc(
2234 uint32_t local_ssrc) {
2235 // TODO(pbos): Consider turning this sanity check into a RTC_DCHECK. You
2236 // should not be able to create a sender with the same SSRC as a receiver, but
2237 // right now this can't be done due to unittests depending on receiving what
2238 // they are sending from the same MediaChannel.
2239 if (local_ssrc == config_.rtp.remote_ssrc) {
2240 LOG(LS_INFO) << "Ignoring call to SetLocalSsrc because parameters are "
2241 "unchanged; local_ssrc=" << local_ssrc;
2242 return;
2243 }
2244
2245 config_.rtp.local_ssrc = local_ssrc;
2246 LOG(LS_INFO)
2247 << "RecreateWebRtcStream (recv) because of SetLocalSsrc; local_ssrc="
2248 << local_ssrc;
2249 RecreateWebRtcStream();
2250 }
2251
2252 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetFeedbackParameters(
2253 bool nack_enabled,
2254 bool remb_enabled,
2255 bool transport_cc_enabled) {
2256 int nack_history_ms = nack_enabled ? kNackHistoryMs : 0;
2257 if (config_.rtp.nack.rtp_history_ms == nack_history_ms &&
2258 config_.rtp.remb == remb_enabled &&
2259 config_.rtp.transport_cc == transport_cc_enabled) {
2260 LOG(LS_INFO)
2261 << "Ignoring call to SetFeedbackParameters because parameters are "
2262 "unchanged; nack="
2263 << nack_enabled << ", remb=" << remb_enabled
2264 << ", transport_cc=" << transport_cc_enabled;
2265 return;
2266 }
2267 config_.rtp.remb = remb_enabled;
2268 config_.rtp.nack.rtp_history_ms = nack_history_ms;
2269 config_.rtp.transport_cc = transport_cc_enabled;
2270 LOG(LS_INFO)
2271 << "RecreateWebRtcStream (recv) because of SetFeedbackParameters; nack="
2272 << nack_enabled << ", remb=" << remb_enabled
2273 << ", transport_cc=" << transport_cc_enabled;
2274 RecreateWebRtcStream();
2275 }
2276
2277 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetRecvParameters(
2278 const ChangedRecvParameters& params) {
2279 bool needs_recreation = false;
2280 std::vector<AllocatedDecoder> old_decoders;
2281 if (params.codec_settings) {
2282 ConfigureCodecs(*params.codec_settings, &old_decoders);
2283 needs_recreation = true;
2284 }
2285 if (params.rtp_header_extensions) {
2286 config_.rtp.extensions = *params.rtp_header_extensions;
2287 needs_recreation = true;
2288 }
2289 if (params.rtcp_mode) {
2290 config_.rtp.rtcp_mode = *params.rtcp_mode;
2291 needs_recreation = true;
2292 }
2293 if (needs_recreation) {
2294 LOG(LS_INFO) << "RecreateWebRtcStream (recv) because of SetRecvParameters";
2295 RecreateWebRtcStream();
2296 ClearDecoders(&old_decoders);
2297 }
2298 }
2299
2300 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::RecreateWebRtcStream() {
2301 if (stream_ != NULL) {
2302 call_->DestroyVideoReceiveStream(stream_);
2303 }
2304 stream_ = call_->CreateVideoReceiveStream(config_);
2305 stream_->Start();
2306 }
2307
2308 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::ClearDecoders(
2309 std::vector<AllocatedDecoder>* allocated_decoders) {
2310 for (size_t i = 0; i < allocated_decoders->size(); ++i) {
2311 if ((*allocated_decoders)[i].external) {
2312 external_decoder_factory_->DestroyVideoDecoder(
2313 (*allocated_decoders)[i].external_decoder);
2314 }
2315 delete (*allocated_decoders)[i].decoder;
2316 }
2317 allocated_decoders->clear();
2318 }
2319
2320 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::RenderFrame(
2321 const webrtc::VideoFrame& frame,
2322 int time_to_render_ms) {
2323 rtc::CritScope crit(&sink_lock_);
2324
2325 if (first_frame_timestamp_ < 0)
2326 first_frame_timestamp_ = frame.timestamp();
2327 int64_t rtp_time_elapsed_since_first_frame =
2328 (timestamp_wraparound_handler_.Unwrap(frame.timestamp()) -
2329 first_frame_timestamp_);
2330 int64_t elapsed_time_ms = rtp_time_elapsed_since_first_frame /
2331 (cricket::kVideoCodecClockrate / 1000);
2332 if (frame.ntp_time_ms() > 0)
2333 estimated_remote_start_ntp_time_ms_ = frame.ntp_time_ms() - elapsed_time_ms;
2334
2335 if (sink_ == NULL) {
2336 LOG(LS_WARNING) << "VideoReceiveStream not connected to a VideoSink.";
2337 return;
2338 }
2339
2340 last_width_ = frame.width();
2341 last_height_ = frame.height();
2342
2343 const WebRtcVideoFrame render_frame(
2344 frame.video_frame_buffer(),
2345 frame.render_time_ms() * rtc::kNumNanosecsPerMillisec, frame.rotation());
2346 sink_->OnFrame(render_frame);
2347 }
2348
2349 bool WebRtcVideoChannel2::WebRtcVideoReceiveStream::IsTextureSupported() const {
2350 return true;
2351 }
2352
2353 bool WebRtcVideoChannel2::WebRtcVideoReceiveStream::SmoothsRenderedFrames()
2354 const {
2355 return disable_prerenderer_smoothing_;
2356 }
2357
2358 bool WebRtcVideoChannel2::WebRtcVideoReceiveStream::IsDefaultStream() const {
2359 return default_stream_;
2360 }
2361
2362 void WebRtcVideoChannel2::WebRtcVideoReceiveStream::SetSink(
2363 rtc::VideoSinkInterface<cricket::VideoFrame>* sink) {
2364 rtc::CritScope crit(&sink_lock_);
2365 sink_ = sink;
2366 }
2367
2368 std::string
2369 WebRtcVideoChannel2::WebRtcVideoReceiveStream::GetCodecNameFromPayloadType(
2370 int payload_type) {
2371 for (const webrtc::VideoReceiveStream::Decoder& decoder : config_.decoders) {
2372 if (decoder.payload_type == payload_type) {
2373 return decoder.payload_name;
2374 }
2375 }
2376 return "";
2377 }
2378
2379 VideoReceiverInfo
2380 WebRtcVideoChannel2::WebRtcVideoReceiveStream::GetVideoReceiverInfo() {
2381 VideoReceiverInfo info;
2382 info.ssrc_groups = ssrc_groups_;
2383 info.add_ssrc(config_.rtp.remote_ssrc);
2384 webrtc::VideoReceiveStream::Stats stats = stream_->GetStats();
2385 info.decoder_implementation_name = stats.decoder_implementation_name;
2386 info.bytes_rcvd = stats.rtp_stats.transmitted.payload_bytes +
2387 stats.rtp_stats.transmitted.header_bytes +
2388 stats.rtp_stats.transmitted.padding_bytes;
2389 info.packets_rcvd = stats.rtp_stats.transmitted.packets;
2390 info.packets_lost = stats.rtcp_stats.cumulative_lost;
2391 info.fraction_lost =
2392 static_cast<float>(stats.rtcp_stats.fraction_lost) / (1 << 8);
2393
2394 info.framerate_rcvd = stats.network_frame_rate;
2395 info.framerate_decoded = stats.decode_frame_rate;
2396 info.framerate_output = stats.render_frame_rate;
2397
2398 {
2399 rtc::CritScope frame_cs(&sink_lock_);
2400 info.frame_width = last_width_;
2401 info.frame_height = last_height_;
2402 info.capture_start_ntp_time_ms = estimated_remote_start_ntp_time_ms_;
2403 }
2404
2405 info.decode_ms = stats.decode_ms;
2406 info.max_decode_ms = stats.max_decode_ms;
2407 info.current_delay_ms = stats.current_delay_ms;
2408 info.target_delay_ms = stats.target_delay_ms;
2409 info.jitter_buffer_ms = stats.jitter_buffer_ms;
2410 info.min_playout_delay_ms = stats.min_playout_delay_ms;
2411 info.render_delay_ms = stats.render_delay_ms;
2412
2413 info.codec_name = GetCodecNameFromPayloadType(stats.current_payload_type);
2414
2415 info.firs_sent = stats.rtcp_packet_type_counts.fir_packets;
2416 info.plis_sent = stats.rtcp_packet_type_counts.pli_packets;
2417 info.nacks_sent = stats.rtcp_packet_type_counts.nack_packets;
2418
2419 return info;
2420 }
2421
2422 WebRtcVideoChannel2::VideoCodecSettings::VideoCodecSettings()
2423 : rtx_payload_type(-1) {}
2424
2425 bool WebRtcVideoChannel2::VideoCodecSettings::operator==(
2426 const WebRtcVideoChannel2::VideoCodecSettings& other) const {
2427 return codec == other.codec &&
2428 fec.ulpfec_payload_type == other.fec.ulpfec_payload_type &&
2429 fec.red_payload_type == other.fec.red_payload_type &&
2430 fec.red_rtx_payload_type == other.fec.red_rtx_payload_type &&
2431 rtx_payload_type == other.rtx_payload_type;
2432 }
2433
2434 bool WebRtcVideoChannel2::VideoCodecSettings::operator!=(
2435 const WebRtcVideoChannel2::VideoCodecSettings& other) const {
2436 return !(*this == other);
2437 }
2438
2439 std::vector<WebRtcVideoChannel2::VideoCodecSettings>
2440 WebRtcVideoChannel2::MapCodecs(const std::vector<VideoCodec>& codecs) {
2441 RTC_DCHECK(!codecs.empty());
2442
2443 std::vector<VideoCodecSettings> video_codecs;
2444 std::map<int, bool> payload_used;
2445 std::map<int, VideoCodec::CodecType> payload_codec_type;
2446 // |rtx_mapping| maps video payload type to rtx payload type.
2447 std::map<int, int> rtx_mapping;
2448
2449 webrtc::FecConfig fec_settings;
2450
2451 for (size_t i = 0; i < codecs.size(); ++i) {
2452 const VideoCodec& in_codec = codecs[i];
2453 int payload_type = in_codec.id;
2454
2455 if (payload_used[payload_type]) {
2456 LOG(LS_ERROR) << "Payload type already registered: "
2457 << in_codec.ToString();
2458 return std::vector<VideoCodecSettings>();
2459 }
2460 payload_used[payload_type] = true;
2461 payload_codec_type[payload_type] = in_codec.GetCodecType();
2462
2463 switch (in_codec.GetCodecType()) {
2464 case VideoCodec::CODEC_RED: {
2465 // RED payload type, should not have duplicates.
2466 RTC_DCHECK(fec_settings.red_payload_type == -1);
2467 fec_settings.red_payload_type = in_codec.id;
2468 continue;
2469 }
2470
2471 case VideoCodec::CODEC_ULPFEC: {
2472 // ULPFEC payload type, should not have duplicates.
2473 RTC_DCHECK(fec_settings.ulpfec_payload_type == -1);
2474 fec_settings.ulpfec_payload_type = in_codec.id;
2475 continue;
2476 }
2477
2478 case VideoCodec::CODEC_RTX: {
2479 int associated_payload_type;
2480 if (!in_codec.GetParam(kCodecParamAssociatedPayloadType,
2481 &associated_payload_type) ||
2482 !IsValidRtpPayloadType(associated_payload_type)) {
2483 LOG(LS_ERROR)
2484 << "RTX codec with invalid or no associated payload type: "
2485 << in_codec.ToString();
2486 return std::vector<VideoCodecSettings>();
2487 }
2488 rtx_mapping[associated_payload_type] = in_codec.id;
2489 continue;
2490 }
2491
2492 case VideoCodec::CODEC_VIDEO:
2493 break;
2494 }
2495
2496 video_codecs.push_back(VideoCodecSettings());
2497 video_codecs.back().codec = in_codec;
2498 }
2499
2500 // One of these codecs should have been a video codec. Only having FEC
2501 // parameters into this code is a logic error.
2502 RTC_DCHECK(!video_codecs.empty());
2503
2504 for (std::map<int, int>::const_iterator it = rtx_mapping.begin();
2505 it != rtx_mapping.end();
2506 ++it) {
2507 if (!payload_used[it->first]) {
2508 LOG(LS_ERROR) << "RTX mapped to payload not in codec list.";
2509 return std::vector<VideoCodecSettings>();
2510 }
2511 if (payload_codec_type[it->first] != VideoCodec::CODEC_VIDEO &&
2512 payload_codec_type[it->first] != VideoCodec::CODEC_RED) {
2513 LOG(LS_ERROR) << "RTX not mapped to regular video codec or RED codec.";
2514 return std::vector<VideoCodecSettings>();
2515 }
2516
2517 if (it->first == fec_settings.red_payload_type) {
2518 fec_settings.red_rtx_payload_type = it->second;
2519 }
2520 }
2521
2522 for (size_t i = 0; i < video_codecs.size(); ++i) {
2523 video_codecs[i].fec = fec_settings;
2524 if (rtx_mapping[video_codecs[i].codec.id] != 0 &&
2525 rtx_mapping[video_codecs[i].codec.id] !=
2526 fec_settings.red_payload_type) {
2527 video_codecs[i].rtx_payload_type = rtx_mapping[video_codecs[i].codec.id];
2528 }
2529 }
2530
2531 return video_codecs;
2532 }
2533
2534 } // namespace cricket
2535
2536 #endif // HAVE_WEBRTC_VIDEO
OLDNEW
« no previous file with comments | « talk/media/webrtc/webrtcvideoengine2.h ('k') | talk/media/webrtc/webrtcvideoengine2_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698