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