Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(287)

Side by Side Diff: content/renderer/media/video_track_recorder.cc

Issue 1233033002: MediaStream: Adding VideoTrackRecorder class and unittests (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: miu@s comments Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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/sys_info.h"
10 #include "base/threading/thread.h"
11 #include "base/time/time.h"
12 #include "base/trace_event/trace_event.h"
13 #include "content/child/child_process.h"
14 #include "media/base/bind_to_current_loop.h"
15 #include "media/base/video_frame.h"
16
17 extern "C" {
18 // VPX_CODEC_DISABLE_COMPAT excludes parts of the libvpx API that provide
19 // backwards compatibility for legacy applications using the library.
20 #define VPX_CODEC_DISABLE_COMPAT 1
21 #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h"
22 #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h"
23 }
24
25 using media::VideoFrame;
26 using media::VideoFrameMetadata;
27
28 namespace content {
29
30 namespace {
31 const vpx_codec_flags_t kNoFlags = 0;
32
33 void OnFrameEncodeCompleted(
34 const content::VideoTrackRecorder::OnEncodedVideoCB& on_encoded_video_cb,
35 const scoped_refptr<VideoFrame>& frame,
36 scoped_ptr<std::string> data,
37 const base::TimeTicks& capture_timestamp,
38 bool keyframe) {
39 DVLOG(1) << (keyframe ? "" : "non ") << "keyframe "
40 << capture_timestamp << " ms - " << data->length() << "B ";
41 on_encoded_video_cb.Run(frame, base::StringPiece(*data), capture_timestamp,
42 keyframe);
43 }
44
45 } // anonymous namespace
46
47 // Inner class encapsulating all libvpx interactions and the encoding+delivery
48 // of received frames. This class is:
49 // - created and destroyed on its parent's thread (usually the main render
50 // thread),
51 // - receives VideoFrames and Run()s the callbacks on another thread (supposedly
52 // the render IO thread), which is cached on first frame arrival,
53 // - uses an internal |encoding_thread_| for libvpx interactions, notably for
54 // encoding (which might take some time).
55 // Only VP8 is supported for the time being.
56 class VideoTrackRecorder::VpxEncoder {
57 public:
58 explicit VpxEncoder(const OnEncodedVideoCB& on_encoded_video_callback);
59 virtual ~VpxEncoder();
miu 2015/08/20 21:31:37 nit: No need to make this virtual (and make the cl
mcasas 2015/08/20 23:26:33 Done.
60
61 void StartFrameEncode(const scoped_refptr<VideoFrame>& frame,
62 const base::TimeTicks& capture_timestamp);
63
64 private:
65 void EncodeOnEncodingThread(const scoped_refptr<VideoFrame>& frame,
66 const base::TimeTicks& capture_timestamp);
67
68 void ConfigureVp8Encoding(const gfx::Size& size);
69
70 // Returns true if |codec_config_| has been filled in at least once.
71 bool IsInitialized() const;
72
73 // Estimate the frame duration from |frame| and |last_frame_timestamp_|.
74 base::TimeDelta CalculateFrameDuration(
75 const scoped_refptr<VideoFrame>& frame);
76
77 // Used to check that we are destroyed on the same thread we were created.
78 base::ThreadChecker main_render_thread_checker_;
79
80 // Task runner where frames to encode and reply callbacks must happen.
81 scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner_;
82
83 // This callback should be exercised on IO thread.
84 const OnEncodedVideoCB on_encoded_video_callback_;
85
86 // Thread for encoding. Active as long as VpxEncoder exists. All variables
87 // below this are used in this thread.
88 base::Thread encoding_thread_;
89 // VP8 internal objects: configuration, encoder and Vpx Image wrapper.
90 vpx_codec_enc_cfg_t codec_config_;
91 vpx_codec_ctx_t encoder_;
92
93 // The |VideoFrame::timestamp()| of the last encoded frame. This is used to
94 // predict the duration of the next frame.
95 base::TimeDelta last_frame_timestamp_;
96 };
97
98 VideoTrackRecorder::VpxEncoder::VpxEncoder(
99 const OnEncodedVideoCB& on_encoded_video_callback)
100 : on_encoded_video_callback_(on_encoded_video_callback),
101 encoding_thread_("EncodingThread") {
102 DCHECK(!on_encoded_video_callback_.is_null());
103
104 codec_config_.g_timebase.den = 0; // Not initialized.
105
106 DCHECK(!encoding_thread_.IsRunning());
107 encoding_thread_.Start();
108 }
109
110 VideoTrackRecorder::VpxEncoder::~VpxEncoder() {
111 DCHECK(main_render_thread_checker_.CalledOnValidThread());
112 DCHECK(encoding_thread_.IsRunning());
113 encoding_thread_.Stop();
114 vpx_codec_destroy(&encoder_);
115 }
116
117 void VideoTrackRecorder::VpxEncoder::StartFrameEncode(
118 const scoped_refptr<VideoFrame>& frame,
119 const base::TimeTicks& capture_timestamp) {
120 // Cache the thread sending frames on first frame arrival.
121 if (!origin_task_runner_.get())
122 origin_task_runner_ = base::MessageLoop::current()->task_runner();
123 DCHECK(origin_task_runner_->BelongsToCurrentThread());
124
125 encoding_thread_.task_runner()->PostTask(
126 FROM_HERE, base::Bind(&VpxEncoder::EncodeOnEncodingThread,
127 base::Unretained(this), frame, capture_timestamp));
128 }
129
130 void VideoTrackRecorder::VpxEncoder::EncodeOnEncodingThread(
131 const scoped_refptr<VideoFrame>& frame,
132 const base::TimeTicks& capture_timestamp) {
133 TRACE_EVENT0("video",
134 "VideoTrackRecorder::VpxEncoder::EncodeOnEncodingThread");
135 DCHECK(encoding_thread_.task_runner()->BelongsToCurrentThread());
136
137 const gfx::Size frame_size = frame->visible_rect().size();
138 if (!IsInitialized() ||
139 gfx::Size(codec_config_.g_w, codec_config_.g_h) != frame_size) {
140 ConfigureVp8Encoding(frame_size);
141 }
142
143 vpx_image_t vpx_image;
144 vpx_image_t* const result = vpx_img_wrap(&vpx_image,
145 VPX_IMG_FMT_I420,
146 frame_size.width(),
147 frame_size.height(),
148 1 /* align */,
149 frame->data(VideoFrame::kYPlane));
150 DCHECK_EQ(result, &vpx_image);
151 vpx_image.planes[VPX_PLANE_Y] = frame->visible_data(VideoFrame::kYPlane);
152 vpx_image.planes[VPX_PLANE_U] = frame->visible_data(VideoFrame::kUPlane);
153 vpx_image.planes[VPX_PLANE_V] = frame->visible_data(VideoFrame::kVPlane);
154 vpx_image.stride[VPX_PLANE_Y] = frame->stride(VideoFrame::kYPlane);
155 vpx_image.stride[VPX_PLANE_U] = frame->stride(VideoFrame::kUPlane);
156 vpx_image.stride[VPX_PLANE_V] = frame->stride(VideoFrame::kVPlane);
157
158 const base::TimeDelta duration = CalculateFrameDuration(frame);
159 // Encode the frame. The presentation time stamp argument here is fixed to
160 // zero to force the encoder to base its single-frame bandwidth calculations
161 // entirely on |predicted_frame_duration|.
162 const vpx_codec_err_t ret = vpx_codec_encode(&encoder_,
163 &vpx_image,
164 0 /* pts */,
165 duration.InMicroseconds(),
166 kNoFlags,
167 VPX_DL_REALTIME);
168 DCHECK_EQ(ret, VPX_CODEC_OK) << vpx_codec_err_to_string(ret) << ", #"
169 << vpx_codec_error(&encoder_) << " -"
170 << vpx_codec_error_detail(&encoder_);
171
172 scoped_ptr<std::string> data(new std::string);
173 bool keyframe = false;
174 vpx_codec_iter_t iter = NULL;
175 const vpx_codec_cx_pkt_t* pkt = NULL;
176 while ((pkt = vpx_codec_get_cx_data(&encoder_, &iter)) != NULL) {
177 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
178 continue;
179 data->assign(static_cast<char*>(pkt->data.frame.buf), pkt->data.frame.sz);
180 keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
181 break;
182 }
183 origin_task_runner_->PostTask(FROM_HERE,
184 base::Bind(OnFrameEncodeCompleted,
miu 2015/08/20 21:31:37 nit: &OnFrameEncodeCompleted
mcasas 2015/08/20 23:26:33 Done.
185 on_encoded_video_callback_,
186 frame,
187 base::Passed(&data),
188 capture_timestamp,
189 keyframe));
190 }
191
192 void VideoTrackRecorder::VpxEncoder::ConfigureVp8Encoding(
193 const gfx::Size& size) {
194 if (IsInitialized()) {
195 // TODO(mcasas) VP8 quirk/optimisation: If the new |size| is strictly less-
196 // than-or-equal than the old size, in terms of area, the existing encoder
197 // instance could be reused after changing |codec_config_.{g_w,g_h}|.
198 DVLOG(1) << "Destroying/Re-Creating encoder for new frame size: "
199 << gfx::Size(codec_config_.g_w, codec_config_.g_h).ToString()
200 << " --> " << size.ToString();
201 vpx_codec_destroy(&encoder_);
202 }
203
204 const vpx_codec_iface_t* interface = vpx_codec_vp8_cx();
205 const vpx_codec_err_t result = vpx_codec_enc_config_default(interface,
206 &codec_config_,
207 0 /* reserved */);
208 DCHECK_EQ(VPX_CODEC_OK, result);
209
210 // Adjust default bit rate to account for the actual size.
211 DCHECK_EQ(320u, codec_config_.g_w);
212 DCHECK_EQ(240u, codec_config_.g_h);
213 DCHECK_EQ(256u, codec_config_.rc_target_bitrate);
214 codec_config_.rc_target_bitrate = size.GetArea() *
215 codec_config_.rc_target_bitrate / codec_config_.g_w / codec_config_.g_h;
216
217 DCHECK(size.width());
218 DCHECK(size.height());
219 codec_config_.g_w = size.width();
220 codec_config_.g_h = size.height();
221 codec_config_.g_pass = VPX_RC_ONE_PASS;
222
223 // Timebase is the smallest interval used by the stream, can be set to the
224 // frame rate or to e.g. microseconds.
225 codec_config_.g_timebase.num = 1;
226 codec_config_.g_timebase.den = base::Time::kMicrosecondsPerSecond;
227
228 // Let the encoder decide where to place the Keyframes, between min and max.
229 // In VPX_KF_AUTO mode libvpx will sometimes emit keyframes regardless of min/
230 // max distance out of necessity.
231 // Note that due to http://crbug.com/440223, it might be necessary to force a
232 // key frame after 10,000frames since decoding fails after 30,000 non-key
233 // frames.
234 codec_config_.kf_mode = VPX_KF_AUTO;
235 codec_config_.kf_min_dist = 0;
236 codec_config_.kf_max_dist = 30000;
237
238 // Do not saturate CPU utilization just for encoding. On a lower-end system
239 // with only 1 or 2 cores, use only one thread for encoding. On systems with
240 // more cores, allow half of the cores to be used for encoding.
241 codec_config_.g_threads =
242 std::min(8, (base::SysInfo::NumberOfProcessors() + 1) / 2);
243
244 // Number of frames to consume before producing output.
245 codec_config_.g_lag_in_frames = 0;
246
247 const vpx_codec_err_t ret = vpx_codec_enc_init(&encoder_, interface,
248 &codec_config_, kNoFlags);
249 DCHECK_EQ(VPX_CODEC_OK, ret);
250 }
251
252 bool VideoTrackRecorder::VpxEncoder::IsInitialized() const {
253 DCHECK(encoding_thread_.task_runner()->BelongsToCurrentThread());
254 return codec_config_.g_timebase.den != 0;
255 }
256
257 base::TimeDelta VideoTrackRecorder::VpxEncoder::CalculateFrameDuration(
258 const scoped_refptr<VideoFrame>& frame) {
259 DCHECK(encoding_thread_.task_runner()->BelongsToCurrentThread());
260
261 using base::TimeDelta;
262 TimeDelta predicted_frame_duration;
263 if (!frame->metadata()->GetTimeDelta(VideoFrameMetadata::FRAME_DURATION,
264 &predicted_frame_duration) ||
265 predicted_frame_duration <= TimeDelta()) {
266 // The source of the video frame did not provide the frame duration. Use
267 // the actual amount of time between the current and previous frame as a
268 // prediction for the next frame's duration.
269 // TODO(mcasas): This duration estimation could lead to artifacts if the
270 // cadence of the received stream is compromised (e.g. camera freeze, pause,
271 // remote packet loss). Investigate using GetFrameRate() in this case.
272 predicted_frame_duration = frame->timestamp() - last_frame_timestamp_;
273 }
274 last_frame_timestamp_ = frame->timestamp();
275 // Make sure |predicted_frame_duration| is in a safe range of values.
276 const TimeDelta kMaxFrameDuration = TimeDelta::FromSecondsD(1.0 / 8);
277 const TimeDelta kMinFrameDuration = TimeDelta::FromMilliseconds(1);
278 return std::min(kMaxFrameDuration, std::max(predicted_frame_duration,
279 kMinFrameDuration));
280 }
281
282 VideoTrackRecorder::VideoTrackRecorder(
283 const blink::WebMediaStreamTrack& track,
284 const OnEncodedVideoCB& on_encoded_video_callback)
285 : track_(track),
286 encoder_(new VpxEncoder(on_encoded_video_callback)),
287 weak_factory_(this) {
288 DCHECK(main_render_thread_checker_.CalledOnValidThread());
289 DCHECK(!track_.isNull());
290 DCHECK(track.extraData());
291 AddToVideoTrack(this,
292 media::BindToCurrentLoop(
293 base::Bind(&VideoTrackRecorder::OnVideoFrame,
294 weak_factory_.GetWeakPtr())),
295 track_);
296 }
297
298 VideoTrackRecorder::~VideoTrackRecorder() {
299 DCHECK(main_render_thread_checker_.CalledOnValidThread());
300 RemoveFromVideoTrack(this, track_);
301 weak_factory_.InvalidateWeakPtrs();
302 track_.reset();
303 }
304
305 void VideoTrackRecorder::OnVideoFrame(const scoped_refptr<VideoFrame>& frame,
306 const base::TimeTicks& timestamp) {
307 DCHECK(main_render_thread_checker_.CalledOnValidThread());
308 encoder_->StartFrameEncode(frame, timestamp);
309 }
310
311 } // namespace content
OLDNEW
« no previous file with comments | « content/renderer/media/video_track_recorder.h ('k') | content/renderer/media/video_track_recorder_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698