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