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