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