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