| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "content/renderer/media/video_track_recorder.h" |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/logging.h" |
| 9 #include "base/threading/thread.h" |
| 10 #include "base/time/time.h" |
| 11 #include "base/trace_event/trace_event.h" |
| 12 #include "content/child/child_process.h" |
| 13 #include "media/base/bind_to_current_loop.h" |
| 14 #include "media/base/video_frame.h" |
| 15 |
| 16 extern "C" { |
| 17 // VPX_CODEC_DISABLE_COMPAT excludes parts of the libvpx API that provide |
| 18 // backwards compatibility for legacy applications using the library. |
| 19 #define VPX_CODEC_DISABLE_COMPAT 1 |
| 20 #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" |
| 21 #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" |
| 22 } |
| 23 |
| 24 using media::VideoFrame; |
| 25 using media::VideoFrameMetadata; |
| 26 |
| 27 namespace content { |
| 28 |
| 29 namespace { |
| 30 |
| 31 const vpx_codec_flags_t kNoFlags = 0; |
| 32 |
| 33 static double GetFrameRate(const scoped_refptr<VideoFrame>& video_frame) { |
| 34 double frame_rate = 0.0f; |
| 35 base::IgnoreResult(video_frame->metadata()->GetDouble( |
| 36 VideoFrameMetadata::FRAME_RATE, &frame_rate)); |
| 37 return frame_rate; |
| 38 } |
| 39 |
| 40 } // anonymous namespace |
| 41 |
| 42 // Inner class encapsulating all libvpx interactions and the encoding+delivery |
| 43 // of received frames. This class is: |
| 44 // - created and destroyed on its parent's thread (usually the main render |
| 45 // thread), |
| 46 // - receives VideoFrames and Run()s the callbacks on another thread (supposedly |
| 47 // the render IO thread), which is cached on first frame arrival, |
| 48 // - uses an internal |encoding_thread_| for libvpx interactions, notably for |
| 49 // encoding (which might take some time). |
| 50 // Only VP8 is supported for the time being. |
| 51 class VideoTrackRecorder::VpxEncoder |
| 52 : public base::RefCountedThreadSafe<VpxEncoder> { |
| 53 public: |
| 54 VpxEncoder(const OnFirstFrameCB& on_first_frame_callback, |
| 55 const OnEncodedVideoCB& on_encoded_video_callback); |
| 56 |
| 57 void StartFrameEncode(const scoped_refptr<VideoFrame>& frame, |
| 58 const base::TimeTicks& capture_timestamp); |
| 59 |
| 60 private: |
| 61 friend class base::RefCountedThreadSafe<VpxEncoder>; |
| 62 virtual ~VpxEncoder(); |
| 63 |
| 64 void EncodeOnEncodingThread(const scoped_refptr<VideoFrame>& frame, |
| 65 const base::TimeTicks& capture_timestamp); |
| 66 |
| 67 void OnFrameEncodeCompleted(scoped_ptr<std::string> data, |
| 68 base::TimeDelta timestamp, |
| 69 bool keyframe); |
| 70 |
| 71 void ConfigureVp8Encoding(const gfx::Size& size); |
| 72 |
| 73 // Returns true if |codec_config_| has been filled in at least once. |
| 74 bool IsInitialized() const; |
| 75 |
| 76 // Estimate the frame duration from |frame| and |last_frame_timestamp_|. |
| 77 base::TimeDelta CalculateFrameDuration( |
| 78 const scoped_refptr<VideoFrame>& frame); |
| 79 |
| 80 // Used to check that we are destroyed on the same thread we were created. |
| 81 base::ThreadChecker main_render_thread_checker_; |
| 82 |
| 83 // Task runner where frames to encode and reply callbacks must happen. |
| 84 scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner_; |
| 85 |
| 86 // Used to ping |on_first_frame_callback_|. Used on IO thread only. |
| 87 bool first_frame_received_; |
| 88 // Written once on IO thread and used (read) from capture thread. |
| 89 uint64_t track_index_; |
| 90 // Callbacks that should be exercised on IO thread. |
| 91 const OnFirstFrameCB on_first_frame_callback_; |
| 92 const OnEncodedVideoCB on_encoded_video_callback_; |
| 93 |
| 94 // Thread for encoding. Active as long as VpxEncoder exists. All variables |
| 95 // below this are used in this thread. |
| 96 base::Thread encoding_thread_; |
| 97 // VP8 internal objects: configuration, encoder and Vpx Image wrapper. |
| 98 vpx_codec_enc_cfg_t codec_config_; |
| 99 vpx_codec_ctx_t encoder_; |
| 100 // Origin of times for frame timestamps. |
| 101 base::TimeTicks first_frame_timestamp_; |
| 102 // The |VideoFrame::timestamp()| of the last encoded frame. This is used to |
| 103 // predict the duration of the next frame. |
| 104 base::TimeDelta last_frame_timestamp_; |
| 105 }; |
| 106 |
| 107 VideoTrackRecorder::VpxEncoder::VpxEncoder( |
| 108 const OnFirstFrameCB& on_first_frame_callback, |
| 109 const OnEncodedVideoCB& on_encoded_video_callback) |
| 110 : first_frame_received_(false), |
| 111 track_index_(0), |
| 112 on_first_frame_callback_(on_first_frame_callback), |
| 113 on_encoded_video_callback_(on_encoded_video_callback), |
| 114 encoding_thread_("EncodingThread") { |
| 115 DCHECK(!on_first_frame_callback_.is_null()); |
| 116 DCHECK(!on_encoded_video_callback_.is_null()); |
| 117 |
| 118 codec_config_.g_timebase.den = 0; // Not initialized. |
| 119 |
| 120 DCHECK(!encoding_thread_.IsRunning()); |
| 121 encoding_thread_.Start(); |
| 122 } |
| 123 |
| 124 void VideoTrackRecorder::VpxEncoder::StartFrameEncode( |
| 125 const scoped_refptr<VideoFrame>& frame, |
| 126 const base::TimeTicks& capture_timestamp) { |
| 127 if (!first_frame_received_) { |
| 128 // Cache the thread sending frames on first frame arrival. |
| 129 DCHECK(!origin_task_runner_.get()); |
| 130 origin_task_runner_ = base::MessageLoop::current()->task_runner(); |
| 131 |
| 132 track_index_ = on_first_frame_callback_.Run(frame->visible_rect().size(), |
| 133 GetFrameRate(frame)); |
| 134 first_frame_timestamp_ = capture_timestamp; |
| 135 first_frame_received_ = true; |
| 136 } |
| 137 DCHECK(origin_task_runner_->BelongsToCurrentThread()); |
| 138 encoding_thread_.task_runner()->PostTask(FROM_HERE, |
| 139 base::Bind(&VpxEncoder::EncodeOnEncodingThread, |
| 140 this, frame, capture_timestamp)); |
| 141 } |
| 142 |
| 143 VideoTrackRecorder::VpxEncoder::~VpxEncoder() { |
| 144 DCHECK(main_render_thread_checker_.CalledOnValidThread()); |
| 145 DCHECK(encoding_thread_.IsRunning()); |
| 146 encoding_thread_.Stop(); |
| 147 } |
| 148 |
| 149 void VideoTrackRecorder::VpxEncoder::EncodeOnEncodingThread( |
| 150 const scoped_refptr<VideoFrame>& frame, |
| 151 const base::TimeTicks& capture_timestamp) { |
| 152 TRACE_EVENT0("video", |
| 153 "VideoTrackRecorder::VpxEncoder::EncodeOnEncodingThread"); |
| 154 DCHECK(encoding_thread_.task_runner()->BelongsToCurrentThread()); |
| 155 |
| 156 const gfx::Size frame_size = frame->visible_rect().size(); |
| 157 if (!IsInitialized() || |
| 158 gfx::Size(codec_config_.g_w, codec_config_.g_h) != frame_size) { |
| 159 ConfigureVp8Encoding(frame_size); |
| 160 } |
| 161 |
| 162 vpx_image_t vpx_image; |
| 163 vpx_image_t* const result = vpx_img_wrap(&vpx_image, |
| 164 VPX_IMG_FMT_I420, |
| 165 frame_size.width(), |
| 166 frame_size.height(), |
| 167 1 /* align */, |
| 168 frame->data(VideoFrame::kYPlane)); |
| 169 DCHECK_EQ(result, &vpx_image); |
| 170 vpx_image.planes[VPX_PLANE_Y] = frame->visible_data(VideoFrame::kYPlane); |
| 171 vpx_image.planes[VPX_PLANE_U] = frame->visible_data(VideoFrame::kUPlane); |
| 172 vpx_image.planes[VPX_PLANE_V] = frame->visible_data(VideoFrame::kVPlane); |
| 173 vpx_image.stride[VPX_PLANE_Y] = frame->stride(VideoFrame::kYPlane); |
| 174 vpx_image.stride[VPX_PLANE_U] = frame->stride(VideoFrame::kUPlane); |
| 175 vpx_image.stride[VPX_PLANE_V] = frame->stride(VideoFrame::kVPlane); |
| 176 |
| 177 const base::TimeDelta duration = CalculateFrameDuration(frame); |
| 178 // Encode the frame. The presentation time stamp argument here is fixed to |
| 179 // zero to force the encoder to base its single-frame bandwidth calculations |
| 180 // entirely on |predicted_frame_duration|. |
| 181 const vpx_codec_err_t ret = vpx_codec_encode(&encoder_, |
| 182 &vpx_image, |
| 183 0 /* pts */, |
| 184 duration.InMicroseconds(), |
| 185 kNoFlags, |
| 186 VPX_DL_REALTIME); |
| 187 DCHECK_EQ(ret, VPX_CODEC_OK) << vpx_codec_err_to_string(ret) << ", #" |
| 188 << vpx_codec_error(&encoder_) << " -" |
| 189 << vpx_codec_error_detail(&encoder_); |
| 190 |
| 191 scoped_ptr<std::string> data(new std::string); |
| 192 bool keyframe = false; |
| 193 vpx_codec_iter_t iter = NULL; |
| 194 const vpx_codec_cx_pkt_t* pkt = NULL; |
| 195 while ((pkt = vpx_codec_get_cx_data(&encoder_, &iter)) != NULL) { |
| 196 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT) |
| 197 continue; |
| 198 data->assign(static_cast<char*>(pkt->data.frame.buf), pkt->data.frame.sz); |
| 199 keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; |
| 200 break; |
| 201 } |
| 202 const int timestamp = |
| 203 (capture_timestamp - first_frame_timestamp_).InMilliseconds(); |
| 204 origin_task_runner_->PostTask(FROM_HERE, |
| 205 base::Bind(&VpxEncoder::OnFrameEncodeCompleted, |
| 206 this, |
| 207 base::Passed(&data), |
| 208 base::TimeDelta::FromMilliseconds(timestamp), |
| 209 keyframe)); |
| 210 } |
| 211 |
| 212 void VideoTrackRecorder::VpxEncoder::OnFrameEncodeCompleted( |
| 213 scoped_ptr<std::string> data, |
| 214 base::TimeDelta timestamp, |
| 215 bool keyframe) { |
| 216 DVLOG(1) << (keyframe ? "" : "non ") << "keyframe " |
| 217 << timestamp.InMilliseconds() << " ms - " << data->length() << "B "; |
| 218 DCHECK(origin_task_runner_->BelongsToCurrentThread()); |
| 219 on_encoded_video_callback_.Run(track_index_, base::StringPiece(*data), |
| 220 timestamp, keyframe); |
| 221 } |
| 222 |
| 223 void VideoTrackRecorder::VpxEncoder::ConfigureVp8Encoding( |
| 224 const gfx::Size& size) { |
| 225 if (IsInitialized()) { |
| 226 // TODO(mcasas): Workaround for certain bug. |
| 227 DVLOG(1) << "Destroying/Re-Creating encoder for larger frame size: " |
| 228 << gfx::Size(codec_config_.g_w, codec_config_.g_h).ToString() |
| 229 << " --> " << size.ToString(); |
| 230 //vpx_codec_destroy(&encoder_); |
| 231 } |
| 232 const vpx_codec_iface_t* interface = vpx_codec_vp8_cx(); |
| 233 vpx_codec_enc_config_default(interface, &codec_config_, 0 /* reserved */); |
| 234 |
| 235 // Adjust default bit rate to account for the actual size. |
| 236 codec_config_.rc_target_bitrate = size.width() * size.height() * |
| 237 codec_config_.rc_target_bitrate / |
| 238 codec_config_.g_w / codec_config_.g_h; |
| 239 DCHECK(size.width()); |
| 240 DCHECK(size.height()); |
| 241 codec_config_.g_w = size.width(); |
| 242 codec_config_.g_h = size.height(); |
| 243 codec_config_.g_pass = VPX_RC_ONE_PASS; |
| 244 |
| 245 // Timebase is the smallest interval used by the stream, can be set to the |
| 246 // frame rate or just to milliseconds. |
| 247 codec_config_.g_timebase.num = 1; |
| 248 codec_config_.g_timebase.den = base::Time::kMillisecondsPerSecond; |
| 249 |
| 250 // Let the encoder decide where to place the Keyframes, between min and max. |
| 251 // In VPX_KF_AUTO mode libvpx will sometimes emit keyframes regardless of min/ |
| 252 // max distance out of necessity. Due to http://crbug.com/440223, decoding |
| 253 // fails after 30,000 non-key frames, so force an "unnecessary" key-frame |
| 254 // every 10,000 frames. |
| 255 codec_config_.kf_mode = VPX_KF_AUTO; |
| 256 codec_config_.kf_min_dist = 10000; |
| 257 codec_config_.kf_max_dist = 10000; |
| 258 |
| 259 // Number of frames to consume before producing output. |
| 260 codec_config_.g_lag_in_frames = 0; |
| 261 |
| 262 const vpx_codec_err_t ret = vpx_codec_enc_init(&encoder_, interface, |
| 263 &codec_config_, kNoFlags); |
| 264 DCHECK_EQ(VPX_CODEC_OK, ret); |
| 265 } |
| 266 |
| 267 bool VideoTrackRecorder::VpxEncoder::IsInitialized() const { |
| 268 DCHECK(encoding_thread_.task_runner()->BelongsToCurrentThread()); |
| 269 return codec_config_.g_timebase.den != 0; |
| 270 } |
| 271 |
| 272 base::TimeDelta VideoTrackRecorder::VpxEncoder::CalculateFrameDuration( |
| 273 const scoped_refptr<VideoFrame>& frame) { |
| 274 DCHECK(encoding_thread_.task_runner()->BelongsToCurrentThread()); |
| 275 |
| 276 base::TimeDelta predicted_frame_duration; |
| 277 if (!frame->metadata()->GetTimeDelta(VideoFrameMetadata::FRAME_DURATION, |
| 278 &predicted_frame_duration) || |
| 279 predicted_frame_duration <= base::TimeDelta()) { |
| 280 // The source of the video frame did not provide the frame duration. Use |
| 281 // the actual amount of time between the current and previous frame as a |
| 282 // prediction for the next frame's duration. |
| 283 // TODO(mcasas): This duration estimation could lead to artifacts if the |
| 284 // cadence of the received stream is compromised (e.g. camera freeze, pause, |
| 285 // remote packet loss). Investigate using GetFrameRate() in this case. |
| 286 predicted_frame_duration = frame->timestamp() - last_frame_timestamp_; |
| 287 } |
| 288 last_frame_timestamp_ = frame->timestamp(); |
| 289 const base::TimeDelta kMinFrameDuration = |
| 290 base::TimeDelta::FromMilliseconds(1); |
| 291 return std::max(predicted_frame_duration, kMinFrameDuration); |
| 292 } |
| 293 |
| 294 VideoTrackRecorder::VideoTrackRecorder( |
| 295 const blink::WebMediaStreamTrack& track, |
| 296 const OnFirstFrameCB& on_first_frame_cb, |
| 297 const OnEncodedVideoCB& on_encoded_video_cb) |
| 298 : track_(track), |
| 299 encoder_(new VpxEncoder(on_first_frame_cb, |
| 300 on_encoded_video_cb)) { |
| 301 DCHECK(main_render_thread_checker_.CalledOnValidThread()); |
| 302 DCHECK(track.extraData()); |
| 303 AddToVideoTrack(this, |
| 304 base::Bind(&VpxEncoder::StartFrameEncode, encoder_), track_); |
| 305 } |
| 306 |
| 307 VideoTrackRecorder::~VideoTrackRecorder() { |
| 308 DCHECK(main_render_thread_checker_.CalledOnValidThread()); |
| 309 RemoveFromVideoTrack(this, track_); |
| 310 } |
| 311 |
| 312 void VideoTrackRecorder::StartFrameEncodeForTesting( |
| 313 const scoped_refptr<VideoFrame>& frame, |
| 314 const base::TimeTicks& capture_timestamp) { |
| 315 encoder_->StartFrameEncode(frame, capture_timestamp); |
| 316 } |
| 317 |
| 318 } // namespace content |
| OLD | NEW |