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