Return linux_android_rel_ng to the CQ.
[chromium-blink-merge.git] / media / filters / ffmpeg_video_decoder.cc
blob7ce78bd09a1206a5f7ca7994b2ad3ad3b1f7b9a9
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.
5 #include "media/filters/ffmpeg_video_decoder.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/location.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "media/base/bind_to_current_loop.h"
17 #include "media/base/decoder_buffer.h"
18 #include "media/base/limits.h"
19 #include "media/base/media_switches.h"
20 #include "media/base/pipeline.h"
21 #include "media/base/video_frame.h"
22 #include "media/base/video_util.h"
23 #include "media/ffmpeg/ffmpeg_common.h"
24 #include "media/filters/ffmpeg_glue.h"
26 namespace media {
28 // Always try to use three threads for video decoding. There is little reason
29 // not to since current day CPUs tend to be multi-core and we measured
30 // performance benefits on older machines such as P4s with hyperthreading.
32 // Handling decoding on separate threads also frees up the pipeline thread to
33 // continue processing. Although it'd be nice to have the option of a single
34 // decoding thread, FFmpeg treats having one thread the same as having zero
35 // threads (i.e., avcodec_decode_video() will execute on the calling thread).
36 // Yet another reason for having two threads :)
37 static const int kDecodeThreads = 2;
38 static const int kMaxDecodeThreads = 16;
40 // Returns the number of threads given the FFmpeg CodecID. Also inspects the
41 // command line for a valid --video-threads flag.
42 static int GetThreadCount(AVCodecID codec_id) {
43 // Refer to http://crbug.com/93932 for tsan suppressions on decoding.
44 int decode_threads = kDecodeThreads;
46 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
47 std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
48 if (threads.empty() || !base::StringToInt(threads, &decode_threads))
49 return decode_threads;
51 decode_threads = std::max(decode_threads, 0);
52 decode_threads = std::min(decode_threads, kMaxDecodeThreads);
53 return decode_threads;
56 static int GetVideoBufferImpl(struct AVCodecContext* s,
57 AVFrame* frame,
58 int flags) {
59 FFmpegVideoDecoder* decoder = static_cast<FFmpegVideoDecoder*>(s->opaque);
60 return decoder->GetVideoBuffer(s, frame, flags);
63 static void ReleaseVideoBufferImpl(void* opaque, uint8* data) {
64 scoped_refptr<VideoFrame> video_frame;
65 video_frame.swap(reinterpret_cast<VideoFrame**>(&opaque));
68 FFmpegVideoDecoder::FFmpegVideoDecoder(
69 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
70 : task_runner_(task_runner), state_(kUninitialized),
71 decode_nalus_(false) {}
73 int FFmpegVideoDecoder::GetVideoBuffer(struct AVCodecContext* codec_context,
74 AVFrame* frame,
75 int flags) {
76 // Don't use |codec_context_| here! With threaded decoding,
77 // it will contain unsynchronized width/height/pix_fmt values,
78 // whereas |codec_context| contains the current threads's
79 // updated width/height/pix_fmt, which can change for adaptive
80 // content.
81 const VideoPixelFormat format =
82 AVPixelFormatToVideoPixelFormat(codec_context->pix_fmt);
84 if (format == PIXEL_FORMAT_UNKNOWN)
85 return AVERROR(EINVAL);
86 DCHECK(format == PIXEL_FORMAT_YV12 || format == PIXEL_FORMAT_YV16 ||
87 format == PIXEL_FORMAT_YV24);
89 gfx::Size size(codec_context->width, codec_context->height);
90 const int ret = av_image_check_size(size.width(), size.height(), 0, NULL);
91 if (ret < 0)
92 return ret;
94 gfx::Size natural_size;
95 if (codec_context->sample_aspect_ratio.num > 0) {
96 natural_size = GetNaturalSize(size,
97 codec_context->sample_aspect_ratio.num,
98 codec_context->sample_aspect_ratio.den);
99 } else {
100 natural_size = config_.natural_size();
103 // FFmpeg has specific requirements on the allocation size of the frame. The
104 // following logic replicates FFmpeg's allocation strategy to ensure buffers
105 // are not overread / overwritten. See ff_init_buffer_info() for details.
107 // When lowres is non-zero, dimensions should be divided by 2^(lowres), but
108 // since we don't use this, just DCHECK that it's zero.
109 DCHECK_EQ(codec_context->lowres, 0);
110 gfx::Size coded_size(std::max(size.width(), codec_context->coded_width),
111 std::max(size.height(), codec_context->coded_height));
113 if (!VideoFrame::IsValidConfig(format, VideoFrame::STORAGE_UNKNOWN,
114 coded_size, gfx::Rect(size), natural_size)) {
115 return AVERROR(EINVAL);
118 // FFmpeg expects the initialize allocation to be zero-initialized. Failure
119 // to do so can lead to unitialized value usage. See http://crbug.com/390941
120 scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame(
121 format, coded_size, gfx::Rect(size), natural_size, kNoTimestamp());
123 // Prefer the color space from the codec context. If it's not specified (or is
124 // set to an unsupported value), fall back on the value from the config.
125 ColorSpace color_space = AVColorSpaceToColorSpace(codec_context->colorspace,
126 codec_context->color_range);
127 if (color_space == COLOR_SPACE_UNSPECIFIED)
128 color_space = config_.color_space();
129 video_frame->metadata()->SetInteger(VideoFrameMetadata::COLOR_SPACE,
130 color_space);
132 for (size_t i = 0; i < VideoFrame::NumPlanes(video_frame->format()); i++) {
133 frame->data[i] = video_frame->data(i);
134 frame->linesize[i] = video_frame->stride(i);
137 frame->width = coded_size.width();
138 frame->height = coded_size.height();
139 frame->format = codec_context->pix_fmt;
140 frame->reordered_opaque = codec_context->reordered_opaque;
142 // Now create an AVBufferRef for the data just allocated. It will own the
143 // reference to the VideoFrame object.
144 void* opaque = NULL;
145 video_frame.swap(reinterpret_cast<VideoFrame**>(&opaque));
146 frame->buf[0] =
147 av_buffer_create(frame->data[0],
148 VideoFrame::AllocationSize(format, coded_size),
149 ReleaseVideoBufferImpl,
150 opaque,
152 return 0;
155 std::string FFmpegVideoDecoder::GetDisplayName() const {
156 return "FFmpegVideoDecoder";
159 void FFmpegVideoDecoder::Initialize(const VideoDecoderConfig& config,
160 bool low_delay,
161 const InitCB& init_cb,
162 const OutputCB& output_cb) {
163 DCHECK(task_runner_->BelongsToCurrentThread());
164 DCHECK(!config.is_encrypted());
165 DCHECK(!output_cb.is_null());
167 FFmpegGlue::InitializeFFmpeg();
169 config_ = config;
170 InitCB bound_init_cb = BindToCurrentLoop(init_cb);
172 if (!config.IsValidConfig() || !ConfigureDecoder(low_delay)) {
173 bound_init_cb.Run(false);
174 return;
177 output_cb_ = BindToCurrentLoop(output_cb);
179 // Success!
180 state_ = kNormal;
181 bound_init_cb.Run(true);
184 void FFmpegVideoDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
185 const DecodeCB& decode_cb) {
186 DCHECK(task_runner_->BelongsToCurrentThread());
187 DCHECK(buffer.get());
188 DCHECK(!decode_cb.is_null());
189 CHECK_NE(state_, kUninitialized);
191 DecodeCB decode_cb_bound = BindToCurrentLoop(decode_cb);
193 if (state_ == kError) {
194 decode_cb_bound.Run(kDecodeError);
195 return;
198 if (state_ == kDecodeFinished) {
199 decode_cb_bound.Run(kOk);
200 return;
203 DCHECK_EQ(state_, kNormal);
205 // During decode, because reads are issued asynchronously, it is possible to
206 // receive multiple end of stream buffers since each decode is acked. When the
207 // first end of stream buffer is read, FFmpeg may still have frames queued
208 // up in the decoder so we need to go through the decode loop until it stops
209 // giving sensible data. After that, the decoder should output empty
210 // frames. There are three states the decoder can be in:
212 // kNormal: This is the starting state. Buffers are decoded. Decode errors
213 // are discarded.
214 // kDecodeFinished: All calls return empty frames.
215 // kError: Unexpected error happened.
217 // These are the possible state transitions.
219 // kNormal -> kDecodeFinished:
220 // When EOS buffer is received and the codec has been flushed.
221 // kNormal -> kError:
222 // A decoding error occurs and decoding needs to stop.
223 // (any state) -> kNormal:
224 // Any time Reset() is called.
226 bool has_produced_frame;
227 do {
228 has_produced_frame = false;
229 if (!FFmpegDecode(buffer, &has_produced_frame)) {
230 state_ = kError;
231 decode_cb_bound.Run(kDecodeError);
232 return;
234 // Repeat to flush the decoder after receiving EOS buffer.
235 } while (buffer->end_of_stream() && has_produced_frame);
237 if (buffer->end_of_stream())
238 state_ = kDecodeFinished;
240 // VideoDecoderShim expects that |decode_cb| is called only after
241 // |output_cb_|.
242 decode_cb_bound.Run(kOk);
245 void FFmpegVideoDecoder::Reset(const base::Closure& closure) {
246 DCHECK(task_runner_->BelongsToCurrentThread());
248 avcodec_flush_buffers(codec_context_.get());
249 state_ = kNormal;
250 task_runner_->PostTask(FROM_HERE, closure);
253 FFmpegVideoDecoder::~FFmpegVideoDecoder() {
254 DCHECK(task_runner_->BelongsToCurrentThread());
256 if (state_ != kUninitialized)
257 ReleaseFFmpegResources();
260 bool FFmpegVideoDecoder::FFmpegDecode(
261 const scoped_refptr<DecoderBuffer>& buffer,
262 bool* has_produced_frame) {
263 DCHECK(!*has_produced_frame);
265 // Create a packet for input data.
266 // Due to FFmpeg API changes we no longer have const read-only pointers.
267 AVPacket packet;
268 av_init_packet(&packet);
269 if (buffer->end_of_stream()) {
270 packet.data = NULL;
271 packet.size = 0;
272 } else {
273 packet.data = const_cast<uint8*>(buffer->data());
274 packet.size = buffer->data_size();
276 // Let FFmpeg handle presentation timestamp reordering.
277 codec_context_->reordered_opaque = buffer->timestamp().InMicroseconds();
280 int frame_decoded = 0;
281 int result = avcodec_decode_video2(codec_context_.get(),
282 av_frame_.get(),
283 &frame_decoded,
284 &packet);
285 // Log the problem if we can't decode a video frame and exit early.
286 if (result < 0) {
287 LOG(ERROR) << "Error decoding video: " << buffer->AsHumanReadableString();
288 return false;
291 // FFmpeg says some codecs might have multiple frames per packet. Previous
292 // discussions with rbultje@ indicate this shouldn't be true for the codecs
293 // we use.
294 DCHECK_EQ(result, packet.size);
296 // If no frame was produced then signal that more data is required to
297 // produce more frames. This can happen under two circumstances:
298 // 1) Decoder was recently initialized/flushed
299 // 2) End of stream was reached and all internal frames have been output
300 if (frame_decoded == 0) {
301 return true;
304 // TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675
305 // The decoder is in a bad state and not decoding correctly.
306 // Checking for NULL avoids a crash in CopyPlane().
307 if (!av_frame_->data[VideoFrame::kYPlane] ||
308 !av_frame_->data[VideoFrame::kUPlane] ||
309 !av_frame_->data[VideoFrame::kVPlane]) {
310 LOG(ERROR) << "Video frame was produced yet has invalid frame data.";
311 av_frame_unref(av_frame_.get());
312 return false;
315 scoped_refptr<VideoFrame> frame =
316 reinterpret_cast<VideoFrame*>(av_buffer_get_opaque(av_frame_->buf[0]));
317 frame->set_timestamp(
318 base::TimeDelta::FromMicroseconds(av_frame_->reordered_opaque));
319 *has_produced_frame = true;
320 output_cb_.Run(frame);
322 av_frame_unref(av_frame_.get());
323 return true;
326 void FFmpegVideoDecoder::ReleaseFFmpegResources() {
327 codec_context_.reset();
328 av_frame_.reset();
331 bool FFmpegVideoDecoder::ConfigureDecoder(bool low_delay) {
332 // Release existing decoder resources if necessary.
333 ReleaseFFmpegResources();
335 // Initialize AVCodecContext structure.
336 codec_context_.reset(avcodec_alloc_context3(NULL));
337 VideoDecoderConfigToAVCodecContext(config_, codec_context_.get());
339 codec_context_->thread_count = GetThreadCount(codec_context_->codec_id);
340 codec_context_->thread_type = low_delay ? FF_THREAD_SLICE : FF_THREAD_FRAME;
341 codec_context_->opaque = this;
342 codec_context_->flags |= CODEC_FLAG_EMU_EDGE;
343 codec_context_->get_buffer2 = GetVideoBufferImpl;
344 codec_context_->refcounted_frames = 1;
346 if (decode_nalus_)
347 codec_context_->flags2 |= CODEC_FLAG2_CHUNKS;
349 AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
350 if (!codec || avcodec_open2(codec_context_.get(), codec, NULL) < 0) {
351 ReleaseFFmpegResources();
352 return false;
355 av_frame_.reset(av_frame_alloc());
356 return true;
359 } // namespace media