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

Side by Side Diff: media/filters/vpx_video_decoder.cc

Issue 11468018: Add libvpx wrapper to media to support VP9 video decoding. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Address comments. Created 8 years 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 | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 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 "media/filters/vpx_video_decoder.h"
6
7 #include "base/bind.h"
8 #include "base/callback_helpers.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/message_loop_proxy.h"
14 #include "base/string_number_conversions.h"
15 #include "media/base/bind_to_loop.h"
16 #include "media/base/decoder_buffer.h"
17 #include "media/base/decryptor.h"
18 #include "media/base/demuxer_stream.h"
19 #include "media/base/media_switches.h"
20 #include "media/base/pipeline.h"
21 #include "media/base/video_decoder_config.h"
22 #include "media/base/video_frame.h"
23 #include "media/base/video_util.h"
24
25 // Include libvpx header files.
26 // VPX_CODEC_DISABLE_COMPAT excludes parts of the libvpx API that provide
27 // backwards compatibility for legacy applications using the library.
28 #define VPX_CODEC_DISABLE_COMPAT 1
29 extern "C" {
30 #include "third_party/libvpx/libvpx.h"
31 }
32
33 namespace media {
34
35 #define BIND_TO_LOOP(function) \
36 media::BindToLoop(message_loop_, base::Bind(function, this))
37
38 // Always try to use three threads for video decoding. There is little reason
39 // not to since current day CPUs tend to be multi-core and we measured
40 // performance benefits on older machines such as P4s with hyperthreading.
41 static const int kDecodeThreads = 2;
42 static const int kMaxDecodeThreads = 16;
43
44 // Returns the number of threads given the FFmpeg CodecID. Also inspects the
45 // command line for a valid --video-threads flag.
46 static int GetThreadCount() {
47 // Refer to http://crbug.com/93932 for tsan suppressions on decoding.
48 int decode_threads = kDecodeThreads;
49
50 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
51 std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
52 if (threads.empty() || !base::StringToInt(threads, &decode_threads))
53 return decode_threads;
54
55 decode_threads = std::max(decode_threads, 0);
56 decode_threads = std::min(decode_threads, kMaxDecodeThreads);
57 return decode_threads;
58 }
59
60 VpxVideoDecoder::VpxVideoDecoder(
61 const scoped_refptr<base::MessageLoopProxy>& message_loop)
62 : message_loop_(message_loop),
63 state_(kUninitialized),
64 frame_num_(0),
65 vpx_codec_(NULL) {
66 }
67
68 VpxVideoDecoder::~VpxVideoDecoder() {
69 DCHECK_EQ(kUninitialized, state_);
70 CloseDecoder();
71 }
72
73 void VpxVideoDecoder::Initialize(
74 const scoped_refptr<DemuxerStream>& stream,
75 const PipelineStatusCB& status_cb,
76 const StatisticsCB& statistics_cb) {
77 if (!message_loop_->BelongsToCurrentThread()) {
78 message_loop_->PostTask(FROM_HERE, base::Bind(
79 &VpxVideoDecoder::Initialize, this,
80 stream, status_cb, statistics_cb));
81 return;
82 }
83
84 DCHECK(!demuxer_stream_) << "Already initialized.";
85
86 if (!stream) {
87 status_cb.Run(PIPELINE_ERROR_DECODE);
88 return;
89 }
90
91 demuxer_stream_ = stream;
92 statistics_cb_ = statistics_cb;
93
94 if (!ConfigureDecoder()) {
95 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
96 return;
97 }
98
99 // Success!
100 state_ = kNormal;
101 status_cb.Run(PIPELINE_OK);
102 }
103
104 bool VpxVideoDecoder::ConfigureDecoder() {
105 const VideoDecoderConfig& config = demuxer_stream_->video_decoder_config();
106 if (!config.IsValidConfig()) {
107 DLOG(ERROR) << "Invalid video stream config: "
108 << config.AsHumanReadableString();
109 return false;
110 }
111
112 if (config.codec() != kCodecVP9)
113 return false;
114
115 CloseDecoder();
116
117 vpx_codec_ = new vpx_codec_ctx();
118 vpx_codec_dec_cfg_t vpx_config = {0};
119 vpx_config.w = config.coded_size().width();
120 vpx_config.h = config.coded_size().height();
121 vpx_config.threads = kDecodeThreads;
122
123 vpx_codec_err_t status = vpx_codec_dec_init(vpx_codec_,
124 vpx_codec_vp8_dx(),
125 &vpx_config,
126 0);
127 if (status != VPX_CODEC_OK) {
128 LOG(ERROR) << "ConfigureDecoder(): vpx_codec_dec_init failed, status="
129 << status;
130 delete vpx_codec_;
131 vpx_codec_ = NULL;
132 return false;
133 }
134
135 return true;
136 }
137
138 void VpxVideoDecoder::CloseDecoder() {
139 if (vpx_codec_) {
140 vpx_codec_destroy(vpx_codec_);
141 delete vpx_codec_;
fgalligan1 2012/12/13 20:17:31 You could set vpx_codec_ to NULL here in case some
Tom Finegan 2012/12/14 01:52:31 Done.
142 }
143 }
144
145 void VpxVideoDecoder::Read(const ReadCB& read_cb) {
146 // Complete operation asynchronously on different stack of execution as per
147 // the API contract of VideoDecoder::Read()
148 message_loop_->PostTask(FROM_HERE, base::Bind(
149 &VpxVideoDecoder::DoRead, this, read_cb));
150 }
151
152 void VpxVideoDecoder::Reset(const base::Closure& closure) {
153 if (!message_loop_->BelongsToCurrentThread()) {
154 message_loop_->PostTask(FROM_HERE, base::Bind(
155 &VpxVideoDecoder::Reset, this, closure));
156 return;
157 }
158
159 DCHECK(reset_cb_.is_null());
160 reset_cb_ = closure;
161
162 //if (decryptor_)
163 // decryptor_->CancelDecrypt(Decryptor::kVideo);
fgalligan1 2012/12/13 20:17:31 Delete
Tom Finegan 2012/12/14 01:52:31 Done.
164
165 // Defer the reset if a read is pending.
166 if (!read_cb_.is_null())
167 return;
168
169 DoReset();
170
171
172 if (!message_loop_->BelongsToCurrentThread()) {
fgalligan1 2012/12/13 20:17:31 This code cannot be called with conditional above.
Tom Finegan 2012/12/14 01:52:31 Yeah, weird. From FFmpegAudioDecoder. Removed.
173 message_loop_->PostTask(FROM_HERE, base::Bind(
174 &VpxVideoDecoder::Reset, this, closure));
175 return;
176 }
177 }
178
179 void VpxVideoDecoder::Stop(const base::Closure& closure) {
180 if (!message_loop_->BelongsToCurrentThread()) {
181 message_loop_->PostTask(FROM_HERE, base::Bind(
182 &VpxVideoDecoder::Stop, this, closure));
183 return;
184 }
185
186 if (state_ == kUninitialized) {
187 closure.Run();
188 return;
189 }
190
191 //if (decryptor_)
192 // decryptor_->CancelDecrypt(Decryptor::kVideo);
fgalligan1 2012/12/13 20:17:31 Remove
Tom Finegan 2012/12/14 01:52:31 Done.
193
194 if (!read_cb_.is_null())
195 base::ResetAndReturn(&read_cb_).Run(kOk, NULL);
196
197 //ReleaseFFmpegResources();
198 state_ = kUninitialized;
199 closure.Run();
200 }
201
202 void VpxVideoDecoder::DoRead(const ReadCB& read_cb) {
203 DCHECK(message_loop_->BelongsToCurrentThread());
204 DCHECK(!read_cb.is_null());
205 CHECK_NE(state_, kUninitialized);
206 CHECK(read_cb_.is_null()) << "Overlapping decodes are not supported.";
207
208 // Return empty frames if decoding has finished.
209 if (state_ == kDecodeFinished) {
210 read_cb.Run(kOk, VideoFrame::CreateEmptyFrame());
211 return;
212 }
213
214 read_cb_ = read_cb;
215 ReadFromDemuxerStream();
216 }
217
218 void VpxVideoDecoder::ReadFromDemuxerStream() {
219 DCHECK_NE(state_, kUninitialized);
220 DCHECK_NE(state_, kDecodeFinished);
221 DCHECK(!read_cb_.is_null());
222
223 demuxer_stream_->Read(base::Bind(
224 &VpxVideoDecoder::DoDecryptOrDecodeBuffer, this));
225 }
226
227 void VpxVideoDecoder::DoDecryptOrDecodeBuffer(
228 DemuxerStream::Status status,
229 const scoped_refptr<DecoderBuffer>& buffer) {
230 if (!message_loop_->BelongsToCurrentThread()) {
231 message_loop_->PostTask(FROM_HERE, base::Bind(
232 &VpxVideoDecoder::DoDecryptOrDecodeBuffer, this, status, buffer));
233 return;
234 }
235
236 DCHECK_NE(state_, kDecodeFinished);
237 DCHECK_EQ(status != DemuxerStream::kOk, !buffer) << status;
238
239 if (state_ == kUninitialized)
240 return;
241
242 DCHECK(!read_cb_.is_null());
243
244 if (!reset_cb_.is_null()) {
245 base::ResetAndReturn(&read_cb_).Run(kOk, NULL);
246 DoReset();
247 return;
248 }
249
250 if (status == DemuxerStream::kAborted) {
251 base::ResetAndReturn(&read_cb_).Run(kOk, NULL);
252 return;
253 }
254
255 if (status == DemuxerStream::kConfigChanged) {
256 if (!ConfigureDecoder()) {
257 base::ResetAndReturn(&read_cb_).Run(kDecodeError, NULL);
258 return;
259 }
260
261 ReadFromDemuxerStream();
262 return;
263 }
264
265 DCHECK_EQ(status, DemuxerStream::kOk);
266
267 /*
268 if (buffer->GetDecryptConfig() && buffer->GetDataSize()) {
269 decryptor_->Decrypt(Decryptor::kVideo,
270 buffer,
271 base::Bind(&FFmpegVideoDecoder::BufferDecrypted, this));
272 return;
273 }
fgalligan1 2012/12/13 20:17:31 Remove
Tom Finegan 2012/12/14 01:52:31 Done.
274 */
275
276 DecodeBuffer(buffer);
277 }
278
279 void VpxVideoDecoder::DecodeBuffer(
280 const scoped_refptr<DecoderBuffer>& buffer) {
281 DCHECK(message_loop_->BelongsToCurrentThread());
282 DCHECK_NE(state_, kUninitialized);
283 DCHECK_NE(state_, kDecodeFinished);
284 DCHECK(reset_cb_.is_null());
285 DCHECK(!read_cb_.is_null());
286 DCHECK(buffer);
287
288 // During decode, because reads are issued asynchronously, it is possible to
289 // receive multiple end of stream buffers since each read is acked. When the
290 // first end of stream buffer is read, FFmpeg may still have frames queued
291 // up in the decoder so we need to go through the decode loop until it stops
292 // giving sensible data. After that, the decoder should output empty
293 // frames. There are three states the decoder can be in:
294 //
295 // kNormal: This is the starting state. Buffers are decoded. Decode errors
296 // are discarded.
297 // kFlushCodec: There isn't any more input data. Call avcodec_decode_video2
298 // until no more data is returned to flush out remaining
299 // frames. The input buffer is ignored at this point.
300 // kDecodeFinished: All calls return empty frames.
301 //
302 // These are the possible state transitions.
303 //
304 // kNormal -> kFlushCodec:
305 // When buffer->IsEndOfStream() is first true.
306 // kNormal -> kDecodeFinished:
307 // A decoding error occurs and decoding needs to stop.
308 // kFlushCodec -> kDecodeFinished:
309 // When avcodec_decode_video2() returns 0 data or errors out.
310 // (any state) -> kNormal:
311 // Any time Reset() is called.
312
313 // Transition to kFlushCodec on the first end of stream buffer.
314 if (state_ == kNormal && buffer->IsEndOfStream()) {
315 state_ = kFlushCodec;
316 }
317
318 scoped_refptr<VideoFrame> video_frame;
319 if (!Decode(buffer, &video_frame)) {
320 state_ = kDecodeFinished;
321 base::ResetAndReturn(&read_cb_).Run(kDecodeError, NULL);
322 return;
323 }
324
325 // Any successful decode counts!
326 if (buffer->GetDataSize()) {
327 PipelineStatistics statistics;
328 statistics.video_bytes_decoded = buffer->GetDataSize();
329 statistics_cb_.Run(statistics);
330 }
331
332 // If we didn't get a frame then we've either completely finished decoding or
333 // we need more data.
334 if (!video_frame) {
335 if (state_ == kFlushCodec) {
336 state_ = kDecodeFinished;
337 base::ResetAndReturn(&read_cb_).Run(kOk, VideoFrame::CreateEmptyFrame());
338 return;
339 }
340
341 ReadFromDemuxerStream();
342 return;
343 }
344
345 base::ResetAndReturn(&read_cb_).Run(kOk, video_frame);
346 }
347
348 bool VpxVideoDecoder::Decode(
349 const scoped_refptr<DecoderBuffer>& buffer,
350 scoped_refptr<VideoFrame>* video_frame) {
351 DCHECK(video_frame);
352
353 // Pass |buffer| to libvpx.
354 int64 timestamp = buffer->GetTimestamp().InMicroseconds();
355 void* user_priv = reinterpret_cast<void*>(&timestamp);
356 vpx_codec_err_t status = vpx_codec_decode(vpx_codec_,
357 buffer->GetData(),
358 buffer->GetDataSize(),
359 user_priv,
360 0);
361 if (status != VPX_CODEC_OK) {
362 LOG(ERROR) << "Decode(): vpx_codec_decode failed, status=" << status;
363 return false;
364 }
365
366 // Gets pointer to decoded data.
367 vpx_codec_iter_t iter = NULL;
368 const vpx_image_t* vpx_image = vpx_codec_get_frame(vpx_codec_, &iter);
369 if (!vpx_image) {
370 *video_frame = NULL;
371 return true;
372 }
373
374 if (vpx_image->user_priv != reinterpret_cast<void*>(&timestamp)) {
375 LOG(ERROR) << "Decode(): invalid output timestamp.";
376 return false;
377 }
378
379 if (!CopyVpxImageTo(vpx_image, video_frame)) {
380 LOG(ERROR) << "Decode(): could not copy vpx image to output buffer.";
381 return false;
382 }
383
384 (*video_frame)->SetTimestamp(base::TimeDelta::FromMicroseconds(timestamp));
385
386 return true;
387 }
388
389 void VpxVideoDecoder::DoReset() {
390 DCHECK(read_cb_.is_null());
391
392 //avcodec_flush_buffers(codec_context_);
fgalligan1 2012/12/13 20:17:31 Remove
Tom Finegan 2012/12/14 01:52:31 Done.
393 state_ = kNormal;
394 reset_cb_.Run();
395 reset_cb_.Reset();
396 }
397
398 bool VpxVideoDecoder::CopyVpxImageTo(
399 const vpx_image* vpx_image,
400 scoped_refptr<VideoFrame>* video_frame) {
401 DCHECK(vpx_image);
402 if (!vpx_image)
403 return false;
404
405 DCHECK_EQ(vpx_image->d_w % 2, 0U);
406 DCHECK_EQ(vpx_image->d_h % 2, 0U);
407 DCHECK(vpx_image->fmt == VPX_IMG_FMT_I420 ||
408 vpx_image->fmt == VPX_IMG_FMT_YV12);
409
410 gfx::Size size(vpx_image->d_w, vpx_image->d_h);
411 gfx::Size natural_size =
412 demuxer_stream_->video_decoder_config().natural_size();
413
414 const VideoFrame::Format format = VideoFrame::YV12;
415 if (!VideoFrame::IsValidConfig(format,
416 size,
417 gfx::Rect(size),
418 natural_size)) {
419 LOG(ERROR) << "CopyVpxImageTo(): invalid video frame.";
420 return false;
421 }
422
423 *video_frame = VideoFrame::CreateFrame(format,
424 size,
425 gfx::Rect(size),
426 natural_size,
427 kNoTimestamp());
428 if (!video_frame) {
429 LOG(ERROR) << "CopyVpxImageTo(): cannot create output video frame.";
430 return false;
431 }
432
433 CopyYPlane(vpx_image->planes[VPX_PLANE_Y],
434 vpx_image->stride[VPX_PLANE_Y],
435 vpx_image->d_h,
436 *video_frame);
437 CopyUPlane(vpx_image->planes[VPX_PLANE_U],
438 vpx_image->stride[VPX_PLANE_U],
439 vpx_image->d_h / 2,
440 *video_frame);
441 CopyVPlane(vpx_image->planes[VPX_PLANE_V],
442 vpx_image->stride[VPX_PLANE_V],
443 vpx_image->d_h / 2,
444 *video_frame);
445
446 return true;
447 }
448
449 } // namespace media
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698