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