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