blob: 9a94b882a24ddeab2c9c58f0a19ae658501ea3c6 [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"
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +000063#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064
65#if !defined(LIBPEERCONNECTION_LIB)
66#ifndef HAVE_WEBRTC_VIDEO
67#error Need webrtc video
68#endif
69#include "talk/media/webrtc/webrtcmediaengine.h"
70
71WRME_EXPORT
72cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
73 webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc,
74 cricket::WebRtcVideoEncoderFactory* encoder_factory,
75 cricket::WebRtcVideoDecoderFactory* decoder_factory) {
76 return new cricket::WebRtcMediaEngine(adm, adm_sc, encoder_factory,
77 decoder_factory);
78}
79
80WRME_EXPORT
81void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
82 delete static_cast<cricket::WebRtcMediaEngine*>(media_engine);
83}
84#endif
85
86
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
110static const int kTimestampDeltaInSecondsForWarning = 2;
111
112static const int kMaxExternalVideoCodecs = 8;
113static const int kExternalVideoPayloadTypeBase = 120;
114
115// Static allocation of payload type values for external video codec.
116static int GetExternalVideoPayloadType(int index) {
117 ASSERT(index >= 0 && index < kMaxExternalVideoCodecs);
118 return kExternalVideoPayloadTypeBase + index;
119}
120
121static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
122 const char* delim = "\r\n";
123 // TODO(fbarchard): Fix strtok lint warning.
124 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
125 LOG_V(sev) << tok;
126 }
127}
128
129// Severity is an integer because it comes is assumed to be from command line.
130static int SeverityToFilter(int severity) {
131 int filter = webrtc::kTraceNone;
132 switch (severity) {
133 case talk_base::LS_VERBOSE:
134 filter |= webrtc::kTraceAll;
135 case talk_base::LS_INFO:
136 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
137 case talk_base::LS_WARNING:
138 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
139 case talk_base::LS_ERROR:
140 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
141 }
142 return filter;
143}
144
145static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
146
147static const bool kNotSending = false;
148
149// Extension header for RTP timestamp offset, see RFC 5450 for details:
150// http://tools.ietf.org/html/rfc5450
151static const char kRtpTimestampOffsetHeaderExtension[] =
152 "urn:ietf:params:rtp-hdrext:toffset";
153static const int kRtpTimeOffsetExtensionId = 2;
154
155// Extension header for absolute send time, see url for details:
156// http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
157static const char kRtpAbsoluteSendTimeHeaderExtension[] =
158 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
159static const int kRtpAbsoluteSendTimeExtensionId = 3;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000160// Default video dscp value.
161// See http://tools.ietf.org/html/rfc2474 for details
162// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
163static const talk_base::DiffServCodePoint kVideoDscpValue =
164 talk_base::DSCP_AF41;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000165
166static bool IsNackEnabled(const VideoCodec& codec) {
167 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
168 kParamValueEmpty));
169}
170
171// Returns true if Receiver Estimated Max Bitrate is enabled.
172static bool IsRembEnabled(const VideoCodec& codec) {
173 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamRemb,
174 kParamValueEmpty));
175}
176
177struct FlushBlackFrameData : public talk_base::MessageData {
178 FlushBlackFrameData(uint32 s, int64 t) : ssrc(s), timestamp(t) {
179 }
180 uint32 ssrc;
181 int64 timestamp;
182};
183
184class WebRtcRenderAdapter : public webrtc::ExternalRenderer {
185 public:
186 explicit WebRtcRenderAdapter(VideoRenderer* renderer)
187 : renderer_(renderer), width_(0), height_(0), watermark_enabled_(false) {
188 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000189
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190 virtual ~WebRtcRenderAdapter() {
191 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000192
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193 void set_watermark_enabled(bool enable) {
194 talk_base::CritScope cs(&crit_);
195 watermark_enabled_ = enable;
196 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000197
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000198 void SetRenderer(VideoRenderer* renderer) {
199 talk_base::CritScope cs(&crit_);
200 renderer_ = renderer;
201 // FrameSizeChange may have already been called when renderer was not set.
202 // If so we should call SetSize here.
203 // TODO(ronghuawu): Add unit test for this case. Didn't do it now
204 // because the WebRtcRenderAdapter is currently hiding in cc file. No
205 // good way to get access to it from the unit test.
206 if (width_ > 0 && height_ > 0 && renderer_ != NULL) {
207 if (!renderer_->SetSize(width_, height_, 0)) {
208 LOG(LS_ERROR)
209 << "WebRtcRenderAdapter SetRenderer failed to SetSize to: "
210 << width_ << "x" << height_;
211 }
212 }
213 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000214
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 // Implementation of webrtc::ExternalRenderer.
216 virtual int FrameSizeChange(unsigned int width, unsigned int height,
217 unsigned int /*number_of_streams*/) {
218 talk_base::CritScope cs(&crit_);
219 width_ = width;
220 height_ = height;
221 LOG(LS_INFO) << "WebRtcRenderAdapter frame size changed to: "
222 << width << "x" << height;
223 if (renderer_ == NULL) {
224 LOG(LS_VERBOSE) << "WebRtcRenderAdapter the renderer has not been set. "
225 << "SetSize will be called later in SetRenderer.";
226 return 0;
227 }
228 return renderer_->SetSize(width_, height_, 0) ? 0 : -1;
229 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000230
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000231 virtual int DeliverFrame(unsigned char* buffer, int buffer_size,
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000232 uint32_t time_stamp, int64_t render_time,
233 void* handle) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000234 talk_base::CritScope cs(&crit_);
235 frame_rate_tracker_.Update(1);
236 if (renderer_ == NULL) {
237 return 0;
238 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000239 // Convert 90K rtp timestamp to ns timestamp.
240 int64 rtp_time_stamp_in_ns = (time_stamp / 90) *
241 talk_base::kNumNanosecsPerMillisec;
242 // Convert milisecond render time to ns timestamp.
243 int64 render_time_stamp_in_ns = render_time *
244 talk_base::kNumNanosecsPerMillisec;
245 // Send the rtp timestamp to renderer as the VideoFrame timestamp.
246 // and the render timestamp as the VideoFrame elapsed_time.
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000247 if (handle == NULL) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000248 return DeliverBufferFrame(buffer, buffer_size, render_time_stamp_in_ns,
249 rtp_time_stamp_in_ns);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000250 } else {
251 return DeliverTextureFrame(handle, render_time_stamp_in_ns,
252 rtp_time_stamp_in_ns);
253 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000254 }
255
256 virtual bool IsTextureSupported() { return true; }
257
258 int DeliverBufferFrame(unsigned char* buffer, int buffer_size,
259 int64 elapsed_time, int64 time_stamp) {
260 WebRtcVideoFrame video_frame;
wu@webrtc.org16d62542013-11-05 23:45:14 +0000261 video_frame.Alias(buffer, buffer_size, width_, height_,
262 1, 1, elapsed_time, time_stamp, 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263
264
265 // Sanity check on decoded frame size.
266 if (buffer_size != static_cast<int>(VideoFrame::SizeOf(width_, height_))) {
267 LOG(LS_WARNING) << "WebRtcRenderAdapter received a strange frame size: "
268 << buffer_size;
269 }
270
271 int ret = renderer_->RenderFrame(&video_frame) ? 0 : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 return ret;
273 }
274
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000275 int DeliverTextureFrame(void* handle, int64 elapsed_time, int64 time_stamp) {
276 WebRtcTextureVideoFrame video_frame(
277 static_cast<webrtc::NativeHandle*>(handle), width_, height_,
278 elapsed_time, time_stamp);
279 return renderer_->RenderFrame(&video_frame);
280 }
281
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000282 unsigned int width() {
283 talk_base::CritScope cs(&crit_);
284 return width_;
285 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000286
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000287 unsigned int height() {
288 talk_base::CritScope cs(&crit_);
289 return height_;
290 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000291
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000292 int framerate() {
293 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000294 return static_cast<int>(frame_rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000295 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000296
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297 VideoRenderer* renderer() {
298 talk_base::CritScope cs(&crit_);
299 return renderer_;
300 }
301
302 private:
303 talk_base::CriticalSection crit_;
304 VideoRenderer* renderer_;
305 unsigned int width_;
306 unsigned int height_;
307 talk_base::RateTracker frame_rate_tracker_;
308 bool watermark_enabled_;
309};
310
311class WebRtcDecoderObserver : public webrtc::ViEDecoderObserver {
312 public:
313 explicit WebRtcDecoderObserver(int video_channel)
314 : video_channel_(video_channel),
315 framerate_(0),
316 bitrate_(0),
wu@webrtc.org97077a32013-10-25 21:18:33 +0000317 decode_ms_(0),
318 max_decode_ms_(0),
319 current_delay_ms_(0),
320 target_delay_ms_(0),
321 jitter_buffer_ms_(0),
322 min_playout_delay_ms_(0),
323 render_delay_ms_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000324 firs_requested_(0) {
325 }
326
327 // virtual functions from VieDecoderObserver.
328 virtual void IncomingCodecChanged(const int videoChannel,
329 const webrtc::VideoCodec& videoCodec) {}
330 virtual void IncomingRate(const int videoChannel,
331 const unsigned int framerate,
332 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000333 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000334 ASSERT(video_channel_ == videoChannel);
335 framerate_ = framerate;
336 bitrate_ = bitrate;
337 }
wu@webrtc.org97077a32013-10-25 21:18:33 +0000338
339 virtual void DecoderTiming(int decode_ms,
340 int max_decode_ms,
341 int current_delay_ms,
342 int target_delay_ms,
343 int jitter_buffer_ms,
344 int min_playout_delay_ms,
345 int render_delay_ms) {
346 talk_base::CritScope cs(&crit_);
347 decode_ms_ = decode_ms;
348 max_decode_ms_ = max_decode_ms;
349 current_delay_ms_ = current_delay_ms;
350 target_delay_ms_ = target_delay_ms;
351 jitter_buffer_ms_ = jitter_buffer_ms;
352 min_playout_delay_ms_ = min_playout_delay_ms;
353 render_delay_ms_ = render_delay_ms;
354 }
355
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 virtual void RequestNewKeyFrame(const int videoChannel) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000357 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000358 ASSERT(video_channel_ == videoChannel);
359 ++firs_requested_;
360 }
361
wu@webrtc.org97077a32013-10-25 21:18:33 +0000362 // Populate |rinfo| based on previously-set data in |*this|.
363 void ExportTo(VideoReceiverInfo* rinfo) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000364 talk_base::CritScope cs(&crit_);
wu@webrtc.org97077a32013-10-25 21:18:33 +0000365 rinfo->firs_sent = firs_requested_;
366 rinfo->framerate_rcvd = framerate_;
367 rinfo->decode_ms = decode_ms_;
368 rinfo->max_decode_ms = max_decode_ms_;
369 rinfo->current_delay_ms = current_delay_ms_;
370 rinfo->target_delay_ms = target_delay_ms_;
371 rinfo->jitter_buffer_ms = jitter_buffer_ms_;
372 rinfo->min_playout_delay_ms = min_playout_delay_ms_;
373 rinfo->render_delay_ms = render_delay_ms_;
wu@webrtc.org78187522013-10-07 23:32:02 +0000374 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375
376 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000377 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000378 int video_channel_;
379 int framerate_;
380 int bitrate_;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000381 int decode_ms_;
382 int max_decode_ms_;
383 int current_delay_ms_;
384 int target_delay_ms_;
385 int jitter_buffer_ms_;
386 int min_playout_delay_ms_;
387 int render_delay_ms_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388 int firs_requested_;
389};
390
391class WebRtcEncoderObserver : public webrtc::ViEEncoderObserver {
392 public:
393 explicit WebRtcEncoderObserver(int video_channel)
394 : video_channel_(video_channel),
395 framerate_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000396 bitrate_(0),
397 suspended_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000398 }
399
400 // virtual functions from VieEncoderObserver.
401 virtual void OutgoingRate(const int videoChannel,
402 const unsigned int framerate,
403 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000404 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405 ASSERT(video_channel_ == videoChannel);
406 framerate_ = framerate;
407 bitrate_ = bitrate;
408 }
409
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000410 virtual void SuspendChange(int video_channel, bool is_suspended) {
411 talk_base::CritScope cs(&crit_);
412 ASSERT(video_channel_ == video_channel);
413 suspended_ = is_suspended;
414 }
415
wu@webrtc.org78187522013-10-07 23:32:02 +0000416 int framerate() const {
417 talk_base::CritScope cs(&crit_);
418 return framerate_;
419 }
420 int bitrate() const {
421 talk_base::CritScope cs(&crit_);
422 return bitrate_;
423 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000424 bool suspended() const {
425 talk_base::CritScope cs(&crit_);
426 return suspended_;
427 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000428
429 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000430 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000431 int video_channel_;
432 int framerate_;
433 int bitrate_;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000434 bool suspended_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000435};
436
437class WebRtcLocalStreamInfo {
438 public:
439 WebRtcLocalStreamInfo()
440 : width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
441 size_t width() const {
442 talk_base::CritScope cs(&crit_);
443 return width_;
444 }
445 size_t height() const {
446 talk_base::CritScope cs(&crit_);
447 return height_;
448 }
449 int64 elapsed_time() const {
450 talk_base::CritScope cs(&crit_);
451 return elapsed_time_;
452 }
453 int64 time_stamp() const {
454 talk_base::CritScope cs(&crit_);
455 return time_stamp_;
456 }
457 int framerate() {
458 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000459 return static_cast<int>(rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000460 }
461 void GetLastFrameInfo(
462 size_t* width, size_t* height, int64* elapsed_time) const {
463 talk_base::CritScope cs(&crit_);
464 *width = width_;
465 *height = height_;
466 *elapsed_time = elapsed_time_;
467 }
468
469 void UpdateFrame(const VideoFrame* frame) {
470 talk_base::CritScope cs(&crit_);
471
472 width_ = frame->GetWidth();
473 height_ = frame->GetHeight();
474 elapsed_time_ = frame->GetElapsedTime();
475 time_stamp_ = frame->GetTimeStamp();
476
477 rate_tracker_.Update(1);
478 }
479
480 private:
481 mutable talk_base::CriticalSection crit_;
482 size_t width_;
483 size_t height_;
484 int64 elapsed_time_;
485 int64 time_stamp_;
486 talk_base::RateTracker rate_tracker_;
487
488 DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
489};
490
491// WebRtcVideoChannelRecvInfo is a container class with members such as renderer
492// and a decoder observer that is used by receive channels.
493// It must exist as long as the receive channel is connected to renderer or a
494// decoder observer in this class and methods in the class should only be called
495// from the worker thread.
496class WebRtcVideoChannelRecvInfo {
497 public:
498 typedef std::map<int, webrtc::VideoDecoder*> DecoderMap; // key: payload type
499 explicit WebRtcVideoChannelRecvInfo(int channel_id)
500 : channel_id_(channel_id),
501 render_adapter_(NULL),
502 decoder_observer_(channel_id) {
503 }
504 int channel_id() { return channel_id_; }
505 void SetRenderer(VideoRenderer* renderer) {
506 render_adapter_.SetRenderer(renderer);
507 }
508 WebRtcRenderAdapter* render_adapter() { return &render_adapter_; }
509 WebRtcDecoderObserver* decoder_observer() { return &decoder_observer_; }
510 void RegisterDecoder(int pl_type, webrtc::VideoDecoder* decoder) {
511 ASSERT(!IsDecoderRegistered(pl_type));
512 registered_decoders_[pl_type] = decoder;
513 }
514 bool IsDecoderRegistered(int pl_type) {
515 return registered_decoders_.count(pl_type) != 0;
516 }
517 const DecoderMap& registered_decoders() {
518 return registered_decoders_;
519 }
520 void ClearRegisteredDecoders() {
521 registered_decoders_.clear();
522 }
523
524 private:
525 int channel_id_; // Webrtc video channel number.
526 // Renderer for this channel.
527 WebRtcRenderAdapter render_adapter_;
528 WebRtcDecoderObserver decoder_observer_;
529 DecoderMap registered_decoders_;
530};
531
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000532class WebRtcOveruseObserver : public webrtc::CpuOveruseObserver {
533 public:
534 explicit WebRtcOveruseObserver(CoordinatedVideoAdapter* video_adapter)
535 : video_adapter_(video_adapter),
536 enabled_(false) {
537 }
538
539 // TODO(mflodman): Consider sending resolution as part of event, to let
540 // adapter know what resolution the request is based on. Helps eliminate stale
541 // data, race conditions.
542 virtual void OveruseDetected() OVERRIDE {
543 talk_base::CritScope cs(&crit_);
544 if (!enabled_) {
545 return;
546 }
547
548 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
549 }
550
551 virtual void NormalUsage() OVERRIDE {
552 talk_base::CritScope cs(&crit_);
553 if (!enabled_) {
554 return;
555 }
556
557 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::UPGRADE);
558 }
559
560 void Enable(bool enable) {
561 talk_base::CritScope cs(&crit_);
562 enabled_ = enable;
563 }
564
565 private:
566 CoordinatedVideoAdapter* video_adapter_;
567 bool enabled_;
568 talk_base::CriticalSection crit_;
569};
570
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000571
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000572class WebRtcVideoChannelSendInfo : public sigslot::has_slots<> {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 public:
574 typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
575 WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
576 webrtc::ViEExternalCapture* external_capture,
577 talk_base::CpuMonitor* cpu_monitor)
578 : channel_id_(channel_id),
579 capture_id_(capture_id),
580 sending_(false),
581 muted_(false),
582 video_capturer_(NULL),
583 encoder_observer_(channel_id),
584 external_capture_(external_capture),
585 capturer_updated_(false),
586 interval_(0),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000587 cpu_monitor_(cpu_monitor) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000588 overuse_observer_.reset(new WebRtcOveruseObserver(&video_adapter_));
589 SignalCpuAdaptationUnable.repeat(video_adapter_.SignalCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000590 if (cpu_monitor) {
591 cpu_monitor->SignalUpdate.connect(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000592 &video_adapter_, &CoordinatedVideoAdapter::OnCpuLoadUpdated);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 }
594 }
595
596 int channel_id() const { return channel_id_; }
597 int capture_id() const { return capture_id_; }
598 void set_sending(bool sending) { sending_ = sending; }
599 bool sending() const { return sending_; }
600 void set_muted(bool on) {
601 // TODO(asapersson): add support.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000602 // video_adapter_.SetBlackOutput(on);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603 muted_ = on;
604 }
605 bool muted() {return muted_; }
606
607 WebRtcEncoderObserver* encoder_observer() { return &encoder_observer_; }
608 webrtc::ViEExternalCapture* external_capture() { return external_capture_; }
609 const VideoFormat& video_format() const {
610 return video_format_;
611 }
612 void set_video_format(const VideoFormat& video_format) {
613 video_format_ = video_format;
614 if (video_format_ != cricket::VideoFormat()) {
615 interval_ = video_format_.interval;
616 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000617 video_adapter_.OnOutputFormatRequest(video_format_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 }
619 void set_interval(int64 interval) {
620 if (video_format() == cricket::VideoFormat()) {
621 interval_ = interval;
622 }
623 }
624 int64 interval() { return interval_; }
625
626 void InitializeAdapterOutputFormat(const webrtc::VideoCodec& codec) {
627 VideoFormat format(codec.width, codec.height,
628 VideoFormat::FpsToInterval(codec.maxFramerate),
629 FOURCC_I420);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000630 if (video_adapter_.output_format().IsSize0x0()) {
631 video_adapter_.SetOutputFormat(format);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632 }
633 }
634
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000635 int CurrentAdaptReason() const {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000636 return video_adapter_.adapt_reason();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000638 webrtc::CpuOveruseObserver* overuse_observer() {
639 return overuse_observer_.get();
640 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641
642 StreamParams* stream_params() { return stream_params_.get(); }
643 void set_stream_params(const StreamParams& sp) {
644 stream_params_.reset(new StreamParams(sp));
645 }
646 void ClearStreamParams() { stream_params_.reset(); }
647 bool has_ssrc(uint32 local_ssrc) const {
648 return !stream_params_ ? false :
649 stream_params_->has_ssrc(local_ssrc);
650 }
651 WebRtcLocalStreamInfo* local_stream_info() {
652 return &local_stream_info_;
653 }
654 VideoCapturer* video_capturer() {
655 return video_capturer_;
656 }
657 void set_video_capturer(VideoCapturer* video_capturer) {
658 if (video_capturer == video_capturer_) {
659 return;
660 }
661 capturer_updated_ = true;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000662
663 // Disconnect from the previous video capturer.
664 if (video_capturer_) {
665 video_capturer_->SignalAdaptFrame.disconnect(this);
666 }
667
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668 video_capturer_ = video_capturer;
669 if (video_capturer && !video_capturer->IsScreencast()) {
670 const VideoFormat* capture_format = video_capturer->GetCaptureFormat();
671 if (capture_format) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000672 // TODO(thorcarpenter): This is broken. Video capturer doesn't have
673 // a capture format until the capturer is started. So, if
674 // the capturer is started immediately after calling set_video_capturer
675 // video adapter may not have the input format set, the interval may
676 // be zero, and all frames may be dropped.
677 // Consider fixing this by having video_adapter keep a pointer to the
678 // video capturer.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000679 video_adapter_.SetInputFormat(*capture_format);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 }
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000681 // TODO(thorcarpenter): When the adapter supports "only frame dropping"
682 // mode, also hook it up to screencast capturers.
683 video_capturer->SignalAdaptFrame.connect(
684 this, &WebRtcVideoChannelSendInfo::AdaptFrame);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 }
686 }
687
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000688 CoordinatedVideoAdapter* video_adapter() { return &video_adapter_; }
689
690 void AdaptFrame(VideoCapturer* capturer, const VideoFrame* input,
691 VideoFrame** adapted) {
692 video_adapter_.AdaptFrame(input, adapted);
693 }
694
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 void ApplyCpuOptions(const VideoOptions& options) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000696 bool cpu_adapt, cpu_smoothing, adapt_third;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000697 float low, med, high;
698 if (options.adapt_input_to_cpu_usage.Get(&cpu_adapt)) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000699 video_adapter_.set_cpu_adaptation(cpu_adapt);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000701 if (options.adapt_cpu_with_smoothing.Get(&cpu_smoothing)) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000702 video_adapter_.set_cpu_smoothing(cpu_smoothing);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000703 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 if (options.process_adaptation_threshhold.Get(&med)) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000705 video_adapter_.set_process_threshold(med);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000706 }
707 if (options.system_low_adaptation_threshhold.Get(&low)) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000708 video_adapter_.set_low_system_threshold(low);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000709 }
710 if (options.system_high_adaptation_threshhold.Get(&high)) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000711 video_adapter_.set_high_system_threshold(high);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000713 if (options.video_adapt_third.Get(&adapt_third)) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000714 video_adapter_.set_scale_third(adapt_third);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000717
718 void SetCpuOveruseDetection(bool enable) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000719 if (cpu_monitor_ && enable) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000720 cpu_monitor_->SignalUpdate.disconnect(&video_adapter_);
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000721 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000722 overuse_observer_->Enable(enable);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000723 video_adapter_.set_cpu_adaptation(enable);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000724 }
725
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 void ProcessFrame(const VideoFrame& original_frame, bool mute,
727 VideoFrame** processed_frame) {
728 if (!mute) {
729 *processed_frame = original_frame.Copy();
730 } else {
731 WebRtcVideoFrame* black_frame = new WebRtcVideoFrame();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000732 black_frame->InitToBlack(static_cast<int>(original_frame.GetWidth()),
733 static_cast<int>(original_frame.GetHeight()),
734 1, 1,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 original_frame.GetElapsedTime(),
736 original_frame.GetTimeStamp());
737 *processed_frame = black_frame;
738 }
739 local_stream_info_.UpdateFrame(*processed_frame);
740 }
741 void RegisterEncoder(int pl_type, webrtc::VideoEncoder* encoder) {
742 ASSERT(!IsEncoderRegistered(pl_type));
743 registered_encoders_[pl_type] = encoder;
744 }
745 bool IsEncoderRegistered(int pl_type) {
746 return registered_encoders_.count(pl_type) != 0;
747 }
748 const EncoderMap& registered_encoders() {
749 return registered_encoders_;
750 }
751 void ClearRegisteredEncoders() {
752 registered_encoders_.clear();
753 }
754
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000755 sigslot::repeater0<> SignalCpuAdaptationUnable;
756
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757 private:
758 int channel_id_;
759 int capture_id_;
760 bool sending_;
761 bool muted_;
762 VideoCapturer* video_capturer_;
763 WebRtcEncoderObserver encoder_observer_;
764 webrtc::ViEExternalCapture* external_capture_;
765 EncoderMap registered_encoders_;
766
767 VideoFormat video_format_;
768
769 talk_base::scoped_ptr<StreamParams> stream_params_;
770
771 WebRtcLocalStreamInfo local_stream_info_;
772
773 bool capturer_updated_;
774
775 int64 interval_;
776
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000777 CoordinatedVideoAdapter video_adapter_;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000778 talk_base::CpuMonitor* cpu_monitor_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000779 talk_base::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780};
781
782const WebRtcVideoEngine::VideoCodecPref
783 WebRtcVideoEngine::kVideoCodecPrefs[] = {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000784 {kVp8PayloadName, 100, -1, 0},
785 {kRedPayloadName, 116, -1, 1},
786 {kFecPayloadName, 117, -1, 2},
787 {kRtxCodecName, 96, 100, 3},
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788};
789
790// The formats are sorted by the descending order of width. We use the order to
791// find the next format for CPU and bandwidth adaptation.
792const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
793 {1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
794 {1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
795 {960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
796 {960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
797 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
798 {640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
799 {640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
800 {480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
801 {480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
802 {480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
803 {320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
804 {320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
805 {320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
806 {240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
807 {240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
808 {240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
809 {160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
810 {160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
811 {160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
812};
813
814const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
815 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
816
817static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
818 webrtc::VideoCodec* target_codec) {
819 if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
820 return;
821 }
822 target_codec->width = video_format.width;
823 target_codec->height = video_format.height;
824 target_codec->maxFramerate = cricket::VideoFormat::IntervalToFps(
825 video_format.interval);
826}
827
828WebRtcVideoEngine::WebRtcVideoEngine() {
829 Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
830 new talk_base::CpuMonitor(NULL));
831}
832
833WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
834 ViEWrapper* vie_wrapper,
835 talk_base::CpuMonitor* cpu_monitor) {
836 Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
837}
838
839WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
840 ViEWrapper* vie_wrapper,
841 ViETraceWrapper* tracing,
842 talk_base::CpuMonitor* cpu_monitor) {
843 Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
844}
845
846void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
847 ViETraceWrapper* tracing,
848 WebRtcVoiceEngine* voice_engine,
849 talk_base::CpuMonitor* cpu_monitor) {
850 LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
851 worker_thread_ = NULL;
852 vie_wrapper_.reset(vie_wrapper);
853 vie_wrapper_base_initialized_ = false;
854 tracing_.reset(tracing);
855 voice_engine_ = voice_engine;
856 initialized_ = false;
857 SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
858 render_module_.reset(new WebRtcPassthroughRender());
859 local_renderer_w_ = local_renderer_h_ = 0;
860 local_renderer_ = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861 capture_started_ = false;
862 decoder_factory_ = NULL;
863 encoder_factory_ = NULL;
864 cpu_monitor_.reset(cpu_monitor);
865
866 SetTraceOptions("");
867 if (tracing_->SetTraceCallback(this) != 0) {
868 LOG_RTCERR1(SetTraceCallback, this);
869 }
870
871 // Set default quality levels for our supported codecs. We override them here
872 // if we know your cpu performance is low, and they can be updated explicitly
873 // by calling SetDefaultCodec. For example by a flute preference setting, or
874 // by the server with a jec in response to our reported system info.
875 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
876 kVideoCodecPrefs[0].name,
877 kDefaultVideoFormat.width,
878 kDefaultVideoFormat.height,
879 VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
880 0);
881 if (!SetDefaultCodec(max_codec)) {
882 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
883 }
884
885
886 // Load our RTP Header extensions.
887 rtp_header_extensions_.push_back(
888 RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
889 kRtpTimeOffsetExtensionId));
890 rtp_header_extensions_.push_back(
891 RtpHeaderExtension(kRtpAbsoluteSendTimeHeaderExtension,
892 kRtpAbsoluteSendTimeExtensionId));
893}
894
895WebRtcVideoEngine::~WebRtcVideoEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896 LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
897 if (initialized_) {
898 Terminate();
899 }
900 if (encoder_factory_) {
901 encoder_factory_->RemoveObserver(this);
902 }
903 tracing_->SetTraceCallback(NULL);
904 // Test to see if the media processor was deregistered properly.
905 ASSERT(SignalMediaFrame.is_empty());
906}
907
908bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
909 LOG(LS_INFO) << "WebRtcVideoEngine::Init";
910 worker_thread_ = worker_thread;
911 ASSERT(worker_thread_ != NULL);
912
913 cpu_monitor_->set_thread(worker_thread_);
914 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
915 LOG(LS_ERROR) << "Failed to start CPU monitor.";
916 cpu_monitor_.reset();
917 }
918
919 bool result = InitVideoEngine();
920 if (result) {
921 LOG(LS_INFO) << "VideoEngine Init done";
922 } else {
923 LOG(LS_ERROR) << "VideoEngine Init failed, releasing";
924 Terminate();
925 }
926 return result;
927}
928
929bool WebRtcVideoEngine::InitVideoEngine() {
930 LOG(LS_INFO) << "WebRtcVideoEngine::InitVideoEngine";
931
932 // Init WebRTC VideoEngine.
933 if (!vie_wrapper_base_initialized_) {
934 if (vie_wrapper_->base()->Init() != 0) {
935 LOG_RTCERR0(Init);
936 return false;
937 }
938 vie_wrapper_base_initialized_ = true;
939 }
940
941 // Log the VoiceEngine version info.
942 char buffer[1024] = "";
943 if (vie_wrapper_->base()->GetVersion(buffer) != 0) {
944 LOG_RTCERR0(GetVersion);
945 return false;
946 }
947
948 LOG(LS_INFO) << "WebRtc VideoEngine Version:";
949 LogMultiline(talk_base::LS_INFO, buffer);
950
951 // Hook up to VoiceEngine for sync purposes, if supplied.
952 if (!voice_engine_) {
953 LOG(LS_WARNING) << "NULL voice engine";
954 } else if ((vie_wrapper_->base()->SetVoiceEngine(
955 voice_engine_->voe()->engine())) != 0) {
956 LOG_RTCERR0(SetVoiceEngine);
957 return false;
958 }
959
960 // Register our custom render module.
961 if (vie_wrapper_->render()->RegisterVideoRenderModule(
962 *render_module_.get()) != 0) {
963 LOG_RTCERR0(RegisterVideoRenderModule);
964 return false;
965 }
966
967 initialized_ = true;
968 return true;
969}
970
971void WebRtcVideoEngine::Terminate() {
972 LOG(LS_INFO) << "WebRtcVideoEngine::Terminate";
973 initialized_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974
975 if (vie_wrapper_->render()->DeRegisterVideoRenderModule(
976 *render_module_.get()) != 0) {
977 LOG_RTCERR0(DeRegisterVideoRenderModule);
978 }
979
980 if (vie_wrapper_->base()->SetVoiceEngine(NULL) != 0) {
981 LOG_RTCERR0(SetVoiceEngine);
982 }
983
984 cpu_monitor_->Stop();
985}
986
987int WebRtcVideoEngine::GetCapabilities() {
988 return VIDEO_RECV | VIDEO_SEND;
989}
990
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000991bool WebRtcVideoEngine::SetOptions(const VideoOptions &options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992 return true;
993}
994
995bool WebRtcVideoEngine::SetDefaultEncoderConfig(
996 const VideoEncoderConfig& config) {
997 return SetDefaultCodec(config.max_codec);
998}
999
wu@webrtc.org78187522013-10-07 23:32:02 +00001000VideoEncoderConfig WebRtcVideoEngine::GetDefaultEncoderConfig() const {
1001 ASSERT(!video_codecs_.empty());
1002 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1003 kVideoCodecPrefs[0].name,
1004 video_codecs_[0].width,
1005 video_codecs_[0].height,
1006 video_codecs_[0].framerate,
1007 0);
1008 return VideoEncoderConfig(max_codec);
1009}
1010
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011// SetDefaultCodec may be called while the capturer is running. For example, a
1012// test call is started in a page with QVGA default codec, and then a real call
1013// is started in another page with VGA default codec. This is the corner case
1014// and happens only when a session is started. We ignore this case currently.
1015bool WebRtcVideoEngine::SetDefaultCodec(const VideoCodec& codec) {
1016 if (!RebuildCodecList(codec)) {
1017 LOG(LS_WARNING) << "Failed to RebuildCodecList";
1018 return false;
1019 }
1020
wu@webrtc.org78187522013-10-07 23:32:02 +00001021 ASSERT(!video_codecs_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 default_codec_format_ = VideoFormat(
1023 video_codecs_[0].width,
1024 video_codecs_[0].height,
1025 VideoFormat::FpsToInterval(video_codecs_[0].framerate),
1026 FOURCC_ANY);
1027 return true;
1028}
1029
1030WebRtcVideoMediaChannel* WebRtcVideoEngine::CreateChannel(
1031 VoiceMediaChannel* voice_channel) {
1032 WebRtcVideoMediaChannel* channel =
1033 new WebRtcVideoMediaChannel(this, voice_channel);
1034 if (!channel->Init()) {
1035 delete channel;
1036 channel = NULL;
1037 }
1038 return channel;
1039}
1040
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
1042 local_renderer_w_ = local_renderer_h_ = 0;
1043 local_renderer_ = renderer;
1044 return true;
1045}
1046
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
1048 return video_codecs_;
1049}
1050
1051const std::vector<RtpHeaderExtension>&
1052WebRtcVideoEngine::rtp_header_extensions() const {
1053 return rtp_header_extensions_;
1054}
1055
1056void WebRtcVideoEngine::SetLogging(int min_sev, const char* filter) {
1057 // if min_sev == -1, we keep the current log level.
1058 if (min_sev >= 0) {
1059 SetTraceFilter(SeverityToFilter(min_sev));
1060 }
1061 SetTraceOptions(filter);
1062}
1063
1064int WebRtcVideoEngine::GetLastEngineError() {
1065 return vie_wrapper_->error();
1066}
1067
1068// Checks to see whether we comprehend and could receive a particular codec
1069bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
1070 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
1071 const VideoFormat fmt(kVideoFormats[i]);
1072 if ((in.width == 0 && in.height == 0) ||
1073 (fmt.width == in.width && fmt.height == in.height)) {
1074 if (encoder_factory_) {
1075 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1076 encoder_factory_->codecs();
1077 for (size_t j = 0; j < codecs.size(); ++j) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001078 VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001079 codecs[j].name, 0, 0, 0, 0);
1080 if (codec.Matches(in))
1081 return true;
1082 }
1083 }
1084 for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
1085 VideoCodec codec(kVideoCodecPrefs[j].payload_type,
1086 kVideoCodecPrefs[j].name, 0, 0, 0, 0);
1087 if (codec.Matches(in)) {
1088 return true;
1089 }
1090 }
1091 }
1092 }
1093 return false;
1094}
1095
1096// Given the requested codec, returns true if we can send that codec type and
1097// updates out with the best quality we could send for that codec. If current is
1098// not empty, we constrain out so that its aspect ratio matches current's.
1099bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
1100 const VideoCodec& current,
1101 VideoCodec* out) {
1102 if (!out) {
1103 return false;
1104 }
1105
1106 std::vector<VideoCodec>::const_iterator local_max;
1107 for (local_max = video_codecs_.begin();
1108 local_max < video_codecs_.end();
1109 ++local_max) {
1110 // First match codecs by payload type
1111 if (!requested.Matches(*local_max)) {
1112 continue;
1113 }
1114
1115 out->id = requested.id;
1116 out->name = requested.name;
1117 out->preference = requested.preference;
1118 out->params = requested.params;
1119 out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
1120 out->width = 0;
1121 out->height = 0;
1122 out->params = requested.params;
1123 out->feedback_params = requested.feedback_params;
1124
1125 if (0 == requested.width && 0 == requested.height) {
1126 // Special case with resolution 0. The channel should not send frames.
1127 return true;
1128 } else if (0 == requested.width || 0 == requested.height) {
1129 // 0xn and nx0 are invalid resolutions.
1130 return false;
1131 }
1132
1133 // Pick the best quality that is within their and our bounds and has the
1134 // correct aspect ratio.
1135 for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
1136 const VideoFormat format(kVideoFormats[j]);
1137
1138 // Skip any format that is larger than the local or remote maximums, or
1139 // smaller than the current best match
1140 if (format.width > requested.width || format.height > requested.height ||
1141 format.width > local_max->width ||
1142 (format.width < out->width && format.height < out->height)) {
1143 continue;
1144 }
1145
1146 bool better = false;
1147
1148 // Check any further constraints on this prospective format
1149 if (!out->width || !out->height) {
1150 // If we don't have any matches yet, this is the best so far.
1151 better = true;
1152 } else if (current.width && current.height) {
1153 // current is set so format must match its ratio exactly.
1154 better =
1155 (format.width * current.height == format.height * current.width);
1156 } else {
1157 // Prefer closer aspect ratios i.e
1158 // format.aspect - requested.aspect < out.aspect - requested.aspect
1159 better = abs(format.width * requested.height * out->height -
1160 requested.width * format.height * out->height) <
1161 abs(out->width * format.height * requested.height -
1162 requested.width * format.height * out->height);
1163 }
1164
1165 if (better) {
1166 out->width = format.width;
1167 out->height = format.height;
1168 }
1169 }
1170 if (out->width > 0) {
1171 return true;
1172 }
1173 }
1174 return false;
1175}
1176
1177static void ConvertToCricketVideoCodec(
1178 const webrtc::VideoCodec& in_codec, VideoCodec* out_codec) {
1179 out_codec->id = in_codec.plType;
1180 out_codec->name = in_codec.plName;
1181 out_codec->width = in_codec.width;
1182 out_codec->height = in_codec.height;
1183 out_codec->framerate = in_codec.maxFramerate;
1184 out_codec->SetParam(kCodecParamMinBitrate, in_codec.minBitrate);
1185 out_codec->SetParam(kCodecParamMaxBitrate, in_codec.maxBitrate);
1186 if (in_codec.qpMax) {
1187 out_codec->SetParam(kCodecParamMaxQuantization, in_codec.qpMax);
1188 }
1189}
1190
1191bool WebRtcVideoEngine::ConvertFromCricketVideoCodec(
1192 const VideoCodec& in_codec, webrtc::VideoCodec* out_codec) {
1193 bool found = false;
1194 int ncodecs = vie_wrapper_->codec()->NumberOfCodecs();
1195 for (int i = 0; i < ncodecs; ++i) {
1196 if (vie_wrapper_->codec()->GetCodec(i, *out_codec) == 0 &&
1197 _stricmp(in_codec.name.c_str(), out_codec->plName) == 0) {
1198 found = true;
1199 break;
1200 }
1201 }
1202
1203 // If not found, check if this is supported by external encoder factory.
1204 if (!found && encoder_factory_) {
1205 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1206 encoder_factory_->codecs();
1207 for (size_t i = 0; i < codecs.size(); ++i) {
1208 if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
1209 out_codec->codecType = codecs[i].type;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001210 out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
1212 codecs[i].name.c_str(), codecs[i].name.length());
1213 found = true;
1214 break;
1215 }
1216 }
1217 }
1218
1219 if (!found) {
1220 LOG(LS_ERROR) << "invalid codec type";
1221 return false;
1222 }
1223
1224 if (in_codec.id != 0)
1225 out_codec->plType = in_codec.id;
1226
1227 if (in_codec.width != 0)
1228 out_codec->width = in_codec.width;
1229
1230 if (in_codec.height != 0)
1231 out_codec->height = in_codec.height;
1232
1233 if (in_codec.framerate != 0)
1234 out_codec->maxFramerate = in_codec.framerate;
1235
1236 // Convert bitrate parameters.
1237 int max_bitrate = kMaxVideoBitrate;
1238 int min_bitrate = kMinVideoBitrate;
1239 int start_bitrate = kStartVideoBitrate;
1240
1241 in_codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
1242 in_codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
1243
1244 if (max_bitrate < min_bitrate) {
1245 return false;
1246 }
1247 start_bitrate = talk_base::_max(start_bitrate, min_bitrate);
1248 start_bitrate = talk_base::_min(start_bitrate, max_bitrate);
1249
1250 out_codec->minBitrate = min_bitrate;
1251 out_codec->startBitrate = start_bitrate;
1252 out_codec->maxBitrate = max_bitrate;
1253
1254 // Convert general codec parameters.
1255 int max_quantization = 0;
1256 if (in_codec.GetParam(kCodecParamMaxQuantization, &max_quantization)) {
1257 if (max_quantization < 0) {
1258 return false;
1259 }
1260 out_codec->qpMax = max_quantization;
1261 }
1262 return true;
1263}
1264
1265void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
1266 talk_base::CritScope cs(&channels_crit_);
1267 channels_.push_back(channel);
1268}
1269
1270void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
1271 talk_base::CritScope cs(&channels_crit_);
1272 channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
1273 channels_.end());
1274}
1275
1276bool WebRtcVideoEngine::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
1277 if (initialized_) {
1278 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
1279 return false;
1280 }
1281 voice_engine_ = voice_engine;
1282 return true;
1283}
1284
1285bool WebRtcVideoEngine::EnableTimedRender() {
1286 if (initialized_) {
1287 LOG(LS_WARNING) << "EnableTimedRender can not be called after Init";
1288 return false;
1289 }
1290 render_module_.reset(webrtc::VideoRender::CreateVideoRender(0, NULL,
1291 false, webrtc::kRenderExternal));
1292 return true;
1293}
1294
1295void WebRtcVideoEngine::SetTraceFilter(int filter) {
1296 tracing_->SetTraceFilter(filter);
1297}
1298
1299// See https://sites.google.com/a/google.com/wavelet/
1300// Home/Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters
1301// for all supported command line setttings.
1302void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
1303 // Set WebRTC trace file.
1304 std::vector<std::string> opts;
1305 talk_base::tokenize(options, ' ', '"', '"', &opts);
1306 std::vector<std::string>::iterator tracefile =
1307 std::find(opts.begin(), opts.end(), "tracefile");
1308 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1309 // Write WebRTC debug output (at same loglevel) to file
1310 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1311 LOG_RTCERR1(SetTraceFile, *tracefile);
1312 }
1313 }
1314}
1315
1316static void AddDefaultFeedbackParams(VideoCodec* codec) {
1317 const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
1318 codec->AddFeedbackParam(kFir);
1319 const FeedbackParam kNack(kRtcpFbParamNack, kParamValueEmpty);
1320 codec->AddFeedbackParam(kNack);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001321 const FeedbackParam kPli(kRtcpFbParamNack, kRtcpFbNackParamPli);
1322 codec->AddFeedbackParam(kPli);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 const FeedbackParam kRemb(kRtcpFbParamRemb, kParamValueEmpty);
1324 codec->AddFeedbackParam(kRemb);
1325}
1326
1327// Rebuilds the codec list to be only those that are less intensive
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001328// than the specified codec. Prefers internal codec over external with
1329// higher preference field.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330bool WebRtcVideoEngine::RebuildCodecList(const VideoCodec& in_codec) {
1331 if (!FindCodec(in_codec))
1332 return false;
1333
1334 video_codecs_.clear();
1335
1336 bool found = false;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001337 std::set<std::string> internal_codec_names;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338 for (size_t i = 0; i < ARRAY_SIZE(kVideoCodecPrefs); ++i) {
1339 const VideoCodecPref& pref(kVideoCodecPrefs[i]);
1340 if (!found)
1341 found = (in_codec.name == pref.name);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001342 if (found) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 VideoCodec codec(pref.payload_type, pref.name,
1344 in_codec.width, in_codec.height, in_codec.framerate,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001345 static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
1347 AddDefaultFeedbackParams(&codec);
1348 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001349 if (pref.associated_payload_type != -1) {
1350 codec.SetParam(kCodecParamAssociatedPayloadType,
1351 pref.associated_payload_type);
1352 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 video_codecs_.push_back(codec);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001354 internal_codec_names.insert(codec.name);
1355 }
1356 }
1357 if (encoder_factory_) {
1358 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1359 encoder_factory_->codecs();
1360 for (size_t i = 0; i < codecs.size(); ++i) {
1361 bool is_internal_codec = internal_codec_names.find(codecs[i].name) !=
1362 internal_codec_names.end();
1363 if (!is_internal_codec) {
1364 if (!found)
1365 found = (in_codec.name == codecs[i].name);
1366 VideoCodec codec(
1367 GetExternalVideoPayloadType(static_cast<int>(i)),
1368 codecs[i].name,
1369 codecs[i].max_width,
1370 codecs[i].max_height,
1371 codecs[i].max_fps,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001372 // Use negative preference on external codec to ensure the internal
1373 // codec is preferred.
1374 static_cast<int>(0 - i));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001375 AddDefaultFeedbackParams(&codec);
1376 video_codecs_.push_back(codec);
1377 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 }
1379 }
1380 ASSERT(found);
1381 return true;
1382}
1383
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384// Ignore spammy trace messages, mostly from the stats API when we haven't
1385// gotten RTCP info yet from the remote side.
1386bool WebRtcVideoEngine::ShouldIgnoreTrace(const std::string& trace) {
1387 static const char* const kTracesToIgnore[] = {
1388 NULL
1389 };
1390 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1391 if (trace.find(*p) == 0) {
1392 return true;
1393 }
1394 }
1395 return false;
1396}
1397
1398int WebRtcVideoEngine::GetNumOfChannels() {
1399 talk_base::CritScope cs(&channels_crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001400 return static_cast<int>(channels_.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401}
1402
1403void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
1404 int length) {
1405 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1406 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1407 sev = talk_base::LS_ERROR;
1408 else if (level == webrtc::kTraceWarning)
1409 sev = talk_base::LS_WARNING;
1410 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1411 sev = talk_base::LS_INFO;
1412 else if (level == webrtc::kTraceTerseInfo)
1413 sev = talk_base::LS_INFO;
1414
1415 // Skip past boilerplate prefix text
1416 if (length < 72) {
1417 std::string msg(trace, length);
1418 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1419 LOG_V(sev) << msg;
1420 } else {
1421 std::string msg(trace + 71, length - 72);
1422 if (!ShouldIgnoreTrace(msg) &&
1423 (!voice_engine_ || !voice_engine_->ShouldIgnoreTrace(msg))) {
1424 LOG_V(sev) << "webrtc: " << msg;
1425 }
1426 }
1427}
1428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001429webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
1430 webrtc::VideoCodecType type) {
1431 if (decoder_factory_ == NULL) {
1432 return NULL;
1433 }
1434 return decoder_factory_->CreateVideoDecoder(type);
1435}
1436
1437void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
1438 ASSERT(decoder_factory_ != NULL);
1439 if (decoder_factory_ == NULL)
1440 return;
1441 decoder_factory_->DestroyVideoDecoder(decoder);
1442}
1443
1444webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
1445 webrtc::VideoCodecType type) {
1446 if (encoder_factory_ == NULL) {
1447 return NULL;
1448 }
1449 return encoder_factory_->CreateVideoEncoder(type);
1450}
1451
1452void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
1453 ASSERT(encoder_factory_ != NULL);
1454 if (encoder_factory_ == NULL)
1455 return;
1456 encoder_factory_->DestroyVideoEncoder(encoder);
1457}
1458
1459bool WebRtcVideoEngine::IsExternalEncoderCodecType(
1460 webrtc::VideoCodecType type) const {
1461 if (!encoder_factory_)
1462 return false;
1463 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1464 encoder_factory_->codecs();
1465 std::vector<WebRtcVideoEncoderFactory::VideoCodec>::const_iterator it;
1466 for (it = codecs.begin(); it != codecs.end(); ++it) {
1467 if (it->type == type)
1468 return true;
1469 }
1470 return false;
1471}
1472
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473void WebRtcVideoEngine::SetExternalDecoderFactory(
1474 WebRtcVideoDecoderFactory* decoder_factory) {
1475 decoder_factory_ = decoder_factory;
1476}
1477
1478void WebRtcVideoEngine::SetExternalEncoderFactory(
1479 WebRtcVideoEncoderFactory* encoder_factory) {
1480 if (encoder_factory_ == encoder_factory)
1481 return;
1482
1483 if (encoder_factory_) {
1484 encoder_factory_->RemoveObserver(this);
1485 }
1486 encoder_factory_ = encoder_factory;
1487 if (encoder_factory_) {
1488 encoder_factory_->AddObserver(this);
1489 }
1490
1491 // Invoke OnCodecAvailable() here in case the list of codecs is already
1492 // available when the encoder factory is installed. If not the encoder
1493 // factory will invoke the callback later when the codecs become available.
1494 OnCodecsAvailable();
1495}
1496
1497void WebRtcVideoEngine::OnCodecsAvailable() {
1498 // Rebuild codec list while reapplying the current default codec format.
1499 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1500 kVideoCodecPrefs[0].name,
1501 video_codecs_[0].width,
1502 video_codecs_[0].height,
1503 video_codecs_[0].framerate,
1504 0);
1505 if (!RebuildCodecList(max_codec)) {
1506 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
1507 }
1508}
1509
1510// WebRtcVideoMediaChannel
1511
1512WebRtcVideoMediaChannel::WebRtcVideoMediaChannel(
1513 WebRtcVideoEngine* engine,
1514 VoiceMediaChannel* channel)
1515 : engine_(engine),
1516 voice_channel_(channel),
1517 vie_channel_(-1),
1518 nack_enabled_(true),
1519 remb_enabled_(false),
1520 render_started_(false),
1521 first_receive_ssrc_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001522 send_rtx_type_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001523 send_red_type_(-1),
1524 send_fec_type_(-1),
1525 send_min_bitrate_(kMinVideoBitrate),
1526 send_start_bitrate_(kStartVideoBitrate),
1527 send_max_bitrate_(kMaxVideoBitrate),
1528 sending_(false),
1529 ratio_w_(0),
1530 ratio_h_(0) {
1531 engine->RegisterChannel(this);
1532}
1533
1534bool WebRtcVideoMediaChannel::Init() {
1535 const uint32 ssrc_key = 0;
1536 return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
1537}
1538
1539WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
1540 const bool send = false;
1541 SetSend(send);
1542 const bool render = false;
1543 SetRender(render);
1544
1545 while (!send_channels_.empty()) {
1546 if (!DeleteSendChannel(send_channels_.begin()->first)) {
1547 LOG(LS_ERROR) << "Unable to delete channel with ssrc key "
1548 << send_channels_.begin()->first;
1549 ASSERT(false);
1550 break;
1551 }
1552 }
1553
1554 // Remove all receive streams and the default channel.
1555 while (!recv_channels_.empty()) {
1556 RemoveRecvStream(recv_channels_.begin()->first);
1557 }
1558
1559 // Unregister the channel from the engine.
1560 engine()->UnregisterChannel(this);
1561 if (worker_thread()) {
1562 worker_thread()->Clear(this);
1563 }
1564}
1565
1566bool WebRtcVideoMediaChannel::SetRecvCodecs(
1567 const std::vector<VideoCodec>& codecs) {
1568 receive_codecs_.clear();
1569 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1570 iter != codecs.end(); ++iter) {
1571 if (engine()->FindCodec(*iter)) {
1572 webrtc::VideoCodec wcodec;
1573 if (engine()->ConvertFromCricketVideoCodec(*iter, &wcodec)) {
1574 receive_codecs_.push_back(wcodec);
1575 }
1576 } else {
1577 LOG(LS_INFO) << "Unknown codec " << iter->name;
1578 return false;
1579 }
1580 }
1581
1582 for (RecvChannelMap::iterator it = recv_channels_.begin();
1583 it != recv_channels_.end(); ++it) {
1584 if (!SetReceiveCodecs(it->second))
1585 return false;
1586 }
1587 return true;
1588}
1589
1590bool WebRtcVideoMediaChannel::SetSendCodecs(
1591 const std::vector<VideoCodec>& codecs) {
1592 // Match with local video codec list.
1593 std::vector<webrtc::VideoCodec> send_codecs;
1594 VideoCodec checked_codec;
1595 VideoCodec current; // defaults to 0x0
1596 if (sending_) {
1597 ConvertToCricketVideoCodec(*send_codec_, &current);
1598 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001599 std::map<int, int> primary_rtx_pt_mapping;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1601 iter != codecs.end(); ++iter) {
1602 if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
1603 send_red_type_ = iter->id;
1604 } else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
1605 send_fec_type_ = iter->id;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001606 } else if (_stricmp(iter->name.c_str(), kRtxCodecName) == 0) {
1607 int rtx_type = iter->id;
1608 int rtx_primary_type = -1;
1609 if (iter->GetParam(kCodecParamAssociatedPayloadType, &rtx_primary_type)) {
1610 primary_rtx_pt_mapping[rtx_primary_type] = rtx_type;
1611 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612 } else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
1613 webrtc::VideoCodec wcodec;
1614 if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
1615 if (send_codecs.empty()) {
1616 nack_enabled_ = IsNackEnabled(checked_codec);
1617 remb_enabled_ = IsRembEnabled(checked_codec);
1618 }
1619 send_codecs.push_back(wcodec);
1620 }
1621 } else {
1622 LOG(LS_WARNING) << "Unknown codec " << iter->name;
1623 }
1624 }
1625
1626 // Fail if we don't have a match.
1627 if (send_codecs.empty()) {
1628 LOG(LS_WARNING) << "No matching codecs available";
1629 return false;
1630 }
1631
1632 // Recv protection.
1633 for (RecvChannelMap::iterator it = recv_channels_.begin();
1634 it != recv_channels_.end(); ++it) {
1635 int channel_id = it->second->channel_id();
1636 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1637 nack_enabled_)) {
1638 return false;
1639 }
1640 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1641 kNotSending,
1642 remb_enabled_) != 0) {
1643 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
1644 return false;
1645 }
1646 }
1647
1648 // Send settings.
1649 for (SendChannelMap::iterator iter = send_channels_.begin();
1650 iter != send_channels_.end(); ++iter) {
1651 int channel_id = iter->second->channel_id();
1652 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1653 nack_enabled_)) {
1654 return false;
1655 }
1656 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1657 remb_enabled_,
1658 remb_enabled_) != 0) {
1659 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
1660 return false;
1661 }
1662 }
1663
1664 // Select the first matched codec.
1665 webrtc::VideoCodec& codec(send_codecs[0]);
1666
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001667 // Set RTX payload type if primary now active. This value will be used in
1668 // SetSendCodec.
1669 std::map<int, int>::const_iterator rtx_it =
1670 primary_rtx_pt_mapping.find(static_cast<int>(codec.plType));
1671 if (rtx_it != primary_rtx_pt_mapping.end()) {
1672 send_rtx_type_ = rtx_it->second;
1673 }
1674
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675 if (!SetSendCodec(
1676 codec, codec.minBitrate, codec.startBitrate, codec.maxBitrate)) {
1677 return false;
1678 }
1679
1680 for (SendChannelMap::iterator iter = send_channels_.begin();
1681 iter != send_channels_.end(); ++iter) {
1682 WebRtcVideoChannelSendInfo* send_channel = iter->second;
1683 send_channel->InitializeAdapterOutputFormat(codec);
1684 }
1685
1686 LogSendCodecChange("SetSendCodecs()");
1687
1688 return true;
1689}
1690
1691bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
1692 if (!send_codec_) {
1693 return false;
1694 }
1695 ConvertToCricketVideoCodec(*send_codec_, send_codec);
1696 return true;
1697}
1698
1699bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
1700 const VideoFormat& format) {
1701 if (!send_codec_) {
1702 LOG(LS_ERROR) << "The send codec has not been set yet.";
1703 return false;
1704 }
1705 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
1706 if (!send_channel) {
1707 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
1708 return false;
1709 }
1710 send_channel->set_video_format(format);
1711 return true;
1712}
1713
1714bool WebRtcVideoMediaChannel::SetRender(bool render) {
1715 if (render == render_started_) {
1716 return true; // no action required
1717 }
1718
1719 bool ret = true;
1720 for (RecvChannelMap::iterator it = recv_channels_.begin();
1721 it != recv_channels_.end(); ++it) {
1722 if (render) {
1723 if (engine()->vie()->render()->StartRender(
1724 it->second->channel_id()) != 0) {
1725 LOG_RTCERR1(StartRender, it->second->channel_id());
1726 ret = false;
1727 }
1728 } else {
1729 if (engine()->vie()->render()->StopRender(
1730 it->second->channel_id()) != 0) {
1731 LOG_RTCERR1(StopRender, it->second->channel_id());
1732 ret = false;
1733 }
1734 }
1735 }
1736 if (ret) {
1737 render_started_ = render;
1738 }
1739
1740 return ret;
1741}
1742
1743bool WebRtcVideoMediaChannel::SetSend(bool send) {
1744 if (!HasReadySendChannels() && send) {
1745 LOG(LS_ERROR) << "No stream added";
1746 return false;
1747 }
1748 if (send == sending()) {
1749 return true; // No action required.
1750 }
1751
1752 if (send) {
1753 // We've been asked to start sending.
1754 // SetSendCodecs must have been called already.
1755 if (!send_codec_) {
1756 return false;
1757 }
1758 // Start send now.
1759 if (!StartSend()) {
1760 return false;
1761 }
1762 } else {
1763 // We've been asked to stop sending.
1764 if (!StopSend()) {
1765 return false;
1766 }
1767 }
1768 sending_ = send;
1769
1770 return true;
1771}
1772
1773bool WebRtcVideoMediaChannel::AddSendStream(const StreamParams& sp) {
1774 LOG(LS_INFO) << "AddSendStream " << sp.ToString();
1775
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001776 if (!IsOneSsrcStream(sp) && !IsSimulcastStream(sp)) {
1777 LOG(LS_ERROR) << "AddSendStream: bad local stream parameters";
1778 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779 }
1780
1781 uint32 ssrc_key;
1782 if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
1783 LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
1784 return false;
1785 }
1786 // If the default channel is already used for sending create a new channel
1787 // otherwise use the default channel for sending.
1788 int channel_id = -1;
1789 if (send_channels_[0]->stream_params() == NULL) {
1790 channel_id = vie_channel_;
1791 } else {
1792 if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
1793 LOG(LS_ERROR) << "AddSendStream: unable to create channel";
1794 return false;
1795 }
1796 }
1797 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1798 // Set the send (local) SSRC.
1799 // If there are multiple send SSRCs, we can only set the first one here, and
1800 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
1801 // (with a codec requires multiple SSRC(s)).
1802 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1803 sp.first_ssrc()) != 0) {
1804 LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
1805 return false;
1806 }
1807
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001808 // Set the corresponding RTX SSRC.
1809 if (!SetLocalRtxSsrc(channel_id, sp, sp.first_ssrc(), 0)) {
1810 return false;
1811 }
1812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813 // Set RTCP CName.
1814 if (engine()->vie()->rtp()->SetRTCPCName(channel_id,
1815 sp.cname.c_str()) != 0) {
1816 LOG_RTCERR2(SetRTCPCName, channel_id, sp.cname.c_str());
1817 return false;
1818 }
1819
1820 // At this point the channel's local SSRC has been updated. If the channel is
1821 // the default channel make sure that all the receive channels are updated as
1822 // well. Receive channels have to have the same SSRC as the default channel in
1823 // order to send receiver reports with this SSRC.
1824 if (IsDefaultChannel(channel_id)) {
1825 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
1826 it != recv_channels_.end(); ++it) {
1827 WebRtcVideoChannelRecvInfo* info = it->second;
1828 int channel_id = info->channel_id();
1829 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1830 sp.first_ssrc()) != 0) {
1831 LOG_RTCERR1(SetLocalSSRC, it->first);
1832 return false;
1833 }
1834 }
1835 }
1836
1837 send_channel->set_stream_params(sp);
1838
1839 // Reset send codec after stream parameters changed.
1840 if (send_codec_) {
1841 if (!SetSendCodec(send_channel, *send_codec_, send_min_bitrate_,
1842 send_start_bitrate_, send_max_bitrate_)) {
1843 return false;
1844 }
1845 LogSendCodecChange("SetSendStreamFormat()");
1846 }
1847
1848 if (sending_) {
1849 return StartSend(send_channel);
1850 }
1851 return true;
1852}
1853
1854bool WebRtcVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
1855 uint32 ssrc_key;
1856 if (!GetSendChannelKey(ssrc, &ssrc_key)) {
1857 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1858 << " which doesn't exist.";
1859 return false;
1860 }
1861 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1862 int channel_id = send_channel->channel_id();
1863 if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
1864 // Default channel will still exist. However, if stream_params() is NULL
1865 // there is no stream to remove.
1866 return false;
1867 }
1868 if (sending_) {
1869 StopSend(send_channel);
1870 }
1871
1872 const WebRtcVideoChannelSendInfo::EncoderMap& encoder_map =
1873 send_channel->registered_encoders();
1874 for (WebRtcVideoChannelSendInfo::EncoderMap::const_iterator it =
1875 encoder_map.begin(); it != encoder_map.end(); ++it) {
1876 if (engine()->vie()->ext_codec()->DeRegisterExternalSendCodec(
1877 channel_id, it->first) != 0) {
1878 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
1879 }
1880 engine()->DestroyExternalEncoder(it->second);
1881 }
1882 send_channel->ClearRegisteredEncoders();
1883
1884 // The receive channels depend on the default channel, recycle it instead.
1885 if (IsDefaultChannel(channel_id)) {
1886 SetCapturer(GetDefaultChannelSsrc(), NULL);
1887 send_channel->ClearStreamParams();
1888 } else {
1889 return DeleteSendChannel(ssrc_key);
1890 }
1891 return true;
1892}
1893
1894bool WebRtcVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
1895 // TODO(zhurunz) Remove this once BWE works properly across different send
1896 // and receive channels.
1897 // Reuse default channel for recv stream in 1:1 call.
1898 if (!InConferenceMode() && first_receive_ssrc_ == 0) {
1899 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
1900 << " reuse default channel #"
1901 << vie_channel_;
1902 first_receive_ssrc_ = sp.first_ssrc();
1903 if (render_started_) {
1904 if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
1905 LOG_RTCERR1(StartRender, vie_channel_);
1906 }
1907 }
1908 return true;
1909 }
1910
1911 if (recv_channels_.find(sp.first_ssrc()) != recv_channels_.end() ||
1912 first_receive_ssrc_ == sp.first_ssrc()) {
1913 LOG(LS_ERROR) << "Stream already exists";
1914 return false;
1915 }
1916
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001917 // TODO(perkj): Implement recv media from multiple media SSRCs per stream.
1918 // NOTE: We have two SSRCs per stream when RTX is enabled.
1919 if (!IsOneSsrcStream(sp)) {
1920 LOG(LS_ERROR) << "WebRtcVideoMediaChannel supports one primary SSRC per"
1921 << " stream and one FID SSRC per primary SSRC.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922 return false;
1923 }
1924
1925 // Create a new channel for receiving video data.
1926 // In order to get the bandwidth estimation work fine for
1927 // receive only channels, we connect all receiving channels
1928 // to our master send channel.
1929 int channel_id = -1;
1930 if (!CreateChannel(sp.first_ssrc(), MD_RECV, &channel_id)) {
1931 return false;
1932 }
1933
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001934 // Set the corresponding RTX SSRC.
1935 uint32 rtx_ssrc;
1936 bool has_rtx = sp.GetFidSsrc(sp.first_ssrc(), &rtx_ssrc);
1937 if (has_rtx && engine()->vie()->rtp()->SetRemoteSSRCType(
1938 channel_id, webrtc::kViEStreamTypeRtx, rtx_ssrc) != 0) {
1939 LOG_RTCERR3(SetRemoteSSRCType, channel_id, webrtc::kViEStreamTypeRtx,
1940 rtx_ssrc);
1941 return false;
1942 }
1943
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 // Get the default renderer.
1945 VideoRenderer* default_renderer = NULL;
1946 if (InConferenceMode()) {
1947 // The recv_channels_ size start out being 1, so if it is two here this
1948 // is the first receive channel created (vie_channel_ is not used for
1949 // receiving in a conference call). This means that the renderer stored
1950 // inside vie_channel_ should be used for the just created channel.
1951 if (recv_channels_.size() == 2 &&
1952 recv_channels_.find(0) != recv_channels_.end()) {
1953 GetRenderer(0, &default_renderer);
1954 }
1955 }
1956
1957 // The first recv stream reuses the default renderer (if a default renderer
1958 // has been set).
1959 if (default_renderer) {
1960 SetRenderer(sp.first_ssrc(), default_renderer);
1961 }
1962
1963 LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
1964 << " registered to VideoEngine channel #"
1965 << channel_id << " and connected to channel #" << vie_channel_;
1966
1967 return true;
1968}
1969
1970bool WebRtcVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
1971 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
1972
1973 if (it == recv_channels_.end()) {
1974 // TODO(perkj): Remove this once BWE works properly across different send
1975 // and receive channels.
1976 // The default channel is reused for recv stream in 1:1 call.
1977 if (first_receive_ssrc_ == ssrc) {
1978 first_receive_ssrc_ = 0;
1979 // Need to stop the renderer and remove it since the render window can be
1980 // deleted after this.
1981 if (render_started_) {
1982 if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
1983 LOG_RTCERR1(StopRender, it->second->channel_id());
1984 }
1985 }
1986 recv_channels_[0]->SetRenderer(NULL);
1987 return true;
1988 }
1989 return false;
1990 }
1991 WebRtcVideoChannelRecvInfo* info = it->second;
1992 int channel_id = info->channel_id();
1993 if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
1994 LOG_RTCERR1(RemoveRenderer, channel_id);
1995 }
1996
1997 if (engine()->vie()->network()->DeregisterSendTransport(channel_id) !=0) {
1998 LOG_RTCERR1(DeRegisterSendTransport, channel_id);
1999 }
2000
2001 if (engine()->vie()->codec()->DeregisterDecoderObserver(
2002 channel_id) != 0) {
2003 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
2004 }
2005
2006 const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
2007 info->registered_decoders();
2008 for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
2009 decoder_map.begin(); it != decoder_map.end(); ++it) {
2010 if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
2011 channel_id, it->first) != 0) {
2012 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
2013 }
2014 engine()->DestroyExternalDecoder(it->second);
2015 }
2016 info->ClearRegisteredDecoders();
2017
2018 LOG(LS_INFO) << "Removing video stream " << ssrc
2019 << " with VideoEngine channel #"
2020 << channel_id;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002021 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022 if (engine()->vie()->base()->DeleteChannel(channel_id) == -1) {
2023 LOG_RTCERR1(DeleteChannel, channel_id);
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002024 ret = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025 }
2026 // Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
2027 delete info;
2028 recv_channels_.erase(it);
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002029 return ret;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030}
2031
2032bool WebRtcVideoMediaChannel::StartSend() {
2033 bool success = true;
2034 for (SendChannelMap::iterator iter = send_channels_.begin();
2035 iter != send_channels_.end(); ++iter) {
2036 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2037 if (!StartSend(send_channel)) {
2038 success = false;
2039 }
2040 }
2041 return success;
2042}
2043
2044bool WebRtcVideoMediaChannel::StartSend(
2045 WebRtcVideoChannelSendInfo* send_channel) {
2046 const int channel_id = send_channel->channel_id();
2047 if (engine()->vie()->base()->StartSend(channel_id) != 0) {
2048 LOG_RTCERR1(StartSend, channel_id);
2049 return false;
2050 }
2051
2052 send_channel->set_sending(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002053 return true;
2054}
2055
2056bool WebRtcVideoMediaChannel::StopSend() {
2057 bool success = true;
2058 for (SendChannelMap::iterator iter = send_channels_.begin();
2059 iter != send_channels_.end(); ++iter) {
2060 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2061 if (!StopSend(send_channel)) {
2062 success = false;
2063 }
2064 }
2065 return success;
2066}
2067
2068bool WebRtcVideoMediaChannel::StopSend(
2069 WebRtcVideoChannelSendInfo* send_channel) {
2070 const int channel_id = send_channel->channel_id();
2071 if (engine()->vie()->base()->StopSend(channel_id) != 0) {
2072 LOG_RTCERR1(StopSend, channel_id);
2073 return false;
2074 }
2075 send_channel->set_sending(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076 return true;
2077}
2078
2079bool WebRtcVideoMediaChannel::SendIntraFrame() {
2080 bool success = true;
2081 for (SendChannelMap::iterator iter = send_channels_.begin();
2082 iter != send_channels_.end();
2083 ++iter) {
2084 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2085 const int channel_id = send_channel->channel_id();
2086 if (engine()->vie()->codec()->SendKeyFrame(channel_id) != 0) {
2087 LOG_RTCERR1(SendKeyFrame, channel_id);
2088 success = false;
2089 }
2090 }
2091 return success;
2092}
2093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002094bool WebRtcVideoMediaChannel::HasReadySendChannels() {
2095 return !send_channels_.empty() &&
2096 ((send_channels_.size() > 1) ||
2097 (send_channels_[0]->stream_params() != NULL));
2098}
2099
2100bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
2101 uint32* key) {
2102 *key = 0;
2103 // If a send channel is not ready to send it will not have local_ssrc
2104 // registered to it.
2105 if (!HasReadySendChannels()) {
2106 return false;
2107 }
2108 // The default channel is stored with key 0. The key therefore does not match
2109 // the SSRC associated with the default channel. Check if the SSRC provided
2110 // corresponds to the default channel's SSRC.
2111 if (local_ssrc == GetDefaultChannelSsrc()) {
2112 return true;
2113 }
2114 if (send_channels_.find(local_ssrc) == send_channels_.end()) {
2115 for (SendChannelMap::iterator iter = send_channels_.begin();
2116 iter != send_channels_.end(); ++iter) {
2117 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2118 if (send_channel->has_ssrc(local_ssrc)) {
2119 *key = iter->first;
2120 return true;
2121 }
2122 }
2123 return false;
2124 }
2125 // The key was found in the above std::map::find call. This means that the
2126 // ssrc is the key.
2127 *key = local_ssrc;
2128 return true;
2129}
2130
2131WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 uint32 local_ssrc) {
2133 uint32 key;
2134 if (!GetSendChannelKey(local_ssrc, &key)) {
2135 return NULL;
2136 }
2137 return send_channels_[key];
2138}
2139
2140bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
2141 uint32* key) {
2142 if (GetSendChannelKey(local_ssrc, key)) {
2143 // If there is a key corresponding to |local_ssrc|, the SSRC is already in
2144 // use. SSRCs need to be unique in a session and at this point a duplicate
2145 // SSRC has been detected.
2146 return false;
2147 }
2148 if (send_channels_[0]->stream_params() == NULL) {
2149 // key should be 0 here as the default channel should be re-used whenever it
2150 // is not used.
2151 *key = 0;
2152 return true;
2153 }
2154 // SSRC is currently not in use and the default channel is already in use. Use
2155 // the SSRC as key since it is supposed to be unique in a session.
2156 *key = local_ssrc;
2157 return true;
2158}
2159
wu@webrtc.org24301a62013-12-13 19:17:43 +00002160int WebRtcVideoMediaChannel::GetSendChannelNum(VideoCapturer* capturer) {
2161 int num = 0;
2162 for (SendChannelMap::iterator iter = send_channels_.begin();
2163 iter != send_channels_.end(); ++iter) {
2164 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2165 if (send_channel->video_capturer() == capturer) {
2166 ++num;
2167 }
2168 }
2169 return num;
2170}
2171
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
2173 WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
2174 const StreamParams* sp = send_channel->stream_params();
2175 if (sp == NULL) {
2176 // This happens if no send stream is currently registered.
2177 return 0;
2178 }
2179 return sp->first_ssrc();
2180}
2181
2182bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
2183 if (send_channels_.find(ssrc_key) == send_channels_.end()) {
2184 return false;
2185 }
2186 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
wu@webrtc.org24301a62013-12-13 19:17:43 +00002187 MaybeDisconnectCapturer(send_channel->video_capturer());
2188 send_channel->set_video_capturer(NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189
2190 int channel_id = send_channel->channel_id();
2191 int capture_id = send_channel->capture_id();
2192 if (engine()->vie()->codec()->DeregisterEncoderObserver(
2193 channel_id) != 0) {
2194 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
2195 }
2196
2197 // Destroy the external capture interface.
2198 if (engine()->vie()->capture()->DisconnectCaptureDevice(
2199 channel_id) != 0) {
2200 LOG_RTCERR1(DisconnectCaptureDevice, channel_id);
2201 }
2202 if (engine()->vie()->capture()->ReleaseCaptureDevice(
2203 capture_id) != 0) {
2204 LOG_RTCERR1(ReleaseCaptureDevice, capture_id);
2205 }
2206
2207 // The default channel is stored in both |send_channels_| and
2208 // |recv_channels_|. To make sure it is only deleted once from vie let the
2209 // delete call happen when tearing down |recv_channels_| and not here.
2210 if (!IsDefaultChannel(channel_id)) {
2211 engine_->vie()->base()->DeleteChannel(channel_id);
2212 }
2213 delete send_channel;
2214 send_channels_.erase(ssrc_key);
2215 return true;
2216}
2217
2218bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
2219 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2220 if (!send_channel) {
2221 return false;
2222 }
2223 VideoCapturer* capturer = send_channel->video_capturer();
2224 if (capturer == NULL) {
2225 return false;
2226 }
wu@webrtc.org24301a62013-12-13 19:17:43 +00002227 MaybeDisconnectCapturer(capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 send_channel->set_video_capturer(NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2230 if (send_codec_) {
2231 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2232 }
2233 return true;
2234}
2235
2236bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
2237 VideoRenderer* renderer) {
2238 if (recv_channels_.find(ssrc) == recv_channels_.end()) {
2239 // TODO(perkj): Remove this once BWE works properly across different send
2240 // and receive channels.
2241 // The default channel is reused for recv stream in 1:1 call.
2242 if (first_receive_ssrc_ == ssrc &&
2243 recv_channels_.find(0) != recv_channels_.end()) {
2244 LOG(LS_INFO) << "SetRenderer " << ssrc
2245 << " reuse default channel #"
2246 << vie_channel_;
2247 recv_channels_[0]->SetRenderer(renderer);
2248 return true;
2249 }
2250 return false;
2251 }
2252
2253 recv_channels_[ssrc]->SetRenderer(renderer);
2254 return true;
2255}
2256
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002257bool WebRtcVideoMediaChannel::GetStats(const StatsOptions& options,
2258 VideoMediaInfo* info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 // Get sender statistics and build VideoSenderInfo.
2260 unsigned int total_bitrate_sent = 0;
2261 unsigned int video_bitrate_sent = 0;
2262 unsigned int fec_bitrate_sent = 0;
2263 unsigned int nack_bitrate_sent = 0;
2264 unsigned int estimated_send_bandwidth = 0;
2265 unsigned int target_enc_bitrate = 0;
2266 if (send_codec_) {
2267 for (SendChannelMap::const_iterator iter = send_channels_.begin();
2268 iter != send_channels_.end(); ++iter) {
2269 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2270 const int channel_id = send_channel->channel_id();
2271 VideoSenderInfo sinfo;
2272 const StreamParams* send_params = send_channel->stream_params();
2273 if (send_params == NULL) {
2274 // This should only happen if the default vie channel is not in use.
2275 // This can happen if no streams have ever been added or the stream
2276 // corresponding to the default channel has been removed. Note that
2277 // there may be non-default vie channels in use when this happen so
2278 // asserting send_channels_.size() == 1 is not correct and neither is
2279 // breaking out of the loop.
2280 ASSERT(channel_id == vie_channel_);
2281 continue;
2282 }
2283 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2284 if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
2285 packets_sent, bytes_recv,
2286 packets_recv) != 0) {
2287 LOG_RTCERR1(GetRTPStatistics, vie_channel_);
2288 continue;
2289 }
2290 WebRtcLocalStreamInfo* channel_stream_info =
2291 send_channel->local_stream_info();
2292
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002293 for (size_t i = 0; i < send_params->ssrcs.size(); ++i) {
2294 sinfo.add_ssrc(send_params->ssrcs[i]);
2295 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002296 sinfo.codec_name = send_codec_->plName;
2297 sinfo.bytes_sent = bytes_sent;
2298 sinfo.packets_sent = packets_sent;
2299 sinfo.packets_cached = -1;
2300 sinfo.packets_lost = -1;
2301 sinfo.fraction_lost = -1;
2302 sinfo.firs_rcvd = -1;
2303 sinfo.nacks_rcvd = -1;
2304 sinfo.rtt_ms = -1;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +00002305 sinfo.input_frame_width = static_cast<int>(channel_stream_info->width());
2306 sinfo.input_frame_height =
2307 static_cast<int>(channel_stream_info->height());
2308 webrtc::VideoCodec vie_codec;
2309 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) == 0) {
2310 sinfo.send_frame_width = vie_codec.width;
2311 sinfo.send_frame_height = vie_codec.height;
2312 } else {
2313 sinfo.send_frame_width = -1;
2314 sinfo.send_frame_height = -1;
2315 LOG_RTCERR1(GetSendCodec, channel_id);
2316 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317 sinfo.framerate_input = channel_stream_info->framerate();
2318 sinfo.framerate_sent = send_channel->encoder_observer()->framerate();
2319 sinfo.nominal_bitrate = send_channel->encoder_observer()->bitrate();
2320 sinfo.preferred_bitrate = send_max_bitrate_;
2321 sinfo.adapt_reason = send_channel->CurrentAdaptReason();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002322 sinfo.capture_jitter_ms = -1;
2323 sinfo.avg_encode_ms = -1;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002324 sinfo.encode_usage_percent = -1;
2325 sinfo.capture_queue_delay_ms_per_s = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002327 int capture_jitter_ms = 0;
2328 int avg_encode_time_ms = 0;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002329 int encode_usage_percent = 0;
2330 int capture_queue_delay_ms_per_s = 0;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002331 if (engine()->vie()->base()->CpuOveruseMeasures(
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002332 channel_id,
2333 &capture_jitter_ms,
2334 &avg_encode_time_ms,
2335 &encode_usage_percent,
2336 &capture_queue_delay_ms_per_s) == 0) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002337 sinfo.capture_jitter_ms = capture_jitter_ms;
2338 sinfo.avg_encode_ms = avg_encode_time_ms;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002339 sinfo.encode_usage_percent = encode_usage_percent;
2340 sinfo.capture_queue_delay_ms_per_s = capture_queue_delay_ms_per_s;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002341 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002342
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002343 // Get received RTCP statistics for the sender (reported by the remote
2344 // client in a RTCP packet), if available.
2345 // It's not a fatal error if we can't, since RTCP may not have arrived
2346 // yet.
2347 webrtc::RtcpStatistics outgoing_stream_rtcp_stats;
2348 int outgoing_stream_rtt_ms;
2349
2350 if (engine_->vie()->rtp()->GetSendChannelRtcpStatistics(
2351 channel_id,
2352 outgoing_stream_rtcp_stats,
2353 outgoing_stream_rtt_ms) == 0) {
2354 // Convert Q8 to float.
2355 sinfo.packets_lost = outgoing_stream_rtcp_stats.cumulative_lost;
2356 sinfo.fraction_lost = static_cast<float>(
2357 outgoing_stream_rtcp_stats.fraction_lost) / (1 << 8);
2358 sinfo.rtt_ms = outgoing_stream_rtt_ms;
2359 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360 info->senders.push_back(sinfo);
2361
2362 unsigned int channel_total_bitrate_sent = 0;
2363 unsigned int channel_video_bitrate_sent = 0;
2364 unsigned int channel_fec_bitrate_sent = 0;
2365 unsigned int channel_nack_bitrate_sent = 0;
2366 if (engine_->vie()->rtp()->GetBandwidthUsage(
2367 channel_id, channel_total_bitrate_sent, channel_video_bitrate_sent,
2368 channel_fec_bitrate_sent, channel_nack_bitrate_sent) == 0) {
2369 total_bitrate_sent += channel_total_bitrate_sent;
2370 video_bitrate_sent += channel_video_bitrate_sent;
2371 fec_bitrate_sent += channel_fec_bitrate_sent;
2372 nack_bitrate_sent += channel_nack_bitrate_sent;
2373 } else {
2374 LOG_RTCERR1(GetBandwidthUsage, channel_id);
2375 }
2376
2377 unsigned int estimated_stream_send_bandwidth = 0;
2378 if (engine_->vie()->rtp()->GetEstimatedSendBandwidth(
2379 channel_id, &estimated_stream_send_bandwidth) == 0) {
2380 estimated_send_bandwidth += estimated_stream_send_bandwidth;
2381 } else {
2382 LOG_RTCERR1(GetEstimatedSendBandwidth, channel_id);
2383 }
2384 unsigned int target_enc_stream_bitrate = 0;
2385 if (engine_->vie()->codec()->GetCodecTargetBitrate(
2386 channel_id, &target_enc_stream_bitrate) == 0) {
2387 target_enc_bitrate += target_enc_stream_bitrate;
2388 } else {
2389 LOG_RTCERR1(GetCodecTargetBitrate, channel_id);
2390 }
2391 }
2392 } else {
2393 LOG(LS_WARNING) << "GetStats: sender information not ready.";
2394 }
2395
2396 // Get the SSRC and stats for each receiver, based on our own calculations.
2397 unsigned int estimated_recv_bandwidth = 0;
2398 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
2399 it != recv_channels_.end(); ++it) {
2400 // Don't report receive statistics from the default channel if we have
2401 // specified receive channels.
2402 if (it->first == 0 && recv_channels_.size() > 1)
2403 continue;
2404 WebRtcVideoChannelRecvInfo* channel = it->second;
2405
2406 unsigned int ssrc;
2407 // Get receiver statistics and build VideoReceiverInfo, if we have data.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002408 // Skip the default channel (ssrc == 0).
2409 if (engine_->vie()->rtp()->GetRemoteSSRC(
2410 channel->channel_id(), ssrc) != 0 ||
2411 ssrc == 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 continue;
2413
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002414 webrtc::StreamDataCounters sent;
2415 webrtc::StreamDataCounters received;
2416 if (engine_->vie()->rtp()->GetRtpStatistics(channel->channel_id(),
2417 sent, received) != 0) {
2418 LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
2419 return false;
2420 }
2421 VideoReceiverInfo rinfo;
2422 rinfo.add_ssrc(ssrc);
2423 rinfo.bytes_rcvd = received.bytes;
2424 rinfo.packets_rcvd = received.packets;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425 rinfo.packets_lost = -1;
2426 rinfo.packets_concealed = -1;
2427 rinfo.fraction_lost = -1; // from SentRTCP
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428 rinfo.nacks_sent = -1;
2429 rinfo.frame_width = channel->render_adapter()->width();
2430 rinfo.frame_height = channel->render_adapter()->height();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 int fps = channel->render_adapter()->framerate();
2432 rinfo.framerate_decoded = fps;
2433 rinfo.framerate_output = fps;
wu@webrtc.org97077a32013-10-25 21:18:33 +00002434 channel->decoder_observer()->ExportTo(&rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002436 // Get our locally created statistics of the received RTP stream.
2437 webrtc::RtcpStatistics incoming_stream_rtcp_stats;
2438 int incoming_stream_rtt_ms;
2439 if (engine_->vie()->rtp()->GetReceiveChannelRtcpStatistics(
2440 channel->channel_id(),
2441 incoming_stream_rtcp_stats,
2442 incoming_stream_rtt_ms) == 0) {
2443 // Convert Q8 to float.
2444 rinfo.packets_lost = incoming_stream_rtcp_stats.cumulative_lost;
2445 rinfo.fraction_lost = static_cast<float>(
2446 incoming_stream_rtcp_stats.fraction_lost) / (1 << 8);
2447 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002448 info->receivers.push_back(rinfo);
2449
2450 unsigned int estimated_recv_stream_bandwidth = 0;
2451 if (engine_->vie()->rtp()->GetEstimatedReceiveBandwidth(
2452 channel->channel_id(), &estimated_recv_stream_bandwidth) == 0) {
2453 estimated_recv_bandwidth += estimated_recv_stream_bandwidth;
2454 } else {
2455 LOG_RTCERR1(GetEstimatedReceiveBandwidth, channel->channel_id());
2456 }
2457 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458 // Build BandwidthEstimationInfo.
2459 // TODO(zhurunz): Add real unittest for this.
2460 BandwidthEstimationInfo bwe;
2461
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002462 // TODO(jiayl): remove the condition when the necessary changes are available
2463 // outside the dev branch.
2464#ifdef USE_WEBRTC_DEV_BRANCH
2465 if (options.include_received_propagation_stats) {
2466 webrtc::ReceiveBandwidthEstimatorStats additional_stats;
2467 // Only call for the default channel because the returned stats are
2468 // collected for all the channels using the same estimator.
2469 if (engine_->vie()->rtp()->GetReceiveBandwidthEstimatorStats(
2470 recv_channels_[0]->channel_id(), &additional_stats)) {
2471 bwe.total_received_propagation_delta_ms =
2472 additional_stats.total_propagation_time_delta_ms;
2473 bwe.recent_received_propagation_delta_ms.swap(
2474 additional_stats.recent_propagation_time_delta_ms);
2475 bwe.recent_received_packet_group_arrival_time_ms.swap(
2476 additional_stats.recent_arrival_time_ms);
2477 }
2478 }
2479#endif
2480
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002481 // Calculations done above per send/receive stream.
2482 bwe.actual_enc_bitrate = video_bitrate_sent;
2483 bwe.transmit_bitrate = total_bitrate_sent;
2484 bwe.retransmit_bitrate = nack_bitrate_sent;
2485 bwe.available_send_bandwidth = estimated_send_bandwidth;
2486 bwe.available_recv_bandwidth = estimated_recv_bandwidth;
2487 bwe.target_enc_bitrate = target_enc_bitrate;
2488
2489 info->bw_estimations.push_back(bwe);
2490
2491 return true;
2492}
2493
2494bool WebRtcVideoMediaChannel::SetCapturer(uint32 ssrc,
2495 VideoCapturer* capturer) {
2496 ASSERT(ssrc != 0);
2497 if (!capturer) {
2498 return RemoveCapturer(ssrc);
2499 }
2500 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2501 if (!send_channel) {
2502 return false;
2503 }
2504 VideoCapturer* old_capturer = send_channel->video_capturer();
wu@webrtc.org24301a62013-12-13 19:17:43 +00002505 MaybeDisconnectCapturer(old_capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002506
2507 send_channel->set_video_capturer(capturer);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00002508 MaybeConnectCapturer(capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002509 if (!capturer->IsScreencast() && ratio_w_ != 0 && ratio_h_ != 0) {
2510 capturer->UpdateAspectRatio(ratio_w_, ratio_h_);
2511 }
2512 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2513 if (send_codec_) {
2514 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2515 }
2516 return true;
2517}
2518
2519bool WebRtcVideoMediaChannel::RequestIntraFrame() {
2520 // There is no API exposed to application to request a key frame
2521 // ViE does this internally when there are errors from decoder
2522 return false;
2523}
2524
wu@webrtc.orga9890802013-12-13 00:21:03 +00002525void WebRtcVideoMediaChannel::OnPacketReceived(
2526 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002527 // Pick which channel to send this packet to. If this packet doesn't match
2528 // any multiplexed streams, just send it to the default channel. Otherwise,
2529 // send it to the specific decoder instance for that stream.
2530 uint32 ssrc = 0;
2531 if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
2532 return;
2533 int which_channel = GetRecvChannelNum(ssrc);
2534 if (which_channel == -1) {
2535 which_channel = video_channel();
2536 }
2537
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002538 engine()->vie()->network()->ReceivedRTPPacket(
2539 which_channel,
2540 packet->data(),
wu@webrtc.orga9890802013-12-13 00:21:03 +00002541 static_cast<int>(packet->length()),
2542 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002543}
2544
wu@webrtc.orga9890802013-12-13 00:21:03 +00002545void WebRtcVideoMediaChannel::OnRtcpReceived(
2546 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002547// Sending channels need all RTCP packets with feedback information.
2548// Even sender reports can contain attached report blocks.
2549// Receiving channels need sender reports in order to create
2550// correct receiver reports.
2551
2552 uint32 ssrc = 0;
2553 if (!GetRtcpSsrc(packet->data(), packet->length(), &ssrc)) {
2554 LOG(LS_WARNING) << "Failed to parse SSRC from received RTCP packet";
2555 return;
2556 }
2557 int type = 0;
2558 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2559 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2560 return;
2561 }
2562
2563 // If it is a sender report, find the channel that is listening.
2564 if (type == kRtcpTypeSR) {
2565 int which_channel = GetRecvChannelNum(ssrc);
2566 if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002567 engine_->vie()->network()->ReceivedRTCPPacket(
2568 which_channel,
2569 packet->data(),
2570 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571 }
2572 }
2573 // SR may continue RR and any RR entry may correspond to any one of the send
2574 // channels. So all RTCP packets must be forwarded all send channels. ViE
2575 // will filter out RR internally.
2576 for (SendChannelMap::iterator iter = send_channels_.begin();
2577 iter != send_channels_.end(); ++iter) {
2578 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2579 int channel_id = send_channel->channel_id();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002580 engine_->vie()->network()->ReceivedRTCPPacket(
2581 channel_id,
2582 packet->data(),
2583 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002584 }
2585}
2586
2587void WebRtcVideoMediaChannel::OnReadyToSend(bool ready) {
2588 SetNetworkTransmissionState(ready);
2589}
2590
2591bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2592 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2593 if (!send_channel) {
2594 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
2595 return false;
2596 }
2597 send_channel->set_muted(muted);
2598 return true;
2599}
2600
2601bool WebRtcVideoMediaChannel::SetRecvRtpHeaderExtensions(
2602 const std::vector<RtpHeaderExtension>& extensions) {
2603 if (receive_extensions_ == extensions) {
2604 return true;
2605 }
2606 receive_extensions_ = extensions;
2607
2608 const RtpHeaderExtension* offset_extension =
2609 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2610 const RtpHeaderExtension* send_time_extension =
2611 FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
2612
2613 // Loop through all receive channels and enable/disable the extensions.
2614 for (RecvChannelMap::iterator channel_it = recv_channels_.begin();
2615 channel_it != recv_channels_.end(); ++channel_it) {
2616 int channel_id = channel_it->second->channel_id();
2617 if (!SetHeaderExtension(
2618 &webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus, channel_id,
2619 offset_extension)) {
2620 return false;
2621 }
2622 if (!SetHeaderExtension(
2623 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
2624 send_time_extension)) {
2625 return false;
2626 }
2627 }
2628 return true;
2629}
2630
2631bool WebRtcVideoMediaChannel::SetSendRtpHeaderExtensions(
2632 const std::vector<RtpHeaderExtension>& extensions) {
2633 send_extensions_ = extensions;
2634
2635 const RtpHeaderExtension* offset_extension =
2636 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2637 const RtpHeaderExtension* send_time_extension =
2638 FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
2639
2640 // Loop through all send channels and enable/disable the extensions.
2641 for (SendChannelMap::iterator channel_it = send_channels_.begin();
2642 channel_it != send_channels_.end(); ++channel_it) {
2643 int channel_id = channel_it->second->channel_id();
2644 if (!SetHeaderExtension(
2645 &webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus, channel_id,
2646 offset_extension)) {
2647 return false;
2648 }
2649 if (!SetHeaderExtension(
2650 &webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus, channel_id,
2651 send_time_extension)) {
2652 return false;
2653 }
2654 }
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002655
2656 if (send_time_extension) {
2657 // For video RTP packets, we would like to update AbsoluteSendTimeHeader
2658 // Extension closer to the network, @ socket level before sending.
2659 // Pushing the extension id to socket layer.
2660 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2661 talk_base::Socket::OPT_RTP_SENDTIME_EXTN_ID,
2662 send_time_extension->id);
2663 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002664 return true;
2665}
2666
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002667bool WebRtcVideoMediaChannel::SetStartSendBandwidth(int bps) {
2668 LOG(LS_INFO) << "WebRtcVideoMediaChannel::SetStartSendBandwidth";
2669
2670 if (!send_codec_) {
2671 LOG(LS_INFO) << "The send codec has not been set up yet";
2672 return true;
2673 }
2674
2675 // On success, SetSendCodec() will reset |send_start_bitrate_| to |bps/1000|,
2676 // by calling MaybeChangeStartBitrate. That method will also clamp the
2677 // start bitrate between min and max, consistent with the override behavior
2678 // in SetMaxSendBandwidth.
2679 return SetSendCodec(*send_codec_,
2680 send_min_bitrate_, bps / 1000, send_max_bitrate_);
2681}
2682
2683bool WebRtcVideoMediaChannel::SetMaxSendBandwidth(int bps) {
2684 LOG(LS_INFO) << "WebRtcVideoMediaChannel::SetMaxSendBandwidth";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002685
2686 if (InConferenceMode()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002687 LOG(LS_INFO) << "Conference mode ignores SetMaxSendBandwidth";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688 return true;
2689 }
2690
2691 if (!send_codec_) {
2692 LOG(LS_INFO) << "The send codec has not been set up yet";
2693 return true;
2694 }
2695
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002696 // Use the default value or the bps for the max
2697 int max_bitrate = (bps <= 0) ? send_max_bitrate_ : (bps / 1000);
2698
2699 // Reduce the current minimum and start bitrates if necessary.
2700 int min_bitrate = talk_base::_min(send_min_bitrate_, max_bitrate);
2701 int start_bitrate = talk_base::_min(send_start_bitrate_, max_bitrate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002702
2703 if (!SetSendCodec(*send_codec_, min_bitrate, start_bitrate, max_bitrate)) {
2704 return false;
2705 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002706 LogSendCodecChange("SetMaxSendBandwidth()");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002707
2708 return true;
2709}
2710
2711bool WebRtcVideoMediaChannel::SetOptions(const VideoOptions &options) {
2712 // Always accept options that are unchanged.
2713 if (options_ == options) {
2714 return true;
2715 }
2716
2717 // Trigger SetSendCodec to set correct noise reduction state if the option has
2718 // changed.
2719 bool denoiser_changed = options.video_noise_reduction.IsSet() &&
2720 (options_.video_noise_reduction != options.video_noise_reduction);
2721
2722 bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
2723 (options_.video_leaky_bucket != options.video_leaky_bucket);
2724
2725 bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
2726 (options_.buffered_mode_latency != options.buffered_mode_latency);
2727
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002728 bool cpu_overuse_detection_changed = options.cpu_overuse_detection.IsSet() &&
2729 (options_.cpu_overuse_detection != options.cpu_overuse_detection);
2730
wu@webrtc.orgde305012013-10-31 15:40:38 +00002731 bool dscp_option_changed = (options_.dscp != options.dscp);
2732
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002733 bool suspend_below_min_bitrate_changed =
2734 options.suspend_below_min_bitrate.IsSet() &&
2735 (options_.suspend_below_min_bitrate != options.suspend_below_min_bitrate);
2736
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 bool conference_mode_turned_off = false;
2738 if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
2739 options_.conference_mode.GetWithDefaultIfUnset(false) &&
2740 !options.conference_mode.GetWithDefaultIfUnset(false)) {
2741 conference_mode_turned_off = true;
2742 }
2743
2744 // Save the options, to be interpreted where appropriate.
2745 // Use options_.SetAll() instead of assignment so that unset value in options
2746 // will not overwrite the previous option value.
2747 options_.SetAll(options);
2748
2749 // Set CPU options for all send channels.
2750 for (SendChannelMap::iterator iter = send_channels_.begin();
2751 iter != send_channels_.end(); ++iter) {
2752 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2753 send_channel->ApplyCpuOptions(options_);
2754 }
2755
2756 // Adjust send codec bitrate if needed.
2757 int conf_max_bitrate = kDefaultConferenceModeMaxVideoBitrate;
2758
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002759 // Save altered min_bitrate level and apply if necessary.
2760 bool adjusted_min_bitrate = false;
2761 if (options.lower_min_bitrate.IsSet()) {
2762 bool lower;
2763 options.lower_min_bitrate.Get(&lower);
2764
2765 int new_send_min_bitrate = lower ? kLowerMinBitrate : kMinVideoBitrate;
2766 adjusted_min_bitrate = (new_send_min_bitrate != send_min_bitrate_);
2767 send_min_bitrate_ = new_send_min_bitrate;
2768 }
2769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002770 int expected_bitrate = send_max_bitrate_;
2771 if (InConferenceMode()) {
2772 expected_bitrate = conf_max_bitrate;
2773 } else if (conference_mode_turned_off) {
2774 // This is a special case for turning conference mode off.
2775 // Max bitrate should go back to the default maximum value instead
2776 // of the current maximum.
2777 expected_bitrate = kMaxVideoBitrate;
2778 }
2779
2780 if (send_codec_ &&
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002781 (send_max_bitrate_ != expected_bitrate || denoiser_changed ||
2782 adjusted_min_bitrate)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002783 // On success, SetSendCodec() will reset send_max_bitrate_ to
2784 // expected_bitrate.
2785 if (!SetSendCodec(*send_codec_,
2786 send_min_bitrate_,
2787 send_start_bitrate_,
2788 expected_bitrate)) {
2789 return false;
2790 }
2791 LogSendCodecChange("SetOptions()");
2792 }
2793 if (leaky_bucket_changed) {
2794 bool enable_leaky_bucket =
2795 options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
2796 for (SendChannelMap::iterator it = send_channels_.begin();
2797 it != send_channels_.end(); ++it) {
2798 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(
2799 it->second->channel_id(), enable_leaky_bucket) != 0) {
2800 LOG_RTCERR2(SetTransmissionSmoothingStatus, it->second->channel_id(),
2801 enable_leaky_bucket);
2802 }
2803 }
2804 }
2805 if (buffer_latency_changed) {
2806 int buffer_latency =
2807 options_.buffered_mode_latency.GetWithDefaultIfUnset(
2808 cricket::kBufferedModeDisabled);
2809 for (SendChannelMap::iterator it = send_channels_.begin();
2810 it != send_channels_.end(); ++it) {
2811 if (engine()->vie()->rtp()->SetSenderBufferingMode(
2812 it->second->channel_id(), buffer_latency) != 0) {
2813 LOG_RTCERR2(SetSenderBufferingMode, it->second->channel_id(),
2814 buffer_latency);
2815 }
2816 }
2817 for (RecvChannelMap::iterator it = recv_channels_.begin();
2818 it != recv_channels_.end(); ++it) {
2819 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
2820 it->second->channel_id(), buffer_latency) != 0) {
2821 LOG_RTCERR2(SetReceiverBufferingMode, it->second->channel_id(),
2822 buffer_latency);
2823 }
2824 }
2825 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002826 if (cpu_overuse_detection_changed) {
2827 bool cpu_overuse_detection =
2828 options_.cpu_overuse_detection.GetWithDefaultIfUnset(false);
2829 for (SendChannelMap::iterator iter = send_channels_.begin();
2830 iter != send_channels_.end(); ++iter) {
2831 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2832 send_channel->SetCpuOveruseDetection(cpu_overuse_detection);
2833 }
2834 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00002835 if (dscp_option_changed) {
2836 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002837 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00002838 dscp = kVideoDscpValue;
2839 if (MediaChannel::SetDscp(dscp) != 0) {
2840 LOG(LS_WARNING) << "Failed to set DSCP settings for video channel";
2841 }
2842 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002843 if (suspend_below_min_bitrate_changed) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002844 if (options_.suspend_below_min_bitrate.GetWithDefaultIfUnset(false)) {
2845 for (SendChannelMap::iterator it = send_channels_.begin();
2846 it != send_channels_.end(); ++it) {
2847 engine()->vie()->codec()->SuspendBelowMinBitrate(
2848 it->second->channel_id());
2849 }
2850 } else {
2851 LOG(LS_WARNING) << "Cannot disable video suspension once it is enabled";
2852 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002853 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854 return true;
2855}
2856
2857void WebRtcVideoMediaChannel::SetInterface(NetworkInterface* iface) {
2858 MediaChannel::SetInterface(iface);
2859 // Set the RTP recv/send buffer to a bigger size
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002860 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2861 talk_base::Socket::OPT_RCVBUF,
2862 kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863
2864 // TODO(sriniv): Remove or re-enable this.
2865 // As part of b/8030474, send-buffer is size now controlled through
2866 // portallocator flags.
2867 // network_interface_->SetOption(NetworkInterface::ST_RTP,
2868 // talk_base::Socket::OPT_SNDBUF,
2869 // kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870}
2871
2872void WebRtcVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
2873 ASSERT(ratio_w != 0);
2874 ASSERT(ratio_h != 0);
2875 ratio_w_ = ratio_w;
2876 ratio_h_ = ratio_h;
2877 // For now assume that all streams want the same aspect ratio.
2878 // TODO(hellner): remove the need for this assumption.
2879 for (SendChannelMap::iterator iter = send_channels_.begin();
2880 iter != send_channels_.end(); ++iter) {
2881 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2882 VideoCapturer* capturer = send_channel->video_capturer();
2883 if (capturer) {
2884 capturer->UpdateAspectRatio(ratio_w, ratio_h);
2885 }
2886 }
2887}
2888
2889bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
2890 VideoRenderer** renderer) {
2891 RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
2892 if (it == recv_channels_.end()) {
2893 if (first_receive_ssrc_ == ssrc &&
2894 recv_channels_.find(0) != recv_channels_.end()) {
2895 LOG(LS_INFO) << " GetRenderer " << ssrc
2896 << " reuse default renderer #"
2897 << vie_channel_;
2898 *renderer = recv_channels_[0]->render_adapter()->renderer();
2899 return true;
2900 }
2901 return false;
2902 }
2903
2904 *renderer = it->second->render_adapter()->renderer();
2905 return true;
2906}
2907
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002908bool WebRtcVideoMediaChannel::GetVideoAdapter(
2909 uint32 ssrc, CoordinatedVideoAdapter** video_adapter) {
2910 SendChannelMap::iterator it = send_channels_.find(ssrc);
2911 if (it == send_channels_.end()) {
2912 return false;
2913 }
2914 *video_adapter = it->second->video_adapter();
2915 return true;
2916}
2917
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002918void WebRtcVideoMediaChannel::SendFrame(VideoCapturer* capturer,
2919 const VideoFrame* frame) {
wu@webrtc.org24301a62013-12-13 19:17:43 +00002920 // If the |capturer| is registered to any send channel, then send the frame
2921 // to those send channels.
2922 bool capturer_is_channel_owned = false;
2923 for (SendChannelMap::iterator iter = send_channels_.begin();
2924 iter != send_channels_.end(); ++iter) {
2925 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2926 if (send_channel->video_capturer() == capturer) {
2927 SendFrame(send_channel, frame, capturer->IsScreencast());
2928 capturer_is_channel_owned = true;
2929 }
2930 }
2931 if (capturer_is_channel_owned) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002932 return;
2933 }
wu@webrtc.org24301a62013-12-13 19:17:43 +00002934
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002935 // TODO(hellner): Remove below for loop once the captured frame no longer
2936 // come from the engine, i.e. the engine no longer owns a capturer.
2937 for (SendChannelMap::iterator iter = send_channels_.begin();
2938 iter != send_channels_.end(); ++iter) {
2939 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2940 if (send_channel->video_capturer() == NULL) {
2941 SendFrame(send_channel, frame, capturer->IsScreencast());
2942 }
2943 }
2944}
2945
2946bool WebRtcVideoMediaChannel::SendFrame(
2947 WebRtcVideoChannelSendInfo* send_channel,
2948 const VideoFrame* frame,
2949 bool is_screencast) {
2950 if (!send_channel) {
2951 return false;
2952 }
2953 if (!send_codec_) {
2954 // Send codec has not been set. No reason to process the frame any further.
2955 return false;
2956 }
2957 const VideoFormat& video_format = send_channel->video_format();
2958 // If the frame should be dropped.
2959 const bool video_format_set = video_format != cricket::VideoFormat();
2960 if (video_format_set &&
2961 (video_format.width == 0 && video_format.height == 0)) {
2962 return true;
2963 }
2964
2965 // Checks if we need to reset vie send codec.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002966 if (!MaybeResetVieSendCodec(send_channel,
2967 static_cast<int>(frame->GetWidth()),
2968 static_cast<int>(frame->GetHeight()),
2969 is_screencast, NULL)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970 LOG(LS_ERROR) << "MaybeResetVieSendCodec failed with "
2971 << frame->GetWidth() << "x" << frame->GetHeight();
2972 return false;
2973 }
2974 const VideoFrame* frame_out = frame;
2975 talk_base::scoped_ptr<VideoFrame> processed_frame;
2976 // Disable muting for screencast.
2977 const bool mute = (send_channel->muted() && !is_screencast);
2978 send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
2979 if (processed_frame) {
2980 frame_out = processed_frame.get();
2981 }
2982
2983 webrtc::ViEVideoFrameI420 frame_i420;
2984 // TODO(ronghuawu): Update the webrtc::ViEVideoFrameI420
2985 // to use const unsigned char*
2986 frame_i420.y_plane = const_cast<unsigned char*>(frame_out->GetYPlane());
2987 frame_i420.u_plane = const_cast<unsigned char*>(frame_out->GetUPlane());
2988 frame_i420.v_plane = const_cast<unsigned char*>(frame_out->GetVPlane());
2989 frame_i420.y_pitch = frame_out->GetYPitch();
2990 frame_i420.u_pitch = frame_out->GetUPitch();
2991 frame_i420.v_pitch = frame_out->GetVPitch();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002992 frame_i420.width = static_cast<uint16>(frame_out->GetWidth());
2993 frame_i420.height = static_cast<uint16>(frame_out->GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002994
2995 int64 timestamp_ntp_ms = 0;
2996 // TODO(justinlin): Reenable after Windows issues with clock drift are fixed.
2997 // Currently reverted to old behavior of discarding capture timestamp.
2998#if 0
2999 // If the frame timestamp is 0, we will use the deliver time.
3000 const int64 frame_timestamp = frame->GetTimeStamp();
3001 if (frame_timestamp != 0) {
3002 if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
3003 kTimestampDeltaInSecondsForWarning) {
3004 LOG(LS_WARNING) << "Frame timestamp differs by more than "
3005 << kTimestampDeltaInSecondsForWarning << " seconds from "
3006 << "current Unix timestamp.";
3007 }
3008
3009 timestamp_ntp_ms =
3010 talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
3011 }
3012#endif
3013
3014 return send_channel->external_capture()->IncomingFrameI420(
3015 frame_i420, timestamp_ntp_ms) == 0;
3016}
3017
3018bool WebRtcVideoMediaChannel::CreateChannel(uint32 ssrc_key,
3019 MediaDirection direction,
3020 int* channel_id) {
3021 // There are 3 types of channels. Sending only, receiving only and
3022 // sending and receiving. The sending and receiving channel is the
3023 // default channel and there is only one. All other channels that are created
3024 // are associated with the default channel which must exist. The default
3025 // channel id is stored in |vie_channel_|. All channels need to know about
3026 // the default channel to properly handle remb which is why there are
3027 // different ViE create channel calls.
3028 // For this channel the local and remote ssrc key is 0. However, it may
3029 // have a non-zero local and/or remote ssrc depending on if it is currently
3030 // sending and/or receiving.
3031 if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
3032 (!send_channels_.empty() || !recv_channels_.empty())) {
3033 ASSERT(false);
3034 return false;
3035 }
3036
3037 *channel_id = -1;
3038 if (direction == MD_RECV) {
3039 // All rec channels are associated with the default channel |vie_channel_|
3040 if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
3041 vie_channel_) != 0) {
3042 LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
3043 return false;
3044 }
3045 } else if (direction == MD_SEND) {
3046 if (engine_->vie()->base()->CreateChannel(*channel_id,
3047 vie_channel_) != 0) {
3048 LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
3049 return false;
3050 }
3051 } else {
3052 ASSERT(direction == MD_SENDRECV);
3053 if (engine_->vie()->base()->CreateChannel(*channel_id) != 0) {
3054 LOG_RTCERR1(CreateChannel, *channel_id);
3055 return false;
3056 }
3057 }
3058 if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
3059 engine_->vie()->base()->DeleteChannel(*channel_id);
3060 *channel_id = -1;
3061 return false;
3062 }
3063
3064 return true;
3065}
3066
3067bool WebRtcVideoMediaChannel::ConfigureChannel(int channel_id,
3068 MediaDirection direction,
3069 uint32 ssrc_key) {
3070 const bool receiving = (direction == MD_RECV) || (direction == MD_SENDRECV);
3071 const bool sending = (direction == MD_SEND) || (direction == MD_SENDRECV);
3072 // Register external transport.
3073 if (engine_->vie()->network()->RegisterSendTransport(
3074 channel_id, *this) != 0) {
3075 LOG_RTCERR1(RegisterSendTransport, channel_id);
3076 return false;
3077 }
3078
3079 // Set MTU.
3080 if (engine_->vie()->network()->SetMTU(channel_id, kVideoMtu) != 0) {
3081 LOG_RTCERR2(SetMTU, channel_id, kVideoMtu);
3082 return false;
3083 }
3084 // Turn on RTCP and loss feedback reporting.
3085 if (engine()->vie()->rtp()->SetRTCPStatus(
3086 channel_id, webrtc::kRtcpCompound_RFC4585) != 0) {
3087 LOG_RTCERR2(SetRTCPStatus, channel_id, webrtc::kRtcpCompound_RFC4585);
3088 return false;
3089 }
3090 // Enable pli as key frame request method.
3091 if (engine_->vie()->rtp()->SetKeyFrameRequestMethod(
3092 channel_id, webrtc::kViEKeyFrameRequestPliRtcp) != 0) {
3093 LOG_RTCERR2(SetKeyFrameRequestMethod,
3094 channel_id, webrtc::kViEKeyFrameRequestPliRtcp);
3095 return false;
3096 }
3097 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3098 // Logged in SetNackFec. Don't spam the logs.
3099 return false;
3100 }
3101 // Note that receiving must always be configured before sending to ensure
3102 // that send and receive channel is configured correctly (ConfigureReceiving
3103 // assumes no sending).
3104 if (receiving) {
3105 if (!ConfigureReceiving(channel_id, ssrc_key)) {
3106 return false;
3107 }
3108 }
3109 if (sending) {
3110 if (!ConfigureSending(channel_id, ssrc_key)) {
3111 return false;
3112 }
3113 }
3114
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00003115 // Start receiving for both receive and send channels so that we get incoming
3116 // RTP (if receiving) as well as RTCP feedback (if sending).
3117 if (engine()->vie()->base()->StartReceive(channel_id) != 0) {
3118 LOG_RTCERR1(StartReceive, channel_id);
3119 return false;
3120 }
3121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003122 return true;
3123}
3124
3125bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
3126 uint32 remote_ssrc_key) {
3127 // Make sure that an SSRC/key isn't registered more than once.
3128 if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
3129 return false;
3130 }
3131 // Connect the voice channel, if there is one.
3132 // TODO(perkj): The A/V is synched by the receiving channel. So we need to
3133 // know the SSRC of the remote audio channel in order to fetch the correct
3134 // webrtc VoiceEngine channel. For now- only sync the default channel used
3135 // in 1-1 calls.
3136 if (remote_ssrc_key == 0 && voice_channel_) {
3137 WebRtcVoiceMediaChannel* voice_channel =
3138 static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
3139 if (engine_->vie()->base()->ConnectAudioChannel(
3140 vie_channel_, voice_channel->voe_channel()) != 0) {
3141 LOG_RTCERR2(ConnectAudioChannel, channel_id,
3142 voice_channel->voe_channel());
3143 LOG(LS_WARNING) << "A/V not synchronized";
3144 // Not a fatal error.
3145 }
3146 }
3147
3148 talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
3149 new WebRtcVideoChannelRecvInfo(channel_id));
3150
3151 // Install a render adapter.
3152 if (engine_->vie()->render()->AddRenderer(channel_id,
3153 webrtc::kVideoI420, channel_info->render_adapter()) != 0) {
3154 LOG_RTCERR3(AddRenderer, channel_id, webrtc::kVideoI420,
3155 channel_info->render_adapter());
3156 return false;
3157 }
3158
3159
3160 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3161 kNotSending,
3162 remb_enabled_) != 0) {
3163 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
3164 return false;
3165 }
3166
3167 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus,
3168 channel_id, receive_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3169 return false;
3170 }
3171
3172 if (!SetHeaderExtension(
3173 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
3174 receive_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
3175 return false;
3176 }
3177
3178 if (remote_ssrc_key != 0) {
3179 // Use the same SSRC as our default channel
3180 // (so the RTCP reports are correct).
3181 unsigned int send_ssrc = 0;
3182 webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
3183 if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
3184 LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
3185 return false;
3186 }
3187 if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
3188 LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
3189 return false;
3190 }
3191 } // Else this is the the default channel and we don't change the SSRC.
3192
3193 // Disable color enhancement since it is a bit too aggressive.
3194 if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
3195 false) != 0) {
3196 LOG_RTCERR1(EnableColorEnhancement, channel_id);
3197 return false;
3198 }
3199
3200 if (!SetReceiveCodecs(channel_info.get())) {
3201 return false;
3202 }
3203
3204 int buffer_latency =
3205 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3206 cricket::kBufferedModeDisabled);
3207 if (buffer_latency != cricket::kBufferedModeDisabled) {
3208 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
3209 channel_id, buffer_latency) != 0) {
3210 LOG_RTCERR2(SetReceiverBufferingMode, channel_id, buffer_latency);
3211 }
3212 }
3213
3214 if (render_started_) {
3215 if (engine_->vie()->render()->StartRender(channel_id) != 0) {
3216 LOG_RTCERR1(StartRender, channel_id);
3217 return false;
3218 }
3219 }
3220
3221 // Register decoder observer for incoming framerate and bitrate.
3222 if (engine()->vie()->codec()->RegisterDecoderObserver(
3223 channel_id, *channel_info->decoder_observer()) != 0) {
3224 LOG_RTCERR1(RegisterDecoderObserver, channel_info->decoder_observer());
3225 return false;
3226 }
3227
3228 recv_channels_[remote_ssrc_key] = channel_info.release();
3229 return true;
3230}
3231
3232bool WebRtcVideoMediaChannel::ConfigureSending(int channel_id,
3233 uint32 local_ssrc_key) {
3234 // The ssrc key can be zero or correspond to an SSRC.
3235 // Make sure the default channel isn't configured more than once.
3236 if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
3237 return false;
3238 }
3239 // Make sure that the SSRC is not already in use.
3240 uint32 dummy_key;
3241 if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
3242 return false;
3243 }
3244 int vie_capture = 0;
3245 webrtc::ViEExternalCapture* external_capture = NULL;
3246 // Register external capture.
3247 if (engine()->vie()->capture()->AllocateExternalCaptureDevice(
3248 vie_capture, external_capture) != 0) {
3249 LOG_RTCERR0(AllocateExternalCaptureDevice);
3250 return false;
3251 }
3252
3253 // Connect external capture.
3254 if (engine()->vie()->capture()->ConnectCaptureDevice(
3255 vie_capture, channel_id) != 0) {
3256 LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
3257 return false;
3258 }
3259 talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
3260 new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
3261 external_capture,
3262 engine()->cpu_monitor()));
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003263 if (engine()->vie()->base()->RegisterCpuOveruseObserver(
3264 channel_id, send_channel->overuse_observer())) {
3265 LOG_RTCERR1(RegisterCpuOveruseObserver, channel_id);
3266 return false;
3267 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003268 send_channel->ApplyCpuOptions(options_);
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003269 send_channel->SignalCpuAdaptationUnable.connect(this,
3270 &WebRtcVideoMediaChannel::OnCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003271
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003272 if (options_.cpu_overuse_detection.GetWithDefaultIfUnset(false)) {
3273 send_channel->SetCpuOveruseDetection(true);
3274 }
3275
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 // Register encoder observer for outgoing framerate and bitrate.
3277 if (engine()->vie()->codec()->RegisterEncoderObserver(
3278 channel_id, *send_channel->encoder_observer()) != 0) {
3279 LOG_RTCERR1(RegisterEncoderObserver, send_channel->encoder_observer());
3280 return false;
3281 }
3282
3283 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus,
3284 channel_id, send_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3285 return false;
3286 }
3287
3288 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus,
3289 channel_id, send_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
3290 return false;
3291 }
3292
3293 if (options_.video_leaky_bucket.GetWithDefaultIfUnset(false)) {
3294 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
3295 true) != 0) {
3296 LOG_RTCERR2(SetTransmissionSmoothingStatus, channel_id, true);
3297 return false;
3298 }
3299 }
3300
3301 int buffer_latency =
3302 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3303 cricket::kBufferedModeDisabled);
3304 if (buffer_latency != cricket::kBufferedModeDisabled) {
3305 if (engine()->vie()->rtp()->SetSenderBufferingMode(
3306 channel_id, buffer_latency) != 0) {
3307 LOG_RTCERR2(SetSenderBufferingMode, channel_id, buffer_latency);
3308 }
3309 }
3310 // The remb status direction correspond to the RTP stream (and not the RTCP
3311 // stream). I.e. if send remb is enabled it means it is receiving remote
3312 // rembs and should use them to estimate bandwidth. Receive remb mean that
3313 // remb packets will be generated and that the channel should be included in
3314 // it. If remb is enabled all channels are allowed to contribute to the remb
3315 // but only receive channels will ever end up actually contributing. This
3316 // keeps the logic simple.
3317 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3318 remb_enabled_,
3319 remb_enabled_) != 0) {
3320 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
3321 return false;
3322 }
3323 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3324 // Logged in SetNackFec. Don't spam the logs.
3325 return false;
3326 }
3327
3328 send_channels_[local_ssrc_key] = send_channel.release();
3329
3330 return true;
3331}
3332
3333bool WebRtcVideoMediaChannel::SetNackFec(int channel_id,
3334 int red_payload_type,
3335 int fec_payload_type,
3336 bool nack_enabled) {
3337 bool enable = (red_payload_type != -1 && fec_payload_type != -1 &&
3338 !InConferenceMode());
3339 if (enable) {
3340 if (engine_->vie()->rtp()->SetHybridNACKFECStatus(
3341 channel_id, nack_enabled, red_payload_type, fec_payload_type) != 0) {
3342 LOG_RTCERR4(SetHybridNACKFECStatus,
3343 channel_id, nack_enabled, red_payload_type, fec_payload_type);
3344 return false;
3345 }
3346 LOG(LS_INFO) << "Hybrid NACK/FEC enabled for channel " << channel_id;
3347 } else {
3348 if (engine_->vie()->rtp()->SetNACKStatus(channel_id, nack_enabled) != 0) {
3349 LOG_RTCERR1(SetNACKStatus, channel_id);
3350 return false;
3351 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003352 std::string enabled = nack_enabled ? "enabled" : "disabled";
3353 LOG(LS_INFO) << "NACK " << enabled << " for channel " << channel_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 }
3355 return true;
3356}
3357
3358bool WebRtcVideoMediaChannel::SetSendCodec(const webrtc::VideoCodec& codec,
3359 int min_bitrate,
3360 int start_bitrate,
3361 int max_bitrate) {
3362 bool ret_val = true;
3363 for (SendChannelMap::iterator iter = send_channels_.begin();
3364 iter != send_channels_.end(); ++iter) {
3365 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3366 ret_val = SetSendCodec(send_channel, codec, min_bitrate, start_bitrate,
3367 max_bitrate) && ret_val;
3368 }
3369 if (ret_val) {
3370 // All SetSendCodec calls were successful. Update the global state
3371 // accordingly.
3372 send_codec_.reset(new webrtc::VideoCodec(codec));
3373 send_min_bitrate_ = min_bitrate;
3374 send_start_bitrate_ = start_bitrate;
3375 send_max_bitrate_ = max_bitrate;
3376 } else {
3377 // At least one SetSendCodec call failed, rollback.
3378 for (SendChannelMap::iterator iter = send_channels_.begin();
3379 iter != send_channels_.end(); ++iter) {
3380 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3381 if (send_codec_) {
3382 SetSendCodec(send_channel, *send_codec_.get(), send_min_bitrate_,
3383 send_start_bitrate_, send_max_bitrate_);
3384 }
3385 }
3386 }
3387 return ret_val;
3388}
3389
3390bool WebRtcVideoMediaChannel::SetSendCodec(
3391 WebRtcVideoChannelSendInfo* send_channel,
3392 const webrtc::VideoCodec& codec,
3393 int min_bitrate,
3394 int start_bitrate,
3395 int max_bitrate) {
3396 if (!send_channel) {
3397 return false;
3398 }
3399 const int channel_id = send_channel->channel_id();
3400 // Make a copy of the codec
3401 webrtc::VideoCodec target_codec = codec;
3402 target_codec.startBitrate = start_bitrate;
3403 target_codec.minBitrate = min_bitrate;
3404 target_codec.maxBitrate = max_bitrate;
3405
3406 // Set the default number of temporal layers for VP8.
3407 if (webrtc::kVideoCodecVP8 == codec.codecType) {
3408 target_codec.codecSpecific.VP8.numberOfTemporalLayers =
3409 kDefaultNumberOfTemporalLayers;
3410
3411 // Turn off the VP8 error resilience
3412 target_codec.codecSpecific.VP8.resilience = webrtc::kResilienceOff;
3413
3414 bool enable_denoising =
3415 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3416 target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
3417 }
3418
3419 // Register external encoder if codec type is supported by encoder factory.
3420 if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
3421 !send_channel->IsEncoderRegistered(target_codec.plType)) {
3422 webrtc::VideoEncoder* encoder =
3423 engine()->CreateExternalEncoder(codec.codecType);
3424 if (encoder) {
3425 if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
3426 channel_id, target_codec.plType, encoder, false) == 0) {
3427 send_channel->RegisterEncoder(target_codec.plType, encoder);
3428 } else {
3429 LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
3430 engine()->DestroyExternalEncoder(encoder);
3431 }
3432 }
3433 }
3434
3435 // Resolution and framerate may vary for different send channels.
3436 const VideoFormat& video_format = send_channel->video_format();
3437 UpdateVideoCodec(video_format, &target_codec);
3438
3439 if (target_codec.width == 0 && target_codec.height == 0) {
3440 const uint32 ssrc = send_channel->stream_params()->first_ssrc();
3441 LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
3442 << "for ssrc: " << ssrc << ".";
3443 } else {
3444 MaybeChangeStartBitrate(channel_id, &target_codec);
3445 if (0 != engine()->vie()->codec()->SetSendCodec(channel_id, target_codec)) {
3446 LOG_RTCERR2(SetSendCodec, channel_id, target_codec.plName);
3447 return false;
3448 }
3449
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003450 // NOTE: SetRtxSendPayloadType must be called after all simulcast SSRCs
3451 // are configured. Otherwise ssrc's configured after this point will use
3452 // the primary PT for RTX.
3453 if (send_rtx_type_ != -1 &&
3454 engine()->vie()->rtp()->SetRtxSendPayloadType(channel_id,
3455 send_rtx_type_) != 0) {
3456 LOG_RTCERR2(SetRtxSendPayloadType, channel_id, send_rtx_type_);
3457 return false;
3458 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003459 }
3460 send_channel->set_interval(
3461 cricket::VideoFormat::FpsToInterval(target_codec.maxFramerate));
3462 return true;
3463}
3464
3465
3466static std::string ToString(webrtc::VideoCodecComplexity complexity) {
3467 switch (complexity) {
3468 case webrtc::kComplexityNormal:
3469 return "normal";
3470 case webrtc::kComplexityHigh:
3471 return "high";
3472 case webrtc::kComplexityHigher:
3473 return "higher";
3474 case webrtc::kComplexityMax:
3475 return "max";
3476 default:
3477 return "unknown";
3478 }
3479}
3480
3481static std::string ToString(webrtc::VP8ResilienceMode resilience) {
3482 switch (resilience) {
3483 case webrtc::kResilienceOff:
3484 return "off";
3485 case webrtc::kResilientStream:
3486 return "stream";
3487 case webrtc::kResilientFrames:
3488 return "frames";
3489 default:
3490 return "unknown";
3491 }
3492}
3493
3494void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
3495 webrtc::VideoCodec vie_codec;
3496 if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
3497 LOG_RTCERR1(GetSendCodec, vie_channel_);
3498 return;
3499 }
3500
3501 LOG(LS_INFO) << reason << " : selected video codec "
3502 << vie_codec.plName << "/"
3503 << vie_codec.width << "x" << vie_codec.height << "x"
3504 << static_cast<int>(vie_codec.maxFramerate) << "fps"
3505 << "@" << vie_codec.maxBitrate << "kbps"
3506 << " (min=" << vie_codec.minBitrate << "kbps,"
3507 << " start=" << vie_codec.startBitrate << "kbps)";
3508 LOG(LS_INFO) << "Video max quantization: " << vie_codec.qpMax;
3509 if (webrtc::kVideoCodecVP8 == vie_codec.codecType) {
3510 LOG(LS_INFO) << "VP8 number of temporal layers: "
3511 << static_cast<int>(
3512 vie_codec.codecSpecific.VP8.numberOfTemporalLayers);
3513 LOG(LS_INFO) << "VP8 options : "
3514 << "picture loss indication = "
3515 << vie_codec.codecSpecific.VP8.pictureLossIndicationOn
3516 << ", feedback mode = "
3517 << vie_codec.codecSpecific.VP8.feedbackModeOn
3518 << ", complexity = "
3519 << ToString(vie_codec.codecSpecific.VP8.complexity)
3520 << ", resilience = "
3521 << ToString(vie_codec.codecSpecific.VP8.resilience)
3522 << ", denoising = "
3523 << vie_codec.codecSpecific.VP8.denoisingOn
3524 << ", error concealment = "
3525 << vie_codec.codecSpecific.VP8.errorConcealmentOn
3526 << ", automatic resize = "
3527 << vie_codec.codecSpecific.VP8.automaticResizeOn
3528 << ", frame dropping = "
3529 << vie_codec.codecSpecific.VP8.frameDroppingOn
3530 << ", key frame interval = "
3531 << vie_codec.codecSpecific.VP8.keyFrameInterval;
3532 }
3533
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003534 if (send_rtx_type_ != -1) {
3535 LOG(LS_INFO) << "RTX payload type: " << send_rtx_type_;
3536 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537}
3538
3539bool WebRtcVideoMediaChannel::SetReceiveCodecs(
3540 WebRtcVideoChannelRecvInfo* info) {
3541 int red_type = -1;
3542 int fec_type = -1;
3543 int channel_id = info->channel_id();
3544 for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
3545 it != receive_codecs_.end(); ++it) {
3546 if (it->codecType == webrtc::kVideoCodecRED) {
3547 red_type = it->plType;
3548 } else if (it->codecType == webrtc::kVideoCodecULPFEC) {
3549 fec_type = it->plType;
3550 }
3551 if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
3552 LOG_RTCERR2(SetReceiveCodec, channel_id, it->plName);
3553 return false;
3554 }
3555 if (!info->IsDecoderRegistered(it->plType) &&
3556 it->codecType != webrtc::kVideoCodecRED &&
3557 it->codecType != webrtc::kVideoCodecULPFEC) {
3558 webrtc::VideoDecoder* decoder =
3559 engine()->CreateExternalDecoder(it->codecType);
3560 if (decoder) {
3561 if (engine()->vie()->ext_codec()->RegisterExternalReceiveCodec(
3562 channel_id, it->plType, decoder) == 0) {
3563 info->RegisterDecoder(it->plType, decoder);
3564 } else {
3565 LOG_RTCERR2(RegisterExternalReceiveCodec, channel_id, it->plName);
3566 engine()->DestroyExternalDecoder(decoder);
3567 }
3568 }
3569 }
3570 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003571 return true;
3572}
3573
3574int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
3575 if (ssrc == first_receive_ssrc_) {
3576 return vie_channel_;
3577 }
3578 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
3579 return (it != recv_channels_.end()) ? it->second->channel_id() : -1;
3580}
3581
3582// If the new frame size is different from the send codec size we set on vie,
3583// we need to reset the send codec on vie.
3584// The new send codec size should not exceed send_codec_ which is controlled
3585// only by the 'jec' logic.
3586bool WebRtcVideoMediaChannel::MaybeResetVieSendCodec(
3587 WebRtcVideoChannelSendInfo* send_channel,
3588 int new_width,
3589 int new_height,
3590 bool is_screencast,
3591 bool* reset) {
3592 if (reset) {
3593 *reset = false;
3594 }
3595 ASSERT(send_codec_.get() != NULL);
3596
3597 webrtc::VideoCodec target_codec = *send_codec_.get();
3598 const VideoFormat& video_format = send_channel->video_format();
3599 UpdateVideoCodec(video_format, &target_codec);
3600
3601 // Vie send codec size should not exceed target_codec.
3602 int target_width = new_width;
3603 int target_height = new_height;
3604 if (!is_screencast &&
3605 (new_width > target_codec.width || new_height > target_codec.height)) {
3606 target_width = target_codec.width;
3607 target_height = target_codec.height;
3608 }
3609
3610 // Get current vie codec.
3611 webrtc::VideoCodec vie_codec;
3612 const int channel_id = send_channel->channel_id();
3613 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) != 0) {
3614 LOG_RTCERR1(GetSendCodec, channel_id);
3615 return false;
3616 }
3617 const int cur_width = vie_codec.width;
3618 const int cur_height = vie_codec.height;
3619
3620 // Only reset send codec when there is a size change. Additionally,
3621 // automatic resize needs to be turned off when screencasting and on when
3622 // not screencasting.
3623 // Don't allow automatic resizing for screencasting.
3624 bool automatic_resize = !is_screencast;
3625 // Turn off VP8 frame dropping when screensharing as the current model does
3626 // not work well at low fps.
3627 bool vp8_frame_dropping = !is_screencast;
3628 // Disable denoising for screencasting.
3629 bool enable_denoising =
3630 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3631 bool denoising = !is_screencast && enable_denoising;
3632 bool reset_send_codec =
3633 target_width != cur_width || target_height != cur_height ||
3634 automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
3635 denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
3636 vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
3637
3638 if (reset_send_codec) {
3639 // Set the new codec on vie.
3640 vie_codec.width = target_width;
3641 vie_codec.height = target_height;
3642 vie_codec.maxFramerate = target_codec.maxFramerate;
3643 vie_codec.startBitrate = target_codec.startBitrate;
3644 vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
3645 vie_codec.codecSpecific.VP8.denoisingOn = denoising;
3646 vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
3647 // TODO(mflodman): Remove 'is_screencast' check when screen cast settings
3648 // are treated correctly in WebRTC.
3649 if (!is_screencast)
3650 MaybeChangeStartBitrate(channel_id, &vie_codec);
3651
3652 if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
3653 LOG_RTCERR1(SetSendCodec, channel_id);
3654 return false;
3655 }
3656 if (reset) {
3657 *reset = true;
3658 }
3659 LogSendCodecChange("Capture size changed");
3660 }
3661
3662 return true;
3663}
3664
3665void WebRtcVideoMediaChannel::MaybeChangeStartBitrate(
3666 int channel_id, webrtc::VideoCodec* video_codec) {
3667 if (video_codec->startBitrate < video_codec->minBitrate) {
3668 video_codec->startBitrate = video_codec->minBitrate;
3669 } else if (video_codec->startBitrate > video_codec->maxBitrate) {
3670 video_codec->startBitrate = video_codec->maxBitrate;
3671 }
3672
3673 // Use a previous target bitrate, if there is one.
3674 unsigned int current_target_bitrate = 0;
3675 if (engine()->vie()->codec()->GetCodecTargetBitrate(
3676 channel_id, &current_target_bitrate) == 0) {
3677 // Convert to kbps.
3678 current_target_bitrate /= 1000;
3679 if (current_target_bitrate > video_codec->maxBitrate) {
3680 current_target_bitrate = video_codec->maxBitrate;
3681 }
3682 if (current_target_bitrate > video_codec->startBitrate) {
3683 video_codec->startBitrate = current_target_bitrate;
3684 }
3685 }
3686}
3687
3688void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
3689 FlushBlackFrameData* black_frame_data =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003690 static_cast<FlushBlackFrameData*>(msg->pdata);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003691 FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
3692 delete black_frame_data;
3693}
3694
3695int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
3696 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003697 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003698 return MediaChannel::SendPacket(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003699}
3700
3701int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
3702 const void* data,
3703 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003704 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003705 return MediaChannel::SendRtcp(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003706}
3707
3708void WebRtcVideoMediaChannel::QueueBlackFrame(uint32 ssrc, int64 timestamp,
3709 int framerate) {
3710 if (timestamp) {
3711 FlushBlackFrameData* black_frame_data = new FlushBlackFrameData(
3712 ssrc,
3713 timestamp);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003714 const int delay_ms = static_cast<int>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003715 2 * cricket::VideoFormat::FpsToInterval(framerate) *
3716 talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
3717 worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
3718 }
3719}
3720
3721void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
3722 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
3723 if (!send_channel) {
3724 return;
3725 }
3726 talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
3727
3728 const WebRtcLocalStreamInfo* channel_stream_info =
3729 send_channel->local_stream_info();
3730 int64 last_frame_time_stamp = channel_stream_info->time_stamp();
3731 if (last_frame_time_stamp == timestamp) {
3732 size_t last_frame_width = 0;
3733 size_t last_frame_height = 0;
3734 int64 last_frame_elapsed_time = 0;
3735 channel_stream_info->GetLastFrameInfo(&last_frame_width, &last_frame_height,
3736 &last_frame_elapsed_time);
3737 if (!last_frame_width || !last_frame_height) {
3738 return;
3739 }
3740 WebRtcVideoFrame black_frame;
3741 // Black frame is not screencast.
3742 const bool screencasting = false;
3743 const int64 timestamp_delta = send_channel->interval();
3744 if (!black_frame.InitToBlack(send_codec_->width, send_codec_->height, 1, 1,
3745 last_frame_elapsed_time + timestamp_delta,
3746 last_frame_time_stamp + timestamp_delta) ||
3747 !SendFrame(send_channel, &black_frame, screencasting)) {
3748 LOG(LS_ERROR) << "Failed to send black frame.";
3749 }
3750 }
3751}
3752
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003753void WebRtcVideoMediaChannel::OnCpuAdaptationUnable() {
3754 // ssrc is hardcoded to 0. This message is based on a system wide issue,
3755 // so finding which ssrc caused it doesn't matter.
3756 SignalMediaError(0, VideoMediaChannel::ERROR_REC_CPU_MAX_CANT_DOWNGRADE);
3757}
3758
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003759void WebRtcVideoMediaChannel::SetNetworkTransmissionState(
3760 bool is_transmitting) {
3761 LOG(LS_INFO) << "SetNetworkTransmissionState: " << is_transmitting;
3762 for (SendChannelMap::iterator iter = send_channels_.begin();
3763 iter != send_channels_.end(); ++iter) {
3764 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3765 int channel_id = send_channel->channel_id();
3766 engine_->vie()->network()->SetNetworkTransmissionState(channel_id,
3767 is_transmitting);
3768 }
3769}
3770
3771bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3772 int channel_id, const RtpHeaderExtension* extension) {
3773 bool enable = false;
3774 int id = 0;
3775 if (extension) {
3776 enable = true;
3777 id = extension->id;
3778 }
3779 if ((engine_->vie()->rtp()->*setter)(channel_id, enable, id) != 0) {
3780 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
3781 return false;
3782 }
3783 return true;
3784}
3785
3786bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3787 int channel_id, const std::vector<RtpHeaderExtension>& extensions,
3788 const char header_extension_uri[]) {
3789 const RtpHeaderExtension* extension = FindHeaderExtension(extensions,
3790 header_extension_uri);
3791 return SetHeaderExtension(setter, channel_id, extension);
3792}
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003793
3794bool WebRtcVideoMediaChannel::SetLocalRtxSsrc(int channel_id,
3795 const StreamParams& send_params,
3796 uint32 primary_ssrc,
3797 int stream_idx) {
3798 uint32 rtx_ssrc = 0;
3799 bool has_rtx = send_params.GetFidSsrc(primary_ssrc, &rtx_ssrc);
3800 if (has_rtx && engine()->vie()->rtp()->SetLocalSSRC(
3801 channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, stream_idx) != 0) {
3802 LOG_RTCERR4(SetLocalSSRC, channel_id, rtx_ssrc,
3803 webrtc::kViEStreamTypeRtx, stream_idx);
3804 return false;
3805 }
3806 return true;
3807}
3808
wu@webrtc.org24301a62013-12-13 19:17:43 +00003809void WebRtcVideoMediaChannel::MaybeConnectCapturer(VideoCapturer* capturer) {
3810 if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
3811 capturer->SignalVideoFrame.connect(this,
3812 &WebRtcVideoMediaChannel::SendFrame);
3813 }
3814}
3815
3816void WebRtcVideoMediaChannel::MaybeDisconnectCapturer(VideoCapturer* capturer) {
3817 if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
3818 capturer->SignalVideoFrame.disconnect(this);
3819 }
3820}
3821
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003822} // namespace cricket
3823
3824#endif // HAVE_WEBRTC_VIDEO