blob: aa136ce8bdaf9e97042238a8cb022233d176aa04 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 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/webrtcvideoengine.h"
30
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include <math.h>
36#include <set>
37
38#include "talk/base/basictypes.h"
39#include "talk/base/buffer.h"
40#include "talk/base/byteorder.h"
41#include "talk/base/common.h"
42#include "talk/base/cpumonitor.h"
43#include "talk/base/logging.h"
44#include "talk/base/stringutils.h"
45#include "talk/base/thread.h"
46#include "talk/base/timeutils.h"
47#include "talk/media/base/constants.h"
48#include "talk/media/base/rtputils.h"
49#include "talk/media/base/streamparams.h"
50#include "talk/media/base/videoadapter.h"
51#include "talk/media/base/videocapturer.h"
52#include "talk/media/base/videorenderer.h"
53#include "talk/media/devices/filevideocapturer.h"
wu@webrtc.org9dba5252013-08-05 20:36:57 +000054#include "talk/media/webrtc/webrtcpassthroughrender.h"
55#include "talk/media/webrtc/webrtctexturevideoframe.h"
56#include "talk/media/webrtc/webrtcvideocapturer.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057#include "talk/media/webrtc/webrtcvideodecoderfactory.h"
58#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059#include "talk/media/webrtc/webrtcvideoframe.h"
60#include "talk/media/webrtc/webrtcvie.h"
61#include "talk/media/webrtc/webrtcvoe.h"
62#include "talk/media/webrtc/webrtcvoiceengine.h"
henrike@webrtc.orga92fd742014-03-26 01:46:18 +000063#include "webrtc/experiments.h"
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +000064#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065
66#if !defined(LIBPEERCONNECTION_LIB)
henrike@webrtc.org28e20752013-07-10 00:45:36 +000067#include "talk/media/webrtc/webrtcmediaengine.h"
68
69WRME_EXPORT
70cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
71 webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc,
72 cricket::WebRtcVideoEncoderFactory* encoder_factory,
73 cricket::WebRtcVideoDecoderFactory* decoder_factory) {
74 return new cricket::WebRtcMediaEngine(adm, adm_sc, encoder_factory,
75 decoder_factory);
76}
77
78WRME_EXPORT
79void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
80 delete static_cast<cricket::WebRtcMediaEngine*>(media_engine);
81}
82#endif
83
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +000084static const int kVideoCodecClockratekHz = cricket::kVideoCodecClockrate / 1000;
85
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086
87namespace cricket {
88
89
90static const int kDefaultLogSeverity = talk_base::LS_WARNING;
91
92static const int kMinVideoBitrate = 50;
93static const int kStartVideoBitrate = 300;
94static const int kMaxVideoBitrate = 2000;
95static const int kDefaultConferenceModeMaxVideoBitrate = 500;
96
wu@webrtc.orgcecfd182013-10-30 05:18:12 +000097// Controlled by exp, try a super low minimum bitrate for poor connections.
98static const int kLowerMinBitrate = 30;
99
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100static const int kVideoMtu = 1200;
101
102static const int kVideoRtpBufferSize = 65536;
103
104static const char kVp8PayloadName[] = "VP8";
105static const char kRedPayloadName[] = "red";
106static const char kFecPayloadName[] = "ulpfec";
107
108static const int kDefaultNumberOfTemporalLayers = 1; // 1:1
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const int kMaxExternalVideoCodecs = 8;
111static const int kExternalVideoPayloadTypeBase = 120;
112
113// Static allocation of payload type values for external video codec.
114static int GetExternalVideoPayloadType(int index) {
115 ASSERT(index >= 0 && index < kMaxExternalVideoCodecs);
116 return kExternalVideoPayloadTypeBase + index;
117}
118
119static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
120 const char* delim = "\r\n";
121 // TODO(fbarchard): Fix strtok lint warning.
122 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
123 LOG_V(sev) << tok;
124 }
125}
126
127// Severity is an integer because it comes is assumed to be from command line.
128static int SeverityToFilter(int severity) {
129 int filter = webrtc::kTraceNone;
130 switch (severity) {
131 case talk_base::LS_VERBOSE:
132 filter |= webrtc::kTraceAll;
133 case talk_base::LS_INFO:
134 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
135 case talk_base::LS_WARNING:
136 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
137 case talk_base::LS_ERROR:
138 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
139 }
140 return filter;
141}
142
143static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
144
145static const bool kNotSending = false;
146
wu@webrtc.orgde305012013-10-31 15:40:38 +0000147// Default video dscp value.
148// See http://tools.ietf.org/html/rfc2474 for details
149// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
150static const talk_base::DiffServCodePoint kVideoDscpValue =
151 talk_base::DSCP_AF41;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000152
153static bool IsNackEnabled(const VideoCodec& codec) {
154 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
155 kParamValueEmpty));
156}
157
158// Returns true if Receiver Estimated Max Bitrate is enabled.
159static bool IsRembEnabled(const VideoCodec& codec) {
160 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamRemb,
161 kParamValueEmpty));
162}
163
164struct FlushBlackFrameData : public talk_base::MessageData {
165 FlushBlackFrameData(uint32 s, int64 t) : ssrc(s), timestamp(t) {
166 }
167 uint32 ssrc;
168 int64 timestamp;
169};
170
171class WebRtcRenderAdapter : public webrtc::ExternalRenderer {
172 public:
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000173 WebRtcRenderAdapter(VideoRenderer* renderer, int channel_id)
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000174 : renderer_(renderer),
175 channel_id_(channel_id),
176 width_(0),
177 height_(0),
178 first_frame_arrived_(false),
179 capture_start_rtp_time_stamp_(0),
180 capture_start_ntp_time_ms_(0) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000181 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000182
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183 virtual ~WebRtcRenderAdapter() {
184 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000185
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186 void SetRenderer(VideoRenderer* renderer) {
187 talk_base::CritScope cs(&crit_);
188 renderer_ = renderer;
189 // FrameSizeChange may have already been called when renderer was not set.
190 // If so we should call SetSize here.
191 // TODO(ronghuawu): Add unit test for this case. Didn't do it now
192 // because the WebRtcRenderAdapter is currently hiding in cc file. No
193 // good way to get access to it from the unit test.
194 if (width_ > 0 && height_ > 0 && renderer_ != NULL) {
195 if (!renderer_->SetSize(width_, height_, 0)) {
196 LOG(LS_ERROR)
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000197 << "WebRtcRenderAdapter (channel " << channel_id_
198 << ") SetRenderer failed to SetSize to: "
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000199 << width_ << "x" << height_;
200 }
201 }
202 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000203
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204 // Implementation of webrtc::ExternalRenderer.
205 virtual int FrameSizeChange(unsigned int width, unsigned int height,
206 unsigned int /*number_of_streams*/) {
207 talk_base::CritScope cs(&crit_);
208 width_ = width;
209 height_ = height;
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000210 LOG(LS_INFO) << "WebRtcRenderAdapter (channel " << channel_id_
211 << ") frame size changed to: "
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212 << width << "x" << height;
213 if (renderer_ == NULL) {
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000214 LOG(LS_VERBOSE) << "WebRtcRenderAdapter (channel " << channel_id_
215 << ") the renderer has not been set. "
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000216 << "SetSize will be called later in SetRenderer.";
217 return 0;
218 }
219 return renderer_->SetSize(width_, height_, 0) ? 0 : -1;
220 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000221
buildbot@webrtc.org1fd5b452014-04-15 17:39:43 +0000222 virtual int DeliverFrame(unsigned char* buffer,
223 int buffer_size,
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000224 uint32_t rtp_time_stamp,
buildbot@webrtc.org1fd5b452014-04-15 17:39:43 +0000225#ifdef USE_WEBRTC_DEV_BRANCH
226 int64_t ntp_time_ms,
227#endif
228 int64_t render_time,
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000229 void* handle) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000230 talk_base::CritScope cs(&crit_);
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000231 if (!first_frame_arrived_) {
232 first_frame_arrived_ = true;
233 capture_start_rtp_time_stamp_ = rtp_time_stamp;
234 }
235#ifdef USE_WEBRTC_DEV_BRANCH
236 if (ntp_time_ms > 0) {
237 uint32 elapsed_time_ms =
238 (rtp_time_stamp - capture_start_rtp_time_stamp_) /
239 kVideoCodecClockratekHz;
240 capture_start_ntp_time_ms_ = ntp_time_ms - elapsed_time_ms;
241 }
242#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243 frame_rate_tracker_.Update(1);
244 if (renderer_ == NULL) {
245 return 0;
246 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247 // Convert 90K rtp timestamp to ns timestamp.
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000248 int64 rtp_time_stamp_in_ns = (rtp_time_stamp / kVideoCodecClockratekHz) *
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249 talk_base::kNumNanosecsPerMillisec;
250 // Convert milisecond render time to ns timestamp.
251 int64 render_time_stamp_in_ns = render_time *
252 talk_base::kNumNanosecsPerMillisec;
253 // Send the rtp timestamp to renderer as the VideoFrame timestamp.
254 // and the render timestamp as the VideoFrame elapsed_time.
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000255 if (handle == NULL) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000256 return DeliverBufferFrame(buffer, buffer_size, render_time_stamp_in_ns,
buildbot@webrtc.org740e6b32014-04-30 15:33:45 +0000257 rtp_time_stamp_in_ns);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000258 } else {
259 return DeliverTextureFrame(handle, render_time_stamp_in_ns,
buildbot@webrtc.org740e6b32014-04-30 15:33:45 +0000260 rtp_time_stamp_in_ns);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000261 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000262 }
263
264 virtual bool IsTextureSupported() { return true; }
265
266 int DeliverBufferFrame(unsigned char* buffer, int buffer_size,
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000267 int64 elapsed_time, int64 rtp_time_stamp_in_ns) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000268 WebRtcVideoFrame video_frame;
wu@webrtc.org16d62542013-11-05 23:45:14 +0000269 video_frame.Alias(buffer, buffer_size, width_, height_,
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000270 1, 1, elapsed_time, rtp_time_stamp_in_ns, 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 // Sanity check on decoded frame size.
273 if (buffer_size != static_cast<int>(VideoFrame::SizeOf(width_, height_))) {
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000274 LOG(LS_WARNING) << "WebRtcRenderAdapter (channel " << channel_id_
275 << ") received a strange frame size: "
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000276 << buffer_size;
277 }
278
279 int ret = renderer_->RenderFrame(&video_frame) ? 0 : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000280 return ret;
281 }
282
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000283 int DeliverTextureFrame(void* handle,
284 int64 elapsed_time,
285 int64 rtp_time_stamp_in_ns) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000286 WebRtcTextureVideoFrame video_frame(
287 static_cast<webrtc::NativeHandle*>(handle), width_, height_,
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000288 elapsed_time, rtp_time_stamp_in_ns);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000289 return renderer_->RenderFrame(&video_frame);
290 }
291
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000292 unsigned int width() {
293 talk_base::CritScope cs(&crit_);
294 return width_;
295 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000296
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297 unsigned int height() {
298 talk_base::CritScope cs(&crit_);
299 return height_;
300 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000301
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000302 int framerate() {
303 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000304 return static_cast<int>(frame_rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000305 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000306
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000307 VideoRenderer* renderer() {
308 talk_base::CritScope cs(&crit_);
309 return renderer_;
310 }
311
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000312 int64 capture_start_ntp_time_ms() {
313 talk_base::CritScope cs(&crit_);
314 return capture_start_ntp_time_ms_;
315 }
316
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000317 private:
318 talk_base::CriticalSection crit_;
319 VideoRenderer* renderer_;
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000320 int channel_id_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000321 unsigned int width_;
322 unsigned int height_;
323 talk_base::RateTracker frame_rate_tracker_;
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +0000324 bool first_frame_arrived_;
325 uint32 capture_start_rtp_time_stamp_;
326 int64 capture_start_ntp_time_ms_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000327};
328
329class WebRtcDecoderObserver : public webrtc::ViEDecoderObserver {
330 public:
331 explicit WebRtcDecoderObserver(int video_channel)
332 : video_channel_(video_channel),
333 framerate_(0),
334 bitrate_(0),
wu@webrtc.org97077a32013-10-25 21:18:33 +0000335 decode_ms_(0),
336 max_decode_ms_(0),
337 current_delay_ms_(0),
338 target_delay_ms_(0),
339 jitter_buffer_ms_(0),
340 min_playout_delay_ms_(0),
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000341 render_delay_ms_(0) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000342 }
343
344 // virtual functions from VieDecoderObserver.
345 virtual void IncomingCodecChanged(const int videoChannel,
346 const webrtc::VideoCodec& videoCodec) {}
347 virtual void IncomingRate(const int videoChannel,
348 const unsigned int framerate,
349 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000350 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351 ASSERT(video_channel_ == videoChannel);
352 framerate_ = framerate;
353 bitrate_ = bitrate;
354 }
wu@webrtc.org97077a32013-10-25 21:18:33 +0000355
356 virtual void DecoderTiming(int decode_ms,
357 int max_decode_ms,
358 int current_delay_ms,
359 int target_delay_ms,
360 int jitter_buffer_ms,
361 int min_playout_delay_ms,
362 int render_delay_ms) {
363 talk_base::CritScope cs(&crit_);
364 decode_ms_ = decode_ms;
365 max_decode_ms_ = max_decode_ms;
366 current_delay_ms_ = current_delay_ms;
367 target_delay_ms_ = target_delay_ms;
368 jitter_buffer_ms_ = jitter_buffer_ms;
369 min_playout_delay_ms_ = min_playout_delay_ms;
370 render_delay_ms_ = render_delay_ms;
371 }
372
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000373 virtual void RequestNewKeyFrame(const int videoChannel) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000374
wu@webrtc.org97077a32013-10-25 21:18:33 +0000375 // Populate |rinfo| based on previously-set data in |*this|.
376 void ExportTo(VideoReceiverInfo* rinfo) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000377 talk_base::CritScope cs(&crit_);
wu@webrtc.org97077a32013-10-25 21:18:33 +0000378 rinfo->framerate_rcvd = framerate_;
379 rinfo->decode_ms = decode_ms_;
380 rinfo->max_decode_ms = max_decode_ms_;
381 rinfo->current_delay_ms = current_delay_ms_;
382 rinfo->target_delay_ms = target_delay_ms_;
383 rinfo->jitter_buffer_ms = jitter_buffer_ms_;
384 rinfo->min_playout_delay_ms = min_playout_delay_ms_;
385 rinfo->render_delay_ms = render_delay_ms_;
wu@webrtc.org78187522013-10-07 23:32:02 +0000386 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387
388 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000389 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000390 int video_channel_;
391 int framerate_;
392 int bitrate_;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000393 int decode_ms_;
394 int max_decode_ms_;
395 int current_delay_ms_;
396 int target_delay_ms_;
397 int jitter_buffer_ms_;
398 int min_playout_delay_ms_;
399 int render_delay_ms_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400};
401
402class WebRtcEncoderObserver : public webrtc::ViEEncoderObserver {
403 public:
404 explicit WebRtcEncoderObserver(int video_channel)
405 : video_channel_(video_channel),
406 framerate_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000407 bitrate_(0),
408 suspended_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000409 }
410
411 // virtual functions from VieEncoderObserver.
412 virtual void OutgoingRate(const int videoChannel,
413 const unsigned int framerate,
414 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000415 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000416 ASSERT(video_channel_ == videoChannel);
417 framerate_ = framerate;
418 bitrate_ = bitrate;
419 }
420
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000421 virtual void SuspendChange(int video_channel, bool is_suspended) {
422 talk_base::CritScope cs(&crit_);
423 ASSERT(video_channel_ == video_channel);
424 suspended_ = is_suspended;
425 }
426
wu@webrtc.org78187522013-10-07 23:32:02 +0000427 int framerate() const {
428 talk_base::CritScope cs(&crit_);
429 return framerate_;
430 }
431 int bitrate() const {
432 talk_base::CritScope cs(&crit_);
433 return bitrate_;
434 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000435 bool suspended() const {
436 talk_base::CritScope cs(&crit_);
437 return suspended_;
438 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439
440 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000441 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000442 int video_channel_;
443 int framerate_;
444 int bitrate_;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000445 bool suspended_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000446};
447
448class WebRtcLocalStreamInfo {
449 public:
450 WebRtcLocalStreamInfo()
451 : width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
452 size_t width() const {
453 talk_base::CritScope cs(&crit_);
454 return width_;
455 }
456 size_t height() const {
457 talk_base::CritScope cs(&crit_);
458 return height_;
459 }
460 int64 elapsed_time() const {
461 talk_base::CritScope cs(&crit_);
462 return elapsed_time_;
463 }
464 int64 time_stamp() const {
465 talk_base::CritScope cs(&crit_);
466 return time_stamp_;
467 }
468 int framerate() {
469 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000470 return static_cast<int>(rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000471 }
472 void GetLastFrameInfo(
473 size_t* width, size_t* height, int64* elapsed_time) const {
474 talk_base::CritScope cs(&crit_);
475 *width = width_;
476 *height = height_;
477 *elapsed_time = elapsed_time_;
478 }
479
480 void UpdateFrame(const VideoFrame* frame) {
481 talk_base::CritScope cs(&crit_);
482
483 width_ = frame->GetWidth();
484 height_ = frame->GetHeight();
485 elapsed_time_ = frame->GetElapsedTime();
486 time_stamp_ = frame->GetTimeStamp();
487
488 rate_tracker_.Update(1);
489 }
490
491 private:
492 mutable talk_base::CriticalSection crit_;
493 size_t width_;
494 size_t height_;
495 int64 elapsed_time_;
496 int64 time_stamp_;
497 talk_base::RateTracker rate_tracker_;
498
499 DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
500};
501
502// WebRtcVideoChannelRecvInfo is a container class with members such as renderer
503// and a decoder observer that is used by receive channels.
504// It must exist as long as the receive channel is connected to renderer or a
505// decoder observer in this class and methods in the class should only be called
506// from the worker thread.
507class WebRtcVideoChannelRecvInfo {
508 public:
509 typedef std::map<int, webrtc::VideoDecoder*> DecoderMap; // key: payload type
510 explicit WebRtcVideoChannelRecvInfo(int channel_id)
511 : channel_id_(channel_id),
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +0000512 render_adapter_(NULL, channel_id),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000513 decoder_observer_(channel_id) {
514 }
515 int channel_id() { return channel_id_; }
516 void SetRenderer(VideoRenderer* renderer) {
517 render_adapter_.SetRenderer(renderer);
518 }
519 WebRtcRenderAdapter* render_adapter() { return &render_adapter_; }
520 WebRtcDecoderObserver* decoder_observer() { return &decoder_observer_; }
521 void RegisterDecoder(int pl_type, webrtc::VideoDecoder* decoder) {
522 ASSERT(!IsDecoderRegistered(pl_type));
523 registered_decoders_[pl_type] = decoder;
524 }
525 bool IsDecoderRegistered(int pl_type) {
526 return registered_decoders_.count(pl_type) != 0;
527 }
528 const DecoderMap& registered_decoders() {
529 return registered_decoders_;
530 }
531 void ClearRegisteredDecoders() {
532 registered_decoders_.clear();
533 }
534
535 private:
536 int channel_id_; // Webrtc video channel number.
537 // Renderer for this channel.
538 WebRtcRenderAdapter render_adapter_;
539 WebRtcDecoderObserver decoder_observer_;
540 DecoderMap registered_decoders_;
541};
542
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000543class WebRtcOveruseObserver : public webrtc::CpuOveruseObserver {
544 public:
545 explicit WebRtcOveruseObserver(CoordinatedVideoAdapter* video_adapter)
546 : video_adapter_(video_adapter),
547 enabled_(false) {
548 }
549
550 // TODO(mflodman): Consider sending resolution as part of event, to let
551 // adapter know what resolution the request is based on. Helps eliminate stale
552 // data, race conditions.
553 virtual void OveruseDetected() OVERRIDE {
554 talk_base::CritScope cs(&crit_);
555 if (!enabled_) {
556 return;
557 }
558
559 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
560 }
561
562 virtual void NormalUsage() OVERRIDE {
563 talk_base::CritScope cs(&crit_);
564 if (!enabled_) {
565 return;
566 }
567
568 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::UPGRADE);
569 }
570
571 void Enable(bool enable) {
572 talk_base::CritScope cs(&crit_);
573 enabled_ = enable;
574 }
575
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000576 bool enabled() const { return enabled_; }
577
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000578 private:
579 CoordinatedVideoAdapter* video_adapter_;
580 bool enabled_;
581 talk_base::CriticalSection crit_;
582};
583
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000584
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000585class WebRtcVideoChannelSendInfo : public sigslot::has_slots<> {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586 public:
587 typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
588 WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
589 webrtc::ViEExternalCapture* external_capture,
590 talk_base::CpuMonitor* cpu_monitor)
591 : channel_id_(channel_id),
592 capture_id_(capture_id),
593 sending_(false),
594 muted_(false),
595 video_capturer_(NULL),
596 encoder_observer_(channel_id),
597 external_capture_(external_capture),
598 capturer_updated_(false),
599 interval_(0),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000600 cpu_monitor_(cpu_monitor),
601 overuse_observer_enabled_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 }
603
604 int channel_id() const { return channel_id_; }
605 int capture_id() const { return capture_id_; }
606 void set_sending(bool sending) { sending_ = sending; }
607 bool sending() const { return sending_; }
608 void set_muted(bool on) {
609 // TODO(asapersson): add support.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000610 // video_adapter_.SetBlackOutput(on);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000611 muted_ = on;
612 }
613 bool muted() {return muted_; }
614
615 WebRtcEncoderObserver* encoder_observer() { return &encoder_observer_; }
616 webrtc::ViEExternalCapture* external_capture() { return external_capture_; }
617 const VideoFormat& video_format() const {
618 return video_format_;
619 }
620 void set_video_format(const VideoFormat& video_format) {
621 video_format_ = video_format;
622 if (video_format_ != cricket::VideoFormat()) {
623 interval_ = video_format_.interval;
624 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000625 CoordinatedVideoAdapter* adapter = video_adapter();
626 if (adapter) {
627 adapter->OnOutputFormatRequest(video_format_);
628 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000629 }
630 void set_interval(int64 interval) {
631 if (video_format() == cricket::VideoFormat()) {
632 interval_ = interval;
633 }
634 }
635 int64 interval() { return interval_; }
636
xians@webrtc.orgef221512014-02-21 10:31:29 +0000637 int CurrentAdaptReason() const {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000638 const CoordinatedVideoAdapter* adapter = video_adapter();
639 if (!adapter) {
640 return CoordinatedVideoAdapter::ADAPTREASON_NONE;
641 }
642 return video_adapter()->adapt_reason();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643 }
644
645 StreamParams* stream_params() { return stream_params_.get(); }
646 void set_stream_params(const StreamParams& sp) {
647 stream_params_.reset(new StreamParams(sp));
648 }
649 void ClearStreamParams() { stream_params_.reset(); }
650 bool has_ssrc(uint32 local_ssrc) const {
651 return !stream_params_ ? false :
652 stream_params_->has_ssrc(local_ssrc);
653 }
654 WebRtcLocalStreamInfo* local_stream_info() {
655 return &local_stream_info_;
656 }
657 VideoCapturer* video_capturer() {
658 return video_capturer_;
659 }
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +0000660 void set_video_capturer(VideoCapturer* video_capturer,
661 ViEWrapper* vie_wrapper) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662 if (video_capturer == video_capturer_) {
663 return;
664 }
xians@webrtc.orgef221512014-02-21 10:31:29 +0000665
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000666 CoordinatedVideoAdapter* old_video_adapter = video_adapter();
667 if (old_video_adapter) {
668 // Disconnect signals from old video adapter.
669 SignalCpuAdaptationUnable.disconnect(old_video_adapter);
670 if (cpu_monitor_) {
671 cpu_monitor_->SignalUpdate.disconnect(old_video_adapter);
xians@webrtc.orgef221512014-02-21 10:31:29 +0000672 }
henrike@webrtc.org26438052014-02-20 22:32:53 +0000673 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000674
675 capturer_updated_ = true;
676 video_capturer_ = video_capturer;
677
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +0000678 vie_wrapper->base()->RegisterCpuOveruseObserver(channel_id_, NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000679 if (!video_capturer) {
680 overuse_observer_.reset();
681 return;
682 }
683
684 CoordinatedVideoAdapter* adapter = video_adapter();
685 ASSERT(adapter && "Video adapter should not be null here.");
686
687 UpdateAdapterCpuOptions();
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000688
689 overuse_observer_.reset(new WebRtcOveruseObserver(adapter));
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +0000690 vie_wrapper->base()->RegisterCpuOveruseObserver(channel_id_,
691 overuse_observer_.get());
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000692 // (Dis)connect the video adapter from the cpu monitor as appropriate.
693 SetCpuOveruseDetection(overuse_observer_enabled_);
694
695 SignalCpuAdaptationUnable.repeat(adapter->SignalCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 }
697
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000698 CoordinatedVideoAdapter* video_adapter() {
699 if (!video_capturer_) {
700 return NULL;
701 }
702 return video_capturer_->video_adapter();
703 }
704 const CoordinatedVideoAdapter* video_adapter() const {
705 if (!video_capturer_) {
706 return NULL;
707 }
708 return video_capturer_->video_adapter();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000709 }
710
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000711 void ApplyCpuOptions(const VideoOptions& video_options) {
712 // Use video_options_.SetAll() instead of assignment so that unset value in
713 // video_options will not overwrite the previous option value.
714 video_options_.SetAll(video_options);
715 UpdateAdapterCpuOptions();
716 }
717
718 void UpdateAdapterCpuOptions() {
719 if (!video_capturer_) {
720 return;
721 }
722
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000723 bool cpu_adapt, cpu_smoothing, adapt_third;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 float low, med, high;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000725
726 // TODO(thorcarpenter): Have VideoAdapter be responsible for setting
727 // all these video options.
728 CoordinatedVideoAdapter* video_adapter = video_capturer_->video_adapter();
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000729 if (video_options_.adapt_input_to_cpu_usage.Get(&cpu_adapt) ||
730 overuse_observer_enabled_) {
731 video_adapter->set_cpu_adaptation(cpu_adapt || overuse_observer_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000733 if (video_options_.adapt_cpu_with_smoothing.Get(&cpu_smoothing)) {
734 video_adapter->set_cpu_smoothing(cpu_smoothing);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000735 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000736 if (video_options_.process_adaptation_threshhold.Get(&med)) {
737 video_adapter->set_process_threshold(med);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000738 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000739 if (video_options_.system_low_adaptation_threshhold.Get(&low)) {
740 video_adapter->set_low_system_threshold(low);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000742 if (video_options_.system_high_adaptation_threshhold.Get(&high)) {
743 video_adapter->set_high_system_threshold(high);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000745 if (video_options_.video_adapt_third.Get(&adapt_third)) {
746 video_adapter->set_scale_third(adapt_third);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000747 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000748 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000749
750 void SetCpuOveruseDetection(bool enable) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000751 overuse_observer_enabled_ = enable;
752
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000753 if (overuse_observer_) {
754 overuse_observer_->Enable(enable);
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000755 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000756
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000757 // The video adapter is signaled by overuse detection if enabled; otherwise
758 // it will be signaled by cpu monitor.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000759 CoordinatedVideoAdapter* adapter = video_adapter();
760 if (adapter) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000761 bool cpu_adapt = false;
762 video_options_.adapt_input_to_cpu_usage.Get(&cpu_adapt);
763 adapter->set_cpu_adaptation(
764 adapter->cpu_adaptation() || cpu_adapt || enable);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000765 if (cpu_monitor_) {
766 if (enable) {
767 cpu_monitor_->SignalUpdate.disconnect(adapter);
768 } else {
769 cpu_monitor_->SignalUpdate.connect(
770 adapter, &CoordinatedVideoAdapter::OnCpuLoadUpdated);
771 }
772 }
773 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000774 }
775
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776 void ProcessFrame(const VideoFrame& original_frame, bool mute,
777 VideoFrame** processed_frame) {
778 if (!mute) {
779 *processed_frame = original_frame.Copy();
780 } else {
781 WebRtcVideoFrame* black_frame = new WebRtcVideoFrame();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000782 black_frame->InitToBlack(static_cast<int>(original_frame.GetWidth()),
783 static_cast<int>(original_frame.GetHeight()),
784 1, 1,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785 original_frame.GetElapsedTime(),
786 original_frame.GetTimeStamp());
787 *processed_frame = black_frame;
788 }
789 local_stream_info_.UpdateFrame(*processed_frame);
790 }
791 void RegisterEncoder(int pl_type, webrtc::VideoEncoder* encoder) {
792 ASSERT(!IsEncoderRegistered(pl_type));
793 registered_encoders_[pl_type] = encoder;
794 }
795 bool IsEncoderRegistered(int pl_type) {
796 return registered_encoders_.count(pl_type) != 0;
797 }
798 const EncoderMap& registered_encoders() {
799 return registered_encoders_;
800 }
801 void ClearRegisteredEncoders() {
802 registered_encoders_.clear();
803 }
804
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000805 sigslot::repeater0<> SignalCpuAdaptationUnable;
806
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 private:
808 int channel_id_;
809 int capture_id_;
810 bool sending_;
811 bool muted_;
812 VideoCapturer* video_capturer_;
813 WebRtcEncoderObserver encoder_observer_;
814 webrtc::ViEExternalCapture* external_capture_;
815 EncoderMap registered_encoders_;
816
817 VideoFormat video_format_;
818
819 talk_base::scoped_ptr<StreamParams> stream_params_;
820
821 WebRtcLocalStreamInfo local_stream_info_;
822
823 bool capturer_updated_;
824
825 int64 interval_;
826
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000827 talk_base::CpuMonitor* cpu_monitor_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000828 talk_base::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000829 bool overuse_observer_enabled_;
830
831 VideoOptions video_options_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832};
833
834const WebRtcVideoEngine::VideoCodecPref
835 WebRtcVideoEngine::kVideoCodecPrefs[] = {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000836 {kVp8PayloadName, 100, -1, 0},
837 {kRedPayloadName, 116, -1, 1},
838 {kFecPayloadName, 117, -1, 2},
839 {kRtxCodecName, 96, 100, 3},
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840};
841
842// The formats are sorted by the descending order of width. We use the order to
843// find the next format for CPU and bandwidth adaptation.
844const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
845 {1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
846 {1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
847 {960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
848 {960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
849 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
850 {640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
851 {640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
852 {480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
853 {480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
854 {480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
855 {320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
856 {320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
857 {320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
858 {240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
859 {240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
860 {240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
861 {160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
862 {160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
863 {160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
864};
865
866const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
867 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
868
869static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
870 webrtc::VideoCodec* target_codec) {
871 if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
872 return;
873 }
874 target_codec->width = video_format.width;
875 target_codec->height = video_format.height;
876 target_codec->maxFramerate = cricket::VideoFormat::IntervalToFps(
877 video_format.interval);
878}
879
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000880static bool GetCpuOveruseOptions(const VideoOptions& options,
881 webrtc::CpuOveruseOptions* overuse_options) {
882 int underuse_threshold = 0;
883 int overuse_threshold = 0;
884 if (!options.cpu_underuse_threshold.Get(&underuse_threshold) ||
885 !options.cpu_overuse_threshold.Get(&overuse_threshold)) {
886 return false;
887 }
888 if (underuse_threshold <= 0 || overuse_threshold <= 0) {
889 return false;
890 }
891 // Valid thresholds.
892 bool encode_usage =
893 options.cpu_overuse_encode_usage.GetWithDefaultIfUnset(false);
894 overuse_options->enable_capture_jitter_method = !encode_usage;
895 overuse_options->enable_encode_usage_method = encode_usage;
896 if (encode_usage) {
897 // Use method based on encode usage.
898 overuse_options->low_encode_usage_threshold_percent = underuse_threshold;
899 overuse_options->high_encode_usage_threshold_percent = overuse_threshold;
900 } else {
901 // Use default method based on capture jitter.
902 overuse_options->low_capture_jitter_threshold_ms =
903 static_cast<float>(underuse_threshold);
904 overuse_options->high_capture_jitter_threshold_ms =
905 static_cast<float>(overuse_threshold);
906 }
907 return true;
908}
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000909
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910WebRtcVideoEngine::WebRtcVideoEngine() {
911 Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
912 new talk_base::CpuMonitor(NULL));
913}
914
915WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
916 ViEWrapper* vie_wrapper,
917 talk_base::CpuMonitor* cpu_monitor) {
918 Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
919}
920
921WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
922 ViEWrapper* vie_wrapper,
923 ViETraceWrapper* tracing,
924 talk_base::CpuMonitor* cpu_monitor) {
925 Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
926}
927
928void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
929 ViETraceWrapper* tracing,
930 WebRtcVoiceEngine* voice_engine,
931 talk_base::CpuMonitor* cpu_monitor) {
932 LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
933 worker_thread_ = NULL;
934 vie_wrapper_.reset(vie_wrapper);
935 vie_wrapper_base_initialized_ = false;
936 tracing_.reset(tracing);
937 voice_engine_ = voice_engine;
938 initialized_ = false;
939 SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
940 render_module_.reset(new WebRtcPassthroughRender());
941 local_renderer_w_ = local_renderer_h_ = 0;
942 local_renderer_ = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 capture_started_ = false;
944 decoder_factory_ = NULL;
945 encoder_factory_ = NULL;
946 cpu_monitor_.reset(cpu_monitor);
947
948 SetTraceOptions("");
949 if (tracing_->SetTraceCallback(this) != 0) {
950 LOG_RTCERR1(SetTraceCallback, this);
951 }
952
953 // Set default quality levels for our supported codecs. We override them here
954 // if we know your cpu performance is low, and they can be updated explicitly
955 // by calling SetDefaultCodec. For example by a flute preference setting, or
956 // by the server with a jec in response to our reported system info.
957 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
958 kVideoCodecPrefs[0].name,
959 kDefaultVideoFormat.width,
960 kDefaultVideoFormat.height,
961 VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
962 0);
963 if (!SetDefaultCodec(max_codec)) {
964 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
965 }
966
967
968 // Load our RTP Header extensions.
969 rtp_header_extensions_.push_back(
970 RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
henrike@webrtc.org79047f92014-03-06 23:46:59 +0000971 kRtpTimestampOffsetHeaderExtensionDefaultId));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972 rtp_header_extensions_.push_back(
henrike@webrtc.org79047f92014-03-06 23:46:59 +0000973 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
974 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975}
976
977WebRtcVideoEngine::~WebRtcVideoEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978 LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
979 if (initialized_) {
980 Terminate();
981 }
982 if (encoder_factory_) {
983 encoder_factory_->RemoveObserver(this);
984 }
985 tracing_->SetTraceCallback(NULL);
986 // Test to see if the media processor was deregistered properly.
987 ASSERT(SignalMediaFrame.is_empty());
988}
989
990bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
991 LOG(LS_INFO) << "WebRtcVideoEngine::Init";
992 worker_thread_ = worker_thread;
993 ASSERT(worker_thread_ != NULL);
994
995 cpu_monitor_->set_thread(worker_thread_);
996 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
997 LOG(LS_ERROR) << "Failed to start CPU monitor.";
998 cpu_monitor_.reset();
999 }
1000
1001 bool result = InitVideoEngine();
1002 if (result) {
1003 LOG(LS_INFO) << "VideoEngine Init done";
1004 } else {
1005 LOG(LS_ERROR) << "VideoEngine Init failed, releasing";
1006 Terminate();
1007 }
1008 return result;
1009}
1010
1011bool WebRtcVideoEngine::InitVideoEngine() {
1012 LOG(LS_INFO) << "WebRtcVideoEngine::InitVideoEngine";
1013
1014 // Init WebRTC VideoEngine.
1015 if (!vie_wrapper_base_initialized_) {
1016 if (vie_wrapper_->base()->Init() != 0) {
1017 LOG_RTCERR0(Init);
1018 return false;
1019 }
1020 vie_wrapper_base_initialized_ = true;
1021 }
1022
1023 // Log the VoiceEngine version info.
1024 char buffer[1024] = "";
1025 if (vie_wrapper_->base()->GetVersion(buffer) != 0) {
1026 LOG_RTCERR0(GetVersion);
1027 return false;
1028 }
1029
1030 LOG(LS_INFO) << "WebRtc VideoEngine Version:";
1031 LogMultiline(talk_base::LS_INFO, buffer);
1032
1033 // Hook up to VoiceEngine for sync purposes, if supplied.
1034 if (!voice_engine_) {
1035 LOG(LS_WARNING) << "NULL voice engine";
1036 } else if ((vie_wrapper_->base()->SetVoiceEngine(
1037 voice_engine_->voe()->engine())) != 0) {
1038 LOG_RTCERR0(SetVoiceEngine);
1039 return false;
1040 }
1041
1042 // Register our custom render module.
1043 if (vie_wrapper_->render()->RegisterVideoRenderModule(
1044 *render_module_.get()) != 0) {
1045 LOG_RTCERR0(RegisterVideoRenderModule);
1046 return false;
1047 }
1048
1049 initialized_ = true;
1050 return true;
1051}
1052
1053void WebRtcVideoEngine::Terminate() {
1054 LOG(LS_INFO) << "WebRtcVideoEngine::Terminate";
1055 initialized_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056
1057 if (vie_wrapper_->render()->DeRegisterVideoRenderModule(
1058 *render_module_.get()) != 0) {
1059 LOG_RTCERR0(DeRegisterVideoRenderModule);
1060 }
1061
1062 if (vie_wrapper_->base()->SetVoiceEngine(NULL) != 0) {
1063 LOG_RTCERR0(SetVoiceEngine);
1064 }
1065
1066 cpu_monitor_->Stop();
1067}
1068
1069int WebRtcVideoEngine::GetCapabilities() {
1070 return VIDEO_RECV | VIDEO_SEND;
1071}
1072
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001073bool WebRtcVideoEngine::SetOptions(const VideoOptions &options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074 return true;
1075}
1076
1077bool WebRtcVideoEngine::SetDefaultEncoderConfig(
1078 const VideoEncoderConfig& config) {
1079 return SetDefaultCodec(config.max_codec);
1080}
1081
wu@webrtc.org78187522013-10-07 23:32:02 +00001082VideoEncoderConfig WebRtcVideoEngine::GetDefaultEncoderConfig() const {
1083 ASSERT(!video_codecs_.empty());
1084 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1085 kVideoCodecPrefs[0].name,
1086 video_codecs_[0].width,
1087 video_codecs_[0].height,
1088 video_codecs_[0].framerate,
1089 0);
1090 return VideoEncoderConfig(max_codec);
1091}
1092
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093// SetDefaultCodec may be called while the capturer is running. For example, a
1094// test call is started in a page with QVGA default codec, and then a real call
1095// is started in another page with VGA default codec. This is the corner case
1096// and happens only when a session is started. We ignore this case currently.
1097bool WebRtcVideoEngine::SetDefaultCodec(const VideoCodec& codec) {
1098 if (!RebuildCodecList(codec)) {
1099 LOG(LS_WARNING) << "Failed to RebuildCodecList";
1100 return false;
1101 }
1102
wu@webrtc.org78187522013-10-07 23:32:02 +00001103 ASSERT(!video_codecs_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 default_codec_format_ = VideoFormat(
1105 video_codecs_[0].width,
1106 video_codecs_[0].height,
1107 VideoFormat::FpsToInterval(video_codecs_[0].framerate),
1108 FOURCC_ANY);
1109 return true;
1110}
1111
1112WebRtcVideoMediaChannel* WebRtcVideoEngine::CreateChannel(
1113 VoiceMediaChannel* voice_channel) {
1114 WebRtcVideoMediaChannel* channel =
1115 new WebRtcVideoMediaChannel(this, voice_channel);
1116 if (!channel->Init()) {
1117 delete channel;
1118 channel = NULL;
1119 }
1120 return channel;
1121}
1122
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001123bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
1124 local_renderer_w_ = local_renderer_h_ = 0;
1125 local_renderer_ = renderer;
1126 return true;
1127}
1128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
1130 return video_codecs_;
1131}
1132
1133const std::vector<RtpHeaderExtension>&
1134WebRtcVideoEngine::rtp_header_extensions() const {
1135 return rtp_header_extensions_;
1136}
1137
1138void WebRtcVideoEngine::SetLogging(int min_sev, const char* filter) {
1139 // if min_sev == -1, we keep the current log level.
1140 if (min_sev >= 0) {
1141 SetTraceFilter(SeverityToFilter(min_sev));
1142 }
1143 SetTraceOptions(filter);
1144}
1145
1146int WebRtcVideoEngine::GetLastEngineError() {
1147 return vie_wrapper_->error();
1148}
1149
1150// Checks to see whether we comprehend and could receive a particular codec
1151bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
1152 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
1153 const VideoFormat fmt(kVideoFormats[i]);
1154 if ((in.width == 0 && in.height == 0) ||
1155 (fmt.width == in.width && fmt.height == in.height)) {
1156 if (encoder_factory_) {
1157 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1158 encoder_factory_->codecs();
1159 for (size_t j = 0; j < codecs.size(); ++j) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001160 VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161 codecs[j].name, 0, 0, 0, 0);
1162 if (codec.Matches(in))
1163 return true;
1164 }
1165 }
1166 for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
1167 VideoCodec codec(kVideoCodecPrefs[j].payload_type,
1168 kVideoCodecPrefs[j].name, 0, 0, 0, 0);
1169 if (codec.Matches(in)) {
1170 return true;
1171 }
1172 }
1173 }
1174 }
1175 return false;
1176}
1177
1178// Given the requested codec, returns true if we can send that codec type and
1179// updates out with the best quality we could send for that codec. If current is
1180// not empty, we constrain out so that its aspect ratio matches current's.
1181bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
1182 const VideoCodec& current,
1183 VideoCodec* out) {
1184 if (!out) {
1185 return false;
1186 }
1187
1188 std::vector<VideoCodec>::const_iterator local_max;
1189 for (local_max = video_codecs_.begin();
1190 local_max < video_codecs_.end();
1191 ++local_max) {
1192 // First match codecs by payload type
1193 if (!requested.Matches(*local_max)) {
1194 continue;
1195 }
1196
1197 out->id = requested.id;
1198 out->name = requested.name;
1199 out->preference = requested.preference;
1200 out->params = requested.params;
1201 out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
1202 out->width = 0;
1203 out->height = 0;
1204 out->params = requested.params;
1205 out->feedback_params = requested.feedback_params;
1206
1207 if (0 == requested.width && 0 == requested.height) {
1208 // Special case with resolution 0. The channel should not send frames.
1209 return true;
1210 } else if (0 == requested.width || 0 == requested.height) {
1211 // 0xn and nx0 are invalid resolutions.
1212 return false;
1213 }
1214
1215 // Pick the best quality that is within their and our bounds and has the
1216 // correct aspect ratio.
1217 for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
1218 const VideoFormat format(kVideoFormats[j]);
1219
1220 // Skip any format that is larger than the local or remote maximums, or
1221 // smaller than the current best match
1222 if (format.width > requested.width || format.height > requested.height ||
1223 format.width > local_max->width ||
1224 (format.width < out->width && format.height < out->height)) {
1225 continue;
1226 }
1227
1228 bool better = false;
1229
1230 // Check any further constraints on this prospective format
1231 if (!out->width || !out->height) {
1232 // If we don't have any matches yet, this is the best so far.
1233 better = true;
1234 } else if (current.width && current.height) {
1235 // current is set so format must match its ratio exactly.
1236 better =
1237 (format.width * current.height == format.height * current.width);
1238 } else {
1239 // Prefer closer aspect ratios i.e
1240 // format.aspect - requested.aspect < out.aspect - requested.aspect
1241 better = abs(format.width * requested.height * out->height -
1242 requested.width * format.height * out->height) <
1243 abs(out->width * format.height * requested.height -
1244 requested.width * format.height * out->height);
1245 }
1246
1247 if (better) {
1248 out->width = format.width;
1249 out->height = format.height;
1250 }
1251 }
1252 if (out->width > 0) {
1253 return true;
1254 }
1255 }
1256 return false;
1257}
1258
1259static void ConvertToCricketVideoCodec(
1260 const webrtc::VideoCodec& in_codec, VideoCodec* out_codec) {
1261 out_codec->id = in_codec.plType;
1262 out_codec->name = in_codec.plName;
1263 out_codec->width = in_codec.width;
1264 out_codec->height = in_codec.height;
1265 out_codec->framerate = in_codec.maxFramerate;
1266 out_codec->SetParam(kCodecParamMinBitrate, in_codec.minBitrate);
1267 out_codec->SetParam(kCodecParamMaxBitrate, in_codec.maxBitrate);
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +00001268 out_codec->SetParam(kCodecParamStartBitrate, in_codec.startBitrate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269 if (in_codec.qpMax) {
1270 out_codec->SetParam(kCodecParamMaxQuantization, in_codec.qpMax);
1271 }
1272}
1273
1274bool WebRtcVideoEngine::ConvertFromCricketVideoCodec(
1275 const VideoCodec& in_codec, webrtc::VideoCodec* out_codec) {
1276 bool found = false;
1277 int ncodecs = vie_wrapper_->codec()->NumberOfCodecs();
1278 for (int i = 0; i < ncodecs; ++i) {
1279 if (vie_wrapper_->codec()->GetCodec(i, *out_codec) == 0 &&
1280 _stricmp(in_codec.name.c_str(), out_codec->plName) == 0) {
1281 found = true;
1282 break;
1283 }
1284 }
1285
1286 // If not found, check if this is supported by external encoder factory.
1287 if (!found && encoder_factory_) {
1288 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1289 encoder_factory_->codecs();
1290 for (size_t i = 0; i < codecs.size(); ++i) {
1291 if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
1292 out_codec->codecType = codecs[i].type;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001293 out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294 talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
1295 codecs[i].name.c_str(), codecs[i].name.length());
1296 found = true;
1297 break;
1298 }
1299 }
1300 }
1301
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00001302 // Is this an RTX codec? Handled separately here since webrtc doesn't handle
1303 // them as webrtc::VideoCodec internally.
1304 if (!found && _stricmp(in_codec.name.c_str(), kRtxCodecName) == 0) {
1305 talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
1306 in_codec.name.c_str(), in_codec.name.length());
1307 out_codec->plType = in_codec.id;
1308 found = true;
1309 }
1310
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 if (!found) {
1312 LOG(LS_ERROR) << "invalid codec type";
1313 return false;
1314 }
1315
1316 if (in_codec.id != 0)
1317 out_codec->plType = in_codec.id;
1318
1319 if (in_codec.width != 0)
1320 out_codec->width = in_codec.width;
1321
1322 if (in_codec.height != 0)
1323 out_codec->height = in_codec.height;
1324
1325 if (in_codec.framerate != 0)
1326 out_codec->maxFramerate = in_codec.framerate;
1327
1328 // Convert bitrate parameters.
1329 int max_bitrate = kMaxVideoBitrate;
1330 int min_bitrate = kMinVideoBitrate;
1331 int start_bitrate = kStartVideoBitrate;
1332
1333 in_codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
1334 in_codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
buildbot@webrtc.orged97bb02014-05-07 11:15:20 +00001335 in_codec.GetParam(kCodecParamStartBitrate, &start_bitrate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001336
1337 if (max_bitrate < min_bitrate) {
1338 return false;
1339 }
1340 start_bitrate = talk_base::_max(start_bitrate, min_bitrate);
1341 start_bitrate = talk_base::_min(start_bitrate, max_bitrate);
1342
1343 out_codec->minBitrate = min_bitrate;
1344 out_codec->startBitrate = start_bitrate;
1345 out_codec->maxBitrate = max_bitrate;
1346
1347 // Convert general codec parameters.
1348 int max_quantization = 0;
1349 if (in_codec.GetParam(kCodecParamMaxQuantization, &max_quantization)) {
1350 if (max_quantization < 0) {
1351 return false;
1352 }
1353 out_codec->qpMax = max_quantization;
1354 }
1355 return true;
1356}
1357
1358void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
1359 talk_base::CritScope cs(&channels_crit_);
1360 channels_.push_back(channel);
1361}
1362
1363void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
1364 talk_base::CritScope cs(&channels_crit_);
1365 channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
1366 channels_.end());
1367}
1368
1369bool WebRtcVideoEngine::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
1370 if (initialized_) {
1371 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
1372 return false;
1373 }
1374 voice_engine_ = voice_engine;
1375 return true;
1376}
1377
1378bool WebRtcVideoEngine::EnableTimedRender() {
1379 if (initialized_) {
1380 LOG(LS_WARNING) << "EnableTimedRender can not be called after Init";
1381 return false;
1382 }
1383 render_module_.reset(webrtc::VideoRender::CreateVideoRender(0, NULL,
1384 false, webrtc::kRenderExternal));
1385 return true;
1386}
1387
1388void WebRtcVideoEngine::SetTraceFilter(int filter) {
1389 tracing_->SetTraceFilter(filter);
1390}
1391
1392// See https://sites.google.com/a/google.com/wavelet/
1393// Home/Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters
1394// for all supported command line setttings.
1395void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
1396 // Set WebRTC trace file.
1397 std::vector<std::string> opts;
1398 talk_base::tokenize(options, ' ', '"', '"', &opts);
1399 std::vector<std::string>::iterator tracefile =
1400 std::find(opts.begin(), opts.end(), "tracefile");
1401 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1402 // Write WebRTC debug output (at same loglevel) to file
1403 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1404 LOG_RTCERR1(SetTraceFile, *tracefile);
1405 }
1406 }
1407}
1408
1409static void AddDefaultFeedbackParams(VideoCodec* codec) {
1410 const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
1411 codec->AddFeedbackParam(kFir);
1412 const FeedbackParam kNack(kRtcpFbParamNack, kParamValueEmpty);
1413 codec->AddFeedbackParam(kNack);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001414 const FeedbackParam kPli(kRtcpFbParamNack, kRtcpFbNackParamPli);
1415 codec->AddFeedbackParam(kPli);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 const FeedbackParam kRemb(kRtcpFbParamRemb, kParamValueEmpty);
1417 codec->AddFeedbackParam(kRemb);
1418}
1419
1420// Rebuilds the codec list to be only those that are less intensive
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001421// than the specified codec. Prefers internal codec over external with
1422// higher preference field.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001423bool WebRtcVideoEngine::RebuildCodecList(const VideoCodec& in_codec) {
1424 if (!FindCodec(in_codec))
1425 return false;
1426
1427 video_codecs_.clear();
1428
1429 bool found = false;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001430 std::set<std::string> internal_codec_names;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431 for (size_t i = 0; i < ARRAY_SIZE(kVideoCodecPrefs); ++i) {
1432 const VideoCodecPref& pref(kVideoCodecPrefs[i]);
1433 if (!found)
1434 found = (in_codec.name == pref.name);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001435 if (found) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436 VideoCodec codec(pref.payload_type, pref.name,
1437 in_codec.width, in_codec.height, in_codec.framerate,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001438 static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439 if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
1440 AddDefaultFeedbackParams(&codec);
1441 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001442 if (pref.associated_payload_type != -1) {
1443 codec.SetParam(kCodecParamAssociatedPayloadType,
1444 pref.associated_payload_type);
1445 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446 video_codecs_.push_back(codec);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001447 internal_codec_names.insert(codec.name);
1448 }
1449 }
1450 if (encoder_factory_) {
1451 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1452 encoder_factory_->codecs();
1453 for (size_t i = 0; i < codecs.size(); ++i) {
1454 bool is_internal_codec = internal_codec_names.find(codecs[i].name) !=
1455 internal_codec_names.end();
1456 if (!is_internal_codec) {
1457 if (!found)
1458 found = (in_codec.name == codecs[i].name);
1459 VideoCodec codec(
1460 GetExternalVideoPayloadType(static_cast<int>(i)),
1461 codecs[i].name,
1462 codecs[i].max_width,
1463 codecs[i].max_height,
1464 codecs[i].max_fps,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001465 // Use negative preference on external codec to ensure the internal
1466 // codec is preferred.
1467 static_cast<int>(0 - i));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001468 AddDefaultFeedbackParams(&codec);
1469 video_codecs_.push_back(codec);
1470 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 }
1472 }
1473 ASSERT(found);
1474 return true;
1475}
1476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477// Ignore spammy trace messages, mostly from the stats API when we haven't
1478// gotten RTCP info yet from the remote side.
1479bool WebRtcVideoEngine::ShouldIgnoreTrace(const std::string& trace) {
1480 static const char* const kTracesToIgnore[] = {
1481 NULL
1482 };
1483 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1484 if (trace.find(*p) == 0) {
1485 return true;
1486 }
1487 }
1488 return false;
1489}
1490
1491int WebRtcVideoEngine::GetNumOfChannels() {
1492 talk_base::CritScope cs(&channels_crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001493 return static_cast<int>(channels_.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494}
1495
1496void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
1497 int length) {
1498 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1499 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1500 sev = talk_base::LS_ERROR;
1501 else if (level == webrtc::kTraceWarning)
1502 sev = talk_base::LS_WARNING;
1503 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1504 sev = talk_base::LS_INFO;
1505 else if (level == webrtc::kTraceTerseInfo)
1506 sev = talk_base::LS_INFO;
1507
1508 // Skip past boilerplate prefix text
1509 if (length < 72) {
1510 std::string msg(trace, length);
1511 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1512 LOG_V(sev) << msg;
1513 } else {
1514 std::string msg(trace + 71, length - 72);
1515 if (!ShouldIgnoreTrace(msg) &&
1516 (!voice_engine_ || !voice_engine_->ShouldIgnoreTrace(msg))) {
1517 LOG_V(sev) << "webrtc: " << msg;
1518 }
1519 }
1520}
1521
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
1523 webrtc::VideoCodecType type) {
1524 if (decoder_factory_ == NULL) {
1525 return NULL;
1526 }
1527 return decoder_factory_->CreateVideoDecoder(type);
1528}
1529
1530void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
1531 ASSERT(decoder_factory_ != NULL);
1532 if (decoder_factory_ == NULL)
1533 return;
1534 decoder_factory_->DestroyVideoDecoder(decoder);
1535}
1536
1537webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
1538 webrtc::VideoCodecType type) {
1539 if (encoder_factory_ == NULL) {
1540 return NULL;
1541 }
1542 return encoder_factory_->CreateVideoEncoder(type);
1543}
1544
1545void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
1546 ASSERT(encoder_factory_ != NULL);
1547 if (encoder_factory_ == NULL)
1548 return;
1549 encoder_factory_->DestroyVideoEncoder(encoder);
1550}
1551
1552bool WebRtcVideoEngine::IsExternalEncoderCodecType(
1553 webrtc::VideoCodecType type) const {
1554 if (!encoder_factory_)
1555 return false;
1556 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1557 encoder_factory_->codecs();
1558 std::vector<WebRtcVideoEncoderFactory::VideoCodec>::const_iterator it;
1559 for (it = codecs.begin(); it != codecs.end(); ++it) {
1560 if (it->type == type)
1561 return true;
1562 }
1563 return false;
1564}
1565
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566void WebRtcVideoEngine::SetExternalDecoderFactory(
1567 WebRtcVideoDecoderFactory* decoder_factory) {
1568 decoder_factory_ = decoder_factory;
1569}
1570
1571void WebRtcVideoEngine::SetExternalEncoderFactory(
1572 WebRtcVideoEncoderFactory* encoder_factory) {
1573 if (encoder_factory_ == encoder_factory)
1574 return;
1575
1576 if (encoder_factory_) {
1577 encoder_factory_->RemoveObserver(this);
1578 }
1579 encoder_factory_ = encoder_factory;
1580 if (encoder_factory_) {
1581 encoder_factory_->AddObserver(this);
1582 }
1583
1584 // Invoke OnCodecAvailable() here in case the list of codecs is already
1585 // available when the encoder factory is installed. If not the encoder
1586 // factory will invoke the callback later when the codecs become available.
1587 OnCodecsAvailable();
1588}
1589
1590void WebRtcVideoEngine::OnCodecsAvailable() {
1591 // Rebuild codec list while reapplying the current default codec format.
1592 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1593 kVideoCodecPrefs[0].name,
1594 video_codecs_[0].width,
1595 video_codecs_[0].height,
1596 video_codecs_[0].framerate,
1597 0);
1598 if (!RebuildCodecList(max_codec)) {
1599 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
1600 }
1601}
1602
1603// WebRtcVideoMediaChannel
1604
1605WebRtcVideoMediaChannel::WebRtcVideoMediaChannel(
1606 WebRtcVideoEngine* engine,
1607 VoiceMediaChannel* channel)
1608 : engine_(engine),
1609 voice_channel_(channel),
1610 vie_channel_(-1),
1611 nack_enabled_(true),
1612 remb_enabled_(false),
1613 render_started_(false),
1614 first_receive_ssrc_(0),
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001615 num_unsignalled_recv_channels_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001616 send_rtx_type_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 send_red_type_(-1),
1618 send_fec_type_(-1),
1619 send_min_bitrate_(kMinVideoBitrate),
1620 send_start_bitrate_(kStartVideoBitrate),
1621 send_max_bitrate_(kMaxVideoBitrate),
1622 sending_(false),
1623 ratio_w_(0),
1624 ratio_h_(0) {
1625 engine->RegisterChannel(this);
1626}
1627
1628bool WebRtcVideoMediaChannel::Init() {
1629 const uint32 ssrc_key = 0;
1630 return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
1631}
1632
1633WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
1634 const bool send = false;
1635 SetSend(send);
1636 const bool render = false;
1637 SetRender(render);
1638
1639 while (!send_channels_.empty()) {
1640 if (!DeleteSendChannel(send_channels_.begin()->first)) {
1641 LOG(LS_ERROR) << "Unable to delete channel with ssrc key "
1642 << send_channels_.begin()->first;
1643 ASSERT(false);
1644 break;
1645 }
1646 }
1647
1648 // Remove all receive streams and the default channel.
1649 while (!recv_channels_.empty()) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001650 RemoveRecvStreamInternal(recv_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001651 }
1652
1653 // Unregister the channel from the engine.
1654 engine()->UnregisterChannel(this);
1655 if (worker_thread()) {
1656 worker_thread()->Clear(this);
1657 }
1658}
1659
1660bool WebRtcVideoMediaChannel::SetRecvCodecs(
1661 const std::vector<VideoCodec>& codecs) {
1662 receive_codecs_.clear();
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00001663 associated_payload_types_.clear();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001664 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1665 iter != codecs.end(); ++iter) {
1666 if (engine()->FindCodec(*iter)) {
1667 webrtc::VideoCodec wcodec;
1668 if (engine()->ConvertFromCricketVideoCodec(*iter, &wcodec)) {
1669 receive_codecs_.push_back(wcodec);
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00001670 int apt;
1671 if (iter->GetParam(cricket::kCodecParamAssociatedPayloadType, &apt)) {
1672 associated_payload_types_[wcodec.plType] = apt;
1673 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674 }
1675 } else {
1676 LOG(LS_INFO) << "Unknown codec " << iter->name;
1677 return false;
1678 }
1679 }
1680
1681 for (RecvChannelMap::iterator it = recv_channels_.begin();
1682 it != recv_channels_.end(); ++it) {
1683 if (!SetReceiveCodecs(it->second))
1684 return false;
1685 }
1686 return true;
1687}
1688
1689bool WebRtcVideoMediaChannel::SetSendCodecs(
1690 const std::vector<VideoCodec>& codecs) {
1691 // Match with local video codec list.
1692 std::vector<webrtc::VideoCodec> send_codecs;
1693 VideoCodec checked_codec;
1694 VideoCodec current; // defaults to 0x0
1695 if (sending_) {
1696 ConvertToCricketVideoCodec(*send_codec_, &current);
1697 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001698 std::map<int, int> primary_rtx_pt_mapping;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001699 bool nack_enabled = nack_enabled_;
1700 bool remb_enabled = remb_enabled_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1702 iter != codecs.end(); ++iter) {
1703 if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
1704 send_red_type_ = iter->id;
1705 } else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
1706 send_fec_type_ = iter->id;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001707 } else if (_stricmp(iter->name.c_str(), kRtxCodecName) == 0) {
1708 int rtx_type = iter->id;
1709 int rtx_primary_type = -1;
1710 if (iter->GetParam(kCodecParamAssociatedPayloadType, &rtx_primary_type)) {
1711 primary_rtx_pt_mapping[rtx_primary_type] = rtx_type;
1712 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713 } else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
1714 webrtc::VideoCodec wcodec;
1715 if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
1716 if (send_codecs.empty()) {
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001717 nack_enabled = IsNackEnabled(checked_codec);
1718 remb_enabled = IsRembEnabled(checked_codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 }
1720 send_codecs.push_back(wcodec);
1721 }
1722 } else {
1723 LOG(LS_WARNING) << "Unknown codec " << iter->name;
1724 }
1725 }
1726
1727 // Fail if we don't have a match.
1728 if (send_codecs.empty()) {
1729 LOG(LS_WARNING) << "No matching codecs available";
1730 return false;
1731 }
1732
1733 // Recv protection.
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001734 // Do not update if the status is same as previously configured.
1735 if (nack_enabled_ != nack_enabled) {
1736 for (RecvChannelMap::iterator it = recv_channels_.begin();
1737 it != recv_channels_.end(); ++it) {
1738 int channel_id = it->second->channel_id();
1739 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1740 nack_enabled)) {
1741 return false;
1742 }
1743 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1744 kNotSending,
1745 remb_enabled_) != 0) {
1746 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
1747 return false;
1748 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001749 }
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001750 nack_enabled_ = nack_enabled;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001751 }
1752
1753 // Send settings.
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001754 // Do not update if the status is same as previously configured.
1755 if (remb_enabled_ != remb_enabled) {
1756 for (SendChannelMap::iterator iter = send_channels_.begin();
1757 iter != send_channels_.end(); ++iter) {
1758 int channel_id = iter->second->channel_id();
1759 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1760 nack_enabled_)) {
1761 return false;
1762 }
1763 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1764 remb_enabled,
1765 remb_enabled) != 0) {
1766 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled, remb_enabled);
1767 return false;
1768 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001769 }
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001770 remb_enabled_ = remb_enabled;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771 }
1772
1773 // Select the first matched codec.
1774 webrtc::VideoCodec& codec(send_codecs[0]);
1775
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001776 // Set RTX payload type if primary now active. This value will be used in
1777 // SetSendCodec.
1778 std::map<int, int>::const_iterator rtx_it =
1779 primary_rtx_pt_mapping.find(static_cast<int>(codec.plType));
1780 if (rtx_it != primary_rtx_pt_mapping.end()) {
1781 send_rtx_type_ = rtx_it->second;
1782 }
1783
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784 if (!SetSendCodec(
1785 codec, codec.minBitrate, codec.startBitrate, codec.maxBitrate)) {
1786 return false;
1787 }
1788
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789 LogSendCodecChange("SetSendCodecs()");
1790
1791 return true;
1792}
1793
1794bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
1795 if (!send_codec_) {
1796 return false;
1797 }
1798 ConvertToCricketVideoCodec(*send_codec_, send_codec);
1799 return true;
1800}
1801
1802bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
1803 const VideoFormat& format) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
1805 if (!send_channel) {
1806 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
1807 return false;
1808 }
1809 send_channel->set_video_format(format);
1810 return true;
1811}
1812
1813bool WebRtcVideoMediaChannel::SetRender(bool render) {
1814 if (render == render_started_) {
1815 return true; // no action required
1816 }
1817
1818 bool ret = true;
1819 for (RecvChannelMap::iterator it = recv_channels_.begin();
1820 it != recv_channels_.end(); ++it) {
1821 if (render) {
1822 if (engine()->vie()->render()->StartRender(
1823 it->second->channel_id()) != 0) {
1824 LOG_RTCERR1(StartRender, it->second->channel_id());
1825 ret = false;
1826 }
1827 } else {
1828 if (engine()->vie()->render()->StopRender(
1829 it->second->channel_id()) != 0) {
1830 LOG_RTCERR1(StopRender, it->second->channel_id());
1831 ret = false;
1832 }
1833 }
1834 }
1835 if (ret) {
1836 render_started_ = render;
1837 }
1838
1839 return ret;
1840}
1841
1842bool WebRtcVideoMediaChannel::SetSend(bool send) {
1843 if (!HasReadySendChannels() && send) {
1844 LOG(LS_ERROR) << "No stream added";
1845 return false;
1846 }
1847 if (send == sending()) {
1848 return true; // No action required.
1849 }
1850
1851 if (send) {
1852 // We've been asked to start sending.
1853 // SetSendCodecs must have been called already.
1854 if (!send_codec_) {
1855 return false;
1856 }
1857 // Start send now.
1858 if (!StartSend()) {
1859 return false;
1860 }
1861 } else {
1862 // We've been asked to stop sending.
1863 if (!StopSend()) {
1864 return false;
1865 }
1866 }
1867 sending_ = send;
1868
1869 return true;
1870}
1871
1872bool WebRtcVideoMediaChannel::AddSendStream(const StreamParams& sp) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001873 if (sp.first_ssrc() == 0) {
1874 LOG(LS_ERROR) << "AddSendStream with 0 ssrc is not supported.";
1875 return false;
1876 }
1877
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 LOG(LS_INFO) << "AddSendStream " << sp.ToString();
1879
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001880 if (!IsOneSsrcStream(sp) && !IsSimulcastStream(sp)) {
1881 LOG(LS_ERROR) << "AddSendStream: bad local stream parameters";
1882 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001883 }
1884
1885 uint32 ssrc_key;
1886 if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
1887 LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
1888 return false;
1889 }
1890 // If the default channel is already used for sending create a new channel
1891 // otherwise use the default channel for sending.
1892 int channel_id = -1;
1893 if (send_channels_[0]->stream_params() == NULL) {
1894 channel_id = vie_channel_;
1895 } else {
1896 if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
1897 LOG(LS_ERROR) << "AddSendStream: unable to create channel";
1898 return false;
1899 }
1900 }
1901 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1902 // Set the send (local) SSRC.
1903 // If there are multiple send SSRCs, we can only set the first one here, and
1904 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
1905 // (with a codec requires multiple SSRC(s)).
1906 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1907 sp.first_ssrc()) != 0) {
1908 LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
1909 return false;
1910 }
1911
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001912 // Set the corresponding RTX SSRC.
1913 if (!SetLocalRtxSsrc(channel_id, sp, sp.first_ssrc(), 0)) {
1914 return false;
1915 }
1916
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917 // Set RTCP CName.
1918 if (engine()->vie()->rtp()->SetRTCPCName(channel_id,
1919 sp.cname.c_str()) != 0) {
1920 LOG_RTCERR2(SetRTCPCName, channel_id, sp.cname.c_str());
1921 return false;
1922 }
1923
1924 // At this point the channel's local SSRC has been updated. If the channel is
1925 // the default channel make sure that all the receive channels are updated as
1926 // well. Receive channels have to have the same SSRC as the default channel in
1927 // order to send receiver reports with this SSRC.
1928 if (IsDefaultChannel(channel_id)) {
1929 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
1930 it != recv_channels_.end(); ++it) {
1931 WebRtcVideoChannelRecvInfo* info = it->second;
1932 int channel_id = info->channel_id();
1933 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1934 sp.first_ssrc()) != 0) {
1935 LOG_RTCERR1(SetLocalSSRC, it->first);
1936 return false;
1937 }
1938 }
1939 }
1940
1941 send_channel->set_stream_params(sp);
1942
1943 // Reset send codec after stream parameters changed.
1944 if (send_codec_) {
1945 if (!SetSendCodec(send_channel, *send_codec_, send_min_bitrate_,
1946 send_start_bitrate_, send_max_bitrate_)) {
1947 return false;
1948 }
1949 LogSendCodecChange("SetSendStreamFormat()");
1950 }
1951
1952 if (sending_) {
1953 return StartSend(send_channel);
1954 }
1955 return true;
1956}
1957
1958bool WebRtcVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001959 if (ssrc == 0) {
1960 LOG(LS_ERROR) << "RemoveSendStream with 0 ssrc is not supported.";
1961 return false;
1962 }
1963
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 uint32 ssrc_key;
1965 if (!GetSendChannelKey(ssrc, &ssrc_key)) {
1966 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1967 << " which doesn't exist.";
1968 return false;
1969 }
1970 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1971 int channel_id = send_channel->channel_id();
1972 if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
1973 // Default channel will still exist. However, if stream_params() is NULL
1974 // there is no stream to remove.
1975 return false;
1976 }
1977 if (sending_) {
1978 StopSend(send_channel);
1979 }
1980
1981 const WebRtcVideoChannelSendInfo::EncoderMap& encoder_map =
1982 send_channel->registered_encoders();
1983 for (WebRtcVideoChannelSendInfo::EncoderMap::const_iterator it =
1984 encoder_map.begin(); it != encoder_map.end(); ++it) {
1985 if (engine()->vie()->ext_codec()->DeRegisterExternalSendCodec(
1986 channel_id, it->first) != 0) {
1987 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
1988 }
1989 engine()->DestroyExternalEncoder(it->second);
1990 }
1991 send_channel->ClearRegisteredEncoders();
1992
1993 // The receive channels depend on the default channel, recycle it instead.
1994 if (IsDefaultChannel(channel_id)) {
1995 SetCapturer(GetDefaultChannelSsrc(), NULL);
1996 send_channel->ClearStreamParams();
1997 } else {
1998 return DeleteSendChannel(ssrc_key);
1999 }
2000 return true;
2001}
2002
2003bool WebRtcVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00002004 if (sp.first_ssrc() == 0) {
2005 LOG(LS_ERROR) << "AddRecvStream with 0 ssrc is not supported.";
2006 return false;
2007 }
2008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 // TODO(zhurunz) Remove this once BWE works properly across different send
2010 // and receive channels.
2011 // Reuse default channel for recv stream in 1:1 call.
2012 if (!InConferenceMode() && first_receive_ssrc_ == 0) {
2013 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2014 << " reuse default channel #"
2015 << vie_channel_;
2016 first_receive_ssrc_ = sp.first_ssrc();
2017 if (render_started_) {
2018 if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
2019 LOG_RTCERR1(StartRender, vie_channel_);
2020 }
2021 }
2022 return true;
2023 }
2024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025 int channel_id = -1;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002026 RecvChannelMap::iterator channel_iterator =
2027 recv_channels_.find(sp.first_ssrc());
2028 if (channel_iterator == recv_channels_.end() &&
2029 first_receive_ssrc_ != sp.first_ssrc()) {
2030 // TODO(perkj): Implement recv media from multiple media SSRCs per stream.
2031 // NOTE: We have two SSRCs per stream when RTX is enabled.
2032 if (!IsOneSsrcStream(sp)) {
2033 LOG(LS_ERROR) << "WebRtcVideoMediaChannel supports one primary SSRC per"
2034 << " stream and one FID SSRC per primary SSRC.";
2035 return false;
2036 }
2037
2038 // Create a new channel for receiving video data.
2039 // In order to get the bandwidth estimation work fine for
2040 // receive only channels, we connect all receiving channels
2041 // to our master send channel.
2042 if (!CreateChannel(sp.first_ssrc(), MD_RECV, &channel_id)) {
2043 return false;
2044 }
2045 } else {
2046 // Already exists.
2047 if (first_receive_ssrc_ == sp.first_ssrc()) {
2048 return false;
2049 }
2050 // Early receive added channel.
2051 channel_id = (*channel_iterator).second->channel_id();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002052 }
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00002053 channel_iterator = recv_channels_.find(sp.first_ssrc());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002054
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002055 // Set the corresponding RTX SSRC.
2056 uint32 rtx_ssrc;
2057 bool has_rtx = sp.GetFidSsrc(sp.first_ssrc(), &rtx_ssrc);
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00002058 if (has_rtx) {
2059 LOG(LS_INFO) << "Setting rtx ssrc " << rtx_ssrc << " for stream "
2060 << sp.first_ssrc();
2061 if (engine()->vie()->rtp()->SetRemoteSSRCType(
2062 channel_id, webrtc::kViEStreamTypeRtx, rtx_ssrc) != 0) {
2063 LOG_RTCERR3(SetRemoteSSRCType, channel_id, webrtc::kViEStreamTypeRtx,
2064 rtx_ssrc);
2065 return false;
2066 }
2067 rtx_to_primary_ssrc_[rtx_ssrc] = sp.first_ssrc();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002068 }
2069
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002070 // Get the default renderer.
2071 VideoRenderer* default_renderer = NULL;
2072 if (InConferenceMode()) {
2073 // The recv_channels_ size start out being 1, so if it is two here this
2074 // is the first receive channel created (vie_channel_ is not used for
2075 // receiving in a conference call). This means that the renderer stored
2076 // inside vie_channel_ should be used for the just created channel.
2077 if (recv_channels_.size() == 2 &&
2078 recv_channels_.find(0) != recv_channels_.end()) {
2079 GetRenderer(0, &default_renderer);
2080 }
2081 }
2082
2083 // The first recv stream reuses the default renderer (if a default renderer
2084 // has been set).
2085 if (default_renderer) {
2086 SetRenderer(sp.first_ssrc(), default_renderer);
2087 }
2088
2089 LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
2090 << " registered to VideoEngine channel #"
2091 << channel_id << " and connected to channel #" << vie_channel_;
2092
2093 return true;
2094}
2095
2096bool WebRtcVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00002097 if (ssrc == 0) {
2098 LOG(LS_ERROR) << "RemoveRecvStream with 0 ssrc is not supported.";
2099 return false;
2100 }
2101 return RemoveRecvStreamInternal(ssrc);
2102}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002103
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00002104bool WebRtcVideoMediaChannel::RemoveRecvStreamInternal(uint32 ssrc) {
2105 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106 if (it == recv_channels_.end()) {
2107 // TODO(perkj): Remove this once BWE works properly across different send
2108 // and receive channels.
2109 // The default channel is reused for recv stream in 1:1 call.
2110 if (first_receive_ssrc_ == ssrc) {
2111 first_receive_ssrc_ = 0;
2112 // Need to stop the renderer and remove it since the render window can be
2113 // deleted after this.
2114 if (render_started_) {
2115 if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
2116 LOG_RTCERR1(StopRender, it->second->channel_id());
2117 }
2118 }
2119 recv_channels_[0]->SetRenderer(NULL);
2120 return true;
2121 }
2122 return false;
2123 }
2124 WebRtcVideoChannelRecvInfo* info = it->second;
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00002125
2126 // Remove any RTX SSRC mappings to this stream.
2127 SsrcMap::iterator rtx_it = rtx_to_primary_ssrc_.begin();
2128 while (rtx_it != rtx_to_primary_ssrc_.end()) {
2129 if (rtx_it->second == ssrc) {
2130 rtx_to_primary_ssrc_.erase(rtx_it++);
2131 } else {
2132 ++rtx_it;
2133 }
2134 }
2135
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 int channel_id = info->channel_id();
2137 if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
2138 LOG_RTCERR1(RemoveRenderer, channel_id);
2139 }
2140
2141 if (engine()->vie()->network()->DeregisterSendTransport(channel_id) !=0) {
2142 LOG_RTCERR1(DeRegisterSendTransport, channel_id);
2143 }
2144
2145 if (engine()->vie()->codec()->DeregisterDecoderObserver(
2146 channel_id) != 0) {
2147 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
2148 }
2149
2150 const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
2151 info->registered_decoders();
2152 for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
2153 decoder_map.begin(); it != decoder_map.end(); ++it) {
2154 if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
2155 channel_id, it->first) != 0) {
2156 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
2157 }
2158 engine()->DestroyExternalDecoder(it->second);
2159 }
2160 info->ClearRegisteredDecoders();
2161
2162 LOG(LS_INFO) << "Removing video stream " << ssrc
2163 << " with VideoEngine channel #"
2164 << channel_id;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002165 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 if (engine()->vie()->base()->DeleteChannel(channel_id) == -1) {
2167 LOG_RTCERR1(DeleteChannel, channel_id);
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002168 ret = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169 }
2170 // Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
2171 delete info;
2172 recv_channels_.erase(it);
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002173 return ret;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002174}
2175
2176bool WebRtcVideoMediaChannel::StartSend() {
2177 bool success = true;
2178 for (SendChannelMap::iterator iter = send_channels_.begin();
2179 iter != send_channels_.end(); ++iter) {
2180 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2181 if (!StartSend(send_channel)) {
2182 success = false;
2183 }
2184 }
2185 return success;
2186}
2187
2188bool WebRtcVideoMediaChannel::StartSend(
2189 WebRtcVideoChannelSendInfo* send_channel) {
2190 const int channel_id = send_channel->channel_id();
2191 if (engine()->vie()->base()->StartSend(channel_id) != 0) {
2192 LOG_RTCERR1(StartSend, channel_id);
2193 return false;
2194 }
2195
2196 send_channel->set_sending(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197 return true;
2198}
2199
2200bool WebRtcVideoMediaChannel::StopSend() {
2201 bool success = true;
2202 for (SendChannelMap::iterator iter = send_channels_.begin();
2203 iter != send_channels_.end(); ++iter) {
2204 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2205 if (!StopSend(send_channel)) {
2206 success = false;
2207 }
2208 }
2209 return success;
2210}
2211
2212bool WebRtcVideoMediaChannel::StopSend(
2213 WebRtcVideoChannelSendInfo* send_channel) {
2214 const int channel_id = send_channel->channel_id();
2215 if (engine()->vie()->base()->StopSend(channel_id) != 0) {
2216 LOG_RTCERR1(StopSend, channel_id);
2217 return false;
2218 }
2219 send_channel->set_sending(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 return true;
2221}
2222
2223bool WebRtcVideoMediaChannel::SendIntraFrame() {
2224 bool success = true;
2225 for (SendChannelMap::iterator iter = send_channels_.begin();
2226 iter != send_channels_.end();
2227 ++iter) {
2228 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2229 const int channel_id = send_channel->channel_id();
2230 if (engine()->vie()->codec()->SendKeyFrame(channel_id) != 0) {
2231 LOG_RTCERR1(SendKeyFrame, channel_id);
2232 success = false;
2233 }
2234 }
2235 return success;
2236}
2237
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238bool WebRtcVideoMediaChannel::HasReadySendChannels() {
2239 return !send_channels_.empty() &&
2240 ((send_channels_.size() > 1) ||
2241 (send_channels_[0]->stream_params() != NULL));
2242}
2243
2244bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
2245 uint32* key) {
2246 *key = 0;
2247 // If a send channel is not ready to send it will not have local_ssrc
2248 // registered to it.
2249 if (!HasReadySendChannels()) {
2250 return false;
2251 }
2252 // The default channel is stored with key 0. The key therefore does not match
2253 // the SSRC associated with the default channel. Check if the SSRC provided
2254 // corresponds to the default channel's SSRC.
2255 if (local_ssrc == GetDefaultChannelSsrc()) {
2256 return true;
2257 }
2258 if (send_channels_.find(local_ssrc) == send_channels_.end()) {
2259 for (SendChannelMap::iterator iter = send_channels_.begin();
2260 iter != send_channels_.end(); ++iter) {
2261 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2262 if (send_channel->has_ssrc(local_ssrc)) {
2263 *key = iter->first;
2264 return true;
2265 }
2266 }
2267 return false;
2268 }
2269 // The key was found in the above std::map::find call. This means that the
2270 // ssrc is the key.
2271 *key = local_ssrc;
2272 return true;
2273}
2274
2275WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 uint32 local_ssrc) {
2277 uint32 key;
2278 if (!GetSendChannelKey(local_ssrc, &key)) {
2279 return NULL;
2280 }
2281 return send_channels_[key];
2282}
2283
2284bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
2285 uint32* key) {
2286 if (GetSendChannelKey(local_ssrc, key)) {
2287 // If there is a key corresponding to |local_ssrc|, the SSRC is already in
2288 // use. SSRCs need to be unique in a session and at this point a duplicate
2289 // SSRC has been detected.
2290 return false;
2291 }
2292 if (send_channels_[0]->stream_params() == NULL) {
2293 // key should be 0 here as the default channel should be re-used whenever it
2294 // is not used.
2295 *key = 0;
2296 return true;
2297 }
2298 // SSRC is currently not in use and the default channel is already in use. Use
2299 // the SSRC as key since it is supposed to be unique in a session.
2300 *key = local_ssrc;
2301 return true;
2302}
2303
wu@webrtc.org24301a62013-12-13 19:17:43 +00002304int WebRtcVideoMediaChannel::GetSendChannelNum(VideoCapturer* capturer) {
2305 int num = 0;
2306 for (SendChannelMap::iterator iter = send_channels_.begin();
2307 iter != send_channels_.end(); ++iter) {
2308 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2309 if (send_channel->video_capturer() == capturer) {
2310 ++num;
2311 }
2312 }
2313 return num;
2314}
2315
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002316uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
2317 WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
2318 const StreamParams* sp = send_channel->stream_params();
2319 if (sp == NULL) {
2320 // This happens if no send stream is currently registered.
2321 return 0;
2322 }
2323 return sp->first_ssrc();
2324}
2325
2326bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
2327 if (send_channels_.find(ssrc_key) == send_channels_.end()) {
2328 return false;
2329 }
2330 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
wu@webrtc.org24301a62013-12-13 19:17:43 +00002331 MaybeDisconnectCapturer(send_channel->video_capturer());
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +00002332 send_channel->set_video_capturer(NULL, engine()->vie());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333
2334 int channel_id = send_channel->channel_id();
2335 int capture_id = send_channel->capture_id();
2336 if (engine()->vie()->codec()->DeregisterEncoderObserver(
2337 channel_id) != 0) {
2338 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
2339 }
2340
2341 // Destroy the external capture interface.
2342 if (engine()->vie()->capture()->DisconnectCaptureDevice(
2343 channel_id) != 0) {
2344 LOG_RTCERR1(DisconnectCaptureDevice, channel_id);
2345 }
2346 if (engine()->vie()->capture()->ReleaseCaptureDevice(
2347 capture_id) != 0) {
2348 LOG_RTCERR1(ReleaseCaptureDevice, capture_id);
2349 }
2350
2351 // The default channel is stored in both |send_channels_| and
2352 // |recv_channels_|. To make sure it is only deleted once from vie let the
2353 // delete call happen when tearing down |recv_channels_| and not here.
2354 if (!IsDefaultChannel(channel_id)) {
2355 engine_->vie()->base()->DeleteChannel(channel_id);
2356 }
2357 delete send_channel;
2358 send_channels_.erase(ssrc_key);
2359 return true;
2360}
2361
2362bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
2363 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2364 if (!send_channel) {
2365 return false;
2366 }
2367 VideoCapturer* capturer = send_channel->video_capturer();
2368 if (capturer == NULL) {
2369 return false;
2370 }
wu@webrtc.org24301a62013-12-13 19:17:43 +00002371 MaybeDisconnectCapturer(capturer);
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +00002372 send_channel->set_video_capturer(NULL, engine()->vie());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2374 if (send_codec_) {
2375 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2376 }
2377 return true;
2378}
2379
2380bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
2381 VideoRenderer* renderer) {
2382 if (recv_channels_.find(ssrc) == recv_channels_.end()) {
2383 // TODO(perkj): Remove this once BWE works properly across different send
2384 // and receive channels.
2385 // The default channel is reused for recv stream in 1:1 call.
2386 if (first_receive_ssrc_ == ssrc &&
2387 recv_channels_.find(0) != recv_channels_.end()) {
2388 LOG(LS_INFO) << "SetRenderer " << ssrc
2389 << " reuse default channel #"
2390 << vie_channel_;
2391 recv_channels_[0]->SetRenderer(renderer);
2392 return true;
2393 }
2394 return false;
2395 }
2396
2397 recv_channels_[ssrc]->SetRenderer(renderer);
2398 return true;
2399}
2400
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002401bool WebRtcVideoMediaChannel::GetStats(const StatsOptions& options,
2402 VideoMediaInfo* info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002403 // Get sender statistics and build VideoSenderInfo.
2404 unsigned int total_bitrate_sent = 0;
2405 unsigned int video_bitrate_sent = 0;
2406 unsigned int fec_bitrate_sent = 0;
2407 unsigned int nack_bitrate_sent = 0;
2408 unsigned int estimated_send_bandwidth = 0;
2409 unsigned int target_enc_bitrate = 0;
2410 if (send_codec_) {
2411 for (SendChannelMap::const_iterator iter = send_channels_.begin();
2412 iter != send_channels_.end(); ++iter) {
2413 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2414 const int channel_id = send_channel->channel_id();
2415 VideoSenderInfo sinfo;
2416 const StreamParams* send_params = send_channel->stream_params();
2417 if (send_params == NULL) {
2418 // This should only happen if the default vie channel is not in use.
2419 // This can happen if no streams have ever been added or the stream
2420 // corresponding to the default channel has been removed. Note that
2421 // there may be non-default vie channels in use when this happen so
2422 // asserting send_channels_.size() == 1 is not correct and neither is
2423 // breaking out of the loop.
2424 ASSERT(channel_id == vie_channel_);
2425 continue;
2426 }
2427 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2428 if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
2429 packets_sent, bytes_recv,
2430 packets_recv) != 0) {
2431 LOG_RTCERR1(GetRTPStatistics, vie_channel_);
2432 continue;
2433 }
2434 WebRtcLocalStreamInfo* channel_stream_info =
2435 send_channel->local_stream_info();
2436
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002437 for (size_t i = 0; i < send_params->ssrcs.size(); ++i) {
2438 sinfo.add_ssrc(send_params->ssrcs[i]);
2439 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 sinfo.codec_name = send_codec_->plName;
2441 sinfo.bytes_sent = bytes_sent;
2442 sinfo.packets_sent = packets_sent;
2443 sinfo.packets_cached = -1;
2444 sinfo.packets_lost = -1;
2445 sinfo.fraction_lost = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 sinfo.rtt_ms = -1;
wu@webrtc.org987f2c92014-03-28 16:22:19 +00002447
2448 VideoCapturer* video_capturer = send_channel->video_capturer();
2449 if (video_capturer) {
buildbot@webrtc.org0b53bd22014-05-06 17:12:36 +00002450 VideoFormat last_captured_frame_format;
wu@webrtc.org987f2c92014-03-28 16:22:19 +00002451 video_capturer->GetStats(&sinfo.adapt_frame_drops,
2452 &sinfo.effects_frame_drops,
buildbot@webrtc.org0b53bd22014-05-06 17:12:36 +00002453 &sinfo.capturer_frame_time,
2454 &last_captured_frame_format);
2455 sinfo.input_frame_width = last_captured_frame_format.width;
2456 sinfo.input_frame_height = last_captured_frame_format.height;
2457 } else {
2458 sinfo.input_frame_width = 0;
2459 sinfo.input_frame_height = 0;
wu@webrtc.org987f2c92014-03-28 16:22:19 +00002460 }
2461
2462 webrtc::VideoCodec vie_codec;
wu@webrtc.org987f2c92014-03-28 16:22:19 +00002463 if (!video_capturer || video_capturer->IsMuted()) {
2464 sinfo.send_frame_width = 0;
2465 sinfo.send_frame_height = 0;
2466 } else if (engine()->vie()->codec()->GetSendCodec(channel_id,
2467 vie_codec) == 0) {
2468 sinfo.send_frame_width = vie_codec.width;
2469 sinfo.send_frame_height = vie_codec.height;
2470 } else {
2471 sinfo.send_frame_width = -1;
2472 sinfo.send_frame_height = -1;
2473 LOG_RTCERR1(GetSendCodec, channel_id);
2474 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002475 sinfo.framerate_input = channel_stream_info->framerate();
2476 sinfo.framerate_sent = send_channel->encoder_observer()->framerate();
2477 sinfo.nominal_bitrate = send_channel->encoder_observer()->bitrate();
2478 sinfo.preferred_bitrate = send_max_bitrate_;
2479 sinfo.adapt_reason = send_channel->CurrentAdaptReason();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002480 sinfo.capture_jitter_ms = -1;
2481 sinfo.avg_encode_ms = -1;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002482 sinfo.encode_usage_percent = -1;
2483 sinfo.capture_queue_delay_ms_per_s = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002484
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002485 int capture_jitter_ms = 0;
2486 int avg_encode_time_ms = 0;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002487 int encode_usage_percent = 0;
2488 int capture_queue_delay_ms_per_s = 0;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002489 if (engine()->vie()->base()->CpuOveruseMeasures(
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002490 channel_id,
2491 &capture_jitter_ms,
2492 &avg_encode_time_ms,
2493 &encode_usage_percent,
2494 &capture_queue_delay_ms_per_s) == 0) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002495 sinfo.capture_jitter_ms = capture_jitter_ms;
2496 sinfo.avg_encode_ms = avg_encode_time_ms;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002497 sinfo.encode_usage_percent = encode_usage_percent;
2498 sinfo.capture_queue_delay_ms_per_s = capture_queue_delay_ms_per_s;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002499 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002500
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002501 webrtc::RtcpPacketTypeCounter rtcp_sent;
2502 webrtc::RtcpPacketTypeCounter rtcp_received;
2503 if (engine()->vie()->rtp()->GetRtcpPacketTypeCounters(
2504 channel_id, &rtcp_sent, &rtcp_received) == 0) {
2505 sinfo.firs_rcvd = rtcp_received.fir_packets;
2506 sinfo.plis_rcvd = rtcp_received.pli_packets;
2507 sinfo.nacks_rcvd = rtcp_received.nack_packets;
2508 } else {
2509 sinfo.firs_rcvd = -1;
2510 sinfo.plis_rcvd = -1;
2511 sinfo.nacks_rcvd = -1;
2512 LOG_RTCERR1(GetRtcpPacketTypeCounters, channel_id);
2513 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002514
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002515 // Get received RTCP statistics for the sender (reported by the remote
2516 // client in a RTCP packet), if available.
2517 // It's not a fatal error if we can't, since RTCP may not have arrived
2518 // yet.
2519 webrtc::RtcpStatistics outgoing_stream_rtcp_stats;
2520 int outgoing_stream_rtt_ms;
2521
2522 if (engine_->vie()->rtp()->GetSendChannelRtcpStatistics(
2523 channel_id,
2524 outgoing_stream_rtcp_stats,
2525 outgoing_stream_rtt_ms) == 0) {
2526 // Convert Q8 to float.
2527 sinfo.packets_lost = outgoing_stream_rtcp_stats.cumulative_lost;
2528 sinfo.fraction_lost = static_cast<float>(
2529 outgoing_stream_rtcp_stats.fraction_lost) / (1 << 8);
2530 sinfo.rtt_ms = outgoing_stream_rtt_ms;
2531 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002532 info->senders.push_back(sinfo);
2533
2534 unsigned int channel_total_bitrate_sent = 0;
2535 unsigned int channel_video_bitrate_sent = 0;
2536 unsigned int channel_fec_bitrate_sent = 0;
2537 unsigned int channel_nack_bitrate_sent = 0;
2538 if (engine_->vie()->rtp()->GetBandwidthUsage(
2539 channel_id, channel_total_bitrate_sent, channel_video_bitrate_sent,
2540 channel_fec_bitrate_sent, channel_nack_bitrate_sent) == 0) {
2541 total_bitrate_sent += channel_total_bitrate_sent;
2542 video_bitrate_sent += channel_video_bitrate_sent;
2543 fec_bitrate_sent += channel_fec_bitrate_sent;
2544 nack_bitrate_sent += channel_nack_bitrate_sent;
2545 } else {
2546 LOG_RTCERR1(GetBandwidthUsage, channel_id);
2547 }
2548
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 unsigned int target_enc_stream_bitrate = 0;
2550 if (engine_->vie()->codec()->GetCodecTargetBitrate(
2551 channel_id, &target_enc_stream_bitrate) == 0) {
2552 target_enc_bitrate += target_enc_stream_bitrate;
2553 } else {
2554 LOG_RTCERR1(GetCodecTargetBitrate, channel_id);
2555 }
2556 }
buildbot@webrtc.orga18b4c92014-05-06 17:48:14 +00002557 if (!send_channels_.empty()) {
2558 // GetEstimatedSendBandwidth returns the estimated bandwidth for all video
2559 // engine channels in a channel group. Any valid channel id will do as it
2560 // is only used to access the right group of channels.
2561 const int channel_id = send_channels_.begin()->second->channel_id();
2562 // Get the send bandwidth available for this MediaChannel.
2563 if (engine_->vie()->rtp()->GetEstimatedSendBandwidth(
2564 channel_id, &estimated_send_bandwidth) != 0) {
2565 LOG_RTCERR1(GetEstimatedSendBandwidth, channel_id);
2566 }
2567 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002568 } else {
2569 LOG(LS_WARNING) << "GetStats: sender information not ready.";
2570 }
2571
2572 // Get the SSRC and stats for each receiver, based on our own calculations.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
2574 it != recv_channels_.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002575 WebRtcVideoChannelRecvInfo* channel = it->second;
2576
2577 unsigned int ssrc;
2578 // Get receiver statistics and build VideoReceiverInfo, if we have data.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002579 // Skip the default channel (ssrc == 0).
2580 if (engine_->vie()->rtp()->GetRemoteSSRC(
2581 channel->channel_id(), ssrc) != 0 ||
2582 ssrc == 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002583 continue;
2584
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002585 webrtc::StreamDataCounters sent;
2586 webrtc::StreamDataCounters received;
2587 if (engine_->vie()->rtp()->GetRtpStatistics(channel->channel_id(),
2588 sent, received) != 0) {
2589 LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
2590 return false;
2591 }
2592 VideoReceiverInfo rinfo;
2593 rinfo.add_ssrc(ssrc);
2594 rinfo.bytes_rcvd = received.bytes;
2595 rinfo.packets_rcvd = received.packets;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002596 rinfo.packets_lost = -1;
2597 rinfo.packets_concealed = -1;
2598 rinfo.fraction_lost = -1; // from SentRTCP
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002599 rinfo.frame_width = channel->render_adapter()->width();
2600 rinfo.frame_height = channel->render_adapter()->height();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 int fps = channel->render_adapter()->framerate();
2602 rinfo.framerate_decoded = fps;
2603 rinfo.framerate_output = fps;
buildbot@webrtc.org0581f0b2014-05-06 21:36:31 +00002604 rinfo.capture_start_ntp_time_ms =
2605 channel->render_adapter()->capture_start_ntp_time_ms();
wu@webrtc.org97077a32013-10-25 21:18:33 +00002606 channel->decoder_observer()->ExportTo(&rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002607
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002608 webrtc::RtcpPacketTypeCounter rtcp_sent;
2609 webrtc::RtcpPacketTypeCounter rtcp_received;
2610 if (engine()->vie()->rtp()->GetRtcpPacketTypeCounters(
2611 channel->channel_id(), &rtcp_sent, &rtcp_received) == 0) {
2612 rinfo.firs_sent = rtcp_sent.fir_packets;
2613 rinfo.plis_sent = rtcp_sent.pli_packets;
2614 rinfo.nacks_sent = rtcp_sent.nack_packets;
2615 } else {
2616 rinfo.firs_sent = -1;
2617 rinfo.plis_sent = -1;
2618 rinfo.nacks_sent = -1;
2619 LOG_RTCERR1(GetRtcpPacketTypeCounters, channel->channel_id());
2620 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002621
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002622 // Get our locally created statistics of the received RTP stream.
2623 webrtc::RtcpStatistics incoming_stream_rtcp_stats;
2624 int incoming_stream_rtt_ms;
2625 if (engine_->vie()->rtp()->GetReceiveChannelRtcpStatistics(
2626 channel->channel_id(),
2627 incoming_stream_rtcp_stats,
2628 incoming_stream_rtt_ms) == 0) {
2629 // Convert Q8 to float.
2630 rinfo.packets_lost = incoming_stream_rtcp_stats.cumulative_lost;
2631 rinfo.fraction_lost = static_cast<float>(
2632 incoming_stream_rtcp_stats.fraction_lost) / (1 << 8);
2633 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002634 info->receivers.push_back(rinfo);
buildbot@webrtc.orga18b4c92014-05-06 17:48:14 +00002635 }
2636 unsigned int estimated_recv_bandwidth = 0;
2637 if (!recv_channels_.empty()) {
2638 // GetEstimatedReceiveBandwidth returns the estimated bandwidth for all
2639 // video engine channels in a channel group. Any valid channel id will do as
2640 // it is only used to access the right group of channels.
2641 const int channel_id = recv_channels_.begin()->second->channel_id();
2642 // Gets the estimated receive bandwidth for the MediaChannel.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002643 if (engine_->vie()->rtp()->GetEstimatedReceiveBandwidth(
buildbot@webrtc.orga18b4c92014-05-06 17:48:14 +00002644 channel_id, &estimated_recv_bandwidth) != 0) {
2645 LOG_RTCERR1(GetEstimatedReceiveBandwidth, channel_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002646 }
2647 }
buildbot@webrtc.orga18b4c92014-05-06 17:48:14 +00002648
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002649 // Build BandwidthEstimationInfo.
2650 // TODO(zhurunz): Add real unittest for this.
2651 BandwidthEstimationInfo bwe;
2652
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002653 // TODO(jiayl): remove the condition when the necessary changes are available
2654 // outside the dev branch.
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002655 if (options.include_received_propagation_stats) {
2656 webrtc::ReceiveBandwidthEstimatorStats additional_stats;
2657 // Only call for the default channel because the returned stats are
2658 // collected for all the channels using the same estimator.
2659 if (engine_->vie()->rtp()->GetReceiveBandwidthEstimatorStats(
mallinath@webrtc.org92fdfeb2014-02-17 18:49:41 +00002660 recv_channels_[0]->channel_id(), &additional_stats) == 0) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002661 bwe.total_received_propagation_delta_ms =
2662 additional_stats.total_propagation_time_delta_ms;
2663 bwe.recent_received_propagation_delta_ms.swap(
2664 additional_stats.recent_propagation_time_delta_ms);
2665 bwe.recent_received_packet_group_arrival_time_ms.swap(
2666 additional_stats.recent_arrival_time_ms);
2667 }
2668 }
henrike@webrtc.orgb8395eb2014-02-28 21:57:22 +00002669
2670 engine_->vie()->rtp()->GetPacerQueuingDelayMs(
2671 recv_channels_[0]->channel_id(), &bwe.bucket_delay);
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002672
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 // Calculations done above per send/receive stream.
2674 bwe.actual_enc_bitrate = video_bitrate_sent;
2675 bwe.transmit_bitrate = total_bitrate_sent;
2676 bwe.retransmit_bitrate = nack_bitrate_sent;
2677 bwe.available_send_bandwidth = estimated_send_bandwidth;
2678 bwe.available_recv_bandwidth = estimated_recv_bandwidth;
2679 bwe.target_enc_bitrate = target_enc_bitrate;
2680
2681 info->bw_estimations.push_back(bwe);
2682
2683 return true;
2684}
2685
2686bool WebRtcVideoMediaChannel::SetCapturer(uint32 ssrc,
2687 VideoCapturer* capturer) {
2688 ASSERT(ssrc != 0);
2689 if (!capturer) {
2690 return RemoveCapturer(ssrc);
2691 }
2692 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2693 if (!send_channel) {
2694 return false;
2695 }
2696 VideoCapturer* old_capturer = send_channel->video_capturer();
wu@webrtc.org24301a62013-12-13 19:17:43 +00002697 MaybeDisconnectCapturer(old_capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +00002699 send_channel->set_video_capturer(capturer, engine()->vie());
wu@webrtc.orga8910d22014-01-23 22:12:45 +00002700 MaybeConnectCapturer(capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 if (!capturer->IsScreencast() && ratio_w_ != 0 && ratio_h_ != 0) {
2702 capturer->UpdateAspectRatio(ratio_w_, ratio_h_);
2703 }
2704 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2705 if (send_codec_) {
2706 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2707 }
2708 return true;
2709}
2710
2711bool WebRtcVideoMediaChannel::RequestIntraFrame() {
2712 // There is no API exposed to application to request a key frame
2713 // ViE does this internally when there are errors from decoder
2714 return false;
2715}
2716
wu@webrtc.orga9890802013-12-13 00:21:03 +00002717void WebRtcVideoMediaChannel::OnPacketReceived(
2718 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719 // Pick which channel to send this packet to. If this packet doesn't match
2720 // any multiplexed streams, just send it to the default channel. Otherwise,
2721 // send it to the specific decoder instance for that stream.
2722 uint32 ssrc = 0;
2723 if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
2724 return;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002725 int processing_channel = GetRecvChannelNum(ssrc);
2726 if (processing_channel == -1) {
2727 // Allocate an unsignalled recv channel for processing in conference mode.
henrike@webrtc.org18e59112014-03-14 17:19:38 +00002728 if (!InConferenceMode()) {
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00002729 // If we can't find or allocate one, use the default.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002730 processing_channel = video_channel();
henrike@webrtc.org18e59112014-03-14 17:19:38 +00002731 } else if (!CreateUnsignalledRecvChannel(ssrc, &processing_channel)) {
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00002732 // If we can't create an unsignalled recv channel, drop the packet in
henrike@webrtc.org18e59112014-03-14 17:19:38 +00002733 // conference mode.
2734 return;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002736 }
2737
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002738 engine()->vie()->network()->ReceivedRTPPacket(
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002739 processing_channel,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002740 packet->data(),
wu@webrtc.orga9890802013-12-13 00:21:03 +00002741 static_cast<int>(packet->length()),
2742 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743}
2744
wu@webrtc.orga9890802013-12-13 00:21:03 +00002745void WebRtcVideoMediaChannel::OnRtcpReceived(
2746 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747// Sending channels need all RTCP packets with feedback information.
2748// Even sender reports can contain attached report blocks.
2749// Receiving channels need sender reports in order to create
2750// correct receiver reports.
2751
2752 uint32 ssrc = 0;
2753 if (!GetRtcpSsrc(packet->data(), packet->length(), &ssrc)) {
2754 LOG(LS_WARNING) << "Failed to parse SSRC from received RTCP packet";
2755 return;
2756 }
2757 int type = 0;
2758 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2759 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2760 return;
2761 }
2762
2763 // If it is a sender report, find the channel that is listening.
2764 if (type == kRtcpTypeSR) {
2765 int which_channel = GetRecvChannelNum(ssrc);
2766 if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002767 engine_->vie()->network()->ReceivedRTCPPacket(
2768 which_channel,
2769 packet->data(),
2770 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 }
2772 }
2773 // SR may continue RR and any RR entry may correspond to any one of the send
2774 // channels. So all RTCP packets must be forwarded all send channels. ViE
2775 // will filter out RR internally.
2776 for (SendChannelMap::iterator iter = send_channels_.begin();
2777 iter != send_channels_.end(); ++iter) {
2778 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2779 int channel_id = send_channel->channel_id();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002780 engine_->vie()->network()->ReceivedRTCPPacket(
2781 channel_id,
2782 packet->data(),
2783 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784 }
2785}
2786
2787void WebRtcVideoMediaChannel::OnReadyToSend(bool ready) {
2788 SetNetworkTransmissionState(ready);
2789}
2790
2791bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2792 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2793 if (!send_channel) {
2794 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
2795 return false;
2796 }
2797 send_channel->set_muted(muted);
2798 return true;
2799}
2800
2801bool WebRtcVideoMediaChannel::SetRecvRtpHeaderExtensions(
2802 const std::vector<RtpHeaderExtension>& extensions) {
2803 if (receive_extensions_ == extensions) {
2804 return true;
2805 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002806
2807 const RtpHeaderExtension* offset_extension =
2808 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2809 const RtpHeaderExtension* send_time_extension =
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002810 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811
2812 // Loop through all receive channels and enable/disable the extensions.
2813 for (RecvChannelMap::iterator channel_it = recv_channels_.begin();
2814 channel_it != recv_channels_.end(); ++channel_it) {
2815 int channel_id = channel_it->second->channel_id();
2816 if (!SetHeaderExtension(
2817 &webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus, channel_id,
2818 offset_extension)) {
2819 return false;
2820 }
2821 if (!SetHeaderExtension(
2822 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
2823 send_time_extension)) {
2824 return false;
2825 }
2826 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002827
2828 receive_extensions_ = extensions;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002829 return true;
2830}
2831
2832bool WebRtcVideoMediaChannel::SetSendRtpHeaderExtensions(
2833 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002834 if (send_extensions_ == extensions) {
2835 return true;
2836 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002837
2838 const RtpHeaderExtension* offset_extension =
2839 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2840 const RtpHeaderExtension* send_time_extension =
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002841 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002842
2843 // Loop through all send channels and enable/disable the extensions.
2844 for (SendChannelMap::iterator channel_it = send_channels_.begin();
2845 channel_it != send_channels_.end(); ++channel_it) {
2846 int channel_id = channel_it->second->channel_id();
2847 if (!SetHeaderExtension(
2848 &webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus, channel_id,
2849 offset_extension)) {
2850 return false;
2851 }
2852 if (!SetHeaderExtension(
2853 &webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus, channel_id,
2854 send_time_extension)) {
2855 return false;
2856 }
2857 }
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002858
2859 if (send_time_extension) {
2860 // For video RTP packets, we would like to update AbsoluteSendTimeHeader
2861 // Extension closer to the network, @ socket level before sending.
2862 // Pushing the extension id to socket layer.
2863 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2864 talk_base::Socket::OPT_RTP_SENDTIME_EXTN_ID,
2865 send_time_extension->id);
2866 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002867
2868 send_extensions_ = extensions;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002869 return true;
2870}
2871
mallinath@webrtc.org92fdfeb2014-02-17 18:49:41 +00002872int WebRtcVideoMediaChannel::GetRtpSendTimeExtnId() const {
2873 const RtpHeaderExtension* send_time_extension = FindHeaderExtension(
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002874 send_extensions_, kRtpAbsoluteSenderTimeHeaderExtension);
mallinath@webrtc.org92fdfeb2014-02-17 18:49:41 +00002875 if (send_time_extension) {
2876 return send_time_extension->id;
2877 }
2878 return -1;
2879}
2880
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002881bool WebRtcVideoMediaChannel::SetStartSendBandwidth(int bps) {
2882 LOG(LS_INFO) << "WebRtcVideoMediaChannel::SetStartSendBandwidth";
2883
2884 if (!send_codec_) {
2885 LOG(LS_INFO) << "The send codec has not been set up yet";
2886 return true;
2887 }
2888
2889 // On success, SetSendCodec() will reset |send_start_bitrate_| to |bps/1000|,
2890 // by calling MaybeChangeStartBitrate. That method will also clamp the
2891 // start bitrate between min and max, consistent with the override behavior
2892 // in SetMaxSendBandwidth.
2893 return SetSendCodec(*send_codec_,
2894 send_min_bitrate_, bps / 1000, send_max_bitrate_);
2895}
2896
2897bool WebRtcVideoMediaChannel::SetMaxSendBandwidth(int bps) {
2898 LOG(LS_INFO) << "WebRtcVideoMediaChannel::SetMaxSendBandwidth";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002899
2900 if (InConferenceMode()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002901 LOG(LS_INFO) << "Conference mode ignores SetMaxSendBandwidth";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002902 return true;
2903 }
2904
2905 if (!send_codec_) {
2906 LOG(LS_INFO) << "The send codec has not been set up yet";
2907 return true;
2908 }
2909
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002910 // Use the default value or the bps for the max
2911 int max_bitrate = (bps <= 0) ? send_max_bitrate_ : (bps / 1000);
2912
2913 // Reduce the current minimum and start bitrates if necessary.
2914 int min_bitrate = talk_base::_min(send_min_bitrate_, max_bitrate);
2915 int start_bitrate = talk_base::_min(send_start_bitrate_, max_bitrate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002916
2917 if (!SetSendCodec(*send_codec_, min_bitrate, start_bitrate, max_bitrate)) {
2918 return false;
2919 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002920 LogSendCodecChange("SetMaxSendBandwidth()");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002921
2922 return true;
2923}
2924
2925bool WebRtcVideoMediaChannel::SetOptions(const VideoOptions &options) {
2926 // Always accept options that are unchanged.
2927 if (options_ == options) {
2928 return true;
2929 }
2930
2931 // Trigger SetSendCodec to set correct noise reduction state if the option has
2932 // changed.
2933 bool denoiser_changed = options.video_noise_reduction.IsSet() &&
2934 (options_.video_noise_reduction != options.video_noise_reduction);
2935
2936 bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
2937 (options_.video_leaky_bucket != options.video_leaky_bucket);
2938
2939 bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
2940 (options_.buffered_mode_latency != options.buffered_mode_latency);
2941
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002942 bool cpu_overuse_detection_changed = options.cpu_overuse_detection.IsSet() &&
2943 (options_.cpu_overuse_detection != options.cpu_overuse_detection);
2944
wu@webrtc.orgde305012013-10-31 15:40:38 +00002945 bool dscp_option_changed = (options_.dscp != options.dscp);
2946
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002947 bool suspend_below_min_bitrate_changed =
2948 options.suspend_below_min_bitrate.IsSet() &&
2949 (options_.suspend_below_min_bitrate != options.suspend_below_min_bitrate);
2950
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002951 bool conference_mode_turned_off = false;
2952 if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
2953 options_.conference_mode.GetWithDefaultIfUnset(false) &&
2954 !options.conference_mode.GetWithDefaultIfUnset(false)) {
2955 conference_mode_turned_off = true;
2956 }
2957
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +00002958 bool improved_wifi_bwe_changed =
2959 options.use_improved_wifi_bandwidth_estimator.IsSet() &&
2960 options_.use_improved_wifi_bandwidth_estimator !=
2961 options.use_improved_wifi_bandwidth_estimator;
2962
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00002963
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002964 // Save the options, to be interpreted where appropriate.
2965 // Use options_.SetAll() instead of assignment so that unset value in options
2966 // will not overwrite the previous option value.
2967 options_.SetAll(options);
2968
2969 // Set CPU options for all send channels.
2970 for (SendChannelMap::iterator iter = send_channels_.begin();
2971 iter != send_channels_.end(); ++iter) {
2972 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2973 send_channel->ApplyCpuOptions(options_);
2974 }
2975
2976 // Adjust send codec bitrate if needed.
2977 int conf_max_bitrate = kDefaultConferenceModeMaxVideoBitrate;
2978
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002979 // Save altered min_bitrate level and apply if necessary.
2980 bool adjusted_min_bitrate = false;
2981 if (options.lower_min_bitrate.IsSet()) {
2982 bool lower;
2983 options.lower_min_bitrate.Get(&lower);
2984
2985 int new_send_min_bitrate = lower ? kLowerMinBitrate : kMinVideoBitrate;
2986 adjusted_min_bitrate = (new_send_min_bitrate != send_min_bitrate_);
2987 send_min_bitrate_ = new_send_min_bitrate;
2988 }
2989
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002990 int expected_bitrate = send_max_bitrate_;
2991 if (InConferenceMode()) {
2992 expected_bitrate = conf_max_bitrate;
2993 } else if (conference_mode_turned_off) {
2994 // This is a special case for turning conference mode off.
2995 // Max bitrate should go back to the default maximum value instead
2996 // of the current maximum.
2997 expected_bitrate = kMaxVideoBitrate;
2998 }
2999
wu@webrtc.org1e6cb2c2014-03-24 17:01:50 +00003000 int options_start_bitrate;
3001 bool start_bitrate_changed = false;
3002 if (options.video_start_bitrate.Get(&options_start_bitrate) &&
3003 options_start_bitrate != send_start_bitrate_) {
3004 send_start_bitrate_ = options_start_bitrate;
3005 start_bitrate_changed = true;
3006 }
3007
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00003008 bool reset_send_codec_needed = send_codec_ &&
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00003009 (send_max_bitrate_ != expected_bitrate || denoiser_changed ||
wu@webrtc.org1e6cb2c2014-03-24 17:01:50 +00003010 adjusted_min_bitrate || start_bitrate_changed);
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00003011
3012
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003013 LOG(LS_INFO) << "Reset send codec needed is enabled? "
3014 << reset_send_codec_needed;
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00003015 if (reset_send_codec_needed) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003016 // On success, SetSendCodec() will reset send_max_bitrate_ to
3017 // expected_bitrate.
3018 if (!SetSendCodec(*send_codec_,
3019 send_min_bitrate_,
3020 send_start_bitrate_,
3021 expected_bitrate)) {
3022 return false;
3023 }
3024 LogSendCodecChange("SetOptions()");
3025 }
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00003026
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003027 if (leaky_bucket_changed) {
3028 bool enable_leaky_bucket =
3029 options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003030 LOG(LS_INFO) << "Leaky bucket is enabled? " << enable_leaky_bucket;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003031 for (SendChannelMap::iterator it = send_channels_.begin();
3032 it != send_channels_.end(); ++it) {
3033 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(
3034 it->second->channel_id(), enable_leaky_bucket) != 0) {
3035 LOG_RTCERR2(SetTransmissionSmoothingStatus, it->second->channel_id(),
3036 enable_leaky_bucket);
3037 }
3038 }
3039 }
3040 if (buffer_latency_changed) {
3041 int buffer_latency =
3042 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3043 cricket::kBufferedModeDisabled);
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003044 LOG(LS_INFO) << "Buffer latency is " << buffer_latency;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003045 for (SendChannelMap::iterator it = send_channels_.begin();
3046 it != send_channels_.end(); ++it) {
3047 if (engine()->vie()->rtp()->SetSenderBufferingMode(
3048 it->second->channel_id(), buffer_latency) != 0) {
3049 LOG_RTCERR2(SetSenderBufferingMode, it->second->channel_id(),
3050 buffer_latency);
3051 }
3052 }
3053 for (RecvChannelMap::iterator it = recv_channels_.begin();
3054 it != recv_channels_.end(); ++it) {
3055 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
3056 it->second->channel_id(), buffer_latency) != 0) {
3057 LOG_RTCERR2(SetReceiverBufferingMode, it->second->channel_id(),
3058 buffer_latency);
3059 }
3060 }
3061 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003062 if (cpu_overuse_detection_changed) {
3063 bool cpu_overuse_detection =
3064 options_.cpu_overuse_detection.GetWithDefaultIfUnset(false);
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003065 LOG(LS_INFO) << "CPU overuse detection is enabled? "
3066 << cpu_overuse_detection;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003067 for (SendChannelMap::iterator iter = send_channels_.begin();
3068 iter != send_channels_.end(); ++iter) {
3069 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3070 send_channel->SetCpuOveruseDetection(cpu_overuse_detection);
3071 }
3072 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00003073 if (dscp_option_changed) {
3074 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00003075 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00003076 dscp = kVideoDscpValue;
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003077 LOG(LS_INFO) << "DSCP is " << dscp;
wu@webrtc.orgde305012013-10-31 15:40:38 +00003078 if (MediaChannel::SetDscp(dscp) != 0) {
3079 LOG(LS_WARNING) << "Failed to set DSCP settings for video channel";
3080 }
3081 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003082 if (suspend_below_min_bitrate_changed) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003083 if (options_.suspend_below_min_bitrate.GetWithDefaultIfUnset(false)) {
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003084 LOG(LS_INFO) << "Suspend below min bitrate enabled.";
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003085 for (SendChannelMap::iterator it = send_channels_.begin();
3086 it != send_channels_.end(); ++it) {
3087 engine()->vie()->codec()->SuspendBelowMinBitrate(
3088 it->second->channel_id());
3089 }
3090 } else {
3091 LOG(LS_WARNING) << "Cannot disable video suspension once it is enabled";
3092 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003093 }
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +00003094 if (improved_wifi_bwe_changed) {
buildbot@webrtc.orgf875f152014-04-14 16:06:21 +00003095 LOG(LS_INFO) << "Improved WIFI BWE called.";
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +00003096 webrtc::Config config;
3097 config.Set(new webrtc::AimdRemoteRateControl(
3098 options_.use_improved_wifi_bandwidth_estimator
3099 .GetWithDefaultIfUnset(false)));
3100 for (SendChannelMap::iterator it = send_channels_.begin();
3101 it != send_channels_.end(); ++it) {
3102 engine()->vie()->network()->SetBandwidthEstimationConfig(
3103 it->second->channel_id(), config);
3104 }
3105 }
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +00003106 webrtc::CpuOveruseOptions overuse_options;
3107 if (GetCpuOveruseOptions(options_, &overuse_options)) {
3108 for (SendChannelMap::iterator it = send_channels_.begin();
3109 it != send_channels_.end(); ++it) {
3110 if (engine()->vie()->base()->SetCpuOveruseOptions(
3111 it->second->channel_id(), overuse_options) != 0) {
3112 LOG_RTCERR1(SetCpuOveruseOptions, it->second->channel_id());
3113 }
3114 }
3115 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 return true;
3117}
3118
3119void WebRtcVideoMediaChannel::SetInterface(NetworkInterface* iface) {
3120 MediaChannel::SetInterface(iface);
3121 // Set the RTP recv/send buffer to a bigger size
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003122 MediaChannel::SetOption(NetworkInterface::ST_RTP,
3123 talk_base::Socket::OPT_RCVBUF,
3124 kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125
3126 // TODO(sriniv): Remove or re-enable this.
3127 // As part of b/8030474, send-buffer is size now controlled through
3128 // portallocator flags.
3129 // network_interface_->SetOption(NetworkInterface::ST_RTP,
3130 // talk_base::Socket::OPT_SNDBUF,
3131 // kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003132}
3133
3134void WebRtcVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
3135 ASSERT(ratio_w != 0);
3136 ASSERT(ratio_h != 0);
3137 ratio_w_ = ratio_w;
3138 ratio_h_ = ratio_h;
3139 // For now assume that all streams want the same aspect ratio.
3140 // TODO(hellner): remove the need for this assumption.
3141 for (SendChannelMap::iterator iter = send_channels_.begin();
3142 iter != send_channels_.end(); ++iter) {
3143 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3144 VideoCapturer* capturer = send_channel->video_capturer();
3145 if (capturer) {
3146 capturer->UpdateAspectRatio(ratio_w, ratio_h);
3147 }
3148 }
3149}
3150
3151bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
3152 VideoRenderer** renderer) {
3153 RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
3154 if (it == recv_channels_.end()) {
3155 if (first_receive_ssrc_ == ssrc &&
3156 recv_channels_.find(0) != recv_channels_.end()) {
3157 LOG(LS_INFO) << " GetRenderer " << ssrc
3158 << " reuse default renderer #"
3159 << vie_channel_;
3160 *renderer = recv_channels_[0]->render_adapter()->renderer();
3161 return true;
3162 }
3163 return false;
3164 }
3165
3166 *renderer = it->second->render_adapter()->renderer();
3167 return true;
3168}
3169
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003170bool WebRtcVideoMediaChannel::GetVideoAdapter(
3171 uint32 ssrc, CoordinatedVideoAdapter** video_adapter) {
3172 SendChannelMap::iterator it = send_channels_.find(ssrc);
3173 if (it == send_channels_.end()) {
3174 return false;
3175 }
3176 *video_adapter = it->second->video_adapter();
3177 return true;
3178}
3179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003180void WebRtcVideoMediaChannel::SendFrame(VideoCapturer* capturer,
3181 const VideoFrame* frame) {
wu@webrtc.org24301a62013-12-13 19:17:43 +00003182 // If the |capturer| is registered to any send channel, then send the frame
3183 // to those send channels.
3184 bool capturer_is_channel_owned = false;
3185 for (SendChannelMap::iterator iter = send_channels_.begin();
3186 iter != send_channels_.end(); ++iter) {
3187 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3188 if (send_channel->video_capturer() == capturer) {
3189 SendFrame(send_channel, frame, capturer->IsScreencast());
3190 capturer_is_channel_owned = true;
3191 }
3192 }
3193 if (capturer_is_channel_owned) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194 return;
3195 }
wu@webrtc.org24301a62013-12-13 19:17:43 +00003196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003197 // TODO(hellner): Remove below for loop once the captured frame no longer
3198 // come from the engine, i.e. the engine no longer owns a capturer.
3199 for (SendChannelMap::iterator iter = send_channels_.begin();
3200 iter != send_channels_.end(); ++iter) {
3201 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3202 if (send_channel->video_capturer() == NULL) {
3203 SendFrame(send_channel, frame, capturer->IsScreencast());
3204 }
3205 }
3206}
3207
3208bool WebRtcVideoMediaChannel::SendFrame(
3209 WebRtcVideoChannelSendInfo* send_channel,
3210 const VideoFrame* frame,
3211 bool is_screencast) {
3212 if (!send_channel) {
3213 return false;
3214 }
3215 if (!send_codec_) {
3216 // Send codec has not been set. No reason to process the frame any further.
3217 return false;
3218 }
3219 const VideoFormat& video_format = send_channel->video_format();
3220 // If the frame should be dropped.
3221 const bool video_format_set = video_format != cricket::VideoFormat();
3222 if (video_format_set &&
3223 (video_format.width == 0 && video_format.height == 0)) {
3224 return true;
3225 }
3226
3227 // Checks if we need to reset vie send codec.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003228 if (!MaybeResetVieSendCodec(send_channel,
3229 static_cast<int>(frame->GetWidth()),
3230 static_cast<int>(frame->GetHeight()),
3231 is_screencast, NULL)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232 LOG(LS_ERROR) << "MaybeResetVieSendCodec failed with "
3233 << frame->GetWidth() << "x" << frame->GetHeight();
3234 return false;
3235 }
3236 const VideoFrame* frame_out = frame;
3237 talk_base::scoped_ptr<VideoFrame> processed_frame;
3238 // Disable muting for screencast.
3239 const bool mute = (send_channel->muted() && !is_screencast);
3240 send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
3241 if (processed_frame) {
3242 frame_out = processed_frame.get();
3243 }
3244
3245 webrtc::ViEVideoFrameI420 frame_i420;
3246 // TODO(ronghuawu): Update the webrtc::ViEVideoFrameI420
3247 // to use const unsigned char*
3248 frame_i420.y_plane = const_cast<unsigned char*>(frame_out->GetYPlane());
3249 frame_i420.u_plane = const_cast<unsigned char*>(frame_out->GetUPlane());
3250 frame_i420.v_plane = const_cast<unsigned char*>(frame_out->GetVPlane());
3251 frame_i420.y_pitch = frame_out->GetYPitch();
3252 frame_i420.u_pitch = frame_out->GetUPitch();
3253 frame_i420.v_pitch = frame_out->GetVPitch();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003254 frame_i420.width = static_cast<uint16>(frame_out->GetWidth());
3255 frame_i420.height = static_cast<uint16>(frame_out->GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256
3257 int64 timestamp_ntp_ms = 0;
3258 // TODO(justinlin): Reenable after Windows issues with clock drift are fixed.
3259 // Currently reverted to old behavior of discarding capture timestamp.
3260#if 0
henrike@webrtc.orgf5bebd42014-04-04 18:39:07 +00003261 static const int kTimestampDeltaInSecondsForWarning = 2;
3262
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 // If the frame timestamp is 0, we will use the deliver time.
3264 const int64 frame_timestamp = frame->GetTimeStamp();
3265 if (frame_timestamp != 0) {
3266 if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
3267 kTimestampDeltaInSecondsForWarning) {
3268 LOG(LS_WARNING) << "Frame timestamp differs by more than "
3269 << kTimestampDeltaInSecondsForWarning << " seconds from "
3270 << "current Unix timestamp.";
3271 }
3272
3273 timestamp_ntp_ms =
3274 talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
3275 }
3276#endif
3277
3278 return send_channel->external_capture()->IncomingFrameI420(
3279 frame_i420, timestamp_ntp_ms) == 0;
3280}
3281
3282bool WebRtcVideoMediaChannel::CreateChannel(uint32 ssrc_key,
3283 MediaDirection direction,
3284 int* channel_id) {
3285 // There are 3 types of channels. Sending only, receiving only and
3286 // sending and receiving. The sending and receiving channel is the
3287 // default channel and there is only one. All other channels that are created
3288 // are associated with the default channel which must exist. The default
3289 // channel id is stored in |vie_channel_|. All channels need to know about
3290 // the default channel to properly handle remb which is why there are
3291 // different ViE create channel calls.
3292 // For this channel the local and remote ssrc key is 0. However, it may
3293 // have a non-zero local and/or remote ssrc depending on if it is currently
3294 // sending and/or receiving.
3295 if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
3296 (!send_channels_.empty() || !recv_channels_.empty())) {
3297 ASSERT(false);
3298 return false;
3299 }
3300
3301 *channel_id = -1;
3302 if (direction == MD_RECV) {
3303 // All rec channels are associated with the default channel |vie_channel_|
3304 if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
3305 vie_channel_) != 0) {
3306 LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
3307 return false;
3308 }
3309 } else if (direction == MD_SEND) {
3310 if (engine_->vie()->base()->CreateChannel(*channel_id,
3311 vie_channel_) != 0) {
3312 LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
3313 return false;
3314 }
3315 } else {
3316 ASSERT(direction == MD_SENDRECV);
3317 if (engine_->vie()->base()->CreateChannel(*channel_id) != 0) {
3318 LOG_RTCERR1(CreateChannel, *channel_id);
3319 return false;
3320 }
3321 }
3322 if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
3323 engine_->vie()->base()->DeleteChannel(*channel_id);
3324 *channel_id = -1;
3325 return false;
3326 }
3327
3328 return true;
3329}
3330
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00003331bool WebRtcVideoMediaChannel::CreateUnsignalledRecvChannel(
3332 uint32 ssrc_key, int* out_channel_id) {
henrike@webrtc.org18e59112014-03-14 17:19:38 +00003333 int unsignalled_recv_channel_limit =
3334 options_.unsignalled_recv_stream_limit.GetWithDefaultIfUnset(
3335 kNumDefaultUnsignalledVideoRecvStreams);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00003336 if (num_unsignalled_recv_channels_ >= unsignalled_recv_channel_limit) {
3337 return false;
3338 }
3339 if (!CreateChannel(ssrc_key, MD_RECV, out_channel_id)) {
3340 return false;
3341 }
3342 // TODO(tvsriram): Support dynamic sizing of unsignalled recv channels.
3343 num_unsignalled_recv_channels_++;
3344 return true;
3345}
3346
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347bool WebRtcVideoMediaChannel::ConfigureChannel(int channel_id,
3348 MediaDirection direction,
3349 uint32 ssrc_key) {
3350 const bool receiving = (direction == MD_RECV) || (direction == MD_SENDRECV);
3351 const bool sending = (direction == MD_SEND) || (direction == MD_SENDRECV);
3352 // Register external transport.
3353 if (engine_->vie()->network()->RegisterSendTransport(
3354 channel_id, *this) != 0) {
3355 LOG_RTCERR1(RegisterSendTransport, channel_id);
3356 return false;
3357 }
3358
3359 // Set MTU.
3360 if (engine_->vie()->network()->SetMTU(channel_id, kVideoMtu) != 0) {
3361 LOG_RTCERR2(SetMTU, channel_id, kVideoMtu);
3362 return false;
3363 }
3364 // Turn on RTCP and loss feedback reporting.
3365 if (engine()->vie()->rtp()->SetRTCPStatus(
3366 channel_id, webrtc::kRtcpCompound_RFC4585) != 0) {
3367 LOG_RTCERR2(SetRTCPStatus, channel_id, webrtc::kRtcpCompound_RFC4585);
3368 return false;
3369 }
3370 // Enable pli as key frame request method.
3371 if (engine_->vie()->rtp()->SetKeyFrameRequestMethod(
3372 channel_id, webrtc::kViEKeyFrameRequestPliRtcp) != 0) {
3373 LOG_RTCERR2(SetKeyFrameRequestMethod,
3374 channel_id, webrtc::kViEKeyFrameRequestPliRtcp);
3375 return false;
3376 }
3377 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3378 // Logged in SetNackFec. Don't spam the logs.
3379 return false;
3380 }
3381 // Note that receiving must always be configured before sending to ensure
3382 // that send and receive channel is configured correctly (ConfigureReceiving
3383 // assumes no sending).
3384 if (receiving) {
3385 if (!ConfigureReceiving(channel_id, ssrc_key)) {
3386 return false;
3387 }
3388 }
3389 if (sending) {
3390 if (!ConfigureSending(channel_id, ssrc_key)) {
3391 return false;
3392 }
3393 }
3394
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00003395 // Start receiving for both receive and send channels so that we get incoming
3396 // RTP (if receiving) as well as RTCP feedback (if sending).
3397 if (engine()->vie()->base()->StartReceive(channel_id) != 0) {
3398 LOG_RTCERR1(StartReceive, channel_id);
3399 return false;
3400 }
3401
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003402 return true;
3403}
3404
3405bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
3406 uint32 remote_ssrc_key) {
3407 // Make sure that an SSRC/key isn't registered more than once.
3408 if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
3409 return false;
3410 }
3411 // Connect the voice channel, if there is one.
3412 // TODO(perkj): The A/V is synched by the receiving channel. So we need to
3413 // know the SSRC of the remote audio channel in order to fetch the correct
3414 // webrtc VoiceEngine channel. For now- only sync the default channel used
3415 // in 1-1 calls.
3416 if (remote_ssrc_key == 0 && voice_channel_) {
3417 WebRtcVoiceMediaChannel* voice_channel =
3418 static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
3419 if (engine_->vie()->base()->ConnectAudioChannel(
3420 vie_channel_, voice_channel->voe_channel()) != 0) {
3421 LOG_RTCERR2(ConnectAudioChannel, channel_id,
3422 voice_channel->voe_channel());
3423 LOG(LS_WARNING) << "A/V not synchronized";
3424 // Not a fatal error.
3425 }
3426 }
3427
3428 talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
3429 new WebRtcVideoChannelRecvInfo(channel_id));
3430
3431 // Install a render adapter.
3432 if (engine_->vie()->render()->AddRenderer(channel_id,
3433 webrtc::kVideoI420, channel_info->render_adapter()) != 0) {
3434 LOG_RTCERR3(AddRenderer, channel_id, webrtc::kVideoI420,
3435 channel_info->render_adapter());
3436 return false;
3437 }
3438
3439
3440 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3441 kNotSending,
3442 remb_enabled_) != 0) {
3443 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
3444 return false;
3445 }
3446
3447 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus,
3448 channel_id, receive_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3449 return false;
3450 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003451 if (!SetHeaderExtension(
3452 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003453 receive_extensions_, kRtpAbsoluteSenderTimeHeaderExtension)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003454 return false;
3455 }
3456
3457 if (remote_ssrc_key != 0) {
3458 // Use the same SSRC as our default channel
3459 // (so the RTCP reports are correct).
3460 unsigned int send_ssrc = 0;
3461 webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
3462 if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
3463 LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
3464 return false;
3465 }
3466 if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
3467 LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
3468 return false;
3469 }
3470 } // Else this is the the default channel and we don't change the SSRC.
3471
3472 // Disable color enhancement since it is a bit too aggressive.
3473 if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
3474 false) != 0) {
3475 LOG_RTCERR1(EnableColorEnhancement, channel_id);
3476 return false;
3477 }
3478
3479 if (!SetReceiveCodecs(channel_info.get())) {
3480 return false;
3481 }
3482
3483 int buffer_latency =
3484 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3485 cricket::kBufferedModeDisabled);
3486 if (buffer_latency != cricket::kBufferedModeDisabled) {
3487 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
3488 channel_id, buffer_latency) != 0) {
3489 LOG_RTCERR2(SetReceiverBufferingMode, channel_id, buffer_latency);
3490 }
3491 }
3492
3493 if (render_started_) {
3494 if (engine_->vie()->render()->StartRender(channel_id) != 0) {
3495 LOG_RTCERR1(StartRender, channel_id);
3496 return false;
3497 }
3498 }
3499
3500 // Register decoder observer for incoming framerate and bitrate.
3501 if (engine()->vie()->codec()->RegisterDecoderObserver(
3502 channel_id, *channel_info->decoder_observer()) != 0) {
3503 LOG_RTCERR1(RegisterDecoderObserver, channel_info->decoder_observer());
3504 return false;
3505 }
3506
3507 recv_channels_[remote_ssrc_key] = channel_info.release();
3508 return true;
3509}
3510
3511bool WebRtcVideoMediaChannel::ConfigureSending(int channel_id,
3512 uint32 local_ssrc_key) {
3513 // The ssrc key can be zero or correspond to an SSRC.
3514 // Make sure the default channel isn't configured more than once.
3515 if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
3516 return false;
3517 }
3518 // Make sure that the SSRC is not already in use.
3519 uint32 dummy_key;
3520 if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
3521 return false;
3522 }
3523 int vie_capture = 0;
3524 webrtc::ViEExternalCapture* external_capture = NULL;
3525 // Register external capture.
3526 if (engine()->vie()->capture()->AllocateExternalCaptureDevice(
3527 vie_capture, external_capture) != 0) {
3528 LOG_RTCERR0(AllocateExternalCaptureDevice);
3529 return false;
3530 }
3531
3532 // Connect external capture.
3533 if (engine()->vie()->capture()->ConnectCaptureDevice(
3534 vie_capture, channel_id) != 0) {
3535 LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
3536 return false;
3537 }
3538 talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
3539 new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
3540 external_capture,
3541 engine()->cpu_monitor()));
3542 send_channel->ApplyCpuOptions(options_);
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003543 send_channel->SignalCpuAdaptationUnable.connect(this,
3544 &WebRtcVideoMediaChannel::OnCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003545
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003546 if (options_.cpu_overuse_detection.GetWithDefaultIfUnset(false)) {
3547 send_channel->SetCpuOveruseDetection(true);
3548 }
3549
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +00003550 webrtc::CpuOveruseOptions overuse_options;
3551 if (GetCpuOveruseOptions(options_, &overuse_options)) {
3552 if (engine()->vie()->base()->SetCpuOveruseOptions(channel_id,
3553 overuse_options) != 0) {
3554 LOG_RTCERR1(SetCpuOveruseOptions, channel_id);
3555 }
3556 }
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +00003557
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003558 // Register encoder observer for outgoing framerate and bitrate.
3559 if (engine()->vie()->codec()->RegisterEncoderObserver(
3560 channel_id, *send_channel->encoder_observer()) != 0) {
3561 LOG_RTCERR1(RegisterEncoderObserver, send_channel->encoder_observer());
3562 return false;
3563 }
3564
3565 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus,
3566 channel_id, send_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3567 return false;
3568 }
3569
3570 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003571 channel_id, send_extensions_, kRtpAbsoluteSenderTimeHeaderExtension)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003572 return false;
3573 }
3574
3575 if (options_.video_leaky_bucket.GetWithDefaultIfUnset(false)) {
3576 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
3577 true) != 0) {
3578 LOG_RTCERR2(SetTransmissionSmoothingStatus, channel_id, true);
3579 return false;
3580 }
3581 }
3582
3583 int buffer_latency =
3584 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3585 cricket::kBufferedModeDisabled);
3586 if (buffer_latency != cricket::kBufferedModeDisabled) {
3587 if (engine()->vie()->rtp()->SetSenderBufferingMode(
3588 channel_id, buffer_latency) != 0) {
3589 LOG_RTCERR2(SetSenderBufferingMode, channel_id, buffer_latency);
3590 }
3591 }
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00003592
3593 if (options_.suspend_below_min_bitrate.GetWithDefaultIfUnset(false)) {
3594 engine()->vie()->codec()->SuspendBelowMinBitrate(channel_id);
3595 }
3596
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003597 // The remb status direction correspond to the RTP stream (and not the RTCP
3598 // stream). I.e. if send remb is enabled it means it is receiving remote
3599 // rembs and should use them to estimate bandwidth. Receive remb mean that
3600 // remb packets will be generated and that the channel should be included in
3601 // it. If remb is enabled all channels are allowed to contribute to the remb
3602 // but only receive channels will ever end up actually contributing. This
3603 // keeps the logic simple.
3604 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3605 remb_enabled_,
3606 remb_enabled_) != 0) {
3607 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
3608 return false;
3609 }
3610 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3611 // Logged in SetNackFec. Don't spam the logs.
3612 return false;
3613 }
3614
3615 send_channels_[local_ssrc_key] = send_channel.release();
3616
3617 return true;
3618}
3619
3620bool WebRtcVideoMediaChannel::SetNackFec(int channel_id,
3621 int red_payload_type,
3622 int fec_payload_type,
3623 bool nack_enabled) {
3624 bool enable = (red_payload_type != -1 && fec_payload_type != -1 &&
3625 !InConferenceMode());
3626 if (enable) {
3627 if (engine_->vie()->rtp()->SetHybridNACKFECStatus(
3628 channel_id, nack_enabled, red_payload_type, fec_payload_type) != 0) {
3629 LOG_RTCERR4(SetHybridNACKFECStatus,
3630 channel_id, nack_enabled, red_payload_type, fec_payload_type);
3631 return false;
3632 }
3633 LOG(LS_INFO) << "Hybrid NACK/FEC enabled for channel " << channel_id;
3634 } else {
3635 if (engine_->vie()->rtp()->SetNACKStatus(channel_id, nack_enabled) != 0) {
3636 LOG_RTCERR1(SetNACKStatus, channel_id);
3637 return false;
3638 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003639 std::string enabled = nack_enabled ? "enabled" : "disabled";
3640 LOG(LS_INFO) << "NACK " << enabled << " for channel " << channel_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003641 }
3642 return true;
3643}
3644
3645bool WebRtcVideoMediaChannel::SetSendCodec(const webrtc::VideoCodec& codec,
3646 int min_bitrate,
3647 int start_bitrate,
3648 int max_bitrate) {
3649 bool ret_val = true;
3650 for (SendChannelMap::iterator iter = send_channels_.begin();
3651 iter != send_channels_.end(); ++iter) {
3652 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3653 ret_val = SetSendCodec(send_channel, codec, min_bitrate, start_bitrate,
3654 max_bitrate) && ret_val;
3655 }
3656 if (ret_val) {
3657 // All SetSendCodec calls were successful. Update the global state
3658 // accordingly.
3659 send_codec_.reset(new webrtc::VideoCodec(codec));
3660 send_min_bitrate_ = min_bitrate;
3661 send_start_bitrate_ = start_bitrate;
3662 send_max_bitrate_ = max_bitrate;
3663 } else {
3664 // At least one SetSendCodec call failed, rollback.
3665 for (SendChannelMap::iterator iter = send_channels_.begin();
3666 iter != send_channels_.end(); ++iter) {
3667 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3668 if (send_codec_) {
3669 SetSendCodec(send_channel, *send_codec_.get(), send_min_bitrate_,
3670 send_start_bitrate_, send_max_bitrate_);
3671 }
3672 }
3673 }
3674 return ret_val;
3675}
3676
3677bool WebRtcVideoMediaChannel::SetSendCodec(
3678 WebRtcVideoChannelSendInfo* send_channel,
3679 const webrtc::VideoCodec& codec,
3680 int min_bitrate,
3681 int start_bitrate,
3682 int max_bitrate) {
3683 if (!send_channel) {
3684 return false;
3685 }
3686 const int channel_id = send_channel->channel_id();
3687 // Make a copy of the codec
3688 webrtc::VideoCodec target_codec = codec;
3689 target_codec.startBitrate = start_bitrate;
3690 target_codec.minBitrate = min_bitrate;
3691 target_codec.maxBitrate = max_bitrate;
3692
3693 // Set the default number of temporal layers for VP8.
3694 if (webrtc::kVideoCodecVP8 == codec.codecType) {
3695 target_codec.codecSpecific.VP8.numberOfTemporalLayers =
3696 kDefaultNumberOfTemporalLayers;
3697
3698 // Turn off the VP8 error resilience
3699 target_codec.codecSpecific.VP8.resilience = webrtc::kResilienceOff;
3700
3701 bool enable_denoising =
3702 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3703 target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
3704 }
3705
3706 // Register external encoder if codec type is supported by encoder factory.
3707 if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
3708 !send_channel->IsEncoderRegistered(target_codec.plType)) {
3709 webrtc::VideoEncoder* encoder =
3710 engine()->CreateExternalEncoder(codec.codecType);
3711 if (encoder) {
3712 if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
3713 channel_id, target_codec.plType, encoder, false) == 0) {
3714 send_channel->RegisterEncoder(target_codec.plType, encoder);
3715 } else {
3716 LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
3717 engine()->DestroyExternalEncoder(encoder);
3718 }
3719 }
3720 }
3721
3722 // Resolution and framerate may vary for different send channels.
3723 const VideoFormat& video_format = send_channel->video_format();
3724 UpdateVideoCodec(video_format, &target_codec);
3725
3726 if (target_codec.width == 0 && target_codec.height == 0) {
3727 const uint32 ssrc = send_channel->stream_params()->first_ssrc();
3728 LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
3729 << "for ssrc: " << ssrc << ".";
3730 } else {
3731 MaybeChangeStartBitrate(channel_id, &target_codec);
wu@webrtc.org05e7b442014-04-01 17:44:24 +00003732 webrtc::VideoCodec current_codec;
3733 if (!engine()->vie()->codec()->GetSendCodec(channel_id, current_codec)) {
3734 // Compare against existing configured send codec.
3735 if (current_codec == target_codec) {
3736 // Codec is already configured on channel. no need to apply.
3737 return true;
3738 }
3739 }
3740
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003741 if (0 != engine()->vie()->codec()->SetSendCodec(channel_id, target_codec)) {
3742 LOG_RTCERR2(SetSendCodec, channel_id, target_codec.plName);
3743 return false;
3744 }
3745
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003746 // NOTE: SetRtxSendPayloadType must be called after all simulcast SSRCs
3747 // are configured. Otherwise ssrc's configured after this point will use
3748 // the primary PT for RTX.
3749 if (send_rtx_type_ != -1 &&
3750 engine()->vie()->rtp()->SetRtxSendPayloadType(channel_id,
3751 send_rtx_type_) != 0) {
3752 LOG_RTCERR2(SetRtxSendPayloadType, channel_id, send_rtx_type_);
3753 return false;
3754 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003755 }
3756 send_channel->set_interval(
3757 cricket::VideoFormat::FpsToInterval(target_codec.maxFramerate));
3758 return true;
3759}
3760
3761
3762static std::string ToString(webrtc::VideoCodecComplexity complexity) {
3763 switch (complexity) {
3764 case webrtc::kComplexityNormal:
3765 return "normal";
3766 case webrtc::kComplexityHigh:
3767 return "high";
3768 case webrtc::kComplexityHigher:
3769 return "higher";
3770 case webrtc::kComplexityMax:
3771 return "max";
3772 default:
3773 return "unknown";
3774 }
3775}
3776
3777static std::string ToString(webrtc::VP8ResilienceMode resilience) {
3778 switch (resilience) {
3779 case webrtc::kResilienceOff:
3780 return "off";
3781 case webrtc::kResilientStream:
3782 return "stream";
3783 case webrtc::kResilientFrames:
3784 return "frames";
3785 default:
3786 return "unknown";
3787 }
3788}
3789
3790void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
3791 webrtc::VideoCodec vie_codec;
3792 if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
3793 LOG_RTCERR1(GetSendCodec, vie_channel_);
3794 return;
3795 }
3796
3797 LOG(LS_INFO) << reason << " : selected video codec "
3798 << vie_codec.plName << "/"
3799 << vie_codec.width << "x" << vie_codec.height << "x"
3800 << static_cast<int>(vie_codec.maxFramerate) << "fps"
3801 << "@" << vie_codec.maxBitrate << "kbps"
3802 << " (min=" << vie_codec.minBitrate << "kbps,"
3803 << " start=" << vie_codec.startBitrate << "kbps)";
3804 LOG(LS_INFO) << "Video max quantization: " << vie_codec.qpMax;
3805 if (webrtc::kVideoCodecVP8 == vie_codec.codecType) {
3806 LOG(LS_INFO) << "VP8 number of temporal layers: "
3807 << static_cast<int>(
3808 vie_codec.codecSpecific.VP8.numberOfTemporalLayers);
3809 LOG(LS_INFO) << "VP8 options : "
3810 << "picture loss indication = "
3811 << vie_codec.codecSpecific.VP8.pictureLossIndicationOn
3812 << ", feedback mode = "
3813 << vie_codec.codecSpecific.VP8.feedbackModeOn
3814 << ", complexity = "
3815 << ToString(vie_codec.codecSpecific.VP8.complexity)
3816 << ", resilience = "
3817 << ToString(vie_codec.codecSpecific.VP8.resilience)
3818 << ", denoising = "
3819 << vie_codec.codecSpecific.VP8.denoisingOn
3820 << ", error concealment = "
3821 << vie_codec.codecSpecific.VP8.errorConcealmentOn
3822 << ", automatic resize = "
3823 << vie_codec.codecSpecific.VP8.automaticResizeOn
3824 << ", frame dropping = "
3825 << vie_codec.codecSpecific.VP8.frameDroppingOn
3826 << ", key frame interval = "
3827 << vie_codec.codecSpecific.VP8.keyFrameInterval;
3828 }
3829
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003830 if (send_rtx_type_ != -1) {
3831 LOG(LS_INFO) << "RTX payload type: " << send_rtx_type_;
3832 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003833}
3834
3835bool WebRtcVideoMediaChannel::SetReceiveCodecs(
3836 WebRtcVideoChannelRecvInfo* info) {
3837 int red_type = -1;
3838 int fec_type = -1;
3839 int channel_id = info->channel_id();
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00003840 // Build a map from payload types to video codecs so that we easily can find
3841 // out if associated payload types are referring to valid codecs.
3842 std::map<int, webrtc::VideoCodec*> pt_to_codec;
3843 for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
3844 it != receive_codecs_.end(); ++it) {
3845 pt_to_codec[it->plType] = &(*it);
3846 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847 for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
3848 it != receive_codecs_.end(); ++it) {
3849 if (it->codecType == webrtc::kVideoCodecRED) {
3850 red_type = it->plType;
3851 } else if (it->codecType == webrtc::kVideoCodecULPFEC) {
3852 fec_type = it->plType;
3853 }
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00003854 // If this is an RTX codec we have to verify that it is associated with
3855 // a valid video codec which we have RTX support for.
3856 if (_stricmp(it->plName, kRtxCodecName) == 0) {
3857 std::map<int, int>::iterator apt_it = associated_payload_types_.find(
3858 it->plType);
3859 bool valid_apt = false;
3860 if (apt_it != associated_payload_types_.end()) {
3861 std::map<int, webrtc::VideoCodec*>::iterator codec_it =
3862 pt_to_codec.find(apt_it->second);
3863 // We currently only support RTX associated with VP8 due to limitations
3864 // in webrtc where only one RTX payload type can be registered.
3865 valid_apt = codec_it != pt_to_codec.end() &&
3866 _stricmp(codec_it->second->plName, kVp8PayloadName) == 0;
3867 }
3868 if (!valid_apt) {
3869 LOG(LS_ERROR) << "The RTX codec isn't associated with a known and "
3870 "supported payload type";
3871 return false;
3872 }
3873 if (engine()->vie()->rtp()->SetRtxReceivePayloadType(
3874 channel_id, it->plType) != 0) {
3875 LOG_RTCERR2(SetRtxReceivePayloadType, channel_id, it->plType);
3876 return false;
3877 }
3878 continue;
3879 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003880 if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
3881 LOG_RTCERR2(SetReceiveCodec, channel_id, it->plName);
3882 return false;
3883 }
3884 if (!info->IsDecoderRegistered(it->plType) &&
3885 it->codecType != webrtc::kVideoCodecRED &&
3886 it->codecType != webrtc::kVideoCodecULPFEC) {
3887 webrtc::VideoDecoder* decoder =
3888 engine()->CreateExternalDecoder(it->codecType);
3889 if (decoder) {
3890 if (engine()->vie()->ext_codec()->RegisterExternalReceiveCodec(
3891 channel_id, it->plType, decoder) == 0) {
3892 info->RegisterDecoder(it->plType, decoder);
3893 } else {
3894 LOG_RTCERR2(RegisterExternalReceiveCodec, channel_id, it->plName);
3895 engine()->DestroyExternalDecoder(decoder);
3896 }
3897 }
3898 }
3899 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003900 return true;
3901}
3902
3903int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
3904 if (ssrc == first_receive_ssrc_) {
3905 return vie_channel_;
3906 }
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00003907 int recv_channel = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003908 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
buildbot@webrtc.orgdd4742a2014-05-07 14:50:35 +00003909 if (it == recv_channels_.end()) {
3910 // Check if we have an RTX stream registered on this SSRC.
3911 SsrcMap::iterator rtx_it = rtx_to_primary_ssrc_.find(ssrc);
3912 if (rtx_it != rtx_to_primary_ssrc_.end()) {
3913 it = recv_channels_.find(rtx_it->second);
3914 assert(it != recv_channels_.end());
3915 recv_channel = it->second->channel_id();
3916 }
3917 } else {
3918 recv_channel = it->second->channel_id();
3919 }
3920 return recv_channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003921}
3922
3923// If the new frame size is different from the send codec size we set on vie,
3924// we need to reset the send codec on vie.
3925// The new send codec size should not exceed send_codec_ which is controlled
3926// only by the 'jec' logic.
3927bool WebRtcVideoMediaChannel::MaybeResetVieSendCodec(
3928 WebRtcVideoChannelSendInfo* send_channel,
3929 int new_width,
3930 int new_height,
3931 bool is_screencast,
3932 bool* reset) {
3933 if (reset) {
3934 *reset = false;
3935 }
3936 ASSERT(send_codec_.get() != NULL);
3937
3938 webrtc::VideoCodec target_codec = *send_codec_.get();
3939 const VideoFormat& video_format = send_channel->video_format();
3940 UpdateVideoCodec(video_format, &target_codec);
3941
3942 // Vie send codec size should not exceed target_codec.
3943 int target_width = new_width;
3944 int target_height = new_height;
3945 if (!is_screencast &&
3946 (new_width > target_codec.width || new_height > target_codec.height)) {
3947 target_width = target_codec.width;
3948 target_height = target_codec.height;
3949 }
3950
3951 // Get current vie codec.
3952 webrtc::VideoCodec vie_codec;
3953 const int channel_id = send_channel->channel_id();
3954 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) != 0) {
3955 LOG_RTCERR1(GetSendCodec, channel_id);
3956 return false;
3957 }
3958 const int cur_width = vie_codec.width;
3959 const int cur_height = vie_codec.height;
3960
3961 // Only reset send codec when there is a size change. Additionally,
3962 // automatic resize needs to be turned off when screencasting and on when
3963 // not screencasting.
3964 // Don't allow automatic resizing for screencasting.
3965 bool automatic_resize = !is_screencast;
3966 // Turn off VP8 frame dropping when screensharing as the current model does
3967 // not work well at low fps.
3968 bool vp8_frame_dropping = !is_screencast;
3969 // Disable denoising for screencasting.
3970 bool enable_denoising =
3971 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +00003972 int screencast_min_bitrate =
3973 options_.screencast_min_bitrate.GetWithDefaultIfUnset(0);
3974 bool leaky_bucket = options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003975 bool denoising = !is_screencast && enable_denoising;
3976 bool reset_send_codec =
3977 target_width != cur_width || target_height != cur_height ||
3978 automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
3979 denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
3980 vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
3981
3982 if (reset_send_codec) {
3983 // Set the new codec on vie.
3984 vie_codec.width = target_width;
3985 vie_codec.height = target_height;
3986 vie_codec.maxFramerate = target_codec.maxFramerate;
3987 vie_codec.startBitrate = target_codec.startBitrate;
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00003988 vie_codec.targetBitrate = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003989 vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
3990 vie_codec.codecSpecific.VP8.denoisingOn = denoising;
3991 vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
buildbot@webrtc.org0d34f142014-05-02 16:54:25 +00003992 MaybeChangeStartBitrate(channel_id, &vie_codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003993
3994 if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
3995 LOG_RTCERR1(SetSendCodec, channel_id);
3996 return false;
3997 }
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +00003998
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +00003999 if (is_screencast) {
4000 engine()->vie()->rtp()->SetMinTransmitBitrate(channel_id,
4001 screencast_min_bitrate);
4002 // If screencast and min bitrate set, force enable pacer.
4003 if (screencast_min_bitrate > 0) {
4004 engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
4005 true);
4006 }
4007 } else {
4008 // In case of switching from screencast to regular capture, set
4009 // min bitrate padding and pacer back to defaults.
4010 engine()->vie()->rtp()->SetMinTransmitBitrate(channel_id, 0);
4011 engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
4012 leaky_bucket);
4013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004014 if (reset) {
4015 *reset = true;
4016 }
4017 LogSendCodecChange("Capture size changed");
4018 }
4019
4020 return true;
4021}
4022
4023void WebRtcVideoMediaChannel::MaybeChangeStartBitrate(
4024 int channel_id, webrtc::VideoCodec* video_codec) {
4025 if (video_codec->startBitrate < video_codec->minBitrate) {
4026 video_codec->startBitrate = video_codec->minBitrate;
4027 } else if (video_codec->startBitrate > video_codec->maxBitrate) {
4028 video_codec->startBitrate = video_codec->maxBitrate;
4029 }
4030
4031 // Use a previous target bitrate, if there is one.
4032 unsigned int current_target_bitrate = 0;
4033 if (engine()->vie()->codec()->GetCodecTargetBitrate(
4034 channel_id, &current_target_bitrate) == 0) {
4035 // Convert to kbps.
4036 current_target_bitrate /= 1000;
4037 if (current_target_bitrate > video_codec->maxBitrate) {
4038 current_target_bitrate = video_codec->maxBitrate;
4039 }
4040 if (current_target_bitrate > video_codec->startBitrate) {
4041 video_codec->startBitrate = current_target_bitrate;
4042 }
4043 }
4044}
4045
4046void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
4047 FlushBlackFrameData* black_frame_data =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00004048 static_cast<FlushBlackFrameData*>(msg->pdata);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004049 FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
4050 delete black_frame_data;
4051}
4052
4053int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
4054 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004055 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00004056 return MediaChannel::SendPacket(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004057}
4058
4059int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
4060 const void* data,
4061 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004062 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00004063 return MediaChannel::SendRtcp(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004064}
4065
4066void WebRtcVideoMediaChannel::QueueBlackFrame(uint32 ssrc, int64 timestamp,
4067 int framerate) {
4068 if (timestamp) {
4069 FlushBlackFrameData* black_frame_data = new FlushBlackFrameData(
4070 ssrc,
4071 timestamp);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00004072 const int delay_ms = static_cast<int>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004073 2 * cricket::VideoFormat::FpsToInterval(framerate) *
4074 talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
4075 worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
4076 }
4077}
4078
4079void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
4080 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
4081 if (!send_channel) {
4082 return;
4083 }
4084 talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
4085
4086 const WebRtcLocalStreamInfo* channel_stream_info =
4087 send_channel->local_stream_info();
4088 int64 last_frame_time_stamp = channel_stream_info->time_stamp();
4089 if (last_frame_time_stamp == timestamp) {
4090 size_t last_frame_width = 0;
4091 size_t last_frame_height = 0;
4092 int64 last_frame_elapsed_time = 0;
4093 channel_stream_info->GetLastFrameInfo(&last_frame_width, &last_frame_height,
4094 &last_frame_elapsed_time);
4095 if (!last_frame_width || !last_frame_height) {
4096 return;
4097 }
4098 WebRtcVideoFrame black_frame;
4099 // Black frame is not screencast.
4100 const bool screencasting = false;
4101 const int64 timestamp_delta = send_channel->interval();
4102 if (!black_frame.InitToBlack(send_codec_->width, send_codec_->height, 1, 1,
4103 last_frame_elapsed_time + timestamp_delta,
4104 last_frame_time_stamp + timestamp_delta) ||
4105 !SendFrame(send_channel, &black_frame, screencasting)) {
4106 LOG(LS_ERROR) << "Failed to send black frame.";
4107 }
4108 }
4109}
4110
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00004111void WebRtcVideoMediaChannel::OnCpuAdaptationUnable() {
4112 // ssrc is hardcoded to 0. This message is based on a system wide issue,
4113 // so finding which ssrc caused it doesn't matter.
4114 SignalMediaError(0, VideoMediaChannel::ERROR_REC_CPU_MAX_CANT_DOWNGRADE);
4115}
4116
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004117void WebRtcVideoMediaChannel::SetNetworkTransmissionState(
4118 bool is_transmitting) {
4119 LOG(LS_INFO) << "SetNetworkTransmissionState: " << is_transmitting;
4120 for (SendChannelMap::iterator iter = send_channels_.begin();
4121 iter != send_channels_.end(); ++iter) {
4122 WebRtcVideoChannelSendInfo* send_channel = iter->second;
4123 int channel_id = send_channel->channel_id();
4124 engine_->vie()->network()->SetNetworkTransmissionState(channel_id,
4125 is_transmitting);
4126 }
4127}
4128
4129bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
4130 int channel_id, const RtpHeaderExtension* extension) {
4131 bool enable = false;
4132 int id = 0;
4133 if (extension) {
4134 enable = true;
4135 id = extension->id;
4136 }
4137 if ((engine_->vie()->rtp()->*setter)(channel_id, enable, id) != 0) {
4138 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
4139 return false;
4140 }
4141 return true;
4142}
4143
4144bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
4145 int channel_id, const std::vector<RtpHeaderExtension>& extensions,
4146 const char header_extension_uri[]) {
4147 const RtpHeaderExtension* extension = FindHeaderExtension(extensions,
4148 header_extension_uri);
4149 return SetHeaderExtension(setter, channel_id, extension);
4150}
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00004151
4152bool WebRtcVideoMediaChannel::SetLocalRtxSsrc(int channel_id,
4153 const StreamParams& send_params,
4154 uint32 primary_ssrc,
4155 int stream_idx) {
4156 uint32 rtx_ssrc = 0;
4157 bool has_rtx = send_params.GetFidSsrc(primary_ssrc, &rtx_ssrc);
4158 if (has_rtx && engine()->vie()->rtp()->SetLocalSSRC(
4159 channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, stream_idx) != 0) {
4160 LOG_RTCERR4(SetLocalSSRC, channel_id, rtx_ssrc,
4161 webrtc::kViEStreamTypeRtx, stream_idx);
4162 return false;
4163 }
4164 return true;
4165}
4166
wu@webrtc.org24301a62013-12-13 19:17:43 +00004167void WebRtcVideoMediaChannel::MaybeConnectCapturer(VideoCapturer* capturer) {
4168 if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
wu@webrtc.orgf7d501d2014-03-27 23:48:25 +00004169 capturer->SignalVideoFrame.connect(this,
4170 &WebRtcVideoMediaChannel::SendFrame);
wu@webrtc.org24301a62013-12-13 19:17:43 +00004171 }
4172}
4173
4174void WebRtcVideoMediaChannel::MaybeDisconnectCapturer(VideoCapturer* capturer) {
4175 if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
4176 capturer->SignalVideoFrame.disconnect(this);
4177 }
4178}
4179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004180} // namespace cricket
4181
4182#endif // HAVE_WEBRTC_VIDEO