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