blob: 723ef1dd83053fc32b7f12b4eadca51165ec6576 [file] [log] [blame]
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001/*
2 * libjingle
3 * Copyright 2014 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/webrtcvideoengine2.h"
30
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include <math.h>
36
37#include <string>
38
39#include "libyuv/convert_from.h"
40#include "talk/base/buffer.h"
41#include "talk/base/logging.h"
42#include "talk/base/stringutils.h"
43#include "talk/media/base/videocapturer.h"
44#include "talk/media/base/videorenderer.h"
45#include "talk/media/webrtc/webrtcvideocapturer.h"
46#include "talk/media/webrtc/webrtcvideoframe.h"
47#include "talk/media/webrtc/webrtcvoiceengine.h"
48#include "webrtc/call.h"
49// TODO(pbos): Move codecs out of modules (webrtc:3070).
50#include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h"
51
52#define UNIMPLEMENTED \
53 LOG(LS_ERROR) << "Call to unimplemented function " << __FUNCTION__; \
54 ASSERT(false)
55
56namespace cricket {
57
58static const int kCpuMonitorPeriodMs = 2000; // 2 seconds.
59
60// This constant is really an on/off, lower-level configurable NACK history
61// duration hasn't been implemented.
62static const int kNackHistoryMs = 1000;
63
64static const int kDefaultFramerate = 30;
65static const int kMinVideoBitrate = 50;
66static const int kMaxVideoBitrate = 2000;
67
68static const int kVideoMtu = 1200;
69static const int kVideoRtpBufferSize = 65536;
70
71static const char kVp8PayloadName[] = "VP8";
72
73static const int kDefaultRtcpReceiverReportSsrc = 1;
74
75struct VideoCodecPref {
76 int payload_type;
77 const char* name;
78 int rtx_payload_type;
79} kDefaultVideoCodecPref = {100, kVp8PayloadName, 96};
80
81VideoCodecPref kRedPref = {116, kRedCodecName, -1};
82VideoCodecPref kUlpfecPref = {117, kUlpfecCodecName, -1};
83
84// The formats are sorted by the descending order of width. We use the order to
85// find the next format for CPU and bandwidth adaptation.
86const VideoFormatPod kDefaultVideoFormat = {
87 640, 400, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY};
88const VideoFormatPod kVideoFormats[] = {
89 {1280, 800, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
90 {1280, 720, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
91 {960, 600, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
92 {960, 540, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
93 kDefaultVideoFormat,
94 {640, 360, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
95 {640, 480, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
96 {480, 300, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
97 {480, 270, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
98 {480, 360, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
99 {320, 200, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
100 {320, 180, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
101 {320, 240, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
102 {240, 150, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
103 {240, 135, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
104 {240, 180, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
105 {160, 100, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
106 {160, 90, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY},
107 {160, 120, FPS_TO_INTERVAL(kDefaultFramerate), FOURCC_ANY}, };
108
109static bool FindFirstMatchingCodec(const std::vector<VideoCodec>& codecs,
110 const VideoCodec& requested_codec,
111 VideoCodec* matching_codec) {
112 for (size_t i = 0; i < codecs.size(); ++i) {
113 if (requested_codec.Matches(codecs[i])) {
114 *matching_codec = codecs[i];
115 return true;
116 }
117 }
118 return false;
119}
120static bool FindBestVideoFormat(int max_width,
121 int max_height,
122 int aspect_width,
123 int aspect_height,
124 VideoFormat* video_format) {
125 assert(max_width > 0);
126 assert(max_height > 0);
127 assert(aspect_width > 0);
128 assert(aspect_height > 0);
129 VideoFormat best_format;
130 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
131 const VideoFormat format(kVideoFormats[i]);
132
133 // Skip any format that is larger than the local or remote maximums, or
134 // smaller than the current best match
135 if (format.width > max_width || format.height > max_height ||
136 (format.width < best_format.width &&
137 format.height < best_format.height)) {
138 continue;
139 }
140
141 // If we don't have any matches yet, this is the best so far.
142 if (best_format.width == 0) {
143 best_format = format;
144 continue;
145 }
146
147 // Prefer closer aspect ratios i.e:
148 // |format| aspect - requested aspect <
149 // |best_format| aspect - requested aspect
150 if (abs(format.width * aspect_height * best_format.height -
151 aspect_width * format.height * best_format.height) <
152 abs(best_format.width * aspect_height * format.height -
153 aspect_width * format.height * best_format.height)) {
154 best_format = format;
155 }
156 }
157 if (best_format.width != 0) {
158 *video_format = best_format;
159 return true;
160 }
161 return false;
162}
163
164static VideoCodec DefaultVideoCodec() {
165 VideoCodec default_codec(kDefaultVideoCodecPref.payload_type,
166 kDefaultVideoCodecPref.name,
167 kDefaultVideoFormat.width,
168 kDefaultVideoFormat.height,
169 kDefaultFramerate,
170 0);
171 return default_codec;
172}
173
174static VideoCodec DefaultRedCodec() {
175 return VideoCodec(kRedPref.payload_type, kRedPref.name, 0, 0, 0, 0);
176}
177
178static VideoCodec DefaultUlpfecCodec() {
179 return VideoCodec(kUlpfecPref.payload_type, kUlpfecPref.name, 0, 0, 0, 0);
180}
181
182static std::vector<VideoCodec> DefaultVideoCodecs() {
183 std::vector<VideoCodec> codecs;
184 codecs.push_back(DefaultVideoCodec());
185 codecs.push_back(DefaultRedCodec());
186 codecs.push_back(DefaultUlpfecCodec());
187 if (kDefaultVideoCodecPref.rtx_payload_type != -1) {
188 codecs.push_back(
189 VideoCodec::CreateRtxCodec(kDefaultVideoCodecPref.rtx_payload_type,
190 kDefaultVideoCodecPref.payload_type));
191 }
192 return codecs;
193}
194
pbos@webrtc.org0d523ee2014-06-05 09:10:55 +0000195WebRtcVideoEncoderFactory2::~WebRtcVideoEncoderFactory2() {
196}
197
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000198class DefaultVideoEncoderFactory : public WebRtcVideoEncoderFactory2 {
199 public:
200 virtual bool CreateEncoderSettings(
201 webrtc::VideoSendStream::Config::EncoderSettings* encoder_settings,
202 const VideoOptions& options,
203 const VideoCodec& codec,
204 size_t num_streams) OVERRIDE {
205 if (num_streams != 1) {
206 LOG(LS_ERROR) << "Unsupported number of streams: " << num_streams;
207 return false;
208 }
209 if (!SupportsCodec(codec)) {
210 LOG(LS_ERROR) << "Can't create encoder settings for unsupported codec: '"
211 << codec.name << "'";
212 return false;
213 }
214
215 *encoder_settings = webrtc::VideoSendStream::Config::EncoderSettings();
216
217 webrtc::VideoStream stream;
218 stream.width = codec.width;
219 stream.height = codec.height;
220 stream.max_framerate =
221 codec.framerate != 0 ? codec.framerate : kDefaultFramerate;
222
223 int min_bitrate = kMinVideoBitrate;
224 codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
225 int max_bitrate = kMaxVideoBitrate;
226 codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
227 stream.min_bitrate_bps = min_bitrate * 1000;
228 stream.target_bitrate_bps = stream.max_bitrate_bps = max_bitrate * 1000;
229
230 int max_qp = 56;
231 codec.GetParam(kCodecParamMaxQuantization, &max_qp);
232 stream.max_qp = max_qp;
233 encoder_settings->streams.push_back(stream);
234
235 encoder_settings->encoder = webrtc::VP8Encoder::Create();
236 encoder_settings->payload_type = kDefaultVideoCodecPref.payload_type;
237 encoder_settings->payload_name = kDefaultVideoCodecPref.name;
238
239 return true;
240 }
241
242 virtual bool SupportsCodec(const VideoCodec& codec) OVERRIDE {
243 return _stricmp(codec.name.c_str(), kVp8PayloadName) == 0;
244 }
pbos@webrtc.org0d523ee2014-06-05 09:10:55 +0000245};
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000246
247WebRtcVideoEngine2::WebRtcVideoEngine2() {
248 // Construct without a factory or voice engine.
249 Construct(NULL, NULL, new talk_base::CpuMonitor(NULL));
250}
251
252WebRtcVideoEngine2::WebRtcVideoEngine2(
253 WebRtcVideoChannelFactory* channel_factory) {
254 // Construct without a voice engine.
255 Construct(channel_factory, NULL, new talk_base::CpuMonitor(NULL));
256}
257
258void WebRtcVideoEngine2::Construct(WebRtcVideoChannelFactory* channel_factory,
259 WebRtcVoiceEngine* voice_engine,
260 talk_base::CpuMonitor* cpu_monitor) {
261 LOG(LS_INFO) << "WebRtcVideoEngine2::WebRtcVideoEngine2";
262 worker_thread_ = NULL;
263 voice_engine_ = voice_engine;
264 initialized_ = false;
265 capture_started_ = false;
266 cpu_monitor_.reset(cpu_monitor);
267 channel_factory_ = channel_factory;
268
269 video_codecs_ = DefaultVideoCodecs();
270 default_codec_format_ = VideoFormat(kDefaultVideoFormat);
pbos@webrtc.org0d523ee2014-06-05 09:10:55 +0000271 default_video_encoder_factory_.reset(new DefaultVideoEncoderFactory());
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000272}
273
274WebRtcVideoEngine2::~WebRtcVideoEngine2() {
275 LOG(LS_INFO) << "WebRtcVideoEngine2::~WebRtcVideoEngine2";
276
277 if (initialized_) {
278 Terminate();
279 }
280}
281
282bool WebRtcVideoEngine2::Init(talk_base::Thread* worker_thread) {
283 LOG(LS_INFO) << "WebRtcVideoEngine2::Init";
284 worker_thread_ = worker_thread;
285 ASSERT(worker_thread_ != NULL);
286
287 cpu_monitor_->set_thread(worker_thread_);
288 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
289 LOG(LS_ERROR) << "Failed to start CPU monitor.";
290 cpu_monitor_.reset();
291 }
292
293 initialized_ = true;
294 return true;
295}
296
297void WebRtcVideoEngine2::Terminate() {
298 LOG(LS_INFO) << "WebRtcVideoEngine2::Terminate";
299
300 cpu_monitor_->Stop();
301
302 initialized_ = false;
303}
304
305int WebRtcVideoEngine2::GetCapabilities() { return VIDEO_RECV | VIDEO_SEND; }
306
307bool WebRtcVideoEngine2::SetOptions(const VideoOptions& options) {
308 // TODO(pbos): Do we need this? This is a no-op in the existing
309 // WebRtcVideoEngine implementation.
310 LOG(LS_VERBOSE) << "SetOptions: " << options.ToString();
311 // options_ = options;
312 return true;
313}
314
315bool WebRtcVideoEngine2::SetDefaultEncoderConfig(
316 const VideoEncoderConfig& config) {
317 // TODO(pbos): Implement. Should be covered by corresponding unit tests.
318 LOG(LS_VERBOSE) << "SetDefaultEncoderConfig()";
319 return true;
320}
321
322VideoEncoderConfig WebRtcVideoEngine2::GetDefaultEncoderConfig() const {
323 return VideoEncoderConfig(DefaultVideoCodec());
324}
325
326WebRtcVideoChannel2* WebRtcVideoEngine2::CreateChannel(
327 VoiceMediaChannel* voice_channel) {
328 LOG(LS_INFO) << "CreateChannel: "
329 << (voice_channel != NULL ? "With" : "Without")
330 << " voice channel.";
331 WebRtcVideoChannel2* channel =
332 channel_factory_ != NULL
333 ? channel_factory_->Create(this, voice_channel)
334 : new WebRtcVideoChannel2(
pbos@webrtc.org0d523ee2014-06-05 09:10:55 +0000335 this, voice_channel, GetVideoEncoderFactory());
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000336 if (!channel->Init()) {
337 delete channel;
338 return NULL;
339 }
340 return channel;
341}
342
343const std::vector<VideoCodec>& WebRtcVideoEngine2::codecs() const {
344 return video_codecs_;
345}
346
347const std::vector<RtpHeaderExtension>&
348WebRtcVideoEngine2::rtp_header_extensions() const {
349 return rtp_header_extensions_;
350}
351
352void WebRtcVideoEngine2::SetLogging(int min_sev, const char* filter) {
353 // TODO(pbos): Set up logging.
354 LOG(LS_VERBOSE) << "SetLogging: " << min_sev << '"' << filter << '"';
355 // if min_sev == -1, we keep the current log level.
356 if (min_sev < 0) {
357 assert(min_sev == -1);
358 return;
359 }
360}
361
362bool WebRtcVideoEngine2::EnableTimedRender() {
363 // TODO(pbos): Figure out whether this can be removed.
364 return true;
365}
366
367bool WebRtcVideoEngine2::SetLocalRenderer(VideoRenderer* renderer) {
368 // TODO(pbos): Implement or remove. Unclear which stream should be rendered
369 // locally even.
370 return true;
371}
372
373// Checks to see whether we comprehend and could receive a particular codec
374bool WebRtcVideoEngine2::FindCodec(const VideoCodec& in) {
375 // TODO(pbos): Probe encoder factory to figure out that the codec is supported
376 // if supported by the encoder factory. Add a corresponding test that fails
377 // with this code (that doesn't ask the factory).
378 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
379 const VideoFormat fmt(kVideoFormats[i]);
380 if ((in.width != 0 || in.height != 0) &&
381 (fmt.width != in.width || fmt.height != in.height)) {
382 continue;
383 }
384 for (size_t j = 0; j < video_codecs_.size(); ++j) {
385 VideoCodec codec(video_codecs_[j].id, video_codecs_[j].name, 0, 0, 0, 0);
386 if (codec.Matches(in)) {
387 return true;
388 }
389 }
390 }
391 return false;
392}
393
394// Tells whether the |requested| codec can be transmitted or not. If it can be
395// transmitted |out| is set with the best settings supported. Aspect ratio will
396// be set as close to |current|'s as possible. If not set |requested|'s
397// dimensions will be used for aspect ratio matching.
398bool WebRtcVideoEngine2::CanSendCodec(const VideoCodec& requested,
399 const VideoCodec& current,
400 VideoCodec* out) {
401 assert(out != NULL);
402 // TODO(pbos): Implement.
403
404 if (requested.width != requested.height &&
405 (requested.height == 0 || requested.width == 0)) {
406 // 0xn and nx0 are invalid resolutions.
407 return false;
408 }
409
410 VideoCodec matching_codec;
411 if (!FindFirstMatchingCodec(video_codecs_, requested, &matching_codec)) {
412 // Codec not supported.
413 return false;
414 }
415
416 // Pick the best quality that is within their and our bounds and has the
417 // correct aspect ratio.
418 VideoFormat format;
419 if (requested.width == 0 && requested.height == 0) {
420 // Special case with resolution 0. The channel should not send frames.
421 } else {
422 int max_width = talk_base::_min(requested.width, matching_codec.width);
423 int max_height = talk_base::_min(requested.height, matching_codec.height);
424 int aspect_width = max_width;
425 int aspect_height = max_height;
426 if (current.width > 0 && current.height > 0) {
427 aspect_width = current.width;
428 aspect_height = current.height;
429 }
430 if (!FindBestVideoFormat(
431 max_width, max_height, aspect_width, aspect_height, &format)) {
432 return false;
433 }
434 }
435
436 out->id = requested.id;
437 out->name = requested.name;
438 out->preference = requested.preference;
439 out->params = requested.params;
440 out->framerate =
441 talk_base::_min(requested.framerate, matching_codec.framerate);
442 out->width = format.width;
443 out->height = format.height;
444 out->params = requested.params;
445 out->feedback_params = requested.feedback_params;
446 return true;
447}
448
449bool WebRtcVideoEngine2::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
450 if (initialized_) {
451 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
452 return false;
453 }
454 voice_engine_ = voice_engine;
455 return true;
456}
457
458// Ignore spammy trace messages, mostly from the stats API when we haven't
459// gotten RTCP info yet from the remote side.
460bool WebRtcVideoEngine2::ShouldIgnoreTrace(const std::string& trace) {
461 static const char* const kTracesToIgnore[] = {NULL};
462 for (const char* const* p = kTracesToIgnore; *p; ++p) {
463 if (trace.find(*p) == 0) {
464 return true;
465 }
466 }
467 return false;
468}
469
pbos@webrtc.org0d523ee2014-06-05 09:10:55 +0000470WebRtcVideoEncoderFactory2* WebRtcVideoEngine2::GetVideoEncoderFactory() const {
471 return default_video_encoder_factory_.get();
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000472}
473
474// Thin map between cricket::VideoFrame and an existing webrtc::I420VideoFrame
475// to avoid having to copy the rendered VideoFrame prematurely.
476// This implementation is only safe to use in a const context and should never
477// be written to.
478class WebRtcVideoRenderFrame : public cricket::VideoFrame {
479 public:
480 explicit WebRtcVideoRenderFrame(const webrtc::I420VideoFrame* frame)
481 : frame_(frame) {}
482
483 virtual bool InitToBlack(int w,
484 int h,
485 size_t pixel_width,
486 size_t pixel_height,
487 int64 elapsed_time,
488 int64 time_stamp) OVERRIDE {
489 UNIMPLEMENTED;
490 return false;
491 }
492
493 virtual bool Reset(uint32 fourcc,
494 int w,
495 int h,
496 int dw,
497 int dh,
498 uint8* sample,
499 size_t sample_size,
500 size_t pixel_width,
501 size_t pixel_height,
502 int64 elapsed_time,
503 int64 time_stamp,
504 int rotation) OVERRIDE {
505 UNIMPLEMENTED;
506 return false;
507 }
508
509 virtual size_t GetWidth() const OVERRIDE {
510 return static_cast<size_t>(frame_->width());
511 }
512 virtual size_t GetHeight() const OVERRIDE {
513 return static_cast<size_t>(frame_->height());
514 }
515
516 virtual const uint8* GetYPlane() const OVERRIDE {
517 return frame_->buffer(webrtc::kYPlane);
518 }
519 virtual const uint8* GetUPlane() const OVERRIDE {
520 return frame_->buffer(webrtc::kUPlane);
521 }
522 virtual const uint8* GetVPlane() const OVERRIDE {
523 return frame_->buffer(webrtc::kVPlane);
524 }
525
526 virtual uint8* GetYPlane() OVERRIDE {
527 UNIMPLEMENTED;
528 return NULL;
529 }
530 virtual uint8* GetUPlane() OVERRIDE {
531 UNIMPLEMENTED;
532 return NULL;
533 }
534 virtual uint8* GetVPlane() OVERRIDE {
535 UNIMPLEMENTED;
536 return NULL;
537 }
538
539 virtual int32 GetYPitch() const OVERRIDE {
540 return frame_->stride(webrtc::kYPlane);
541 }
542 virtual int32 GetUPitch() const OVERRIDE {
543 return frame_->stride(webrtc::kUPlane);
544 }
545 virtual int32 GetVPitch() const OVERRIDE {
546 return frame_->stride(webrtc::kVPlane);
547 }
548
549 virtual void* GetNativeHandle() const OVERRIDE { return NULL; }
550
551 virtual size_t GetPixelWidth() const OVERRIDE { return 1; }
552 virtual size_t GetPixelHeight() const OVERRIDE { return 1; }
553
554 virtual int64 GetElapsedTime() const OVERRIDE {
555 // Convert millisecond render time to ns timestamp.
556 return frame_->render_time_ms() * talk_base::kNumNanosecsPerMillisec;
557 }
558 virtual int64 GetTimeStamp() const OVERRIDE {
559 // Convert 90K rtp timestamp to ns timestamp.
560 return (frame_->timestamp() / 90) * talk_base::kNumNanosecsPerMillisec;
561 }
562 virtual void SetElapsedTime(int64 elapsed_time) OVERRIDE { UNIMPLEMENTED; }
563 virtual void SetTimeStamp(int64 time_stamp) OVERRIDE { UNIMPLEMENTED; }
564
565 virtual int GetRotation() const OVERRIDE {
566 UNIMPLEMENTED;
567 return ROTATION_0;
568 }
569
570 virtual VideoFrame* Copy() const OVERRIDE {
571 UNIMPLEMENTED;
572 return NULL;
573 }
574
575 virtual bool MakeExclusive() OVERRIDE {
576 UNIMPLEMENTED;
577 return false;
578 }
579
580 virtual size_t CopyToBuffer(uint8* buffer, size_t size) const {
581 UNIMPLEMENTED;
582 return 0;
583 }
584
585 // TODO(fbarchard): Refactor into base class and share with LMI
586 virtual size_t ConvertToRgbBuffer(uint32 to_fourcc,
587 uint8* buffer,
588 size_t size,
589 int stride_rgb) const OVERRIDE {
590 size_t width = GetWidth();
591 size_t height = GetHeight();
592 size_t needed = (stride_rgb >= 0 ? stride_rgb : -stride_rgb) * height;
593 if (size < needed) {
594 LOG(LS_WARNING) << "RGB buffer is not large enough";
595 return needed;
596 }
597
598 if (libyuv::ConvertFromI420(GetYPlane(),
599 GetYPitch(),
600 GetUPlane(),
601 GetUPitch(),
602 GetVPlane(),
603 GetVPitch(),
604 buffer,
605 stride_rgb,
606 static_cast<int>(width),
607 static_cast<int>(height),
608 to_fourcc)) {
609 LOG(LS_ERROR) << "RGB type not supported: " << to_fourcc;
610 return 0; // 0 indicates error
611 }
612 return needed;
613 }
614
615 protected:
616 virtual VideoFrame* CreateEmptyFrame(int w,
617 int h,
618 size_t pixel_width,
619 size_t pixel_height,
620 int64 elapsed_time,
621 int64 time_stamp) const OVERRIDE {
622 // TODO(pbos): Remove WebRtcVideoFrame dependency, and have a non-const
623 // version of I420VideoFrame wrapped.
624 WebRtcVideoFrame* frame = new WebRtcVideoFrame();
625 frame->InitToBlack(
626 w, h, pixel_width, pixel_height, elapsed_time, time_stamp);
627 return frame;
628 }
629
630 private:
631 const webrtc::I420VideoFrame* const frame_;
632};
633
634WebRtcVideoRenderer::WebRtcVideoRenderer()
635 : last_width_(-1), last_height_(-1), renderer_(NULL) {}
636
637void WebRtcVideoRenderer::RenderFrame(const webrtc::I420VideoFrame& frame,
638 int time_to_render_ms) {
639 talk_base::CritScope crit(&lock_);
640 if (renderer_ == NULL) {
641 LOG(LS_WARNING) << "VideoReceiveStream not connected to a VideoRenderer.";
642 return;
643 }
644
645 if (frame.width() != last_width_ || frame.height() != last_height_) {
646 SetSize(frame.width(), frame.height());
647 }
648
649 LOG(LS_VERBOSE) << "RenderFrame: (" << frame.width() << "x" << frame.height()
650 << ")";
651
652 const WebRtcVideoRenderFrame render_frame(&frame);
653 renderer_->RenderFrame(&render_frame);
654}
655
656void WebRtcVideoRenderer::SetRenderer(cricket::VideoRenderer* renderer) {
657 talk_base::CritScope crit(&lock_);
658 renderer_ = renderer;
659 if (renderer_ != NULL && last_width_ != -1) {
660 SetSize(last_width_, last_height_);
661 }
662}
663
664VideoRenderer* WebRtcVideoRenderer::GetRenderer() {
665 talk_base::CritScope crit(&lock_);
666 return renderer_;
667}
668
669void WebRtcVideoRenderer::SetSize(int width, int height) {
670 talk_base::CritScope crit(&lock_);
671 if (!renderer_->SetSize(width, height, 0)) {
672 LOG(LS_ERROR) << "Could not set renderer size.";
673 }
674 last_width_ = width;
675 last_height_ = height;
676}
677
678// WebRtcVideoChannel2
679
680WebRtcVideoChannel2::WebRtcVideoChannel2(
681 WebRtcVideoEngine2* engine,
682 VoiceMediaChannel* voice_channel,
683 WebRtcVideoEncoderFactory2* encoder_factory)
684 : encoder_factory_(encoder_factory) {
685 // TODO(pbos): Connect the video and audio with |voice_channel|.
686 webrtc::Call::Config config(this);
687 Construct(webrtc::Call::Create(config), engine);
688}
689
690WebRtcVideoChannel2::WebRtcVideoChannel2(
691 webrtc::Call* call,
692 WebRtcVideoEngine2* engine,
693 WebRtcVideoEncoderFactory2* encoder_factory)
694 : encoder_factory_(encoder_factory) {
695 Construct(call, engine);
696}
697
698void WebRtcVideoChannel2::Construct(webrtc::Call* call,
699 WebRtcVideoEngine2* engine) {
700 rtcp_receiver_report_ssrc_ = kDefaultRtcpReceiverReportSsrc;
701 sending_ = false;
702 call_.reset(call);
703 default_renderer_ = NULL;
704 default_send_ssrc_ = 0;
705 default_recv_ssrc_ = 0;
706}
707
708WebRtcVideoChannel2::~WebRtcVideoChannel2() {
709 for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
710 send_streams_.begin();
711 it != send_streams_.end();
712 ++it) {
713 delete it->second;
714 }
715
716 for (std::map<uint32, webrtc::VideoReceiveStream*>::iterator it =
717 receive_streams_.begin();
718 it != receive_streams_.end();
719 ++it) {
720 assert(it->second != NULL);
721 call_->DestroyVideoReceiveStream(it->second);
722 }
723
724 for (std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.begin();
725 it != renderers_.end();
726 ++it) {
727 assert(it->second != NULL);
728 delete it->second;
729 }
730}
731
732bool WebRtcVideoChannel2::Init() { return true; }
733
734namespace {
735
736static bool ValidateCodecFormats(const std::vector<VideoCodec>& codecs) {
737 for (size_t i = 0; i < codecs.size(); ++i) {
738 if (!codecs[i].ValidateCodecFormat()) {
739 return false;
740 }
741 }
742 return true;
743}
744
745static std::string CodecVectorToString(const std::vector<VideoCodec>& codecs) {
746 std::stringstream out;
747 out << '{';
748 for (size_t i = 0; i < codecs.size(); ++i) {
749 out << codecs[i].ToString();
750 if (i != codecs.size() - 1) {
751 out << ", ";
752 }
753 }
754 out << '}';
755 return out.str();
756}
757
758} // namespace
759
760bool WebRtcVideoChannel2::SetRecvCodecs(const std::vector<VideoCodec>& codecs) {
761 // TODO(pbos): Must these receive codecs propagate to existing receive
762 // streams?
763 LOG(LS_INFO) << "SetRecvCodecs: " << CodecVectorToString(codecs);
764 if (!ValidateCodecFormats(codecs)) {
765 return false;
766 }
767
768 const std::vector<VideoCodecSettings> mapped_codecs = MapCodecs(codecs);
769 if (mapped_codecs.empty()) {
770 LOG(LS_ERROR) << "SetRecvCodecs called without video codec payloads.";
771 return false;
772 }
773
774 // TODO(pbos): Add a decoder factory which controls supported codecs.
775 // Blocked on webrtc:2854.
776 for (size_t i = 0; i < mapped_codecs.size(); ++i) {
777 if (_stricmp(mapped_codecs[i].codec.name.c_str(), kVp8PayloadName) != 0) {
778 LOG(LS_ERROR) << "SetRecvCodecs called with unsupported codec: '"
779 << mapped_codecs[i].codec.name << "'";
780 return false;
781 }
782 }
783
784 recv_codecs_ = mapped_codecs;
785 return true;
786}
787
788bool WebRtcVideoChannel2::SetSendCodecs(const std::vector<VideoCodec>& codecs) {
789 LOG(LS_INFO) << "SetSendCodecs: " << CodecVectorToString(codecs);
790 if (!ValidateCodecFormats(codecs)) {
791 return false;
792 }
793
794 const std::vector<VideoCodecSettings> supported_codecs =
795 FilterSupportedCodecs(MapCodecs(codecs));
796
797 if (supported_codecs.empty()) {
798 LOG(LS_ERROR) << "No video codecs supported by encoder factory.";
799 return false;
800 }
801
802 send_codec_.Set(supported_codecs.front());
803 LOG(LS_INFO) << "Using codec: " << supported_codecs.front().codec.ToString();
804
805 SetCodecForAllSendStreams(supported_codecs.front());
806
807 return true;
808}
809
810bool WebRtcVideoChannel2::GetSendCodec(VideoCodec* codec) {
811 VideoCodecSettings codec_settings;
812 if (!send_codec_.Get(&codec_settings)) {
813 LOG(LS_VERBOSE) << "GetSendCodec: No send codec set.";
814 return false;
815 }
816 *codec = codec_settings.codec;
817 return true;
818}
819
820bool WebRtcVideoChannel2::SetSendStreamFormat(uint32 ssrc,
821 const VideoFormat& format) {
822 LOG(LS_VERBOSE) << "SetSendStreamFormat:" << ssrc << " -> "
823 << format.ToString();
824 if (send_streams_.find(ssrc) == send_streams_.end()) {
825 return false;
826 }
827 return send_streams_[ssrc]->SetVideoFormat(format);
828}
829
830bool WebRtcVideoChannel2::SetRender(bool render) {
831 // TODO(pbos): Implement. Or refactor away as it shouldn't be needed.
832 LOG(LS_VERBOSE) << "SetRender: " << (render ? "true" : "false");
833 return true;
834}
835
836bool WebRtcVideoChannel2::SetSend(bool send) {
837 LOG(LS_VERBOSE) << "SetSend: " << (send ? "true" : "false");
838 if (send && !send_codec_.IsSet()) {
839 LOG(LS_ERROR) << "SetSend(true) called before setting codec.";
840 return false;
841 }
842 if (send) {
843 StartAllSendStreams();
844 } else {
845 StopAllSendStreams();
846 }
847 sending_ = send;
848 return true;
849}
850
851static bool ConfigureSendSsrcs(webrtc::VideoSendStream::Config* config,
852 const StreamParams& sp) {
853 if (!sp.has_ssrc_groups()) {
854 config->rtp.ssrcs = sp.ssrcs;
855 return true;
856 }
857
858 if (sp.get_ssrc_group(kFecSsrcGroupSemantics) != NULL) {
859 LOG(LS_ERROR) << "Standalone FEC SSRCs not supported.";
860 return false;
861 }
862
863 const SsrcGroup* sim_group = sp.get_ssrc_group(kSimSsrcGroupSemantics);
864 if (sim_group == NULL) {
865 LOG(LS_ERROR) << "Grouped StreamParams without regular SSRC group: "
866 << sp.ToString();
867 return false;
868 }
869
870 // Map RTX SSRCs.
871 std::vector<uint32_t> rtx_ssrcs;
872 for (size_t i = 0; i < sim_group->ssrcs.size(); ++i) {
873 uint32_t rtx_ssrc;
874 if (!sp.GetFidSsrc(sim_group->ssrcs[i], &rtx_ssrc)) {
875 continue;
876 }
877 rtx_ssrcs.push_back(rtx_ssrc);
878 }
879 if (!rtx_ssrcs.empty() && sim_group->ssrcs.size() != rtx_ssrcs.size()) {
880 LOG(LS_ERROR)
881 << "RTX SSRCs exist, but don't cover all SSRCs (unsupported): "
882 << sp.ToString();
883 return false;
884 }
885 config->rtp.rtx.ssrcs = rtx_ssrcs;
886 config->rtp.ssrcs = sim_group->ssrcs;
887 return true;
888}
889
890bool WebRtcVideoChannel2::AddSendStream(const StreamParams& sp) {
891 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
892 if (sp.ssrcs.empty()) {
893 LOG(LS_ERROR) << "No SSRCs in stream parameters.";
894 return false;
895 }
896
897 uint32 ssrc = sp.first_ssrc();
898 assert(ssrc != 0);
899 // TODO(pbos): Make sure none of sp.ssrcs are used, not just the identifying
900 // ssrc.
901 if (send_streams_.find(ssrc) != send_streams_.end()) {
902 LOG(LS_ERROR) << "Send stream with ssrc '" << ssrc << "' already exists.";
903 return false;
904 }
905
906 webrtc::VideoSendStream::Config config = call_->GetDefaultSendConfig();
907
908 if (!ConfigureSendSsrcs(&config, sp)) {
909 return false;
910 }
911
912 VideoCodecSettings codec_settings;
913 if (!send_codec_.Get(&codec_settings)) {
914 // TODO(pbos): Set up a temporary fake encoder for VideoSendStream instead
915 // of setting default codecs not to break CreateEncoderSettings.
916 SetSendCodecs(DefaultVideoCodecs());
917 assert(send_codec_.IsSet());
918 send_codec_.Get(&codec_settings);
919 // This is only to bring up defaults to make VideoSendStream setup easier
920 // and avoid complexity. We still don't want to allow sending with the
921 // default codec.
922 send_codec_.Clear();
923 }
924
925 // CreateEncoderSettings will allocate a suitable VideoEncoder instance
926 // matching current settings.
927 if (!encoder_factory_->CreateEncoderSettings(&config.encoder_settings,
928 options_,
929 codec_settings.codec,
930 config.rtp.ssrcs.size())) {
931 LOG(LS_ERROR) << "Failed to create suitable encoder settings.";
932 return false;
933 }
934
935 config.rtp.c_name = sp.cname;
936 config.rtp.fec = codec_settings.fec;
937 if (!config.rtp.rtx.ssrcs.empty()) {
938 config.rtp.rtx.payload_type = codec_settings.rtx_payload_type;
939 }
940
941 config.rtp.nack.rtp_history_ms = kNackHistoryMs;
942 config.rtp.max_packet_size = kVideoMtu;
943
944 WebRtcVideoSendStream* stream =
945 new WebRtcVideoSendStream(call_.get(), config, encoder_factory_);
946 send_streams_[ssrc] = stream;
947
948 if (rtcp_receiver_report_ssrc_ == kDefaultRtcpReceiverReportSsrc) {
949 rtcp_receiver_report_ssrc_ = ssrc;
950 }
951 if (default_send_ssrc_ == 0) {
952 default_send_ssrc_ = ssrc;
953 }
954 if (sending_) {
955 stream->Start();
956 }
957
958 return true;
959}
960
961bool WebRtcVideoChannel2::RemoveSendStream(uint32 ssrc) {
962 LOG(LS_INFO) << "RemoveSendStream: " << ssrc;
963
964 if (ssrc == 0) {
965 if (default_send_ssrc_ == 0) {
966 LOG(LS_ERROR) << "No default send stream active.";
967 return false;
968 }
969
970 LOG(LS_VERBOSE) << "Removing default stream: " << default_send_ssrc_;
971 ssrc = default_send_ssrc_;
972 }
973
974 std::map<uint32, WebRtcVideoSendStream*>::iterator it =
975 send_streams_.find(ssrc);
976 if (it == send_streams_.end()) {
977 return false;
978 }
979
980 delete it->second;
981 send_streams_.erase(it);
982
983 if (ssrc == default_send_ssrc_) {
984 default_send_ssrc_ = 0;
985 }
986
987 return true;
988}
989
990bool WebRtcVideoChannel2::AddRecvStream(const StreamParams& sp) {
991 LOG(LS_INFO) << "AddRecvStream: " << sp.ToString();
992 assert(sp.ssrcs.size() > 0);
993
994 uint32 ssrc = sp.first_ssrc();
995 assert(ssrc != 0); // TODO(pbos): Is this ever valid?
996 if (default_recv_ssrc_ == 0) {
997 default_recv_ssrc_ = ssrc;
998 }
999
1000 // TODO(pbos): Check if any of the SSRCs overlap.
1001 if (receive_streams_.find(ssrc) != receive_streams_.end()) {
1002 LOG(LS_ERROR) << "Receive stream for SSRC " << ssrc << "already exists.";
1003 return false;
1004 }
1005
1006 webrtc::VideoReceiveStream::Config config = call_->GetDefaultReceiveConfig();
1007 config.rtp.remote_ssrc = ssrc;
1008 config.rtp.local_ssrc = rtcp_receiver_report_ssrc_;
1009 uint32 rtx_ssrc = 0;
1010 if (sp.GetFidSsrc(ssrc, &rtx_ssrc)) {
1011 // TODO(pbos): Right now, VideoReceiveStream accepts any rtx payload, this
1012 // should use the actual codec payloads that may be received.
1013 // (for each receive payload, set rtx[payload].ssrc = rtx_ssrc.
1014 config.rtp.rtx[0].ssrc = rtx_ssrc;
1015 }
1016
pbos@webrtc.org19864742014-05-30 07:35:47 +00001017 config.rtp.nack.rtp_history_ms = kNackHistoryMs;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001018 config.rtp.remb = true;
1019 // TODO(pbos): This protection is against setting the same local ssrc as
1020 // remote which is not permitted by the lower-level API. RTCP requires a
1021 // corresponding sender SSRC. Figure out what to do when we don't have
1022 // (receive-only) or know a good local SSRC.
1023 if (config.rtp.remote_ssrc == config.rtp.local_ssrc) {
1024 if (config.rtp.local_ssrc != kDefaultRtcpReceiverReportSsrc) {
1025 config.rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc;
1026 } else {
1027 config.rtp.local_ssrc = kDefaultRtcpReceiverReportSsrc + 1;
1028 }
1029 }
1030 bool default_renderer_used = false;
1031 for (std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.begin();
1032 it != renderers_.end();
1033 ++it) {
1034 if (it->second->GetRenderer() == default_renderer_) {
1035 default_renderer_used = true;
1036 break;
1037 }
1038 }
1039
1040 assert(renderers_[ssrc] == NULL);
1041 renderers_[ssrc] = new WebRtcVideoRenderer();
1042 if (!default_renderer_used) {
1043 renderers_[ssrc]->SetRenderer(default_renderer_);
1044 }
1045 config.renderer = renderers_[ssrc];
1046
1047 {
1048 // TODO(pbos): Base receive codecs off recv_codecs_ and set up using a
1049 // DecoderFactory similar to send side. Pending webrtc:2854.
1050 // Also set up default codecs if there's nothing in recv_codecs_.
1051 webrtc::VideoCodec codec;
1052 memset(&codec, 0, sizeof(codec));
1053
1054 codec.plType = kDefaultVideoCodecPref.payload_type;
1055 strcpy(codec.plName, kDefaultVideoCodecPref.name);
1056 codec.codecType = webrtc::kVideoCodecVP8;
1057 codec.codecSpecific.VP8.resilience = webrtc::kResilientStream;
1058 codec.codecSpecific.VP8.numberOfTemporalLayers = 1;
1059 codec.codecSpecific.VP8.denoisingOn = true;
1060 codec.codecSpecific.VP8.errorConcealmentOn = false;
1061 codec.codecSpecific.VP8.automaticResizeOn = false;
1062 codec.codecSpecific.VP8.frameDroppingOn = true;
1063 codec.codecSpecific.VP8.keyFrameInterval = 3000;
1064 // Bitrates don't matter and are ignored for the receiver. This is put in to
1065 // have the current underlying implementation accept the VideoCodec.
1066 codec.minBitrate = codec.startBitrate = codec.maxBitrate = 300;
1067 config.codecs.push_back(codec);
1068 for (size_t i = 0; i < recv_codecs_.size(); ++i) {
1069 if (recv_codecs_[i].codec.id == codec.plType) {
1070 config.rtp.fec = recv_codecs_[i].fec;
1071 if (recv_codecs_[i].rtx_payload_type != -1 && rtx_ssrc != 0) {
1072 config.rtp.rtx[codec.plType].ssrc = rtx_ssrc;
1073 config.rtp.rtx[codec.plType].payload_type =
1074 recv_codecs_[i].rtx_payload_type;
1075 }
1076 break;
1077 }
1078 }
1079 }
1080
1081 webrtc::VideoReceiveStream* receive_stream =
1082 call_->CreateVideoReceiveStream(config);
1083 assert(receive_stream != NULL);
1084
1085 receive_streams_[ssrc] = receive_stream;
1086 receive_stream->Start();
1087
1088 return true;
1089}
1090
1091bool WebRtcVideoChannel2::RemoveRecvStream(uint32 ssrc) {
1092 LOG(LS_INFO) << "RemoveRecvStream: " << ssrc;
1093 if (ssrc == 0) {
1094 ssrc = default_recv_ssrc_;
1095 }
1096
1097 std::map<uint32, webrtc::VideoReceiveStream*>::iterator stream =
1098 receive_streams_.find(ssrc);
1099 if (stream == receive_streams_.end()) {
1100 LOG(LS_ERROR) << "Stream not found for ssrc: " << ssrc;
1101 return false;
1102 }
1103 call_->DestroyVideoReceiveStream(stream->second);
1104 receive_streams_.erase(stream);
1105
1106 std::map<uint32, WebRtcVideoRenderer*>::iterator renderer =
1107 renderers_.find(ssrc);
1108 assert(renderer != renderers_.end());
1109 delete renderer->second;
1110 renderers_.erase(renderer);
1111
1112 if (ssrc == default_recv_ssrc_) {
1113 default_recv_ssrc_ = 0;
1114 }
1115
1116 return true;
1117}
1118
1119bool WebRtcVideoChannel2::SetRenderer(uint32 ssrc, VideoRenderer* renderer) {
1120 LOG(LS_INFO) << "SetRenderer: ssrc:" << ssrc << " "
1121 << (renderer ? "(ptr)" : "NULL");
1122 bool is_default_ssrc = false;
1123 if (ssrc == 0) {
1124 is_default_ssrc = true;
1125 ssrc = default_recv_ssrc_;
1126 default_renderer_ = renderer;
1127 }
1128
1129 std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.find(ssrc);
1130 if (it == renderers_.end()) {
1131 return is_default_ssrc;
1132 }
1133
1134 it->second->SetRenderer(renderer);
1135 return true;
1136}
1137
1138bool WebRtcVideoChannel2::GetRenderer(uint32 ssrc, VideoRenderer** renderer) {
1139 if (ssrc == 0) {
1140 if (default_renderer_ == NULL) {
1141 return false;
1142 }
1143 *renderer = default_renderer_;
1144 return true;
1145 }
1146
1147 std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.find(ssrc);
1148 if (it == renderers_.end()) {
1149 return false;
1150 }
1151 *renderer = it->second->GetRenderer();
1152 return true;
1153}
1154
1155bool WebRtcVideoChannel2::GetStats(const StatsOptions& options,
1156 VideoMediaInfo* info) {
1157 // TODO(pbos): Implement.
1158 return true;
1159}
1160
1161bool WebRtcVideoChannel2::SetCapturer(uint32 ssrc, VideoCapturer* capturer) {
1162 LOG(LS_INFO) << "SetCapturer: " << ssrc << " -> "
1163 << (capturer != NULL ? "(capturer)" : "NULL");
1164 assert(ssrc != 0);
1165 if (send_streams_.find(ssrc) == send_streams_.end()) {
1166 LOG(LS_ERROR) << "No sending stream on ssrc " << ssrc;
1167 return false;
1168 }
1169 return send_streams_[ssrc]->SetCapturer(capturer);
1170}
1171
1172bool WebRtcVideoChannel2::SendIntraFrame() {
1173 // TODO(pbos): Implement.
1174 LOG(LS_VERBOSE) << "SendIntraFrame().";
1175 return true;
1176}
1177
1178bool WebRtcVideoChannel2::RequestIntraFrame() {
1179 // TODO(pbos): Implement.
1180 LOG(LS_VERBOSE) << "SendIntraFrame().";
1181 return true;
1182}
1183
1184void WebRtcVideoChannel2::OnPacketReceived(
1185 talk_base::Buffer* packet,
1186 const talk_base::PacketTime& packet_time) {
pbos@webrtc.org4e545cc2014-05-14 13:58:13 +00001187 const webrtc::PacketReceiver::DeliveryStatus delivery_result =
1188 call_->Receiver()->DeliverPacket(
1189 reinterpret_cast<const uint8_t*>(packet->data()), packet->length());
1190 switch (delivery_result) {
1191 case webrtc::PacketReceiver::DELIVERY_OK:
1192 return;
1193 case webrtc::PacketReceiver::DELIVERY_PACKET_ERROR:
1194 return;
1195 case webrtc::PacketReceiver::DELIVERY_UNKNOWN_SSRC:
1196 break;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001197 }
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001198
1199 uint32 ssrc = 0;
1200 if (default_recv_ssrc_ != 0) { // Already one default stream.
pbos@webrtc.org4e545cc2014-05-14 13:58:13 +00001201 LOG(LS_WARNING) << "Unknown SSRC, but default receive stream already set.";
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001202 return;
1203 }
1204
1205 if (!GetRtpSsrc(packet->data(), packet->length(), &ssrc)) {
1206 return;
1207 }
1208
1209 StreamParams sp;
1210 sp.ssrcs.push_back(ssrc);
pbos@webrtc.orgc34bb3a2014-05-30 07:38:43 +00001211 LOG(LS_INFO) << "Creating default receive stream for SSRC=" << ssrc << ".";
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001212 AddRecvStream(sp);
1213
pbos@webrtc.org1e019d12014-05-16 11:38:45 +00001214 if (call_->Receiver()->DeliverPacket(
1215 reinterpret_cast<const uint8_t*>(packet->data()), packet->length()) !=
1216 webrtc::PacketReceiver::DELIVERY_OK) {
1217 LOG(LS_WARNING) << "Failed to deliver RTP packet after creating default "
1218 "receiver.";
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001219 return;
1220 }
1221}
1222
1223void WebRtcVideoChannel2::OnRtcpReceived(
1224 talk_base::Buffer* packet,
1225 const talk_base::PacketTime& packet_time) {
pbos@webrtc.org1e019d12014-05-16 11:38:45 +00001226 if (call_->Receiver()->DeliverPacket(
1227 reinterpret_cast<const uint8_t*>(packet->data()), packet->length()) !=
1228 webrtc::PacketReceiver::DELIVERY_OK) {
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001229 LOG(LS_WARNING) << "Failed to deliver RTCP packet.";
1230 }
1231}
1232
1233void WebRtcVideoChannel2::OnReadyToSend(bool ready) {
1234 LOG(LS_VERBOSE) << "OnReadySend: " << (ready ? "Ready." : "Not ready.");
1235}
1236
1237bool WebRtcVideoChannel2::MuteStream(uint32 ssrc, bool mute) {
1238 LOG(LS_VERBOSE) << "MuteStream: " << ssrc << " -> "
1239 << (mute ? "mute" : "unmute");
1240 assert(ssrc != 0);
1241 if (send_streams_.find(ssrc) == send_streams_.end()) {
1242 LOG(LS_ERROR) << "No sending stream on ssrc " << ssrc;
1243 return false;
1244 }
1245 return send_streams_[ssrc]->MuteStream(mute);
1246}
1247
1248bool WebRtcVideoChannel2::SetRecvRtpHeaderExtensions(
1249 const std::vector<RtpHeaderExtension>& extensions) {
1250 // TODO(pbos): Implement.
1251 LOG(LS_VERBOSE) << "SetRecvRtpHeaderExtensions()";
1252 return true;
1253}
1254
1255bool WebRtcVideoChannel2::SetSendRtpHeaderExtensions(
1256 const std::vector<RtpHeaderExtension>& extensions) {
1257 // TODO(pbos): Implement.
1258 LOG(LS_VERBOSE) << "SetSendRtpHeaderExtensions()";
1259 return true;
1260}
1261
1262bool WebRtcVideoChannel2::SetStartSendBandwidth(int bps) {
1263 // TODO(pbos): Implement.
1264 LOG(LS_VERBOSE) << "SetStartSendBandwidth: " << bps;
1265 return true;
1266}
1267
1268bool WebRtcVideoChannel2::SetMaxSendBandwidth(int bps) {
1269 // TODO(pbos): Implement.
1270 LOG(LS_VERBOSE) << "SetMaxSendBandwidth: " << bps;
1271 return true;
1272}
1273
1274bool WebRtcVideoChannel2::SetOptions(const VideoOptions& options) {
1275 LOG(LS_VERBOSE) << "SetOptions: " << options.ToString();
1276 options_.SetAll(options);
1277 return true;
1278}
1279
1280void WebRtcVideoChannel2::SetInterface(NetworkInterface* iface) {
1281 MediaChannel::SetInterface(iface);
1282 // Set the RTP recv/send buffer to a bigger size
1283 MediaChannel::SetOption(NetworkInterface::ST_RTP,
1284 talk_base::Socket::OPT_RCVBUF,
1285 kVideoRtpBufferSize);
1286
1287 // TODO(sriniv): Remove or re-enable this.
1288 // As part of b/8030474, send-buffer is size now controlled through
1289 // portallocator flags.
1290 // network_interface_->SetOption(NetworkInterface::ST_RTP,
1291 // talk_base::Socket::OPT_SNDBUF,
1292 // kVideoRtpBufferSize);
1293}
1294
1295void WebRtcVideoChannel2::UpdateAspectRatio(int ratio_w, int ratio_h) {
1296 // TODO(pbos): Implement.
1297}
1298
1299void WebRtcVideoChannel2::OnMessage(talk_base::Message* msg) {
1300 // Ignored.
1301}
1302
1303bool WebRtcVideoChannel2::SendRtp(const uint8_t* data, size_t len) {
1304 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
1305 return MediaChannel::SendPacket(&packet);
1306}
1307
1308bool WebRtcVideoChannel2::SendRtcp(const uint8_t* data, size_t len) {
1309 talk_base::Buffer packet(data, len, kMaxRtpPacketLen);
1310 return MediaChannel::SendRtcp(&packet);
1311}
1312
1313void WebRtcVideoChannel2::StartAllSendStreams() {
1314 for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
1315 send_streams_.begin();
1316 it != send_streams_.end();
1317 ++it) {
1318 it->second->Start();
1319 }
1320}
1321
1322void WebRtcVideoChannel2::StopAllSendStreams() {
1323 for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
1324 send_streams_.begin();
1325 it != send_streams_.end();
1326 ++it) {
1327 it->second->Stop();
1328 }
1329}
1330
1331void WebRtcVideoChannel2::SetCodecForAllSendStreams(
1332 const WebRtcVideoChannel2::VideoCodecSettings& codec) {
1333 for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
1334 send_streams_.begin();
1335 it != send_streams_.end();
1336 ++it) {
1337 assert(it->second != NULL);
1338 it->second->SetCodec(options_, codec);
1339 }
1340}
1341
1342WebRtcVideoChannel2::WebRtcVideoSendStream::WebRtcVideoSendStream(
1343 webrtc::Call* call,
1344 const webrtc::VideoSendStream::Config& config,
1345 WebRtcVideoEncoderFactory2* encoder_factory)
1346 : call_(call),
1347 config_(config),
1348 encoder_factory_(encoder_factory),
1349 capturer_(NULL),
1350 stream_(NULL),
1351 sending_(false),
1352 muted_(false),
1353 format_(static_cast<int>(config.encoder_settings.streams.back().height),
1354 static_cast<int>(config.encoder_settings.streams.back().width),
1355 VideoFormat::FpsToInterval(
1356 config.encoder_settings.streams.back().max_framerate),
1357 FOURCC_I420) {
1358 RecreateWebRtcStream();
1359}
1360
1361WebRtcVideoChannel2::WebRtcVideoSendStream::~WebRtcVideoSendStream() {
1362 DisconnectCapturer();
1363 call_->DestroyVideoSendStream(stream_);
1364 delete config_.encoder_settings.encoder;
1365}
1366
1367static void SetWebRtcFrameToBlack(webrtc::I420VideoFrame* video_frame) {
1368 assert(video_frame != NULL);
1369 memset(video_frame->buffer(webrtc::kYPlane),
1370 16,
1371 video_frame->allocated_size(webrtc::kYPlane));
1372 memset(video_frame->buffer(webrtc::kUPlane),
1373 128,
1374 video_frame->allocated_size(webrtc::kUPlane));
1375 memset(video_frame->buffer(webrtc::kVPlane),
1376 128,
1377 video_frame->allocated_size(webrtc::kVPlane));
1378}
1379
1380static void CreateBlackFrame(webrtc::I420VideoFrame* video_frame,
1381 int width,
1382 int height) {
1383 video_frame->CreateEmptyFrame(
1384 width, height, width, (width + 1) / 2, (width + 1) / 2);
1385 SetWebRtcFrameToBlack(video_frame);
1386}
1387
1388static void ConvertToI420VideoFrame(const VideoFrame& frame,
1389 webrtc::I420VideoFrame* i420_frame) {
1390 i420_frame->CreateFrame(
1391 static_cast<int>(frame.GetYPitch() * frame.GetHeight()),
1392 frame.GetYPlane(),
1393 static_cast<int>(frame.GetUPitch() * ((frame.GetHeight() + 1) / 2)),
1394 frame.GetUPlane(),
1395 static_cast<int>(frame.GetVPitch() * ((frame.GetHeight() + 1) / 2)),
1396 frame.GetVPlane(),
1397 static_cast<int>(frame.GetWidth()),
1398 static_cast<int>(frame.GetHeight()),
1399 static_cast<int>(frame.GetYPitch()),
1400 static_cast<int>(frame.GetUPitch()),
1401 static_cast<int>(frame.GetVPitch()));
1402}
1403
1404void WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame(
1405 VideoCapturer* capturer,
1406 const VideoFrame* frame) {
1407 LOG(LS_VERBOSE) << "InputFrame: " << frame->GetWidth() << "x"
1408 << frame->GetHeight();
1409 bool is_screencast = capturer->IsScreencast();
1410 // Lock before copying, can be called concurrently when swapping input source.
1411 talk_base::CritScope frame_cs(&frame_lock_);
1412 if (!muted_) {
1413 ConvertToI420VideoFrame(*frame, &video_frame_);
1414 } else {
1415 // Create a tiny black frame to transmit instead.
1416 CreateBlackFrame(&video_frame_, 1, 1);
1417 is_screencast = false;
1418 }
1419 talk_base::CritScope cs(&lock_);
1420 if (format_.width == 0) { // Dropping frames.
1421 assert(format_.height == 0);
1422 LOG(LS_VERBOSE) << "VideoFormat 0x0 set, Dropping frame.";
1423 return;
1424 }
1425 // Reconfigure codec if necessary.
1426 if (is_screencast) {
1427 SetDimensions(video_frame_.width(), video_frame_.height());
1428 }
1429 LOG(LS_VERBOSE) << "SwapFrame: " << video_frame_.width() << "x"
1430 << video_frame_.height() << " -> (codec) "
1431 << config_.encoder_settings.streams.back().width << "x"
1432 << config_.encoder_settings.streams.back().height;
1433 stream_->Input()->SwapFrame(&video_frame_);
1434}
1435
1436bool WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer(
1437 VideoCapturer* capturer) {
1438 if (!DisconnectCapturer() && capturer == NULL) {
1439 return false;
1440 }
1441
1442 {
1443 talk_base::CritScope cs(&lock_);
1444
1445 if (capturer == NULL) {
1446 LOG(LS_VERBOSE) << "Disabling capturer, sending black frame.";
1447 webrtc::I420VideoFrame black_frame;
1448
1449 int width = format_.width;
1450 int height = format_.height;
1451 int half_width = (width + 1) / 2;
1452 black_frame.CreateEmptyFrame(
1453 width, height, width, half_width, half_width);
1454 SetWebRtcFrameToBlack(&black_frame);
1455 SetDimensions(width, height);
1456 stream_->Input()->SwapFrame(&black_frame);
1457
1458 capturer_ = NULL;
1459 return true;
1460 }
1461
1462 capturer_ = capturer;
1463 }
1464 // Lock cannot be held while connecting the capturer to prevent lock-order
1465 // violations.
1466 capturer->SignalVideoFrame.connect(this, &WebRtcVideoSendStream::InputFrame);
1467 return true;
1468}
1469
1470bool WebRtcVideoChannel2::WebRtcVideoSendStream::SetVideoFormat(
1471 const VideoFormat& format) {
1472 if ((format.width == 0 || format.height == 0) &&
1473 format.width != format.height) {
1474 LOG(LS_ERROR) << "Can't set VideoFormat, width or height is zero (but not "
1475 "both, 0x0 drops frames).";
1476 return false;
1477 }
1478
1479 talk_base::CritScope cs(&lock_);
1480 if (format.width == 0 && format.height == 0) {
1481 LOG(LS_INFO)
1482 << "0x0 resolution selected. Captured frames will be dropped for ssrc: "
1483 << config_.rtp.ssrcs[0] << ".";
1484 } else {
1485 // TODO(pbos): Fix me, this only affects the last stream!
1486 config_.encoder_settings.streams.back().max_framerate =
1487 VideoFormat::IntervalToFps(format.interval);
1488 SetDimensions(format.width, format.height);
1489 }
1490
1491 format_ = format;
1492 return true;
1493}
1494
1495bool WebRtcVideoChannel2::WebRtcVideoSendStream::MuteStream(bool mute) {
1496 talk_base::CritScope cs(&lock_);
1497 bool was_muted = muted_;
1498 muted_ = mute;
1499 return was_muted != mute;
1500}
1501
1502bool WebRtcVideoChannel2::WebRtcVideoSendStream::DisconnectCapturer() {
1503 talk_base::CritScope cs(&lock_);
1504 if (capturer_ == NULL) {
1505 return false;
1506 }
1507 capturer_->SignalVideoFrame.disconnect(this);
1508 capturer_ = NULL;
1509 return true;
1510}
1511
1512void WebRtcVideoChannel2::WebRtcVideoSendStream::SetCodec(
1513 const VideoOptions& options,
1514 const VideoCodecSettings& codec) {
1515 talk_base::CritScope cs(&lock_);
1516 webrtc::VideoEncoder* old_encoder = config_.encoder_settings.encoder;
1517 if (!encoder_factory_->CreateEncoderSettings(
1518 &config_.encoder_settings,
1519 options,
1520 codec.codec,
1521 config_.encoder_settings.streams.size())) {
1522 LOG(LS_ERROR) << "Could not create encoder settings for: '"
1523 << codec.codec.name
1524 << "'. This is most definitely a bug as SetCodec should only "
1525 "receive codecs which the encoder factory claims to "
1526 "support.";
1527 return;
1528 }
1529 format_ = VideoFormat(codec.codec.width,
1530 codec.codec.height,
1531 VideoFormat::FpsToInterval(30),
1532 FOURCC_I420);
1533 config_.rtp.fec = codec.fec;
1534 // TODO(pbos): Should changing RTX payload type be allowed?
1535 RecreateWebRtcStream();
1536 delete old_encoder;
1537}
1538
1539void WebRtcVideoChannel2::WebRtcVideoSendStream::SetDimensions(int width,
1540 int height) {
1541 assert(!config_.encoder_settings.streams.empty());
1542 LOG(LS_VERBOSE) << "SetDimensions: " << width << "x" << height;
1543 if (config_.encoder_settings.streams.back().width == width &&
1544 config_.encoder_settings.streams.back().height == height) {
1545 return;
1546 }
1547
1548 // TODO(pbos): Fix me, this only affects the last stream!
1549 config_.encoder_settings.streams.back().width = width;
1550 config_.encoder_settings.streams.back().height = height;
1551 // TODO(pbos): Last parameter shouldn't always be NULL?
1552 if (!stream_->ReconfigureVideoEncoder(config_.encoder_settings.streams,
1553 NULL)) {
1554 LOG(LS_WARNING) << "Failed to reconfigure video encoder for dimensions: "
1555 << width << "x" << height;
1556 return;
1557 }
1558}
1559
1560void WebRtcVideoChannel2::WebRtcVideoSendStream::Start() {
1561 talk_base::CritScope cs(&lock_);
1562 stream_->Start();
1563 sending_ = true;
1564}
1565
1566void WebRtcVideoChannel2::WebRtcVideoSendStream::Stop() {
1567 talk_base::CritScope cs(&lock_);
1568 stream_->Stop();
1569 sending_ = false;
1570}
1571
1572void WebRtcVideoChannel2::WebRtcVideoSendStream::RecreateWebRtcStream() {
1573 if (stream_ != NULL) {
1574 call_->DestroyVideoSendStream(stream_);
1575 }
1576 stream_ = call_->CreateVideoSendStream(config_);
1577 if (sending_) {
1578 stream_->Start();
1579 }
1580}
1581
1582WebRtcVideoChannel2::VideoCodecSettings::VideoCodecSettings()
1583 : rtx_payload_type(-1) {}
1584
1585std::vector<WebRtcVideoChannel2::VideoCodecSettings>
1586WebRtcVideoChannel2::MapCodecs(const std::vector<VideoCodec>& codecs) {
1587 assert(!codecs.empty());
1588
1589 std::vector<VideoCodecSettings> video_codecs;
1590 std::map<int, bool> payload_used;
1591 std::map<int, int> rtx_mapping; // video payload type -> rtx payload type.
1592
1593 webrtc::FecConfig fec_settings;
1594
1595 for (size_t i = 0; i < codecs.size(); ++i) {
1596 const VideoCodec& in_codec = codecs[i];
1597 int payload_type = in_codec.id;
1598
1599 if (payload_used[payload_type]) {
1600 LOG(LS_ERROR) << "Payload type already registered: "
1601 << in_codec.ToString();
1602 return std::vector<VideoCodecSettings>();
1603 }
1604 payload_used[payload_type] = true;
1605
1606 switch (in_codec.GetCodecType()) {
1607 case VideoCodec::CODEC_RED: {
1608 // RED payload type, should not have duplicates.
1609 assert(fec_settings.red_payload_type == -1);
1610 fec_settings.red_payload_type = in_codec.id;
1611 continue;
1612 }
1613
1614 case VideoCodec::CODEC_ULPFEC: {
1615 // ULPFEC payload type, should not have duplicates.
1616 assert(fec_settings.ulpfec_payload_type == -1);
1617 fec_settings.ulpfec_payload_type = in_codec.id;
1618 continue;
1619 }
1620
1621 case VideoCodec::CODEC_RTX: {
1622 int associated_payload_type;
1623 if (!in_codec.GetParam(kCodecParamAssociatedPayloadType,
1624 &associated_payload_type)) {
1625 LOG(LS_ERROR) << "RTX codec without associated payload type: "
1626 << in_codec.ToString();
1627 return std::vector<VideoCodecSettings>();
1628 }
1629 rtx_mapping[associated_payload_type] = in_codec.id;
1630 continue;
1631 }
1632
1633 case VideoCodec::CODEC_VIDEO:
1634 break;
1635 }
1636
1637 video_codecs.push_back(VideoCodecSettings());
1638 video_codecs.back().codec = in_codec;
1639 }
1640
1641 // One of these codecs should have been a video codec. Only having FEC
1642 // parameters into this code is a logic error.
1643 assert(!video_codecs.empty());
1644
1645 // TODO(pbos): Write tests that figure out that I have not verified that RTX
1646 // codecs aren't mapped to bogus payloads.
1647 for (size_t i = 0; i < video_codecs.size(); ++i) {
1648 video_codecs[i].fec = fec_settings;
1649 if (rtx_mapping[video_codecs[i].codec.id] != 0) {
1650 video_codecs[i].rtx_payload_type = rtx_mapping[video_codecs[i].codec.id];
1651 }
1652 }
1653
1654 return video_codecs;
1655}
1656
1657std::vector<WebRtcVideoChannel2::VideoCodecSettings>
1658WebRtcVideoChannel2::FilterSupportedCodecs(
1659 const std::vector<WebRtcVideoChannel2::VideoCodecSettings>& mapped_codecs) {
1660 std::vector<VideoCodecSettings> supported_codecs;
1661 for (size_t i = 0; i < mapped_codecs.size(); ++i) {
1662 if (encoder_factory_->SupportsCodec(mapped_codecs[i].codec)) {
1663 supported_codecs.push_back(mapped_codecs[i]);
1664 }
1665 }
1666 return supported_codecs;
1667}
1668
1669} // namespace cricket
1670
1671#endif // HAVE_WEBRTC_VIDEO