blob: 397deb0d40d601ed6d60e2cfea85e1370d03c03f [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.org9dba5252013-08-05 20:36:57 +0000231 uint32_t time_stamp, int64_t render_time
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000232 , void* handle
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000233 ) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000234 talk_base::CritScope cs(&crit_);
235 frame_rate_tracker_.Update(1);
236 if (renderer_ == NULL) {
237 return 0;
238 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000239 // Convert 90K rtp timestamp to ns timestamp.
240 int64 rtp_time_stamp_in_ns = (time_stamp / 90) *
241 talk_base::kNumNanosecsPerMillisec;
242 // Convert milisecond render time to ns timestamp.
243 int64 render_time_stamp_in_ns = render_time *
244 talk_base::kNumNanosecsPerMillisec;
245 // Send the rtp timestamp to renderer as the VideoFrame timestamp.
246 // and the render timestamp as the VideoFrame elapsed_time.
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000247 if (handle == NULL) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000248 return DeliverBufferFrame(buffer, buffer_size, render_time_stamp_in_ns,
249 rtp_time_stamp_in_ns);
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000250 } else {
251 return DeliverTextureFrame(handle, render_time_stamp_in_ns,
252 rtp_time_stamp_in_ns);
253 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000254 }
255
256 virtual bool IsTextureSupported() { return true; }
257
258 int DeliverBufferFrame(unsigned char* buffer, int buffer_size,
259 int64 elapsed_time, int64 time_stamp) {
260 WebRtcVideoFrame video_frame;
wu@webrtc.org16d62542013-11-05 23:45:14 +0000261 video_frame.Alias(buffer, buffer_size, width_, height_,
262 1, 1, elapsed_time, time_stamp, 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263
264
265 // Sanity check on decoded frame size.
266 if (buffer_size != static_cast<int>(VideoFrame::SizeOf(width_, height_))) {
267 LOG(LS_WARNING) << "WebRtcRenderAdapter received a strange frame size: "
268 << buffer_size;
269 }
270
271 int ret = renderer_->RenderFrame(&video_frame) ? 0 : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 return ret;
273 }
274
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000275 int DeliverTextureFrame(void* handle, int64 elapsed_time, int64 time_stamp) {
276 WebRtcTextureVideoFrame video_frame(
277 static_cast<webrtc::NativeHandle*>(handle), width_, height_,
278 elapsed_time, time_stamp);
279 return renderer_->RenderFrame(&video_frame);
280 }
281
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000282 unsigned int width() {
283 talk_base::CritScope cs(&crit_);
284 return width_;
285 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000286
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000287 unsigned int height() {
288 talk_base::CritScope cs(&crit_);
289 return height_;
290 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000291
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000292 int framerate() {
293 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000294 return static_cast<int>(frame_rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000295 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +0000296
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297 VideoRenderer* renderer() {
298 talk_base::CritScope cs(&crit_);
299 return renderer_;
300 }
301
302 private:
303 talk_base::CriticalSection crit_;
304 VideoRenderer* renderer_;
305 unsigned int width_;
306 unsigned int height_;
307 talk_base::RateTracker frame_rate_tracker_;
308 bool watermark_enabled_;
309};
310
311class WebRtcDecoderObserver : public webrtc::ViEDecoderObserver {
312 public:
313 explicit WebRtcDecoderObserver(int video_channel)
314 : video_channel_(video_channel),
315 framerate_(0),
316 bitrate_(0),
wu@webrtc.org97077a32013-10-25 21:18:33 +0000317 decode_ms_(0),
318 max_decode_ms_(0),
319 current_delay_ms_(0),
320 target_delay_ms_(0),
321 jitter_buffer_ms_(0),
322 min_playout_delay_ms_(0),
323 render_delay_ms_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000324 firs_requested_(0) {
325 }
326
327 // virtual functions from VieDecoderObserver.
328 virtual void IncomingCodecChanged(const int videoChannel,
329 const webrtc::VideoCodec& videoCodec) {}
330 virtual void IncomingRate(const int videoChannel,
331 const unsigned int framerate,
332 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000333 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000334 ASSERT(video_channel_ == videoChannel);
335 framerate_ = framerate;
336 bitrate_ = bitrate;
337 }
wu@webrtc.org97077a32013-10-25 21:18:33 +0000338
339 virtual void DecoderTiming(int decode_ms,
340 int max_decode_ms,
341 int current_delay_ms,
342 int target_delay_ms,
343 int jitter_buffer_ms,
344 int min_playout_delay_ms,
345 int render_delay_ms) {
346 talk_base::CritScope cs(&crit_);
347 decode_ms_ = decode_ms;
348 max_decode_ms_ = max_decode_ms;
349 current_delay_ms_ = current_delay_ms;
350 target_delay_ms_ = target_delay_ms;
351 jitter_buffer_ms_ = jitter_buffer_ms;
352 min_playout_delay_ms_ = min_playout_delay_ms;
353 render_delay_ms_ = render_delay_ms;
354 }
355
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 virtual void RequestNewKeyFrame(const int videoChannel) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000357 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000358 ASSERT(video_channel_ == videoChannel);
359 ++firs_requested_;
360 }
361
wu@webrtc.org97077a32013-10-25 21:18:33 +0000362 // Populate |rinfo| based on previously-set data in |*this|.
363 void ExportTo(VideoReceiverInfo* rinfo) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000364 talk_base::CritScope cs(&crit_);
wu@webrtc.org97077a32013-10-25 21:18:33 +0000365 rinfo->firs_sent = firs_requested_;
366 rinfo->framerate_rcvd = framerate_;
367 rinfo->decode_ms = decode_ms_;
368 rinfo->max_decode_ms = max_decode_ms_;
369 rinfo->current_delay_ms = current_delay_ms_;
370 rinfo->target_delay_ms = target_delay_ms_;
371 rinfo->jitter_buffer_ms = jitter_buffer_ms_;
372 rinfo->min_playout_delay_ms = min_playout_delay_ms_;
373 rinfo->render_delay_ms = render_delay_ms_;
wu@webrtc.org78187522013-10-07 23:32:02 +0000374 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375
376 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000377 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000378 int video_channel_;
379 int framerate_;
380 int bitrate_;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000381 int decode_ms_;
382 int max_decode_ms_;
383 int current_delay_ms_;
384 int target_delay_ms_;
385 int jitter_buffer_ms_;
386 int min_playout_delay_ms_;
387 int render_delay_ms_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388 int firs_requested_;
389};
390
391class WebRtcEncoderObserver : public webrtc::ViEEncoderObserver {
392 public:
393 explicit WebRtcEncoderObserver(int video_channel)
394 : video_channel_(video_channel),
395 framerate_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000396 bitrate_(0),
397 suspended_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000398 }
399
400 // virtual functions from VieEncoderObserver.
401 virtual void OutgoingRate(const int videoChannel,
402 const unsigned int framerate,
403 const unsigned int bitrate) {
wu@webrtc.org78187522013-10-07 23:32:02 +0000404 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405 ASSERT(video_channel_ == videoChannel);
406 framerate_ = framerate;
407 bitrate_ = bitrate;
408 }
409
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000410 virtual void SuspendChange(int video_channel, bool is_suspended) {
411 talk_base::CritScope cs(&crit_);
412 ASSERT(video_channel_ == video_channel);
413 suspended_ = is_suspended;
414 }
415
wu@webrtc.org78187522013-10-07 23:32:02 +0000416 int framerate() const {
417 talk_base::CritScope cs(&crit_);
418 return framerate_;
419 }
420 int bitrate() const {
421 talk_base::CritScope cs(&crit_);
422 return bitrate_;
423 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000424 bool suspended() const {
425 talk_base::CritScope cs(&crit_);
426 return suspended_;
427 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000428
429 private:
wu@webrtc.org78187522013-10-07 23:32:02 +0000430 mutable talk_base::CriticalSection crit_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000431 int video_channel_;
432 int framerate_;
433 int bitrate_;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000434 bool suspended_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000435};
436
437class WebRtcLocalStreamInfo {
438 public:
439 WebRtcLocalStreamInfo()
440 : width_(0), height_(0), elapsed_time_(-1), time_stamp_(-1) {}
441 size_t width() const {
442 talk_base::CritScope cs(&crit_);
443 return width_;
444 }
445 size_t height() const {
446 talk_base::CritScope cs(&crit_);
447 return height_;
448 }
449 int64 elapsed_time() const {
450 talk_base::CritScope cs(&crit_);
451 return elapsed_time_;
452 }
453 int64 time_stamp() const {
454 talk_base::CritScope cs(&crit_);
455 return time_stamp_;
456 }
457 int framerate() {
458 talk_base::CritScope cs(&crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000459 return static_cast<int>(rate_tracker_.units_second());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000460 }
461 void GetLastFrameInfo(
462 size_t* width, size_t* height, int64* elapsed_time) const {
463 talk_base::CritScope cs(&crit_);
464 *width = width_;
465 *height = height_;
466 *elapsed_time = elapsed_time_;
467 }
468
469 void UpdateFrame(const VideoFrame* frame) {
470 talk_base::CritScope cs(&crit_);
471
472 width_ = frame->GetWidth();
473 height_ = frame->GetHeight();
474 elapsed_time_ = frame->GetElapsedTime();
475 time_stamp_ = frame->GetTimeStamp();
476
477 rate_tracker_.Update(1);
478 }
479
480 private:
481 mutable talk_base::CriticalSection crit_;
482 size_t width_;
483 size_t height_;
484 int64 elapsed_time_;
485 int64 time_stamp_;
486 talk_base::RateTracker rate_tracker_;
487
488 DISALLOW_COPY_AND_ASSIGN(WebRtcLocalStreamInfo);
489};
490
491// WebRtcVideoChannelRecvInfo is a container class with members such as renderer
492// and a decoder observer that is used by receive channels.
493// It must exist as long as the receive channel is connected to renderer or a
494// decoder observer in this class and methods in the class should only be called
495// from the worker thread.
496class WebRtcVideoChannelRecvInfo {
497 public:
498 typedef std::map<int, webrtc::VideoDecoder*> DecoderMap; // key: payload type
499 explicit WebRtcVideoChannelRecvInfo(int channel_id)
500 : channel_id_(channel_id),
501 render_adapter_(NULL),
502 decoder_observer_(channel_id) {
503 }
504 int channel_id() { return channel_id_; }
505 void SetRenderer(VideoRenderer* renderer) {
506 render_adapter_.SetRenderer(renderer);
507 }
508 WebRtcRenderAdapter* render_adapter() { return &render_adapter_; }
509 WebRtcDecoderObserver* decoder_observer() { return &decoder_observer_; }
510 void RegisterDecoder(int pl_type, webrtc::VideoDecoder* decoder) {
511 ASSERT(!IsDecoderRegistered(pl_type));
512 registered_decoders_[pl_type] = decoder;
513 }
514 bool IsDecoderRegistered(int pl_type) {
515 return registered_decoders_.count(pl_type) != 0;
516 }
517 const DecoderMap& registered_decoders() {
518 return registered_decoders_;
519 }
520 void ClearRegisteredDecoders() {
521 registered_decoders_.clear();
522 }
523
524 private:
525 int channel_id_; // Webrtc video channel number.
526 // Renderer for this channel.
527 WebRtcRenderAdapter render_adapter_;
528 WebRtcDecoderObserver decoder_observer_;
529 DecoderMap registered_decoders_;
530};
531
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000532class WebRtcOveruseObserver : public webrtc::CpuOveruseObserver {
533 public:
534 explicit WebRtcOveruseObserver(CoordinatedVideoAdapter* video_adapter)
535 : video_adapter_(video_adapter),
536 enabled_(false) {
537 }
538
539 // TODO(mflodman): Consider sending resolution as part of event, to let
540 // adapter know what resolution the request is based on. Helps eliminate stale
541 // data, race conditions.
542 virtual void OveruseDetected() OVERRIDE {
543 talk_base::CritScope cs(&crit_);
544 if (!enabled_) {
545 return;
546 }
547
548 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::DOWNGRADE);
549 }
550
551 virtual void NormalUsage() OVERRIDE {
552 talk_base::CritScope cs(&crit_);
553 if (!enabled_) {
554 return;
555 }
556
557 video_adapter_->OnCpuResolutionRequest(CoordinatedVideoAdapter::UPGRADE);
558 }
559
560 void Enable(bool enable) {
561 talk_base::CritScope cs(&crit_);
562 enabled_ = enable;
563 }
564
565 private:
566 CoordinatedVideoAdapter* video_adapter_;
567 bool enabled_;
568 talk_base::CriticalSection crit_;
569};
570
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000571
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000572class WebRtcVideoChannelSendInfo : public sigslot::has_slots<> {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 public:
574 typedef std::map<int, webrtc::VideoEncoder*> EncoderMap; // key: payload type
575 WebRtcVideoChannelSendInfo(int channel_id, int capture_id,
576 webrtc::ViEExternalCapture* external_capture,
577 talk_base::CpuMonitor* cpu_monitor)
578 : channel_id_(channel_id),
579 capture_id_(capture_id),
580 sending_(false),
581 muted_(false),
582 video_capturer_(NULL),
583 encoder_observer_(channel_id),
584 external_capture_(external_capture),
585 capturer_updated_(false),
586 interval_(0),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000587 video_adapter_(new CoordinatedVideoAdapter),
588 cpu_monitor_(cpu_monitor) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000589 overuse_observer_.reset(new WebRtcOveruseObserver(video_adapter_.get()));
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000590 SignalCpuAdaptationUnable.repeat(video_adapter_->SignalCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000591 if (cpu_monitor) {
592 cpu_monitor->SignalUpdate.connect(
593 video_adapter_.get(), &CoordinatedVideoAdapter::OnCpuLoadUpdated);
594 }
595 }
596
597 int channel_id() const { return channel_id_; }
598 int capture_id() const { return capture_id_; }
599 void set_sending(bool sending) { sending_ = sending; }
600 bool sending() const { return sending_; }
601 void set_muted(bool on) {
602 // TODO(asapersson): add support.
603 // video_adapter_->SetBlackOutput(on);
604 muted_ = on;
605 }
606 bool muted() {return muted_; }
607
608 WebRtcEncoderObserver* encoder_observer() { return &encoder_observer_; }
609 webrtc::ViEExternalCapture* external_capture() { return external_capture_; }
610 const VideoFormat& video_format() const {
611 return video_format_;
612 }
613 void set_video_format(const VideoFormat& video_format) {
614 video_format_ = video_format;
615 if (video_format_ != cricket::VideoFormat()) {
616 interval_ = video_format_.interval;
617 }
618 video_adapter_->OnOutputFormatRequest(video_format_);
619 }
620 void set_interval(int64 interval) {
621 if (video_format() == cricket::VideoFormat()) {
622 interval_ = interval;
623 }
624 }
625 int64 interval() { return interval_; }
626
627 void InitializeAdapterOutputFormat(const webrtc::VideoCodec& codec) {
628 VideoFormat format(codec.width, codec.height,
629 VideoFormat::FpsToInterval(codec.maxFramerate),
630 FOURCC_I420);
631 if (video_adapter_->output_format().IsSize0x0()) {
632 video_adapter_->SetOutputFormat(format);
633 }
634 }
635
636 bool AdaptFrame(const VideoFrame* in_frame, const VideoFrame** out_frame) {
637 *out_frame = NULL;
638 return video_adapter_->AdaptFrame(in_frame, out_frame);
639 }
640 int CurrentAdaptReason() const {
641 return video_adapter_->adapt_reason();
642 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000643 webrtc::CpuOveruseObserver* overuse_observer() {
644 return overuse_observer_.get();
645 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646
647 StreamParams* stream_params() { return stream_params_.get(); }
648 void set_stream_params(const StreamParams& sp) {
649 stream_params_.reset(new StreamParams(sp));
650 }
651 void ClearStreamParams() { stream_params_.reset(); }
652 bool has_ssrc(uint32 local_ssrc) const {
653 return !stream_params_ ? false :
654 stream_params_->has_ssrc(local_ssrc);
655 }
656 WebRtcLocalStreamInfo* local_stream_info() {
657 return &local_stream_info_;
658 }
659 VideoCapturer* video_capturer() {
660 return video_capturer_;
661 }
662 void set_video_capturer(VideoCapturer* video_capturer) {
663 if (video_capturer == video_capturer_) {
664 return;
665 }
666 capturer_updated_ = true;
667 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.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678 video_adapter_->SetInputFormat(*capture_format);
679 }
680 }
681 }
682
683 void ApplyCpuOptions(const VideoOptions& options) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000684 bool cpu_adapt, cpu_smoothing, adapt_third;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 float low, med, high;
686 if (options.adapt_input_to_cpu_usage.Get(&cpu_adapt)) {
687 video_adapter_->set_cpu_adaptation(cpu_adapt);
688 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000689 if (options.adapt_cpu_with_smoothing.Get(&cpu_smoothing)) {
690 video_adapter_->set_cpu_smoothing(cpu_smoothing);
691 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692 if (options.process_adaptation_threshhold.Get(&med)) {
693 video_adapter_->set_process_threshold(med);
694 }
695 if (options.system_low_adaptation_threshhold.Get(&low)) {
696 video_adapter_->set_low_system_threshold(low);
697 }
698 if (options.system_high_adaptation_threshhold.Get(&high)) {
699 video_adapter_->set_high_system_threshold(high);
700 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000701 if (options.video_adapt_third.Get(&adapt_third)) {
702 video_adapter_->set_scale_third(adapt_third);
703 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000705
706 void SetCpuOveruseDetection(bool enable) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000707 if (cpu_monitor_ && enable) {
708 cpu_monitor_->SignalUpdate.disconnect(video_adapter_.get());
709 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000710 overuse_observer_->Enable(enable);
711 video_adapter_->set_cpu_adaptation(enable);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000712 }
713
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714 void ProcessFrame(const VideoFrame& original_frame, bool mute,
715 VideoFrame** processed_frame) {
716 if (!mute) {
717 *processed_frame = original_frame.Copy();
718 } else {
719 WebRtcVideoFrame* black_frame = new WebRtcVideoFrame();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000720 black_frame->InitToBlack(static_cast<int>(original_frame.GetWidth()),
721 static_cast<int>(original_frame.GetHeight()),
722 1, 1,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 original_frame.GetElapsedTime(),
724 original_frame.GetTimeStamp());
725 *processed_frame = black_frame;
726 }
727 local_stream_info_.UpdateFrame(*processed_frame);
728 }
729 void RegisterEncoder(int pl_type, webrtc::VideoEncoder* encoder) {
730 ASSERT(!IsEncoderRegistered(pl_type));
731 registered_encoders_[pl_type] = encoder;
732 }
733 bool IsEncoderRegistered(int pl_type) {
734 return registered_encoders_.count(pl_type) != 0;
735 }
736 const EncoderMap& registered_encoders() {
737 return registered_encoders_;
738 }
739 void ClearRegisteredEncoders() {
740 registered_encoders_.clear();
741 }
742
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000743 sigslot::repeater0<> SignalCpuAdaptationUnable;
744
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 private:
746 int channel_id_;
747 int capture_id_;
748 bool sending_;
749 bool muted_;
750 VideoCapturer* video_capturer_;
751 WebRtcEncoderObserver encoder_observer_;
752 webrtc::ViEExternalCapture* external_capture_;
753 EncoderMap registered_encoders_;
754
755 VideoFormat video_format_;
756
757 talk_base::scoped_ptr<StreamParams> stream_params_;
758
759 WebRtcLocalStreamInfo local_stream_info_;
760
761 bool capturer_updated_;
762
763 int64 interval_;
764
765 talk_base::scoped_ptr<CoordinatedVideoAdapter> video_adapter_;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000766 talk_base::CpuMonitor* cpu_monitor_;
wu@webrtc.orgcadf9042013-08-30 21:24:16 +0000767 talk_base::scoped_ptr<WebRtcOveruseObserver> overuse_observer_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768};
769
770const WebRtcVideoEngine::VideoCodecPref
771 WebRtcVideoEngine::kVideoCodecPrefs[] = {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000772 {kVp8PayloadName, 100, -1, 0},
773 {kRedPayloadName, 116, -1, 1},
774 {kFecPayloadName, 117, -1, 2},
775 {kRtxCodecName, 96, 100, 3},
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776};
777
778// The formats are sorted by the descending order of width. We use the order to
779// find the next format for CPU and bandwidth adaptation.
780const VideoFormatPod WebRtcVideoEngine::kVideoFormats[] = {
781 {1280, 800, FPS_TO_INTERVAL(30), FOURCC_ANY},
782 {1280, 720, FPS_TO_INTERVAL(30), FOURCC_ANY},
783 {960, 600, FPS_TO_INTERVAL(30), FOURCC_ANY},
784 {960, 540, FPS_TO_INTERVAL(30), FOURCC_ANY},
785 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY},
786 {640, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
787 {640, 480, FPS_TO_INTERVAL(30), FOURCC_ANY},
788 {480, 300, FPS_TO_INTERVAL(30), FOURCC_ANY},
789 {480, 270, FPS_TO_INTERVAL(30), FOURCC_ANY},
790 {480, 360, FPS_TO_INTERVAL(30), FOURCC_ANY},
791 {320, 200, FPS_TO_INTERVAL(30), FOURCC_ANY},
792 {320, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
793 {320, 240, FPS_TO_INTERVAL(30), FOURCC_ANY},
794 {240, 150, FPS_TO_INTERVAL(30), FOURCC_ANY},
795 {240, 135, FPS_TO_INTERVAL(30), FOURCC_ANY},
796 {240, 180, FPS_TO_INTERVAL(30), FOURCC_ANY},
797 {160, 100, FPS_TO_INTERVAL(30), FOURCC_ANY},
798 {160, 90, FPS_TO_INTERVAL(30), FOURCC_ANY},
799 {160, 120, FPS_TO_INTERVAL(30), FOURCC_ANY},
800};
801
802const VideoFormatPod WebRtcVideoEngine::kDefaultVideoFormat =
803 {640, 400, FPS_TO_INTERVAL(30), FOURCC_ANY};
804
805static void UpdateVideoCodec(const cricket::VideoFormat& video_format,
806 webrtc::VideoCodec* target_codec) {
807 if ((target_codec == NULL) || (video_format == cricket::VideoFormat())) {
808 return;
809 }
810 target_codec->width = video_format.width;
811 target_codec->height = video_format.height;
812 target_codec->maxFramerate = cricket::VideoFormat::IntervalToFps(
813 video_format.interval);
814}
815
816WebRtcVideoEngine::WebRtcVideoEngine() {
817 Construct(new ViEWrapper(), new ViETraceWrapper(), NULL,
818 new talk_base::CpuMonitor(NULL));
819}
820
821WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
822 ViEWrapper* vie_wrapper,
823 talk_base::CpuMonitor* cpu_monitor) {
824 Construct(vie_wrapper, new ViETraceWrapper(), voice_engine, cpu_monitor);
825}
826
827WebRtcVideoEngine::WebRtcVideoEngine(WebRtcVoiceEngine* voice_engine,
828 ViEWrapper* vie_wrapper,
829 ViETraceWrapper* tracing,
830 talk_base::CpuMonitor* cpu_monitor) {
831 Construct(vie_wrapper, tracing, voice_engine, cpu_monitor);
832}
833
834void WebRtcVideoEngine::Construct(ViEWrapper* vie_wrapper,
835 ViETraceWrapper* tracing,
836 WebRtcVoiceEngine* voice_engine,
837 talk_base::CpuMonitor* cpu_monitor) {
838 LOG(LS_INFO) << "WebRtcVideoEngine::WebRtcVideoEngine";
839 worker_thread_ = NULL;
840 vie_wrapper_.reset(vie_wrapper);
841 vie_wrapper_base_initialized_ = false;
842 tracing_.reset(tracing);
843 voice_engine_ = voice_engine;
844 initialized_ = false;
845 SetTraceFilter(SeverityToFilter(kDefaultLogSeverity));
846 render_module_.reset(new WebRtcPassthroughRender());
847 local_renderer_w_ = local_renderer_h_ = 0;
848 local_renderer_ = NULL;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849 capture_started_ = false;
850 decoder_factory_ = NULL;
851 encoder_factory_ = NULL;
852 cpu_monitor_.reset(cpu_monitor);
853
854 SetTraceOptions("");
855 if (tracing_->SetTraceCallback(this) != 0) {
856 LOG_RTCERR1(SetTraceCallback, this);
857 }
858
859 // Set default quality levels for our supported codecs. We override them here
860 // if we know your cpu performance is low, and they can be updated explicitly
861 // by calling SetDefaultCodec. For example by a flute preference setting, or
862 // by the server with a jec in response to our reported system info.
863 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
864 kVideoCodecPrefs[0].name,
865 kDefaultVideoFormat.width,
866 kDefaultVideoFormat.height,
867 VideoFormat::IntervalToFps(kDefaultVideoFormat.interval),
868 0);
869 if (!SetDefaultCodec(max_codec)) {
870 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
871 }
872
873
874 // Load our RTP Header extensions.
875 rtp_header_extensions_.push_back(
876 RtpHeaderExtension(kRtpTimestampOffsetHeaderExtension,
877 kRtpTimeOffsetExtensionId));
878 rtp_header_extensions_.push_back(
879 RtpHeaderExtension(kRtpAbsoluteSendTimeHeaderExtension,
880 kRtpAbsoluteSendTimeExtensionId));
881}
882
883WebRtcVideoEngine::~WebRtcVideoEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884 LOG(LS_INFO) << "WebRtcVideoEngine::~WebRtcVideoEngine";
885 if (initialized_) {
886 Terminate();
887 }
888 if (encoder_factory_) {
889 encoder_factory_->RemoveObserver(this);
890 }
891 tracing_->SetTraceCallback(NULL);
892 // Test to see if the media processor was deregistered properly.
893 ASSERT(SignalMediaFrame.is_empty());
894}
895
896bool WebRtcVideoEngine::Init(talk_base::Thread* worker_thread) {
897 LOG(LS_INFO) << "WebRtcVideoEngine::Init";
898 worker_thread_ = worker_thread;
899 ASSERT(worker_thread_ != NULL);
900
901 cpu_monitor_->set_thread(worker_thread_);
902 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
903 LOG(LS_ERROR) << "Failed to start CPU monitor.";
904 cpu_monitor_.reset();
905 }
906
907 bool result = InitVideoEngine();
908 if (result) {
909 LOG(LS_INFO) << "VideoEngine Init done";
910 } else {
911 LOG(LS_ERROR) << "VideoEngine Init failed, releasing";
912 Terminate();
913 }
914 return result;
915}
916
917bool WebRtcVideoEngine::InitVideoEngine() {
918 LOG(LS_INFO) << "WebRtcVideoEngine::InitVideoEngine";
919
920 // Init WebRTC VideoEngine.
921 if (!vie_wrapper_base_initialized_) {
922 if (vie_wrapper_->base()->Init() != 0) {
923 LOG_RTCERR0(Init);
924 return false;
925 }
926 vie_wrapper_base_initialized_ = true;
927 }
928
929 // Log the VoiceEngine version info.
930 char buffer[1024] = "";
931 if (vie_wrapper_->base()->GetVersion(buffer) != 0) {
932 LOG_RTCERR0(GetVersion);
933 return false;
934 }
935
936 LOG(LS_INFO) << "WebRtc VideoEngine Version:";
937 LogMultiline(talk_base::LS_INFO, buffer);
938
939 // Hook up to VoiceEngine for sync purposes, if supplied.
940 if (!voice_engine_) {
941 LOG(LS_WARNING) << "NULL voice engine";
942 } else if ((vie_wrapper_->base()->SetVoiceEngine(
943 voice_engine_->voe()->engine())) != 0) {
944 LOG_RTCERR0(SetVoiceEngine);
945 return false;
946 }
947
948 // Register our custom render module.
949 if (vie_wrapper_->render()->RegisterVideoRenderModule(
950 *render_module_.get()) != 0) {
951 LOG_RTCERR0(RegisterVideoRenderModule);
952 return false;
953 }
954
955 initialized_ = true;
956 return true;
957}
958
959void WebRtcVideoEngine::Terminate() {
960 LOG(LS_INFO) << "WebRtcVideoEngine::Terminate";
961 initialized_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962
963 if (vie_wrapper_->render()->DeRegisterVideoRenderModule(
964 *render_module_.get()) != 0) {
965 LOG_RTCERR0(DeRegisterVideoRenderModule);
966 }
967
968 if (vie_wrapper_->base()->SetVoiceEngine(NULL) != 0) {
969 LOG_RTCERR0(SetVoiceEngine);
970 }
971
972 cpu_monitor_->Stop();
973}
974
975int WebRtcVideoEngine::GetCapabilities() {
976 return VIDEO_RECV | VIDEO_SEND;
977}
978
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000979bool WebRtcVideoEngine::SetOptions(const VideoOptions &options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 return true;
981}
982
983bool WebRtcVideoEngine::SetDefaultEncoderConfig(
984 const VideoEncoderConfig& config) {
985 return SetDefaultCodec(config.max_codec);
986}
987
wu@webrtc.org78187522013-10-07 23:32:02 +0000988VideoEncoderConfig WebRtcVideoEngine::GetDefaultEncoderConfig() const {
989 ASSERT(!video_codecs_.empty());
990 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
991 kVideoCodecPrefs[0].name,
992 video_codecs_[0].width,
993 video_codecs_[0].height,
994 video_codecs_[0].framerate,
995 0);
996 return VideoEncoderConfig(max_codec);
997}
998
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999// SetDefaultCodec may be called while the capturer is running. For example, a
1000// test call is started in a page with QVGA default codec, and then a real call
1001// is started in another page with VGA default codec. This is the corner case
1002// and happens only when a session is started. We ignore this case currently.
1003bool WebRtcVideoEngine::SetDefaultCodec(const VideoCodec& codec) {
1004 if (!RebuildCodecList(codec)) {
1005 LOG(LS_WARNING) << "Failed to RebuildCodecList";
1006 return false;
1007 }
1008
wu@webrtc.org78187522013-10-07 23:32:02 +00001009 ASSERT(!video_codecs_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 default_codec_format_ = VideoFormat(
1011 video_codecs_[0].width,
1012 video_codecs_[0].height,
1013 VideoFormat::FpsToInterval(video_codecs_[0].framerate),
1014 FOURCC_ANY);
1015 return true;
1016}
1017
1018WebRtcVideoMediaChannel* WebRtcVideoEngine::CreateChannel(
1019 VoiceMediaChannel* voice_channel) {
1020 WebRtcVideoMediaChannel* channel =
1021 new WebRtcVideoMediaChannel(this, voice_channel);
1022 if (!channel->Init()) {
1023 delete channel;
1024 channel = NULL;
1025 }
1026 return channel;
1027}
1028
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001029bool WebRtcVideoEngine::SetLocalRenderer(VideoRenderer* renderer) {
1030 local_renderer_w_ = local_renderer_h_ = 0;
1031 local_renderer_ = renderer;
1032 return true;
1033}
1034
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035const std::vector<VideoCodec>& WebRtcVideoEngine::codecs() const {
1036 return video_codecs_;
1037}
1038
1039const std::vector<RtpHeaderExtension>&
1040WebRtcVideoEngine::rtp_header_extensions() const {
1041 return rtp_header_extensions_;
1042}
1043
1044void WebRtcVideoEngine::SetLogging(int min_sev, const char* filter) {
1045 // if min_sev == -1, we keep the current log level.
1046 if (min_sev >= 0) {
1047 SetTraceFilter(SeverityToFilter(min_sev));
1048 }
1049 SetTraceOptions(filter);
1050}
1051
1052int WebRtcVideoEngine::GetLastEngineError() {
1053 return vie_wrapper_->error();
1054}
1055
1056// Checks to see whether we comprehend and could receive a particular codec
1057bool WebRtcVideoEngine::FindCodec(const VideoCodec& in) {
1058 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
1059 const VideoFormat fmt(kVideoFormats[i]);
1060 if ((in.width == 0 && in.height == 0) ||
1061 (fmt.width == in.width && fmt.height == in.height)) {
1062 if (encoder_factory_) {
1063 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1064 encoder_factory_->codecs();
1065 for (size_t j = 0; j < codecs.size(); ++j) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001066 VideoCodec codec(GetExternalVideoPayloadType(static_cast<int>(j)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 codecs[j].name, 0, 0, 0, 0);
1068 if (codec.Matches(in))
1069 return true;
1070 }
1071 }
1072 for (size_t j = 0; j < ARRAY_SIZE(kVideoCodecPrefs); ++j) {
1073 VideoCodec codec(kVideoCodecPrefs[j].payload_type,
1074 kVideoCodecPrefs[j].name, 0, 0, 0, 0);
1075 if (codec.Matches(in)) {
1076 return true;
1077 }
1078 }
1079 }
1080 }
1081 return false;
1082}
1083
1084// Given the requested codec, returns true if we can send that codec type and
1085// updates out with the best quality we could send for that codec. If current is
1086// not empty, we constrain out so that its aspect ratio matches current's.
1087bool WebRtcVideoEngine::CanSendCodec(const VideoCodec& requested,
1088 const VideoCodec& current,
1089 VideoCodec* out) {
1090 if (!out) {
1091 return false;
1092 }
1093
1094 std::vector<VideoCodec>::const_iterator local_max;
1095 for (local_max = video_codecs_.begin();
1096 local_max < video_codecs_.end();
1097 ++local_max) {
1098 // First match codecs by payload type
1099 if (!requested.Matches(*local_max)) {
1100 continue;
1101 }
1102
1103 out->id = requested.id;
1104 out->name = requested.name;
1105 out->preference = requested.preference;
1106 out->params = requested.params;
1107 out->framerate = talk_base::_min(requested.framerate, local_max->framerate);
1108 out->width = 0;
1109 out->height = 0;
1110 out->params = requested.params;
1111 out->feedback_params = requested.feedback_params;
1112
1113 if (0 == requested.width && 0 == requested.height) {
1114 // Special case with resolution 0. The channel should not send frames.
1115 return true;
1116 } else if (0 == requested.width || 0 == requested.height) {
1117 // 0xn and nx0 are invalid resolutions.
1118 return false;
1119 }
1120
1121 // Pick the best quality that is within their and our bounds and has the
1122 // correct aspect ratio.
1123 for (int j = 0; j < ARRAY_SIZE(kVideoFormats); ++j) {
1124 const VideoFormat format(kVideoFormats[j]);
1125
1126 // Skip any format that is larger than the local or remote maximums, or
1127 // smaller than the current best match
1128 if (format.width > requested.width || format.height > requested.height ||
1129 format.width > local_max->width ||
1130 (format.width < out->width && format.height < out->height)) {
1131 continue;
1132 }
1133
1134 bool better = false;
1135
1136 // Check any further constraints on this prospective format
1137 if (!out->width || !out->height) {
1138 // If we don't have any matches yet, this is the best so far.
1139 better = true;
1140 } else if (current.width && current.height) {
1141 // current is set so format must match its ratio exactly.
1142 better =
1143 (format.width * current.height == format.height * current.width);
1144 } else {
1145 // Prefer closer aspect ratios i.e
1146 // format.aspect - requested.aspect < out.aspect - requested.aspect
1147 better = abs(format.width * requested.height * out->height -
1148 requested.width * format.height * out->height) <
1149 abs(out->width * format.height * requested.height -
1150 requested.width * format.height * out->height);
1151 }
1152
1153 if (better) {
1154 out->width = format.width;
1155 out->height = format.height;
1156 }
1157 }
1158 if (out->width > 0) {
1159 return true;
1160 }
1161 }
1162 return false;
1163}
1164
1165static void ConvertToCricketVideoCodec(
1166 const webrtc::VideoCodec& in_codec, VideoCodec* out_codec) {
1167 out_codec->id = in_codec.plType;
1168 out_codec->name = in_codec.plName;
1169 out_codec->width = in_codec.width;
1170 out_codec->height = in_codec.height;
1171 out_codec->framerate = in_codec.maxFramerate;
1172 out_codec->SetParam(kCodecParamMinBitrate, in_codec.minBitrate);
1173 out_codec->SetParam(kCodecParamMaxBitrate, in_codec.maxBitrate);
1174 if (in_codec.qpMax) {
1175 out_codec->SetParam(kCodecParamMaxQuantization, in_codec.qpMax);
1176 }
1177}
1178
1179bool WebRtcVideoEngine::ConvertFromCricketVideoCodec(
1180 const VideoCodec& in_codec, webrtc::VideoCodec* out_codec) {
1181 bool found = false;
1182 int ncodecs = vie_wrapper_->codec()->NumberOfCodecs();
1183 for (int i = 0; i < ncodecs; ++i) {
1184 if (vie_wrapper_->codec()->GetCodec(i, *out_codec) == 0 &&
1185 _stricmp(in_codec.name.c_str(), out_codec->plName) == 0) {
1186 found = true;
1187 break;
1188 }
1189 }
1190
1191 // If not found, check if this is supported by external encoder factory.
1192 if (!found && encoder_factory_) {
1193 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1194 encoder_factory_->codecs();
1195 for (size_t i = 0; i < codecs.size(); ++i) {
1196 if (_stricmp(in_codec.name.c_str(), codecs[i].name.c_str()) == 0) {
1197 out_codec->codecType = codecs[i].type;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001198 out_codec->plType = GetExternalVideoPayloadType(static_cast<int>(i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199 talk_base::strcpyn(out_codec->plName, sizeof(out_codec->plName),
1200 codecs[i].name.c_str(), codecs[i].name.length());
1201 found = true;
1202 break;
1203 }
1204 }
1205 }
1206
1207 if (!found) {
1208 LOG(LS_ERROR) << "invalid codec type";
1209 return false;
1210 }
1211
1212 if (in_codec.id != 0)
1213 out_codec->plType = in_codec.id;
1214
1215 if (in_codec.width != 0)
1216 out_codec->width = in_codec.width;
1217
1218 if (in_codec.height != 0)
1219 out_codec->height = in_codec.height;
1220
1221 if (in_codec.framerate != 0)
1222 out_codec->maxFramerate = in_codec.framerate;
1223
1224 // Convert bitrate parameters.
1225 int max_bitrate = kMaxVideoBitrate;
1226 int min_bitrate = kMinVideoBitrate;
1227 int start_bitrate = kStartVideoBitrate;
1228
1229 in_codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
1230 in_codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
1231
1232 if (max_bitrate < min_bitrate) {
1233 return false;
1234 }
1235 start_bitrate = talk_base::_max(start_bitrate, min_bitrate);
1236 start_bitrate = talk_base::_min(start_bitrate, max_bitrate);
1237
1238 out_codec->minBitrate = min_bitrate;
1239 out_codec->startBitrate = start_bitrate;
1240 out_codec->maxBitrate = max_bitrate;
1241
1242 // Convert general codec parameters.
1243 int max_quantization = 0;
1244 if (in_codec.GetParam(kCodecParamMaxQuantization, &max_quantization)) {
1245 if (max_quantization < 0) {
1246 return false;
1247 }
1248 out_codec->qpMax = max_quantization;
1249 }
1250 return true;
1251}
1252
1253void WebRtcVideoEngine::RegisterChannel(WebRtcVideoMediaChannel *channel) {
1254 talk_base::CritScope cs(&channels_crit_);
1255 channels_.push_back(channel);
1256}
1257
1258void WebRtcVideoEngine::UnregisterChannel(WebRtcVideoMediaChannel *channel) {
1259 talk_base::CritScope cs(&channels_crit_);
1260 channels_.erase(std::remove(channels_.begin(), channels_.end(), channel),
1261 channels_.end());
1262}
1263
1264bool WebRtcVideoEngine::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
1265 if (initialized_) {
1266 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
1267 return false;
1268 }
1269 voice_engine_ = voice_engine;
1270 return true;
1271}
1272
1273bool WebRtcVideoEngine::EnableTimedRender() {
1274 if (initialized_) {
1275 LOG(LS_WARNING) << "EnableTimedRender can not be called after Init";
1276 return false;
1277 }
1278 render_module_.reset(webrtc::VideoRender::CreateVideoRender(0, NULL,
1279 false, webrtc::kRenderExternal));
1280 return true;
1281}
1282
1283void WebRtcVideoEngine::SetTraceFilter(int filter) {
1284 tracing_->SetTraceFilter(filter);
1285}
1286
1287// See https://sites.google.com/a/google.com/wavelet/
1288// Home/Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters
1289// for all supported command line setttings.
1290void WebRtcVideoEngine::SetTraceOptions(const std::string& options) {
1291 // Set WebRTC trace file.
1292 std::vector<std::string> opts;
1293 talk_base::tokenize(options, ' ', '"', '"', &opts);
1294 std::vector<std::string>::iterator tracefile =
1295 std::find(opts.begin(), opts.end(), "tracefile");
1296 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1297 // Write WebRTC debug output (at same loglevel) to file
1298 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1299 LOG_RTCERR1(SetTraceFile, *tracefile);
1300 }
1301 }
1302}
1303
1304static void AddDefaultFeedbackParams(VideoCodec* codec) {
1305 const FeedbackParam kFir(kRtcpFbParamCcm, kRtcpFbCcmParamFir);
1306 codec->AddFeedbackParam(kFir);
1307 const FeedbackParam kNack(kRtcpFbParamNack, kParamValueEmpty);
1308 codec->AddFeedbackParam(kNack);
1309 const FeedbackParam kRemb(kRtcpFbParamRemb, kParamValueEmpty);
1310 codec->AddFeedbackParam(kRemb);
1311}
1312
1313// Rebuilds the codec list to be only those that are less intensive
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001314// than the specified codec. Prefers internal codec over external with
1315// higher preference field.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316bool WebRtcVideoEngine::RebuildCodecList(const VideoCodec& in_codec) {
1317 if (!FindCodec(in_codec))
1318 return false;
1319
1320 video_codecs_.clear();
1321
1322 bool found = false;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001323 std::set<std::string> internal_codec_names;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 for (size_t i = 0; i < ARRAY_SIZE(kVideoCodecPrefs); ++i) {
1325 const VideoCodecPref& pref(kVideoCodecPrefs[i]);
1326 if (!found)
1327 found = (in_codec.name == pref.name);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001328 if (found) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 VideoCodec codec(pref.payload_type, pref.name,
1330 in_codec.width, in_codec.height, in_codec.framerate,
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001331 static_cast<int>(ARRAY_SIZE(kVideoCodecPrefs) - i));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 if (_stricmp(kVp8PayloadName, codec.name.c_str()) == 0) {
1333 AddDefaultFeedbackParams(&codec);
1334 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001335 if (pref.associated_payload_type != -1) {
1336 codec.SetParam(kCodecParamAssociatedPayloadType,
1337 pref.associated_payload_type);
1338 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339 video_codecs_.push_back(codec);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001340 internal_codec_names.insert(codec.name);
1341 }
1342 }
1343 if (encoder_factory_) {
1344 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1345 encoder_factory_->codecs();
1346 for (size_t i = 0; i < codecs.size(); ++i) {
1347 bool is_internal_codec = internal_codec_names.find(codecs[i].name) !=
1348 internal_codec_names.end();
1349 if (!is_internal_codec) {
1350 if (!found)
1351 found = (in_codec.name == codecs[i].name);
1352 VideoCodec codec(
1353 GetExternalVideoPayloadType(static_cast<int>(i)),
1354 codecs[i].name,
1355 codecs[i].max_width,
1356 codecs[i].max_height,
1357 codecs[i].max_fps,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001358 // Use negative preference on external codec to ensure the internal
1359 // codec is preferred.
1360 static_cast<int>(0 - i));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +00001361 AddDefaultFeedbackParams(&codec);
1362 video_codecs_.push_back(codec);
1363 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 }
1365 }
1366 ASSERT(found);
1367 return true;
1368}
1369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370// Ignore spammy trace messages, mostly from the stats API when we haven't
1371// gotten RTCP info yet from the remote side.
1372bool WebRtcVideoEngine::ShouldIgnoreTrace(const std::string& trace) {
1373 static const char* const kTracesToIgnore[] = {
1374 NULL
1375 };
1376 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1377 if (trace.find(*p) == 0) {
1378 return true;
1379 }
1380 }
1381 return false;
1382}
1383
1384int WebRtcVideoEngine::GetNumOfChannels() {
1385 talk_base::CritScope cs(&channels_crit_);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001386 return static_cast<int>(channels_.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387}
1388
1389void WebRtcVideoEngine::Print(webrtc::TraceLevel level, const char* trace,
1390 int length) {
1391 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1392 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1393 sev = talk_base::LS_ERROR;
1394 else if (level == webrtc::kTraceWarning)
1395 sev = talk_base::LS_WARNING;
1396 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1397 sev = talk_base::LS_INFO;
1398 else if (level == webrtc::kTraceTerseInfo)
1399 sev = talk_base::LS_INFO;
1400
1401 // Skip past boilerplate prefix text
1402 if (length < 72) {
1403 std::string msg(trace, length);
1404 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1405 LOG_V(sev) << msg;
1406 } else {
1407 std::string msg(trace + 71, length - 72);
1408 if (!ShouldIgnoreTrace(msg) &&
1409 (!voice_engine_ || !voice_engine_->ShouldIgnoreTrace(msg))) {
1410 LOG_V(sev) << "webrtc: " << msg;
1411 }
1412 }
1413}
1414
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415webrtc::VideoDecoder* WebRtcVideoEngine::CreateExternalDecoder(
1416 webrtc::VideoCodecType type) {
1417 if (decoder_factory_ == NULL) {
1418 return NULL;
1419 }
1420 return decoder_factory_->CreateVideoDecoder(type);
1421}
1422
1423void WebRtcVideoEngine::DestroyExternalDecoder(webrtc::VideoDecoder* decoder) {
1424 ASSERT(decoder_factory_ != NULL);
1425 if (decoder_factory_ == NULL)
1426 return;
1427 decoder_factory_->DestroyVideoDecoder(decoder);
1428}
1429
1430webrtc::VideoEncoder* WebRtcVideoEngine::CreateExternalEncoder(
1431 webrtc::VideoCodecType type) {
1432 if (encoder_factory_ == NULL) {
1433 return NULL;
1434 }
1435 return encoder_factory_->CreateVideoEncoder(type);
1436}
1437
1438void WebRtcVideoEngine::DestroyExternalEncoder(webrtc::VideoEncoder* encoder) {
1439 ASSERT(encoder_factory_ != NULL);
1440 if (encoder_factory_ == NULL)
1441 return;
1442 encoder_factory_->DestroyVideoEncoder(encoder);
1443}
1444
1445bool WebRtcVideoEngine::IsExternalEncoderCodecType(
1446 webrtc::VideoCodecType type) const {
1447 if (!encoder_factory_)
1448 return false;
1449 const std::vector<WebRtcVideoEncoderFactory::VideoCodec>& codecs =
1450 encoder_factory_->codecs();
1451 std::vector<WebRtcVideoEncoderFactory::VideoCodec>::const_iterator it;
1452 for (it = codecs.begin(); it != codecs.end(); ++it) {
1453 if (it->type == type)
1454 return true;
1455 }
1456 return false;
1457}
1458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459void WebRtcVideoEngine::SetExternalDecoderFactory(
1460 WebRtcVideoDecoderFactory* decoder_factory) {
1461 decoder_factory_ = decoder_factory;
1462}
1463
1464void WebRtcVideoEngine::SetExternalEncoderFactory(
1465 WebRtcVideoEncoderFactory* encoder_factory) {
1466 if (encoder_factory_ == encoder_factory)
1467 return;
1468
1469 if (encoder_factory_) {
1470 encoder_factory_->RemoveObserver(this);
1471 }
1472 encoder_factory_ = encoder_factory;
1473 if (encoder_factory_) {
1474 encoder_factory_->AddObserver(this);
1475 }
1476
1477 // Invoke OnCodecAvailable() here in case the list of codecs is already
1478 // available when the encoder factory is installed. If not the encoder
1479 // factory will invoke the callback later when the codecs become available.
1480 OnCodecsAvailable();
1481}
1482
1483void WebRtcVideoEngine::OnCodecsAvailable() {
1484 // Rebuild codec list while reapplying the current default codec format.
1485 VideoCodec max_codec(kVideoCodecPrefs[0].payload_type,
1486 kVideoCodecPrefs[0].name,
1487 video_codecs_[0].width,
1488 video_codecs_[0].height,
1489 video_codecs_[0].framerate,
1490 0);
1491 if (!RebuildCodecList(max_codec)) {
1492 LOG(LS_ERROR) << "Failed to initialize list of supported codec types";
1493 }
1494}
1495
1496// WebRtcVideoMediaChannel
1497
1498WebRtcVideoMediaChannel::WebRtcVideoMediaChannel(
1499 WebRtcVideoEngine* engine,
1500 VoiceMediaChannel* channel)
1501 : engine_(engine),
1502 voice_channel_(channel),
1503 vie_channel_(-1),
1504 nack_enabled_(true),
1505 remb_enabled_(false),
1506 render_started_(false),
1507 first_receive_ssrc_(0),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001508 send_rtx_type_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 send_red_type_(-1),
1510 send_fec_type_(-1),
1511 send_min_bitrate_(kMinVideoBitrate),
1512 send_start_bitrate_(kStartVideoBitrate),
1513 send_max_bitrate_(kMaxVideoBitrate),
1514 sending_(false),
1515 ratio_w_(0),
1516 ratio_h_(0) {
1517 engine->RegisterChannel(this);
1518}
1519
1520bool WebRtcVideoMediaChannel::Init() {
1521 const uint32 ssrc_key = 0;
1522 return CreateChannel(ssrc_key, MD_SENDRECV, &vie_channel_);
1523}
1524
1525WebRtcVideoMediaChannel::~WebRtcVideoMediaChannel() {
1526 const bool send = false;
1527 SetSend(send);
1528 const bool render = false;
1529 SetRender(render);
1530
1531 while (!send_channels_.empty()) {
1532 if (!DeleteSendChannel(send_channels_.begin()->first)) {
1533 LOG(LS_ERROR) << "Unable to delete channel with ssrc key "
1534 << send_channels_.begin()->first;
1535 ASSERT(false);
1536 break;
1537 }
1538 }
1539
1540 // Remove all receive streams and the default channel.
1541 while (!recv_channels_.empty()) {
1542 RemoveRecvStream(recv_channels_.begin()->first);
1543 }
1544
1545 // Unregister the channel from the engine.
1546 engine()->UnregisterChannel(this);
1547 if (worker_thread()) {
1548 worker_thread()->Clear(this);
1549 }
1550}
1551
1552bool WebRtcVideoMediaChannel::SetRecvCodecs(
1553 const std::vector<VideoCodec>& codecs) {
1554 receive_codecs_.clear();
1555 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1556 iter != codecs.end(); ++iter) {
1557 if (engine()->FindCodec(*iter)) {
1558 webrtc::VideoCodec wcodec;
1559 if (engine()->ConvertFromCricketVideoCodec(*iter, &wcodec)) {
1560 receive_codecs_.push_back(wcodec);
1561 }
1562 } else {
1563 LOG(LS_INFO) << "Unknown codec " << iter->name;
1564 return false;
1565 }
1566 }
1567
1568 for (RecvChannelMap::iterator it = recv_channels_.begin();
1569 it != recv_channels_.end(); ++it) {
1570 if (!SetReceiveCodecs(it->second))
1571 return false;
1572 }
1573 return true;
1574}
1575
1576bool WebRtcVideoMediaChannel::SetSendCodecs(
1577 const std::vector<VideoCodec>& codecs) {
1578 // Match with local video codec list.
1579 std::vector<webrtc::VideoCodec> send_codecs;
1580 VideoCodec checked_codec;
1581 VideoCodec current; // defaults to 0x0
1582 if (sending_) {
1583 ConvertToCricketVideoCodec(*send_codec_, &current);
1584 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001585 std::map<int, int> primary_rtx_pt_mapping;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 for (std::vector<VideoCodec>::const_iterator iter = codecs.begin();
1587 iter != codecs.end(); ++iter) {
1588 if (_stricmp(iter->name.c_str(), kRedPayloadName) == 0) {
1589 send_red_type_ = iter->id;
1590 } else if (_stricmp(iter->name.c_str(), kFecPayloadName) == 0) {
1591 send_fec_type_ = iter->id;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001592 } else if (_stricmp(iter->name.c_str(), kRtxCodecName) == 0) {
1593 int rtx_type = iter->id;
1594 int rtx_primary_type = -1;
1595 if (iter->GetParam(kCodecParamAssociatedPayloadType, &rtx_primary_type)) {
1596 primary_rtx_pt_mapping[rtx_primary_type] = rtx_type;
1597 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598 } else if (engine()->CanSendCodec(*iter, current, &checked_codec)) {
1599 webrtc::VideoCodec wcodec;
1600 if (engine()->ConvertFromCricketVideoCodec(checked_codec, &wcodec)) {
1601 if (send_codecs.empty()) {
1602 nack_enabled_ = IsNackEnabled(checked_codec);
1603 remb_enabled_ = IsRembEnabled(checked_codec);
1604 }
1605 send_codecs.push_back(wcodec);
1606 }
1607 } else {
1608 LOG(LS_WARNING) << "Unknown codec " << iter->name;
1609 }
1610 }
1611
1612 // Fail if we don't have a match.
1613 if (send_codecs.empty()) {
1614 LOG(LS_WARNING) << "No matching codecs available";
1615 return false;
1616 }
1617
1618 // Recv protection.
1619 for (RecvChannelMap::iterator it = recv_channels_.begin();
1620 it != recv_channels_.end(); ++it) {
1621 int channel_id = it->second->channel_id();
1622 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1623 nack_enabled_)) {
1624 return false;
1625 }
1626 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1627 kNotSending,
1628 remb_enabled_) != 0) {
1629 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
1630 return false;
1631 }
1632 }
1633
1634 // Send settings.
1635 for (SendChannelMap::iterator iter = send_channels_.begin();
1636 iter != send_channels_.end(); ++iter) {
1637 int channel_id = iter->second->channel_id();
1638 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_,
1639 nack_enabled_)) {
1640 return false;
1641 }
1642 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
1643 remb_enabled_,
1644 remb_enabled_) != 0) {
1645 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
1646 return false;
1647 }
1648 }
1649
1650 // Select the first matched codec.
1651 webrtc::VideoCodec& codec(send_codecs[0]);
1652
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001653 // Set RTX payload type if primary now active. This value will be used in
1654 // SetSendCodec.
1655 std::map<int, int>::const_iterator rtx_it =
1656 primary_rtx_pt_mapping.find(static_cast<int>(codec.plType));
1657 if (rtx_it != primary_rtx_pt_mapping.end()) {
1658 send_rtx_type_ = rtx_it->second;
1659 }
1660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661 if (!SetSendCodec(
1662 codec, codec.minBitrate, codec.startBitrate, codec.maxBitrate)) {
1663 return false;
1664 }
1665
1666 for (SendChannelMap::iterator iter = send_channels_.begin();
1667 iter != send_channels_.end(); ++iter) {
1668 WebRtcVideoChannelSendInfo* send_channel = iter->second;
1669 send_channel->InitializeAdapterOutputFormat(codec);
1670 }
1671
1672 LogSendCodecChange("SetSendCodecs()");
1673
1674 return true;
1675}
1676
1677bool WebRtcVideoMediaChannel::GetSendCodec(VideoCodec* send_codec) {
1678 if (!send_codec_) {
1679 return false;
1680 }
1681 ConvertToCricketVideoCodec(*send_codec_, send_codec);
1682 return true;
1683}
1684
1685bool WebRtcVideoMediaChannel::SetSendStreamFormat(uint32 ssrc,
1686 const VideoFormat& format) {
1687 if (!send_codec_) {
1688 LOG(LS_ERROR) << "The send codec has not been set yet.";
1689 return false;
1690 }
1691 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
1692 if (!send_channel) {
1693 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
1694 return false;
1695 }
1696 send_channel->set_video_format(format);
1697 return true;
1698}
1699
1700bool WebRtcVideoMediaChannel::SetRender(bool render) {
1701 if (render == render_started_) {
1702 return true; // no action required
1703 }
1704
1705 bool ret = true;
1706 for (RecvChannelMap::iterator it = recv_channels_.begin();
1707 it != recv_channels_.end(); ++it) {
1708 if (render) {
1709 if (engine()->vie()->render()->StartRender(
1710 it->second->channel_id()) != 0) {
1711 LOG_RTCERR1(StartRender, it->second->channel_id());
1712 ret = false;
1713 }
1714 } else {
1715 if (engine()->vie()->render()->StopRender(
1716 it->second->channel_id()) != 0) {
1717 LOG_RTCERR1(StopRender, it->second->channel_id());
1718 ret = false;
1719 }
1720 }
1721 }
1722 if (ret) {
1723 render_started_ = render;
1724 }
1725
1726 return ret;
1727}
1728
1729bool WebRtcVideoMediaChannel::SetSend(bool send) {
1730 if (!HasReadySendChannels() && send) {
1731 LOG(LS_ERROR) << "No stream added";
1732 return false;
1733 }
1734 if (send == sending()) {
1735 return true; // No action required.
1736 }
1737
1738 if (send) {
1739 // We've been asked to start sending.
1740 // SetSendCodecs must have been called already.
1741 if (!send_codec_) {
1742 return false;
1743 }
1744 // Start send now.
1745 if (!StartSend()) {
1746 return false;
1747 }
1748 } else {
1749 // We've been asked to stop sending.
1750 if (!StopSend()) {
1751 return false;
1752 }
1753 }
1754 sending_ = send;
1755
1756 return true;
1757}
1758
1759bool WebRtcVideoMediaChannel::AddSendStream(const StreamParams& sp) {
1760 LOG(LS_INFO) << "AddSendStream " << sp.ToString();
1761
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001762 if (!IsOneSsrcStream(sp) && !IsSimulcastStream(sp)) {
1763 LOG(LS_ERROR) << "AddSendStream: bad local stream parameters";
1764 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765 }
1766
1767 uint32 ssrc_key;
1768 if (!CreateSendChannelKey(sp.first_ssrc(), &ssrc_key)) {
1769 LOG(LS_ERROR) << "Trying to register duplicate ssrc: " << sp.first_ssrc();
1770 return false;
1771 }
1772 // If the default channel is already used for sending create a new channel
1773 // otherwise use the default channel for sending.
1774 int channel_id = -1;
1775 if (send_channels_[0]->stream_params() == NULL) {
1776 channel_id = vie_channel_;
1777 } else {
1778 if (!CreateChannel(ssrc_key, MD_SEND, &channel_id)) {
1779 LOG(LS_ERROR) << "AddSendStream: unable to create channel";
1780 return false;
1781 }
1782 }
1783 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1784 // Set the send (local) SSRC.
1785 // If there are multiple send SSRCs, we can only set the first one here, and
1786 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
1787 // (with a codec requires multiple SSRC(s)).
1788 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1789 sp.first_ssrc()) != 0) {
1790 LOG_RTCERR2(SetLocalSSRC, channel_id, sp.first_ssrc());
1791 return false;
1792 }
1793
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001794 // Set the corresponding RTX SSRC.
1795 if (!SetLocalRtxSsrc(channel_id, sp, sp.first_ssrc(), 0)) {
1796 return false;
1797 }
1798
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799 // Set RTCP CName.
1800 if (engine()->vie()->rtp()->SetRTCPCName(channel_id,
1801 sp.cname.c_str()) != 0) {
1802 LOG_RTCERR2(SetRTCPCName, channel_id, sp.cname.c_str());
1803 return false;
1804 }
1805
1806 // At this point the channel's local SSRC has been updated. If the channel is
1807 // the default channel make sure that all the receive channels are updated as
1808 // well. Receive channels have to have the same SSRC as the default channel in
1809 // order to send receiver reports with this SSRC.
1810 if (IsDefaultChannel(channel_id)) {
1811 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
1812 it != recv_channels_.end(); ++it) {
1813 WebRtcVideoChannelRecvInfo* info = it->second;
1814 int channel_id = info->channel_id();
1815 if (engine()->vie()->rtp()->SetLocalSSRC(channel_id,
1816 sp.first_ssrc()) != 0) {
1817 LOG_RTCERR1(SetLocalSSRC, it->first);
1818 return false;
1819 }
1820 }
1821 }
1822
1823 send_channel->set_stream_params(sp);
1824
1825 // Reset send codec after stream parameters changed.
1826 if (send_codec_) {
1827 if (!SetSendCodec(send_channel, *send_codec_, send_min_bitrate_,
1828 send_start_bitrate_, send_max_bitrate_)) {
1829 return false;
1830 }
1831 LogSendCodecChange("SetSendStreamFormat()");
1832 }
1833
1834 if (sending_) {
1835 return StartSend(send_channel);
1836 }
1837 return true;
1838}
1839
1840bool WebRtcVideoMediaChannel::RemoveSendStream(uint32 ssrc) {
1841 uint32 ssrc_key;
1842 if (!GetSendChannelKey(ssrc, &ssrc_key)) {
1843 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
1844 << " which doesn't exist.";
1845 return false;
1846 }
1847 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
1848 int channel_id = send_channel->channel_id();
1849 if (IsDefaultChannel(channel_id) && (send_channel->stream_params() == NULL)) {
1850 // Default channel will still exist. However, if stream_params() is NULL
1851 // there is no stream to remove.
1852 return false;
1853 }
1854 if (sending_) {
1855 StopSend(send_channel);
1856 }
1857
1858 const WebRtcVideoChannelSendInfo::EncoderMap& encoder_map =
1859 send_channel->registered_encoders();
1860 for (WebRtcVideoChannelSendInfo::EncoderMap::const_iterator it =
1861 encoder_map.begin(); it != encoder_map.end(); ++it) {
1862 if (engine()->vie()->ext_codec()->DeRegisterExternalSendCodec(
1863 channel_id, it->first) != 0) {
1864 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
1865 }
1866 engine()->DestroyExternalEncoder(it->second);
1867 }
1868 send_channel->ClearRegisteredEncoders();
1869
1870 // The receive channels depend on the default channel, recycle it instead.
1871 if (IsDefaultChannel(channel_id)) {
1872 SetCapturer(GetDefaultChannelSsrc(), NULL);
1873 send_channel->ClearStreamParams();
1874 } else {
1875 return DeleteSendChannel(ssrc_key);
1876 }
1877 return true;
1878}
1879
1880bool WebRtcVideoMediaChannel::AddRecvStream(const StreamParams& sp) {
1881 // TODO(zhurunz) Remove this once BWE works properly across different send
1882 // and receive channels.
1883 // Reuse default channel for recv stream in 1:1 call.
1884 if (!InConferenceMode() && first_receive_ssrc_ == 0) {
1885 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
1886 << " reuse default channel #"
1887 << vie_channel_;
1888 first_receive_ssrc_ = sp.first_ssrc();
1889 if (render_started_) {
1890 if (engine()->vie()->render()->StartRender(vie_channel_) !=0) {
1891 LOG_RTCERR1(StartRender, vie_channel_);
1892 }
1893 }
1894 return true;
1895 }
1896
1897 if (recv_channels_.find(sp.first_ssrc()) != recv_channels_.end() ||
1898 first_receive_ssrc_ == sp.first_ssrc()) {
1899 LOG(LS_ERROR) << "Stream already exists";
1900 return false;
1901 }
1902
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001903 // TODO(perkj): Implement recv media from multiple media SSRCs per stream.
1904 // NOTE: We have two SSRCs per stream when RTX is enabled.
1905 if (!IsOneSsrcStream(sp)) {
1906 LOG(LS_ERROR) << "WebRtcVideoMediaChannel supports one primary SSRC per"
1907 << " stream and one FID SSRC per primary SSRC.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908 return false;
1909 }
1910
1911 // Create a new channel for receiving video data.
1912 // In order to get the bandwidth estimation work fine for
1913 // receive only channels, we connect all receiving channels
1914 // to our master send channel.
1915 int channel_id = -1;
1916 if (!CreateChannel(sp.first_ssrc(), MD_RECV, &channel_id)) {
1917 return false;
1918 }
1919
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001920 // Set the corresponding RTX SSRC.
1921 uint32 rtx_ssrc;
1922 bool has_rtx = sp.GetFidSsrc(sp.first_ssrc(), &rtx_ssrc);
1923 if (has_rtx && engine()->vie()->rtp()->SetRemoteSSRCType(
1924 channel_id, webrtc::kViEStreamTypeRtx, rtx_ssrc) != 0) {
1925 LOG_RTCERR3(SetRemoteSSRCType, channel_id, webrtc::kViEStreamTypeRtx,
1926 rtx_ssrc);
1927 return false;
1928 }
1929
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 // Get the default renderer.
1931 VideoRenderer* default_renderer = NULL;
1932 if (InConferenceMode()) {
1933 // The recv_channels_ size start out being 1, so if it is two here this
1934 // is the first receive channel created (vie_channel_ is not used for
1935 // receiving in a conference call). This means that the renderer stored
1936 // inside vie_channel_ should be used for the just created channel.
1937 if (recv_channels_.size() == 2 &&
1938 recv_channels_.find(0) != recv_channels_.end()) {
1939 GetRenderer(0, &default_renderer);
1940 }
1941 }
1942
1943 // The first recv stream reuses the default renderer (if a default renderer
1944 // has been set).
1945 if (default_renderer) {
1946 SetRenderer(sp.first_ssrc(), default_renderer);
1947 }
1948
1949 LOG(LS_INFO) << "New video stream " << sp.first_ssrc()
1950 << " registered to VideoEngine channel #"
1951 << channel_id << " and connected to channel #" << vie_channel_;
1952
1953 return true;
1954}
1955
1956bool WebRtcVideoMediaChannel::RemoveRecvStream(uint32 ssrc) {
1957 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
1958
1959 if (it == recv_channels_.end()) {
1960 // TODO(perkj): Remove this once BWE works properly across different send
1961 // and receive channels.
1962 // The default channel is reused for recv stream in 1:1 call.
1963 if (first_receive_ssrc_ == ssrc) {
1964 first_receive_ssrc_ = 0;
1965 // Need to stop the renderer and remove it since the render window can be
1966 // deleted after this.
1967 if (render_started_) {
1968 if (engine()->vie()->render()->StopRender(vie_channel_) !=0) {
1969 LOG_RTCERR1(StopRender, it->second->channel_id());
1970 }
1971 }
1972 recv_channels_[0]->SetRenderer(NULL);
1973 return true;
1974 }
1975 return false;
1976 }
1977 WebRtcVideoChannelRecvInfo* info = it->second;
1978 int channel_id = info->channel_id();
1979 if (engine()->vie()->render()->RemoveRenderer(channel_id) != 0) {
1980 LOG_RTCERR1(RemoveRenderer, channel_id);
1981 }
1982
1983 if (engine()->vie()->network()->DeregisterSendTransport(channel_id) !=0) {
1984 LOG_RTCERR1(DeRegisterSendTransport, channel_id);
1985 }
1986
1987 if (engine()->vie()->codec()->DeregisterDecoderObserver(
1988 channel_id) != 0) {
1989 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
1990 }
1991
1992 const WebRtcVideoChannelRecvInfo::DecoderMap& decoder_map =
1993 info->registered_decoders();
1994 for (WebRtcVideoChannelRecvInfo::DecoderMap::const_iterator it =
1995 decoder_map.begin(); it != decoder_map.end(); ++it) {
1996 if (engine()->vie()->ext_codec()->DeRegisterExternalReceiveCodec(
1997 channel_id, it->first) != 0) {
1998 LOG_RTCERR1(DeregisterDecoderObserver, channel_id);
1999 }
2000 engine()->DestroyExternalDecoder(it->second);
2001 }
2002 info->ClearRegisteredDecoders();
2003
2004 LOG(LS_INFO) << "Removing video stream " << ssrc
2005 << " with VideoEngine channel #"
2006 << channel_id;
2007 if (engine()->vie()->base()->DeleteChannel(channel_id) == -1) {
2008 LOG_RTCERR1(DeleteChannel, channel_id);
2009 // Leak the WebRtcVideoChannelRecvInfo owned by |it| but remove the channel
2010 // from recv_channels_.
2011 recv_channels_.erase(it);
2012 return false;
2013 }
2014 // Delete the WebRtcVideoChannelRecvInfo pointed to by it->second.
2015 delete info;
2016 recv_channels_.erase(it);
2017 return true;
2018}
2019
2020bool WebRtcVideoMediaChannel::StartSend() {
2021 bool success = true;
2022 for (SendChannelMap::iterator iter = send_channels_.begin();
2023 iter != send_channels_.end(); ++iter) {
2024 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2025 if (!StartSend(send_channel)) {
2026 success = false;
2027 }
2028 }
2029 return success;
2030}
2031
2032bool WebRtcVideoMediaChannel::StartSend(
2033 WebRtcVideoChannelSendInfo* send_channel) {
2034 const int channel_id = send_channel->channel_id();
2035 if (engine()->vie()->base()->StartSend(channel_id) != 0) {
2036 LOG_RTCERR1(StartSend, channel_id);
2037 return false;
2038 }
2039
2040 send_channel->set_sending(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002041 return true;
2042}
2043
2044bool WebRtcVideoMediaChannel::StopSend() {
2045 bool success = true;
2046 for (SendChannelMap::iterator iter = send_channels_.begin();
2047 iter != send_channels_.end(); ++iter) {
2048 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2049 if (!StopSend(send_channel)) {
2050 success = false;
2051 }
2052 }
2053 return success;
2054}
2055
2056bool WebRtcVideoMediaChannel::StopSend(
2057 WebRtcVideoChannelSendInfo* send_channel) {
2058 const int channel_id = send_channel->channel_id();
2059 if (engine()->vie()->base()->StopSend(channel_id) != 0) {
2060 LOG_RTCERR1(StopSend, channel_id);
2061 return false;
2062 }
2063 send_channel->set_sending(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002064 return true;
2065}
2066
2067bool WebRtcVideoMediaChannel::SendIntraFrame() {
2068 bool success = true;
2069 for (SendChannelMap::iterator iter = send_channels_.begin();
2070 iter != send_channels_.end();
2071 ++iter) {
2072 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2073 const int channel_id = send_channel->channel_id();
2074 if (engine()->vie()->codec()->SendKeyFrame(channel_id) != 0) {
2075 LOG_RTCERR1(SendKeyFrame, channel_id);
2076 success = false;
2077 }
2078 }
2079 return success;
2080}
2081
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002082bool WebRtcVideoMediaChannel::HasReadySendChannels() {
2083 return !send_channels_.empty() &&
2084 ((send_channels_.size() > 1) ||
2085 (send_channels_[0]->stream_params() != NULL));
2086}
2087
2088bool WebRtcVideoMediaChannel::GetSendChannelKey(uint32 local_ssrc,
2089 uint32* key) {
2090 *key = 0;
2091 // If a send channel is not ready to send it will not have local_ssrc
2092 // registered to it.
2093 if (!HasReadySendChannels()) {
2094 return false;
2095 }
2096 // The default channel is stored with key 0. The key therefore does not match
2097 // the SSRC associated with the default channel. Check if the SSRC provided
2098 // corresponds to the default channel's SSRC.
2099 if (local_ssrc == GetDefaultChannelSsrc()) {
2100 return true;
2101 }
2102 if (send_channels_.find(local_ssrc) == send_channels_.end()) {
2103 for (SendChannelMap::iterator iter = send_channels_.begin();
2104 iter != send_channels_.end(); ++iter) {
2105 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2106 if (send_channel->has_ssrc(local_ssrc)) {
2107 *key = iter->first;
2108 return true;
2109 }
2110 }
2111 return false;
2112 }
2113 // The key was found in the above std::map::find call. This means that the
2114 // ssrc is the key.
2115 *key = local_ssrc;
2116 return true;
2117}
2118
2119WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
2120 VideoCapturer* video_capturer) {
2121 for (SendChannelMap::iterator iter = send_channels_.begin();
2122 iter != send_channels_.end(); ++iter) {
2123 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2124 if (send_channel->video_capturer() == video_capturer) {
2125 return send_channel;
2126 }
2127 }
2128 return NULL;
2129}
2130
2131WebRtcVideoChannelSendInfo* WebRtcVideoMediaChannel::GetSendChannel(
2132 uint32 local_ssrc) {
2133 uint32 key;
2134 if (!GetSendChannelKey(local_ssrc, &key)) {
2135 return NULL;
2136 }
2137 return send_channels_[key];
2138}
2139
2140bool WebRtcVideoMediaChannel::CreateSendChannelKey(uint32 local_ssrc,
2141 uint32* key) {
2142 if (GetSendChannelKey(local_ssrc, key)) {
2143 // If there is a key corresponding to |local_ssrc|, the SSRC is already in
2144 // use. SSRCs need to be unique in a session and at this point a duplicate
2145 // SSRC has been detected.
2146 return false;
2147 }
2148 if (send_channels_[0]->stream_params() == NULL) {
2149 // key should be 0 here as the default channel should be re-used whenever it
2150 // is not used.
2151 *key = 0;
2152 return true;
2153 }
2154 // SSRC is currently not in use and the default channel is already in use. Use
2155 // the SSRC as key since it is supposed to be unique in a session.
2156 *key = local_ssrc;
2157 return true;
2158}
2159
2160uint32 WebRtcVideoMediaChannel::GetDefaultChannelSsrc() {
2161 WebRtcVideoChannelSendInfo* send_channel = send_channels_[0];
2162 const StreamParams* sp = send_channel->stream_params();
2163 if (sp == NULL) {
2164 // This happens if no send stream is currently registered.
2165 return 0;
2166 }
2167 return sp->first_ssrc();
2168}
2169
2170bool WebRtcVideoMediaChannel::DeleteSendChannel(uint32 ssrc_key) {
2171 if (send_channels_.find(ssrc_key) == send_channels_.end()) {
2172 return false;
2173 }
2174 WebRtcVideoChannelSendInfo* send_channel = send_channels_[ssrc_key];
2175 VideoCapturer* capturer = send_channel->video_capturer();
2176 if (capturer != NULL) {
2177 capturer->SignalVideoFrame.disconnect(this);
2178 send_channel->set_video_capturer(NULL);
2179 }
2180
2181 int channel_id = send_channel->channel_id();
2182 int capture_id = send_channel->capture_id();
2183 if (engine()->vie()->codec()->DeregisterEncoderObserver(
2184 channel_id) != 0) {
2185 LOG_RTCERR1(DeregisterEncoderObserver, channel_id);
2186 }
2187
2188 // Destroy the external capture interface.
2189 if (engine()->vie()->capture()->DisconnectCaptureDevice(
2190 channel_id) != 0) {
2191 LOG_RTCERR1(DisconnectCaptureDevice, channel_id);
2192 }
2193 if (engine()->vie()->capture()->ReleaseCaptureDevice(
2194 capture_id) != 0) {
2195 LOG_RTCERR1(ReleaseCaptureDevice, capture_id);
2196 }
2197
2198 // The default channel is stored in both |send_channels_| and
2199 // |recv_channels_|. To make sure it is only deleted once from vie let the
2200 // delete call happen when tearing down |recv_channels_| and not here.
2201 if (!IsDefaultChannel(channel_id)) {
2202 engine_->vie()->base()->DeleteChannel(channel_id);
2203 }
2204 delete send_channel;
2205 send_channels_.erase(ssrc_key);
2206 return true;
2207}
2208
2209bool WebRtcVideoMediaChannel::RemoveCapturer(uint32 ssrc) {
2210 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2211 if (!send_channel) {
2212 return false;
2213 }
2214 VideoCapturer* capturer = send_channel->video_capturer();
2215 if (capturer == NULL) {
2216 return false;
2217 }
2218 capturer->SignalVideoFrame.disconnect(this);
2219 send_channel->set_video_capturer(NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2221 if (send_codec_) {
2222 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2223 }
2224 return true;
2225}
2226
2227bool WebRtcVideoMediaChannel::SetRenderer(uint32 ssrc,
2228 VideoRenderer* renderer) {
2229 if (recv_channels_.find(ssrc) == recv_channels_.end()) {
2230 // TODO(perkj): Remove this once BWE works properly across different send
2231 // and receive channels.
2232 // The default channel is reused for recv stream in 1:1 call.
2233 if (first_receive_ssrc_ == ssrc &&
2234 recv_channels_.find(0) != recv_channels_.end()) {
2235 LOG(LS_INFO) << "SetRenderer " << ssrc
2236 << " reuse default channel #"
2237 << vie_channel_;
2238 recv_channels_[0]->SetRenderer(renderer);
2239 return true;
2240 }
2241 return false;
2242 }
2243
2244 recv_channels_[ssrc]->SetRenderer(renderer);
2245 return true;
2246}
2247
2248bool WebRtcVideoMediaChannel::GetStats(VideoMediaInfo* info) {
2249 // Get sender statistics and build VideoSenderInfo.
2250 unsigned int total_bitrate_sent = 0;
2251 unsigned int video_bitrate_sent = 0;
2252 unsigned int fec_bitrate_sent = 0;
2253 unsigned int nack_bitrate_sent = 0;
2254 unsigned int estimated_send_bandwidth = 0;
2255 unsigned int target_enc_bitrate = 0;
2256 if (send_codec_) {
2257 for (SendChannelMap::const_iterator iter = send_channels_.begin();
2258 iter != send_channels_.end(); ++iter) {
2259 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2260 const int channel_id = send_channel->channel_id();
2261 VideoSenderInfo sinfo;
2262 const StreamParams* send_params = send_channel->stream_params();
2263 if (send_params == NULL) {
2264 // This should only happen if the default vie channel is not in use.
2265 // This can happen if no streams have ever been added or the stream
2266 // corresponding to the default channel has been removed. Note that
2267 // there may be non-default vie channels in use when this happen so
2268 // asserting send_channels_.size() == 1 is not correct and neither is
2269 // breaking out of the loop.
2270 ASSERT(channel_id == vie_channel_);
2271 continue;
2272 }
2273 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2274 if (engine_->vie()->rtp()->GetRTPStatistics(channel_id, bytes_sent,
2275 packets_sent, bytes_recv,
2276 packets_recv) != 0) {
2277 LOG_RTCERR1(GetRTPStatistics, vie_channel_);
2278 continue;
2279 }
2280 WebRtcLocalStreamInfo* channel_stream_info =
2281 send_channel->local_stream_info();
2282
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002283 for (size_t i = 0; i < send_params->ssrcs.size(); ++i) {
2284 sinfo.add_ssrc(send_params->ssrcs[i]);
2285 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002286 sinfo.codec_name = send_codec_->plName;
2287 sinfo.bytes_sent = bytes_sent;
2288 sinfo.packets_sent = packets_sent;
2289 sinfo.packets_cached = -1;
2290 sinfo.packets_lost = -1;
2291 sinfo.fraction_lost = -1;
2292 sinfo.firs_rcvd = -1;
2293 sinfo.nacks_rcvd = -1;
2294 sinfo.rtt_ms = -1;
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002295 sinfo.frame_width = static_cast<int>(channel_stream_info->width());
2296 sinfo.frame_height = static_cast<int>(channel_stream_info->height());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297 sinfo.framerate_input = channel_stream_info->framerate();
2298 sinfo.framerate_sent = send_channel->encoder_observer()->framerate();
2299 sinfo.nominal_bitrate = send_channel->encoder_observer()->bitrate();
2300 sinfo.preferred_bitrate = send_max_bitrate_;
2301 sinfo.adapt_reason = send_channel->CurrentAdaptReason();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002302 sinfo.capture_jitter_ms = -1;
2303 sinfo.avg_encode_ms = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002305#ifdef USE_WEBRTC_DEV_BRANCH
2306 int capture_jitter_ms = 0;
2307 int avg_encode_time_ms = 0;
2308 if (engine()->vie()->base()->CpuOveruseMeasures(
2309 channel_id, &capture_jitter_ms, &avg_encode_time_ms) == 0) {
2310 sinfo.capture_jitter_ms = capture_jitter_ms;
2311 sinfo.avg_encode_ms = avg_encode_time_ms;
2312 }
2313#endif
2314
2315#ifdef USE_WEBRTC_DEV_BRANCH
2316 // Get received RTCP statistics for the sender (reported by the remote
2317 // client in a RTCP packet), if available.
2318 // It's not a fatal error if we can't, since RTCP may not have arrived
2319 // yet.
2320 webrtc::RtcpStatistics outgoing_stream_rtcp_stats;
2321 int outgoing_stream_rtt_ms;
2322
2323 if (engine_->vie()->rtp()->GetSendChannelRtcpStatistics(
2324 channel_id,
2325 outgoing_stream_rtcp_stats,
2326 outgoing_stream_rtt_ms) == 0) {
2327 // Convert Q8 to float.
2328 sinfo.packets_lost = outgoing_stream_rtcp_stats.cumulative_lost;
2329 sinfo.fraction_lost = static_cast<float>(
2330 outgoing_stream_rtcp_stats.fraction_lost) / (1 << 8);
2331 sinfo.rtt_ms = outgoing_stream_rtt_ms;
2332 }
2333#else
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334 // Get received RTCP statistics for the sender, if available.
2335 // It's not a fatal error if we can't, since RTCP may not have arrived
2336 // yet.
2337 uint16 r_fraction_lost;
2338 unsigned int r_cumulative_lost;
2339 unsigned int r_extended_max;
2340 unsigned int r_jitter;
2341 int r_rtt_ms;
2342
2343 if (engine_->vie()->rtp()->GetSentRTCPStatistics(
2344 channel_id,
2345 r_fraction_lost,
2346 r_cumulative_lost,
2347 r_extended_max,
2348 r_jitter, r_rtt_ms) == 0) {
2349 // Convert Q8 to float.
2350 sinfo.packets_lost = r_cumulative_lost;
2351 sinfo.fraction_lost = static_cast<float>(r_fraction_lost) / (1 << 8);
2352 sinfo.rtt_ms = r_rtt_ms;
2353 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002354#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002355 info->senders.push_back(sinfo);
2356
2357 unsigned int channel_total_bitrate_sent = 0;
2358 unsigned int channel_video_bitrate_sent = 0;
2359 unsigned int channel_fec_bitrate_sent = 0;
2360 unsigned int channel_nack_bitrate_sent = 0;
2361 if (engine_->vie()->rtp()->GetBandwidthUsage(
2362 channel_id, channel_total_bitrate_sent, channel_video_bitrate_sent,
2363 channel_fec_bitrate_sent, channel_nack_bitrate_sent) == 0) {
2364 total_bitrate_sent += channel_total_bitrate_sent;
2365 video_bitrate_sent += channel_video_bitrate_sent;
2366 fec_bitrate_sent += channel_fec_bitrate_sent;
2367 nack_bitrate_sent += channel_nack_bitrate_sent;
2368 } else {
2369 LOG_RTCERR1(GetBandwidthUsage, channel_id);
2370 }
2371
2372 unsigned int estimated_stream_send_bandwidth = 0;
2373 if (engine_->vie()->rtp()->GetEstimatedSendBandwidth(
2374 channel_id, &estimated_stream_send_bandwidth) == 0) {
2375 estimated_send_bandwidth += estimated_stream_send_bandwidth;
2376 } else {
2377 LOG_RTCERR1(GetEstimatedSendBandwidth, channel_id);
2378 }
2379 unsigned int target_enc_stream_bitrate = 0;
2380 if (engine_->vie()->codec()->GetCodecTargetBitrate(
2381 channel_id, &target_enc_stream_bitrate) == 0) {
2382 target_enc_bitrate += target_enc_stream_bitrate;
2383 } else {
2384 LOG_RTCERR1(GetCodecTargetBitrate, channel_id);
2385 }
2386 }
2387 } else {
2388 LOG(LS_WARNING) << "GetStats: sender information not ready.";
2389 }
2390
2391 // Get the SSRC and stats for each receiver, based on our own calculations.
2392 unsigned int estimated_recv_bandwidth = 0;
2393 for (RecvChannelMap::const_iterator it = recv_channels_.begin();
2394 it != recv_channels_.end(); ++it) {
2395 // Don't report receive statistics from the default channel if we have
2396 // specified receive channels.
2397 if (it->first == 0 && recv_channels_.size() > 1)
2398 continue;
2399 WebRtcVideoChannelRecvInfo* channel = it->second;
2400
2401 unsigned int ssrc;
2402 // Get receiver statistics and build VideoReceiverInfo, if we have data.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +00002403 // Skip the default channel (ssrc == 0).
2404 if (engine_->vie()->rtp()->GetRemoteSSRC(
2405 channel->channel_id(), ssrc) != 0 ||
2406 ssrc == 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002407 continue;
2408
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002409#ifdef USE_WEBRTC_DEV_BRANCH
2410 webrtc::StreamDataCounters sent;
2411 webrtc::StreamDataCounters received;
2412 if (engine_->vie()->rtp()->GetRtpStatistics(channel->channel_id(),
2413 sent, received) != 0) {
2414 LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
2415 return false;
2416 }
2417 VideoReceiverInfo rinfo;
2418 rinfo.add_ssrc(ssrc);
2419 rinfo.bytes_rcvd = received.bytes;
2420 rinfo.packets_rcvd = received.packets;
2421#else
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422 unsigned int bytes_sent, packets_sent, bytes_recv, packets_recv;
2423 if (engine_->vie()->rtp()->GetRTPStatistics(
2424 channel->channel_id(), bytes_sent, packets_sent, bytes_recv,
2425 packets_recv) != 0) {
2426 LOG_RTCERR1(GetRTPStatistics, channel->channel_id());
2427 return false;
2428 }
2429 VideoReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002430 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 rinfo.bytes_rcvd = bytes_recv;
2432 rinfo.packets_rcvd = packets_recv;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002433#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434 rinfo.packets_lost = -1;
2435 rinfo.packets_concealed = -1;
2436 rinfo.fraction_lost = -1; // from SentRTCP
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002437 rinfo.nacks_sent = -1;
2438 rinfo.frame_width = channel->render_adapter()->width();
2439 rinfo.frame_height = channel->render_adapter()->height();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 int fps = channel->render_adapter()->framerate();
2441 rinfo.framerate_decoded = fps;
2442 rinfo.framerate_output = fps;
wu@webrtc.org97077a32013-10-25 21:18:33 +00002443 channel->decoder_observer()->ExportTo(&rinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002445#ifdef USE_WEBRTC_DEV_BRANCH
2446 // Get our locally created statistics of the received RTP stream.
2447 webrtc::RtcpStatistics incoming_stream_rtcp_stats;
2448 int incoming_stream_rtt_ms;
2449 if (engine_->vie()->rtp()->GetReceiveChannelRtcpStatistics(
2450 channel->channel_id(),
2451 incoming_stream_rtcp_stats,
2452 incoming_stream_rtt_ms) == 0) {
2453 // Convert Q8 to float.
2454 rinfo.packets_lost = incoming_stream_rtcp_stats.cumulative_lost;
2455 rinfo.fraction_lost = static_cast<float>(
2456 incoming_stream_rtcp_stats.fraction_lost) / (1 << 8);
2457 }
2458#else
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 // Get sent RTCP statistics.
2460 uint16 s_fraction_lost;
2461 unsigned int s_cumulative_lost;
2462 unsigned int s_extended_max;
2463 unsigned int s_jitter;
2464 int s_rtt_ms;
2465 if (engine_->vie()->rtp()->GetReceivedRTCPStatistics(channel->channel_id(),
2466 s_fraction_lost, s_cumulative_lost, s_extended_max,
2467 s_jitter, s_rtt_ms) == 0) {
2468 // Convert Q8 to float.
2469 rinfo.packets_lost = s_cumulative_lost;
2470 rinfo.fraction_lost = static_cast<float>(s_fraction_lost) / (1 << 8);
2471 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002472#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473 info->receivers.push_back(rinfo);
2474
2475 unsigned int estimated_recv_stream_bandwidth = 0;
2476 if (engine_->vie()->rtp()->GetEstimatedReceiveBandwidth(
2477 channel->channel_id(), &estimated_recv_stream_bandwidth) == 0) {
2478 estimated_recv_bandwidth += estimated_recv_stream_bandwidth;
2479 } else {
2480 LOG_RTCERR1(GetEstimatedReceiveBandwidth, channel->channel_id());
2481 }
2482 }
2483
2484 // Build BandwidthEstimationInfo.
2485 // TODO(zhurunz): Add real unittest for this.
2486 BandwidthEstimationInfo bwe;
2487
2488 // Calculations done above per send/receive stream.
2489 bwe.actual_enc_bitrate = video_bitrate_sent;
2490 bwe.transmit_bitrate = total_bitrate_sent;
2491 bwe.retransmit_bitrate = nack_bitrate_sent;
2492 bwe.available_send_bandwidth = estimated_send_bandwidth;
2493 bwe.available_recv_bandwidth = estimated_recv_bandwidth;
2494 bwe.target_enc_bitrate = target_enc_bitrate;
2495
2496 info->bw_estimations.push_back(bwe);
2497
2498 return true;
2499}
2500
2501bool WebRtcVideoMediaChannel::SetCapturer(uint32 ssrc,
2502 VideoCapturer* capturer) {
2503 ASSERT(ssrc != 0);
2504 if (!capturer) {
2505 return RemoveCapturer(ssrc);
2506 }
2507 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2508 if (!send_channel) {
2509 return false;
2510 }
2511 VideoCapturer* old_capturer = send_channel->video_capturer();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002512 if (old_capturer) {
2513 old_capturer->SignalVideoFrame.disconnect(this);
2514 }
2515
2516 send_channel->set_video_capturer(capturer);
2517 capturer->SignalVideoFrame.connect(
2518 this,
2519 &WebRtcVideoMediaChannel::AdaptAndSendFrame);
2520 if (!capturer->IsScreencast() && ratio_w_ != 0 && ratio_h_ != 0) {
2521 capturer->UpdateAspectRatio(ratio_w_, ratio_h_);
2522 }
2523 const int64 timestamp = send_channel->local_stream_info()->time_stamp();
2524 if (send_codec_) {
2525 QueueBlackFrame(ssrc, timestamp, send_codec_->maxFramerate);
2526 }
2527 return true;
2528}
2529
2530bool WebRtcVideoMediaChannel::RequestIntraFrame() {
2531 // There is no API exposed to application to request a key frame
2532 // ViE does this internally when there are errors from decoder
2533 return false;
2534}
2535
2536void WebRtcVideoMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
2537 // Pick which channel to send this packet to. If this packet doesn't match
2538 // any multiplexed streams, just send it to the default channel. Otherwise,
2539 // send it to the specific decoder instance for that stream.
2540 uint32 ssrc = 0;
2541 if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc))
2542 return;
2543 int which_channel = GetRecvChannelNum(ssrc);
2544 if (which_channel == -1) {
2545 which_channel = video_channel();
2546 }
2547
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002548 engine()->vie()->network()->ReceivedRTPPacket(
2549 which_channel,
2550 packet->data(),
2551 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002552}
2553
2554void WebRtcVideoMediaChannel::OnRtcpReceived(talk_base::Buffer* packet) {
2555// Sending channels need all RTCP packets with feedback information.
2556// Even sender reports can contain attached report blocks.
2557// Receiving channels need sender reports in order to create
2558// correct receiver reports.
2559
2560 uint32 ssrc = 0;
2561 if (!GetRtcpSsrc(packet->data(), packet->length(), &ssrc)) {
2562 LOG(LS_WARNING) << "Failed to parse SSRC from received RTCP packet";
2563 return;
2564 }
2565 int type = 0;
2566 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2567 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2568 return;
2569 }
2570
2571 // If it is a sender report, find the channel that is listening.
2572 if (type == kRtcpTypeSR) {
2573 int which_channel = GetRecvChannelNum(ssrc);
2574 if (which_channel != -1 && !IsDefaultChannel(which_channel)) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002575 engine_->vie()->network()->ReceivedRTCPPacket(
2576 which_channel,
2577 packet->data(),
2578 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579 }
2580 }
2581 // SR may continue RR and any RR entry may correspond to any one of the send
2582 // channels. So all RTCP packets must be forwarded all send channels. ViE
2583 // will filter out RR internally.
2584 for (SendChannelMap::iterator iter = send_channels_.begin();
2585 iter != send_channels_.end(); ++iter) {
2586 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2587 int channel_id = send_channel->channel_id();
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002588 engine_->vie()->network()->ReceivedRTCPPacket(
2589 channel_id,
2590 packet->data(),
2591 static_cast<int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592 }
2593}
2594
2595void WebRtcVideoMediaChannel::OnReadyToSend(bool ready) {
2596 SetNetworkTransmissionState(ready);
2597}
2598
2599bool WebRtcVideoMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2600 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
2601 if (!send_channel) {
2602 LOG(LS_ERROR) << "The specified ssrc " << ssrc << " is not in use.";
2603 return false;
2604 }
2605 send_channel->set_muted(muted);
2606 return true;
2607}
2608
2609bool WebRtcVideoMediaChannel::SetRecvRtpHeaderExtensions(
2610 const std::vector<RtpHeaderExtension>& extensions) {
2611 if (receive_extensions_ == extensions) {
2612 return true;
2613 }
2614 receive_extensions_ = extensions;
2615
2616 const RtpHeaderExtension* offset_extension =
2617 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2618 const RtpHeaderExtension* send_time_extension =
2619 FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
2620
2621 // Loop through all receive channels and enable/disable the extensions.
2622 for (RecvChannelMap::iterator channel_it = recv_channels_.begin();
2623 channel_it != recv_channels_.end(); ++channel_it) {
2624 int channel_id = channel_it->second->channel_id();
2625 if (!SetHeaderExtension(
2626 &webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus, channel_id,
2627 offset_extension)) {
2628 return false;
2629 }
2630 if (!SetHeaderExtension(
2631 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
2632 send_time_extension)) {
2633 return false;
2634 }
2635 }
2636 return true;
2637}
2638
2639bool WebRtcVideoMediaChannel::SetSendRtpHeaderExtensions(
2640 const std::vector<RtpHeaderExtension>& extensions) {
2641 send_extensions_ = extensions;
2642
2643 const RtpHeaderExtension* offset_extension =
2644 FindHeaderExtension(extensions, kRtpTimestampOffsetHeaderExtension);
2645 const RtpHeaderExtension* send_time_extension =
2646 FindHeaderExtension(extensions, kRtpAbsoluteSendTimeHeaderExtension);
2647
2648 // Loop through all send channels and enable/disable the extensions.
2649 for (SendChannelMap::iterator channel_it = send_channels_.begin();
2650 channel_it != send_channels_.end(); ++channel_it) {
2651 int channel_id = channel_it->second->channel_id();
2652 if (!SetHeaderExtension(
2653 &webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus, channel_id,
2654 offset_extension)) {
2655 return false;
2656 }
2657 if (!SetHeaderExtension(
2658 &webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus, channel_id,
2659 send_time_extension)) {
2660 return false;
2661 }
2662 }
2663 return true;
2664}
2665
2666bool WebRtcVideoMediaChannel::SetSendBandwidth(bool autobw, int bps) {
2667 LOG(LS_INFO) << "WebRtcVideoMediaChanne::SetSendBandwidth";
2668
2669 if (InConferenceMode()) {
2670 LOG(LS_INFO) << "Conference mode ignores SetSendBandWidth";
2671 return true;
2672 }
2673
2674 if (!send_codec_) {
2675 LOG(LS_INFO) << "The send codec has not been set up yet";
2676 return true;
2677 }
2678
2679 int min_bitrate;
2680 int start_bitrate;
2681 int max_bitrate;
2682 if (autobw) {
2683 // Use the default values for min bitrate.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002684 min_bitrate = send_min_bitrate_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002685 // Use the default value or the bps for the max
2686 max_bitrate = (bps <= 0) ? send_max_bitrate_ : (bps / 1000);
2687 // Maximum start bitrate can be kStartVideoBitrate.
2688 start_bitrate = talk_base::_min(kStartVideoBitrate, max_bitrate);
2689 } else {
2690 // Use the default start or the bps as the target bitrate.
2691 int target_bitrate = (bps <= 0) ? kStartVideoBitrate : (bps / 1000);
2692 min_bitrate = target_bitrate;
2693 start_bitrate = target_bitrate;
2694 max_bitrate = target_bitrate;
2695 }
2696
2697 if (!SetSendCodec(*send_codec_, min_bitrate, start_bitrate, max_bitrate)) {
2698 return false;
2699 }
2700 LogSendCodecChange("SetSendBandwidth()");
2701
2702 return true;
2703}
2704
2705bool WebRtcVideoMediaChannel::SetOptions(const VideoOptions &options) {
2706 // Always accept options that are unchanged.
2707 if (options_ == options) {
2708 return true;
2709 }
2710
2711 // Trigger SetSendCodec to set correct noise reduction state if the option has
2712 // changed.
2713 bool denoiser_changed = options.video_noise_reduction.IsSet() &&
2714 (options_.video_noise_reduction != options.video_noise_reduction);
2715
2716 bool leaky_bucket_changed = options.video_leaky_bucket.IsSet() &&
2717 (options_.video_leaky_bucket != options.video_leaky_bucket);
2718
2719 bool buffer_latency_changed = options.buffered_mode_latency.IsSet() &&
2720 (options_.buffered_mode_latency != options.buffered_mode_latency);
2721
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002722 bool cpu_overuse_detection_changed = options.cpu_overuse_detection.IsSet() &&
2723 (options_.cpu_overuse_detection != options.cpu_overuse_detection);
2724
wu@webrtc.orgde305012013-10-31 15:40:38 +00002725 bool dscp_option_changed = (options_.dscp != options.dscp);
2726
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002727 bool suspend_below_min_bitrate_changed =
2728 options.suspend_below_min_bitrate.IsSet() &&
2729 (options_.suspend_below_min_bitrate != options.suspend_below_min_bitrate);
2730
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002731 bool conference_mode_turned_off = false;
2732 if (options_.conference_mode.IsSet() && options.conference_mode.IsSet() &&
2733 options_.conference_mode.GetWithDefaultIfUnset(false) &&
2734 !options.conference_mode.GetWithDefaultIfUnset(false)) {
2735 conference_mode_turned_off = true;
2736 }
2737
2738 // Save the options, to be interpreted where appropriate.
2739 // Use options_.SetAll() instead of assignment so that unset value in options
2740 // will not overwrite the previous option value.
2741 options_.SetAll(options);
2742
2743 // Set CPU options for all send channels.
2744 for (SendChannelMap::iterator iter = send_channels_.begin();
2745 iter != send_channels_.end(); ++iter) {
2746 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2747 send_channel->ApplyCpuOptions(options_);
2748 }
2749
2750 // Adjust send codec bitrate if needed.
2751 int conf_max_bitrate = kDefaultConferenceModeMaxVideoBitrate;
2752
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002753 // Save altered min_bitrate level and apply if necessary.
2754 bool adjusted_min_bitrate = false;
2755 if (options.lower_min_bitrate.IsSet()) {
2756 bool lower;
2757 options.lower_min_bitrate.Get(&lower);
2758
2759 int new_send_min_bitrate = lower ? kLowerMinBitrate : kMinVideoBitrate;
2760 adjusted_min_bitrate = (new_send_min_bitrate != send_min_bitrate_);
2761 send_min_bitrate_ = new_send_min_bitrate;
2762 }
2763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002764 int expected_bitrate = send_max_bitrate_;
2765 if (InConferenceMode()) {
2766 expected_bitrate = conf_max_bitrate;
2767 } else if (conference_mode_turned_off) {
2768 // This is a special case for turning conference mode off.
2769 // Max bitrate should go back to the default maximum value instead
2770 // of the current maximum.
2771 expected_bitrate = kMaxVideoBitrate;
2772 }
2773
2774 if (send_codec_ &&
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00002775 (send_max_bitrate_ != expected_bitrate || denoiser_changed ||
2776 adjusted_min_bitrate)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002777 // On success, SetSendCodec() will reset send_max_bitrate_ to
2778 // expected_bitrate.
2779 if (!SetSendCodec(*send_codec_,
2780 send_min_bitrate_,
2781 send_start_bitrate_,
2782 expected_bitrate)) {
2783 return false;
2784 }
2785 LogSendCodecChange("SetOptions()");
2786 }
2787 if (leaky_bucket_changed) {
2788 bool enable_leaky_bucket =
2789 options_.video_leaky_bucket.GetWithDefaultIfUnset(false);
2790 for (SendChannelMap::iterator it = send_channels_.begin();
2791 it != send_channels_.end(); ++it) {
2792 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(
2793 it->second->channel_id(), enable_leaky_bucket) != 0) {
2794 LOG_RTCERR2(SetTransmissionSmoothingStatus, it->second->channel_id(),
2795 enable_leaky_bucket);
2796 }
2797 }
2798 }
2799 if (buffer_latency_changed) {
2800 int buffer_latency =
2801 options_.buffered_mode_latency.GetWithDefaultIfUnset(
2802 cricket::kBufferedModeDisabled);
2803 for (SendChannelMap::iterator it = send_channels_.begin();
2804 it != send_channels_.end(); ++it) {
2805 if (engine()->vie()->rtp()->SetSenderBufferingMode(
2806 it->second->channel_id(), buffer_latency) != 0) {
2807 LOG_RTCERR2(SetSenderBufferingMode, it->second->channel_id(),
2808 buffer_latency);
2809 }
2810 }
2811 for (RecvChannelMap::iterator it = recv_channels_.begin();
2812 it != recv_channels_.end(); ++it) {
2813 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
2814 it->second->channel_id(), buffer_latency) != 0) {
2815 LOG_RTCERR2(SetReceiverBufferingMode, it->second->channel_id(),
2816 buffer_latency);
2817 }
2818 }
2819 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002820 if (cpu_overuse_detection_changed) {
2821 bool cpu_overuse_detection =
2822 options_.cpu_overuse_detection.GetWithDefaultIfUnset(false);
2823 for (SendChannelMap::iterator iter = send_channels_.begin();
2824 iter != send_channels_.end(); ++iter) {
2825 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2826 send_channel->SetCpuOveruseDetection(cpu_overuse_detection);
2827 }
2828 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00002829 if (dscp_option_changed) {
2830 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
2831 if (options.dscp.GetWithDefaultIfUnset(false))
2832 dscp = kVideoDscpValue;
2833 if (MediaChannel::SetDscp(dscp) != 0) {
2834 LOG(LS_WARNING) << "Failed to set DSCP settings for video channel";
2835 }
2836 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002837 if (suspend_below_min_bitrate_changed) {
2838#ifdef USE_WEBRTC_DEV_BRANCH
2839 if (options_.suspend_below_min_bitrate.GetWithDefaultIfUnset(false)) {
2840 for (SendChannelMap::iterator it = send_channels_.begin();
2841 it != send_channels_.end(); ++it) {
2842 engine()->vie()->codec()->SuspendBelowMinBitrate(
2843 it->second->channel_id());
2844 }
2845 } else {
2846 LOG(LS_WARNING) << "Cannot disable video suspension once it is enabled";
2847 }
2848#endif
2849 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850 return true;
2851}
2852
2853void WebRtcVideoMediaChannel::SetInterface(NetworkInterface* iface) {
2854 MediaChannel::SetInterface(iface);
2855 // Set the RTP recv/send buffer to a bigger size
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002856 MediaChannel::SetOption(NetworkInterface::ST_RTP,
2857 talk_base::Socket::OPT_RCVBUF,
2858 kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859
2860 // TODO(sriniv): Remove or re-enable this.
2861 // As part of b/8030474, send-buffer is size now controlled through
2862 // portallocator flags.
2863 // network_interface_->SetOption(NetworkInterface::ST_RTP,
2864 // talk_base::Socket::OPT_SNDBUF,
2865 // kVideoRtpBufferSize);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002866}
2867
2868void WebRtcVideoMediaChannel::UpdateAspectRatio(int ratio_w, int ratio_h) {
2869 ASSERT(ratio_w != 0);
2870 ASSERT(ratio_h != 0);
2871 ratio_w_ = ratio_w;
2872 ratio_h_ = ratio_h;
2873 // For now assume that all streams want the same aspect ratio.
2874 // TODO(hellner): remove the need for this assumption.
2875 for (SendChannelMap::iterator iter = send_channels_.begin();
2876 iter != send_channels_.end(); ++iter) {
2877 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2878 VideoCapturer* capturer = send_channel->video_capturer();
2879 if (capturer) {
2880 capturer->UpdateAspectRatio(ratio_w, ratio_h);
2881 }
2882 }
2883}
2884
2885bool WebRtcVideoMediaChannel::GetRenderer(uint32 ssrc,
2886 VideoRenderer** renderer) {
2887 RecvChannelMap::const_iterator it = recv_channels_.find(ssrc);
2888 if (it == recv_channels_.end()) {
2889 if (first_receive_ssrc_ == ssrc &&
2890 recv_channels_.find(0) != recv_channels_.end()) {
2891 LOG(LS_INFO) << " GetRenderer " << ssrc
2892 << " reuse default renderer #"
2893 << vie_channel_;
2894 *renderer = recv_channels_[0]->render_adapter()->renderer();
2895 return true;
2896 }
2897 return false;
2898 }
2899
2900 *renderer = it->second->render_adapter()->renderer();
2901 return true;
2902}
2903
2904void WebRtcVideoMediaChannel::AdaptAndSendFrame(VideoCapturer* capturer,
2905 const VideoFrame* frame) {
2906 if (capturer->IsScreencast()) {
2907 // Do not adapt frames that are screencast.
2908 SendFrame(capturer, frame);
2909 return;
2910 }
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002911 // TODO(thorcarpenter): This is broken. One capturer registered on two ssrc
2912 // will not send any video to the second ssrc send channel. We should remove
2913 // GetSendChannel(capturer) and pass in an ssrc here.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002914 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(capturer);
2915 if (!send_channel) {
2916 SendFrame(capturer, frame);
2917 return;
2918 }
2919 const VideoFrame* output_frame = NULL;
2920 send_channel->AdaptFrame(frame, &output_frame);
2921 if (output_frame) {
2922 SendFrame(send_channel, output_frame, capturer->IsScreencast());
2923 }
2924}
2925
2926// TODO(zhurunz): Add unittests to test this function.
2927void WebRtcVideoMediaChannel::SendFrame(VideoCapturer* capturer,
2928 const VideoFrame* frame) {
2929 // If there's send channel registers to the |capturer|, then only send the
2930 // frame to that channel and return. Otherwise send the frame to the default
2931 // channel, which currently taking frames from the engine.
2932 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(capturer);
2933 if (send_channel) {
2934 SendFrame(send_channel, frame, capturer->IsScreencast());
2935 return;
2936 }
2937 // TODO(hellner): Remove below for loop once the captured frame no longer
2938 // come from the engine, i.e. the engine no longer owns a capturer.
2939 for (SendChannelMap::iterator iter = send_channels_.begin();
2940 iter != send_channels_.end(); ++iter) {
2941 WebRtcVideoChannelSendInfo* send_channel = iter->second;
2942 if (send_channel->video_capturer() == NULL) {
2943 SendFrame(send_channel, frame, capturer->IsScreencast());
2944 }
2945 }
2946}
2947
2948bool WebRtcVideoMediaChannel::SendFrame(
2949 WebRtcVideoChannelSendInfo* send_channel,
2950 const VideoFrame* frame,
2951 bool is_screencast) {
2952 if (!send_channel) {
2953 return false;
2954 }
2955 if (!send_codec_) {
2956 // Send codec has not been set. No reason to process the frame any further.
2957 return false;
2958 }
2959 const VideoFormat& video_format = send_channel->video_format();
2960 // If the frame should be dropped.
2961 const bool video_format_set = video_format != cricket::VideoFormat();
2962 if (video_format_set &&
2963 (video_format.width == 0 && video_format.height == 0)) {
2964 return true;
2965 }
2966
2967 // Checks if we need to reset vie send codec.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002968 if (!MaybeResetVieSendCodec(send_channel,
2969 static_cast<int>(frame->GetWidth()),
2970 static_cast<int>(frame->GetHeight()),
2971 is_screencast, NULL)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002972 LOG(LS_ERROR) << "MaybeResetVieSendCodec failed with "
2973 << frame->GetWidth() << "x" << frame->GetHeight();
2974 return false;
2975 }
2976 const VideoFrame* frame_out = frame;
2977 talk_base::scoped_ptr<VideoFrame> processed_frame;
2978 // Disable muting for screencast.
2979 const bool mute = (send_channel->muted() && !is_screencast);
2980 send_channel->ProcessFrame(*frame_out, mute, processed_frame.use());
2981 if (processed_frame) {
2982 frame_out = processed_frame.get();
2983 }
2984
2985 webrtc::ViEVideoFrameI420 frame_i420;
2986 // TODO(ronghuawu): Update the webrtc::ViEVideoFrameI420
2987 // to use const unsigned char*
2988 frame_i420.y_plane = const_cast<unsigned char*>(frame_out->GetYPlane());
2989 frame_i420.u_plane = const_cast<unsigned char*>(frame_out->GetUPlane());
2990 frame_i420.v_plane = const_cast<unsigned char*>(frame_out->GetVPlane());
2991 frame_i420.y_pitch = frame_out->GetYPitch();
2992 frame_i420.u_pitch = frame_out->GetUPitch();
2993 frame_i420.v_pitch = frame_out->GetVPitch();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002994 frame_i420.width = static_cast<uint16>(frame_out->GetWidth());
2995 frame_i420.height = static_cast<uint16>(frame_out->GetHeight());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002996
2997 int64 timestamp_ntp_ms = 0;
2998 // TODO(justinlin): Reenable after Windows issues with clock drift are fixed.
2999 // Currently reverted to old behavior of discarding capture timestamp.
3000#if 0
3001 // If the frame timestamp is 0, we will use the deliver time.
3002 const int64 frame_timestamp = frame->GetTimeStamp();
3003 if (frame_timestamp != 0) {
3004 if (abs(time(NULL) - frame_timestamp / talk_base::kNumNanosecsPerSec) >
3005 kTimestampDeltaInSecondsForWarning) {
3006 LOG(LS_WARNING) << "Frame timestamp differs by more than "
3007 << kTimestampDeltaInSecondsForWarning << " seconds from "
3008 << "current Unix timestamp.";
3009 }
3010
3011 timestamp_ntp_ms =
3012 talk_base::UnixTimestampNanosecsToNtpMillisecs(frame_timestamp);
3013 }
3014#endif
3015
3016 return send_channel->external_capture()->IncomingFrameI420(
3017 frame_i420, timestamp_ntp_ms) == 0;
3018}
3019
3020bool WebRtcVideoMediaChannel::CreateChannel(uint32 ssrc_key,
3021 MediaDirection direction,
3022 int* channel_id) {
3023 // There are 3 types of channels. Sending only, receiving only and
3024 // sending and receiving. The sending and receiving channel is the
3025 // default channel and there is only one. All other channels that are created
3026 // are associated with the default channel which must exist. The default
3027 // channel id is stored in |vie_channel_|. All channels need to know about
3028 // the default channel to properly handle remb which is why there are
3029 // different ViE create channel calls.
3030 // For this channel the local and remote ssrc key is 0. However, it may
3031 // have a non-zero local and/or remote ssrc depending on if it is currently
3032 // sending and/or receiving.
3033 if ((vie_channel_ == -1 || direction == MD_SENDRECV) &&
3034 (!send_channels_.empty() || !recv_channels_.empty())) {
3035 ASSERT(false);
3036 return false;
3037 }
3038
3039 *channel_id = -1;
3040 if (direction == MD_RECV) {
3041 // All rec channels are associated with the default channel |vie_channel_|
3042 if (engine_->vie()->base()->CreateReceiveChannel(*channel_id,
3043 vie_channel_) != 0) {
3044 LOG_RTCERR2(CreateReceiveChannel, *channel_id, vie_channel_);
3045 return false;
3046 }
3047 } else if (direction == MD_SEND) {
3048 if (engine_->vie()->base()->CreateChannel(*channel_id,
3049 vie_channel_) != 0) {
3050 LOG_RTCERR2(CreateChannel, *channel_id, vie_channel_);
3051 return false;
3052 }
3053 } else {
3054 ASSERT(direction == MD_SENDRECV);
3055 if (engine_->vie()->base()->CreateChannel(*channel_id) != 0) {
3056 LOG_RTCERR1(CreateChannel, *channel_id);
3057 return false;
3058 }
3059 }
3060 if (!ConfigureChannel(*channel_id, direction, ssrc_key)) {
3061 engine_->vie()->base()->DeleteChannel(*channel_id);
3062 *channel_id = -1;
3063 return false;
3064 }
3065
3066 return true;
3067}
3068
3069bool WebRtcVideoMediaChannel::ConfigureChannel(int channel_id,
3070 MediaDirection direction,
3071 uint32 ssrc_key) {
3072 const bool receiving = (direction == MD_RECV) || (direction == MD_SENDRECV);
3073 const bool sending = (direction == MD_SEND) || (direction == MD_SENDRECV);
3074 // Register external transport.
3075 if (engine_->vie()->network()->RegisterSendTransport(
3076 channel_id, *this) != 0) {
3077 LOG_RTCERR1(RegisterSendTransport, channel_id);
3078 return false;
3079 }
3080
3081 // Set MTU.
3082 if (engine_->vie()->network()->SetMTU(channel_id, kVideoMtu) != 0) {
3083 LOG_RTCERR2(SetMTU, channel_id, kVideoMtu);
3084 return false;
3085 }
3086 // Turn on RTCP and loss feedback reporting.
3087 if (engine()->vie()->rtp()->SetRTCPStatus(
3088 channel_id, webrtc::kRtcpCompound_RFC4585) != 0) {
3089 LOG_RTCERR2(SetRTCPStatus, channel_id, webrtc::kRtcpCompound_RFC4585);
3090 return false;
3091 }
3092 // Enable pli as key frame request method.
3093 if (engine_->vie()->rtp()->SetKeyFrameRequestMethod(
3094 channel_id, webrtc::kViEKeyFrameRequestPliRtcp) != 0) {
3095 LOG_RTCERR2(SetKeyFrameRequestMethod,
3096 channel_id, webrtc::kViEKeyFrameRequestPliRtcp);
3097 return false;
3098 }
3099 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3100 // Logged in SetNackFec. Don't spam the logs.
3101 return false;
3102 }
3103 // Note that receiving must always be configured before sending to ensure
3104 // that send and receive channel is configured correctly (ConfigureReceiving
3105 // assumes no sending).
3106 if (receiving) {
3107 if (!ConfigureReceiving(channel_id, ssrc_key)) {
3108 return false;
3109 }
3110 }
3111 if (sending) {
3112 if (!ConfigureSending(channel_id, ssrc_key)) {
3113 return false;
3114 }
3115 }
3116
3117 return true;
3118}
3119
3120bool WebRtcVideoMediaChannel::ConfigureReceiving(int channel_id,
3121 uint32 remote_ssrc_key) {
3122 // Make sure that an SSRC/key isn't registered more than once.
3123 if (recv_channels_.find(remote_ssrc_key) != recv_channels_.end()) {
3124 return false;
3125 }
3126 // Connect the voice channel, if there is one.
3127 // TODO(perkj): The A/V is synched by the receiving channel. So we need to
3128 // know the SSRC of the remote audio channel in order to fetch the correct
3129 // webrtc VoiceEngine channel. For now- only sync the default channel used
3130 // in 1-1 calls.
3131 if (remote_ssrc_key == 0 && voice_channel_) {
3132 WebRtcVoiceMediaChannel* voice_channel =
3133 static_cast<WebRtcVoiceMediaChannel*>(voice_channel_);
3134 if (engine_->vie()->base()->ConnectAudioChannel(
3135 vie_channel_, voice_channel->voe_channel()) != 0) {
3136 LOG_RTCERR2(ConnectAudioChannel, channel_id,
3137 voice_channel->voe_channel());
3138 LOG(LS_WARNING) << "A/V not synchronized";
3139 // Not a fatal error.
3140 }
3141 }
3142
3143 talk_base::scoped_ptr<WebRtcVideoChannelRecvInfo> channel_info(
3144 new WebRtcVideoChannelRecvInfo(channel_id));
3145
3146 // Install a render adapter.
3147 if (engine_->vie()->render()->AddRenderer(channel_id,
3148 webrtc::kVideoI420, channel_info->render_adapter()) != 0) {
3149 LOG_RTCERR3(AddRenderer, channel_id, webrtc::kVideoI420,
3150 channel_info->render_adapter());
3151 return false;
3152 }
3153
3154
3155 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3156 kNotSending,
3157 remb_enabled_) != 0) {
3158 LOG_RTCERR3(SetRembStatus, channel_id, kNotSending, remb_enabled_);
3159 return false;
3160 }
3161
3162 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetReceiveTimestampOffsetStatus,
3163 channel_id, receive_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3164 return false;
3165 }
3166
3167 if (!SetHeaderExtension(
3168 &webrtc::ViERTP_RTCP::SetReceiveAbsoluteSendTimeStatus, channel_id,
3169 receive_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
3170 return false;
3171 }
3172
3173 if (remote_ssrc_key != 0) {
3174 // Use the same SSRC as our default channel
3175 // (so the RTCP reports are correct).
3176 unsigned int send_ssrc = 0;
3177 webrtc::ViERTP_RTCP* rtp = engine()->vie()->rtp();
3178 if (rtp->GetLocalSSRC(vie_channel_, send_ssrc) == -1) {
3179 LOG_RTCERR2(GetLocalSSRC, vie_channel_, send_ssrc);
3180 return false;
3181 }
3182 if (rtp->SetLocalSSRC(channel_id, send_ssrc) == -1) {
3183 LOG_RTCERR2(SetLocalSSRC, channel_id, send_ssrc);
3184 return false;
3185 }
3186 } // Else this is the the default channel and we don't change the SSRC.
3187
3188 // Disable color enhancement since it is a bit too aggressive.
3189 if (engine()->vie()->image()->EnableColorEnhancement(channel_id,
3190 false) != 0) {
3191 LOG_RTCERR1(EnableColorEnhancement, channel_id);
3192 return false;
3193 }
3194
3195 if (!SetReceiveCodecs(channel_info.get())) {
3196 return false;
3197 }
3198
3199 int buffer_latency =
3200 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3201 cricket::kBufferedModeDisabled);
3202 if (buffer_latency != cricket::kBufferedModeDisabled) {
3203 if (engine()->vie()->rtp()->SetReceiverBufferingMode(
3204 channel_id, buffer_latency) != 0) {
3205 LOG_RTCERR2(SetReceiverBufferingMode, channel_id, buffer_latency);
3206 }
3207 }
3208
3209 if (render_started_) {
3210 if (engine_->vie()->render()->StartRender(channel_id) != 0) {
3211 LOG_RTCERR1(StartRender, channel_id);
3212 return false;
3213 }
3214 }
3215
3216 // Register decoder observer for incoming framerate and bitrate.
3217 if (engine()->vie()->codec()->RegisterDecoderObserver(
3218 channel_id, *channel_info->decoder_observer()) != 0) {
3219 LOG_RTCERR1(RegisterDecoderObserver, channel_info->decoder_observer());
3220 return false;
3221 }
3222
3223 recv_channels_[remote_ssrc_key] = channel_info.release();
3224 return true;
3225}
3226
3227bool WebRtcVideoMediaChannel::ConfigureSending(int channel_id,
3228 uint32 local_ssrc_key) {
3229 // The ssrc key can be zero or correspond to an SSRC.
3230 // Make sure the default channel isn't configured more than once.
3231 if (local_ssrc_key == 0 && send_channels_.find(0) != send_channels_.end()) {
3232 return false;
3233 }
3234 // Make sure that the SSRC is not already in use.
3235 uint32 dummy_key;
3236 if (GetSendChannelKey(local_ssrc_key, &dummy_key)) {
3237 return false;
3238 }
3239 int vie_capture = 0;
3240 webrtc::ViEExternalCapture* external_capture = NULL;
3241 // Register external capture.
3242 if (engine()->vie()->capture()->AllocateExternalCaptureDevice(
3243 vie_capture, external_capture) != 0) {
3244 LOG_RTCERR0(AllocateExternalCaptureDevice);
3245 return false;
3246 }
3247
3248 // Connect external capture.
3249 if (engine()->vie()->capture()->ConnectCaptureDevice(
3250 vie_capture, channel_id) != 0) {
3251 LOG_RTCERR2(ConnectCaptureDevice, vie_capture, channel_id);
3252 return false;
3253 }
3254 talk_base::scoped_ptr<WebRtcVideoChannelSendInfo> send_channel(
3255 new WebRtcVideoChannelSendInfo(channel_id, vie_capture,
3256 external_capture,
3257 engine()->cpu_monitor()));
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003258 if (engine()->vie()->base()->RegisterCpuOveruseObserver(
3259 channel_id, send_channel->overuse_observer())) {
3260 LOG_RTCERR1(RegisterCpuOveruseObserver, channel_id);
3261 return false;
3262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 send_channel->ApplyCpuOptions(options_);
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003264 send_channel->SignalCpuAdaptationUnable.connect(this,
3265 &WebRtcVideoMediaChannel::OnCpuAdaptationUnable);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003267 if (options_.cpu_overuse_detection.GetWithDefaultIfUnset(false)) {
3268 send_channel->SetCpuOveruseDetection(true);
3269 }
3270
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003271 // Register encoder observer for outgoing framerate and bitrate.
3272 if (engine()->vie()->codec()->RegisterEncoderObserver(
3273 channel_id, *send_channel->encoder_observer()) != 0) {
3274 LOG_RTCERR1(RegisterEncoderObserver, send_channel->encoder_observer());
3275 return false;
3276 }
3277
3278 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendTimestampOffsetStatus,
3279 channel_id, send_extensions_, kRtpTimestampOffsetHeaderExtension)) {
3280 return false;
3281 }
3282
3283 if (!SetHeaderExtension(&webrtc::ViERTP_RTCP::SetSendAbsoluteSendTimeStatus,
3284 channel_id, send_extensions_, kRtpAbsoluteSendTimeHeaderExtension)) {
3285 return false;
3286 }
3287
3288 if (options_.video_leaky_bucket.GetWithDefaultIfUnset(false)) {
3289 if (engine()->vie()->rtp()->SetTransmissionSmoothingStatus(channel_id,
3290 true) != 0) {
3291 LOG_RTCERR2(SetTransmissionSmoothingStatus, channel_id, true);
3292 return false;
3293 }
3294 }
3295
3296 int buffer_latency =
3297 options_.buffered_mode_latency.GetWithDefaultIfUnset(
3298 cricket::kBufferedModeDisabled);
3299 if (buffer_latency != cricket::kBufferedModeDisabled) {
3300 if (engine()->vie()->rtp()->SetSenderBufferingMode(
3301 channel_id, buffer_latency) != 0) {
3302 LOG_RTCERR2(SetSenderBufferingMode, channel_id, buffer_latency);
3303 }
3304 }
3305 // The remb status direction correspond to the RTP stream (and not the RTCP
3306 // stream). I.e. if send remb is enabled it means it is receiving remote
3307 // rembs and should use them to estimate bandwidth. Receive remb mean that
3308 // remb packets will be generated and that the channel should be included in
3309 // it. If remb is enabled all channels are allowed to contribute to the remb
3310 // but only receive channels will ever end up actually contributing. This
3311 // keeps the logic simple.
3312 if (engine_->vie()->rtp()->SetRembStatus(channel_id,
3313 remb_enabled_,
3314 remb_enabled_) != 0) {
3315 LOG_RTCERR3(SetRembStatus, channel_id, remb_enabled_, remb_enabled_);
3316 return false;
3317 }
3318 if (!SetNackFec(channel_id, send_red_type_, send_fec_type_, nack_enabled_)) {
3319 // Logged in SetNackFec. Don't spam the logs.
3320 return false;
3321 }
3322
3323 send_channels_[local_ssrc_key] = send_channel.release();
3324
3325 return true;
3326}
3327
3328bool WebRtcVideoMediaChannel::SetNackFec(int channel_id,
3329 int red_payload_type,
3330 int fec_payload_type,
3331 bool nack_enabled) {
3332 bool enable = (red_payload_type != -1 && fec_payload_type != -1 &&
3333 !InConferenceMode());
3334 if (enable) {
3335 if (engine_->vie()->rtp()->SetHybridNACKFECStatus(
3336 channel_id, nack_enabled, red_payload_type, fec_payload_type) != 0) {
3337 LOG_RTCERR4(SetHybridNACKFECStatus,
3338 channel_id, nack_enabled, red_payload_type, fec_payload_type);
3339 return false;
3340 }
3341 LOG(LS_INFO) << "Hybrid NACK/FEC enabled for channel " << channel_id;
3342 } else {
3343 if (engine_->vie()->rtp()->SetNACKStatus(channel_id, nack_enabled) != 0) {
3344 LOG_RTCERR1(SetNACKStatus, channel_id);
3345 return false;
3346 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003347 std::string enabled = nack_enabled ? "enabled" : "disabled";
3348 LOG(LS_INFO) << "NACK " << enabled << " for channel " << channel_id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349 }
3350 return true;
3351}
3352
3353bool WebRtcVideoMediaChannel::SetSendCodec(const webrtc::VideoCodec& codec,
3354 int min_bitrate,
3355 int start_bitrate,
3356 int max_bitrate) {
3357 bool ret_val = true;
3358 for (SendChannelMap::iterator iter = send_channels_.begin();
3359 iter != send_channels_.end(); ++iter) {
3360 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3361 ret_val = SetSendCodec(send_channel, codec, min_bitrate, start_bitrate,
3362 max_bitrate) && ret_val;
3363 }
3364 if (ret_val) {
3365 // All SetSendCodec calls were successful. Update the global state
3366 // accordingly.
3367 send_codec_.reset(new webrtc::VideoCodec(codec));
3368 send_min_bitrate_ = min_bitrate;
3369 send_start_bitrate_ = start_bitrate;
3370 send_max_bitrate_ = max_bitrate;
3371 } else {
3372 // At least one SetSendCodec call failed, rollback.
3373 for (SendChannelMap::iterator iter = send_channels_.begin();
3374 iter != send_channels_.end(); ++iter) {
3375 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3376 if (send_codec_) {
3377 SetSendCodec(send_channel, *send_codec_.get(), send_min_bitrate_,
3378 send_start_bitrate_, send_max_bitrate_);
3379 }
3380 }
3381 }
3382 return ret_val;
3383}
3384
3385bool WebRtcVideoMediaChannel::SetSendCodec(
3386 WebRtcVideoChannelSendInfo* send_channel,
3387 const webrtc::VideoCodec& codec,
3388 int min_bitrate,
3389 int start_bitrate,
3390 int max_bitrate) {
3391 if (!send_channel) {
3392 return false;
3393 }
3394 const int channel_id = send_channel->channel_id();
3395 // Make a copy of the codec
3396 webrtc::VideoCodec target_codec = codec;
3397 target_codec.startBitrate = start_bitrate;
3398 target_codec.minBitrate = min_bitrate;
3399 target_codec.maxBitrate = max_bitrate;
3400
3401 // Set the default number of temporal layers for VP8.
3402 if (webrtc::kVideoCodecVP8 == codec.codecType) {
3403 target_codec.codecSpecific.VP8.numberOfTemporalLayers =
3404 kDefaultNumberOfTemporalLayers;
3405
3406 // Turn off the VP8 error resilience
3407 target_codec.codecSpecific.VP8.resilience = webrtc::kResilienceOff;
3408
3409 bool enable_denoising =
3410 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3411 target_codec.codecSpecific.VP8.denoisingOn = enable_denoising;
3412 }
3413
3414 // Register external encoder if codec type is supported by encoder factory.
3415 if (engine()->IsExternalEncoderCodecType(codec.codecType) &&
3416 !send_channel->IsEncoderRegistered(target_codec.plType)) {
3417 webrtc::VideoEncoder* encoder =
3418 engine()->CreateExternalEncoder(codec.codecType);
3419 if (encoder) {
3420 if (engine()->vie()->ext_codec()->RegisterExternalSendCodec(
3421 channel_id, target_codec.plType, encoder, false) == 0) {
3422 send_channel->RegisterEncoder(target_codec.plType, encoder);
3423 } else {
3424 LOG_RTCERR2(RegisterExternalSendCodec, channel_id, target_codec.plName);
3425 engine()->DestroyExternalEncoder(encoder);
3426 }
3427 }
3428 }
3429
3430 // Resolution and framerate may vary for different send channels.
3431 const VideoFormat& video_format = send_channel->video_format();
3432 UpdateVideoCodec(video_format, &target_codec);
3433
3434 if (target_codec.width == 0 && target_codec.height == 0) {
3435 const uint32 ssrc = send_channel->stream_params()->first_ssrc();
3436 LOG(LS_INFO) << "0x0 resolution selected. Captured frames will be dropped "
3437 << "for ssrc: " << ssrc << ".";
3438 } else {
3439 MaybeChangeStartBitrate(channel_id, &target_codec);
3440 if (0 != engine()->vie()->codec()->SetSendCodec(channel_id, target_codec)) {
3441 LOG_RTCERR2(SetSendCodec, channel_id, target_codec.plName);
3442 return false;
3443 }
3444
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003445 // NOTE: SetRtxSendPayloadType must be called after all simulcast SSRCs
3446 // are configured. Otherwise ssrc's configured after this point will use
3447 // the primary PT for RTX.
3448 if (send_rtx_type_ != -1 &&
3449 engine()->vie()->rtp()->SetRtxSendPayloadType(channel_id,
3450 send_rtx_type_) != 0) {
3451 LOG_RTCERR2(SetRtxSendPayloadType, channel_id, send_rtx_type_);
3452 return false;
3453 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003454 }
3455 send_channel->set_interval(
3456 cricket::VideoFormat::FpsToInterval(target_codec.maxFramerate));
3457 return true;
3458}
3459
3460
3461static std::string ToString(webrtc::VideoCodecComplexity complexity) {
3462 switch (complexity) {
3463 case webrtc::kComplexityNormal:
3464 return "normal";
3465 case webrtc::kComplexityHigh:
3466 return "high";
3467 case webrtc::kComplexityHigher:
3468 return "higher";
3469 case webrtc::kComplexityMax:
3470 return "max";
3471 default:
3472 return "unknown";
3473 }
3474}
3475
3476static std::string ToString(webrtc::VP8ResilienceMode resilience) {
3477 switch (resilience) {
3478 case webrtc::kResilienceOff:
3479 return "off";
3480 case webrtc::kResilientStream:
3481 return "stream";
3482 case webrtc::kResilientFrames:
3483 return "frames";
3484 default:
3485 return "unknown";
3486 }
3487}
3488
3489void WebRtcVideoMediaChannel::LogSendCodecChange(const std::string& reason) {
3490 webrtc::VideoCodec vie_codec;
3491 if (engine()->vie()->codec()->GetSendCodec(vie_channel_, vie_codec) != 0) {
3492 LOG_RTCERR1(GetSendCodec, vie_channel_);
3493 return;
3494 }
3495
3496 LOG(LS_INFO) << reason << " : selected video codec "
3497 << vie_codec.plName << "/"
3498 << vie_codec.width << "x" << vie_codec.height << "x"
3499 << static_cast<int>(vie_codec.maxFramerate) << "fps"
3500 << "@" << vie_codec.maxBitrate << "kbps"
3501 << " (min=" << vie_codec.minBitrate << "kbps,"
3502 << " start=" << vie_codec.startBitrate << "kbps)";
3503 LOG(LS_INFO) << "Video max quantization: " << vie_codec.qpMax;
3504 if (webrtc::kVideoCodecVP8 == vie_codec.codecType) {
3505 LOG(LS_INFO) << "VP8 number of temporal layers: "
3506 << static_cast<int>(
3507 vie_codec.codecSpecific.VP8.numberOfTemporalLayers);
3508 LOG(LS_INFO) << "VP8 options : "
3509 << "picture loss indication = "
3510 << vie_codec.codecSpecific.VP8.pictureLossIndicationOn
3511 << ", feedback mode = "
3512 << vie_codec.codecSpecific.VP8.feedbackModeOn
3513 << ", complexity = "
3514 << ToString(vie_codec.codecSpecific.VP8.complexity)
3515 << ", resilience = "
3516 << ToString(vie_codec.codecSpecific.VP8.resilience)
3517 << ", denoising = "
3518 << vie_codec.codecSpecific.VP8.denoisingOn
3519 << ", error concealment = "
3520 << vie_codec.codecSpecific.VP8.errorConcealmentOn
3521 << ", automatic resize = "
3522 << vie_codec.codecSpecific.VP8.automaticResizeOn
3523 << ", frame dropping = "
3524 << vie_codec.codecSpecific.VP8.frameDroppingOn
3525 << ", key frame interval = "
3526 << vie_codec.codecSpecific.VP8.keyFrameInterval;
3527 }
3528
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003529 if (send_rtx_type_ != -1) {
3530 LOG(LS_INFO) << "RTX payload type: " << send_rtx_type_;
3531 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003532}
3533
3534bool WebRtcVideoMediaChannel::SetReceiveCodecs(
3535 WebRtcVideoChannelRecvInfo* info) {
3536 int red_type = -1;
3537 int fec_type = -1;
3538 int channel_id = info->channel_id();
3539 for (std::vector<webrtc::VideoCodec>::iterator it = receive_codecs_.begin();
3540 it != receive_codecs_.end(); ++it) {
3541 if (it->codecType == webrtc::kVideoCodecRED) {
3542 red_type = it->plType;
3543 } else if (it->codecType == webrtc::kVideoCodecULPFEC) {
3544 fec_type = it->plType;
3545 }
3546 if (engine()->vie()->codec()->SetReceiveCodec(channel_id, *it) != 0) {
3547 LOG_RTCERR2(SetReceiveCodec, channel_id, it->plName);
3548 return false;
3549 }
3550 if (!info->IsDecoderRegistered(it->plType) &&
3551 it->codecType != webrtc::kVideoCodecRED &&
3552 it->codecType != webrtc::kVideoCodecULPFEC) {
3553 webrtc::VideoDecoder* decoder =
3554 engine()->CreateExternalDecoder(it->codecType);
3555 if (decoder) {
3556 if (engine()->vie()->ext_codec()->RegisterExternalReceiveCodec(
3557 channel_id, it->plType, decoder) == 0) {
3558 info->RegisterDecoder(it->plType, decoder);
3559 } else {
3560 LOG_RTCERR2(RegisterExternalReceiveCodec, channel_id, it->plName);
3561 engine()->DestroyExternalDecoder(decoder);
3562 }
3563 }
3564 }
3565 }
3566
3567 // Start receiving packets if at least one receive codec has been set.
3568 if (!receive_codecs_.empty()) {
3569 if (engine()->vie()->base()->StartReceive(channel_id) != 0) {
3570 LOG_RTCERR1(StartReceive, channel_id);
3571 return false;
3572 }
3573 }
3574 return true;
3575}
3576
3577int WebRtcVideoMediaChannel::GetRecvChannelNum(uint32 ssrc) {
3578 if (ssrc == first_receive_ssrc_) {
3579 return vie_channel_;
3580 }
3581 RecvChannelMap::iterator it = recv_channels_.find(ssrc);
3582 return (it != recv_channels_.end()) ? it->second->channel_id() : -1;
3583}
3584
3585// If the new frame size is different from the send codec size we set on vie,
3586// we need to reset the send codec on vie.
3587// The new send codec size should not exceed send_codec_ which is controlled
3588// only by the 'jec' logic.
3589bool WebRtcVideoMediaChannel::MaybeResetVieSendCodec(
3590 WebRtcVideoChannelSendInfo* send_channel,
3591 int new_width,
3592 int new_height,
3593 bool is_screencast,
3594 bool* reset) {
3595 if (reset) {
3596 *reset = false;
3597 }
3598 ASSERT(send_codec_.get() != NULL);
3599
3600 webrtc::VideoCodec target_codec = *send_codec_.get();
3601 const VideoFormat& video_format = send_channel->video_format();
3602 UpdateVideoCodec(video_format, &target_codec);
3603
3604 // Vie send codec size should not exceed target_codec.
3605 int target_width = new_width;
3606 int target_height = new_height;
3607 if (!is_screencast &&
3608 (new_width > target_codec.width || new_height > target_codec.height)) {
3609 target_width = target_codec.width;
3610 target_height = target_codec.height;
3611 }
3612
3613 // Get current vie codec.
3614 webrtc::VideoCodec vie_codec;
3615 const int channel_id = send_channel->channel_id();
3616 if (engine()->vie()->codec()->GetSendCodec(channel_id, vie_codec) != 0) {
3617 LOG_RTCERR1(GetSendCodec, channel_id);
3618 return false;
3619 }
3620 const int cur_width = vie_codec.width;
3621 const int cur_height = vie_codec.height;
3622
3623 // Only reset send codec when there is a size change. Additionally,
3624 // automatic resize needs to be turned off when screencasting and on when
3625 // not screencasting.
3626 // Don't allow automatic resizing for screencasting.
3627 bool automatic_resize = !is_screencast;
3628 // Turn off VP8 frame dropping when screensharing as the current model does
3629 // not work well at low fps.
3630 bool vp8_frame_dropping = !is_screencast;
3631 // Disable denoising for screencasting.
3632 bool enable_denoising =
3633 options_.video_noise_reduction.GetWithDefaultIfUnset(false);
3634 bool denoising = !is_screencast && enable_denoising;
3635 bool reset_send_codec =
3636 target_width != cur_width || target_height != cur_height ||
3637 automatic_resize != vie_codec.codecSpecific.VP8.automaticResizeOn ||
3638 denoising != vie_codec.codecSpecific.VP8.denoisingOn ||
3639 vp8_frame_dropping != vie_codec.codecSpecific.VP8.frameDroppingOn;
3640
3641 if (reset_send_codec) {
3642 // Set the new codec on vie.
3643 vie_codec.width = target_width;
3644 vie_codec.height = target_height;
3645 vie_codec.maxFramerate = target_codec.maxFramerate;
3646 vie_codec.startBitrate = target_codec.startBitrate;
3647 vie_codec.codecSpecific.VP8.automaticResizeOn = automatic_resize;
3648 vie_codec.codecSpecific.VP8.denoisingOn = denoising;
3649 vie_codec.codecSpecific.VP8.frameDroppingOn = vp8_frame_dropping;
3650 // TODO(mflodman): Remove 'is_screencast' check when screen cast settings
3651 // are treated correctly in WebRTC.
3652 if (!is_screencast)
3653 MaybeChangeStartBitrate(channel_id, &vie_codec);
3654
3655 if (engine()->vie()->codec()->SetSendCodec(channel_id, vie_codec) != 0) {
3656 LOG_RTCERR1(SetSendCodec, channel_id);
3657 return false;
3658 }
3659 if (reset) {
3660 *reset = true;
3661 }
3662 LogSendCodecChange("Capture size changed");
3663 }
3664
3665 return true;
3666}
3667
3668void WebRtcVideoMediaChannel::MaybeChangeStartBitrate(
3669 int channel_id, webrtc::VideoCodec* video_codec) {
3670 if (video_codec->startBitrate < video_codec->minBitrate) {
3671 video_codec->startBitrate = video_codec->minBitrate;
3672 } else if (video_codec->startBitrate > video_codec->maxBitrate) {
3673 video_codec->startBitrate = video_codec->maxBitrate;
3674 }
3675
3676 // Use a previous target bitrate, if there is one.
3677 unsigned int current_target_bitrate = 0;
3678 if (engine()->vie()->codec()->GetCodecTargetBitrate(
3679 channel_id, &current_target_bitrate) == 0) {
3680 // Convert to kbps.
3681 current_target_bitrate /= 1000;
3682 if (current_target_bitrate > video_codec->maxBitrate) {
3683 current_target_bitrate = video_codec->maxBitrate;
3684 }
3685 if (current_target_bitrate > video_codec->startBitrate) {
3686 video_codec->startBitrate = current_target_bitrate;
3687 }
3688 }
3689}
3690
3691void WebRtcVideoMediaChannel::OnMessage(talk_base::Message* msg) {
3692 FlushBlackFrameData* black_frame_data =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003693 static_cast<FlushBlackFrameData*>(msg->pdata);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003694 FlushBlackFrame(black_frame_data->ssrc, black_frame_data->timestamp);
3695 delete black_frame_data;
3696}
3697
3698int WebRtcVideoMediaChannel::SendPacket(int channel, const void* data,
3699 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003700 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003701 return MediaChannel::SendPacket(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003702}
3703
3704int WebRtcVideoMediaChannel::SendRTCPPacket(int channel,
3705 const void* data,
3706 int len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003707 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003708 return MediaChannel::SendRtcp(&packet) ? len : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003709}
3710
3711void WebRtcVideoMediaChannel::QueueBlackFrame(uint32 ssrc, int64 timestamp,
3712 int framerate) {
3713 if (timestamp) {
3714 FlushBlackFrameData* black_frame_data = new FlushBlackFrameData(
3715 ssrc,
3716 timestamp);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003717 const int delay_ms = static_cast<int>(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003718 2 * cricket::VideoFormat::FpsToInterval(framerate) *
3719 talk_base::kNumMillisecsPerSec / talk_base::kNumNanosecsPerSec);
3720 worker_thread()->PostDelayed(delay_ms, this, 0, black_frame_data);
3721 }
3722}
3723
3724void WebRtcVideoMediaChannel::FlushBlackFrame(uint32 ssrc, int64 timestamp) {
3725 WebRtcVideoChannelSendInfo* send_channel = GetSendChannel(ssrc);
3726 if (!send_channel) {
3727 return;
3728 }
3729 talk_base::scoped_ptr<const VideoFrame> black_frame_ptr;
3730
3731 const WebRtcLocalStreamInfo* channel_stream_info =
3732 send_channel->local_stream_info();
3733 int64 last_frame_time_stamp = channel_stream_info->time_stamp();
3734 if (last_frame_time_stamp == timestamp) {
3735 size_t last_frame_width = 0;
3736 size_t last_frame_height = 0;
3737 int64 last_frame_elapsed_time = 0;
3738 channel_stream_info->GetLastFrameInfo(&last_frame_width, &last_frame_height,
3739 &last_frame_elapsed_time);
3740 if (!last_frame_width || !last_frame_height) {
3741 return;
3742 }
3743 WebRtcVideoFrame black_frame;
3744 // Black frame is not screencast.
3745 const bool screencasting = false;
3746 const int64 timestamp_delta = send_channel->interval();
3747 if (!black_frame.InitToBlack(send_codec_->width, send_codec_->height, 1, 1,
3748 last_frame_elapsed_time + timestamp_delta,
3749 last_frame_time_stamp + timestamp_delta) ||
3750 !SendFrame(send_channel, &black_frame, screencasting)) {
3751 LOG(LS_ERROR) << "Failed to send black frame.";
3752 }
3753 }
3754}
3755
wu@webrtc.orgd64719d2013-08-01 00:00:07 +00003756void WebRtcVideoMediaChannel::OnCpuAdaptationUnable() {
3757 // ssrc is hardcoded to 0. This message is based on a system wide issue,
3758 // so finding which ssrc caused it doesn't matter.
3759 SignalMediaError(0, VideoMediaChannel::ERROR_REC_CPU_MAX_CANT_DOWNGRADE);
3760}
3761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003762void WebRtcVideoMediaChannel::SetNetworkTransmissionState(
3763 bool is_transmitting) {
3764 LOG(LS_INFO) << "SetNetworkTransmissionState: " << is_transmitting;
3765 for (SendChannelMap::iterator iter = send_channels_.begin();
3766 iter != send_channels_.end(); ++iter) {
3767 WebRtcVideoChannelSendInfo* send_channel = iter->second;
3768 int channel_id = send_channel->channel_id();
3769 engine_->vie()->network()->SetNetworkTransmissionState(channel_id,
3770 is_transmitting);
3771 }
3772}
3773
3774bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3775 int channel_id, const RtpHeaderExtension* extension) {
3776 bool enable = false;
3777 int id = 0;
3778 if (extension) {
3779 enable = true;
3780 id = extension->id;
3781 }
3782 if ((engine_->vie()->rtp()->*setter)(channel_id, enable, id) != 0) {
3783 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
3784 return false;
3785 }
3786 return true;
3787}
3788
3789bool WebRtcVideoMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3790 int channel_id, const std::vector<RtpHeaderExtension>& extensions,
3791 const char header_extension_uri[]) {
3792 const RtpHeaderExtension* extension = FindHeaderExtension(extensions,
3793 header_extension_uri);
3794 return SetHeaderExtension(setter, channel_id, extension);
3795}
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003796
3797bool WebRtcVideoMediaChannel::SetLocalRtxSsrc(int channel_id,
3798 const StreamParams& send_params,
3799 uint32 primary_ssrc,
3800 int stream_idx) {
3801 uint32 rtx_ssrc = 0;
3802 bool has_rtx = send_params.GetFidSsrc(primary_ssrc, &rtx_ssrc);
3803 if (has_rtx && engine()->vie()->rtp()->SetLocalSSRC(
3804 channel_id, rtx_ssrc, webrtc::kViEStreamTypeRtx, stream_idx) != 0) {
3805 LOG_RTCERR4(SetLocalSSRC, channel_id, rtx_ssrc,
3806 webrtc::kViEStreamTypeRtx, stream_idx);
3807 return false;
3808 }
3809 return true;
3810}
3811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003812} // namespace cricket
3813
3814#endif // HAVE_WEBRTC_VIDEO