blob: 6032134cf8c039996f24ed754ee3459bd969c70c [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"
63
64#if !defined(LIBPEERCONNECTION_LIB)
65#ifndef HAVE_WEBRTC_VIDEO
66#error Need webrtc video
67#endif
68#include "talk/media/webrtc/webrtcmediaengine.h"
69
70WRME_EXPORT
71cricket::MediaEngineInterface* CreateWebRtcMediaEngine(
72 webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc,
73 cricket::WebRtcVideoEncoderFactory* encoder_factory,
74 cricket::WebRtcVideoDecoderFactory* decoder_factory) {
75 return new cricket::WebRtcMediaEngine(adm, adm_sc, encoder_factory,
76 decoder_factory);
77}
78
79WRME_EXPORT
80void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) {
81 delete static_cast<cricket::WebRtcMediaEngine*>(media_engine);
82}
83#endif
84
85
86namespace cricket {
87
88
89static const int kDefaultLogSeverity = talk_base::LS_WARNING;
90
91static const int kMinVideoBitrate = 50;
92static const int kStartVideoBitrate = 300;
93static const int kMaxVideoBitrate = 2000;
94static const int kDefaultConferenceModeMaxVideoBitrate = 500;
95
wu@webrtc.orgcecfd182013-10-30 05:18:12 +000096// Controlled by exp, try a super low minimum bitrate for poor connections.
97static const int kLowerMinBitrate = 30;
98
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099static const int kVideoMtu = 1200;
100
101static const int kVideoRtpBufferSize = 65536;
102
103static const char kVp8PayloadName[] = "VP8";
104static const char kRedPayloadName[] = "red";
105static const char kFecPayloadName[] = "ulpfec";
106
107static const int kDefaultNumberOfTemporalLayers = 1; // 1:1
108
109static const int kTimestampDeltaInSecondsForWarning = 2;
110
111static const int kMaxExternalVideoCodecs = 8;
112static const int kExternalVideoPayloadTypeBase = 120;
113
114// Static allocation of payload type values for external video codec.
115static int GetExternalVideoPayloadType(int index) {
116 ASSERT(index >= 0 && index < kMaxExternalVideoCodecs);
117 return kExternalVideoPayloadTypeBase + index;
118}
119
120static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
121 const char* delim = "\r\n";
122 // TODO(fbarchard): Fix strtok lint warning.
123 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
124 LOG_V(sev) << tok;
125 }
126}
127
128// Severity is an integer because it comes is assumed to be from command line.
129static int SeverityToFilter(int severity) {
130 int filter = webrtc::kTraceNone;
131 switch (severity) {
132 case talk_base::LS_VERBOSE:
133 filter |= webrtc::kTraceAll;
134 case talk_base::LS_INFO:
135 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
136 case talk_base::LS_WARNING:
137 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
138 case talk_base::LS_ERROR:
139 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
140 }
141 return filter;
142}
143
144static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
145
146static const bool kNotSending = false;
147
148// Extension header for RTP timestamp offset, see RFC 5450 for details:
149// http://tools.ietf.org/html/rfc5450
150static const char kRtpTimestampOffsetHeaderExtension[] =
151 "urn:ietf:params:rtp-hdrext:toffset";
152static const int kRtpTimeOffsetExtensionId = 2;
153
154// Extension header for absolute send time, see url for details:
155// http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
156static const char kRtpAbsoluteSendTimeHeaderExtension[] =
157 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
158static const int kRtpAbsoluteSendTimeExtensionId = 3;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000159// Default video dscp value.
160// See http://tools.ietf.org/html/rfc2474 for details
161// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
162static const talk_base::DiffServCodePoint kVideoDscpValue =
163 talk_base::DSCP_AF41;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000164
165static bool IsNackEnabled(const VideoCodec& codec) {
166 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
167 kParamValueEmpty));
168}
169
170// Returns true if Receiver Estimated Max Bitrate is enabled.
171static bool IsRembEnabled(const VideoCodec& codec) {
172 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamRemb,
173 kParamValueEmpty));
174}
175
176struct FlushBlackFrameData : public talk_base::MessageData {
177 FlushBlackFrameData(uint32 s, int64 t) : ssrc(s), timestamp(t) {
178 }
179 uint32 ssrc;
180 int64 timestamp;
181};
182
183class WebRtcRenderAdapter : public webrtc::ExternalRenderer {
184 public:
185 explicit WebRtcRenderAdapter(VideoRenderer* renderer)
186 : renderer_(renderer), width_(0), height_(0), watermark_enabled_(false) {
187 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000188
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 virtual ~WebRtcRenderAdapter() {
190 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000191
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000192 void set_watermark_enabled(bool enable) {
193 talk_base::CritScope cs(&crit_);
194 watermark_enabled_ = enable;
195 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000196
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000197 void SetRenderer(VideoRenderer* renderer) {
198 talk_base::CritScope cs(&crit_);
199 renderer_ = renderer;
200 // FrameSizeChange may have already been called when renderer was not set.
201 // If so we should call SetSize here.
202 // TODO(ronghuawu): Add unit test for this case. Didn't do it now
203 // because the WebRtcRenderAdapter is currently hiding in cc file. No
204 // good way to get access to it from the unit test.
205 if (width_ > 0 && height_ > 0 && renderer_ != NULL) {
206 if (!renderer_->SetSize(width_, height_, 0)) {
207 LOG(LS_ERROR)
208 << "WebRtcRenderAdapter SetRenderer failed to SetSize to: "
209 << width_ << "x" << height_;
210 }
211 }
212 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000213
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214 // Implementation of webrtc::ExternalRenderer.
215 virtual int FrameSizeChange(unsigned int width, unsigned int height,
216 unsigned int /*number_of_streams*/) {
217 talk_base::CritScope cs(&crit_);
218 width_ = width;
219 height_ = height;
220 LOG(LS_INFO) << "WebRtcRenderAdapter frame size changed to: "
221 << width << "x" << height;
222 if (renderer_ == NULL) {
223 LOG(LS_VERBOSE) << "WebRtcRenderAdapter the renderer has not been set. "
224 << "SetSize will be called later in SetRenderer.";
225 return 0;
226 }
227 return renderer_->SetSize(width_, height_, 0) ? 0 : -1;
228 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000229
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000230 virtual int DeliverFrame(unsigned char* buffer, int buffer_size,
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000231 uint32_t time_stamp, int64_t render_time
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000232 , void* handle
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000233 ) {
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),
396 bitrate_(0) {
397 }
398
399 // virtual functions from VieEncoderObserver.
400 virtual void OutgoingRate(const int videoChannel,
401 const unsigned int framerate,
402 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000403 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 ASSERT(video_channel_ == videoChannel);
405 framerate_ = framerate;
406 bitrate_ = bitrate;
407 }
408
wu@webrtc.org78187522013-10-07 23:32:02 +0000409 int framerate() const {
410 talk_base::CritScope cs(&crit_);
411 return framerate_;
412 }
413 int bitrate() const {
414 talk_base::CritScope cs(&crit_);
415 return bitrate_;
416 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000417
418 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000419 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000420 int video_channel_;
421 int framerate_;
422 int bitrate_;
423};
424
425class WebRtcLocalStreamInfo {
426 public:
427 WebRtcLocalStreamInfo()
428 : width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
429 size_t width() const {
430 talk_base::CritScope cs(&crit_);
431 return width_;
432 }
433 size_t height() const {
434 talk_base::CritScope cs(&crit_);
435 return height_;
436 }
437 int64 elapsed_time() const {
438 talk_base::CritScope cs(&crit_);
439 return elapsed_time_;
440 }
441 int64 time_stamp() const {
442 talk_base::CritScope cs(&crit_);
443 return time_stamp_;
444 }
445 int framerate() {
446 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000447 return static_cast<int>(rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000448 }
449 void GetLastFrameInfo(
450 size_t* width, size_t* height, int64* elapsed_time) const {
451 talk_base::CritScope cs(&crit_);
452 *width = width_;
453 *height = height_;
454 *elapsed_time = elapsed_time_;
455 }
456
457 void UpdateFrame(const VideoFrame* frame) {
458 talk_base::CritScope cs(&crit_);
459
460 width_ = frame->GetWidth();
461 height_ = frame->GetHeight();
462 elapsed_time_ = frame->GetElapsedTime();
463 time_stamp_ = frame->GetTimeStamp();
464
465 rate_tracker_.Update(1);
466 }
467
468 private:
469 mutable talk_base::CriticalSection crit_;
470 size_t width_;
471 size_t height_;
472 int64 elapsed_time_;
473 int64 time_stamp_;
474 talk_base::RateTracker rate_tracker_;
475
476 DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
477};
478
479// WebRtcVideoChannelRecvInfo is a container class with members such as renderer
480// and a decoder observer that is used by receive channels.
481// It must exist as long as the receive channel is connected to renderer or a
482// decoder observer in this class and methods in the class should only be called
483// from the worker thread.
484class WebRtcVideoChannelRecvInfo {
485 public:
486 typedef std::map<int, webrtc::VideoDecoder*> DecoderMap; // key: payload type
487 explicit WebRtcVideoChannelRecvInfo(int channel_id)
488 : channel_id_(channel_id),
489 render_adapter_(NULL),
490 decoder_observer_(channel_id) {
491 }
492 int channel_id() { return channel_id_; }
493 void SetRenderer(VideoRenderer* renderer) {
494 render_adapter_.SetRenderer(renderer);
495 }
496 WebRtcRenderAdapter* render_adapter() { return &render_adapter_; }
497 WebRtcDecoderObserver* decoder_observer() { return &decoder_observer_; }
498 void RegisterDecoder(int pl_type, webrtc::VideoDecoder* decoder) {
499 ASSERT(!IsDecoderRegistered(pl_type));
500 registered_decoders_[pl_type] = decoder;
501 }
502 bool IsDecoderRegistered(int pl_type) {
503 return registered_decoders_.count(pl_type) != 0;
504 }
505 const DecoderMap& registered_decoders() {
506 return registered_decoders_;
507 }
508 void ClearRegisteredDecoders() {
509 registered_decoders_.clear();
510 }
511
512 private:
513 int channel_id_; // Webrtc video channel number.
514 // Renderer for this channel.
515 WebRtcRenderAdapter render_adapter_;
516 WebRtcDecoderObserver decoder_observer_;
517 DecoderMap registered_decoders_;
518};
519
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000520class WebRtcOveruseObserver : public webrtc::CpuOveruseObserver {
521 public:
522 explicit WebRtcOveruseObserver(CoordinatedVideoAdapter* video_adapter)
523 : video_adapter_(video_adapter),
524 enabled_(false) {
525 }
526
527 // TODO(mflodman): Consider sending resolution as part of event, to let
528 // adapter know what resolution the request is based on. Helps eliminate stale
529 // data, race conditions.
530 virtual void OveruseDetected() OVERRIDE {
531 talk_base::CritScope cs(&crit_);
532 if (!enabled_) {
533 return;
534 }
535
536 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
537 }
538
539 virtual void NormalUsage() OVERRIDE {
540 talk_base::CritScope cs(&crit_);
541 if (!enabled_) {
542 return;
543 }
544
545 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::UPGRADE);
546 }
547
548 void Enable(bool enable) {
549 talk_base::CritScope cs(&crit_);
550 enabled_ = enable;
551 }
552
553 private:
554 CoordinatedVideoAdapter* video_adapter_;
555 bool enabled_;
556 talk_base::CriticalSection crit_;
557};
558
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000559
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000560class WebRtcVideoChannelSendInfo : public sigslot::has_slots<> {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561 public:
562 typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
563 WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
564 webrtc::ViEExternalCapture* external_capture,
565 talk_base::CpuMonitor* cpu_monitor)
566 : channel_id_(channel_id),
567 capture_id_(capture_id),
568 sending_(false),
569 muted_(false),
570 video_capturer_(NULL),
571 encoder_observer_(channel_id),
572 external_capture_(external_capture),
573 capturer_updated_(false),
574 interval_(0),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000575 video_adapter_(new CoordinatedVideoAdapter),
576 cpu_monitor_(cpu_monitor) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000577 overuse_observer_.reset(new WebRtcOveruseObserver(video_adapter_.get()));
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000578 SignalCpuAdaptationUnable.repeat(video_adapter_->SignalCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000579 if (cpu_monitor) {
580 cpu_monitor->SignalUpdate.connect(
581 video_adapter_.get(), &CoordinatedVideoAdapter::OnCpuLoadUpdated);
582 }
583 }
584
585 int channel_id() const { return channel_id_; }
586 int capture_id() const { return capture_id_; }
587 void set_sending(bool sending) { sending_ = sending; }
588 bool sending() const { return sending_; }
589 void set_muted(bool on) {
590 // TODO(asapersson): add support.
591 // video_adapter_->SetBlackOutput(on);
592 muted_ = on;
593 }
594 bool muted() {return muted_; }
595
596 WebRtcEncoderObserver* encoder_observer() { return &encoder_observer_; }
597 webrtc::ViEExternalCapture* external_capture() { return external_capture_; }
598 const VideoFormat& video_format() const {
599 return video_format_;
600 }
601 void set_video_format(const VideoFormat& video_format) {
602 video_format_ = video_format;
603 if (video_format_ != cricket::VideoFormat()) {
604 interval_ = video_format_.interval;
605 }
606 video_adapter_->OnOutputFormatRequest(video_format_);
607 }
608 void set_interval(int64 interval) {
609 if (video_format() == cricket::VideoFormat()) {
610 interval_ = interval;
611 }
612 }
613 int64 interval() { return interval_; }
614
615 void InitializeAdapterOutputFormat(const webrtc::VideoCodec& codec) {
616 VideoFormat format(codec.width, codec.height,
617 VideoFormat::FpsToInterval(codec.maxFramerate),
618 FOURCC_I420);
619 if (video_adapter_->output_format().IsSize0x0()) {
620 video_adapter_->SetOutputFormat(format);
621 }
622 }
623
624 bool AdaptFrame(const VideoFrame* in_frame, const VideoFrame** out_frame) {
625 *out_frame = NULL;
626 return video_adapter_->AdaptFrame(in_frame, out_frame);
627 }
628 int CurrentAdaptReason() const {
629 return video_adapter_->adapt_reason();
630 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000631 webrtc::CpuOveruseObserver* overuse_observer() {
632 return overuse_observer_.get();
633 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000634
635 StreamParams* stream_params() { return stream_params_.get(); }
636 void set_stream_params(const StreamParams& sp) {
637 stream_params_.reset(new StreamParams(sp));
638 }
639 void ClearStreamParams() { stream_params_.reset(); }
640 bool has_ssrc(uint32 local_ssrc) const {
641 return !stream_params_ ? false :
642 stream_params_->has_ssrc(local_ssrc);
643 }
644 WebRtcLocalStreamInfo* local_stream_info() {
645 return &local_stream_info_;
646 }
647 VideoCapturer* video_capturer() {
648 return video_capturer_;
649 }
650 void set_video_capturer(VideoCapturer* video_capturer) {
651 if (video_capturer == video_capturer_) {
652 return;
653 }
654 capturer_updated_ = true;
655 video_capturer_ = video_capturer;
656 if (video_capturer && !video_capturer->IsScreencast()) {
657 const VideoFormat* capture_format = video_capturer->GetCaptureFormat();
658 if (capture_format) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000659 // TODO(thorcarpenter): This is broken. Video capturer doesn't have
660 // a capture format until the capturer is started. So, if
661 // the capturer is started immediately after calling set_video_capturer
662 // video adapter may not have the input format set, the interval may
663 // be zero, and all frames may be dropped.
664 // Consider fixing this by having video_adapter keep a pointer to the
665 // video capturer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 video_adapter_->SetInputFormat(*capture_format);
667 }
668 }
669 }
670
671 void ApplyCpuOptions(const VideoOptions& options) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000672 bool cpu_adapt, cpu_smoothing, adapt_third;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673 float low, med, high;
674 if (options.adapt_input_to_cpu_usage.Get(&cpu_adapt)) {
675 video_adapter_->set_cpu_adaptation(cpu_adapt);
676 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000677 if (options.adapt_cpu_with_smoothing.Get(&cpu_smoothing)) {
678 video_adapter_->set_cpu_smoothing(cpu_smoothing);
679 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 if (options.process_adaptation_threshhold.Get(&med)) {
681 video_adapter_->set_process_threshold(med);
682 }
683 if (options.system_low_adaptation_threshhold.Get(&low)) {
684 video_adapter_->set_low_system_threshold(low);
685 }
686 if (options.system_high_adaptation_threshhold.Get(&high)) {
687 video_adapter_->set_high_system_threshold(high);
688 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000689 if (options.video_adapt_third.Get(&adapt_third)) {
690 video_adapter_->set_scale_third(adapt_third);
691 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000693
694 void SetCpuOveruseDetection(bool enable) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000695 if (cpu_monitor_ && enable) {
696 cpu_monitor_->SignalUpdate.disconnect(video_adapter_.get());
697 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000698 overuse_observer_->Enable(enable);
699 video_adapter_->set_cpu_adaptation(enable);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000700 }
701
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 void ProcessFrame(const VideoFrame& original_frame, bool mute,
703 VideoFrame** processed_frame) {
704 if (!mute) {
705 *processed_frame = original_frame.Copy();
706 } else {
707 WebRtcVideoFrame* black_frame = new WebRtcVideoFrame();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000708 black_frame->InitToBlack(static_cast<int>(original_frame.GetWidth()),
709 static_cast<int>(original_frame.GetHeight()),
710 1, 1,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711 original_frame.GetElapsedTime(),
712 original_frame.GetTimeStamp());
713 *processed_frame = black_frame;
714 }
715 local_stream_info_.UpdateFrame(*processed_frame);
716 }
717 void RegisterEncoder(int pl_type, webrtc::VideoEncoder* encoder) {
718 ASSERT(!IsEncoderRegistered(pl_type));
719 registered_encoders_[pl_type] = encoder;
720 }
721 bool IsEncoderRegistered(int pl_type) {
722 return registered_encoders_.count(pl_type) != 0;
723 }
724 const EncoderMap& registered_encoders() {
725 return registered_encoders_;
726 }
727 void ClearRegisteredEncoders() {
728 registered_encoders_.clear();
729 }
730
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000731 sigslot::repeater0<> SignalCpuAdaptationUnable;
732
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 private:
734 int channel_id_;
735 int capture_id_;
736 bool sending_;
737 bool muted_;
738 VideoCapturer* video_capturer_;
739 WebRtcEncoderObserver encoder_observer_;
740 webrtc::ViEExternalCapture* external_capture_;
741 EncoderMap registered_encoders_;
742
743 VideoFormat video_format_;
744
745 talk_base::scoped_ptr<StreamParams> stream_params_;
746
747 WebRtcLocalStreamInfo local_stream_info_;
748
749 bool capturer_updated_;
750
751 int64 interval_;
752
753 talk_base::scoped_ptr<CoordinatedVideoAdapter> video_adapter_;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000754 talk_base::CpuMonitor* cpu_monitor_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000755 talk_base::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756};
757
758const WebRtcVideoEngine::VideoCodecPref
759 WebRtcVideoEngine::kVideoCodecPrefs[] = {
760 {kVp8PayloadName, 100, 0},
761 {kRedPayloadName, 116, 1},
762 {kFecPayloadName, 117, 2},
763};
764
765// The formats are sorted by the descending order of width. We use the order to
766// find the next format for CPU and bandwidth adaptation.
767const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
768 {1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
769 {1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
770 {960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
771 {960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
772 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
773 {640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
774 {640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
775 {480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
776 {480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
777 {480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
778 {320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
779 {320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
780 {320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
781 {240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
782 {240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
783 {240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
784 {160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
785 {160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
786 {160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
787};
788
789const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
790 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
791
792static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
793 webrtc::VideoCodec* target_codec) {
794 if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
795 return;
796 }
797 target_codec->width = video_format.width;
798 target_codec->height = video_format.height;
799 target_codec->maxFramerate = cricket::VideoFormat::IntervalToFps(
800 video_format.interval);
801}
802
803WebRtcVideoEngine::WebRtcVideoEngine() {
804 Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
805 new talk_base::CpuMonitor(NULL));
806}
807
808WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
809 ViEWrapper* vie_wrapper,
810 talk_base::CpuMonitor* cpu_monitor) {
811 Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
812}
813
814WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
815 ViEWrapper* vie_wrapper,
816 ViETraceWrapper* tracing,
817 talk_base::CpuMonitor* cpu_monitor) {
818 Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
819}
820
821void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
822 ViETraceWrapper* tracing,
823 WebRtcVoiceEngine* voice_engine,
824 talk_base::CpuMonitor* cpu_monitor) {
825 LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
826 worker_thread_ = NULL;
827 vie_wrapper_.reset(vie_wrapper);
828 vie_wrapper_base_initialized_ = false;
829 tracing_.reset(tracing);
830 voice_engine_ = voice_engine;
831 initialized_ = false;
832 SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
833 render_module_.reset(new WebRtcPassthroughRender());
834 local_renderer_w_ = local_renderer_h_ = 0;
835 local_renderer_ = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000836 capture_started_ = false;
837 decoder_factory_ = NULL;
838 encoder_factory_ = NULL;
839 cpu_monitor_.reset(cpu_monitor);
840
841 SetTraceOptions("");
842 if (tracing_->SetTraceCallback(this) != 0) {
843 LOG_RTCERR1(SetTraceCallback, this);
844 }
845
846 // Set default quality levels for our supported codecs. We override them here
847 // if we know your cpu performance is low, and they can be updated explicitly
848 // by calling SetDefaultCodec. For example by a flute preference setting, or
849 // by the server with a jec in response to our reported system info.
850 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
851 kVideoCodecPrefs[0].name,
852 kDefaultVideoFormat.width,
853 kDefaultVideoFormat.height,
854 VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
855 0);
856 if (!SetDefaultCodec(max_codec)) {
857 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
858 }
859
860
861 // Load our RTP Header extensions.
862 rtp_header_extensions_.push_back(
863 RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
864 kRtpTimeOffsetExtensionId));
865 rtp_header_extensions_.push_back(
866 RtpHeaderExtension(kRtpAbsoluteSendTimeHeaderExtension,
867 kRtpAbsoluteSendTimeExtensionId));
868}
869
870WebRtcVideoEngine::~WebRtcVideoEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000871 LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
872 if (initialized_) {
873 Terminate();
874 }
875 if (encoder_factory_) {
876 encoder_factory_->RemoveObserver(this);
877 }
878 tracing_->SetTraceCallback(NULL);
879 // Test to see if the media processor was deregistered properly.
880 ASSERT(SignalMediaFrame.is_empty());
881}
882
883bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
884 LOG(LS_INFO) << "WebRtcVideoEngine::Init";
885 worker_thread_ = worker_thread;
886 ASSERT(worker_thread_ != NULL);
887
888 cpu_monitor_->set_thread(worker_thread_);
889 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
890 LOG(LS_ERROR) << "Failed to start CPU monitor.";
891 cpu_monitor_.reset();
892 }
893
894 bool result = InitVideoEngine();
895 if (result) {
896 LOG(LS_INFO) << "VideoEngine Init done";
897 } else {
898 LOG(LS_ERROR) << "VideoEngine Init failed, releasing";
899 Terminate();
900 }
901 return result;
902}
903
904bool WebRtcVideoEngine::InitVideoEngine() {
905 LOG(LS_INFO) << "WebRtcVideoEngine::InitVideoEngine";
906
907 // Init WebRTC VideoEngine.
908 if (!vie_wrapper_base_initialized_) {
909 if (vie_wrapper_->base()->Init() != 0) {
910 LOG_RTCERR0(Init);
911 return false;
912 }
913 vie_wrapper_base_initialized_ = true;
914 }
915
916 // Log the VoiceEngine version info.
917 char buffer[1024] = "";
918 if (vie_wrapper_->base()->GetVersion(buffer) != 0) {
919 LOG_RTCERR0(GetVersion);
920 return false;
921 }
922
923 LOG(LS_INFO) << "WebRtc VideoEngine Version:";
924 LogMultiline(talk_base::LS_INFO, buffer);
925
926 // Hook up to VoiceEngine for sync purposes, if supplied.
927 if (!voice_engine_) {
928 LOG(LS_WARNING) << "NULL voice engine";
929 } else if ((vie_wrapper_->base()->SetVoiceEngine(
930 voice_engine_->voe()->engine())) != 0) {
931 LOG_RTCERR0(SetVoiceEngine);
932 return false;
933 }
934
935 // Register our custom render module.
936 if (vie_wrapper_->render()->RegisterVideoRenderModule(
937 *render_module_.get()) != 0) {
938 LOG_RTCERR0(RegisterVideoRenderModule);
939 return false;
940 }
941
942 initialized_ = true;
943 return true;
944}
945
946void WebRtcVideoEngine::Terminate() {
947 LOG(LS_INFO) << "WebRtcVideoEngine::Terminate";
948 initialized_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949
950 if (vie_wrapper_->render()->DeRegisterVideoRenderModule(
951 *render_module_.get()) != 0) {
952 LOG_RTCERR0(DeRegisterVideoRenderModule);
953 }
954
955 if (vie_wrapper_->base()->SetVoiceEngine(NULL) != 0) {
956 LOG_RTCERR0(SetVoiceEngine);
957 }
958
959 cpu_monitor_->Stop();
960}
961
962int WebRtcVideoEngine::GetCapabilities() {
963 return VIDEO_RECV | VIDEO_SEND;
964}
965
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000966bool WebRtcVideoEngine::SetOptions(const VideoOptions &options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 return true;
968}
969
970bool WebRtcVideoEngine::SetDefaultEncoderConfig(
971 const VideoEncoderConfig& config) {
972 return SetDefaultCodec(config.max_codec);
973}
974
wu@webrtc.org78187522013-10-07 23:32:02 +0000975VideoEncoderConfig WebRtcVideoEngine::GetDefaultEncoderConfig() const {
976 ASSERT(!video_codecs_.empty());
977 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
978 kVideoCodecPrefs[0].name,
979 video_codecs_[0].width,
980 video_codecs_[0].height,
981 video_codecs_[0].framerate,
982 0);
983 return VideoEncoderConfig(max_codec);
984}
985
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986// SetDefaultCodec may be called while the capturer is running. For example, a
987// test call is started in a page with QVGA default codec, and then a real call
988// is started in another page with VGA default codec. This is the corner case
989// and happens only when a session is started. We ignore this case currently.
990bool WebRtcVideoEngine::SetDefaultCodec(const VideoCodec& codec) {
991 if (!RebuildCodecList(codec)) {
992 LOG(LS_WARNING) << "Failed to RebuildCodecList";
993 return false;
994 }
995
wu@webrtc.org78187522013-10-07 23:32:02 +0000996 ASSERT(!video_codecs_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 default_codec_format_ = VideoFormat(
998 video_codecs_[0].width,
999 video_codecs_[0].height,
1000 VideoFormat::FpsToInterval(video_codecs_[0].framerate),
1001 FOURCC_ANY);
1002 return true;
1003}
1004
1005WebRtcVideoMediaChannel* WebRtcVideoEngine::CreateChannel(
1006 VoiceMediaChannel* voice_channel) {
1007 WebRtcVideoMediaChannel* channel =
1008 new WebRtcVideoMediaChannel(this, voice_channel);
1009 if (!channel->Init()) {
1010 delete channel;
1011 channel = NULL;
1012 }
1013 return channel;
1014}
1015
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
1017 local_renderer_w_ = local_renderer_h_ = 0;
1018 local_renderer_ = renderer;
1019 return true;
1020}
1021
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
1023 return video_codecs_;
1024}
1025
1026const std::vector<RtpHeaderExtension>&
1027WebRtcVideoEngine::rtp_header_extensions() const {
1028 return rtp_header_extensions_;
1029}
1030
1031void WebRtcVideoEngine::SetLogging(int min_sev, const char* filter) {
1032 // if min_sev == -1, we keep the current log level.
1033 if (min_sev >= 0) {
1034 SetTraceFilter(SeverityToFilter(min_sev));
1035 }
1036 SetTraceOptions(filter);
1037}
1038
1039int WebRtcVideoEngine::GetLastEngineError() {
1040 return vie_wrapper_->error();
1041}
1042
1043// Checks to see whether we comprehend and could receive a particular codec
1044bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
1045 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
1046 const VideoFormat fmt(kVideoFormats[i]);
1047 if ((in.width == 0 && in.height == 0) ||
1048 (fmt.width == in.width && fmt.height == in.height)) {
1049 if (encoder_factory_) {
1050 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1051 encoder_factory_->codecs();
1052 for (size_t j = 0; j < codecs.size(); ++j) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001053 VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054 codecs[j].name, 0, 0, 0, 0);
1055 if (codec.Matches(in))
1056 return true;
1057 }
1058 }
1059 for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
1060 VideoCodec codec(kVideoCodecPrefs[j].payload_type,
1061 kVideoCodecPrefs[j].name, 0, 0, 0, 0);
1062 if (codec.Matches(in)) {
1063 return true;
1064 }
1065 }
1066 }
1067 }
1068 return false;
1069}
1070
1071// Given the requested codec, returns true if we can send that codec type and
1072// updates out with the best quality we could send for that codec. If current is
1073// not empty, we constrain out so that its aspect ratio matches current's.
1074bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
1075 const VideoCodec& current,
1076 VideoCodec* out) {
1077 if (!out) {
1078 return false;
1079 }
1080
1081 std::vector<VideoCodec>::const_iterator local_max;
1082 for (local_max = video_codecs_.begin();
1083 local_max < video_codecs_.end();
1084 ++local_max) {
1085 // First match codecs by payload type
1086 if (!requested.Matches(*local_max)) {
1087 continue;
1088 }
1089
1090 out->id = requested.id;
1091 out->name = requested.name;
1092 out->preference = requested.preference;
1093 out->params = requested.params;
1094 out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
1095 out->width = 0;
1096 out->height = 0;
1097 out->params = requested.params;
1098 out->feedback_params = requested.feedback_params;
1099
1100 if (0 == requested.width && 0 == requested.height) {
1101 // Special case with resolution 0. The channel should not send frames.
1102 return true;
1103 } else if (0 == requested.width || 0 == requested.height) {
1104 // 0xn and nx0 are invalid resolutions.
1105 return false;
1106 }
1107
1108 // Pick the best quality that is within their and our bounds and has the
1109 // correct aspect ratio.
1110 for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
1111 const VideoFormat format(kVideoFormats[j]);
1112
1113 // Skip any format that is larger than the local or remote maximums, or
1114 // smaller than the current best match
1115 if (format.width > requested.width || format.height > requested.height ||
1116 format.width > local_max->width ||
1117 (format.width < out->width && format.height < out->height)) {
1118 continue;
1119 }
1120
1121 bool better = false;
1122
1123 // Check any further constraints on this prospective format
1124 if (!out->width || !out->height) {
1125 // If we don't have any matches yet, this is the best so far.
1126 better = true;
1127 } else if (current.width && current.height) {
1128 // current is set so format must match its ratio exactly.
1129 better =
1130 (format.width * current.height == format.height * current.width);
1131 } else {
1132 // Prefer closer aspect ratios i.e
1133 // format.aspect - requested.aspect < out.aspect - requested.aspect
1134 better = abs(format.width * requested.height * out->height -
1135 requested.width * format.height * out->height) <
1136 abs(out->width * format.height * requested.height -
1137 requested.width * format.height * out->height);
1138 }
1139
1140 if (better) {
1141 out->width = format.width;
1142 out->height = format.height;
1143 }
1144 }
1145 if (out->width > 0) {
1146 return true;
1147 }
1148 }
1149 return false;
1150}
1151
1152static void ConvertToCricketVideoCodec(
1153 const webrtc::VideoCodec& in_codec, VideoCodec* out_codec) {
1154 out_codec->id = in_codec.plType;
1155 out_codec->name = in_codec.plName;
1156 out_codec->width = in_codec.width;
1157 out_codec->height = in_codec.height;
1158 out_codec->framerate = in_codec.maxFramerate;
1159 out_codec->SetParam(kCodecParamMinBitrate, in_codec.minBitrate);
1160 out_codec->SetParam(kCodecParamMaxBitrate, in_codec.maxBitrate);
1161 if (in_codec.qpMax) {
1162 out_codec->SetParam(kCodecParamMaxQuantization, in_codec.qpMax);
1163 }
1164}
1165
1166bool WebRtcVideoEngine::ConvertFromCricketVideoCodec(
1167 const VideoCodec& in_codec, webrtc::VideoCodec* out_codec) {
1168 bool found = false;
1169 int ncodecs = vie_wrapper_->codec()->NumberOfCodecs();
1170 for (int i = 0; i < ncodecs; ++i) {
1171 if (vie_wrapper_->codec()->GetCodec(i, *out_codec) == 0 &&
1172 _stricmp(in_codec.name.c_str(), out_codec->plName) == 0) {
1173 found = true;
1174 break;
1175 }
1176 }
1177
1178 // If not found, check if this is supported by external encoder factory.
1179 if (!found && encoder_factory_) {
1180 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1181 encoder_factory_->codecs();
1182 for (size_t i = 0; i < codecs.size(); ++i) {
1183 if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
1184 out_codec->codecType = codecs[i].type;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001185 out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
1187 codecs[i].name.c_str(), codecs[i].name.length());
1188 found = true;
1189 break;
1190 }
1191 }
1192 }
1193
1194 if (!found) {
1195 LOG(LS_ERROR) << "invalid codec type";
1196 return false;
1197 }
1198
1199 if (in_codec.id != 0)
1200 out_codec->plType = in_codec.id;
1201
1202 if (in_codec.width != 0)
1203 out_codec->width = in_codec.width;
1204
1205 if (in_codec.height != 0)
1206 out_codec->height = in_codec.height;
1207
1208 if (in_codec.framerate != 0)
1209 out_codec->maxFramerate = in_codec.framerate;
1210
1211 // Convert bitrate parameters.
1212 int max_bitrate = kMaxVideoBitrate;
1213 int min_bitrate = kMinVideoBitrate;
1214 int start_bitrate = kStartVideoBitrate;
1215
1216 in_codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
1217 in_codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
1218
1219 if (max_bitrate < min_bitrate) {
1220 return false;
1221 }
1222 start_bitrate = talk_base::_max(start_bitrate, min_bitrate);
1223 start_bitrate = talk_base::_min(start_bitrate, max_bitrate);
1224
1225 out_codec->minBitrate = min_bitrate;
1226 out_codec->startBitrate = start_bitrate;
1227 out_codec->maxBitrate = max_bitrate;
1228
1229 // Convert general codec parameters.
1230 int max_quantization = 0;
1231 if (in_codec.GetParam(kCodecParamMaxQuantization, &max_quantization)) {
1232 if (max_quantization < 0) {
1233 return false;
1234 }
1235 out_codec->qpMax = max_quantization;
1236 }
1237 return true;
1238}
1239
1240void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
1241 talk_base::CritScope cs(&channels_crit_);
1242 channels_.push_back(channel);
1243}
1244
1245void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
1246 talk_base::CritScope cs(&channels_crit_);
1247 channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
1248 channels_.end());
1249}
1250
1251bool WebRtcVideoEngine::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
1252 if (initialized_) {
1253 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
1254 return false;
1255 }
1256 voice_engine_ = voice_engine;
1257 return true;
1258}
1259
1260bool WebRtcVideoEngine::EnableTimedRender() {
1261 if (initialized_) {
1262 LOG(LS_WARNING) << "EnableTimedRender can not be called after Init";
1263 return false;
1264 }
1265 render_module_.reset(webrtc::VideoRender::CreateVideoRender(0, NULL,
1266 false, webrtc::kRenderExternal));
1267 return true;
1268}
1269
1270void WebRtcVideoEngine::SetTraceFilter(int filter) {
1271 tracing_->SetTraceFilter(filter);
1272}
1273
1274// See https://sites.google.com/a/google.com/wavelet/
1275// Home/Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters
1276// for all supported command line setttings.
1277void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
1278 // Set WebRTC trace file.
1279 std::vector<std::string> opts;
1280 talk_base::tokenize(options, ' ', '"', '"', &opts);
1281 std::vector<std::string>::iterator tracefile =
1282 std::find(opts.begin(), opts.end(), "tracefile");
1283 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1284 // Write WebRTC debug output (at same loglevel) to file
1285 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1286 LOG_RTCERR1(SetTraceFile, *tracefile);
1287 }
1288 }
1289}
1290
1291static void AddDefaultFeedbackParams(VideoCodec* codec) {
1292 const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
1293 codec->AddFeedbackParam(kFir);
1294 const FeedbackParam kNack(kRtcpFbParamNack, kParamValueEmpty);
1295 codec->AddFeedbackParam(kNack);
1296 const FeedbackParam kRemb(kRtcpFbParamRemb, kParamValueEmpty);
1297 codec->AddFeedbackParam(kRemb);
1298}
1299
1300// Rebuilds the codec list to be only those that are less intensive
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001301// than the specified codec. Prefers internal codec over external with
1302// higher preference field.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303bool WebRtcVideoEngine::RebuildCodecList(const VideoCodec& in_codec) {
1304 if (!FindCodec(in_codec))
1305 return false;
1306
1307 video_codecs_.clear();
1308
1309 bool found = false;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001310 std::set<std::string> internal_codec_names;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 for (size_t i = 0; i < ARRAY_SIZE(kVideoCodecPrefs); ++i) {
1312 const VideoCodecPref& pref(kVideoCodecPrefs[i]);
1313 if (!found)
1314 found = (in_codec.name == pref.name);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001315 if (found) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 VideoCodec codec(pref.payload_type, pref.name,
1317 in_codec.width, in_codec.height, in_codec.framerate,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001318 static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319 if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
1320 AddDefaultFeedbackParams(&codec);
1321 }
1322 video_codecs_.push_back(codec);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001323 internal_codec_names.insert(codec.name);
1324 }
1325 }
1326 if (encoder_factory_) {
1327 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1328 encoder_factory_->codecs();
1329 for (size_t i = 0; i < codecs.size(); ++i) {
1330 bool is_internal_codec = internal_codec_names.find(codecs[i].name) !=
1331 internal_codec_names.end();
1332 if (!is_internal_codec) {
1333 if (!found)
1334 found = (in_codec.name == codecs[i].name);
1335 VideoCodec codec(
1336 GetExternalVideoPayloadType(static_cast<int>(i)),
1337 codecs[i].name,
1338 codecs[i].max_width,
1339 codecs[i].max_height,
1340 codecs[i].max_fps,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001341 // Use negative preference on external codec to ensure the internal
1342 // codec is preferred.
1343 static_cast<int>(0 - i));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001344 AddDefaultFeedbackParams(&codec);
1345 video_codecs_.push_back(codec);
1346 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 }
1348 }
1349 ASSERT(found);
1350 return true;
1351}
1352
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353// Ignore spammy trace messages, mostly from the stats API when we haven't
1354// gotten RTCP info yet from the remote side.
1355bool WebRtcVideoEngine::ShouldIgnoreTrace(const std::string& trace) {
1356 static const char* const kTracesToIgnore[] = {
1357 NULL
1358 };
1359 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1360 if (trace.find(*p) == 0) {
1361 return true;
1362 }
1363 }
1364 return false;
1365}
1366
1367int WebRtcVideoEngine::GetNumOfChannels() {
1368 talk_base::CritScope cs(&channels_crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001369 return static_cast<int>(channels_.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
1372void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
1373 int length) {
1374 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1375 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1376 sev = talk_base::LS_ERROR;
1377 else if (level == webrtc::kTraceWarning)
1378 sev = talk_base::LS_WARNING;
1379 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1380 sev = talk_base::LS_INFO;
1381 else if (level == webrtc::kTraceTerseInfo)
1382 sev = talk_base::LS_INFO;
1383
1384 // Skip past boilerplate prefix text
1385 if (length < 72) {
1386 std::string msg(trace, length);
1387 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1388 LOG_V(sev) << msg;
1389 } else {
1390 std::string msg(trace + 71, length - 72);
1391 if (!ShouldIgnoreTrace(msg) &&
1392 (!voice_engine_ || !voice_engine_->ShouldIgnoreTrace(msg))) {
1393 LOG_V(sev) << "webrtc: " << msg;
1394 }
1395 }
1396}
1397
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
1399 webrtc::VideoCodecType type) {
1400 if (decoder_factory_ == NULL) {
1401 return NULL;
1402 }
1403 return decoder_factory_->CreateVideoDecoder(type);
1404}
1405
1406void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
1407 ASSERT(decoder_factory_ != NULL);
1408 if (decoder_factory_ == NULL)
1409 return;
1410 decoder_factory_->DestroyVideoDecoder(decoder);
1411}
1412
1413webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
1414 webrtc::VideoCodecType type) {
1415 if (encoder_factory_ == NULL) {
1416 return NULL;
1417 }
1418 return encoder_factory_->CreateVideoEncoder(type);
1419}
1420
1421void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
1422 ASSERT(encoder_factory_ != NULL);
1423 if (encoder_factory_ == NULL)
1424 return;
1425 encoder_factory_->DestroyVideoEncoder(encoder);
1426}
1427
1428bool WebRtcVideoEngine::IsExternalEncoderCodecType(
1429 webrtc::VideoCodecType type) const {
1430 if (!encoder_factory_)
1431 return false;
1432 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1433 encoder_factory_->codecs();
1434 std::vector<WebRtcVideoEncoderFactory::VideoCodec>::const_iterator it;
1435 for (it = codecs.begin(); it != codecs.end(); ++it) {
1436 if (it->type == type)
1437 return true;
1438 }
1439 return false;
1440}
1441
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442void WebRtcVideoEngine::SetExternalDecoderFactory(
1443 WebRtcVideoDecoderFactory* decoder_factory) {
1444 decoder_factory_ = decoder_factory;
1445}
1446
1447void WebRtcVideoEngine::SetExternalEncoderFactory(
1448 WebRtcVideoEncoderFactory* encoder_factory) {
1449 if (encoder_factory_ == encoder_factory)
1450 return;
1451
1452 if (encoder_factory_) {
1453 encoder_factory_->RemoveObserver(this);
1454 }
1455 encoder_factory_ = encoder_factory;
1456 if (encoder_factory_) {
1457 encoder_factory_->AddObserver(this);
1458 }
1459
1460 // Invoke OnCodecAvailable() here in case the list of codecs is already
1461 // available when the encoder factory is installed. If not the encoder
1462 // factory will invoke the callback later when the codecs become available.
1463 OnCodecsAvailable();
1464}
1465
1466void WebRtcVideoEngine::OnCodecsAvailable() {
1467 // Rebuild codec list while reapplying the current default codec format.
1468 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1469 kVideoCodecPrefs[0].name,
1470 video_codecs_[0].width,
1471 video_codecs_[0].height,
1472 video_codecs_[0].framerate,
1473 0);
1474 if (!RebuildCodecList(max_codec)) {
1475 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
1476 }
1477}
1478
1479// WebRtcVideoMediaChannel
1480
1481WebRtcVideoMediaChannel::WebRtcVideoMediaChannel(
1482 WebRtcVideoEngine* engine,
1483 VoiceMediaChannel* channel)
1484 : engine_(engine),
1485 voice_channel_(channel),
1486 vie_channel_(-1),
1487 nack_enabled_(true),
1488 remb_enabled_(false),
1489 render_started_(false),
1490 first_receive_ssrc_(0),
1491 send_red_type_(-1),
1492 send_fec_type_(-1),
1493 send_min_bitrate_(kMinVideoBitrate),
1494 send_start_bitrate_(kStartVideoBitrate),
1495 send_max_bitrate_(kMaxVideoBitrate),
1496 sending_(false),
1497 ratio_w_(0),
1498 ratio_h_(0) {
1499 engine->RegisterChannel(this);
1500}
1501
1502bool WebRtcVideoMediaChannel::Init() {
1503 const uint32 ssrc_key = 0;
1504 return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
1505}
1506
1507WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
1508 const bool send = false;
1509 SetSend(send);
1510 const bool render = false;
1511 SetRender(render);
1512
1513 while (!send_channels_.empty()) {
1514 if (!DeleteSendChannel(send_channels_.begin()->first)) {
1515 LOG(LS_ERROR) << "Unable to delete channel with ssrc key "
1516 << send_channels_.begin()->first;
1517 ASSERT(false);
1518 break;
1519 }
1520 }
1521
1522 // Remove all receive streams and the default channel.
1523 while (!recv_channels_.empty()) {
1524 RemoveRecvStream(recv_channels_.begin()->first);
1525 }
1526
1527 // Unregister the channel from the engine.
1528 engine()->UnregisterChannel(this);
1529 if (worker_thread()) {
1530 worker_thread()->Clear(this);
1531 }
1532}
1533
1534bool WebRtcVideoMediaChannel::SetRecvCodecs(
1535 const std::vector<VideoCodec>& codecs) {
1536 receive_codecs_.clear();
1537 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1538 iter != codecs.end(); ++iter) {
1539 if (engine()->FindCodec(*iter)) {
1540 webrtc::VideoCodec wcodec;
1541 if (engine()->ConvertFromCricketVideoCodec(*iter, &wcodec)) {
1542 receive_codecs_.push_back(wcodec);
1543 }
1544 } else {
1545 LOG(LS_INFO) << "Unknown codec " << iter->name;
1546 return false;
1547 }
1548 }
1549
1550 for (RecvChannelMap::iterator it = recv_channels_.begin();
1551 it != recv_channels_.end(); ++it) {
1552 if (!SetReceiveCodecs(it->second))
1553 return false;
1554 }
1555 return true;
1556}
1557
1558bool WebRtcVideoMediaChannel::SetSendCodecs(
1559 const std::vector<VideoCodec>& codecs) {
1560 // Match with local video codec list.
1561 std::vector<webrtc::VideoCodec> send_codecs;
1562 VideoCodec checked_codec;
1563 VideoCodec current; // defaults to 0x0
1564 if (sending_) {
1565 ConvertToCricketVideoCodec(*send_codec_, &current);
1566 }
1567 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1568 iter != codecs.end(); ++iter) {
1569 if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
1570 send_red_type_ = iter->id;
1571 } else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
1572 send_fec_type_ = iter->id;
1573 } else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
1574 webrtc::VideoCodec wcodec;
1575 if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
1576 if (send_codecs.empty()) {
1577 nack_enabled_ = IsNackEnabled(checked_codec);
1578 remb_enabled_ = IsRembEnabled(checked_codec);
1579 }
1580 send_codecs.push_back(wcodec);
1581 }
1582 } else {
1583 LOG(LS_WARNING) << "Unknown codec " << iter->name;
1584 }
1585 }
1586
1587 // Fail if we don't have a match.
1588 if (send_codecs.empty()) {
1589 LOG(LS_WARNING) << "No matching codecs available";
1590 return false;
1591 }
1592
1593 // Recv protection.
1594 for (RecvChannelMap::iterator it = recv_channels_.begin();
1595 it != recv_channels_.end(); ++it) {
1596 int channel_id = it->second->channel_id();
1597 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1598 nack_enabled_)) {
1599 return false;
1600 }
1601 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1602 kNotSending,
1603 remb_enabled_) != 0) {
1604 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
1605 return false;
1606 }
1607 }
1608
1609 // Send settings.
1610 for (SendChannelMap::iterator iter = send_channels_.begin();
1611 iter != send_channels_.end(); ++iter) {
1612 int channel_id = iter->second->channel_id();
1613 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1614 nack_enabled_)) {
1615 return false;
1616 }
1617 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1618 remb_enabled_,
1619 remb_enabled_) != 0) {
1620 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
1621 return false;
1622 }
1623 }
1624
1625 // Select the first matched codec.
1626 webrtc::VideoCodec& codec(send_codecs[0]);
1627
1628 if (!SetSendCodec(
1629 codec, codec.minBitrate, codec.startBitrate, codec.maxBitrate)) {
1630 return false;
1631 }
1632
1633 for (SendChannelMap::iterator iter = send_channels_.begin();
1634 iter != send_channels_.end(); ++iter) {
1635 WebRtcVideoChannelSendInfo* send_channel = iter->second;
1636 send_channel->InitializeAdapterOutputFormat(codec);
1637 }
1638
1639 LogSendCodecChange("SetSendCodecs()");
1640
1641 return true;
1642}
1643
1644bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
1645 if (!send_codec_) {
1646 return false;
1647 }
1648 ConvertToCricketVideoCodec(*send_codec_, send_codec);
1649 return true;
1650}
1651
1652bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
1653 const VideoFormat& format) {
1654 if (!send_codec_) {
1655 LOG(LS_ERROR) << "The send codec has not been set yet.";
1656 return false;
1657 }
1658 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
1659 if (!send_channel) {
1660 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
1661 return false;
1662 }
1663 send_channel->set_video_format(format);
1664 return true;
1665}
1666
1667bool WebRtcVideoMediaChannel::SetRender(bool render) {
1668 if (render == render_started_) {
1669 return true; // no action required
1670 }
1671
1672 bool ret = true;
1673 for (RecvChannelMap::iterator it = recv_channels_.begin();
1674 it != recv_channels_.end(); ++it) {
1675 if (render) {
1676 if (engine()->vie()->render()->StartRender(
1677 it->second->channel_id()) != 0) {
1678 LOG_RTCERR1(StartRender, it->second->channel_id());
1679 ret = false;
1680 }
1681 } else {
1682 if (engine()->vie()->render()->StopRender(
1683 it->second->channel_id()) != 0) {
1684 LOG_RTCERR1(StopRender, it->second->channel_id());
1685 ret = false;
1686 }
1687 }
1688 }
1689 if (ret) {
1690 render_started_ = render;
1691 }
1692
1693 return ret;
1694}
1695
1696bool WebRtcVideoMediaChannel::SetSend(bool send) {
1697 if (!HasReadySendChannels() && send) {
1698 LOG(LS_ERROR) << "No stream added";
1699 return false;
1700 }
1701 if (send == sending()) {
1702 return true; // No action required.
1703 }
1704
1705 if (send) {
1706 // We've been asked to start sending.
1707 // SetSendCodecs must have been called already.
1708 if (!send_codec_) {
1709 return false;
1710 }
1711 // Start send now.
1712 if (!StartSend()) {
1713 return false;
1714 }
1715 } else {
1716 // We've been asked to stop sending.
1717 if (!StopSend()) {
1718 return false;
1719 }
1720 }
1721 sending_ = send;
1722
1723 return true;
1724}
1725
1726bool WebRtcVideoMediaChannel::AddSendStream(const StreamParams& sp) {
1727 LOG(LS_INFO) << "AddSendStream " << sp.ToString();
1728
1729 if (!IsOneSsrcStream(sp)) {
1730 LOG(LS_ERROR) << "AddSendStream: bad local stream parameters";
1731 return false;
1732 }
1733
1734 uint32 ssrc_key;
1735 if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
1736 LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
1737 return false;
1738 }
1739 // If the default channel is already used for sending create a new channel
1740 // otherwise use the default channel for sending.
1741 int channel_id = -1;
1742 if (send_channels_[0]->stream_params() == NULL) {
1743 channel_id = vie_channel_;
1744 } else {
1745 if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
1746 LOG(LS_ERROR) << "AddSendStream: unable to create channel";
1747 return false;
1748 }
1749 }
1750 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1751 // Set the send (local) SSRC.
1752 // If there are multiple send SSRCs, we can only set the first one here, and
1753 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
1754 // (with a codec requires multiple SSRC(s)).
1755 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1756 sp.first_ssrc()) != 0) {
1757 LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
1758 return false;
1759 }
1760
1761 // Set RTCP CName.
1762 if (engine()->vie()->rtp()->SetRTCPCName(channel_id,
1763 sp.cname.c_str()) != 0) {
1764 LOG_RTCERR2(SetRTCPCName, channel_id, sp.cname.c_str());
1765 return false;
1766 }
1767
1768 // At this point the channel's local SSRC has been updated. If the channel is
1769 // the default channel make sure that all the receive channels are updated as
1770 // well. Receive channels have to have the same SSRC as the default channel in
1771 // order to send receiver reports with this SSRC.
1772 if (IsDefaultChannel(channel_id)) {
1773 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
1774 it != recv_channels_.end(); ++it) {
1775 WebRtcVideoChannelRecvInfo* info = it->second;
1776 int channel_id = info->channel_id();
1777 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1778 sp.first_ssrc()) != 0) {
1779 LOG_RTCERR1(SetLocalSSRC, it->first);
1780 return false;
1781 }
1782 }
1783 }
1784
1785 send_channel->set_stream_params(sp);
1786
1787 // Reset send codec after stream parameters changed.
1788 if (send_codec_) {
1789 if (!SetSendCodec(send_channel, *send_codec_, send_min_bitrate_,
1790 send_start_bitrate_, send_max_bitrate_)) {
1791 return false;
1792 }
1793 LogSendCodecChange("SetSendStreamFormat()");
1794 }
1795
1796 if (sending_) {
1797 return StartSend(send_channel);
1798 }
1799 return true;
1800}
1801
1802bool WebRtcVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
1803 uint32 ssrc_key;
1804 if (!GetSendChannelKey(ssrc, &ssrc_key)) {
1805 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1806 << " which doesn't exist.";
1807 return false;
1808 }
1809 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1810 int channel_id = send_channel->channel_id();
1811 if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
1812 // Default channel will still exist. However, if stream_params() is NULL
1813 // there is no stream to remove.
1814 return false;
1815 }
1816 if (sending_) {
1817 StopSend(send_channel);
1818 }
1819
1820 const WebRtcVideoChannelSendInfo::EncoderMap& encoder_map =
1821 send_channel->registered_encoders();
1822 for (WebRtcVideoChannelSendInfo::EncoderMap::const_iterator it =
1823 encoder_map.begin(); it != encoder_map.end(); ++it) {
1824 if (engine()->vie()->ext_codec()->DeRegisterExternalSendCodec(
1825 channel_id, it->first) != 0) {
1826 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
1827 }
1828 engine()->DestroyExternalEncoder(it->second);
1829 }
1830 send_channel->ClearRegisteredEncoders();
1831
1832 // The receive channels depend on the default channel, recycle it instead.
1833 if (IsDefaultChannel(channel_id)) {
1834 SetCapturer(GetDefaultChannelSsrc(), NULL);
1835 send_channel->ClearStreamParams();
1836 } else {
1837 return DeleteSendChannel(ssrc_key);
1838 }
1839 return true;
1840}
1841
1842bool WebRtcVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
1843 // TODO(zhurunz) Remove this once BWE works properly across different send
1844 // and receive channels.
1845 // Reuse default channel for recv stream in 1:1 call.
1846 if (!InConferenceMode() && first_receive_ssrc_ == 0) {
1847 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
1848 << " reuse default channel #"
1849 << vie_channel_;
1850 first_receive_ssrc_ = sp.first_ssrc();
1851 if (render_started_) {
1852 if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
1853 LOG_RTCERR1(StartRender, vie_channel_);
1854 }
1855 }
1856 return true;
1857 }
1858
1859 if (recv_channels_.find(sp.first_ssrc()) != recv_channels_.end() ||
1860 first_receive_ssrc_ == sp.first_ssrc()) {
1861 LOG(LS_ERROR) << "Stream already exists";
1862 return false;
1863 }
1864
1865 // TODO(perkj): Implement recv media from multiple SSRCs per stream.
1866 if (sp.ssrcs.size() != 1) {
1867 LOG(LS_ERROR) << "WebRtcVideoMediaChannel supports one receiving SSRC per"
1868 << " stream";
1869 return false;
1870 }
1871
1872 // Create a new channel for receiving video data.
1873 // In order to get the bandwidth estimation work fine for
1874 // receive only channels, we connect all receiving channels
1875 // to our master send channel.
1876 int channel_id = -1;
1877 if (!CreateChannel(sp.first_ssrc(), MD_RECV, &channel_id)) {
1878 return false;
1879 }
1880
1881 // Get the default renderer.
1882 VideoRenderer* default_renderer = NULL;
1883 if (InConferenceMode()) {
1884 // The recv_channels_ size start out being 1, so if it is two here this
1885 // is the first receive channel created (vie_channel_ is not used for
1886 // receiving in a conference call). This means that the renderer stored
1887 // inside vie_channel_ should be used for the just created channel.
1888 if (recv_channels_.size() == 2 &&
1889 recv_channels_.find(0) != recv_channels_.end()) {
1890 GetRenderer(0, &default_renderer);
1891 }
1892 }
1893
1894 // The first recv stream reuses the default renderer (if a default renderer
1895 // has been set).
1896 if (default_renderer) {
1897 SetRenderer(sp.first_ssrc(), default_renderer);
1898 }
1899
1900 LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
1901 << " registered to VideoEngine channel #"
1902 << channel_id << " and connected to channel #" << vie_channel_;
1903
1904 return true;
1905}
1906
1907bool WebRtcVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
1908 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
1909
1910 if (it == recv_channels_.end()) {
1911 // TODO(perkj): Remove this once BWE works properly across different send
1912 // and receive channels.
1913 // The default channel is reused for recv stream in 1:1 call.
1914 if (first_receive_ssrc_ == ssrc) {
1915 first_receive_ssrc_ = 0;
1916 // Need to stop the renderer and remove it since the render window can be
1917 // deleted after this.
1918 if (render_started_) {
1919 if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
1920 LOG_RTCERR1(StopRender, it->second->channel_id());
1921 }
1922 }
1923 recv_channels_[0]->SetRenderer(NULL);
1924 return true;
1925 }
1926 return false;
1927 }
1928 WebRtcVideoChannelRecvInfo* info = it->second;
1929 int channel_id = info->channel_id();
1930 if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
1931 LOG_RTCERR1(RemoveRenderer, channel_id);
1932 }
1933
1934 if (engine()->vie()->network()->DeregisterSendTransport(channel_id) !=0) {
1935 LOG_RTCERR1(DeRegisterSendTransport, channel_id);
1936 }
1937
1938 if (engine()->vie()->codec()->DeregisterDecoderObserver(
1939 channel_id) != 0) {
1940 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
1941 }
1942
1943 const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
1944 info->registered_decoders();
1945 for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
1946 decoder_map.begin(); it != decoder_map.end(); ++it) {
1947 if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
1948 channel_id, it->first) != 0) {
1949 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
1950 }
1951 engine()->DestroyExternalDecoder(it->second);
1952 }
1953 info->ClearRegisteredDecoders();
1954
1955 LOG(LS_INFO) << "Removing video stream " << ssrc
1956 << " with VideoEngine channel #"
1957 << channel_id;
1958 if (engine()->vie()->base()->DeleteChannel(channel_id) == -1) {
1959 LOG_RTCERR1(DeleteChannel, channel_id);
1960 // Leak the WebRtcVideoChannelRecvInfo owned by |it| but remove the channel
1961 // from recv_channels_.
1962 recv_channels_.erase(it);
1963 return false;
1964 }
1965 // Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
1966 delete info;
1967 recv_channels_.erase(it);
1968 return true;
1969}
1970
1971bool WebRtcVideoMediaChannel::StartSend() {
1972 bool success = true;
1973 for (SendChannelMap::iterator iter = send_channels_.begin();
1974 iter != send_channels_.end(); ++iter) {
1975 WebRtcVideoChannelSendInfo* send_channel = iter->second;
1976 if (!StartSend(send_channel)) {
1977 success = false;
1978 }
1979 }
1980 return success;
1981}
1982
1983bool WebRtcVideoMediaChannel::StartSend(
1984 WebRtcVideoChannelSendInfo* send_channel) {
1985 const int channel_id = send_channel->channel_id();
1986 if (engine()->vie()->base()->StartSend(channel_id) != 0) {
1987 LOG_RTCERR1(StartSend, channel_id);
1988 return false;
1989 }
1990
1991 send_channel->set_sending(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 return true;
1993}
1994
1995bool WebRtcVideoMediaChannel::StopSend() {
1996 bool success = true;
1997 for (SendChannelMap::iterator iter = send_channels_.begin();
1998 iter != send_channels_.end(); ++iter) {
1999 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2000 if (!StopSend(send_channel)) {
2001 success = false;
2002 }
2003 }
2004 return success;
2005}
2006
2007bool WebRtcVideoMediaChannel::StopSend(
2008 WebRtcVideoChannelSendInfo* send_channel) {
2009 const int channel_id = send_channel->channel_id();
2010 if (engine()->vie()->base()->StopSend(channel_id) != 0) {
2011 LOG_RTCERR1(StopSend, channel_id);
2012 return false;
2013 }
2014 send_channel->set_sending(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 return true;
2016}
2017
2018bool WebRtcVideoMediaChannel::SendIntraFrame() {
2019 bool success = true;
2020 for (SendChannelMap::iterator iter = send_channels_.begin();
2021 iter != send_channels_.end();
2022 ++iter) {
2023 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2024 const int channel_id = send_channel->channel_id();
2025 if (engine()->vie()->codec()->SendKeyFrame(channel_id) != 0) {
2026 LOG_RTCERR1(SendKeyFrame, channel_id);
2027 success = false;
2028 }
2029 }
2030 return success;
2031}
2032
2033bool WebRtcVideoMediaChannel::IsOneSsrcStream(const StreamParams& sp) {
2034 return (sp.ssrcs.size() == 1 && sp.ssrc_groups.size() == 0);
2035}
2036
2037bool WebRtcVideoMediaChannel::HasReadySendChannels() {
2038 return !send_channels_.empty() &&
2039 ((send_channels_.size() > 1) ||
2040 (send_channels_[0]->stream_params() != NULL));
2041}
2042
2043bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
2044 uint32* key) {
2045 *key = 0;
2046 // If a send channel is not ready to send it will not have local_ssrc
2047 // registered to it.
2048 if (!HasReadySendChannels()) {
2049 return false;
2050 }
2051 // The default channel is stored with key 0. The key therefore does not match
2052 // the SSRC associated with the default channel. Check if the SSRC provided
2053 // corresponds to the default channel's SSRC.
2054 if (local_ssrc == GetDefaultChannelSsrc()) {
2055 return true;
2056 }
2057 if (send_channels_.find(local_ssrc) == send_channels_.end()) {
2058 for (SendChannelMap::iterator iter = send_channels_.begin();
2059 iter != send_channels_.end(); ++iter) {
2060 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2061 if (send_channel->has_ssrc(local_ssrc)) {
2062 *key = iter->first;
2063 return true;
2064 }
2065 }
2066 return false;
2067 }
2068 // The key was found in the above std::map::find call. This means that the
2069 // ssrc is the key.
2070 *key = local_ssrc;
2071 return true;
2072}
2073
2074WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
2075 VideoCapturer* video_capturer) {
2076 for (SendChannelMap::iterator iter = send_channels_.begin();
2077 iter != send_channels_.end(); ++iter) {
2078 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2079 if (send_channel->video_capturer() == video_capturer) {
2080 return send_channel;
2081 }
2082 }
2083 return NULL;
2084}
2085
2086WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
2087 uint32 local_ssrc) {
2088 uint32 key;
2089 if (!GetSendChannelKey(local_ssrc, &key)) {
2090 return NULL;
2091 }
2092 return send_channels_[key];
2093}
2094
2095bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
2096 uint32* key) {
2097 if (GetSendChannelKey(local_ssrc, key)) {
2098 // If there is a key corresponding to |local_ssrc|, the SSRC is already in
2099 // use. SSRCs need to be unique in a session and at this point a duplicate
2100 // SSRC has been detected.
2101 return false;
2102 }
2103 if (send_channels_[0]->stream_params() == NULL) {
2104 // key should be 0 here as the default channel should be re-used whenever it
2105 // is not used.
2106 *key = 0;
2107 return true;
2108 }
2109 // SSRC is currently not in use and the default channel is already in use. Use
2110 // the SSRC as key since it is supposed to be unique in a session.
2111 *key = local_ssrc;
2112 return true;
2113}
2114
2115uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
2116 WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
2117 const StreamParams* sp = send_channel->stream_params();
2118 if (sp == NULL) {
2119 // This happens if no send stream is currently registered.
2120 return 0;
2121 }
2122 return sp->first_ssrc();
2123}
2124
2125bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
2126 if (send_channels_.find(ssrc_key) == send_channels_.end()) {
2127 return false;
2128 }
2129 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
2130 VideoCapturer* capturer = send_channel->video_capturer();
2131 if (capturer != NULL) {
2132 capturer->SignalVideoFrame.disconnect(this);
2133 send_channel->set_video_capturer(NULL);
2134 }
2135
2136 int channel_id = send_channel->channel_id();
2137 int capture_id = send_channel->capture_id();
2138 if (engine()->vie()->codec()->DeregisterEncoderObserver(
2139 channel_id) != 0) {
2140 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
2141 }
2142
2143 // Destroy the external capture interface.
2144 if (engine()->vie()->capture()->DisconnectCaptureDevice(
2145 channel_id) != 0) {
2146 LOG_RTCERR1(DisconnectCaptureDevice, channel_id);
2147 }
2148 if (engine()->vie()->capture()->ReleaseCaptureDevice(
2149 capture_id) != 0) {
2150 LOG_RTCERR1(ReleaseCaptureDevice, capture_id);
2151 }
2152
2153 // The default channel is stored in both |send_channels_| and
2154 // |recv_channels_|. To make sure it is only deleted once from vie let the
2155 // delete call happen when tearing down |recv_channels_| and not here.
2156 if (!IsDefaultChannel(channel_id)) {
2157 engine_->vie()->base()->DeleteChannel(channel_id);
2158 }
2159 delete send_channel;
2160 send_channels_.erase(ssrc_key);
2161 return true;
2162}
2163
2164bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
2165 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2166 if (!send_channel) {
2167 return false;
2168 }
2169 VideoCapturer* capturer = send_channel->video_capturer();
2170 if (capturer == NULL) {
2171 return false;
2172 }
2173 capturer->SignalVideoFrame.disconnect(this);
2174 send_channel->set_video_capturer(NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002175 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2176 if (send_codec_) {
2177 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2178 }
2179 return true;
2180}
2181
2182bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
2183 VideoRenderer* renderer) {
2184 if (recv_channels_.find(ssrc) == recv_channels_.end()) {
2185 // TODO(perkj): Remove this once BWE works properly across different send
2186 // and receive channels.
2187 // The default channel is reused for recv stream in 1:1 call.
2188 if (first_receive_ssrc_ == ssrc &&
2189 recv_channels_.find(0) != recv_channels_.end()) {
2190 LOG(LS_INFO) << "SetRenderer " << ssrc
2191 << " reuse default channel #"
2192 << vie_channel_;
2193 recv_channels_[0]->SetRenderer(renderer);
2194 return true;
2195 }
2196 return false;
2197 }
2198
2199 recv_channels_[ssrc]->SetRenderer(renderer);
2200 return true;
2201}
2202
2203bool WebRtcVideoMediaChannel::GetStats(VideoMediaInfo* info) {
2204 // Get sender statistics and build VideoSenderInfo.
2205 unsigned int total_bitrate_sent = 0;
2206 unsigned int video_bitrate_sent = 0;
2207 unsigned int fec_bitrate_sent = 0;
2208 unsigned int nack_bitrate_sent = 0;
2209 unsigned int estimated_send_bandwidth = 0;
2210 unsigned int target_enc_bitrate = 0;
2211 if (send_codec_) {
2212 for (SendChannelMap::const_iterator iter = send_channels_.begin();
2213 iter != send_channels_.end(); ++iter) {
2214 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2215 const int channel_id = send_channel->channel_id();
2216 VideoSenderInfo sinfo;
2217 const StreamParams* send_params = send_channel->stream_params();
2218 if (send_params == NULL) {
2219 // This should only happen if the default vie channel is not in use.
2220 // This can happen if no streams have ever been added or the stream
2221 // corresponding to the default channel has been removed. Note that
2222 // there may be non-default vie channels in use when this happen so
2223 // asserting send_channels_.size() == 1 is not correct and neither is
2224 // breaking out of the loop.
2225 ASSERT(channel_id == vie_channel_);
2226 continue;
2227 }
2228 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2229 if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
2230 packets_sent, bytes_recv,
2231 packets_recv) != 0) {
2232 LOG_RTCERR1(GetRTPStatistics, vie_channel_);
2233 continue;
2234 }
2235 WebRtcLocalStreamInfo* channel_stream_info =
2236 send_channel->local_stream_info();
2237
2238 sinfo.ssrcs = send_params->ssrcs;
2239 sinfo.codec_name = send_codec_->plName;
2240 sinfo.bytes_sent = bytes_sent;
2241 sinfo.packets_sent = packets_sent;
2242 sinfo.packets_cached = -1;
2243 sinfo.packets_lost = -1;
2244 sinfo.fraction_lost = -1;
2245 sinfo.firs_rcvd = -1;
2246 sinfo.nacks_rcvd = -1;
2247 sinfo.rtt_ms = -1;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002248 sinfo.frame_width = static_cast<int>(channel_stream_info->width());
2249 sinfo.frame_height = static_cast<int>(channel_stream_info->height());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 sinfo.framerate_input = channel_stream_info->framerate();
2251 sinfo.framerate_sent = send_channel->encoder_observer()->framerate();
2252 sinfo.nominal_bitrate = send_channel->encoder_observer()->bitrate();
2253 sinfo.preferred_bitrate = send_max_bitrate_;
2254 sinfo.adapt_reason = send_channel->CurrentAdaptReason();
2255
2256 // Get received RTCP statistics for the sender, if available.
2257 // It's not a fatal error if we can't, since RTCP may not have arrived
2258 // yet.
2259 uint16 r_fraction_lost;
2260 unsigned int r_cumulative_lost;
2261 unsigned int r_extended_max;
2262 unsigned int r_jitter;
2263 int r_rtt_ms;
2264
2265 if (engine_->vie()->rtp()->GetSentRTCPStatistics(
2266 channel_id,
2267 r_fraction_lost,
2268 r_cumulative_lost,
2269 r_extended_max,
2270 r_jitter, r_rtt_ms) == 0) {
2271 // Convert Q8 to float.
2272 sinfo.packets_lost = r_cumulative_lost;
2273 sinfo.fraction_lost = static_cast<float>(r_fraction_lost) / (1 << 8);
2274 sinfo.rtt_ms = r_rtt_ms;
2275 }
2276 info->senders.push_back(sinfo);
2277
2278 unsigned int channel_total_bitrate_sent = 0;
2279 unsigned int channel_video_bitrate_sent = 0;
2280 unsigned int channel_fec_bitrate_sent = 0;
2281 unsigned int channel_nack_bitrate_sent = 0;
2282 if (engine_->vie()->rtp()->GetBandwidthUsage(
2283 channel_id, channel_total_bitrate_sent, channel_video_bitrate_sent,
2284 channel_fec_bitrate_sent, channel_nack_bitrate_sent) == 0) {
2285 total_bitrate_sent += channel_total_bitrate_sent;
2286 video_bitrate_sent += channel_video_bitrate_sent;
2287 fec_bitrate_sent += channel_fec_bitrate_sent;
2288 nack_bitrate_sent += channel_nack_bitrate_sent;
2289 } else {
2290 LOG_RTCERR1(GetBandwidthUsage, channel_id);
2291 }
2292
2293 unsigned int estimated_stream_send_bandwidth = 0;
2294 if (engine_->vie()->rtp()->GetEstimatedSendBandwidth(
2295 channel_id, &estimated_stream_send_bandwidth) == 0) {
2296 estimated_send_bandwidth += estimated_stream_send_bandwidth;
2297 } else {
2298 LOG_RTCERR1(GetEstimatedSendBandwidth, channel_id);
2299 }
2300 unsigned int target_enc_stream_bitrate = 0;
2301 if (engine_->vie()->codec()->GetCodecTargetBitrate(
2302 channel_id, &target_enc_stream_bitrate) == 0) {
2303 target_enc_bitrate += target_enc_stream_bitrate;
2304 } else {
2305 LOG_RTCERR1(GetCodecTargetBitrate, channel_id);
2306 }
2307 }
2308 } else {
2309 LOG(LS_WARNING) << "GetStats: sender information not ready.";
2310 }
2311
2312 // Get the SSRC and stats for each receiver, based on our own calculations.
2313 unsigned int estimated_recv_bandwidth = 0;
2314 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
2315 it != recv_channels_.end(); ++it) {
2316 // Don't report receive statistics from the default channel if we have
2317 // specified receive channels.
2318 if (it->first == 0 && recv_channels_.size() > 1)
2319 continue;
2320 WebRtcVideoChannelRecvInfo* channel = it->second;
2321
2322 unsigned int ssrc;
2323 // Get receiver statistics and build VideoReceiverInfo, if we have data.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002324 // Skip the default channel (ssrc == 0).
2325 if (engine_->vie()->rtp()->GetRemoteSSRC(
2326 channel->channel_id(), ssrc) != 0 ||
2327 ssrc == 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 continue;
2329
2330 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2331 if (engine_->vie()->rtp()->GetRTPStatistics(
2332 channel->channel_id(), bytes_sent, packets_sent, bytes_recv,
2333 packets_recv) != 0) {
2334 LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
2335 return false;
2336 }
2337 VideoReceiverInfo rinfo;
2338 rinfo.ssrcs.push_back(ssrc);
2339 rinfo.bytes_rcvd = bytes_recv;
2340 rinfo.packets_rcvd = packets_recv;
2341 rinfo.packets_lost = -1;
2342 rinfo.packets_concealed = -1;
2343 rinfo.fraction_lost = -1; // from SentRTCP
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344 rinfo.nacks_sent = -1;
2345 rinfo.frame_width = channel->render_adapter()->width();
2346 rinfo.frame_height = channel->render_adapter()->height();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 int fps = channel->render_adapter()->framerate();
2348 rinfo.framerate_decoded = fps;
2349 rinfo.framerate_output = fps;
wu@webrtc.org97077a32013-10-25 21:18:33 +00002350 channel->decoder_observer()->ExportTo(&rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002351
2352 // Get sent RTCP statistics.
2353 uint16 s_fraction_lost;
2354 unsigned int s_cumulative_lost;
2355 unsigned int s_extended_max;
2356 unsigned int s_jitter;
2357 int s_rtt_ms;
2358 if (engine_->vie()->rtp()->GetReceivedRTCPStatistics(channel->channel_id(),
2359 s_fraction_lost, s_cumulative_lost, s_extended_max,
2360 s_jitter, s_rtt_ms) == 0) {
2361 // Convert Q8 to float.
2362 rinfo.packets_lost = s_cumulative_lost;
2363 rinfo.fraction_lost = static_cast<float>(s_fraction_lost) / (1 << 8);
2364 }
2365 info->receivers.push_back(rinfo);
2366
2367 unsigned int estimated_recv_stream_bandwidth = 0;
2368 if (engine_->vie()->rtp()->GetEstimatedReceiveBandwidth(
2369 channel->channel_id(), &estimated_recv_stream_bandwidth) == 0) {
2370 estimated_recv_bandwidth += estimated_recv_stream_bandwidth;
2371 } else {
2372 LOG_RTCERR1(GetEstimatedReceiveBandwidth, channel->channel_id());
2373 }
2374 }
2375
2376 // Build BandwidthEstimationInfo.
2377 // TODO(zhurunz): Add real unittest for this.
2378 BandwidthEstimationInfo bwe;
2379
2380 // Calculations done above per send/receive stream.
2381 bwe.actual_enc_bitrate = video_bitrate_sent;
2382 bwe.transmit_bitrate = total_bitrate_sent;
2383 bwe.retransmit_bitrate = nack_bitrate_sent;
2384 bwe.available_send_bandwidth = estimated_send_bandwidth;
2385 bwe.available_recv_bandwidth = estimated_recv_bandwidth;
2386 bwe.target_enc_bitrate = target_enc_bitrate;
2387
2388 info->bw_estimations.push_back(bwe);
2389
2390 return true;
2391}
2392
2393bool WebRtcVideoMediaChannel::SetCapturer(uint32 ssrc,
2394 VideoCapturer* capturer) {
2395 ASSERT(ssrc != 0);
2396 if (!capturer) {
2397 return RemoveCapturer(ssrc);
2398 }
2399 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2400 if (!send_channel) {
2401 return false;
2402 }
2403 VideoCapturer* old_capturer = send_channel->video_capturer();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404 if (old_capturer) {
2405 old_capturer->SignalVideoFrame.disconnect(this);
2406 }
2407
2408 send_channel->set_video_capturer(capturer);
2409 capturer->SignalVideoFrame.connect(
2410 this,
2411 &WebRtcVideoMediaChannel::AdaptAndSendFrame);
2412 if (!capturer->IsScreencast() && ratio_w_ != 0 && ratio_h_ != 0) {
2413 capturer->UpdateAspectRatio(ratio_w_, ratio_h_);
2414 }
2415 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2416 if (send_codec_) {
2417 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2418 }
2419 return true;
2420}
2421
2422bool WebRtcVideoMediaChannel::RequestIntraFrame() {
2423 // There is no API exposed to application to request a key frame
2424 // ViE does this internally when there are errors from decoder
2425 return false;
2426}
2427
2428void WebRtcVideoMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
2429 // Pick which channel to send this packet to. If this packet doesn't match
2430 // any multiplexed streams, just send it to the default channel. Otherwise,
2431 // send it to the specific decoder instance for that stream.
2432 uint32 ssrc = 0;
2433 if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
2434 return;
2435 int which_channel = GetRecvChannelNum(ssrc);
2436 if (which_channel == -1) {
2437 which_channel = video_channel();
2438 }
2439
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002440 engine()->vie()->network()->ReceivedRTPPacket(
2441 which_channel,
2442 packet->data(),
2443 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444}
2445
2446void WebRtcVideoMediaChannel::OnRtcpReceived(talk_base::Buffer* packet) {
2447// Sending channels need all RTCP packets with feedback information.
2448// Even sender reports can contain attached report blocks.
2449// Receiving channels need sender reports in order to create
2450// correct receiver reports.
2451
2452 uint32 ssrc = 0;
2453 if (!GetRtcpSsrc(packet->data(), packet->length(), &ssrc)) {
2454 LOG(LS_WARNING) << "Failed to parse SSRC from received RTCP packet";
2455 return;
2456 }
2457 int type = 0;
2458 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2459 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2460 return;
2461 }
2462
2463 // If it is a sender report, find the channel that is listening.
2464 if (type == kRtcpTypeSR) {
2465 int which_channel = GetRecvChannelNum(ssrc);
2466 if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002467 engine_->vie()->network()->ReceivedRTCPPacket(
2468 which_channel,
2469 packet->data(),
2470 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 }
2472 }
2473 // SR may continue RR and any RR entry may correspond to any one of the send
2474 // channels. So all RTCP packets must be forwarded all send channels. ViE
2475 // will filter out RR internally.
2476 for (SendChannelMap::iterator iter = send_channels_.begin();
2477 iter != send_channels_.end(); ++iter) {
2478 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2479 int channel_id = send_channel->channel_id();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002480 engine_->vie()->network()->ReceivedRTCPPacket(
2481 channel_id,
2482 packet->data(),
2483 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002484 }
2485}
2486
2487void WebRtcVideoMediaChannel::OnReadyToSend(bool ready) {
2488 SetNetworkTransmissionState(ready);
2489}
2490
2491bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2492 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2493 if (!send_channel) {
2494 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
2495 return false;
2496 }
2497 send_channel->set_muted(muted);
2498 return true;
2499}
2500
2501bool WebRtcVideoMediaChannel::SetRecvRtpHeaderExtensions(
2502 const std::vector<RtpHeaderExtension>& extensions) {
2503 if (receive_extensions_ == extensions) {
2504 return true;
2505 }
2506 receive_extensions_ = extensions;
2507
2508 const RtpHeaderExtension* offset_extension =
2509 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2510 const RtpHeaderExtension* send_time_extension =
2511 FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
2512
2513 // Loop through all receive channels and enable/disable the extensions.
2514 for (RecvChannelMap::iterator channel_it = recv_channels_.begin();
2515 channel_it != recv_channels_.end(); ++channel_it) {
2516 int channel_id = channel_it->second->channel_id();
2517 if (!SetHeaderExtension(
2518 &webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus, channel_id,
2519 offset_extension)) {
2520 return false;
2521 }
2522 if (!SetHeaderExtension(
2523 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
2524 send_time_extension)) {
2525 return false;
2526 }
2527 }
2528 return true;
2529}
2530
2531bool WebRtcVideoMediaChannel::SetSendRtpHeaderExtensions(
2532 const std::vector<RtpHeaderExtension>& extensions) {
2533 send_extensions_ = extensions;
2534
2535 const RtpHeaderExtension* offset_extension =
2536 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2537 const RtpHeaderExtension* send_time_extension =
2538 FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
2539
2540 // Loop through all send channels and enable/disable the extensions.
2541 for (SendChannelMap::iterator channel_it = send_channels_.begin();
2542 channel_it != send_channels_.end(); ++channel_it) {
2543 int channel_id = channel_it->second->channel_id();
2544 if (!SetHeaderExtension(
2545 &webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus, channel_id,
2546 offset_extension)) {
2547 return false;
2548 }
2549 if (!SetHeaderExtension(
2550 &webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus, channel_id,
2551 send_time_extension)) {
2552 return false;
2553 }
2554 }
2555 return true;
2556}
2557
2558bool WebRtcVideoMediaChannel::SetSendBandwidth(bool autobw, int bps) {
2559 LOG(LS_INFO) << "WebRtcVideoMediaChanne::SetSendBandwidth";
2560
2561 if (InConferenceMode()) {
2562 LOG(LS_INFO) << "Conference mode ignores SetSendBandWidth";
2563 return true;
2564 }
2565
2566 if (!send_codec_) {
2567 LOG(LS_INFO) << "The send codec has not been set up yet";
2568 return true;
2569 }
2570
2571 int min_bitrate;
2572 int start_bitrate;
2573 int max_bitrate;
2574 if (autobw) {
2575 // Use the default values for min bitrate.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002576 min_bitrate = send_min_bitrate_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577 // Use the default value or the bps for the max
2578 max_bitrate = (bps <= 0) ? send_max_bitrate_ : (bps / 1000);
2579 // Maximum start bitrate can be kStartVideoBitrate.
2580 start_bitrate = talk_base::_min(kStartVideoBitrate, max_bitrate);
2581 } else {
2582 // Use the default start or the bps as the target bitrate.
2583 int target_bitrate = (bps <= 0) ? kStartVideoBitrate : (bps / 1000);
2584 min_bitrate = target_bitrate;
2585 start_bitrate = target_bitrate;
2586 max_bitrate = target_bitrate;
2587 }
2588
2589 if (!SetSendCodec(*send_codec_, min_bitrate, start_bitrate, max_bitrate)) {
2590 return false;
2591 }
2592 LogSendCodecChange("SetSendBandwidth()");
2593
2594 return true;
2595}
2596
2597bool WebRtcVideoMediaChannel::SetOptions(const VideoOptions &options) {
2598 // Always accept options that are unchanged.
2599 if (options_ == options) {
2600 return true;
2601 }
2602
2603 // Trigger SetSendCodec to set correct noise reduction state if the option has
2604 // changed.
2605 bool denoiser_changed = options.video_noise_reduction.IsSet() &&
2606 (options_.video_noise_reduction != options.video_noise_reduction);
2607
2608 bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
2609 (options_.video_leaky_bucket != options.video_leaky_bucket);
2610
2611 bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
2612 (options_.buffered_mode_latency != options.buffered_mode_latency);
2613
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002614 bool cpu_overuse_detection_changed = options.cpu_overuse_detection.IsSet() &&
2615 (options_.cpu_overuse_detection != options.cpu_overuse_detection);
2616
wu@webrtc.orgde305012013-10-31 15:40:38 +00002617 bool dscp_option_changed = (options_.dscp != options.dscp);
2618
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619 bool conference_mode_turned_off = false;
2620 if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
2621 options_.conference_mode.GetWithDefaultIfUnset(false) &&
2622 !options.conference_mode.GetWithDefaultIfUnset(false)) {
2623 conference_mode_turned_off = true;
2624 }
2625
2626 // Save the options, to be interpreted where appropriate.
2627 // Use options_.SetAll() instead of assignment so that unset value in options
2628 // will not overwrite the previous option value.
2629 options_.SetAll(options);
2630
2631 // Set CPU options for all send channels.
2632 for (SendChannelMap::iterator iter = send_channels_.begin();
2633 iter != send_channels_.end(); ++iter) {
2634 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2635 send_channel->ApplyCpuOptions(options_);
2636 }
2637
2638 // Adjust send codec bitrate if needed.
2639 int conf_max_bitrate = kDefaultConferenceModeMaxVideoBitrate;
2640
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002641 // Save altered min_bitrate level and apply if necessary.
2642 bool adjusted_min_bitrate = false;
2643 if (options.lower_min_bitrate.IsSet()) {
2644 bool lower;
2645 options.lower_min_bitrate.Get(&lower);
2646
2647 int new_send_min_bitrate = lower ? kLowerMinBitrate : kMinVideoBitrate;
2648 adjusted_min_bitrate = (new_send_min_bitrate != send_min_bitrate_);
2649 send_min_bitrate_ = new_send_min_bitrate;
2650 }
2651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002652 int expected_bitrate = send_max_bitrate_;
2653 if (InConferenceMode()) {
2654 expected_bitrate = conf_max_bitrate;
2655 } else if (conference_mode_turned_off) {
2656 // This is a special case for turning conference mode off.
2657 // Max bitrate should go back to the default maximum value instead
2658 // of the current maximum.
2659 expected_bitrate = kMaxVideoBitrate;
2660 }
2661
2662 if (send_codec_ &&
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002663 (send_max_bitrate_ != expected_bitrate || denoiser_changed ||
2664 adjusted_min_bitrate)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002665 // On success, SetSendCodec() will reset send_max_bitrate_ to
2666 // expected_bitrate.
2667 if (!SetSendCodec(*send_codec_,
2668 send_min_bitrate_,
2669 send_start_bitrate_,
2670 expected_bitrate)) {
2671 return false;
2672 }
2673 LogSendCodecChange("SetOptions()");
2674 }
2675 if (leaky_bucket_changed) {
2676 bool enable_leaky_bucket =
2677 options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
2678 for (SendChannelMap::iterator it = send_channels_.begin();
2679 it != send_channels_.end(); ++it) {
2680 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(
2681 it->second->channel_id(), enable_leaky_bucket) != 0) {
2682 LOG_RTCERR2(SetTransmissionSmoothingStatus, it->second->channel_id(),
2683 enable_leaky_bucket);
2684 }
2685 }
2686 }
2687 if (buffer_latency_changed) {
2688 int buffer_latency =
2689 options_.buffered_mode_latency.GetWithDefaultIfUnset(
2690 cricket::kBufferedModeDisabled);
2691 for (SendChannelMap::iterator it = send_channels_.begin();
2692 it != send_channels_.end(); ++it) {
2693 if (engine()->vie()->rtp()->SetSenderBufferingMode(
2694 it->second->channel_id(), buffer_latency) != 0) {
2695 LOG_RTCERR2(SetSenderBufferingMode, it->second->channel_id(),
2696 buffer_latency);
2697 }
2698 }
2699 for (RecvChannelMap::iterator it = recv_channels_.begin();
2700 it != recv_channels_.end(); ++it) {
2701 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
2702 it->second->channel_id(), buffer_latency) != 0) {
2703 LOG_RTCERR2(SetReceiverBufferingMode, it->second->channel_id(),
2704 buffer_latency);
2705 }
2706 }
2707 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002708 if (cpu_overuse_detection_changed) {
2709 bool cpu_overuse_detection =
2710 options_.cpu_overuse_detection.GetWithDefaultIfUnset(false);
2711 for (SendChannelMap::iterator iter = send_channels_.begin();
2712 iter != send_channels_.end(); ++iter) {
2713 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2714 send_channel->SetCpuOveruseDetection(cpu_overuse_detection);
2715 }
2716 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00002717 if (dscp_option_changed) {
2718 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
2719 if (options.dscp.GetWithDefaultIfUnset(false))
2720 dscp = kVideoDscpValue;
2721 if (MediaChannel::SetDscp(dscp) != 0) {
2722 LOG(LS_WARNING) << "Failed to set DSCP settings for video channel";
2723 }
2724 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002725 return true;
2726}
2727
2728void WebRtcVideoMediaChannel::SetInterface(NetworkInterface* iface) {
2729 MediaChannel::SetInterface(iface);
2730 // Set the RTP recv/send buffer to a bigger size
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002731 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2732 talk_base::Socket::OPT_RCVBUF,
2733 kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734
2735 // TODO(sriniv): Remove or re-enable this.
2736 // As part of b/8030474, send-buffer is size now controlled through
2737 // portallocator flags.
2738 // network_interface_->SetOption(NetworkInterface::ST_RTP,
2739 // talk_base::Socket::OPT_SNDBUF,
2740 // kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002741}
2742
2743void WebRtcVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
2744 ASSERT(ratio_w != 0);
2745 ASSERT(ratio_h != 0);
2746 ratio_w_ = ratio_w;
2747 ratio_h_ = ratio_h;
2748 // For now assume that all streams want the same aspect ratio.
2749 // TODO(hellner): remove the need for this assumption.
2750 for (SendChannelMap::iterator iter = send_channels_.begin();
2751 iter != send_channels_.end(); ++iter) {
2752 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2753 VideoCapturer* capturer = send_channel->video_capturer();
2754 if (capturer) {
2755 capturer->UpdateAspectRatio(ratio_w, ratio_h);
2756 }
2757 }
2758}
2759
2760bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
2761 VideoRenderer** renderer) {
2762 RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
2763 if (it == recv_channels_.end()) {
2764 if (first_receive_ssrc_ == ssrc &&
2765 recv_channels_.find(0) != recv_channels_.end()) {
2766 LOG(LS_INFO) << " GetRenderer " << ssrc
2767 << " reuse default renderer #"
2768 << vie_channel_;
2769 *renderer = recv_channels_[0]->render_adapter()->renderer();
2770 return true;
2771 }
2772 return false;
2773 }
2774
2775 *renderer = it->second->render_adapter()->renderer();
2776 return true;
2777}
2778
2779void WebRtcVideoMediaChannel::AdaptAndSendFrame(VideoCapturer* capturer,
2780 const VideoFrame* frame) {
2781 if (capturer->IsScreencast()) {
2782 // Do not adapt frames that are screencast.
2783 SendFrame(capturer, frame);
2784 return;
2785 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002786 // TODO(thorcarpenter): This is broken. One capturer registered on two ssrc
2787 // will not send any video to the second ssrc send channel. We should remove
2788 // GetSendChannel(capturer) and pass in an ssrc here.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002789 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(capturer);
2790 if (!send_channel) {
2791 SendFrame(capturer, frame);
2792 return;
2793 }
2794 const VideoFrame* output_frame = NULL;
2795 send_channel->AdaptFrame(frame, &output_frame);
2796 if (output_frame) {
2797 SendFrame(send_channel, output_frame, capturer->IsScreencast());
2798 }
2799}
2800
2801// TODO(zhurunz): Add unittests to test this function.
2802void WebRtcVideoMediaChannel::SendFrame(VideoCapturer* capturer,
2803 const VideoFrame* frame) {
2804 // If there's send channel registers to the |capturer|, then only send the
2805 // frame to that channel and return. Otherwise send the frame to the default
2806 // channel, which currently taking frames from the engine.
2807 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(capturer);
2808 if (send_channel) {
2809 SendFrame(send_channel, frame, capturer->IsScreencast());
2810 return;
2811 }
2812 // TODO(hellner): Remove below for loop once the captured frame no longer
2813 // come from the engine, i.e. the engine no longer owns a capturer.
2814 for (SendChannelMap::iterator iter = send_channels_.begin();
2815 iter != send_channels_.end(); ++iter) {
2816 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2817 if (send_channel->video_capturer() == NULL) {
2818 SendFrame(send_channel, frame, capturer->IsScreencast());
2819 }
2820 }
2821}
2822
2823bool WebRtcVideoMediaChannel::SendFrame(
2824 WebRtcVideoChannelSendInfo* send_channel,
2825 const VideoFrame* frame,
2826 bool is_screencast) {
2827 if (!send_channel) {
2828 return false;
2829 }
2830 if (!send_codec_) {
2831 // Send codec has not been set. No reason to process the frame any further.
2832 return false;
2833 }
2834 const VideoFormat& video_format = send_channel->video_format();
2835 // If the frame should be dropped.
2836 const bool video_format_set = video_format != cricket::VideoFormat();
2837 if (video_format_set &&
2838 (video_format.width == 0 && video_format.height == 0)) {
2839 return true;
2840 }
2841
2842 // Checks if we need to reset vie send codec.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002843 if (!MaybeResetVieSendCodec(send_channel,
2844 static_cast<int>(frame->GetWidth()),
2845 static_cast<int>(frame->GetHeight()),
2846 is_screencast, NULL)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 LOG(LS_ERROR) << "MaybeResetVieSendCodec failed with "
2848 << frame->GetWidth() << "x" << frame->GetHeight();
2849 return false;
2850 }
2851 const VideoFrame* frame_out = frame;
2852 talk_base::scoped_ptr<VideoFrame> processed_frame;
2853 // Disable muting for screencast.
2854 const bool mute = (send_channel->muted() && !is_screencast);
2855 send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
2856 if (processed_frame) {
2857 frame_out = processed_frame.get();
2858 }
2859
2860 webrtc::ViEVideoFrameI420 frame_i420;
2861 // TODO(ronghuawu): Update the webrtc::ViEVideoFrameI420
2862 // to use const unsigned char*
2863 frame_i420.y_plane = const_cast<unsigned char*>(frame_out->GetYPlane());
2864 frame_i420.u_plane = const_cast<unsigned char*>(frame_out->GetUPlane());
2865 frame_i420.v_plane = const_cast<unsigned char*>(frame_out->GetVPlane());
2866 frame_i420.y_pitch = frame_out->GetYPitch();
2867 frame_i420.u_pitch = frame_out->GetUPitch();
2868 frame_i420.v_pitch = frame_out->GetVPitch();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002869 frame_i420.width = static_cast<uint16>(frame_out->GetWidth());
2870 frame_i420.height = static_cast<uint16>(frame_out->GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871
2872 int64 timestamp_ntp_ms = 0;
2873 // TODO(justinlin): Reenable after Windows issues with clock drift are fixed.
2874 // Currently reverted to old behavior of discarding capture timestamp.
2875#if 0
2876 // If the frame timestamp is 0, we will use the deliver time.
2877 const int64 frame_timestamp = frame->GetTimeStamp();
2878 if (frame_timestamp != 0) {
2879 if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
2880 kTimestampDeltaInSecondsForWarning) {
2881 LOG(LS_WARNING) << "Frame timestamp differs by more than "
2882 << kTimestampDeltaInSecondsForWarning << " seconds from "
2883 << "current Unix timestamp.";
2884 }
2885
2886 timestamp_ntp_ms =
2887 talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
2888 }
2889#endif
2890
2891 return send_channel->external_capture()->IncomingFrameI420(
2892 frame_i420, timestamp_ntp_ms) == 0;
2893}
2894
2895bool WebRtcVideoMediaChannel::CreateChannel(uint32 ssrc_key,
2896 MediaDirection direction,
2897 int* channel_id) {
2898 // There are 3 types of channels. Sending only, receiving only and
2899 // sending and receiving. The sending and receiving channel is the
2900 // default channel and there is only one. All other channels that are created
2901 // are associated with the default channel which must exist. The default
2902 // channel id is stored in |vie_channel_|. All channels need to know about
2903 // the default channel to properly handle remb which is why there are
2904 // different ViE create channel calls.
2905 // For this channel the local and remote ssrc key is 0. However, it may
2906 // have a non-zero local and/or remote ssrc depending on if it is currently
2907 // sending and/or receiving.
2908 if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
2909 (!send_channels_.empty() || !recv_channels_.empty())) {
2910 ASSERT(false);
2911 return false;
2912 }
2913
2914 *channel_id = -1;
2915 if (direction == MD_RECV) {
2916 // All rec channels are associated with the default channel |vie_channel_|
2917 if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
2918 vie_channel_) != 0) {
2919 LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
2920 return false;
2921 }
2922 } else if (direction == MD_SEND) {
2923 if (engine_->vie()->base()->CreateChannel(*channel_id,
2924 vie_channel_) != 0) {
2925 LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
2926 return false;
2927 }
2928 } else {
2929 ASSERT(direction == MD_SENDRECV);
2930 if (engine_->vie()->base()->CreateChannel(*channel_id) != 0) {
2931 LOG_RTCERR1(CreateChannel, *channel_id);
2932 return false;
2933 }
2934 }
2935 if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
2936 engine_->vie()->base()->DeleteChannel(*channel_id);
2937 *channel_id = -1;
2938 return false;
2939 }
2940
2941 return true;
2942}
2943
2944bool WebRtcVideoMediaChannel::ConfigureChannel(int channel_id,
2945 MediaDirection direction,
2946 uint32 ssrc_key) {
2947 const bool receiving = (direction == MD_RECV) || (direction == MD_SENDRECV);
2948 const bool sending = (direction == MD_SEND) || (direction == MD_SENDRECV);
2949 // Register external transport.
2950 if (engine_->vie()->network()->RegisterSendTransport(
2951 channel_id, *this) != 0) {
2952 LOG_RTCERR1(RegisterSendTransport, channel_id);
2953 return false;
2954 }
2955
2956 // Set MTU.
2957 if (engine_->vie()->network()->SetMTU(channel_id, kVideoMtu) != 0) {
2958 LOG_RTCERR2(SetMTU, channel_id, kVideoMtu);
2959 return false;
2960 }
2961 // Turn on RTCP and loss feedback reporting.
2962 if (engine()->vie()->rtp()->SetRTCPStatus(
2963 channel_id, webrtc::kRtcpCompound_RFC4585) != 0) {
2964 LOG_RTCERR2(SetRTCPStatus, channel_id, webrtc::kRtcpCompound_RFC4585);
2965 return false;
2966 }
2967 // Enable pli as key frame request method.
2968 if (engine_->vie()->rtp()->SetKeyFrameRequestMethod(
2969 channel_id, webrtc::kViEKeyFrameRequestPliRtcp) != 0) {
2970 LOG_RTCERR2(SetKeyFrameRequestMethod,
2971 channel_id, webrtc::kViEKeyFrameRequestPliRtcp);
2972 return false;
2973 }
2974 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
2975 // Logged in SetNackFec. Don't spam the logs.
2976 return false;
2977 }
2978 // Note that receiving must always be configured before sending to ensure
2979 // that send and receive channel is configured correctly (ConfigureReceiving
2980 // assumes no sending).
2981 if (receiving) {
2982 if (!ConfigureReceiving(channel_id, ssrc_key)) {
2983 return false;
2984 }
2985 }
2986 if (sending) {
2987 if (!ConfigureSending(channel_id, ssrc_key)) {
2988 return false;
2989 }
2990 }
2991
2992 return true;
2993}
2994
2995bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
2996 uint32 remote_ssrc_key) {
2997 // Make sure that an SSRC/key isn't registered more than once.
2998 if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
2999 return false;
3000 }
3001 // Connect the voice channel, if there is one.
3002 // TODO(perkj): The A/V is synched by the receiving channel. So we need to
3003 // know the SSRC of the remote audio channel in order to fetch the correct
3004 // webrtc VoiceEngine channel. For now- only sync the default channel used
3005 // in 1-1 calls.
3006 if (remote_ssrc_key == 0 && voice_channel_) {
3007 WebRtcVoiceMediaChannel* voice_channel =
3008 static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
3009 if (engine_->vie()->base()->ConnectAudioChannel(
3010 vie_channel_, voice_channel->voe_channel()) != 0) {
3011 LOG_RTCERR2(ConnectAudioChannel, channel_id,
3012 voice_channel->voe_channel());
3013 LOG(LS_WARNING) << "A/V not synchronized";
3014 // Not a fatal error.
3015 }
3016 }
3017
3018 talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
3019 new WebRtcVideoChannelRecvInfo(channel_id));
3020
3021 // Install a render adapter.
3022 if (engine_->vie()->render()->AddRenderer(channel_id,
3023 webrtc::kVideoI420, channel_info->render_adapter()) != 0) {
3024 LOG_RTCERR3(AddRenderer, channel_id, webrtc::kVideoI420,
3025 channel_info->render_adapter());
3026 return false;
3027 }
3028
3029
3030 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3031 kNotSending,
3032 remb_enabled_) != 0) {
3033 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
3034 return false;
3035 }
3036
3037 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus,
3038 channel_id, receive_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3039 return false;
3040 }
3041
3042 if (!SetHeaderExtension(
3043 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
3044 receive_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
3045 return false;
3046 }
3047
3048 if (remote_ssrc_key != 0) {
3049 // Use the same SSRC as our default channel
3050 // (so the RTCP reports are correct).
3051 unsigned int send_ssrc = 0;
3052 webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
3053 if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
3054 LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
3055 return false;
3056 }
3057 if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
3058 LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
3059 return false;
3060 }
3061 } // Else this is the the default channel and we don't change the SSRC.
3062
3063 // Disable color enhancement since it is a bit too aggressive.
3064 if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
3065 false) != 0) {
3066 LOG_RTCERR1(EnableColorEnhancement, channel_id);
3067 return false;
3068 }
3069
3070 if (!SetReceiveCodecs(channel_info.get())) {
3071 return false;
3072 }
3073
3074 int buffer_latency =
3075 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3076 cricket::kBufferedModeDisabled);
3077 if (buffer_latency != cricket::kBufferedModeDisabled) {
3078 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
3079 channel_id, buffer_latency) != 0) {
3080 LOG_RTCERR2(SetReceiverBufferingMode, channel_id, buffer_latency);
3081 }
3082 }
3083
3084 if (render_started_) {
3085 if (engine_->vie()->render()->StartRender(channel_id) != 0) {
3086 LOG_RTCERR1(StartRender, channel_id);
3087 return false;
3088 }
3089 }
3090
3091 // Register decoder observer for incoming framerate and bitrate.
3092 if (engine()->vie()->codec()->RegisterDecoderObserver(
3093 channel_id, *channel_info->decoder_observer()) != 0) {
3094 LOG_RTCERR1(RegisterDecoderObserver, channel_info->decoder_observer());
3095 return false;
3096 }
3097
3098 recv_channels_[remote_ssrc_key] = channel_info.release();
3099 return true;
3100}
3101
3102bool WebRtcVideoMediaChannel::ConfigureSending(int channel_id,
3103 uint32 local_ssrc_key) {
3104 // The ssrc key can be zero or correspond to an SSRC.
3105 // Make sure the default channel isn't configured more than once.
3106 if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
3107 return false;
3108 }
3109 // Make sure that the SSRC is not already in use.
3110 uint32 dummy_key;
3111 if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
3112 return false;
3113 }
3114 int vie_capture = 0;
3115 webrtc::ViEExternalCapture* external_capture = NULL;
3116 // Register external capture.
3117 if (engine()->vie()->capture()->AllocateExternalCaptureDevice(
3118 vie_capture, external_capture) != 0) {
3119 LOG_RTCERR0(AllocateExternalCaptureDevice);
3120 return false;
3121 }
3122
3123 // Connect external capture.
3124 if (engine()->vie()->capture()->ConnectCaptureDevice(
3125 vie_capture, channel_id) != 0) {
3126 LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
3127 return false;
3128 }
3129 talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
3130 new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
3131 external_capture,
3132 engine()->cpu_monitor()));
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003133 if (engine()->vie()->base()->RegisterCpuOveruseObserver(
3134 channel_id, send_channel->overuse_observer())) {
3135 LOG_RTCERR1(RegisterCpuOveruseObserver, channel_id);
3136 return false;
3137 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 send_channel->ApplyCpuOptions(options_);
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003139 send_channel->SignalCpuAdaptationUnable.connect(this,
3140 &WebRtcVideoMediaChannel::OnCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003141
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003142 if (options_.cpu_overuse_detection.GetWithDefaultIfUnset(false)) {
3143 send_channel->SetCpuOveruseDetection(true);
3144 }
3145
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146 // Register encoder observer for outgoing framerate and bitrate.
3147 if (engine()->vie()->codec()->RegisterEncoderObserver(
3148 channel_id, *send_channel->encoder_observer()) != 0) {
3149 LOG_RTCERR1(RegisterEncoderObserver, send_channel->encoder_observer());
3150 return false;
3151 }
3152
3153 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus,
3154 channel_id, send_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3155 return false;
3156 }
3157
3158 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus,
3159 channel_id, send_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
3160 return false;
3161 }
3162
3163 if (options_.video_leaky_bucket.GetWithDefaultIfUnset(false)) {
3164 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
3165 true) != 0) {
3166 LOG_RTCERR2(SetTransmissionSmoothingStatus, channel_id, true);
3167 return false;
3168 }
3169 }
3170
3171 int buffer_latency =
3172 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3173 cricket::kBufferedModeDisabled);
3174 if (buffer_latency != cricket::kBufferedModeDisabled) {
3175 if (engine()->vie()->rtp()->SetSenderBufferingMode(
3176 channel_id, buffer_latency) != 0) {
3177 LOG_RTCERR2(SetSenderBufferingMode, channel_id, buffer_latency);
3178 }
3179 }
3180 // The remb status direction correspond to the RTP stream (and not the RTCP
3181 // stream). I.e. if send remb is enabled it means it is receiving remote
3182 // rembs and should use them to estimate bandwidth. Receive remb mean that
3183 // remb packets will be generated and that the channel should be included in
3184 // it. If remb is enabled all channels are allowed to contribute to the remb
3185 // but only receive channels will ever end up actually contributing. This
3186 // keeps the logic simple.
3187 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3188 remb_enabled_,
3189 remb_enabled_) != 0) {
3190 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
3191 return false;
3192 }
3193 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3194 // Logged in SetNackFec. Don't spam the logs.
3195 return false;
3196 }
3197
3198 send_channels_[local_ssrc_key] = send_channel.release();
3199
3200 return true;
3201}
3202
3203bool WebRtcVideoMediaChannel::SetNackFec(int channel_id,
3204 int red_payload_type,
3205 int fec_payload_type,
3206 bool nack_enabled) {
3207 bool enable = (red_payload_type != -1 && fec_payload_type != -1 &&
3208 !InConferenceMode());
3209 if (enable) {
3210 if (engine_->vie()->rtp()->SetHybridNACKFECStatus(
3211 channel_id, nack_enabled, red_payload_type, fec_payload_type) != 0) {
3212 LOG_RTCERR4(SetHybridNACKFECStatus,
3213 channel_id, nack_enabled, red_payload_type, fec_payload_type);
3214 return false;
3215 }
3216 LOG(LS_INFO) << "Hybrid NACK/FEC enabled for channel " << channel_id;
3217 } else {
3218 if (engine_->vie()->rtp()->SetNACKStatus(channel_id, nack_enabled) != 0) {
3219 LOG_RTCERR1(SetNACKStatus, channel_id);
3220 return false;
3221 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003222 std::string enabled = nack_enabled ? "enabled" : "disabled";
3223 LOG(LS_INFO) << "NACK " << enabled << " for channel " << channel_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224 }
3225 return true;
3226}
3227
3228bool WebRtcVideoMediaChannel::SetSendCodec(const webrtc::VideoCodec& codec,
3229 int min_bitrate,
3230 int start_bitrate,
3231 int max_bitrate) {
3232 bool ret_val = true;
3233 for (SendChannelMap::iterator iter = send_channels_.begin();
3234 iter != send_channels_.end(); ++iter) {
3235 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3236 ret_val = SetSendCodec(send_channel, codec, min_bitrate, start_bitrate,
3237 max_bitrate) && ret_val;
3238 }
3239 if (ret_val) {
3240 // All SetSendCodec calls were successful. Update the global state
3241 // accordingly.
3242 send_codec_.reset(new webrtc::VideoCodec(codec));
3243 send_min_bitrate_ = min_bitrate;
3244 send_start_bitrate_ = start_bitrate;
3245 send_max_bitrate_ = max_bitrate;
3246 } else {
3247 // At least one SetSendCodec call failed, rollback.
3248 for (SendChannelMap::iterator iter = send_channels_.begin();
3249 iter != send_channels_.end(); ++iter) {
3250 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3251 if (send_codec_) {
3252 SetSendCodec(send_channel, *send_codec_.get(), send_min_bitrate_,
3253 send_start_bitrate_, send_max_bitrate_);
3254 }
3255 }
3256 }
3257 return ret_val;
3258}
3259
3260bool WebRtcVideoMediaChannel::SetSendCodec(
3261 WebRtcVideoChannelSendInfo* send_channel,
3262 const webrtc::VideoCodec& codec,
3263 int min_bitrate,
3264 int start_bitrate,
3265 int max_bitrate) {
3266 if (!send_channel) {
3267 return false;
3268 }
3269 const int channel_id = send_channel->channel_id();
3270 // Make a copy of the codec
3271 webrtc::VideoCodec target_codec = codec;
3272 target_codec.startBitrate = start_bitrate;
3273 target_codec.minBitrate = min_bitrate;
3274 target_codec.maxBitrate = max_bitrate;
3275
3276 // Set the default number of temporal layers for VP8.
3277 if (webrtc::kVideoCodecVP8 == codec.codecType) {
3278 target_codec.codecSpecific.VP8.numberOfTemporalLayers =
3279 kDefaultNumberOfTemporalLayers;
3280
3281 // Turn off the VP8 error resilience
3282 target_codec.codecSpecific.VP8.resilience = webrtc::kResilienceOff;
3283
3284 bool enable_denoising =
3285 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3286 target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
3287 }
3288
3289 // Register external encoder if codec type is supported by encoder factory.
3290 if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
3291 !send_channel->IsEncoderRegistered(target_codec.plType)) {
3292 webrtc::VideoEncoder* encoder =
3293 engine()->CreateExternalEncoder(codec.codecType);
3294 if (encoder) {
3295 if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
3296 channel_id, target_codec.plType, encoder, false) == 0) {
3297 send_channel->RegisterEncoder(target_codec.plType, encoder);
3298 } else {
3299 LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
3300 engine()->DestroyExternalEncoder(encoder);
3301 }
3302 }
3303 }
3304
3305 // Resolution and framerate may vary for different send channels.
3306 const VideoFormat& video_format = send_channel->video_format();
3307 UpdateVideoCodec(video_format, &target_codec);
3308
3309 if (target_codec.width == 0 && target_codec.height == 0) {
3310 const uint32 ssrc = send_channel->stream_params()->first_ssrc();
3311 LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
3312 << "for ssrc: " << ssrc << ".";
3313 } else {
3314 MaybeChangeStartBitrate(channel_id, &target_codec);
3315 if (0 != engine()->vie()->codec()->SetSendCodec(channel_id, target_codec)) {
3316 LOG_RTCERR2(SetSendCodec, channel_id, target_codec.plName);
3317 return false;
3318 }
3319
3320 }
3321 send_channel->set_interval(
3322 cricket::VideoFormat::FpsToInterval(target_codec.maxFramerate));
3323 return true;
3324}
3325
3326
3327static std::string ToString(webrtc::VideoCodecComplexity complexity) {
3328 switch (complexity) {
3329 case webrtc::kComplexityNormal:
3330 return "normal";
3331 case webrtc::kComplexityHigh:
3332 return "high";
3333 case webrtc::kComplexityHigher:
3334 return "higher";
3335 case webrtc::kComplexityMax:
3336 return "max";
3337 default:
3338 return "unknown";
3339 }
3340}
3341
3342static std::string ToString(webrtc::VP8ResilienceMode resilience) {
3343 switch (resilience) {
3344 case webrtc::kResilienceOff:
3345 return "off";
3346 case webrtc::kResilientStream:
3347 return "stream";
3348 case webrtc::kResilientFrames:
3349 return "frames";
3350 default:
3351 return "unknown";
3352 }
3353}
3354
3355void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
3356 webrtc::VideoCodec vie_codec;
3357 if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
3358 LOG_RTCERR1(GetSendCodec, vie_channel_);
3359 return;
3360 }
3361
3362 LOG(LS_INFO) << reason << " : selected video codec "
3363 << vie_codec.plName << "/"
3364 << vie_codec.width << "x" << vie_codec.height << "x"
3365 << static_cast<int>(vie_codec.maxFramerate) << "fps"
3366 << "@" << vie_codec.maxBitrate << "kbps"
3367 << " (min=" << vie_codec.minBitrate << "kbps,"
3368 << " start=" << vie_codec.startBitrate << "kbps)";
3369 LOG(LS_INFO) << "Video max quantization: " << vie_codec.qpMax;
3370 if (webrtc::kVideoCodecVP8 == vie_codec.codecType) {
3371 LOG(LS_INFO) << "VP8 number of temporal layers: "
3372 << static_cast<int>(
3373 vie_codec.codecSpecific.VP8.numberOfTemporalLayers);
3374 LOG(LS_INFO) << "VP8 options : "
3375 << "picture loss indication = "
3376 << vie_codec.codecSpecific.VP8.pictureLossIndicationOn
3377 << ", feedback mode = "
3378 << vie_codec.codecSpecific.VP8.feedbackModeOn
3379 << ", complexity = "
3380 << ToString(vie_codec.codecSpecific.VP8.complexity)
3381 << ", resilience = "
3382 << ToString(vie_codec.codecSpecific.VP8.resilience)
3383 << ", denoising = "
3384 << vie_codec.codecSpecific.VP8.denoisingOn
3385 << ", error concealment = "
3386 << vie_codec.codecSpecific.VP8.errorConcealmentOn
3387 << ", automatic resize = "
3388 << vie_codec.codecSpecific.VP8.automaticResizeOn
3389 << ", frame dropping = "
3390 << vie_codec.codecSpecific.VP8.frameDroppingOn
3391 << ", key frame interval = "
3392 << vie_codec.codecSpecific.VP8.keyFrameInterval;
3393 }
3394
3395}
3396
3397bool WebRtcVideoMediaChannel::SetReceiveCodecs(
3398 WebRtcVideoChannelRecvInfo* info) {
3399 int red_type = -1;
3400 int fec_type = -1;
3401 int channel_id = info->channel_id();
3402 for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
3403 it != receive_codecs_.end(); ++it) {
3404 if (it->codecType == webrtc::kVideoCodecRED) {
3405 red_type = it->plType;
3406 } else if (it->codecType == webrtc::kVideoCodecULPFEC) {
3407 fec_type = it->plType;
3408 }
3409 if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
3410 LOG_RTCERR2(SetReceiveCodec, channel_id, it->plName);
3411 return false;
3412 }
3413 if (!info->IsDecoderRegistered(it->plType) &&
3414 it->codecType != webrtc::kVideoCodecRED &&
3415 it->codecType != webrtc::kVideoCodecULPFEC) {
3416 webrtc::VideoDecoder* decoder =
3417 engine()->CreateExternalDecoder(it->codecType);
3418 if (decoder) {
3419 if (engine()->vie()->ext_codec()->RegisterExternalReceiveCodec(
3420 channel_id, it->plType, decoder) == 0) {
3421 info->RegisterDecoder(it->plType, decoder);
3422 } else {
3423 LOG_RTCERR2(RegisterExternalReceiveCodec, channel_id, it->plName);
3424 engine()->DestroyExternalDecoder(decoder);
3425 }
3426 }
3427 }
3428 }
3429
3430 // Start receiving packets if at least one receive codec has been set.
3431 if (!receive_codecs_.empty()) {
3432 if (engine()->vie()->base()->StartReceive(channel_id) != 0) {
3433 LOG_RTCERR1(StartReceive, channel_id);
3434 return false;
3435 }
3436 }
3437 return true;
3438}
3439
3440int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
3441 if (ssrc == first_receive_ssrc_) {
3442 return vie_channel_;
3443 }
3444 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
3445 return (it != recv_channels_.end()) ? it->second->channel_id() : -1;
3446}
3447
3448// If the new frame size is different from the send codec size we set on vie,
3449// we need to reset the send codec on vie.
3450// The new send codec size should not exceed send_codec_ which is controlled
3451// only by the 'jec' logic.
3452bool WebRtcVideoMediaChannel::MaybeResetVieSendCodec(
3453 WebRtcVideoChannelSendInfo* send_channel,
3454 int new_width,
3455 int new_height,
3456 bool is_screencast,
3457 bool* reset) {
3458 if (reset) {
3459 *reset = false;
3460 }
3461 ASSERT(send_codec_.get() != NULL);
3462
3463 webrtc::VideoCodec target_codec = *send_codec_.get();
3464 const VideoFormat& video_format = send_channel->video_format();
3465 UpdateVideoCodec(video_format, &target_codec);
3466
3467 // Vie send codec size should not exceed target_codec.
3468 int target_width = new_width;
3469 int target_height = new_height;
3470 if (!is_screencast &&
3471 (new_width > target_codec.width || new_height > target_codec.height)) {
3472 target_width = target_codec.width;
3473 target_height = target_codec.height;
3474 }
3475
3476 // Get current vie codec.
3477 webrtc::VideoCodec vie_codec;
3478 const int channel_id = send_channel->channel_id();
3479 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) != 0) {
3480 LOG_RTCERR1(GetSendCodec, channel_id);
3481 return false;
3482 }
3483 const int cur_width = vie_codec.width;
3484 const int cur_height = vie_codec.height;
3485
3486 // Only reset send codec when there is a size change. Additionally,
3487 // automatic resize needs to be turned off when screencasting and on when
3488 // not screencasting.
3489 // Don't allow automatic resizing for screencasting.
3490 bool automatic_resize = !is_screencast;
3491 // Turn off VP8 frame dropping when screensharing as the current model does
3492 // not work well at low fps.
3493 bool vp8_frame_dropping = !is_screencast;
3494 // Disable denoising for screencasting.
3495 bool enable_denoising =
3496 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3497 bool denoising = !is_screencast && enable_denoising;
3498 bool reset_send_codec =
3499 target_width != cur_width || target_height != cur_height ||
3500 automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
3501 denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
3502 vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
3503
3504 if (reset_send_codec) {
3505 // Set the new codec on vie.
3506 vie_codec.width = target_width;
3507 vie_codec.height = target_height;
3508 vie_codec.maxFramerate = target_codec.maxFramerate;
3509 vie_codec.startBitrate = target_codec.startBitrate;
3510 vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
3511 vie_codec.codecSpecific.VP8.denoisingOn = denoising;
3512 vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
3513 // TODO(mflodman): Remove 'is_screencast' check when screen cast settings
3514 // are treated correctly in WebRTC.
3515 if (!is_screencast)
3516 MaybeChangeStartBitrate(channel_id, &vie_codec);
3517
3518 if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
3519 LOG_RTCERR1(SetSendCodec, channel_id);
3520 return false;
3521 }
3522 if (reset) {
3523 *reset = true;
3524 }
3525 LogSendCodecChange("Capture size changed");
3526 }
3527
3528 return true;
3529}
3530
3531void WebRtcVideoMediaChannel::MaybeChangeStartBitrate(
3532 int channel_id, webrtc::VideoCodec* video_codec) {
3533 if (video_codec->startBitrate < video_codec->minBitrate) {
3534 video_codec->startBitrate = video_codec->minBitrate;
3535 } else if (video_codec->startBitrate > video_codec->maxBitrate) {
3536 video_codec->startBitrate = video_codec->maxBitrate;
3537 }
3538
3539 // Use a previous target bitrate, if there is one.
3540 unsigned int current_target_bitrate = 0;
3541 if (engine()->vie()->codec()->GetCodecTargetBitrate(
3542 channel_id, &current_target_bitrate) == 0) {
3543 // Convert to kbps.
3544 current_target_bitrate /= 1000;
3545 if (current_target_bitrate > video_codec->maxBitrate) {
3546 current_target_bitrate = video_codec->maxBitrate;
3547 }
3548 if (current_target_bitrate > video_codec->startBitrate) {
3549 video_codec->startBitrate = current_target_bitrate;
3550 }
3551 }
3552}
3553
3554void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
3555 FlushBlackFrameData* black_frame_data =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003556 static_cast<FlushBlackFrameData*>(msg->pdata);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003557 FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
3558 delete black_frame_data;
3559}
3560
3561int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
3562 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003563 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003564 return MediaChannel::SendPacket(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003565}
3566
3567int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
3568 const void* data,
3569 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003570 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003571 return MediaChannel::SendRtcp(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003572}
3573
3574void WebRtcVideoMediaChannel::QueueBlackFrame(uint32 ssrc, int64 timestamp,
3575 int framerate) {
3576 if (timestamp) {
3577 FlushBlackFrameData* black_frame_data = new FlushBlackFrameData(
3578 ssrc,
3579 timestamp);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003580 const int delay_ms = static_cast<int>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003581 2 * cricket::VideoFormat::FpsToInterval(framerate) *
3582 talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
3583 worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
3584 }
3585}
3586
3587void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
3588 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
3589 if (!send_channel) {
3590 return;
3591 }
3592 talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
3593
3594 const WebRtcLocalStreamInfo* channel_stream_info =
3595 send_channel->local_stream_info();
3596 int64 last_frame_time_stamp = channel_stream_info->time_stamp();
3597 if (last_frame_time_stamp == timestamp) {
3598 size_t last_frame_width = 0;
3599 size_t last_frame_height = 0;
3600 int64 last_frame_elapsed_time = 0;
3601 channel_stream_info->GetLastFrameInfo(&last_frame_width, &last_frame_height,
3602 &last_frame_elapsed_time);
3603 if (!last_frame_width || !last_frame_height) {
3604 return;
3605 }
3606 WebRtcVideoFrame black_frame;
3607 // Black frame is not screencast.
3608 const bool screencasting = false;
3609 const int64 timestamp_delta = send_channel->interval();
3610 if (!black_frame.InitToBlack(send_codec_->width, send_codec_->height, 1, 1,
3611 last_frame_elapsed_time + timestamp_delta,
3612 last_frame_time_stamp + timestamp_delta) ||
3613 !SendFrame(send_channel, &black_frame, screencasting)) {
3614 LOG(LS_ERROR) << "Failed to send black frame.";
3615 }
3616 }
3617}
3618
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003619void WebRtcVideoMediaChannel::OnCpuAdaptationUnable() {
3620 // ssrc is hardcoded to 0. This message is based on a system wide issue,
3621 // so finding which ssrc caused it doesn't matter.
3622 SignalMediaError(0, VideoMediaChannel::ERROR_REC_CPU_MAX_CANT_DOWNGRADE);
3623}
3624
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003625void WebRtcVideoMediaChannel::SetNetworkTransmissionState(
3626 bool is_transmitting) {
3627 LOG(LS_INFO) << "SetNetworkTransmissionState: " << is_transmitting;
3628 for (SendChannelMap::iterator iter = send_channels_.begin();
3629 iter != send_channels_.end(); ++iter) {
3630 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3631 int channel_id = send_channel->channel_id();
3632 engine_->vie()->network()->SetNetworkTransmissionState(channel_id,
3633 is_transmitting);
3634 }
3635}
3636
3637bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3638 int channel_id, const RtpHeaderExtension* extension) {
3639 bool enable = false;
3640 int id = 0;
3641 if (extension) {
3642 enable = true;
3643 id = extension->id;
3644 }
3645 if ((engine_->vie()->rtp()->*setter)(channel_id, enable, id) != 0) {
3646 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
3647 return false;
3648 }
3649 return true;
3650}
3651
3652bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3653 int channel_id, const std::vector<RtpHeaderExtension>& extensions,
3654 const char header_extension_uri[]) {
3655 const RtpHeaderExtension* extension = FindHeaderExtension(extensions,
3656 header_extension_uri);
3657 return SetHeaderExtension(setter, channel_id, extension);
3658}
3659} // namespace cricket
3660
3661#endif // HAVE_WEBRTC_VIDEO