blob: 385b19e6d21e5a416705eae6e2d249463d2a3b46 [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
wu@webrtc.orgde305012013-10-31 15:40:38 +0000149// Default video dscp value.
150// See http://tools.ietf.org/html/rfc2474 for details
151// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
152static const talk_base::DiffServCodePoint kVideoDscpValue =
153 talk_base::DSCP_AF41;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154
155static bool IsNackEnabled(const VideoCodec& codec) {
156 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
157 kParamValueEmpty));
158}
159
160// Returns true if Receiver Estimated Max Bitrate is enabled.
161static bool IsRembEnabled(const VideoCodec& codec) {
162 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamRemb,
163 kParamValueEmpty));
164}
165
166struct FlushBlackFrameData : public talk_base::MessageData {
167 FlushBlackFrameData(uint32 s, int64 t) : ssrc(s), timestamp(t) {
168 }
169 uint32 ssrc;
170 int64 timestamp;
171};
172
173class WebRtcRenderAdapter : public webrtc::ExternalRenderer {
174 public:
175 explicit WebRtcRenderAdapter(VideoRenderer* renderer)
henrike@webrtc.orge9793ab2014-03-18 14:36:23 +0000176 : renderer_(renderer), width_(0), height_(0) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000178
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000179 virtual ~WebRtcRenderAdapter() {
180 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000181
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 void SetRenderer(VideoRenderer* renderer) {
183 talk_base::CritScope cs(&crit_);
184 renderer_ = renderer;
185 // FrameSizeChange may have already been called when renderer was not set.
186 // If so we should call SetSize here.
187 // TODO(ronghuawu): Add unit test for this case. Didn't do it now
188 // because the WebRtcRenderAdapter is currently hiding in cc file. No
189 // good way to get access to it from the unit test.
190 if (width_ > 0 && height_ > 0 && renderer_ != NULL) {
191 if (!renderer_->SetSize(width_, height_, 0)) {
192 LOG(LS_ERROR)
193 << "WebRtcRenderAdapter SetRenderer failed to SetSize to: "
194 << width_ << "x" << height_;
195 }
196 }
197 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000198
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000199 // Implementation of webrtc::ExternalRenderer.
200 virtual int FrameSizeChange(unsigned int width, unsigned int height,
201 unsigned int /*number_of_streams*/) {
202 talk_base::CritScope cs(&crit_);
203 width_ = width;
204 height_ = height;
205 LOG(LS_INFO) << "WebRtcRenderAdapter frame size changed to: "
206 << width << "x" << height;
207 if (renderer_ == NULL) {
208 LOG(LS_VERBOSE) << "WebRtcRenderAdapter the renderer has not been set. "
209 << "SetSize will be called later in SetRenderer.";
210 return 0;
211 }
212 return renderer_->SetSize(width_, height_, 0) ? 0 : -1;
213 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000214
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 virtual int DeliverFrame(unsigned char* buffer, int buffer_size,
wu@webrtc.org9caf2762013-12-11 18:25:07 +0000216 uint32_t time_stamp, int64_t render_time,
217 void* handle) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218 talk_base::CritScope cs(&crit_);
219 frame_rate_tracker_.Update(1);
220 if (renderer_ == NULL) {
221 return 0;
222 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000223 // Convert 90K rtp timestamp to ns timestamp.
224 int64 rtp_time_stamp_in_ns = (time_stamp / 90) *
225 talk_base::kNumNanosecsPerMillisec;
226 // Convert milisecond render time to ns timestamp.
227 int64 render_time_stamp_in_ns = render_time *
228 talk_base::kNumNanosecsPerMillisec;
229 // Send the rtp timestamp to renderer as the VideoFrame timestamp.
230 // and the render timestamp as the VideoFrame elapsed_time.
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000231 if (handle == NULL) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000232 return DeliverBufferFrame(buffer, buffer_size, render_time_stamp_in_ns,
233 rtp_time_stamp_in_ns);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000234 } else {
235 return DeliverTextureFrame(handle, render_time_stamp_in_ns,
236 rtp_time_stamp_in_ns);
237 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000238 }
239
240 virtual bool IsTextureSupported() { return true; }
241
242 int DeliverBufferFrame(unsigned char* buffer, int buffer_size,
243 int64 elapsed_time, int64 time_stamp) {
244 WebRtcVideoFrame video_frame;
wu@webrtc.org16d62542013-11-05 23:45:14 +0000245 video_frame.Alias(buffer, buffer_size, width_, height_,
246 1, 1, elapsed_time, time_stamp, 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248 // Sanity check on decoded frame size.
249 if (buffer_size != static_cast<int>(VideoFrame::SizeOf(width_, height_))) {
250 LOG(LS_WARNING) << "WebRtcRenderAdapter received a strange frame size: "
251 << buffer_size;
252 }
253
254 int ret = renderer_->RenderFrame(&video_frame) ? 0 : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255 return ret;
256 }
257
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000258 int DeliverTextureFrame(void* handle, int64 elapsed_time, int64 time_stamp) {
259 WebRtcTextureVideoFrame video_frame(
260 static_cast<webrtc::NativeHandle*>(handle), width_, height_,
261 elapsed_time, time_stamp);
262 return renderer_->RenderFrame(&video_frame);
263 }
264
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000265 unsigned int width() {
266 talk_base::CritScope cs(&crit_);
267 return width_;
268 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000269
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 unsigned int height() {
271 talk_base::CritScope cs(&crit_);
272 return height_;
273 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000274
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 int framerate() {
276 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000277 return static_cast<int>(frame_rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000278 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000279
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000280 VideoRenderer* renderer() {
281 talk_base::CritScope cs(&crit_);
282 return renderer_;
283 }
284
285 private:
286 talk_base::CriticalSection crit_;
287 VideoRenderer* renderer_;
288 unsigned int width_;
289 unsigned int height_;
290 talk_base::RateTracker frame_rate_tracker_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000291};
292
293class WebRtcDecoderObserver : public webrtc::ViEDecoderObserver {
294 public:
295 explicit WebRtcDecoderObserver(int video_channel)
296 : video_channel_(video_channel),
297 framerate_(0),
298 bitrate_(0),
wu@webrtc.org97077a32013-10-25 21:18:33 +0000299 decode_ms_(0),
300 max_decode_ms_(0),
301 current_delay_ms_(0),
302 target_delay_ms_(0),
303 jitter_buffer_ms_(0),
304 min_playout_delay_ms_(0),
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000305 render_delay_ms_(0) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000306 }
307
308 // virtual functions from VieDecoderObserver.
309 virtual void IncomingCodecChanged(const int videoChannel,
310 const webrtc::VideoCodec& videoCodec) {}
311 virtual void IncomingRate(const int videoChannel,
312 const unsigned int framerate,
313 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000314 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000315 ASSERT(video_channel_ == videoChannel);
316 framerate_ = framerate;
317 bitrate_ = bitrate;
318 }
wu@webrtc.org97077a32013-10-25 21:18:33 +0000319
320 virtual void DecoderTiming(int decode_ms,
321 int max_decode_ms,
322 int current_delay_ms,
323 int target_delay_ms,
324 int jitter_buffer_ms,
325 int min_playout_delay_ms,
326 int render_delay_ms) {
327 talk_base::CritScope cs(&crit_);
328 decode_ms_ = decode_ms;
329 max_decode_ms_ = max_decode_ms;
330 current_delay_ms_ = current_delay_ms;
331 target_delay_ms_ = target_delay_ms;
332 jitter_buffer_ms_ = jitter_buffer_ms;
333 min_playout_delay_ms_ = min_playout_delay_ms;
334 render_delay_ms_ = render_delay_ms;
335 }
336
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000337 virtual void RequestNewKeyFrame(const int videoChannel) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338
wu@webrtc.org97077a32013-10-25 21:18:33 +0000339 // Populate |rinfo| based on previously-set data in |*this|.
340 void ExportTo(VideoReceiverInfo* rinfo) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000341 talk_base::CritScope cs(&crit_);
wu@webrtc.org97077a32013-10-25 21:18:33 +0000342 rinfo->framerate_rcvd = framerate_;
343 rinfo->decode_ms = decode_ms_;
344 rinfo->max_decode_ms = max_decode_ms_;
345 rinfo->current_delay_ms = current_delay_ms_;
346 rinfo->target_delay_ms = target_delay_ms_;
347 rinfo->jitter_buffer_ms = jitter_buffer_ms_;
348 rinfo->min_playout_delay_ms = min_playout_delay_ms_;
349 rinfo->render_delay_ms = render_delay_ms_;
wu@webrtc.org78187522013-10-07 23:32:02 +0000350 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000351
352 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000353 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 int video_channel_;
355 int framerate_;
356 int bitrate_;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000357 int decode_ms_;
358 int max_decode_ms_;
359 int current_delay_ms_;
360 int target_delay_ms_;
361 int jitter_buffer_ms_;
362 int min_playout_delay_ms_;
363 int render_delay_ms_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000364};
365
366class WebRtcEncoderObserver : public webrtc::ViEEncoderObserver {
367 public:
368 explicit WebRtcEncoderObserver(int video_channel)
369 : video_channel_(video_channel),
370 framerate_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000371 bitrate_(0),
372 suspended_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000373 }
374
375 // virtual functions from VieEncoderObserver.
376 virtual void OutgoingRate(const int videoChannel,
377 const unsigned int framerate,
378 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000379 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000380 ASSERT(video_channel_ == videoChannel);
381 framerate_ = framerate;
382 bitrate_ = bitrate;
383 }
384
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000385 virtual void SuspendChange(int video_channel, bool is_suspended) {
386 talk_base::CritScope cs(&crit_);
387 ASSERT(video_channel_ == video_channel);
388 suspended_ = is_suspended;
389 }
390
wu@webrtc.org78187522013-10-07 23:32:02 +0000391 int framerate() const {
392 talk_base::CritScope cs(&crit_);
393 return framerate_;
394 }
395 int bitrate() const {
396 talk_base::CritScope cs(&crit_);
397 return bitrate_;
398 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000399 bool suspended() const {
400 talk_base::CritScope cs(&crit_);
401 return suspended_;
402 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403
404 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000405 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406 int video_channel_;
407 int framerate_;
408 int bitrate_;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000409 bool suspended_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000410};
411
412class WebRtcLocalStreamInfo {
413 public:
414 WebRtcLocalStreamInfo()
415 : width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
416 size_t width() const {
417 talk_base::CritScope cs(&crit_);
418 return width_;
419 }
420 size_t height() const {
421 talk_base::CritScope cs(&crit_);
422 return height_;
423 }
424 int64 elapsed_time() const {
425 talk_base::CritScope cs(&crit_);
426 return elapsed_time_;
427 }
428 int64 time_stamp() const {
429 talk_base::CritScope cs(&crit_);
430 return time_stamp_;
431 }
432 int framerate() {
433 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000434 return static_cast<int>(rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000435 }
436 void GetLastFrameInfo(
437 size_t* width, size_t* height, int64* elapsed_time) const {
438 talk_base::CritScope cs(&crit_);
439 *width = width_;
440 *height = height_;
441 *elapsed_time = elapsed_time_;
442 }
443
444 void UpdateFrame(const VideoFrame* frame) {
445 talk_base::CritScope cs(&crit_);
446
447 width_ = frame->GetWidth();
448 height_ = frame->GetHeight();
449 elapsed_time_ = frame->GetElapsedTime();
450 time_stamp_ = frame->GetTimeStamp();
451
452 rate_tracker_.Update(1);
453 }
454
455 private:
456 mutable talk_base::CriticalSection crit_;
457 size_t width_;
458 size_t height_;
459 int64 elapsed_time_;
460 int64 time_stamp_;
461 talk_base::RateTracker rate_tracker_;
462
463 DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
464};
465
466// WebRtcVideoChannelRecvInfo is a container class with members such as renderer
467// and a decoder observer that is used by receive channels.
468// It must exist as long as the receive channel is connected to renderer or a
469// decoder observer in this class and methods in the class should only be called
470// from the worker thread.
471class WebRtcVideoChannelRecvInfo {
472 public:
473 typedef std::map<int, webrtc::VideoDecoder*> DecoderMap; // key: payload type
474 explicit WebRtcVideoChannelRecvInfo(int channel_id)
475 : channel_id_(channel_id),
476 render_adapter_(NULL),
477 decoder_observer_(channel_id) {
478 }
479 int channel_id() { return channel_id_; }
480 void SetRenderer(VideoRenderer* renderer) {
481 render_adapter_.SetRenderer(renderer);
482 }
483 WebRtcRenderAdapter* render_adapter() { return &render_adapter_; }
484 WebRtcDecoderObserver* decoder_observer() { return &decoder_observer_; }
485 void RegisterDecoder(int pl_type, webrtc::VideoDecoder* decoder) {
486 ASSERT(!IsDecoderRegistered(pl_type));
487 registered_decoders_[pl_type] = decoder;
488 }
489 bool IsDecoderRegistered(int pl_type) {
490 return registered_decoders_.count(pl_type) != 0;
491 }
492 const DecoderMap& registered_decoders() {
493 return registered_decoders_;
494 }
495 void ClearRegisteredDecoders() {
496 registered_decoders_.clear();
497 }
498
499 private:
500 int channel_id_; // Webrtc video channel number.
501 // Renderer for this channel.
502 WebRtcRenderAdapter render_adapter_;
503 WebRtcDecoderObserver decoder_observer_;
504 DecoderMap registered_decoders_;
505};
506
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000507class WebRtcOveruseObserver : public webrtc::CpuOveruseObserver {
508 public:
509 explicit WebRtcOveruseObserver(CoordinatedVideoAdapter* video_adapter)
510 : video_adapter_(video_adapter),
511 enabled_(false) {
512 }
513
514 // TODO(mflodman): Consider sending resolution as part of event, to let
515 // adapter know what resolution the request is based on. Helps eliminate stale
516 // data, race conditions.
517 virtual void OveruseDetected() OVERRIDE {
518 talk_base::CritScope cs(&crit_);
519 if (!enabled_) {
520 return;
521 }
522
523 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
524 }
525
526 virtual void NormalUsage() OVERRIDE {
527 talk_base::CritScope cs(&crit_);
528 if (!enabled_) {
529 return;
530 }
531
532 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::UPGRADE);
533 }
534
535 void Enable(bool enable) {
536 talk_base::CritScope cs(&crit_);
537 enabled_ = enable;
538 }
539
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000540 bool enabled() const { return enabled_; }
541
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000542 private:
543 CoordinatedVideoAdapter* video_adapter_;
544 bool enabled_;
545 talk_base::CriticalSection crit_;
546};
547
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000548
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000549class WebRtcVideoChannelSendInfo : public sigslot::has_slots<> {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000550 public:
551 typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
552 WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
553 webrtc::ViEExternalCapture* external_capture,
554 talk_base::CpuMonitor* cpu_monitor)
555 : channel_id_(channel_id),
556 capture_id_(capture_id),
557 sending_(false),
558 muted_(false),
559 video_capturer_(NULL),
560 encoder_observer_(channel_id),
561 external_capture_(external_capture),
562 capturer_updated_(false),
563 interval_(0),
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000564 cpu_monitor_(cpu_monitor),
565 overuse_observer_enabled_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000566 }
567
568 int channel_id() const { return channel_id_; }
569 int capture_id() const { return capture_id_; }
570 void set_sending(bool sending) { sending_ = sending; }
571 bool sending() const { return sending_; }
572 void set_muted(bool on) {
573 // TODO(asapersson): add support.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000574 // video_adapter_.SetBlackOutput(on);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575 muted_ = on;
576 }
577 bool muted() {return muted_; }
578
579 WebRtcEncoderObserver* encoder_observer() { return &encoder_observer_; }
580 webrtc::ViEExternalCapture* external_capture() { return external_capture_; }
581 const VideoFormat& video_format() const {
582 return video_format_;
583 }
584 void set_video_format(const VideoFormat& video_format) {
585 video_format_ = video_format;
586 if (video_format_ != cricket::VideoFormat()) {
587 interval_ = video_format_.interval;
588 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000589 CoordinatedVideoAdapter* adapter = video_adapter();
590 if (adapter) {
591 adapter->OnOutputFormatRequest(video_format_);
592 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 }
594 void set_interval(int64 interval) {
595 if (video_format() == cricket::VideoFormat()) {
596 interval_ = interval;
597 }
598 }
599 int64 interval() { return interval_; }
600
xians@webrtc.orgef221512014-02-21 10:31:29 +0000601 int CurrentAdaptReason() const {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000602 const CoordinatedVideoAdapter* adapter = video_adapter();
603 if (!adapter) {
604 return CoordinatedVideoAdapter::ADAPTREASON_NONE;
605 }
606 return video_adapter()->adapt_reason();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000607 }
608
609 StreamParams* stream_params() { return stream_params_.get(); }
610 void set_stream_params(const StreamParams& sp) {
611 stream_params_.reset(new StreamParams(sp));
612 }
613 void ClearStreamParams() { stream_params_.reset(); }
614 bool has_ssrc(uint32 local_ssrc) const {
615 return !stream_params_ ? false :
616 stream_params_->has_ssrc(local_ssrc);
617 }
618 WebRtcLocalStreamInfo* local_stream_info() {
619 return &local_stream_info_;
620 }
621 VideoCapturer* video_capturer() {
622 return video_capturer_;
623 }
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +0000624 void set_video_capturer(VideoCapturer* video_capturer,
625 ViEWrapper* vie_wrapper) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 if (video_capturer == video_capturer_) {
627 return;
628 }
xians@webrtc.orgef221512014-02-21 10:31:29 +0000629
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000630 CoordinatedVideoAdapter* old_video_adapter = video_adapter();
631 if (old_video_adapter) {
632 // Disconnect signals from old video adapter.
633 SignalCpuAdaptationUnable.disconnect(old_video_adapter);
634 if (cpu_monitor_) {
635 cpu_monitor_->SignalUpdate.disconnect(old_video_adapter);
xians@webrtc.orgef221512014-02-21 10:31:29 +0000636 }
henrike@webrtc.org26438052014-02-20 22:32:53 +0000637 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000638
639 capturer_updated_ = true;
640 video_capturer_ = video_capturer;
641
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +0000642 vie_wrapper->base()->RegisterCpuOveruseObserver(channel_id_, NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000643 if (!video_capturer) {
644 overuse_observer_.reset();
645 return;
646 }
647
648 CoordinatedVideoAdapter* adapter = video_adapter();
649 ASSERT(adapter && "Video adapter should not be null here.");
650
651 UpdateAdapterCpuOptions();
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000652
653 overuse_observer_.reset(new WebRtcOveruseObserver(adapter));
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +0000654 vie_wrapper->base()->RegisterCpuOveruseObserver(channel_id_,
655 overuse_observer_.get());
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000656 // (Dis)connect the video adapter from the cpu monitor as appropriate.
657 SetCpuOveruseDetection(overuse_observer_enabled_);
658
659 SignalCpuAdaptationUnable.repeat(adapter->SignalCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000660 }
661
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000662 CoordinatedVideoAdapter* video_adapter() {
663 if (!video_capturer_) {
664 return NULL;
665 }
666 return video_capturer_->video_adapter();
667 }
668 const CoordinatedVideoAdapter* video_adapter() const {
669 if (!video_capturer_) {
670 return NULL;
671 }
672 return video_capturer_->video_adapter();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000673 }
674
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000675 void ApplyCpuOptions(const VideoOptions& video_options) {
676 // Use video_options_.SetAll() instead of assignment so that unset value in
677 // video_options will not overwrite the previous option value.
678 video_options_.SetAll(video_options);
679 UpdateAdapterCpuOptions();
680 }
681
682 void UpdateAdapterCpuOptions() {
683 if (!video_capturer_) {
684 return;
685 }
686
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000687 bool cpu_adapt, cpu_smoothing, adapt_third;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688 float low, med, high;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000689
690 // TODO(thorcarpenter): Have VideoAdapter be responsible for setting
691 // all these video options.
692 CoordinatedVideoAdapter* video_adapter = video_capturer_->video_adapter();
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000693 if (video_options_.adapt_input_to_cpu_usage.Get(&cpu_adapt) ||
694 overuse_observer_enabled_) {
695 video_adapter->set_cpu_adaptation(cpu_adapt || overuse_observer_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000697 if (video_options_.adapt_cpu_with_smoothing.Get(&cpu_smoothing)) {
698 video_adapter->set_cpu_smoothing(cpu_smoothing);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000699 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000700 if (video_options_.process_adaptation_threshhold.Get(&med)) {
701 video_adapter->set_process_threshold(med);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000703 if (video_options_.system_low_adaptation_threshhold.Get(&low)) {
704 video_adapter->set_low_system_threshold(low);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000706 if (video_options_.system_high_adaptation_threshhold.Get(&high)) {
707 video_adapter->set_high_system_threshold(high);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000709 if (video_options_.video_adapt_third.Get(&adapt_third)) {
710 video_adapter->set_scale_third(adapt_third);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000713
714 void SetCpuOveruseDetection(bool enable) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000715 overuse_observer_enabled_ = enable;
716
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000717 if (overuse_observer_) {
718 overuse_observer_->Enable(enable);
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000719 }
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000720
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000721 // The video adapter is signaled by overuse detection if enabled; otherwise
722 // it will be signaled by cpu monitor.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000723 CoordinatedVideoAdapter* adapter = video_adapter();
724 if (adapter) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000725 bool cpu_adapt = false;
726 video_options_.adapt_input_to_cpu_usage.Get(&cpu_adapt);
727 adapter->set_cpu_adaptation(
728 adapter->cpu_adaptation() || cpu_adapt || enable);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000729 if (cpu_monitor_) {
730 if (enable) {
731 cpu_monitor_->SignalUpdate.disconnect(adapter);
732 } else {
733 cpu_monitor_->SignalUpdate.connect(
734 adapter, &CoordinatedVideoAdapter::OnCpuLoadUpdated);
735 }
736 }
737 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000738 }
739
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740 void ProcessFrame(const VideoFrame& original_frame, bool mute,
741 VideoFrame** processed_frame) {
742 if (!mute) {
743 *processed_frame = original_frame.Copy();
744 } else {
745 WebRtcVideoFrame* black_frame = new WebRtcVideoFrame();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000746 black_frame->InitToBlack(static_cast<int>(original_frame.GetWidth()),
747 static_cast<int>(original_frame.GetHeight()),
748 1, 1,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 original_frame.GetElapsedTime(),
750 original_frame.GetTimeStamp());
751 *processed_frame = black_frame;
752 }
753 local_stream_info_.UpdateFrame(*processed_frame);
754 }
755 void RegisterEncoder(int pl_type, webrtc::VideoEncoder* encoder) {
756 ASSERT(!IsEncoderRegistered(pl_type));
757 registered_encoders_[pl_type] = encoder;
758 }
759 bool IsEncoderRegistered(int pl_type) {
760 return registered_encoders_.count(pl_type) != 0;
761 }
762 const EncoderMap& registered_encoders() {
763 return registered_encoders_;
764 }
765 void ClearRegisteredEncoders() {
766 registered_encoders_.clear();
767 }
768
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000769 sigslot::repeater0<> SignalCpuAdaptationUnable;
770
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771 private:
772 int channel_id_;
773 int capture_id_;
774 bool sending_;
775 bool muted_;
776 VideoCapturer* video_capturer_;
777 WebRtcEncoderObserver encoder_observer_;
778 webrtc::ViEExternalCapture* external_capture_;
779 EncoderMap registered_encoders_;
780
781 VideoFormat video_format_;
782
783 talk_base::scoped_ptr<StreamParams> stream_params_;
784
785 WebRtcLocalStreamInfo local_stream_info_;
786
787 bool capturer_updated_;
788
789 int64 interval_;
790
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000791 talk_base::CpuMonitor* cpu_monitor_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000792 talk_base::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +0000793 bool overuse_observer_enabled_;
794
795 VideoOptions video_options_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796};
797
798const WebRtcVideoEngine::VideoCodecPref
799 WebRtcVideoEngine::kVideoCodecPrefs[] = {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000800 {kVp8PayloadName, 100, -1, 0},
801 {kRedPayloadName, 116, -1, 1},
802 {kFecPayloadName, 117, -1, 2},
803 {kRtxCodecName, 96, 100, 3},
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804};
805
806// The formats are sorted by the descending order of width. We use the order to
807// find the next format for CPU and bandwidth adaptation.
808const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
809 {1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
810 {1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
811 {960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
812 {960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
813 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
814 {640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
815 {640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
816 {480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
817 {480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
818 {480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
819 {320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
820 {320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
821 {320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
822 {240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
823 {240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
824 {240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
825 {160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
826 {160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
827 {160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
828};
829
830const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
831 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
832
833static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
834 webrtc::VideoCodec* target_codec) {
835 if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
836 return;
837 }
838 target_codec->width = video_format.width;
839 target_codec->height = video_format.height;
840 target_codec->maxFramerate = cricket::VideoFormat::IntervalToFps(
841 video_format.interval);
842}
843
844WebRtcVideoEngine::WebRtcVideoEngine() {
845 Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
846 new talk_base::CpuMonitor(NULL));
847}
848
849WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
850 ViEWrapper* vie_wrapper,
851 talk_base::CpuMonitor* cpu_monitor) {
852 Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
853}
854
855WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
856 ViEWrapper* vie_wrapper,
857 ViETraceWrapper* tracing,
858 talk_base::CpuMonitor* cpu_monitor) {
859 Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
860}
861
862void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
863 ViETraceWrapper* tracing,
864 WebRtcVoiceEngine* voice_engine,
865 talk_base::CpuMonitor* cpu_monitor) {
866 LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
867 worker_thread_ = NULL;
868 vie_wrapper_.reset(vie_wrapper);
869 vie_wrapper_base_initialized_ = false;
870 tracing_.reset(tracing);
871 voice_engine_ = voice_engine;
872 initialized_ = false;
873 SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
874 render_module_.reset(new WebRtcPassthroughRender());
875 local_renderer_w_ = local_renderer_h_ = 0;
876 local_renderer_ = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877 capture_started_ = false;
878 decoder_factory_ = NULL;
879 encoder_factory_ = NULL;
880 cpu_monitor_.reset(cpu_monitor);
881
882 SetTraceOptions("");
883 if (tracing_->SetTraceCallback(this) != 0) {
884 LOG_RTCERR1(SetTraceCallback, this);
885 }
886
887 // Set default quality levels for our supported codecs. We override them here
888 // if we know your cpu performance is low, and they can be updated explicitly
889 // by calling SetDefaultCodec. For example by a flute preference setting, or
890 // by the server with a jec in response to our reported system info.
891 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
892 kVideoCodecPrefs[0].name,
893 kDefaultVideoFormat.width,
894 kDefaultVideoFormat.height,
895 VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
896 0);
897 if (!SetDefaultCodec(max_codec)) {
898 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
899 }
900
901
902 // Load our RTP Header extensions.
903 rtp_header_extensions_.push_back(
904 RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
henrike@webrtc.org79047f92014-03-06 23:46:59 +0000905 kRtpTimestampOffsetHeaderExtensionDefaultId));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 rtp_header_extensions_.push_back(
henrike@webrtc.org79047f92014-03-06 23:46:59 +0000907 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
908 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909}
910
911WebRtcVideoEngine::~WebRtcVideoEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912 LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
913 if (initialized_) {
914 Terminate();
915 }
916 if (encoder_factory_) {
917 encoder_factory_->RemoveObserver(this);
918 }
919 tracing_->SetTraceCallback(NULL);
920 // Test to see if the media processor was deregistered properly.
921 ASSERT(SignalMediaFrame.is_empty());
922}
923
924bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
925 LOG(LS_INFO) << "WebRtcVideoEngine::Init";
926 worker_thread_ = worker_thread;
927 ASSERT(worker_thread_ != NULL);
928
929 cpu_monitor_->set_thread(worker_thread_);
930 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
931 LOG(LS_ERROR) << "Failed to start CPU monitor.";
932 cpu_monitor_.reset();
933 }
934
935 bool result = InitVideoEngine();
936 if (result) {
937 LOG(LS_INFO) << "VideoEngine Init done";
938 } else {
939 LOG(LS_ERROR) << "VideoEngine Init failed, releasing";
940 Terminate();
941 }
942 return result;
943}
944
945bool WebRtcVideoEngine::InitVideoEngine() {
946 LOG(LS_INFO) << "WebRtcVideoEngine::InitVideoEngine";
947
948 // Init WebRTC VideoEngine.
949 if (!vie_wrapper_base_initialized_) {
950 if (vie_wrapper_->base()->Init() != 0) {
951 LOG_RTCERR0(Init);
952 return false;
953 }
954 vie_wrapper_base_initialized_ = true;
955 }
956
957 // Log the VoiceEngine version info.
958 char buffer[1024] = "";
959 if (vie_wrapper_->base()->GetVersion(buffer) != 0) {
960 LOG_RTCERR0(GetVersion);
961 return false;
962 }
963
964 LOG(LS_INFO) << "WebRtc VideoEngine Version:";
965 LogMultiline(talk_base::LS_INFO, buffer);
966
967 // Hook up to VoiceEngine for sync purposes, if supplied.
968 if (!voice_engine_) {
969 LOG(LS_WARNING) << "NULL voice engine";
970 } else if ((vie_wrapper_->base()->SetVoiceEngine(
971 voice_engine_->voe()->engine())) != 0) {
972 LOG_RTCERR0(SetVoiceEngine);
973 return false;
974 }
975
976 // Register our custom render module.
977 if (vie_wrapper_->render()->RegisterVideoRenderModule(
978 *render_module_.get()) != 0) {
979 LOG_RTCERR0(RegisterVideoRenderModule);
980 return false;
981 }
982
983 initialized_ = true;
984 return true;
985}
986
987void WebRtcVideoEngine::Terminate() {
988 LOG(LS_INFO) << "WebRtcVideoEngine::Terminate";
989 initialized_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990
991 if (vie_wrapper_->render()->DeRegisterVideoRenderModule(
992 *render_module_.get()) != 0) {
993 LOG_RTCERR0(DeRegisterVideoRenderModule);
994 }
995
996 if (vie_wrapper_->base()->SetVoiceEngine(NULL) != 0) {
997 LOG_RTCERR0(SetVoiceEngine);
998 }
999
1000 cpu_monitor_->Stop();
1001}
1002
1003int WebRtcVideoEngine::GetCapabilities() {
1004 return VIDEO_RECV | VIDEO_SEND;
1005}
1006
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001007bool WebRtcVideoEngine::SetOptions(const VideoOptions &options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001008 return true;
1009}
1010
1011bool WebRtcVideoEngine::SetDefaultEncoderConfig(
1012 const VideoEncoderConfig& config) {
1013 return SetDefaultCodec(config.max_codec);
1014}
1015
wu@webrtc.org78187522013-10-07 23:32:02 +00001016VideoEncoderConfig WebRtcVideoEngine::GetDefaultEncoderConfig() const {
1017 ASSERT(!video_codecs_.empty());
1018 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1019 kVideoCodecPrefs[0].name,
1020 video_codecs_[0].width,
1021 video_codecs_[0].height,
1022 video_codecs_[0].framerate,
1023 0);
1024 return VideoEncoderConfig(max_codec);
1025}
1026
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027// SetDefaultCodec may be called while the capturer is running. For example, a
1028// test call is started in a page with QVGA default codec, and then a real call
1029// is started in another page with VGA default codec. This is the corner case
1030// and happens only when a session is started. We ignore this case currently.
1031bool WebRtcVideoEngine::SetDefaultCodec(const VideoCodec& codec) {
1032 if (!RebuildCodecList(codec)) {
1033 LOG(LS_WARNING) << "Failed to RebuildCodecList";
1034 return false;
1035 }
1036
wu@webrtc.org78187522013-10-07 23:32:02 +00001037 ASSERT(!video_codecs_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 default_codec_format_ = VideoFormat(
1039 video_codecs_[0].width,
1040 video_codecs_[0].height,
1041 VideoFormat::FpsToInterval(video_codecs_[0].framerate),
1042 FOURCC_ANY);
1043 return true;
1044}
1045
1046WebRtcVideoMediaChannel* WebRtcVideoEngine::CreateChannel(
1047 VoiceMediaChannel* voice_channel) {
1048 WebRtcVideoMediaChannel* channel =
1049 new WebRtcVideoMediaChannel(this, voice_channel);
1050 if (!channel->Init()) {
1051 delete channel;
1052 channel = NULL;
1053 }
1054 return channel;
1055}
1056
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
1058 local_renderer_w_ = local_renderer_h_ = 0;
1059 local_renderer_ = renderer;
1060 return true;
1061}
1062
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
1064 return video_codecs_;
1065}
1066
1067const std::vector<RtpHeaderExtension>&
1068WebRtcVideoEngine::rtp_header_extensions() const {
1069 return rtp_header_extensions_;
1070}
1071
1072void WebRtcVideoEngine::SetLogging(int min_sev, const char* filter) {
1073 // if min_sev == -1, we keep the current log level.
1074 if (min_sev >= 0) {
1075 SetTraceFilter(SeverityToFilter(min_sev));
1076 }
1077 SetTraceOptions(filter);
1078}
1079
1080int WebRtcVideoEngine::GetLastEngineError() {
1081 return vie_wrapper_->error();
1082}
1083
1084// Checks to see whether we comprehend and could receive a particular codec
1085bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
1086 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
1087 const VideoFormat fmt(kVideoFormats[i]);
1088 if ((in.width == 0 && in.height == 0) ||
1089 (fmt.width == in.width && fmt.height == in.height)) {
1090 if (encoder_factory_) {
1091 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1092 encoder_factory_->codecs();
1093 for (size_t j = 0; j < codecs.size(); ++j) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001094 VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 codecs[j].name, 0, 0, 0, 0);
1096 if (codec.Matches(in))
1097 return true;
1098 }
1099 }
1100 for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
1101 VideoCodec codec(kVideoCodecPrefs[j].payload_type,
1102 kVideoCodecPrefs[j].name, 0, 0, 0, 0);
1103 if (codec.Matches(in)) {
1104 return true;
1105 }
1106 }
1107 }
1108 }
1109 return false;
1110}
1111
1112// Given the requested codec, returns true if we can send that codec type and
1113// updates out with the best quality we could send for that codec. If current is
1114// not empty, we constrain out so that its aspect ratio matches current's.
1115bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
1116 const VideoCodec& current,
1117 VideoCodec* out) {
1118 if (!out) {
1119 return false;
1120 }
1121
1122 std::vector<VideoCodec>::const_iterator local_max;
1123 for (local_max = video_codecs_.begin();
1124 local_max < video_codecs_.end();
1125 ++local_max) {
1126 // First match codecs by payload type
1127 if (!requested.Matches(*local_max)) {
1128 continue;
1129 }
1130
1131 out->id = requested.id;
1132 out->name = requested.name;
1133 out->preference = requested.preference;
1134 out->params = requested.params;
1135 out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
1136 out->width = 0;
1137 out->height = 0;
1138 out->params = requested.params;
1139 out->feedback_params = requested.feedback_params;
1140
1141 if (0 == requested.width && 0 == requested.height) {
1142 // Special case with resolution 0. The channel should not send frames.
1143 return true;
1144 } else if (0 == requested.width || 0 == requested.height) {
1145 // 0xn and nx0 are invalid resolutions.
1146 return false;
1147 }
1148
1149 // Pick the best quality that is within their and our bounds and has the
1150 // correct aspect ratio.
1151 for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
1152 const VideoFormat format(kVideoFormats[j]);
1153
1154 // Skip any format that is larger than the local or remote maximums, or
1155 // smaller than the current best match
1156 if (format.width > requested.width || format.height > requested.height ||
1157 format.width > local_max->width ||
1158 (format.width < out->width && format.height < out->height)) {
1159 continue;
1160 }
1161
1162 bool better = false;
1163
1164 // Check any further constraints on this prospective format
1165 if (!out->width || !out->height) {
1166 // If we don't have any matches yet, this is the best so far.
1167 better = true;
1168 } else if (current.width && current.height) {
1169 // current is set so format must match its ratio exactly.
1170 better =
1171 (format.width * current.height == format.height * current.width);
1172 } else {
1173 // Prefer closer aspect ratios i.e
1174 // format.aspect - requested.aspect < out.aspect - requested.aspect
1175 better = abs(format.width * requested.height * out->height -
1176 requested.width * format.height * out->height) <
1177 abs(out->width * format.height * requested.height -
1178 requested.width * format.height * out->height);
1179 }
1180
1181 if (better) {
1182 out->width = format.width;
1183 out->height = format.height;
1184 }
1185 }
1186 if (out->width > 0) {
1187 return true;
1188 }
1189 }
1190 return false;
1191}
1192
1193static void ConvertToCricketVideoCodec(
1194 const webrtc::VideoCodec& in_codec, VideoCodec* out_codec) {
1195 out_codec->id = in_codec.plType;
1196 out_codec->name = in_codec.plName;
1197 out_codec->width = in_codec.width;
1198 out_codec->height = in_codec.height;
1199 out_codec->framerate = in_codec.maxFramerate;
1200 out_codec->SetParam(kCodecParamMinBitrate, in_codec.minBitrate);
1201 out_codec->SetParam(kCodecParamMaxBitrate, in_codec.maxBitrate);
1202 if (in_codec.qpMax) {
1203 out_codec->SetParam(kCodecParamMaxQuantization, in_codec.qpMax);
1204 }
1205}
1206
1207bool WebRtcVideoEngine::ConvertFromCricketVideoCodec(
1208 const VideoCodec& in_codec, webrtc::VideoCodec* out_codec) {
1209 bool found = false;
1210 int ncodecs = vie_wrapper_->codec()->NumberOfCodecs();
1211 for (int i = 0; i < ncodecs; ++i) {
1212 if (vie_wrapper_->codec()->GetCodec(i, *out_codec) == 0 &&
1213 _stricmp(in_codec.name.c_str(), out_codec->plName) == 0) {
1214 found = true;
1215 break;
1216 }
1217 }
1218
1219 // If not found, check if this is supported by external encoder factory.
1220 if (!found && encoder_factory_) {
1221 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1222 encoder_factory_->codecs();
1223 for (size_t i = 0; i < codecs.size(); ++i) {
1224 if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
1225 out_codec->codecType = codecs[i].type;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001226 out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227 talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
1228 codecs[i].name.c_str(), codecs[i].name.length());
1229 found = true;
1230 break;
1231 }
1232 }
1233 }
1234
1235 if (!found) {
1236 LOG(LS_ERROR) << "invalid codec type";
1237 return false;
1238 }
1239
1240 if (in_codec.id != 0)
1241 out_codec->plType = in_codec.id;
1242
1243 if (in_codec.width != 0)
1244 out_codec->width = in_codec.width;
1245
1246 if (in_codec.height != 0)
1247 out_codec->height = in_codec.height;
1248
1249 if (in_codec.framerate != 0)
1250 out_codec->maxFramerate = in_codec.framerate;
1251
1252 // Convert bitrate parameters.
1253 int max_bitrate = kMaxVideoBitrate;
1254 int min_bitrate = kMinVideoBitrate;
1255 int start_bitrate = kStartVideoBitrate;
1256
1257 in_codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
1258 in_codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
1259
1260 if (max_bitrate < min_bitrate) {
1261 return false;
1262 }
1263 start_bitrate = talk_base::_max(start_bitrate, min_bitrate);
1264 start_bitrate = talk_base::_min(start_bitrate, max_bitrate);
1265
1266 out_codec->minBitrate = min_bitrate;
1267 out_codec->startBitrate = start_bitrate;
1268 out_codec->maxBitrate = max_bitrate;
1269
1270 // Convert general codec parameters.
1271 int max_quantization = 0;
1272 if (in_codec.GetParam(kCodecParamMaxQuantization, &max_quantization)) {
1273 if (max_quantization < 0) {
1274 return false;
1275 }
1276 out_codec->qpMax = max_quantization;
1277 }
1278 return true;
1279}
1280
1281void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
1282 talk_base::CritScope cs(&channels_crit_);
1283 channels_.push_back(channel);
1284}
1285
1286void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
1287 talk_base::CritScope cs(&channels_crit_);
1288 channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
1289 channels_.end());
1290}
1291
1292bool WebRtcVideoEngine::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
1293 if (initialized_) {
1294 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
1295 return false;
1296 }
1297 voice_engine_ = voice_engine;
1298 return true;
1299}
1300
1301bool WebRtcVideoEngine::EnableTimedRender() {
1302 if (initialized_) {
1303 LOG(LS_WARNING) << "EnableTimedRender can not be called after Init";
1304 return false;
1305 }
1306 render_module_.reset(webrtc::VideoRender::CreateVideoRender(0, NULL,
1307 false, webrtc::kRenderExternal));
1308 return true;
1309}
1310
1311void WebRtcVideoEngine::SetTraceFilter(int filter) {
1312 tracing_->SetTraceFilter(filter);
1313}
1314
1315// See https://sites.google.com/a/google.com/wavelet/
1316// Home/Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters
1317// for all supported command line setttings.
1318void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
1319 // Set WebRTC trace file.
1320 std::vector<std::string> opts;
1321 talk_base::tokenize(options, ' ', '"', '"', &opts);
1322 std::vector<std::string>::iterator tracefile =
1323 std::find(opts.begin(), opts.end(), "tracefile");
1324 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1325 // Write WebRTC debug output (at same loglevel) to file
1326 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1327 LOG_RTCERR1(SetTraceFile, *tracefile);
1328 }
1329 }
1330}
1331
1332static void AddDefaultFeedbackParams(VideoCodec* codec) {
1333 const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
1334 codec->AddFeedbackParam(kFir);
1335 const FeedbackParam kNack(kRtcpFbParamNack, kParamValueEmpty);
1336 codec->AddFeedbackParam(kNack);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001337 const FeedbackParam kPli(kRtcpFbParamNack, kRtcpFbNackParamPli);
1338 codec->AddFeedbackParam(kPli);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339 const FeedbackParam kRemb(kRtcpFbParamRemb, kParamValueEmpty);
1340 codec->AddFeedbackParam(kRemb);
1341}
1342
1343// Rebuilds the codec list to be only those that are less intensive
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001344// than the specified codec. Prefers internal codec over external with
1345// higher preference field.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346bool WebRtcVideoEngine::RebuildCodecList(const VideoCodec& in_codec) {
1347 if (!FindCodec(in_codec))
1348 return false;
1349
1350 video_codecs_.clear();
1351
1352 bool found = false;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001353 std::set<std::string> internal_codec_names;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 for (size_t i = 0; i < ARRAY_SIZE(kVideoCodecPrefs); ++i) {
1355 const VideoCodecPref& pref(kVideoCodecPrefs[i]);
1356 if (!found)
1357 found = (in_codec.name == pref.name);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001358 if (found) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 VideoCodec codec(pref.payload_type, pref.name,
1360 in_codec.width, in_codec.height, in_codec.framerate,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001361 static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001362 if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
1363 AddDefaultFeedbackParams(&codec);
1364 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001365 if (pref.associated_payload_type != -1) {
1366 codec.SetParam(kCodecParamAssociatedPayloadType,
1367 pref.associated_payload_type);
1368 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 video_codecs_.push_back(codec);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001370 internal_codec_names.insert(codec.name);
1371 }
1372 }
1373 if (encoder_factory_) {
1374 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1375 encoder_factory_->codecs();
1376 for (size_t i = 0; i < codecs.size(); ++i) {
1377 bool is_internal_codec = internal_codec_names.find(codecs[i].name) !=
1378 internal_codec_names.end();
1379 if (!is_internal_codec) {
1380 if (!found)
1381 found = (in_codec.name == codecs[i].name);
1382 VideoCodec codec(
1383 GetExternalVideoPayloadType(static_cast<int>(i)),
1384 codecs[i].name,
1385 codecs[i].max_width,
1386 codecs[i].max_height,
1387 codecs[i].max_fps,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001388 // Use negative preference on external codec to ensure the internal
1389 // codec is preferred.
1390 static_cast<int>(0 - i));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001391 AddDefaultFeedbackParams(&codec);
1392 video_codecs_.push_back(codec);
1393 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394 }
1395 }
1396 ASSERT(found);
1397 return true;
1398}
1399
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400// Ignore spammy trace messages, mostly from the stats API when we haven't
1401// gotten RTCP info yet from the remote side.
1402bool WebRtcVideoEngine::ShouldIgnoreTrace(const std::string& trace) {
1403 static const char* const kTracesToIgnore[] = {
1404 NULL
1405 };
1406 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1407 if (trace.find(*p) == 0) {
1408 return true;
1409 }
1410 }
1411 return false;
1412}
1413
1414int WebRtcVideoEngine::GetNumOfChannels() {
1415 talk_base::CritScope cs(&channels_crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001416 return static_cast<int>(channels_.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417}
1418
1419void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
1420 int length) {
1421 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1422 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1423 sev = talk_base::LS_ERROR;
1424 else if (level == webrtc::kTraceWarning)
1425 sev = talk_base::LS_WARNING;
1426 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1427 sev = talk_base::LS_INFO;
1428 else if (level == webrtc::kTraceTerseInfo)
1429 sev = talk_base::LS_INFO;
1430
1431 // Skip past boilerplate prefix text
1432 if (length < 72) {
1433 std::string msg(trace, length);
1434 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1435 LOG_V(sev) << msg;
1436 } else {
1437 std::string msg(trace + 71, length - 72);
1438 if (!ShouldIgnoreTrace(msg) &&
1439 (!voice_engine_ || !voice_engine_->ShouldIgnoreTrace(msg))) {
1440 LOG_V(sev) << "webrtc: " << msg;
1441 }
1442 }
1443}
1444
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
1446 webrtc::VideoCodecType type) {
1447 if (decoder_factory_ == NULL) {
1448 return NULL;
1449 }
1450 return decoder_factory_->CreateVideoDecoder(type);
1451}
1452
1453void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
1454 ASSERT(decoder_factory_ != NULL);
1455 if (decoder_factory_ == NULL)
1456 return;
1457 decoder_factory_->DestroyVideoDecoder(decoder);
1458}
1459
1460webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
1461 webrtc::VideoCodecType type) {
1462 if (encoder_factory_ == NULL) {
1463 return NULL;
1464 }
1465 return encoder_factory_->CreateVideoEncoder(type);
1466}
1467
1468void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
1469 ASSERT(encoder_factory_ != NULL);
1470 if (encoder_factory_ == NULL)
1471 return;
1472 encoder_factory_->DestroyVideoEncoder(encoder);
1473}
1474
1475bool WebRtcVideoEngine::IsExternalEncoderCodecType(
1476 webrtc::VideoCodecType type) const {
1477 if (!encoder_factory_)
1478 return false;
1479 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1480 encoder_factory_->codecs();
1481 std::vector<WebRtcVideoEncoderFactory::VideoCodec>::const_iterator it;
1482 for (it = codecs.begin(); it != codecs.end(); ++it) {
1483 if (it->type == type)
1484 return true;
1485 }
1486 return false;
1487}
1488
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489void WebRtcVideoEngine::SetExternalDecoderFactory(
1490 WebRtcVideoDecoderFactory* decoder_factory) {
1491 decoder_factory_ = decoder_factory;
1492}
1493
1494void WebRtcVideoEngine::SetExternalEncoderFactory(
1495 WebRtcVideoEncoderFactory* encoder_factory) {
1496 if (encoder_factory_ == encoder_factory)
1497 return;
1498
1499 if (encoder_factory_) {
1500 encoder_factory_->RemoveObserver(this);
1501 }
1502 encoder_factory_ = encoder_factory;
1503 if (encoder_factory_) {
1504 encoder_factory_->AddObserver(this);
1505 }
1506
1507 // Invoke OnCodecAvailable() here in case the list of codecs is already
1508 // available when the encoder factory is installed. If not the encoder
1509 // factory will invoke the callback later when the codecs become available.
1510 OnCodecsAvailable();
1511}
1512
1513void WebRtcVideoEngine::OnCodecsAvailable() {
1514 // Rebuild codec list while reapplying the current default codec format.
1515 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1516 kVideoCodecPrefs[0].name,
1517 video_codecs_[0].width,
1518 video_codecs_[0].height,
1519 video_codecs_[0].framerate,
1520 0);
1521 if (!RebuildCodecList(max_codec)) {
1522 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
1523 }
1524}
1525
1526// WebRtcVideoMediaChannel
1527
1528WebRtcVideoMediaChannel::WebRtcVideoMediaChannel(
1529 WebRtcVideoEngine* engine,
1530 VoiceMediaChannel* channel)
1531 : engine_(engine),
1532 voice_channel_(channel),
1533 vie_channel_(-1),
1534 nack_enabled_(true),
1535 remb_enabled_(false),
1536 render_started_(false),
1537 first_receive_ssrc_(0),
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001538 num_unsignalled_recv_channels_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001539 send_rtx_type_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540 send_red_type_(-1),
1541 send_fec_type_(-1),
1542 send_min_bitrate_(kMinVideoBitrate),
1543 send_start_bitrate_(kStartVideoBitrate),
1544 send_max_bitrate_(kMaxVideoBitrate),
1545 sending_(false),
1546 ratio_w_(0),
1547 ratio_h_(0) {
1548 engine->RegisterChannel(this);
1549}
1550
1551bool WebRtcVideoMediaChannel::Init() {
1552 const uint32 ssrc_key = 0;
1553 return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
1554}
1555
1556WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
1557 const bool send = false;
1558 SetSend(send);
1559 const bool render = false;
1560 SetRender(render);
1561
1562 while (!send_channels_.empty()) {
1563 if (!DeleteSendChannel(send_channels_.begin()->first)) {
1564 LOG(LS_ERROR) << "Unable to delete channel with ssrc key "
1565 << send_channels_.begin()->first;
1566 ASSERT(false);
1567 break;
1568 }
1569 }
1570
1571 // Remove all receive streams and the default channel.
1572 while (!recv_channels_.empty()) {
1573 RemoveRecvStream(recv_channels_.begin()->first);
1574 }
1575
1576 // Unregister the channel from the engine.
1577 engine()->UnregisterChannel(this);
1578 if (worker_thread()) {
1579 worker_thread()->Clear(this);
1580 }
1581}
1582
1583bool WebRtcVideoMediaChannel::SetRecvCodecs(
1584 const std::vector<VideoCodec>& codecs) {
1585 receive_codecs_.clear();
1586 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1587 iter != codecs.end(); ++iter) {
1588 if (engine()->FindCodec(*iter)) {
1589 webrtc::VideoCodec wcodec;
1590 if (engine()->ConvertFromCricketVideoCodec(*iter, &wcodec)) {
1591 receive_codecs_.push_back(wcodec);
1592 }
1593 } else {
1594 LOG(LS_INFO) << "Unknown codec " << iter->name;
1595 return false;
1596 }
1597 }
1598
1599 for (RecvChannelMap::iterator it = recv_channels_.begin();
1600 it != recv_channels_.end(); ++it) {
1601 if (!SetReceiveCodecs(it->second))
1602 return false;
1603 }
1604 return true;
1605}
1606
1607bool WebRtcVideoMediaChannel::SetSendCodecs(
1608 const std::vector<VideoCodec>& codecs) {
1609 // Match with local video codec list.
1610 std::vector<webrtc::VideoCodec> send_codecs;
1611 VideoCodec checked_codec;
1612 VideoCodec current; // defaults to 0x0
1613 if (sending_) {
1614 ConvertToCricketVideoCodec(*send_codec_, &current);
1615 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001616 std::map<int, int> primary_rtx_pt_mapping;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1618 iter != codecs.end(); ++iter) {
1619 if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
1620 send_red_type_ = iter->id;
1621 } else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
1622 send_fec_type_ = iter->id;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001623 } else if (_stricmp(iter->name.c_str(), kRtxCodecName) == 0) {
1624 int rtx_type = iter->id;
1625 int rtx_primary_type = -1;
1626 if (iter->GetParam(kCodecParamAssociatedPayloadType, &rtx_primary_type)) {
1627 primary_rtx_pt_mapping[rtx_primary_type] = rtx_type;
1628 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001629 } else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
1630 webrtc::VideoCodec wcodec;
1631 if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
1632 if (send_codecs.empty()) {
1633 nack_enabled_ = IsNackEnabled(checked_codec);
1634 remb_enabled_ = IsRembEnabled(checked_codec);
1635 }
1636 send_codecs.push_back(wcodec);
1637 }
1638 } else {
1639 LOG(LS_WARNING) << "Unknown codec " << iter->name;
1640 }
1641 }
1642
1643 // Fail if we don't have a match.
1644 if (send_codecs.empty()) {
1645 LOG(LS_WARNING) << "No matching codecs available";
1646 return false;
1647 }
1648
1649 // Recv protection.
1650 for (RecvChannelMap::iterator it = recv_channels_.begin();
1651 it != recv_channels_.end(); ++it) {
1652 int channel_id = it->second->channel_id();
1653 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1654 nack_enabled_)) {
1655 return false;
1656 }
1657 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1658 kNotSending,
1659 remb_enabled_) != 0) {
1660 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
1661 return false;
1662 }
1663 }
1664
1665 // Send settings.
1666 for (SendChannelMap::iterator iter = send_channels_.begin();
1667 iter != send_channels_.end(); ++iter) {
1668 int channel_id = iter->second->channel_id();
1669 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1670 nack_enabled_)) {
1671 return false;
1672 }
1673 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1674 remb_enabled_,
1675 remb_enabled_) != 0) {
1676 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
1677 return false;
1678 }
1679 }
1680
1681 // Select the first matched codec.
1682 webrtc::VideoCodec& codec(send_codecs[0]);
1683
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001684 // Set RTX payload type if primary now active. This value will be used in
1685 // SetSendCodec.
1686 std::map<int, int>::const_iterator rtx_it =
1687 primary_rtx_pt_mapping.find(static_cast<int>(codec.plType));
1688 if (rtx_it != primary_rtx_pt_mapping.end()) {
1689 send_rtx_type_ = rtx_it->second;
1690 }
1691
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692 if (!SetSendCodec(
1693 codec, codec.minBitrate, codec.startBitrate, codec.maxBitrate)) {
1694 return false;
1695 }
1696
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001697 LogSendCodecChange("SetSendCodecs()");
1698
1699 return true;
1700}
1701
1702bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
1703 if (!send_codec_) {
1704 return false;
1705 }
1706 ConvertToCricketVideoCodec(*send_codec_, send_codec);
1707 return true;
1708}
1709
1710bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
1711 const VideoFormat& format) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001712 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
1713 if (!send_channel) {
1714 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
1715 return false;
1716 }
1717 send_channel->set_video_format(format);
1718 return true;
1719}
1720
1721bool WebRtcVideoMediaChannel::SetRender(bool render) {
1722 if (render == render_started_) {
1723 return true; // no action required
1724 }
1725
1726 bool ret = true;
1727 for (RecvChannelMap::iterator it = recv_channels_.begin();
1728 it != recv_channels_.end(); ++it) {
1729 if (render) {
1730 if (engine()->vie()->render()->StartRender(
1731 it->second->channel_id()) != 0) {
1732 LOG_RTCERR1(StartRender, it->second->channel_id());
1733 ret = false;
1734 }
1735 } else {
1736 if (engine()->vie()->render()->StopRender(
1737 it->second->channel_id()) != 0) {
1738 LOG_RTCERR1(StopRender, it->second->channel_id());
1739 ret = false;
1740 }
1741 }
1742 }
1743 if (ret) {
1744 render_started_ = render;
1745 }
1746
1747 return ret;
1748}
1749
1750bool WebRtcVideoMediaChannel::SetSend(bool send) {
1751 if (!HasReadySendChannels() && send) {
1752 LOG(LS_ERROR) << "No stream added";
1753 return false;
1754 }
1755 if (send == sending()) {
1756 return true; // No action required.
1757 }
1758
1759 if (send) {
1760 // We've been asked to start sending.
1761 // SetSendCodecs must have been called already.
1762 if (!send_codec_) {
1763 return false;
1764 }
1765 // Start send now.
1766 if (!StartSend()) {
1767 return false;
1768 }
1769 } else {
1770 // We've been asked to stop sending.
1771 if (!StopSend()) {
1772 return false;
1773 }
1774 }
1775 sending_ = send;
1776
1777 return true;
1778}
1779
1780bool WebRtcVideoMediaChannel::AddSendStream(const StreamParams& sp) {
1781 LOG(LS_INFO) << "AddSendStream " << sp.ToString();
1782
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001783 if (!IsOneSsrcStream(sp) && !IsSimulcastStream(sp)) {
1784 LOG(LS_ERROR) << "AddSendStream: bad local stream parameters";
1785 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001786 }
1787
1788 uint32 ssrc_key;
1789 if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
1790 LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
1791 return false;
1792 }
1793 // If the default channel is already used for sending create a new channel
1794 // otherwise use the default channel for sending.
1795 int channel_id = -1;
1796 if (send_channels_[0]->stream_params() == NULL) {
1797 channel_id = vie_channel_;
1798 } else {
1799 if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
1800 LOG(LS_ERROR) << "AddSendStream: unable to create channel";
1801 return false;
1802 }
1803 }
1804 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1805 // Set the send (local) SSRC.
1806 // If there are multiple send SSRCs, we can only set the first one here, and
1807 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
1808 // (with a codec requires multiple SSRC(s)).
1809 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1810 sp.first_ssrc()) != 0) {
1811 LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
1812 return false;
1813 }
1814
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001815 // Set the corresponding RTX SSRC.
1816 if (!SetLocalRtxSsrc(channel_id, sp, sp.first_ssrc(), 0)) {
1817 return false;
1818 }
1819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 // Set RTCP CName.
1821 if (engine()->vie()->rtp()->SetRTCPCName(channel_id,
1822 sp.cname.c_str()) != 0) {
1823 LOG_RTCERR2(SetRTCPCName, channel_id, sp.cname.c_str());
1824 return false;
1825 }
1826
1827 // At this point the channel's local SSRC has been updated. If the channel is
1828 // the default channel make sure that all the receive channels are updated as
1829 // well. Receive channels have to have the same SSRC as the default channel in
1830 // order to send receiver reports with this SSRC.
1831 if (IsDefaultChannel(channel_id)) {
1832 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
1833 it != recv_channels_.end(); ++it) {
1834 WebRtcVideoChannelRecvInfo* info = it->second;
1835 int channel_id = info->channel_id();
1836 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1837 sp.first_ssrc()) != 0) {
1838 LOG_RTCERR1(SetLocalSSRC, it->first);
1839 return false;
1840 }
1841 }
1842 }
1843
1844 send_channel->set_stream_params(sp);
1845
1846 // Reset send codec after stream parameters changed.
1847 if (send_codec_) {
1848 if (!SetSendCodec(send_channel, *send_codec_, send_min_bitrate_,
1849 send_start_bitrate_, send_max_bitrate_)) {
1850 return false;
1851 }
1852 LogSendCodecChange("SetSendStreamFormat()");
1853 }
1854
1855 if (sending_) {
1856 return StartSend(send_channel);
1857 }
1858 return true;
1859}
1860
1861bool WebRtcVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
1862 uint32 ssrc_key;
1863 if (!GetSendChannelKey(ssrc, &ssrc_key)) {
1864 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1865 << " which doesn't exist.";
1866 return false;
1867 }
1868 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1869 int channel_id = send_channel->channel_id();
1870 if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
1871 // Default channel will still exist. However, if stream_params() is NULL
1872 // there is no stream to remove.
1873 return false;
1874 }
1875 if (sending_) {
1876 StopSend(send_channel);
1877 }
1878
1879 const WebRtcVideoChannelSendInfo::EncoderMap& encoder_map =
1880 send_channel->registered_encoders();
1881 for (WebRtcVideoChannelSendInfo::EncoderMap::const_iterator it =
1882 encoder_map.begin(); it != encoder_map.end(); ++it) {
1883 if (engine()->vie()->ext_codec()->DeRegisterExternalSendCodec(
1884 channel_id, it->first) != 0) {
1885 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
1886 }
1887 engine()->DestroyExternalEncoder(it->second);
1888 }
1889 send_channel->ClearRegisteredEncoders();
1890
1891 // The receive channels depend on the default channel, recycle it instead.
1892 if (IsDefaultChannel(channel_id)) {
1893 SetCapturer(GetDefaultChannelSsrc(), NULL);
1894 send_channel->ClearStreamParams();
1895 } else {
1896 return DeleteSendChannel(ssrc_key);
1897 }
1898 return true;
1899}
1900
1901bool WebRtcVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
1902 // TODO(zhurunz) Remove this once BWE works properly across different send
1903 // and receive channels.
1904 // Reuse default channel for recv stream in 1:1 call.
1905 if (!InConferenceMode() && first_receive_ssrc_ == 0) {
1906 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
1907 << " reuse default channel #"
1908 << vie_channel_;
1909 first_receive_ssrc_ = sp.first_ssrc();
1910 if (render_started_) {
1911 if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
1912 LOG_RTCERR1(StartRender, vie_channel_);
1913 }
1914 }
1915 return true;
1916 }
1917
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 int channel_id = -1;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001919 RecvChannelMap::iterator channel_iterator =
1920 recv_channels_.find(sp.first_ssrc());
1921 if (channel_iterator == recv_channels_.end() &&
1922 first_receive_ssrc_ != sp.first_ssrc()) {
1923 // TODO(perkj): Implement recv media from multiple media SSRCs per stream.
1924 // NOTE: We have two SSRCs per stream when RTX is enabled.
1925 if (!IsOneSsrcStream(sp)) {
1926 LOG(LS_ERROR) << "WebRtcVideoMediaChannel supports one primary SSRC per"
1927 << " stream and one FID SSRC per primary SSRC.";
1928 return false;
1929 }
1930
1931 // Create a new channel for receiving video data.
1932 // In order to get the bandwidth estimation work fine for
1933 // receive only channels, we connect all receiving channels
1934 // to our master send channel.
1935 if (!CreateChannel(sp.first_ssrc(), MD_RECV, &channel_id)) {
1936 return false;
1937 }
1938 } else {
1939 // Already exists.
1940 if (first_receive_ssrc_ == sp.first_ssrc()) {
1941 return false;
1942 }
1943 // Early receive added channel.
1944 channel_id = (*channel_iterator).second->channel_id();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 }
1946
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001947 // Set the corresponding RTX SSRC.
1948 uint32 rtx_ssrc;
1949 bool has_rtx = sp.GetFidSsrc(sp.first_ssrc(), &rtx_ssrc);
1950 if (has_rtx && engine()->vie()->rtp()->SetRemoteSSRCType(
1951 channel_id, webrtc::kViEStreamTypeRtx, rtx_ssrc) != 0) {
1952 LOG_RTCERR3(SetRemoteSSRCType, channel_id, webrtc::kViEStreamTypeRtx,
1953 rtx_ssrc);
1954 return false;
1955 }
1956
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957 // Get the default renderer.
1958 VideoRenderer* default_renderer = NULL;
1959 if (InConferenceMode()) {
1960 // The recv_channels_ size start out being 1, so if it is two here this
1961 // is the first receive channel created (vie_channel_ is not used for
1962 // receiving in a conference call). This means that the renderer stored
1963 // inside vie_channel_ should be used for the just created channel.
1964 if (recv_channels_.size() == 2 &&
1965 recv_channels_.find(0) != recv_channels_.end()) {
1966 GetRenderer(0, &default_renderer);
1967 }
1968 }
1969
1970 // The first recv stream reuses the default renderer (if a default renderer
1971 // has been set).
1972 if (default_renderer) {
1973 SetRenderer(sp.first_ssrc(), default_renderer);
1974 }
1975
1976 LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
1977 << " registered to VideoEngine channel #"
1978 << channel_id << " and connected to channel #" << vie_channel_;
1979
1980 return true;
1981}
1982
1983bool WebRtcVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
1984 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
1985
1986 if (it == recv_channels_.end()) {
1987 // TODO(perkj): Remove this once BWE works properly across different send
1988 // and receive channels.
1989 // The default channel is reused for recv stream in 1:1 call.
1990 if (first_receive_ssrc_ == ssrc) {
1991 first_receive_ssrc_ = 0;
1992 // Need to stop the renderer and remove it since the render window can be
1993 // deleted after this.
1994 if (render_started_) {
1995 if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
1996 LOG_RTCERR1(StopRender, it->second->channel_id());
1997 }
1998 }
1999 recv_channels_[0]->SetRenderer(NULL);
2000 return true;
2001 }
2002 return false;
2003 }
2004 WebRtcVideoChannelRecvInfo* info = it->second;
2005 int channel_id = info->channel_id();
2006 if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
2007 LOG_RTCERR1(RemoveRenderer, channel_id);
2008 }
2009
2010 if (engine()->vie()->network()->DeregisterSendTransport(channel_id) !=0) {
2011 LOG_RTCERR1(DeRegisterSendTransport, channel_id);
2012 }
2013
2014 if (engine()->vie()->codec()->DeregisterDecoderObserver(
2015 channel_id) != 0) {
2016 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
2017 }
2018
2019 const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
2020 info->registered_decoders();
2021 for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
2022 decoder_map.begin(); it != decoder_map.end(); ++it) {
2023 if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
2024 channel_id, it->first) != 0) {
2025 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
2026 }
2027 engine()->DestroyExternalDecoder(it->second);
2028 }
2029 info->ClearRegisteredDecoders();
2030
2031 LOG(LS_INFO) << "Removing video stream " << ssrc
2032 << " with VideoEngine channel #"
2033 << channel_id;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002034 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 if (engine()->vie()->base()->DeleteChannel(channel_id) == -1) {
2036 LOG_RTCERR1(DeleteChannel, channel_id);
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002037 ret = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038 }
2039 // Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
2040 delete info;
2041 recv_channels_.erase(it);
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002042 return ret;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002043}
2044
2045bool WebRtcVideoMediaChannel::StartSend() {
2046 bool success = true;
2047 for (SendChannelMap::iterator iter = send_channels_.begin();
2048 iter != send_channels_.end(); ++iter) {
2049 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2050 if (!StartSend(send_channel)) {
2051 success = false;
2052 }
2053 }
2054 return success;
2055}
2056
2057bool WebRtcVideoMediaChannel::StartSend(
2058 WebRtcVideoChannelSendInfo* send_channel) {
2059 const int channel_id = send_channel->channel_id();
2060 if (engine()->vie()->base()->StartSend(channel_id) != 0) {
2061 LOG_RTCERR1(StartSend, channel_id);
2062 return false;
2063 }
2064
2065 send_channel->set_sending(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002066 return true;
2067}
2068
2069bool WebRtcVideoMediaChannel::StopSend() {
2070 bool success = true;
2071 for (SendChannelMap::iterator iter = send_channels_.begin();
2072 iter != send_channels_.end(); ++iter) {
2073 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2074 if (!StopSend(send_channel)) {
2075 success = false;
2076 }
2077 }
2078 return success;
2079}
2080
2081bool WebRtcVideoMediaChannel::StopSend(
2082 WebRtcVideoChannelSendInfo* send_channel) {
2083 const int channel_id = send_channel->channel_id();
2084 if (engine()->vie()->base()->StopSend(channel_id) != 0) {
2085 LOG_RTCERR1(StopSend, channel_id);
2086 return false;
2087 }
2088 send_channel->set_sending(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089 return true;
2090}
2091
2092bool WebRtcVideoMediaChannel::SendIntraFrame() {
2093 bool success = true;
2094 for (SendChannelMap::iterator iter = send_channels_.begin();
2095 iter != send_channels_.end();
2096 ++iter) {
2097 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2098 const int channel_id = send_channel->channel_id();
2099 if (engine()->vie()->codec()->SendKeyFrame(channel_id) != 0) {
2100 LOG_RTCERR1(SendKeyFrame, channel_id);
2101 success = false;
2102 }
2103 }
2104 return success;
2105}
2106
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107bool WebRtcVideoMediaChannel::HasReadySendChannels() {
2108 return !send_channels_.empty() &&
2109 ((send_channels_.size() > 1) ||
2110 (send_channels_[0]->stream_params() != NULL));
2111}
2112
2113bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
2114 uint32* key) {
2115 *key = 0;
2116 // If a send channel is not ready to send it will not have local_ssrc
2117 // registered to it.
2118 if (!HasReadySendChannels()) {
2119 return false;
2120 }
2121 // The default channel is stored with key 0. The key therefore does not match
2122 // the SSRC associated with the default channel. Check if the SSRC provided
2123 // corresponds to the default channel's SSRC.
2124 if (local_ssrc == GetDefaultChannelSsrc()) {
2125 return true;
2126 }
2127 if (send_channels_.find(local_ssrc) == send_channels_.end()) {
2128 for (SendChannelMap::iterator iter = send_channels_.begin();
2129 iter != send_channels_.end(); ++iter) {
2130 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2131 if (send_channel->has_ssrc(local_ssrc)) {
2132 *key = iter->first;
2133 return true;
2134 }
2135 }
2136 return false;
2137 }
2138 // The key was found in the above std::map::find call. This means that the
2139 // ssrc is the key.
2140 *key = local_ssrc;
2141 return true;
2142}
2143
2144WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145 uint32 local_ssrc) {
2146 uint32 key;
2147 if (!GetSendChannelKey(local_ssrc, &key)) {
2148 return NULL;
2149 }
2150 return send_channels_[key];
2151}
2152
2153bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
2154 uint32* key) {
2155 if (GetSendChannelKey(local_ssrc, key)) {
2156 // If there is a key corresponding to |local_ssrc|, the SSRC is already in
2157 // use. SSRCs need to be unique in a session and at this point a duplicate
2158 // SSRC has been detected.
2159 return false;
2160 }
2161 if (send_channels_[0]->stream_params() == NULL) {
2162 // key should be 0 here as the default channel should be re-used whenever it
2163 // is not used.
2164 *key = 0;
2165 return true;
2166 }
2167 // SSRC is currently not in use and the default channel is already in use. Use
2168 // the SSRC as key since it is supposed to be unique in a session.
2169 *key = local_ssrc;
2170 return true;
2171}
2172
wu@webrtc.org24301a62013-12-13 19:17:43 +00002173int WebRtcVideoMediaChannel::GetSendChannelNum(VideoCapturer* capturer) {
2174 int num = 0;
2175 for (SendChannelMap::iterator iter = send_channels_.begin();
2176 iter != send_channels_.end(); ++iter) {
2177 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2178 if (send_channel->video_capturer() == capturer) {
2179 ++num;
2180 }
2181 }
2182 return num;
2183}
2184
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
2186 WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
2187 const StreamParams* sp = send_channel->stream_params();
2188 if (sp == NULL) {
2189 // This happens if no send stream is currently registered.
2190 return 0;
2191 }
2192 return sp->first_ssrc();
2193}
2194
2195bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
2196 if (send_channels_.find(ssrc_key) == send_channels_.end()) {
2197 return false;
2198 }
2199 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
wu@webrtc.org24301a62013-12-13 19:17:43 +00002200 MaybeDisconnectCapturer(send_channel->video_capturer());
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +00002201 send_channel->set_video_capturer(NULL, engine()->vie());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202
2203 int channel_id = send_channel->channel_id();
2204 int capture_id = send_channel->capture_id();
2205 if (engine()->vie()->codec()->DeregisterEncoderObserver(
2206 channel_id) != 0) {
2207 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
2208 }
2209
2210 // Destroy the external capture interface.
2211 if (engine()->vie()->capture()->DisconnectCaptureDevice(
2212 channel_id) != 0) {
2213 LOG_RTCERR1(DisconnectCaptureDevice, channel_id);
2214 }
2215 if (engine()->vie()->capture()->ReleaseCaptureDevice(
2216 capture_id) != 0) {
2217 LOG_RTCERR1(ReleaseCaptureDevice, capture_id);
2218 }
2219
2220 // The default channel is stored in both |send_channels_| and
2221 // |recv_channels_|. To make sure it is only deleted once from vie let the
2222 // delete call happen when tearing down |recv_channels_| and not here.
2223 if (!IsDefaultChannel(channel_id)) {
2224 engine_->vie()->base()->DeleteChannel(channel_id);
2225 }
2226 delete send_channel;
2227 send_channels_.erase(ssrc_key);
2228 return true;
2229}
2230
2231bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
2232 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2233 if (!send_channel) {
2234 return false;
2235 }
2236 VideoCapturer* capturer = send_channel->video_capturer();
2237 if (capturer == NULL) {
2238 return false;
2239 }
wu@webrtc.org24301a62013-12-13 19:17:43 +00002240 MaybeDisconnectCapturer(capturer);
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +00002241 send_channel->set_video_capturer(NULL, engine()->vie());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2243 if (send_codec_) {
2244 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2245 }
2246 return true;
2247}
2248
2249bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
2250 VideoRenderer* renderer) {
2251 if (recv_channels_.find(ssrc) == recv_channels_.end()) {
2252 // TODO(perkj): Remove this once BWE works properly across different send
2253 // and receive channels.
2254 // The default channel is reused for recv stream in 1:1 call.
2255 if (first_receive_ssrc_ == ssrc &&
2256 recv_channels_.find(0) != recv_channels_.end()) {
2257 LOG(LS_INFO) << "SetRenderer " << ssrc
2258 << " reuse default channel #"
2259 << vie_channel_;
2260 recv_channels_[0]->SetRenderer(renderer);
2261 return true;
2262 }
2263 return false;
2264 }
2265
2266 recv_channels_[ssrc]->SetRenderer(renderer);
2267 return true;
2268}
2269
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002270bool WebRtcVideoMediaChannel::GetStats(const StatsOptions& options,
2271 VideoMediaInfo* info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002272 // Get sender statistics and build VideoSenderInfo.
2273 unsigned int total_bitrate_sent = 0;
2274 unsigned int video_bitrate_sent = 0;
2275 unsigned int fec_bitrate_sent = 0;
2276 unsigned int nack_bitrate_sent = 0;
2277 unsigned int estimated_send_bandwidth = 0;
2278 unsigned int target_enc_bitrate = 0;
2279 if (send_codec_) {
2280 for (SendChannelMap::const_iterator iter = send_channels_.begin();
2281 iter != send_channels_.end(); ++iter) {
2282 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2283 const int channel_id = send_channel->channel_id();
2284 VideoSenderInfo sinfo;
2285 const StreamParams* send_params = send_channel->stream_params();
2286 if (send_params == NULL) {
2287 // This should only happen if the default vie channel is not in use.
2288 // This can happen if no streams have ever been added or the stream
2289 // corresponding to the default channel has been removed. Note that
2290 // there may be non-default vie channels in use when this happen so
2291 // asserting send_channels_.size() == 1 is not correct and neither is
2292 // breaking out of the loop.
2293 ASSERT(channel_id == vie_channel_);
2294 continue;
2295 }
2296 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2297 if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
2298 packets_sent, bytes_recv,
2299 packets_recv) != 0) {
2300 LOG_RTCERR1(GetRTPStatistics, vie_channel_);
2301 continue;
2302 }
2303 WebRtcLocalStreamInfo* channel_stream_info =
2304 send_channel->local_stream_info();
2305
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002306 for (size_t i = 0; i < send_params->ssrcs.size(); ++i) {
2307 sinfo.add_ssrc(send_params->ssrcs[i]);
2308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309 sinfo.codec_name = send_codec_->plName;
2310 sinfo.bytes_sent = bytes_sent;
2311 sinfo.packets_sent = packets_sent;
2312 sinfo.packets_cached = -1;
2313 sinfo.packets_lost = -1;
2314 sinfo.fraction_lost = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 sinfo.rtt_ms = -1;
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +00002316 sinfo.input_frame_width = static_cast<int>(channel_stream_info->width());
2317 sinfo.input_frame_height =
2318 static_cast<int>(channel_stream_info->height());
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002319
2320 VideoCapturer* video_capturer = send_channel->video_capturer();
2321 if (video_capturer) {
2322 video_capturer->GetStats(&sinfo.adapt_frame_drops,
2323 &sinfo.effects_frame_drops,
2324 &sinfo.capturer_frame_time);
2325 }
2326
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +00002327 webrtc::VideoCodec vie_codec;
2328 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) == 0) {
2329 sinfo.send_frame_width = vie_codec.width;
2330 sinfo.send_frame_height = vie_codec.height;
2331 } else {
2332 sinfo.send_frame_width = -1;
2333 sinfo.send_frame_height = -1;
2334 LOG_RTCERR1(GetSendCodec, channel_id);
2335 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002336 sinfo.framerate_input = channel_stream_info->framerate();
2337 sinfo.framerate_sent = send_channel->encoder_observer()->framerate();
2338 sinfo.nominal_bitrate = send_channel->encoder_observer()->bitrate();
2339 sinfo.preferred_bitrate = send_max_bitrate_;
2340 sinfo.adapt_reason = send_channel->CurrentAdaptReason();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002341 sinfo.capture_jitter_ms = -1;
2342 sinfo.avg_encode_ms = -1;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002343 sinfo.encode_usage_percent = -1;
2344 sinfo.capture_queue_delay_ms_per_s = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002346 int capture_jitter_ms = 0;
2347 int avg_encode_time_ms = 0;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002348 int encode_usage_percent = 0;
2349 int capture_queue_delay_ms_per_s = 0;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002350 if (engine()->vie()->base()->CpuOveruseMeasures(
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002351 channel_id,
2352 &capture_jitter_ms,
2353 &avg_encode_time_ms,
2354 &encode_usage_percent,
2355 &capture_queue_delay_ms_per_s) == 0) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002356 sinfo.capture_jitter_ms = capture_jitter_ms;
2357 sinfo.avg_encode_ms = avg_encode_time_ms;
wu@webrtc.org9caf2762013-12-11 18:25:07 +00002358 sinfo.encode_usage_percent = encode_usage_percent;
2359 sinfo.capture_queue_delay_ms_per_s = capture_queue_delay_ms_per_s;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002360 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002361
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002362#ifdef USE_WEBRTC_DEV_BRANCH
2363 webrtc::RtcpPacketTypeCounter rtcp_sent;
2364 webrtc::RtcpPacketTypeCounter rtcp_received;
2365 if (engine()->vie()->rtp()->GetRtcpPacketTypeCounters(
2366 channel_id, &rtcp_sent, &rtcp_received) == 0) {
2367 sinfo.firs_rcvd = rtcp_received.fir_packets;
2368 sinfo.plis_rcvd = rtcp_received.pli_packets;
2369 sinfo.nacks_rcvd = rtcp_received.nack_packets;
2370 } else {
2371 sinfo.firs_rcvd = -1;
2372 sinfo.plis_rcvd = -1;
2373 sinfo.nacks_rcvd = -1;
2374 LOG_RTCERR1(GetRtcpPacketTypeCounters, channel_id);
2375 }
2376#else
2377 sinfo.firs_rcvd = -1;
2378 sinfo.plis_rcvd = -1;
2379 sinfo.nacks_rcvd = -1;
2380#endif
2381
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002382 // Get received RTCP statistics for the sender (reported by the remote
2383 // client in a RTCP packet), if available.
2384 // It's not a fatal error if we can't, since RTCP may not have arrived
2385 // yet.
2386 webrtc::RtcpStatistics outgoing_stream_rtcp_stats;
2387 int outgoing_stream_rtt_ms;
2388
2389 if (engine_->vie()->rtp()->GetSendChannelRtcpStatistics(
2390 channel_id,
2391 outgoing_stream_rtcp_stats,
2392 outgoing_stream_rtt_ms) == 0) {
2393 // Convert Q8 to float.
2394 sinfo.packets_lost = outgoing_stream_rtcp_stats.cumulative_lost;
2395 sinfo.fraction_lost = static_cast<float>(
2396 outgoing_stream_rtcp_stats.fraction_lost) / (1 << 8);
2397 sinfo.rtt_ms = outgoing_stream_rtt_ms;
2398 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 info->senders.push_back(sinfo);
2400
2401 unsigned int channel_total_bitrate_sent = 0;
2402 unsigned int channel_video_bitrate_sent = 0;
2403 unsigned int channel_fec_bitrate_sent = 0;
2404 unsigned int channel_nack_bitrate_sent = 0;
2405 if (engine_->vie()->rtp()->GetBandwidthUsage(
2406 channel_id, channel_total_bitrate_sent, channel_video_bitrate_sent,
2407 channel_fec_bitrate_sent, channel_nack_bitrate_sent) == 0) {
2408 total_bitrate_sent += channel_total_bitrate_sent;
2409 video_bitrate_sent += channel_video_bitrate_sent;
2410 fec_bitrate_sent += channel_fec_bitrate_sent;
2411 nack_bitrate_sent += channel_nack_bitrate_sent;
2412 } else {
2413 LOG_RTCERR1(GetBandwidthUsage, channel_id);
2414 }
2415
2416 unsigned int estimated_stream_send_bandwidth = 0;
2417 if (engine_->vie()->rtp()->GetEstimatedSendBandwidth(
2418 channel_id, &estimated_stream_send_bandwidth) == 0) {
2419 estimated_send_bandwidth += estimated_stream_send_bandwidth;
2420 } else {
2421 LOG_RTCERR1(GetEstimatedSendBandwidth, channel_id);
2422 }
2423 unsigned int target_enc_stream_bitrate = 0;
2424 if (engine_->vie()->codec()->GetCodecTargetBitrate(
2425 channel_id, &target_enc_stream_bitrate) == 0) {
2426 target_enc_bitrate += target_enc_stream_bitrate;
2427 } else {
2428 LOG_RTCERR1(GetCodecTargetBitrate, channel_id);
2429 }
2430 }
2431 } else {
2432 LOG(LS_WARNING) << "GetStats: sender information not ready.";
2433 }
2434
2435 // Get the SSRC and stats for each receiver, based on our own calculations.
2436 unsigned int estimated_recv_bandwidth = 0;
2437 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
2438 it != recv_channels_.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439 WebRtcVideoChannelRecvInfo* channel = it->second;
2440
2441 unsigned int ssrc;
2442 // Get receiver statistics and build VideoReceiverInfo, if we have data.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002443 // Skip the default channel (ssrc == 0).
2444 if (engine_->vie()->rtp()->GetRemoteSSRC(
2445 channel->channel_id(), ssrc) != 0 ||
2446 ssrc == 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002447 continue;
2448
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002449 webrtc::StreamDataCounters sent;
2450 webrtc::StreamDataCounters received;
2451 if (engine_->vie()->rtp()->GetRtpStatistics(channel->channel_id(),
2452 sent, received) != 0) {
2453 LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
2454 return false;
2455 }
2456 VideoReceiverInfo rinfo;
2457 rinfo.add_ssrc(ssrc);
2458 rinfo.bytes_rcvd = received.bytes;
2459 rinfo.packets_rcvd = received.packets;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 rinfo.packets_lost = -1;
2461 rinfo.packets_concealed = -1;
2462 rinfo.fraction_lost = -1; // from SentRTCP
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 rinfo.frame_width = channel->render_adapter()->width();
2464 rinfo.frame_height = channel->render_adapter()->height();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 int fps = channel->render_adapter()->framerate();
2466 rinfo.framerate_decoded = fps;
2467 rinfo.framerate_output = fps;
wu@webrtc.org97077a32013-10-25 21:18:33 +00002468 channel->decoder_observer()->ExportTo(&rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002469
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002470#ifdef USE_WEBRTC_DEV_BRANCH
2471 webrtc::RtcpPacketTypeCounter rtcp_sent;
2472 webrtc::RtcpPacketTypeCounter rtcp_received;
2473 if (engine()->vie()->rtp()->GetRtcpPacketTypeCounters(
2474 channel->channel_id(), &rtcp_sent, &rtcp_received) == 0) {
2475 rinfo.firs_sent = rtcp_sent.fir_packets;
2476 rinfo.plis_sent = rtcp_sent.pli_packets;
2477 rinfo.nacks_sent = rtcp_sent.nack_packets;
2478 } else {
2479 rinfo.firs_sent = -1;
2480 rinfo.plis_sent = -1;
2481 rinfo.nacks_sent = -1;
2482 LOG_RTCERR1(GetRtcpPacketTypeCounters, channel->channel_id());
2483 }
2484#else
2485 rinfo.firs_sent = -1;
2486 rinfo.plis_sent = -1;
2487 rinfo.nacks_sent = -1;
2488#endif
2489
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002490 // Get our locally created statistics of the received RTP stream.
2491 webrtc::RtcpStatistics incoming_stream_rtcp_stats;
2492 int incoming_stream_rtt_ms;
2493 if (engine_->vie()->rtp()->GetReceiveChannelRtcpStatistics(
2494 channel->channel_id(),
2495 incoming_stream_rtcp_stats,
2496 incoming_stream_rtt_ms) == 0) {
2497 // Convert Q8 to float.
2498 rinfo.packets_lost = incoming_stream_rtcp_stats.cumulative_lost;
2499 rinfo.fraction_lost = static_cast<float>(
2500 incoming_stream_rtcp_stats.fraction_lost) / (1 << 8);
2501 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002502 info->receivers.push_back(rinfo);
2503
2504 unsigned int estimated_recv_stream_bandwidth = 0;
2505 if (engine_->vie()->rtp()->GetEstimatedReceiveBandwidth(
2506 channel->channel_id(), &estimated_recv_stream_bandwidth) == 0) {
2507 estimated_recv_bandwidth += estimated_recv_stream_bandwidth;
2508 } else {
2509 LOG_RTCERR1(GetEstimatedReceiveBandwidth, channel->channel_id());
2510 }
2511 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002512 // Build BandwidthEstimationInfo.
2513 // TODO(zhurunz): Add real unittest for this.
2514 BandwidthEstimationInfo bwe;
2515
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002516 // TODO(jiayl): remove the condition when the necessary changes are available
2517 // outside the dev branch.
2518#ifdef USE_WEBRTC_DEV_BRANCH
2519 if (options.include_received_propagation_stats) {
2520 webrtc::ReceiveBandwidthEstimatorStats additional_stats;
2521 // Only call for the default channel because the returned stats are
2522 // collected for all the channels using the same estimator.
2523 if (engine_->vie()->rtp()->GetReceiveBandwidthEstimatorStats(
mallinath@webrtc.org92fdfeb2014-02-17 18:49:41 +00002524 recv_channels_[0]->channel_id(), &additional_stats) == 0) {
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002525 bwe.total_received_propagation_delta_ms =
2526 additional_stats.total_propagation_time_delta_ms;
2527 bwe.recent_received_propagation_delta_ms.swap(
2528 additional_stats.recent_propagation_time_delta_ms);
2529 bwe.recent_received_packet_group_arrival_time_ms.swap(
2530 additional_stats.recent_arrival_time_ms);
2531 }
2532 }
henrike@webrtc.orgb8395eb2014-02-28 21:57:22 +00002533
2534 engine_->vie()->rtp()->GetPacerQueuingDelayMs(
2535 recv_channels_[0]->channel_id(), &bwe.bucket_delay);
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002536#endif
2537
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002538 // Calculations done above per send/receive stream.
2539 bwe.actual_enc_bitrate = video_bitrate_sent;
2540 bwe.transmit_bitrate = total_bitrate_sent;
2541 bwe.retransmit_bitrate = nack_bitrate_sent;
2542 bwe.available_send_bandwidth = estimated_send_bandwidth;
2543 bwe.available_recv_bandwidth = estimated_recv_bandwidth;
2544 bwe.target_enc_bitrate = target_enc_bitrate;
2545
2546 info->bw_estimations.push_back(bwe);
2547
2548 return true;
2549}
2550
2551bool WebRtcVideoMediaChannel::SetCapturer(uint32 ssrc,
2552 VideoCapturer* capturer) {
2553 ASSERT(ssrc != 0);
2554 if (!capturer) {
2555 return RemoveCapturer(ssrc);
2556 }
2557 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2558 if (!send_channel) {
2559 return false;
2560 }
2561 VideoCapturer* old_capturer = send_channel->video_capturer();
wu@webrtc.org24301a62013-12-13 19:17:43 +00002562 MaybeDisconnectCapturer(old_capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563
henrike@webrtc.orgc7bec842014-03-12 19:53:43 +00002564 send_channel->set_video_capturer(capturer, engine()->vie());
wu@webrtc.orga8910d22014-01-23 22:12:45 +00002565 MaybeConnectCapturer(capturer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002566 if (!capturer->IsScreencast() && ratio_w_ != 0 && ratio_h_ != 0) {
2567 capturer->UpdateAspectRatio(ratio_w_, ratio_h_);
2568 }
2569 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2570 if (send_codec_) {
2571 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2572 }
2573 return true;
2574}
2575
2576bool WebRtcVideoMediaChannel::RequestIntraFrame() {
2577 // There is no API exposed to application to request a key frame
2578 // ViE does this internally when there are errors from decoder
2579 return false;
2580}
2581
wu@webrtc.orga9890802013-12-13 00:21:03 +00002582void WebRtcVideoMediaChannel::OnPacketReceived(
2583 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002584 // Pick which channel to send this packet to. If this packet doesn't match
2585 // any multiplexed streams, just send it to the default channel. Otherwise,
2586 // send it to the specific decoder instance for that stream.
2587 uint32 ssrc = 0;
2588 if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
2589 return;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002590 int processing_channel = GetRecvChannelNum(ssrc);
2591 if (processing_channel == -1) {
2592 // Allocate an unsignalled recv channel for processing in conference mode.
henrike@webrtc.org18e59112014-03-14 17:19:38 +00002593 if (!InConferenceMode()) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002594 // If we cant find or allocate one, use the default.
2595 processing_channel = video_channel();
henrike@webrtc.org18e59112014-03-14 17:19:38 +00002596 } else if (!CreateUnsignalledRecvChannel(ssrc, &processing_channel)) {
2597 // If we cant create an unsignalled recv channel, drop the packet in
2598 // conference mode.
2599 return;
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002600 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 }
2602
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002603 engine()->vie()->network()->ReceivedRTPPacket(
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002604 processing_channel,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002605 packet->data(),
wu@webrtc.orga9890802013-12-13 00:21:03 +00002606 static_cast<int>(packet->length()),
2607 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608}
2609
wu@webrtc.orga9890802013-12-13 00:21:03 +00002610void WebRtcVideoMediaChannel::OnRtcpReceived(
2611 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002612// Sending channels need all RTCP packets with feedback information.
2613// Even sender reports can contain attached report blocks.
2614// Receiving channels need sender reports in order to create
2615// correct receiver reports.
2616
2617 uint32 ssrc = 0;
2618 if (!GetRtcpSsrc(packet->data(), packet->length(), &ssrc)) {
2619 LOG(LS_WARNING) << "Failed to parse SSRC from received RTCP packet";
2620 return;
2621 }
2622 int type = 0;
2623 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2624 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2625 return;
2626 }
2627
2628 // If it is a sender report, find the channel that is listening.
2629 if (type == kRtcpTypeSR) {
2630 int which_channel = GetRecvChannelNum(ssrc);
2631 if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002632 engine_->vie()->network()->ReceivedRTCPPacket(
2633 which_channel,
2634 packet->data(),
2635 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 }
2637 }
2638 // SR may continue RR and any RR entry may correspond to any one of the send
2639 // channels. So all RTCP packets must be forwarded all send channels. ViE
2640 // will filter out RR internally.
2641 for (SendChannelMap::iterator iter = send_channels_.begin();
2642 iter != send_channels_.end(); ++iter) {
2643 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2644 int channel_id = send_channel->channel_id();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002645 engine_->vie()->network()->ReceivedRTCPPacket(
2646 channel_id,
2647 packet->data(),
2648 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002649 }
2650}
2651
2652void WebRtcVideoMediaChannel::OnReadyToSend(bool ready) {
2653 SetNetworkTransmissionState(ready);
2654}
2655
2656bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2657 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2658 if (!send_channel) {
2659 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
2660 return false;
2661 }
2662 send_channel->set_muted(muted);
2663 return true;
2664}
2665
2666bool WebRtcVideoMediaChannel::SetRecvRtpHeaderExtensions(
2667 const std::vector<RtpHeaderExtension>& extensions) {
2668 if (receive_extensions_ == extensions) {
2669 return true;
2670 }
2671 receive_extensions_ = extensions;
2672
2673 const RtpHeaderExtension* offset_extension =
2674 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2675 const RtpHeaderExtension* send_time_extension =
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002676 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677
2678 // Loop through all receive channels and enable/disable the extensions.
2679 for (RecvChannelMap::iterator channel_it = recv_channels_.begin();
2680 channel_it != recv_channels_.end(); ++channel_it) {
2681 int channel_id = channel_it->second->channel_id();
2682 if (!SetHeaderExtension(
2683 &webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus, channel_id,
2684 offset_extension)) {
2685 return false;
2686 }
2687 if (!SetHeaderExtension(
2688 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
2689 send_time_extension)) {
2690 return false;
2691 }
2692 }
2693 return true;
2694}
2695
2696bool WebRtcVideoMediaChannel::SetSendRtpHeaderExtensions(
2697 const std::vector<RtpHeaderExtension>& extensions) {
2698 send_extensions_ = extensions;
2699
2700 const RtpHeaderExtension* offset_extension =
2701 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2702 const RtpHeaderExtension* send_time_extension =
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002703 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704
2705 // Loop through all send channels and enable/disable the extensions.
2706 for (SendChannelMap::iterator channel_it = send_channels_.begin();
2707 channel_it != send_channels_.end(); ++channel_it) {
2708 int channel_id = channel_it->second->channel_id();
2709 if (!SetHeaderExtension(
2710 &webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus, channel_id,
2711 offset_extension)) {
2712 return false;
2713 }
2714 if (!SetHeaderExtension(
2715 &webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus, channel_id,
2716 send_time_extension)) {
2717 return false;
2718 }
2719 }
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00002720
2721 if (send_time_extension) {
2722 // For video RTP packets, we would like to update AbsoluteSendTimeHeader
2723 // Extension closer to the network, @ socket level before sending.
2724 // Pushing the extension id to socket layer.
2725 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2726 talk_base::Socket::OPT_RTP_SENDTIME_EXTN_ID,
2727 send_time_extension->id);
2728 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002729 return true;
2730}
2731
mallinath@webrtc.org92fdfeb2014-02-17 18:49:41 +00002732int WebRtcVideoMediaChannel::GetRtpSendTimeExtnId() const {
2733 const RtpHeaderExtension* send_time_extension = FindHeaderExtension(
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002734 send_extensions_, kRtpAbsoluteSenderTimeHeaderExtension);
mallinath@webrtc.org92fdfeb2014-02-17 18:49:41 +00002735 if (send_time_extension) {
2736 return send_time_extension->id;
2737 }
2738 return -1;
2739}
2740
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002741bool WebRtcVideoMediaChannel::SetStartSendBandwidth(int bps) {
2742 LOG(LS_INFO) << "WebRtcVideoMediaChannel::SetStartSendBandwidth";
2743
2744 if (!send_codec_) {
2745 LOG(LS_INFO) << "The send codec has not been set up yet";
2746 return true;
2747 }
2748
2749 // On success, SetSendCodec() will reset |send_start_bitrate_| to |bps/1000|,
2750 // by calling MaybeChangeStartBitrate. That method will also clamp the
2751 // start bitrate between min and max, consistent with the override behavior
2752 // in SetMaxSendBandwidth.
2753 return SetSendCodec(*send_codec_,
2754 send_min_bitrate_, bps / 1000, send_max_bitrate_);
2755}
2756
2757bool WebRtcVideoMediaChannel::SetMaxSendBandwidth(int bps) {
2758 LOG(LS_INFO) << "WebRtcVideoMediaChannel::SetMaxSendBandwidth";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002759
2760 if (InConferenceMode()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002761 LOG(LS_INFO) << "Conference mode ignores SetMaxSendBandwidth";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 return true;
2763 }
2764
2765 if (!send_codec_) {
2766 LOG(LS_INFO) << "The send codec has not been set up yet";
2767 return true;
2768 }
2769
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002770 // Use the default value or the bps for the max
2771 int max_bitrate = (bps <= 0) ? send_max_bitrate_ : (bps / 1000);
2772
2773 // Reduce the current minimum and start bitrates if necessary.
2774 int min_bitrate = talk_base::_min(send_min_bitrate_, max_bitrate);
2775 int start_bitrate = talk_base::_min(send_start_bitrate_, max_bitrate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776
2777 if (!SetSendCodec(*send_codec_, min_bitrate, start_bitrate, max_bitrate)) {
2778 return false;
2779 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002780 LogSendCodecChange("SetMaxSendBandwidth()");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002781
2782 return true;
2783}
2784
2785bool WebRtcVideoMediaChannel::SetOptions(const VideoOptions &options) {
2786 // Always accept options that are unchanged.
2787 if (options_ == options) {
2788 return true;
2789 }
2790
2791 // Trigger SetSendCodec to set correct noise reduction state if the option has
2792 // changed.
2793 bool denoiser_changed = options.video_noise_reduction.IsSet() &&
2794 (options_.video_noise_reduction != options.video_noise_reduction);
2795
2796 bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
2797 (options_.video_leaky_bucket != options.video_leaky_bucket);
2798
2799 bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
2800 (options_.buffered_mode_latency != options.buffered_mode_latency);
2801
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002802 bool cpu_overuse_detection_changed = options.cpu_overuse_detection.IsSet() &&
2803 (options_.cpu_overuse_detection != options.cpu_overuse_detection);
2804
wu@webrtc.orgde305012013-10-31 15:40:38 +00002805 bool dscp_option_changed = (options_.dscp != options.dscp);
2806
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002807 bool suspend_below_min_bitrate_changed =
2808 options.suspend_below_min_bitrate.IsSet() &&
2809 (options_.suspend_below_min_bitrate != options.suspend_below_min_bitrate);
2810
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811 bool conference_mode_turned_off = false;
2812 if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
2813 options_.conference_mode.GetWithDefaultIfUnset(false) &&
2814 !options.conference_mode.GetWithDefaultIfUnset(false)) {
2815 conference_mode_turned_off = true;
2816 }
2817
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00002818
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002819 // Save the options, to be interpreted where appropriate.
2820 // Use options_.SetAll() instead of assignment so that unset value in options
2821 // will not overwrite the previous option value.
2822 options_.SetAll(options);
2823
2824 // Set CPU options for all send channels.
2825 for (SendChannelMap::iterator iter = send_channels_.begin();
2826 iter != send_channels_.end(); ++iter) {
2827 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2828 send_channel->ApplyCpuOptions(options_);
2829 }
2830
2831 // Adjust send codec bitrate if needed.
2832 int conf_max_bitrate = kDefaultConferenceModeMaxVideoBitrate;
2833
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002834 // Save altered min_bitrate level and apply if necessary.
2835 bool adjusted_min_bitrate = false;
2836 if (options.lower_min_bitrate.IsSet()) {
2837 bool lower;
2838 options.lower_min_bitrate.Get(&lower);
2839
2840 int new_send_min_bitrate = lower ? kLowerMinBitrate : kMinVideoBitrate;
2841 adjusted_min_bitrate = (new_send_min_bitrate != send_min_bitrate_);
2842 send_min_bitrate_ = new_send_min_bitrate;
2843 }
2844
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 int expected_bitrate = send_max_bitrate_;
2846 if (InConferenceMode()) {
2847 expected_bitrate = conf_max_bitrate;
2848 } else if (conference_mode_turned_off) {
2849 // This is a special case for turning conference mode off.
2850 // Max bitrate should go back to the default maximum value instead
2851 // of the current maximum.
2852 expected_bitrate = kMaxVideoBitrate;
2853 }
2854
wu@webrtc.org1e6cb2c2014-03-24 17:01:50 +00002855 int options_start_bitrate;
2856 bool start_bitrate_changed = false;
2857 if (options.video_start_bitrate.Get(&options_start_bitrate) &&
2858 options_start_bitrate != send_start_bitrate_) {
2859 send_start_bitrate_ = options_start_bitrate;
2860 start_bitrate_changed = true;
2861 }
2862
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00002863 bool reset_send_codec_needed = send_codec_ &&
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002864 (send_max_bitrate_ != expected_bitrate || denoiser_changed ||
wu@webrtc.org1e6cb2c2014-03-24 17:01:50 +00002865 adjusted_min_bitrate || start_bitrate_changed);
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00002866
2867
2868 if (reset_send_codec_needed) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002869 // On success, SetSendCodec() will reset send_max_bitrate_ to
2870 // expected_bitrate.
2871 if (!SetSendCodec(*send_codec_,
2872 send_min_bitrate_,
2873 send_start_bitrate_,
2874 expected_bitrate)) {
2875 return false;
2876 }
2877 LogSendCodecChange("SetOptions()");
2878 }
henrike@webrtc.org10bd88e2014-03-11 21:07:25 +00002879
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002880 if (leaky_bucket_changed) {
2881 bool enable_leaky_bucket =
2882 options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
henrike@webrtc.org152208a2014-03-21 21:43:26 +00002883 LOG(LS_INFO) << "Leaky bucket is enabled : " << enable_leaky_bucket;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002884 for (SendChannelMap::iterator it = send_channels_.begin();
2885 it != send_channels_.end(); ++it) {
2886 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(
2887 it->second->channel_id(), enable_leaky_bucket) != 0) {
2888 LOG_RTCERR2(SetTransmissionSmoothingStatus, it->second->channel_id(),
2889 enable_leaky_bucket);
2890 }
2891 }
2892 }
2893 if (buffer_latency_changed) {
2894 int buffer_latency =
2895 options_.buffered_mode_latency.GetWithDefaultIfUnset(
2896 cricket::kBufferedModeDisabled);
2897 for (SendChannelMap::iterator it = send_channels_.begin();
2898 it != send_channels_.end(); ++it) {
2899 if (engine()->vie()->rtp()->SetSenderBufferingMode(
2900 it->second->channel_id(), buffer_latency) != 0) {
2901 LOG_RTCERR2(SetSenderBufferingMode, it->second->channel_id(),
2902 buffer_latency);
2903 }
2904 }
2905 for (RecvChannelMap::iterator it = recv_channels_.begin();
2906 it != recv_channels_.end(); ++it) {
2907 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
2908 it->second->channel_id(), buffer_latency) != 0) {
2909 LOG_RTCERR2(SetReceiverBufferingMode, it->second->channel_id(),
2910 buffer_latency);
2911 }
2912 }
2913 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002914 if (cpu_overuse_detection_changed) {
2915 bool cpu_overuse_detection =
2916 options_.cpu_overuse_detection.GetWithDefaultIfUnset(false);
2917 for (SendChannelMap::iterator iter = send_channels_.begin();
2918 iter != send_channels_.end(); ++iter) {
2919 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2920 send_channel->SetCpuOveruseDetection(cpu_overuse_detection);
2921 }
2922 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00002923 if (dscp_option_changed) {
2924 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002925 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00002926 dscp = kVideoDscpValue;
2927 if (MediaChannel::SetDscp(dscp) != 0) {
2928 LOG(LS_WARNING) << "Failed to set DSCP settings for video channel";
2929 }
2930 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002931 if (suspend_below_min_bitrate_changed) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002932 if (options_.suspend_below_min_bitrate.GetWithDefaultIfUnset(false)) {
2933 for (SendChannelMap::iterator it = send_channels_.begin();
2934 it != send_channels_.end(); ++it) {
2935 engine()->vie()->codec()->SuspendBelowMinBitrate(
2936 it->second->channel_id());
2937 }
2938 } else {
2939 LOG(LS_WARNING) << "Cannot disable video suspension once it is enabled";
2940 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002942 return true;
2943}
2944
2945void WebRtcVideoMediaChannel::SetInterface(NetworkInterface* iface) {
2946 MediaChannel::SetInterface(iface);
2947 // Set the RTP recv/send buffer to a bigger size
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002948 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2949 talk_base::Socket::OPT_RCVBUF,
2950 kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002951
2952 // TODO(sriniv): Remove or re-enable this.
2953 // As part of b/8030474, send-buffer is size now controlled through
2954 // portallocator flags.
2955 // network_interface_->SetOption(NetworkInterface::ST_RTP,
2956 // talk_base::Socket::OPT_SNDBUF,
2957 // kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958}
2959
2960void WebRtcVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
2961 ASSERT(ratio_w != 0);
2962 ASSERT(ratio_h != 0);
2963 ratio_w_ = ratio_w;
2964 ratio_h_ = ratio_h;
2965 // For now assume that all streams want the same aspect ratio.
2966 // TODO(hellner): remove the need for this assumption.
2967 for (SendChannelMap::iterator iter = send_channels_.begin();
2968 iter != send_channels_.end(); ++iter) {
2969 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2970 VideoCapturer* capturer = send_channel->video_capturer();
2971 if (capturer) {
2972 capturer->UpdateAspectRatio(ratio_w, ratio_h);
2973 }
2974 }
2975}
2976
2977bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
2978 VideoRenderer** renderer) {
2979 RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
2980 if (it == recv_channels_.end()) {
2981 if (first_receive_ssrc_ == ssrc &&
2982 recv_channels_.find(0) != recv_channels_.end()) {
2983 LOG(LS_INFO) << " GetRenderer " << ssrc
2984 << " reuse default renderer #"
2985 << vie_channel_;
2986 *renderer = recv_channels_[0]->render_adapter()->renderer();
2987 return true;
2988 }
2989 return false;
2990 }
2991
2992 *renderer = it->second->render_adapter()->renderer();
2993 return true;
2994}
2995
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002996bool WebRtcVideoMediaChannel::GetVideoAdapter(
2997 uint32 ssrc, CoordinatedVideoAdapter** video_adapter) {
2998 SendChannelMap::iterator it = send_channels_.find(ssrc);
2999 if (it == send_channels_.end()) {
3000 return false;
3001 }
3002 *video_adapter = it->second->video_adapter();
3003 return true;
3004}
3005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003006void WebRtcVideoMediaChannel::SendFrame(VideoCapturer* capturer,
3007 const VideoFrame* frame) {
wu@webrtc.org24301a62013-12-13 19:17:43 +00003008 // If the |capturer| is registered to any send channel, then send the frame
3009 // to those send channels.
3010 bool capturer_is_channel_owned = false;
3011 for (SendChannelMap::iterator iter = send_channels_.begin();
3012 iter != send_channels_.end(); ++iter) {
3013 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3014 if (send_channel->video_capturer() == capturer) {
3015 SendFrame(send_channel, frame, capturer->IsScreencast());
3016 capturer_is_channel_owned = true;
3017 }
3018 }
3019 if (capturer_is_channel_owned) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003020 return;
3021 }
wu@webrtc.org24301a62013-12-13 19:17:43 +00003022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003023 // TODO(hellner): Remove below for loop once the captured frame no longer
3024 // come from the engine, i.e. the engine no longer owns a capturer.
3025 for (SendChannelMap::iterator iter = send_channels_.begin();
3026 iter != send_channels_.end(); ++iter) {
3027 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3028 if (send_channel->video_capturer() == NULL) {
3029 SendFrame(send_channel, frame, capturer->IsScreencast());
3030 }
3031 }
3032}
3033
3034bool WebRtcVideoMediaChannel::SendFrame(
3035 WebRtcVideoChannelSendInfo* send_channel,
3036 const VideoFrame* frame,
3037 bool is_screencast) {
3038 if (!send_channel) {
3039 return false;
3040 }
3041 if (!send_codec_) {
3042 // Send codec has not been set. No reason to process the frame any further.
3043 return false;
3044 }
3045 const VideoFormat& video_format = send_channel->video_format();
3046 // If the frame should be dropped.
3047 const bool video_format_set = video_format != cricket::VideoFormat();
3048 if (video_format_set &&
3049 (video_format.width == 0 && video_format.height == 0)) {
3050 return true;
3051 }
3052
3053 // Checks if we need to reset vie send codec.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003054 if (!MaybeResetVieSendCodec(send_channel,
3055 static_cast<int>(frame->GetWidth()),
3056 static_cast<int>(frame->GetHeight()),
3057 is_screencast, NULL)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 LOG(LS_ERROR) << "MaybeResetVieSendCodec failed with "
3059 << frame->GetWidth() << "x" << frame->GetHeight();
3060 return false;
3061 }
3062 const VideoFrame* frame_out = frame;
3063 talk_base::scoped_ptr<VideoFrame> processed_frame;
3064 // Disable muting for screencast.
3065 const bool mute = (send_channel->muted() && !is_screencast);
3066 send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
3067 if (processed_frame) {
3068 frame_out = processed_frame.get();
3069 }
3070
3071 webrtc::ViEVideoFrameI420 frame_i420;
3072 // TODO(ronghuawu): Update the webrtc::ViEVideoFrameI420
3073 // to use const unsigned char*
3074 frame_i420.y_plane = const_cast<unsigned char*>(frame_out->GetYPlane());
3075 frame_i420.u_plane = const_cast<unsigned char*>(frame_out->GetUPlane());
3076 frame_i420.v_plane = const_cast<unsigned char*>(frame_out->GetVPlane());
3077 frame_i420.y_pitch = frame_out->GetYPitch();
3078 frame_i420.u_pitch = frame_out->GetUPitch();
3079 frame_i420.v_pitch = frame_out->GetVPitch();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003080 frame_i420.width = static_cast<uint16>(frame_out->GetWidth());
3081 frame_i420.height = static_cast<uint16>(frame_out->GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082
3083 int64 timestamp_ntp_ms = 0;
3084 // TODO(justinlin): Reenable after Windows issues with clock drift are fixed.
3085 // Currently reverted to old behavior of discarding capture timestamp.
3086#if 0
3087 // If the frame timestamp is 0, we will use the deliver time.
3088 const int64 frame_timestamp = frame->GetTimeStamp();
3089 if (frame_timestamp != 0) {
3090 if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
3091 kTimestampDeltaInSecondsForWarning) {
3092 LOG(LS_WARNING) << "Frame timestamp differs by more than "
3093 << kTimestampDeltaInSecondsForWarning << " seconds from "
3094 << "current Unix timestamp.";
3095 }
3096
3097 timestamp_ntp_ms =
3098 talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
3099 }
3100#endif
3101
3102 return send_channel->external_capture()->IncomingFrameI420(
3103 frame_i420, timestamp_ntp_ms) == 0;
3104}
3105
3106bool WebRtcVideoMediaChannel::CreateChannel(uint32 ssrc_key,
3107 MediaDirection direction,
3108 int* channel_id) {
3109 // There are 3 types of channels. Sending only, receiving only and
3110 // sending and receiving. The sending and receiving channel is the
3111 // default channel and there is only one. All other channels that are created
3112 // are associated with the default channel which must exist. The default
3113 // channel id is stored in |vie_channel_|. All channels need to know about
3114 // the default channel to properly handle remb which is why there are
3115 // different ViE create channel calls.
3116 // For this channel the local and remote ssrc key is 0. However, it may
3117 // have a non-zero local and/or remote ssrc depending on if it is currently
3118 // sending and/or receiving.
3119 if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
3120 (!send_channels_.empty() || !recv_channels_.empty())) {
3121 ASSERT(false);
3122 return false;
3123 }
3124
3125 *channel_id = -1;
3126 if (direction == MD_RECV) {
3127 // All rec channels are associated with the default channel |vie_channel_|
3128 if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
3129 vie_channel_) != 0) {
3130 LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
3131 return false;
3132 }
3133 } else if (direction == MD_SEND) {
3134 if (engine_->vie()->base()->CreateChannel(*channel_id,
3135 vie_channel_) != 0) {
3136 LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
3137 return false;
3138 }
3139 } else {
3140 ASSERT(direction == MD_SENDRECV);
3141 if (engine_->vie()->base()->CreateChannel(*channel_id) != 0) {
3142 LOG_RTCERR1(CreateChannel, *channel_id);
3143 return false;
3144 }
3145 }
3146 if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
3147 engine_->vie()->base()->DeleteChannel(*channel_id);
3148 *channel_id = -1;
3149 return false;
3150 }
3151
3152 return true;
3153}
3154
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00003155bool WebRtcVideoMediaChannel::CreateUnsignalledRecvChannel(
3156 uint32 ssrc_key, int* out_channel_id) {
henrike@webrtc.org18e59112014-03-14 17:19:38 +00003157 int unsignalled_recv_channel_limit =
3158 options_.unsignalled_recv_stream_limit.GetWithDefaultIfUnset(
3159 kNumDefaultUnsignalledVideoRecvStreams);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00003160 if (num_unsignalled_recv_channels_ >= unsignalled_recv_channel_limit) {
3161 return false;
3162 }
3163 if (!CreateChannel(ssrc_key, MD_RECV, out_channel_id)) {
3164 return false;
3165 }
3166 // TODO(tvsriram): Support dynamic sizing of unsignalled recv channels.
3167 num_unsignalled_recv_channels_++;
3168 return true;
3169}
3170
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003171bool WebRtcVideoMediaChannel::ConfigureChannel(int channel_id,
3172 MediaDirection direction,
3173 uint32 ssrc_key) {
3174 const bool receiving = (direction == MD_RECV) || (direction == MD_SENDRECV);
3175 const bool sending = (direction == MD_SEND) || (direction == MD_SENDRECV);
3176 // Register external transport.
3177 if (engine_->vie()->network()->RegisterSendTransport(
3178 channel_id, *this) != 0) {
3179 LOG_RTCERR1(RegisterSendTransport, channel_id);
3180 return false;
3181 }
3182
3183 // Set MTU.
3184 if (engine_->vie()->network()->SetMTU(channel_id, kVideoMtu) != 0) {
3185 LOG_RTCERR2(SetMTU, channel_id, kVideoMtu);
3186 return false;
3187 }
3188 // Turn on RTCP and loss feedback reporting.
3189 if (engine()->vie()->rtp()->SetRTCPStatus(
3190 channel_id, webrtc::kRtcpCompound_RFC4585) != 0) {
3191 LOG_RTCERR2(SetRTCPStatus, channel_id, webrtc::kRtcpCompound_RFC4585);
3192 return false;
3193 }
3194 // Enable pli as key frame request method.
3195 if (engine_->vie()->rtp()->SetKeyFrameRequestMethod(
3196 channel_id, webrtc::kViEKeyFrameRequestPliRtcp) != 0) {
3197 LOG_RTCERR2(SetKeyFrameRequestMethod,
3198 channel_id, webrtc::kViEKeyFrameRequestPliRtcp);
3199 return false;
3200 }
3201 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3202 // Logged in SetNackFec. Don't spam the logs.
3203 return false;
3204 }
3205 // Note that receiving must always be configured before sending to ensure
3206 // that send and receive channel is configured correctly (ConfigureReceiving
3207 // assumes no sending).
3208 if (receiving) {
3209 if (!ConfigureReceiving(channel_id, ssrc_key)) {
3210 return false;
3211 }
3212 }
3213 if (sending) {
3214 if (!ConfigureSending(channel_id, ssrc_key)) {
3215 return false;
3216 }
3217 }
3218
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00003219 // Start receiving for both receive and send channels so that we get incoming
3220 // RTP (if receiving) as well as RTCP feedback (if sending).
3221 if (engine()->vie()->base()->StartReceive(channel_id) != 0) {
3222 LOG_RTCERR1(StartReceive, channel_id);
3223 return false;
3224 }
3225
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003226 return true;
3227}
3228
3229bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
3230 uint32 remote_ssrc_key) {
3231 // Make sure that an SSRC/key isn't registered more than once.
3232 if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
3233 return false;
3234 }
3235 // Connect the voice channel, if there is one.
3236 // TODO(perkj): The A/V is synched by the receiving channel. So we need to
3237 // know the SSRC of the remote audio channel in order to fetch the correct
3238 // webrtc VoiceEngine channel. For now- only sync the default channel used
3239 // in 1-1 calls.
3240 if (remote_ssrc_key == 0 && voice_channel_) {
3241 WebRtcVoiceMediaChannel* voice_channel =
3242 static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
3243 if (engine_->vie()->base()->ConnectAudioChannel(
3244 vie_channel_, voice_channel->voe_channel()) != 0) {
3245 LOG_RTCERR2(ConnectAudioChannel, channel_id,
3246 voice_channel->voe_channel());
3247 LOG(LS_WARNING) << "A/V not synchronized";
3248 // Not a fatal error.
3249 }
3250 }
3251
3252 talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
3253 new WebRtcVideoChannelRecvInfo(channel_id));
3254
3255 // Install a render adapter.
3256 if (engine_->vie()->render()->AddRenderer(channel_id,
3257 webrtc::kVideoI420, channel_info->render_adapter()) != 0) {
3258 LOG_RTCERR3(AddRenderer, channel_id, webrtc::kVideoI420,
3259 channel_info->render_adapter());
3260 return false;
3261 }
3262
3263
3264 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3265 kNotSending,
3266 remb_enabled_) != 0) {
3267 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
3268 return false;
3269 }
3270
3271 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus,
3272 channel_id, receive_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3273 return false;
3274 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 if (!SetHeaderExtension(
3276 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003277 receive_extensions_, kRtpAbsoluteSenderTimeHeaderExtension)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278 return false;
3279 }
3280
3281 if (remote_ssrc_key != 0) {
3282 // Use the same SSRC as our default channel
3283 // (so the RTCP reports are correct).
3284 unsigned int send_ssrc = 0;
3285 webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
3286 if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
3287 LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
3288 return false;
3289 }
3290 if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
3291 LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
3292 return false;
3293 }
3294 } // Else this is the the default channel and we don't change the SSRC.
3295
3296 // Disable color enhancement since it is a bit too aggressive.
3297 if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
3298 false) != 0) {
3299 LOG_RTCERR1(EnableColorEnhancement, channel_id);
3300 return false;
3301 }
3302
3303 if (!SetReceiveCodecs(channel_info.get())) {
3304 return false;
3305 }
3306
3307 int buffer_latency =
3308 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3309 cricket::kBufferedModeDisabled);
3310 if (buffer_latency != cricket::kBufferedModeDisabled) {
3311 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
3312 channel_id, buffer_latency) != 0) {
3313 LOG_RTCERR2(SetReceiverBufferingMode, channel_id, buffer_latency);
3314 }
3315 }
3316
3317 if (render_started_) {
3318 if (engine_->vie()->render()->StartRender(channel_id) != 0) {
3319 LOG_RTCERR1(StartRender, channel_id);
3320 return false;
3321 }
3322 }
3323
3324 // Register decoder observer for incoming framerate and bitrate.
3325 if (engine()->vie()->codec()->RegisterDecoderObserver(
3326 channel_id, *channel_info->decoder_observer()) != 0) {
3327 LOG_RTCERR1(RegisterDecoderObserver, channel_info->decoder_observer());
3328 return false;
3329 }
3330
3331 recv_channels_[remote_ssrc_key] = channel_info.release();
3332 return true;
3333}
3334
3335bool WebRtcVideoMediaChannel::ConfigureSending(int channel_id,
3336 uint32 local_ssrc_key) {
3337 // The ssrc key can be zero or correspond to an SSRC.
3338 // Make sure the default channel isn't configured more than once.
3339 if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
3340 return false;
3341 }
3342 // Make sure that the SSRC is not already in use.
3343 uint32 dummy_key;
3344 if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
3345 return false;
3346 }
3347 int vie_capture = 0;
3348 webrtc::ViEExternalCapture* external_capture = NULL;
3349 // Register external capture.
3350 if (engine()->vie()->capture()->AllocateExternalCaptureDevice(
3351 vie_capture, external_capture) != 0) {
3352 LOG_RTCERR0(AllocateExternalCaptureDevice);
3353 return false;
3354 }
3355
3356 // Connect external capture.
3357 if (engine()->vie()->capture()->ConnectCaptureDevice(
3358 vie_capture, channel_id) != 0) {
3359 LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
3360 return false;
3361 }
3362 talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
3363 new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
3364 external_capture,
3365 engine()->cpu_monitor()));
3366 send_channel->ApplyCpuOptions(options_);
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003367 send_channel->SignalCpuAdaptationUnable.connect(this,
3368 &WebRtcVideoMediaChannel::OnCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003370 if (options_.cpu_overuse_detection.GetWithDefaultIfUnset(false)) {
3371 send_channel->SetCpuOveruseDetection(true);
3372 }
3373
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003374 // Register encoder observer for outgoing framerate and bitrate.
3375 if (engine()->vie()->codec()->RegisterEncoderObserver(
3376 channel_id, *send_channel->encoder_observer()) != 0) {
3377 LOG_RTCERR1(RegisterEncoderObserver, send_channel->encoder_observer());
3378 return false;
3379 }
3380
3381 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus,
3382 channel_id, send_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3383 return false;
3384 }
3385
3386 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003387 channel_id, send_extensions_, kRtpAbsoluteSenderTimeHeaderExtension)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003388 return false;
3389 }
3390
3391 if (options_.video_leaky_bucket.GetWithDefaultIfUnset(false)) {
3392 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
3393 true) != 0) {
3394 LOG_RTCERR2(SetTransmissionSmoothingStatus, channel_id, true);
3395 return false;
3396 }
3397 }
3398
3399 int buffer_latency =
3400 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3401 cricket::kBufferedModeDisabled);
3402 if (buffer_latency != cricket::kBufferedModeDisabled) {
3403 if (engine()->vie()->rtp()->SetSenderBufferingMode(
3404 channel_id, buffer_latency) != 0) {
3405 LOG_RTCERR2(SetSenderBufferingMode, channel_id, buffer_latency);
3406 }
3407 }
3408 // The remb status direction correspond to the RTP stream (and not the RTCP
3409 // stream). I.e. if send remb is enabled it means it is receiving remote
3410 // rembs and should use them to estimate bandwidth. Receive remb mean that
3411 // remb packets will be generated and that the channel should be included in
3412 // it. If remb is enabled all channels are allowed to contribute to the remb
3413 // but only receive channels will ever end up actually contributing. This
3414 // keeps the logic simple.
3415 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3416 remb_enabled_,
3417 remb_enabled_) != 0) {
3418 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
3419 return false;
3420 }
3421 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3422 // Logged in SetNackFec. Don't spam the logs.
3423 return false;
3424 }
3425
3426 send_channels_[local_ssrc_key] = send_channel.release();
3427
3428 return true;
3429}
3430
3431bool WebRtcVideoMediaChannel::SetNackFec(int channel_id,
3432 int red_payload_type,
3433 int fec_payload_type,
3434 bool nack_enabled) {
3435 bool enable = (red_payload_type != -1 && fec_payload_type != -1 &&
3436 !InConferenceMode());
3437 if (enable) {
3438 if (engine_->vie()->rtp()->SetHybridNACKFECStatus(
3439 channel_id, nack_enabled, red_payload_type, fec_payload_type) != 0) {
3440 LOG_RTCERR4(SetHybridNACKFECStatus,
3441 channel_id, nack_enabled, red_payload_type, fec_payload_type);
3442 return false;
3443 }
3444 LOG(LS_INFO) << "Hybrid NACK/FEC enabled for channel " << channel_id;
3445 } else {
3446 if (engine_->vie()->rtp()->SetNACKStatus(channel_id, nack_enabled) != 0) {
3447 LOG_RTCERR1(SetNACKStatus, channel_id);
3448 return false;
3449 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003450 std::string enabled = nack_enabled ? "enabled" : "disabled";
3451 LOG(LS_INFO) << "NACK " << enabled << " for channel " << channel_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003452 }
3453 return true;
3454}
3455
3456bool WebRtcVideoMediaChannel::SetSendCodec(const webrtc::VideoCodec& codec,
3457 int min_bitrate,
3458 int start_bitrate,
3459 int max_bitrate) {
3460 bool ret_val = true;
3461 for (SendChannelMap::iterator iter = send_channels_.begin();
3462 iter != send_channels_.end(); ++iter) {
3463 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3464 ret_val = SetSendCodec(send_channel, codec, min_bitrate, start_bitrate,
3465 max_bitrate) && ret_val;
3466 }
3467 if (ret_val) {
3468 // All SetSendCodec calls were successful. Update the global state
3469 // accordingly.
3470 send_codec_.reset(new webrtc::VideoCodec(codec));
3471 send_min_bitrate_ = min_bitrate;
3472 send_start_bitrate_ = start_bitrate;
3473 send_max_bitrate_ = max_bitrate;
3474 } else {
3475 // At least one SetSendCodec call failed, rollback.
3476 for (SendChannelMap::iterator iter = send_channels_.begin();
3477 iter != send_channels_.end(); ++iter) {
3478 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3479 if (send_codec_) {
3480 SetSendCodec(send_channel, *send_codec_.get(), send_min_bitrate_,
3481 send_start_bitrate_, send_max_bitrate_);
3482 }
3483 }
3484 }
3485 return ret_val;
3486}
3487
3488bool WebRtcVideoMediaChannel::SetSendCodec(
3489 WebRtcVideoChannelSendInfo* send_channel,
3490 const webrtc::VideoCodec& codec,
3491 int min_bitrate,
3492 int start_bitrate,
3493 int max_bitrate) {
3494 if (!send_channel) {
3495 return false;
3496 }
3497 const int channel_id = send_channel->channel_id();
3498 // Make a copy of the codec
3499 webrtc::VideoCodec target_codec = codec;
3500 target_codec.startBitrate = start_bitrate;
3501 target_codec.minBitrate = min_bitrate;
3502 target_codec.maxBitrate = max_bitrate;
3503
3504 // Set the default number of temporal layers for VP8.
3505 if (webrtc::kVideoCodecVP8 == codec.codecType) {
3506 target_codec.codecSpecific.VP8.numberOfTemporalLayers =
3507 kDefaultNumberOfTemporalLayers;
3508
3509 // Turn off the VP8 error resilience
3510 target_codec.codecSpecific.VP8.resilience = webrtc::kResilienceOff;
3511
3512 bool enable_denoising =
3513 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3514 target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
3515 }
3516
3517 // Register external encoder if codec type is supported by encoder factory.
3518 if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
3519 !send_channel->IsEncoderRegistered(target_codec.plType)) {
3520 webrtc::VideoEncoder* encoder =
3521 engine()->CreateExternalEncoder(codec.codecType);
3522 if (encoder) {
3523 if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
3524 channel_id, target_codec.plType, encoder, false) == 0) {
3525 send_channel->RegisterEncoder(target_codec.plType, encoder);
3526 } else {
3527 LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
3528 engine()->DestroyExternalEncoder(encoder);
3529 }
3530 }
3531 }
3532
3533 // Resolution and framerate may vary for different send channels.
3534 const VideoFormat& video_format = send_channel->video_format();
3535 UpdateVideoCodec(video_format, &target_codec);
3536
3537 if (target_codec.width == 0 && target_codec.height == 0) {
3538 const uint32 ssrc = send_channel->stream_params()->first_ssrc();
3539 LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
3540 << "for ssrc: " << ssrc << ".";
3541 } else {
3542 MaybeChangeStartBitrate(channel_id, &target_codec);
3543 if (0 != engine()->vie()->codec()->SetSendCodec(channel_id, target_codec)) {
3544 LOG_RTCERR2(SetSendCodec, channel_id, target_codec.plName);
3545 return false;
3546 }
3547
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003548 // NOTE: SetRtxSendPayloadType must be called after all simulcast SSRCs
3549 // are configured. Otherwise ssrc's configured after this point will use
3550 // the primary PT for RTX.
3551 if (send_rtx_type_ != -1 &&
3552 engine()->vie()->rtp()->SetRtxSendPayloadType(channel_id,
3553 send_rtx_type_) != 0) {
3554 LOG_RTCERR2(SetRtxSendPayloadType, channel_id, send_rtx_type_);
3555 return false;
3556 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003557 }
3558 send_channel->set_interval(
3559 cricket::VideoFormat::FpsToInterval(target_codec.maxFramerate));
3560 return true;
3561}
3562
3563
3564static std::string ToString(webrtc::VideoCodecComplexity complexity) {
3565 switch (complexity) {
3566 case webrtc::kComplexityNormal:
3567 return "normal";
3568 case webrtc::kComplexityHigh:
3569 return "high";
3570 case webrtc::kComplexityHigher:
3571 return "higher";
3572 case webrtc::kComplexityMax:
3573 return "max";
3574 default:
3575 return "unknown";
3576 }
3577}
3578
3579static std::string ToString(webrtc::VP8ResilienceMode resilience) {
3580 switch (resilience) {
3581 case webrtc::kResilienceOff:
3582 return "off";
3583 case webrtc::kResilientStream:
3584 return "stream";
3585 case webrtc::kResilientFrames:
3586 return "frames";
3587 default:
3588 return "unknown";
3589 }
3590}
3591
3592void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
3593 webrtc::VideoCodec vie_codec;
3594 if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
3595 LOG_RTCERR1(GetSendCodec, vie_channel_);
3596 return;
3597 }
3598
3599 LOG(LS_INFO) << reason << " : selected video codec "
3600 << vie_codec.plName << "/"
3601 << vie_codec.width << "x" << vie_codec.height << "x"
3602 << static_cast<int>(vie_codec.maxFramerate) << "fps"
3603 << "@" << vie_codec.maxBitrate << "kbps"
3604 << " (min=" << vie_codec.minBitrate << "kbps,"
3605 << " start=" << vie_codec.startBitrate << "kbps)";
3606 LOG(LS_INFO) << "Video max quantization: " << vie_codec.qpMax;
3607 if (webrtc::kVideoCodecVP8 == vie_codec.codecType) {
3608 LOG(LS_INFO) << "VP8 number of temporal layers: "
3609 << static_cast<int>(
3610 vie_codec.codecSpecific.VP8.numberOfTemporalLayers);
3611 LOG(LS_INFO) << "VP8 options : "
3612 << "picture loss indication = "
3613 << vie_codec.codecSpecific.VP8.pictureLossIndicationOn
3614 << ", feedback mode = "
3615 << vie_codec.codecSpecific.VP8.feedbackModeOn
3616 << ", complexity = "
3617 << ToString(vie_codec.codecSpecific.VP8.complexity)
3618 << ", resilience = "
3619 << ToString(vie_codec.codecSpecific.VP8.resilience)
3620 << ", denoising = "
3621 << vie_codec.codecSpecific.VP8.denoisingOn
3622 << ", error concealment = "
3623 << vie_codec.codecSpecific.VP8.errorConcealmentOn
3624 << ", automatic resize = "
3625 << vie_codec.codecSpecific.VP8.automaticResizeOn
3626 << ", frame dropping = "
3627 << vie_codec.codecSpecific.VP8.frameDroppingOn
3628 << ", key frame interval = "
3629 << vie_codec.codecSpecific.VP8.keyFrameInterval;
3630 }
3631
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003632 if (send_rtx_type_ != -1) {
3633 LOG(LS_INFO) << "RTX payload type: " << send_rtx_type_;
3634 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003635}
3636
3637bool WebRtcVideoMediaChannel::SetReceiveCodecs(
3638 WebRtcVideoChannelRecvInfo* info) {
3639 int red_type = -1;
3640 int fec_type = -1;
3641 int channel_id = info->channel_id();
3642 for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
3643 it != receive_codecs_.end(); ++it) {
3644 if (it->codecType == webrtc::kVideoCodecRED) {
3645 red_type = it->plType;
3646 } else if (it->codecType == webrtc::kVideoCodecULPFEC) {
3647 fec_type = it->plType;
3648 }
3649 if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
3650 LOG_RTCERR2(SetReceiveCodec, channel_id, it->plName);
3651 return false;
3652 }
3653 if (!info->IsDecoderRegistered(it->plType) &&
3654 it->codecType != webrtc::kVideoCodecRED &&
3655 it->codecType != webrtc::kVideoCodecULPFEC) {
3656 webrtc::VideoDecoder* decoder =
3657 engine()->CreateExternalDecoder(it->codecType);
3658 if (decoder) {
3659 if (engine()->vie()->ext_codec()->RegisterExternalReceiveCodec(
3660 channel_id, it->plType, decoder) == 0) {
3661 info->RegisterDecoder(it->plType, decoder);
3662 } else {
3663 LOG_RTCERR2(RegisterExternalReceiveCodec, channel_id, it->plName);
3664 engine()->DestroyExternalDecoder(decoder);
3665 }
3666 }
3667 }
3668 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003669 return true;
3670}
3671
3672int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
3673 if (ssrc == first_receive_ssrc_) {
3674 return vie_channel_;
3675 }
3676 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
3677 return (it != recv_channels_.end()) ? it->second->channel_id() : -1;
3678}
3679
3680// If the new frame size is different from the send codec size we set on vie,
3681// we need to reset the send codec on vie.
3682// The new send codec size should not exceed send_codec_ which is controlled
3683// only by the 'jec' logic.
3684bool WebRtcVideoMediaChannel::MaybeResetVieSendCodec(
3685 WebRtcVideoChannelSendInfo* send_channel,
3686 int new_width,
3687 int new_height,
3688 bool is_screencast,
3689 bool* reset) {
3690 if (reset) {
3691 *reset = false;
3692 }
3693 ASSERT(send_codec_.get() != NULL);
3694
3695 webrtc::VideoCodec target_codec = *send_codec_.get();
3696 const VideoFormat& video_format = send_channel->video_format();
3697 UpdateVideoCodec(video_format, &target_codec);
3698
3699 // Vie send codec size should not exceed target_codec.
3700 int target_width = new_width;
3701 int target_height = new_height;
3702 if (!is_screencast &&
3703 (new_width > target_codec.width || new_height > target_codec.height)) {
3704 target_width = target_codec.width;
3705 target_height = target_codec.height;
3706 }
3707
3708 // Get current vie codec.
3709 webrtc::VideoCodec vie_codec;
3710 const int channel_id = send_channel->channel_id();
3711 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) != 0) {
3712 LOG_RTCERR1(GetSendCodec, channel_id);
3713 return false;
3714 }
3715 const int cur_width = vie_codec.width;
3716 const int cur_height = vie_codec.height;
3717
3718 // Only reset send codec when there is a size change. Additionally,
3719 // automatic resize needs to be turned off when screencasting and on when
3720 // not screencasting.
3721 // Don't allow automatic resizing for screencasting.
3722 bool automatic_resize = !is_screencast;
3723 // Turn off VP8 frame dropping when screensharing as the current model does
3724 // not work well at low fps.
3725 bool vp8_frame_dropping = !is_screencast;
3726 // Disable denoising for screencasting.
3727 bool enable_denoising =
3728 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3729 bool denoising = !is_screencast && enable_denoising;
3730 bool reset_send_codec =
3731 target_width != cur_width || target_height != cur_height ||
3732 automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
3733 denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
3734 vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
3735
3736 if (reset_send_codec) {
3737 // Set the new codec on vie.
3738 vie_codec.width = target_width;
3739 vie_codec.height = target_height;
3740 vie_codec.maxFramerate = target_codec.maxFramerate;
3741 vie_codec.startBitrate = target_codec.startBitrate;
3742 vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
3743 vie_codec.codecSpecific.VP8.denoisingOn = denoising;
3744 vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
3745 // TODO(mflodman): Remove 'is_screencast' check when screen cast settings
3746 // are treated correctly in WebRTC.
3747 if (!is_screencast)
3748 MaybeChangeStartBitrate(channel_id, &vie_codec);
3749
3750 if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
3751 LOG_RTCERR1(SetSendCodec, channel_id);
3752 return false;
3753 }
3754 if (reset) {
3755 *reset = true;
3756 }
3757 LogSendCodecChange("Capture size changed");
3758 }
3759
3760 return true;
3761}
3762
3763void WebRtcVideoMediaChannel::MaybeChangeStartBitrate(
3764 int channel_id, webrtc::VideoCodec* video_codec) {
3765 if (video_codec->startBitrate < video_codec->minBitrate) {
3766 video_codec->startBitrate = video_codec->minBitrate;
3767 } else if (video_codec->startBitrate > video_codec->maxBitrate) {
3768 video_codec->startBitrate = video_codec->maxBitrate;
3769 }
3770
3771 // Use a previous target bitrate, if there is one.
3772 unsigned int current_target_bitrate = 0;
3773 if (engine()->vie()->codec()->GetCodecTargetBitrate(
3774 channel_id, &current_target_bitrate) == 0) {
3775 // Convert to kbps.
3776 current_target_bitrate /= 1000;
3777 if (current_target_bitrate > video_codec->maxBitrate) {
3778 current_target_bitrate = video_codec->maxBitrate;
3779 }
3780 if (current_target_bitrate > video_codec->startBitrate) {
3781 video_codec->startBitrate = current_target_bitrate;
3782 }
3783 }
3784}
3785
3786void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
3787 FlushBlackFrameData* black_frame_data =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003788 static_cast<FlushBlackFrameData*>(msg->pdata);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003789 FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
3790 delete black_frame_data;
3791}
3792
3793int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
3794 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003795 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003796 return MediaChannel::SendPacket(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003797}
3798
3799int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
3800 const void* data,
3801 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003802 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003803 return MediaChannel::SendRtcp(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003804}
3805
3806void WebRtcVideoMediaChannel::QueueBlackFrame(uint32 ssrc, int64 timestamp,
3807 int framerate) {
3808 if (timestamp) {
3809 FlushBlackFrameData* black_frame_data = new FlushBlackFrameData(
3810 ssrc,
3811 timestamp);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003812 const int delay_ms = static_cast<int>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003813 2 * cricket::VideoFormat::FpsToInterval(framerate) *
3814 talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
3815 worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
3816 }
3817}
3818
3819void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
3820 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
3821 if (!send_channel) {
3822 return;
3823 }
3824 talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
3825
3826 const WebRtcLocalStreamInfo* channel_stream_info =
3827 send_channel->local_stream_info();
3828 int64 last_frame_time_stamp = channel_stream_info->time_stamp();
3829 if (last_frame_time_stamp == timestamp) {
3830 size_t last_frame_width = 0;
3831 size_t last_frame_height = 0;
3832 int64 last_frame_elapsed_time = 0;
3833 channel_stream_info->GetLastFrameInfo(&last_frame_width, &last_frame_height,
3834 &last_frame_elapsed_time);
3835 if (!last_frame_width || !last_frame_height) {
3836 return;
3837 }
3838 WebRtcVideoFrame black_frame;
3839 // Black frame is not screencast.
3840 const bool screencasting = false;
3841 const int64 timestamp_delta = send_channel->interval();
3842 if (!black_frame.InitToBlack(send_codec_->width, send_codec_->height, 1, 1,
3843 last_frame_elapsed_time + timestamp_delta,
3844 last_frame_time_stamp + timestamp_delta) ||
3845 !SendFrame(send_channel, &black_frame, screencasting)) {
3846 LOG(LS_ERROR) << "Failed to send black frame.";
3847 }
3848 }
3849}
3850
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003851void WebRtcVideoMediaChannel::OnCpuAdaptationUnable() {
3852 // ssrc is hardcoded to 0. This message is based on a system wide issue,
3853 // so finding which ssrc caused it doesn't matter.
3854 SignalMediaError(0, VideoMediaChannel::ERROR_REC_CPU_MAX_CANT_DOWNGRADE);
3855}
3856
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003857void WebRtcVideoMediaChannel::SetNetworkTransmissionState(
3858 bool is_transmitting) {
3859 LOG(LS_INFO) << "SetNetworkTransmissionState: " << is_transmitting;
3860 for (SendChannelMap::iterator iter = send_channels_.begin();
3861 iter != send_channels_.end(); ++iter) {
3862 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3863 int channel_id = send_channel->channel_id();
3864 engine_->vie()->network()->SetNetworkTransmissionState(channel_id,
3865 is_transmitting);
3866 }
3867}
3868
3869bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3870 int channel_id, const RtpHeaderExtension* extension) {
3871 bool enable = false;
3872 int id = 0;
3873 if (extension) {
3874 enable = true;
3875 id = extension->id;
3876 }
3877 if ((engine_->vie()->rtp()->*setter)(channel_id, enable, id) != 0) {
3878 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
3879 return false;
3880 }
3881 return true;
3882}
3883
3884bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3885 int channel_id, const std::vector<RtpHeaderExtension>& extensions,
3886 const char header_extension_uri[]) {
3887 const RtpHeaderExtension* extension = FindHeaderExtension(extensions,
3888 header_extension_uri);
3889 return SetHeaderExtension(setter, channel_id, extension);
3890}
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003891
3892bool WebRtcVideoMediaChannel::SetLocalRtxSsrc(int channel_id,
3893 const StreamParams& send_params,
3894 uint32 primary_ssrc,
3895 int stream_idx) {
3896 uint32 rtx_ssrc = 0;
3897 bool has_rtx = send_params.GetFidSsrc(primary_ssrc, &rtx_ssrc);
3898 if (has_rtx && engine()->vie()->rtp()->SetLocalSSRC(
3899 channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, stream_idx) != 0) {
3900 LOG_RTCERR4(SetLocalSSRC, channel_id, rtx_ssrc,
3901 webrtc::kViEStreamTypeRtx, stream_idx);
3902 return false;
3903 }
3904 return true;
3905}
3906
wu@webrtc.org24301a62013-12-13 19:17:43 +00003907void WebRtcVideoMediaChannel::MaybeConnectCapturer(VideoCapturer* capturer) {
3908 if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
3909 capturer->SignalVideoFrame.connect(this,
3910 &WebRtcVideoMediaChannel::SendFrame);
3911 }
3912}
3913
3914void WebRtcVideoMediaChannel::MaybeDisconnectCapturer(VideoCapturer* capturer) {
3915 if (capturer != NULL && GetSendChannelNum(capturer) == 1) {
3916 capturer->SignalVideoFrame.disconnect(this);
3917 }
3918}
3919
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003920} // namespace cricket
3921
3922#endif // HAVE_WEBRTC_VIDEO