blob: 6ee07a32fd934d83fda0b7025d00d2e0c9c0cd74 [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
buildbot@webrtc.orgd41eaeb2014-06-12 07:13:26 +0000198std::vector<webrtc::VideoStream> WebRtcVideoEncoderFactory2::CreateVideoStreams(
199 const VideoCodec& codec,
200 const VideoOptions& options,
201 size_t num_streams) {
202 assert(SupportsCodec(codec));
203 if (num_streams != 1) {
204 LOG(LS_ERROR) << "Unsupported number of streams: " << num_streams;
205 return std::vector<webrtc::VideoStream>();
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +0000206 }
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000207
buildbot@webrtc.orgd41eaeb2014-06-12 07:13:26 +0000208 webrtc::VideoStream stream;
209 stream.width = codec.width;
210 stream.height = codec.height;
211 stream.max_framerate =
212 codec.framerate != 0 ? codec.framerate : kDefaultFramerate;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000213
buildbot@webrtc.orgd41eaeb2014-06-12 07:13:26 +0000214 int min_bitrate = kMinVideoBitrate;
215 codec.GetParam(kCodecParamMinBitrate, &min_bitrate);
216 int max_bitrate = kMaxVideoBitrate;
217 codec.GetParam(kCodecParamMaxBitrate, &max_bitrate);
218 stream.min_bitrate_bps = min_bitrate * 1000;
219 stream.target_bitrate_bps = stream.max_bitrate_bps = max_bitrate * 1000;
220
221 int max_qp = 56;
222 codec.GetParam(kCodecParamMaxQuantization, &max_qp);
223 stream.max_qp = max_qp;
224 std::vector<webrtc::VideoStream> streams;
225 streams.push_back(stream);
226 return streams;
227}
228
229webrtc::VideoEncoder* WebRtcVideoEncoderFactory2::CreateVideoEncoder(
230 const VideoCodec& codec,
231 const VideoOptions& options) {
232 assert(SupportsCodec(codec));
233 return webrtc::VP8Encoder::Create();
234}
235
236bool WebRtcVideoEncoderFactory2::SupportsCodec(const VideoCodec& codec) {
237 return _stricmp(codec.name.c_str(), kVp8PayloadName) == 0;
238}
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000239
240WebRtcVideoEngine2::WebRtcVideoEngine2() {
241 // Construct without a factory or voice engine.
242 Construct(NULL, NULL, new talk_base::CpuMonitor(NULL));
243}
244
245WebRtcVideoEngine2::WebRtcVideoEngine2(
246 WebRtcVideoChannelFactory* channel_factory) {
247 // Construct without a voice engine.
248 Construct(channel_factory, NULL, new talk_base::CpuMonitor(NULL));
249}
250
251void WebRtcVideoEngine2::Construct(WebRtcVideoChannelFactory* channel_factory,
252 WebRtcVoiceEngine* voice_engine,
253 talk_base::CpuMonitor* cpu_monitor) {
254 LOG(LS_INFO) << "WebRtcVideoEngine2::WebRtcVideoEngine2";
255 worker_thread_ = NULL;
256 voice_engine_ = voice_engine;
257 initialized_ = false;
258 capture_started_ = false;
259 cpu_monitor_.reset(cpu_monitor);
260 channel_factory_ = channel_factory;
261
262 video_codecs_ = DefaultVideoCodecs();
263 default_codec_format_ = VideoFormat(kDefaultVideoFormat);
264}
265
266WebRtcVideoEngine2::~WebRtcVideoEngine2() {
267 LOG(LS_INFO) << "WebRtcVideoEngine2::~WebRtcVideoEngine2";
268
269 if (initialized_) {
270 Terminate();
271 }
272}
273
274bool WebRtcVideoEngine2::Init(talk_base::Thread* worker_thread) {
275 LOG(LS_INFO) << "WebRtcVideoEngine2::Init";
276 worker_thread_ = worker_thread;
277 ASSERT(worker_thread_ != NULL);
278
279 cpu_monitor_->set_thread(worker_thread_);
280 if (!cpu_monitor_->Start(kCpuMonitorPeriodMs)) {
281 LOG(LS_ERROR) << "Failed to start CPU monitor.";
282 cpu_monitor_.reset();
283 }
284
285 initialized_ = true;
286 return true;
287}
288
289void WebRtcVideoEngine2::Terminate() {
290 LOG(LS_INFO) << "WebRtcVideoEngine2::Terminate";
291
292 cpu_monitor_->Stop();
293
294 initialized_ = false;
295}
296
297int WebRtcVideoEngine2::GetCapabilities() { return VIDEO_RECV | VIDEO_SEND; }
298
299bool WebRtcVideoEngine2::SetOptions(const VideoOptions& options) {
300 // TODO(pbos): Do we need this? This is a no-op in the existing
301 // WebRtcVideoEngine implementation.
302 LOG(LS_VERBOSE) << "SetOptions: " << options.ToString();
303 // options_ = options;
304 return true;
305}
306
307bool WebRtcVideoEngine2::SetDefaultEncoderConfig(
308 const VideoEncoderConfig& config) {
309 // TODO(pbos): Implement. Should be covered by corresponding unit tests.
310 LOG(LS_VERBOSE) << "SetDefaultEncoderConfig()";
311 return true;
312}
313
314VideoEncoderConfig WebRtcVideoEngine2::GetDefaultEncoderConfig() const {
315 return VideoEncoderConfig(DefaultVideoCodec());
316}
317
318WebRtcVideoChannel2* WebRtcVideoEngine2::CreateChannel(
319 VoiceMediaChannel* voice_channel) {
320 LOG(LS_INFO) << "CreateChannel: "
321 << (voice_channel != NULL ? "With" : "Without")
322 << " voice channel.";
323 WebRtcVideoChannel2* channel =
324 channel_factory_ != NULL
325 ? channel_factory_->Create(this, voice_channel)
326 : new WebRtcVideoChannel2(
pbos@webrtc.org0d523ee2014-06-05 09:10:55 +0000327 this, voice_channel, GetVideoEncoderFactory());
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000328 if (!channel->Init()) {
329 delete channel;
330 return NULL;
331 }
332 return channel;
333}
334
335const std::vector<VideoCodec>& WebRtcVideoEngine2::codecs() const {
336 return video_codecs_;
337}
338
339const std::vector<RtpHeaderExtension>&
340WebRtcVideoEngine2::rtp_header_extensions() const {
341 return rtp_header_extensions_;
342}
343
344void WebRtcVideoEngine2::SetLogging(int min_sev, const char* filter) {
345 // TODO(pbos): Set up logging.
346 LOG(LS_VERBOSE) << "SetLogging: " << min_sev << '"' << filter << '"';
347 // if min_sev == -1, we keep the current log level.
348 if (min_sev < 0) {
349 assert(min_sev == -1);
350 return;
351 }
352}
353
354bool WebRtcVideoEngine2::EnableTimedRender() {
355 // TODO(pbos): Figure out whether this can be removed.
356 return true;
357}
358
359bool WebRtcVideoEngine2::SetLocalRenderer(VideoRenderer* renderer) {
360 // TODO(pbos): Implement or remove. Unclear which stream should be rendered
361 // locally even.
362 return true;
363}
364
365// Checks to see whether we comprehend and could receive a particular codec
366bool WebRtcVideoEngine2::FindCodec(const VideoCodec& in) {
367 // TODO(pbos): Probe encoder factory to figure out that the codec is supported
368 // if supported by the encoder factory. Add a corresponding test that fails
369 // with this code (that doesn't ask the factory).
370 for (int i = 0; i < ARRAY_SIZE(kVideoFormats); ++i) {
371 const VideoFormat fmt(kVideoFormats[i]);
372 if ((in.width != 0 || in.height != 0) &&
373 (fmt.width != in.width || fmt.height != in.height)) {
374 continue;
375 }
376 for (size_t j = 0; j < video_codecs_.size(); ++j) {
377 VideoCodec codec(video_codecs_[j].id, video_codecs_[j].name, 0, 0, 0, 0);
378 if (codec.Matches(in)) {
379 return true;
380 }
381 }
382 }
383 return false;
384}
385
386// Tells whether the |requested| codec can be transmitted or not. If it can be
387// transmitted |out| is set with the best settings supported. Aspect ratio will
388// be set as close to |current|'s as possible. If not set |requested|'s
389// dimensions will be used for aspect ratio matching.
390bool WebRtcVideoEngine2::CanSendCodec(const VideoCodec& requested,
391 const VideoCodec& current,
392 VideoCodec* out) {
393 assert(out != NULL);
394 // TODO(pbos): Implement.
395
396 if (requested.width != requested.height &&
397 (requested.height == 0 || requested.width == 0)) {
398 // 0xn and nx0 are invalid resolutions.
399 return false;
400 }
401
402 VideoCodec matching_codec;
403 if (!FindFirstMatchingCodec(video_codecs_, requested, &matching_codec)) {
404 // Codec not supported.
405 return false;
406 }
407
408 // Pick the best quality that is within their and our bounds and has the
409 // correct aspect ratio.
410 VideoFormat format;
411 if (requested.width == 0 && requested.height == 0) {
412 // Special case with resolution 0. The channel should not send frames.
413 } else {
414 int max_width = talk_base::_min(requested.width, matching_codec.width);
415 int max_height = talk_base::_min(requested.height, matching_codec.height);
416 int aspect_width = max_width;
417 int aspect_height = max_height;
418 if (current.width > 0 && current.height > 0) {
419 aspect_width = current.width;
420 aspect_height = current.height;
421 }
422 if (!FindBestVideoFormat(
423 max_width, max_height, aspect_width, aspect_height, &format)) {
424 return false;
425 }
426 }
427
428 out->id = requested.id;
429 out->name = requested.name;
430 out->preference = requested.preference;
431 out->params = requested.params;
432 out->framerate =
433 talk_base::_min(requested.framerate, matching_codec.framerate);
434 out->width = format.width;
435 out->height = format.height;
436 out->params = requested.params;
437 out->feedback_params = requested.feedback_params;
438 return true;
439}
440
441bool WebRtcVideoEngine2::SetVoiceEngine(WebRtcVoiceEngine* voice_engine) {
442 if (initialized_) {
443 LOG(LS_WARNING) << "SetVoiceEngine can not be called after Init";
444 return false;
445 }
446 voice_engine_ = voice_engine;
447 return true;
448}
449
450// Ignore spammy trace messages, mostly from the stats API when we haven't
451// gotten RTCP info yet from the remote side.
452bool WebRtcVideoEngine2::ShouldIgnoreTrace(const std::string& trace) {
453 static const char* const kTracesToIgnore[] = {NULL};
454 for (const char* const* p = kTracesToIgnore; *p; ++p) {
455 if (trace.find(*p) == 0) {
456 return true;
457 }
458 }
459 return false;
460}
461
buildbot@webrtc.orgd41eaeb2014-06-12 07:13:26 +0000462WebRtcVideoEncoderFactory2* WebRtcVideoEngine2::GetVideoEncoderFactory() {
463 return &default_video_encoder_factory_;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000464}
465
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +0000466// Thin map between VideoFrame and an existing webrtc::I420VideoFrame
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000467// to avoid having to copy the rendered VideoFrame prematurely.
468// This implementation is only safe to use in a const context and should never
469// be written to.
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +0000470class WebRtcVideoRenderFrame : public VideoFrame {
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000471 public:
472 explicit WebRtcVideoRenderFrame(const webrtc::I420VideoFrame* frame)
473 : frame_(frame) {}
474
475 virtual bool InitToBlack(int w,
476 int h,
477 size_t pixel_width,
478 size_t pixel_height,
479 int64 elapsed_time,
480 int64 time_stamp) OVERRIDE {
481 UNIMPLEMENTED;
482 return false;
483 }
484
485 virtual bool Reset(uint32 fourcc,
486 int w,
487 int h,
488 int dw,
489 int dh,
490 uint8* sample,
491 size_t sample_size,
492 size_t pixel_width,
493 size_t pixel_height,
494 int64 elapsed_time,
495 int64 time_stamp,
496 int rotation) OVERRIDE {
497 UNIMPLEMENTED;
498 return false;
499 }
500
501 virtual size_t GetWidth() const OVERRIDE {
502 return static_cast<size_t>(frame_->width());
503 }
504 virtual size_t GetHeight() const OVERRIDE {
505 return static_cast<size_t>(frame_->height());
506 }
507
508 virtual const uint8* GetYPlane() const OVERRIDE {
509 return frame_->buffer(webrtc::kYPlane);
510 }
511 virtual const uint8* GetUPlane() const OVERRIDE {
512 return frame_->buffer(webrtc::kUPlane);
513 }
514 virtual const uint8* GetVPlane() const OVERRIDE {
515 return frame_->buffer(webrtc::kVPlane);
516 }
517
518 virtual uint8* GetYPlane() OVERRIDE {
519 UNIMPLEMENTED;
520 return NULL;
521 }
522 virtual uint8* GetUPlane() OVERRIDE {
523 UNIMPLEMENTED;
524 return NULL;
525 }
526 virtual uint8* GetVPlane() OVERRIDE {
527 UNIMPLEMENTED;
528 return NULL;
529 }
530
531 virtual int32 GetYPitch() const OVERRIDE {
532 return frame_->stride(webrtc::kYPlane);
533 }
534 virtual int32 GetUPitch() const OVERRIDE {
535 return frame_->stride(webrtc::kUPlane);
536 }
537 virtual int32 GetVPitch() const OVERRIDE {
538 return frame_->stride(webrtc::kVPlane);
539 }
540
541 virtual void* GetNativeHandle() const OVERRIDE { return NULL; }
542
543 virtual size_t GetPixelWidth() const OVERRIDE { return 1; }
544 virtual size_t GetPixelHeight() const OVERRIDE { return 1; }
545
546 virtual int64 GetElapsedTime() const OVERRIDE {
547 // Convert millisecond render time to ns timestamp.
548 return frame_->render_time_ms() * talk_base::kNumNanosecsPerMillisec;
549 }
550 virtual int64 GetTimeStamp() const OVERRIDE {
551 // Convert 90K rtp timestamp to ns timestamp.
552 return (frame_->timestamp() / 90) * talk_base::kNumNanosecsPerMillisec;
553 }
554 virtual void SetElapsedTime(int64 elapsed_time) OVERRIDE { UNIMPLEMENTED; }
555 virtual void SetTimeStamp(int64 time_stamp) OVERRIDE { UNIMPLEMENTED; }
556
557 virtual int GetRotation() const OVERRIDE {
558 UNIMPLEMENTED;
559 return ROTATION_0;
560 }
561
562 virtual VideoFrame* Copy() const OVERRIDE {
563 UNIMPLEMENTED;
564 return NULL;
565 }
566
567 virtual bool MakeExclusive() OVERRIDE {
568 UNIMPLEMENTED;
569 return false;
570 }
571
572 virtual size_t CopyToBuffer(uint8* buffer, size_t size) const {
573 UNIMPLEMENTED;
574 return 0;
575 }
576
577 // TODO(fbarchard): Refactor into base class and share with LMI
578 virtual size_t ConvertToRgbBuffer(uint32 to_fourcc,
579 uint8* buffer,
580 size_t size,
581 int stride_rgb) const OVERRIDE {
582 size_t width = GetWidth();
583 size_t height = GetHeight();
584 size_t needed = (stride_rgb >= 0 ? stride_rgb : -stride_rgb) * height;
585 if (size < needed) {
586 LOG(LS_WARNING) << "RGB buffer is not large enough";
587 return needed;
588 }
589
590 if (libyuv::ConvertFromI420(GetYPlane(),
591 GetYPitch(),
592 GetUPlane(),
593 GetUPitch(),
594 GetVPlane(),
595 GetVPitch(),
596 buffer,
597 stride_rgb,
598 static_cast<int>(width),
599 static_cast<int>(height),
600 to_fourcc)) {
601 LOG(LS_ERROR) << "RGB type not supported: " << to_fourcc;
602 return 0; // 0 indicates error
603 }
604 return needed;
605 }
606
607 protected:
608 virtual VideoFrame* CreateEmptyFrame(int w,
609 int h,
610 size_t pixel_width,
611 size_t pixel_height,
612 int64 elapsed_time,
613 int64 time_stamp) const OVERRIDE {
614 // TODO(pbos): Remove WebRtcVideoFrame dependency, and have a non-const
615 // version of I420VideoFrame wrapped.
616 WebRtcVideoFrame* frame = new WebRtcVideoFrame();
617 frame->InitToBlack(
618 w, h, pixel_width, pixel_height, elapsed_time, time_stamp);
619 return frame;
620 }
621
622 private:
623 const webrtc::I420VideoFrame* const frame_;
624};
625
626WebRtcVideoRenderer::WebRtcVideoRenderer()
627 : last_width_(-1), last_height_(-1), renderer_(NULL) {}
628
629void WebRtcVideoRenderer::RenderFrame(const webrtc::I420VideoFrame& frame,
630 int time_to_render_ms) {
631 talk_base::CritScope crit(&lock_);
632 if (renderer_ == NULL) {
633 LOG(LS_WARNING) << "VideoReceiveStream not connected to a VideoRenderer.";
634 return;
635 }
636
637 if (frame.width() != last_width_ || frame.height() != last_height_) {
638 SetSize(frame.width(), frame.height());
639 }
640
641 LOG(LS_VERBOSE) << "RenderFrame: (" << frame.width() << "x" << frame.height()
642 << ")";
643
644 const WebRtcVideoRenderFrame render_frame(&frame);
645 renderer_->RenderFrame(&render_frame);
646}
647
648void WebRtcVideoRenderer::SetRenderer(cricket::VideoRenderer* renderer) {
649 talk_base::CritScope crit(&lock_);
650 renderer_ = renderer;
651 if (renderer_ != NULL && last_width_ != -1) {
652 SetSize(last_width_, last_height_);
653 }
654}
655
656VideoRenderer* WebRtcVideoRenderer::GetRenderer() {
657 talk_base::CritScope crit(&lock_);
658 return renderer_;
659}
660
661void WebRtcVideoRenderer::SetSize(int width, int height) {
662 talk_base::CritScope crit(&lock_);
663 if (!renderer_->SetSize(width, height, 0)) {
664 LOG(LS_ERROR) << "Could not set renderer size.";
665 }
666 last_width_ = width;
667 last_height_ = height;
668}
669
670// WebRtcVideoChannel2
671
672WebRtcVideoChannel2::WebRtcVideoChannel2(
673 WebRtcVideoEngine2* engine,
674 VoiceMediaChannel* voice_channel,
675 WebRtcVideoEncoderFactory2* encoder_factory)
676 : encoder_factory_(encoder_factory) {
677 // TODO(pbos): Connect the video and audio with |voice_channel|.
678 webrtc::Call::Config config(this);
679 Construct(webrtc::Call::Create(config), engine);
680}
681
682WebRtcVideoChannel2::WebRtcVideoChannel2(
683 webrtc::Call* call,
684 WebRtcVideoEngine2* engine,
685 WebRtcVideoEncoderFactory2* encoder_factory)
686 : encoder_factory_(encoder_factory) {
687 Construct(call, engine);
688}
689
690void WebRtcVideoChannel2::Construct(webrtc::Call* call,
691 WebRtcVideoEngine2* engine) {
692 rtcp_receiver_report_ssrc_ = kDefaultRtcpReceiverReportSsrc;
693 sending_ = false;
694 call_.reset(call);
695 default_renderer_ = NULL;
696 default_send_ssrc_ = 0;
697 default_recv_ssrc_ = 0;
698}
699
700WebRtcVideoChannel2::~WebRtcVideoChannel2() {
701 for (std::map<uint32, WebRtcVideoSendStream*>::iterator it =
702 send_streams_.begin();
703 it != send_streams_.end();
704 ++it) {
705 delete it->second;
706 }
707
708 for (std::map<uint32, webrtc::VideoReceiveStream*>::iterator it =
709 receive_streams_.begin();
710 it != receive_streams_.end();
711 ++it) {
712 assert(it->second != NULL);
713 call_->DestroyVideoReceiveStream(it->second);
714 }
715
716 for (std::map<uint32, WebRtcVideoRenderer*>::iterator it = renderers_.begin();
717 it != renderers_.end();
718 ++it) {
719 assert(it->second != NULL);
720 delete it->second;
721 }
722}
723
724bool WebRtcVideoChannel2::Init() { return true; }
725
726namespace {
727
728static bool ValidateCodecFormats(const std::vector<VideoCodec>& codecs) {
729 for (size_t i = 0; i < codecs.size(); ++i) {
730 if (!codecs[i].ValidateCodecFormat()) {
731 return false;
732 }
733 }
734 return true;
735}
736
737static std::string CodecVectorToString(const std::vector<VideoCodec>& codecs) {
738 std::stringstream out;
739 out << '{';
740 for (size_t i = 0; i < codecs.size(); ++i) {
741 out << codecs[i].ToString();
742 if (i != codecs.size() - 1) {
743 out << ", ";
744 }
745 }
746 out << '}';
747 return out.str();
748}
749
750} // namespace
751
752bool WebRtcVideoChannel2::SetRecvCodecs(const std::vector<VideoCodec>& codecs) {
753 // TODO(pbos): Must these receive codecs propagate to existing receive
754 // streams?
755 LOG(LS_INFO) << "SetRecvCodecs: " << CodecVectorToString(codecs);
756 if (!ValidateCodecFormats(codecs)) {
757 return false;
758 }
759
760 const std::vector<VideoCodecSettings> mapped_codecs = MapCodecs(codecs);
761 if (mapped_codecs.empty()) {
762 LOG(LS_ERROR) << "SetRecvCodecs called without video codec payloads.";
763 return false;
764 }
765
766 // TODO(pbos): Add a decoder factory which controls supported codecs.
767 // Blocked on webrtc:2854.
768 for (size_t i = 0; i < mapped_codecs.size(); ++i) {
769 if (_stricmp(mapped_codecs[i].codec.name.c_str(), kVp8PayloadName) != 0) {
770 LOG(LS_ERROR) << "SetRecvCodecs called with unsupported codec: '"
771 << mapped_codecs[i].codec.name << "'";
772 return false;
773 }
774 }
775
776 recv_codecs_ = mapped_codecs;
777 return true;
778}
779
780bool WebRtcVideoChannel2::SetSendCodecs(const std::vector<VideoCodec>& codecs) {
781 LOG(LS_INFO) << "SetSendCodecs: " << CodecVectorToString(codecs);
782 if (!ValidateCodecFormats(codecs)) {
783 return false;
784 }
785
786 const std::vector<VideoCodecSettings> supported_codecs =
787 FilterSupportedCodecs(MapCodecs(codecs));
788
789 if (supported_codecs.empty()) {
790 LOG(LS_ERROR) << "No video codecs supported by encoder factory.";
791 return false;
792 }
793
794 send_codec_.Set(supported_codecs.front());
795 LOG(LS_INFO) << "Using codec: " << supported_codecs.front().codec.ToString();
796
797 SetCodecForAllSendStreams(supported_codecs.front());
798
799 return true;
800}
801
802bool WebRtcVideoChannel2::GetSendCodec(VideoCodec* codec) {
803 VideoCodecSettings codec_settings;
804 if (!send_codec_.Get(&codec_settings)) {
805 LOG(LS_VERBOSE) << "GetSendCodec: No send codec set.";
806 return false;
807 }
808 *codec = codec_settings.codec;
809 return true;
810}
811
812bool WebRtcVideoChannel2::SetSendStreamFormat(uint32 ssrc,
813 const VideoFormat& format) {
814 LOG(LS_VERBOSE) << "SetSendStreamFormat:" << ssrc << " -> "
815 << format.ToString();
816 if (send_streams_.find(ssrc) == send_streams_.end()) {
817 return false;
818 }
819 return send_streams_[ssrc]->SetVideoFormat(format);
820}
821
822bool WebRtcVideoChannel2::SetRender(bool render) {
823 // TODO(pbos): Implement. Or refactor away as it shouldn't be needed.
824 LOG(LS_VERBOSE) << "SetRender: " << (render ? "true" : "false");
825 return true;
826}
827
828bool WebRtcVideoChannel2::SetSend(bool send) {
829 LOG(LS_VERBOSE) << "SetSend: " << (send ? "true" : "false");
830 if (send && !send_codec_.IsSet()) {
831 LOG(LS_ERROR) << "SetSend(true) called before setting codec.";
832 return false;
833 }
834 if (send) {
835 StartAllSendStreams();
836 } else {
837 StopAllSendStreams();
838 }
839 sending_ = send;
840 return true;
841}
842
843static bool ConfigureSendSsrcs(webrtc::VideoSendStream::Config* config,
844 const StreamParams& sp) {
845 if (!sp.has_ssrc_groups()) {
846 config->rtp.ssrcs = sp.ssrcs;
847 return true;
848 }
849
850 if (sp.get_ssrc_group(kFecSsrcGroupSemantics) != NULL) {
851 LOG(LS_ERROR) << "Standalone FEC SSRCs not supported.";
852 return false;
853 }
854
855 const SsrcGroup* sim_group = sp.get_ssrc_group(kSimSsrcGroupSemantics);
856 if (sim_group == NULL) {
857 LOG(LS_ERROR) << "Grouped StreamParams without regular SSRC group: "
858 << sp.ToString();
859 return false;
860 }
861
862 // Map RTX SSRCs.
863 std::vector<uint32_t> rtx_ssrcs;
864 for (size_t i = 0; i < sim_group->ssrcs.size(); ++i) {
865 uint32_t rtx_ssrc;
866 if (!sp.GetFidSsrc(sim_group->ssrcs[i], &rtx_ssrc)) {
867 continue;
868 }
869 rtx_ssrcs.push_back(rtx_ssrc);
870 }
871 if (!rtx_ssrcs.empty() && sim_group->ssrcs.size() != rtx_ssrcs.size()) {
872 LOG(LS_ERROR)
873 << "RTX SSRCs exist, but don't cover all SSRCs (unsupported): "
874 << sp.ToString();
875 return false;
876 }
877 config->rtp.rtx.ssrcs = rtx_ssrcs;
878 config->rtp.ssrcs = sim_group->ssrcs;
879 return true;
880}
881
882bool WebRtcVideoChannel2::AddSendStream(const StreamParams& sp) {
883 LOG(LS_INFO) << "AddSendStream: " << sp.ToString();
884 if (sp.ssrcs.empty()) {
885 LOG(LS_ERROR) << "No SSRCs in stream parameters.";
886 return false;
887 }
888
889 uint32 ssrc = sp.first_ssrc();
890 assert(ssrc != 0);
891 // TODO(pbos): Make sure none of sp.ssrcs are used, not just the identifying
892 // ssrc.
893 if (send_streams_.find(ssrc) != send_streams_.end()) {
894 LOG(LS_ERROR) << "Send stream with ssrc '" << ssrc << "' already exists.";
895 return false;
896 }
897
898 webrtc::VideoSendStream::Config config = call_->GetDefaultSendConfig();
899
900 if (!ConfigureSendSsrcs(&config, sp)) {
901 return false;
902 }
903
904 VideoCodecSettings codec_settings;
905 if (!send_codec_.Get(&codec_settings)) {
906 // TODO(pbos): Set up a temporary fake encoder for VideoSendStream instead
907 // of setting default codecs not to break CreateEncoderSettings.
908 SetSendCodecs(DefaultVideoCodecs());
909 assert(send_codec_.IsSet());
910 send_codec_.Get(&codec_settings);
911 // This is only to bring up defaults to make VideoSendStream setup easier
912 // and avoid complexity. We still don't want to allow sending with the
913 // default codec.
914 send_codec_.Clear();
915 }
916
917 // CreateEncoderSettings will allocate a suitable VideoEncoder instance
918 // matching current settings.
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +0000919 std::vector<webrtc::VideoStream> video_streams =
920 encoder_factory_->CreateVideoStreams(
921 codec_settings.codec, options_, config.rtp.ssrcs.size());
922 if (video_streams.empty()) {
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000923 return false;
924 }
925
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +0000926 config.encoder_settings.encoder =
927 encoder_factory_->CreateVideoEncoder(codec_settings.codec, options_);
928 config.encoder_settings.payload_name = codec_settings.codec.name;
929 config.encoder_settings.payload_type = codec_settings.codec.id;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000930 config.rtp.c_name = sp.cname;
931 config.rtp.fec = codec_settings.fec;
932 if (!config.rtp.rtx.ssrcs.empty()) {
933 config.rtp.rtx.payload_type = codec_settings.rtx_payload_type;
934 }
935
936 config.rtp.nack.rtp_history_ms = kNackHistoryMs;
937 config.rtp.max_packet_size = kVideoMtu;
938
939 WebRtcVideoSendStream* stream =
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +0000940 new WebRtcVideoSendStream(call_.get(),
941 config,
942 options_,
943 codec_settings.codec,
944 video_streams,
945 encoder_factory_);
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +0000946 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
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001342WebRtcVideoChannel2::WebRtcVideoSendStream::VideoSendStreamParameters::
1343 VideoSendStreamParameters(
1344 const webrtc::VideoSendStream::Config& config,
1345 const VideoOptions& options,
1346 const VideoCodec& codec,
1347 const std::vector<webrtc::VideoStream>& video_streams)
1348 : config(config),
1349 options(options),
1350 codec(codec),
1351 video_streams(video_streams) {
1352}
1353
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001354WebRtcVideoChannel2::WebRtcVideoSendStream::WebRtcVideoSendStream(
1355 webrtc::Call* call,
1356 const webrtc::VideoSendStream::Config& config,
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001357 const VideoOptions& options,
1358 const VideoCodec& codec,
1359 const std::vector<webrtc::VideoStream>& video_streams,
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001360 WebRtcVideoEncoderFactory2* encoder_factory)
1361 : call_(call),
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001362 parameters_(config, options, codec, video_streams),
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001363 encoder_factory_(encoder_factory),
1364 capturer_(NULL),
1365 stream_(NULL),
1366 sending_(false),
1367 muted_(false),
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001368 format_(static_cast<int>(video_streams.back().height),
1369 static_cast<int>(video_streams.back().width),
1370 VideoFormat::FpsToInterval(video_streams.back().max_framerate),
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001371 FOURCC_I420) {
1372 RecreateWebRtcStream();
1373}
1374
1375WebRtcVideoChannel2::WebRtcVideoSendStream::~WebRtcVideoSendStream() {
1376 DisconnectCapturer();
1377 call_->DestroyVideoSendStream(stream_);
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001378 delete parameters_.config.encoder_settings.encoder;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001379}
1380
1381static void SetWebRtcFrameToBlack(webrtc::I420VideoFrame* video_frame) {
1382 assert(video_frame != NULL);
1383 memset(video_frame->buffer(webrtc::kYPlane),
1384 16,
1385 video_frame->allocated_size(webrtc::kYPlane));
1386 memset(video_frame->buffer(webrtc::kUPlane),
1387 128,
1388 video_frame->allocated_size(webrtc::kUPlane));
1389 memset(video_frame->buffer(webrtc::kVPlane),
1390 128,
1391 video_frame->allocated_size(webrtc::kVPlane));
1392}
1393
1394static void CreateBlackFrame(webrtc::I420VideoFrame* video_frame,
1395 int width,
1396 int height) {
1397 video_frame->CreateEmptyFrame(
1398 width, height, width, (width + 1) / 2, (width + 1) / 2);
1399 SetWebRtcFrameToBlack(video_frame);
1400}
1401
1402static void ConvertToI420VideoFrame(const VideoFrame& frame,
1403 webrtc::I420VideoFrame* i420_frame) {
1404 i420_frame->CreateFrame(
1405 static_cast<int>(frame.GetYPitch() * frame.GetHeight()),
1406 frame.GetYPlane(),
1407 static_cast<int>(frame.GetUPitch() * ((frame.GetHeight() + 1) / 2)),
1408 frame.GetUPlane(),
1409 static_cast<int>(frame.GetVPitch() * ((frame.GetHeight() + 1) / 2)),
1410 frame.GetVPlane(),
1411 static_cast<int>(frame.GetWidth()),
1412 static_cast<int>(frame.GetHeight()),
1413 static_cast<int>(frame.GetYPitch()),
1414 static_cast<int>(frame.GetUPitch()),
1415 static_cast<int>(frame.GetVPitch()));
1416}
1417
1418void WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame(
1419 VideoCapturer* capturer,
1420 const VideoFrame* frame) {
1421 LOG(LS_VERBOSE) << "InputFrame: " << frame->GetWidth() << "x"
1422 << frame->GetHeight();
1423 bool is_screencast = capturer->IsScreencast();
1424 // Lock before copying, can be called concurrently when swapping input source.
1425 talk_base::CritScope frame_cs(&frame_lock_);
1426 if (!muted_) {
1427 ConvertToI420VideoFrame(*frame, &video_frame_);
1428 } else {
1429 // Create a tiny black frame to transmit instead.
1430 CreateBlackFrame(&video_frame_, 1, 1);
1431 is_screencast = false;
1432 }
1433 talk_base::CritScope cs(&lock_);
1434 if (format_.width == 0) { // Dropping frames.
1435 assert(format_.height == 0);
1436 LOG(LS_VERBOSE) << "VideoFormat 0x0 set, Dropping frame.";
1437 return;
1438 }
1439 // Reconfigure codec if necessary.
1440 if (is_screencast) {
1441 SetDimensions(video_frame_.width(), video_frame_.height());
1442 }
1443 LOG(LS_VERBOSE) << "SwapFrame: " << video_frame_.width() << "x"
1444 << video_frame_.height() << " -> (codec) "
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001445 << parameters_.video_streams.back().width << "x"
1446 << parameters_.video_streams.back().height;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001447 stream_->Input()->SwapFrame(&video_frame_);
1448}
1449
1450bool WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer(
1451 VideoCapturer* capturer) {
1452 if (!DisconnectCapturer() && capturer == NULL) {
1453 return false;
1454 }
1455
1456 {
1457 talk_base::CritScope cs(&lock_);
1458
1459 if (capturer == NULL) {
1460 LOG(LS_VERBOSE) << "Disabling capturer, sending black frame.";
1461 webrtc::I420VideoFrame black_frame;
1462
1463 int width = format_.width;
1464 int height = format_.height;
1465 int half_width = (width + 1) / 2;
1466 black_frame.CreateEmptyFrame(
1467 width, height, width, half_width, half_width);
1468 SetWebRtcFrameToBlack(&black_frame);
1469 SetDimensions(width, height);
1470 stream_->Input()->SwapFrame(&black_frame);
1471
1472 capturer_ = NULL;
1473 return true;
1474 }
1475
1476 capturer_ = capturer;
1477 }
1478 // Lock cannot be held while connecting the capturer to prevent lock-order
1479 // violations.
1480 capturer->SignalVideoFrame.connect(this, &WebRtcVideoSendStream::InputFrame);
1481 return true;
1482}
1483
1484bool WebRtcVideoChannel2::WebRtcVideoSendStream::SetVideoFormat(
1485 const VideoFormat& format) {
1486 if ((format.width == 0 || format.height == 0) &&
1487 format.width != format.height) {
1488 LOG(LS_ERROR) << "Can't set VideoFormat, width or height is zero (but not "
1489 "both, 0x0 drops frames).";
1490 return false;
1491 }
1492
1493 talk_base::CritScope cs(&lock_);
1494 if (format.width == 0 && format.height == 0) {
1495 LOG(LS_INFO)
1496 << "0x0 resolution selected. Captured frames will be dropped for ssrc: "
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001497 << parameters_.config.rtp.ssrcs[0] << ".";
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001498 } else {
1499 // TODO(pbos): Fix me, this only affects the last stream!
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001500 parameters_.video_streams.back().max_framerate =
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001501 VideoFormat::IntervalToFps(format.interval);
1502 SetDimensions(format.width, format.height);
1503 }
1504
1505 format_ = format;
1506 return true;
1507}
1508
1509bool WebRtcVideoChannel2::WebRtcVideoSendStream::MuteStream(bool mute) {
1510 talk_base::CritScope cs(&lock_);
1511 bool was_muted = muted_;
1512 muted_ = mute;
1513 return was_muted != mute;
1514}
1515
1516bool WebRtcVideoChannel2::WebRtcVideoSendStream::DisconnectCapturer() {
1517 talk_base::CritScope cs(&lock_);
1518 if (capturer_ == NULL) {
1519 return false;
1520 }
1521 capturer_->SignalVideoFrame.disconnect(this);
1522 capturer_ = NULL;
1523 return true;
1524}
1525
1526void WebRtcVideoChannel2::WebRtcVideoSendStream::SetCodec(
1527 const VideoOptions& options,
1528 const VideoCodecSettings& codec) {
1529 talk_base::CritScope cs(&lock_);
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001530
1531 std::vector<webrtc::VideoStream> video_streams =
1532 encoder_factory_->CreateVideoStreams(
1533 codec.codec, options, parameters_.video_streams.size());
1534 if (video_streams.empty()) {
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001535 return;
1536 }
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001537 parameters_.video_streams = video_streams;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001538 format_ = VideoFormat(codec.codec.width,
1539 codec.codec.height,
1540 VideoFormat::FpsToInterval(30),
1541 FOURCC_I420);
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001542
1543 webrtc::VideoEncoder* old_encoder =
1544 parameters_.config.encoder_settings.encoder;
1545 parameters_.config.encoder_settings.encoder =
1546 encoder_factory_->CreateVideoEncoder(codec.codec, options);
1547 parameters_.config.rtp.fec = codec.fec;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001548 // TODO(pbos): Should changing RTX payload type be allowed?
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001549 parameters_.codec = codec.codec;
1550 parameters_.options = options;
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001551 RecreateWebRtcStream();
1552 delete old_encoder;
1553}
1554
1555void WebRtcVideoChannel2::WebRtcVideoSendStream::SetDimensions(int width,
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001556 int height) {
1557 assert(!parameters_.video_streams.empty());
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001558 LOG(LS_VERBOSE) << "SetDimensions: " << width << "x" << height;
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001559 if (parameters_.video_streams.back().width == width &&
1560 parameters_.video_streams.back().height == height) {
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001561 return;
1562 }
1563
1564 // TODO(pbos): Fix me, this only affects the last stream!
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001565 parameters_.video_streams.back().width = width;
1566 parameters_.video_streams.back().height = height;
1567
1568 // TODO(pbos): Wire up encoder_parameters, webrtc:3424.
1569 if (!stream_->ReconfigureVideoEncoder(parameters_.video_streams, NULL)) {
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001570 LOG(LS_WARNING) << "Failed to reconfigure video encoder for dimensions: "
1571 << width << "x" << height;
1572 return;
1573 }
1574}
1575
1576void WebRtcVideoChannel2::WebRtcVideoSendStream::Start() {
1577 talk_base::CritScope cs(&lock_);
1578 stream_->Start();
1579 sending_ = true;
1580}
1581
1582void WebRtcVideoChannel2::WebRtcVideoSendStream::Stop() {
1583 talk_base::CritScope cs(&lock_);
1584 stream_->Stop();
1585 sending_ = false;
1586}
1587
1588void WebRtcVideoChannel2::WebRtcVideoSendStream::RecreateWebRtcStream() {
1589 if (stream_ != NULL) {
1590 call_->DestroyVideoSendStream(stream_);
1591 }
pbos@webrtc.org6ae48c62014-06-06 10:49:19 +00001592
1593 // TODO(pbos): Wire up encoder_parameters, webrtc:3424.
1594 stream_ = call_->CreateVideoSendStream(
1595 parameters_.config, parameters_.video_streams, NULL);
pbos@webrtc.orgb5a22b12014-05-13 11:07:01 +00001596 if (sending_) {
1597 stream_->Start();
1598 }
1599}
1600
1601WebRtcVideoChannel2::VideoCodecSettings::VideoCodecSettings()
1602 : rtx_payload_type(-1) {}
1603
1604std::vector<WebRtcVideoChannel2::VideoCodecSettings>
1605WebRtcVideoChannel2::MapCodecs(const std::vector<VideoCodec>& codecs) {
1606 assert(!codecs.empty());
1607
1608 std::vector<VideoCodecSettings> video_codecs;
1609 std::map<int, bool> payload_used;
1610 std::map<int, int> rtx_mapping; // video payload type -> rtx payload type.
1611
1612 webrtc::FecConfig fec_settings;
1613
1614 for (size_t i = 0; i < codecs.size(); ++i) {
1615 const VideoCodec& in_codec = codecs[i];
1616 int payload_type = in_codec.id;
1617
1618 if (payload_used[payload_type]) {
1619 LOG(LS_ERROR) << "Payload type already registered: "
1620 << in_codec.ToString();
1621 return std::vector<VideoCodecSettings>();
1622 }
1623 payload_used[payload_type] = true;
1624
1625 switch (in_codec.GetCodecType()) {
1626 case VideoCodec::CODEC_RED: {
1627 // RED payload type, should not have duplicates.
1628 assert(fec_settings.red_payload_type == -1);
1629 fec_settings.red_payload_type = in_codec.id;
1630 continue;
1631 }
1632
1633 case VideoCodec::CODEC_ULPFEC: {
1634 // ULPFEC payload type, should not have duplicates.
1635 assert(fec_settings.ulpfec_payload_type == -1);
1636 fec_settings.ulpfec_payload_type = in_codec.id;
1637 continue;
1638 }
1639
1640 case VideoCodec::CODEC_RTX: {
1641 int associated_payload_type;
1642 if (!in_codec.GetParam(kCodecParamAssociatedPayloadType,
1643 &associated_payload_type)) {
1644 LOG(LS_ERROR) << "RTX codec without associated payload type: "
1645 << in_codec.ToString();
1646 return std::vector<VideoCodecSettings>();
1647 }
1648 rtx_mapping[associated_payload_type] = in_codec.id;
1649 continue;
1650 }
1651
1652 case VideoCodec::CODEC_VIDEO:
1653 break;
1654 }
1655
1656 video_codecs.push_back(VideoCodecSettings());
1657 video_codecs.back().codec = in_codec;
1658 }
1659
1660 // One of these codecs should have been a video codec. Only having FEC
1661 // parameters into this code is a logic error.
1662 assert(!video_codecs.empty());
1663
1664 // TODO(pbos): Write tests that figure out that I have not verified that RTX
1665 // codecs aren't mapped to bogus payloads.
1666 for (size_t i = 0; i < video_codecs.size(); ++i) {
1667 video_codecs[i].fec = fec_settings;
1668 if (rtx_mapping[video_codecs[i].codec.id] != 0) {
1669 video_codecs[i].rtx_payload_type = rtx_mapping[video_codecs[i].codec.id];
1670 }
1671 }
1672
1673 return video_codecs;
1674}
1675
1676std::vector<WebRtcVideoChannel2::VideoCodecSettings>
1677WebRtcVideoChannel2::FilterSupportedCodecs(
1678 const std::vector<WebRtcVideoChannel2::VideoCodecSettings>& mapped_codecs) {
1679 std::vector<VideoCodecSettings> supported_codecs;
1680 for (size_t i = 0; i < mapped_codecs.size(); ++i) {
1681 if (encoder_factory_->SupportsCodec(mapped_codecs[i].codec)) {
1682 supported_codecs.push_back(mapped_codecs[i]);
1683 }
1684 }
1685 return supported_codecs;
1686}
1687
1688} // namespace cricket
1689
1690#endif // HAVE_WEBRTC_VIDEO