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