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