Updating XTBs based on .GRDs from branch master
[chromium-blink-merge.git] / media / filters / ffmpeg_audio_decoder.cc
blob673f460cb8dacea0f38c5d24b81a06e4d67975ce
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_audio_decoder.h"
7 #include "base/callback_helpers.h"
8 #include "base/single_thread_task_runner.h"
9 #include "media/base/audio_buffer.h"
10 #include "media/base/audio_bus.h"
11 #include "media/base/audio_decoder_config.h"
12 #include "media/base/audio_discard_helper.h"
13 #include "media/base/bind_to_current_loop.h"
14 #include "media/base/decoder_buffer.h"
15 #include "media/base/limits.h"
16 #include "media/ffmpeg/ffmpeg_common.h"
17 #include "media/filters/ffmpeg_glue.h"
19 namespace media {
21 // Returns true if the decode result was end of stream.
22 static inline bool IsEndOfStream(int result,
23 int decoded_size,
24 const scoped_refptr<DecoderBuffer>& input) {
25 // Three conditions to meet to declare end of stream for this decoder:
26 // 1. FFmpeg didn't read anything.
27 // 2. FFmpeg didn't output anything.
28 // 3. An end of stream buffer is received.
29 return result == 0 && decoded_size == 0 && input->end_of_stream();
32 // Return the number of channels from the data in |frame|.
33 static inline int DetermineChannels(AVFrame* frame) {
34 #if defined(CHROMIUM_NO_AVFRAME_CHANNELS)
35 // When use_system_ffmpeg==1, libav's AVFrame doesn't have channels field.
36 return av_get_channel_layout_nb_channels(frame->channel_layout);
37 #else
38 return frame->channels;
39 #endif
42 // Called by FFmpeg's allocation routine to free a buffer. |opaque| is the
43 // AudioBuffer allocated, so unref it.
44 static void ReleaseAudioBufferImpl(void* opaque, uint8* data) {
45 scoped_refptr<AudioBuffer> buffer;
46 buffer.swap(reinterpret_cast<AudioBuffer**>(&opaque));
49 // Called by FFmpeg's allocation routine to allocate a buffer. Uses
50 // AVCodecContext.opaque to get the object reference in order to call
51 // GetAudioBuffer() to do the actual allocation.
52 static int GetAudioBuffer(struct AVCodecContext* s, AVFrame* frame, int flags) {
53 DCHECK(s->codec->capabilities & CODEC_CAP_DR1);
54 DCHECK_EQ(s->codec_type, AVMEDIA_TYPE_AUDIO);
56 // Since this routine is called by FFmpeg when a buffer is required for audio
57 // data, use the values supplied by FFmpeg (ignoring the current settings).
58 // FFmpegDecode() gets to determine if the buffer is useable or not.
59 AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
60 SampleFormat sample_format = AVSampleFormatToSampleFormat(format);
61 int channels = DetermineChannels(frame);
62 if (channels <= 0 || channels >= limits::kMaxChannels) {
63 DLOG(ERROR) << "Requested number of channels (" << channels
64 << ") exceeds limit.";
65 return AVERROR(EINVAL);
68 int bytes_per_channel = SampleFormatToBytesPerChannel(sample_format);
69 if (frame->nb_samples <= 0)
70 return AVERROR(EINVAL);
72 if (s->channels != channels) {
73 DLOG(ERROR) << "AVCodecContext and AVFrame disagree on channel count.";
74 return AVERROR(EINVAL);
77 // Determine how big the buffer should be and allocate it. FFmpeg may adjust
78 // how big each channel data is in order to meet the alignment policy, so
79 // we need to take this into consideration.
80 int buffer_size_in_bytes =
81 av_samples_get_buffer_size(&frame->linesize[0],
82 channels,
83 frame->nb_samples,
84 format,
85 AudioBuffer::kChannelAlignment);
86 // Check for errors from av_samples_get_buffer_size().
87 if (buffer_size_in_bytes < 0)
88 return buffer_size_in_bytes;
89 int frames_required = buffer_size_in_bytes / bytes_per_channel / channels;
90 DCHECK_GE(frames_required, frame->nb_samples);
91 scoped_refptr<AudioBuffer> buffer = AudioBuffer::CreateBuffer(
92 sample_format,
93 ChannelLayoutToChromeChannelLayout(s->channel_layout, s->channels),
94 channels,
95 s->sample_rate,
96 frames_required);
98 // Initialize the data[] and extended_data[] fields to point into the memory
99 // allocated for AudioBuffer. |number_of_planes| will be 1 for interleaved
100 // audio and equal to |channels| for planar audio.
101 int number_of_planes = buffer->channel_data().size();
102 if (number_of_planes <= AV_NUM_DATA_POINTERS) {
103 DCHECK_EQ(frame->extended_data, frame->data);
104 for (int i = 0; i < number_of_planes; ++i)
105 frame->data[i] = buffer->channel_data()[i];
106 } else {
107 // There are more channels than can fit into data[], so allocate
108 // extended_data[] and fill appropriately.
109 frame->extended_data = static_cast<uint8**>(
110 av_malloc(number_of_planes * sizeof(*frame->extended_data)));
111 int i = 0;
112 for (; i < AV_NUM_DATA_POINTERS; ++i)
113 frame->extended_data[i] = frame->data[i] = buffer->channel_data()[i];
114 for (; i < number_of_planes; ++i)
115 frame->extended_data[i] = buffer->channel_data()[i];
118 // Now create an AVBufferRef for the data just allocated. It will own the
119 // reference to the AudioBuffer object.
120 void* opaque = NULL;
121 buffer.swap(reinterpret_cast<AudioBuffer**>(&opaque));
122 frame->buf[0] = av_buffer_create(
123 frame->data[0], buffer_size_in_bytes, ReleaseAudioBufferImpl, opaque, 0);
124 return 0;
127 FFmpegAudioDecoder::FFmpegAudioDecoder(
128 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
129 const scoped_refptr<MediaLog>& media_log)
130 : task_runner_(task_runner),
131 state_(kUninitialized),
132 av_sample_format_(0),
133 media_log_(media_log) {
136 FFmpegAudioDecoder::~FFmpegAudioDecoder() {
137 DCHECK(task_runner_->BelongsToCurrentThread());
139 if (state_ != kUninitialized)
140 ReleaseFFmpegResources();
143 std::string FFmpegAudioDecoder::GetDisplayName() const {
144 return "FFmpegAudioDecoder";
147 void FFmpegAudioDecoder::Initialize(const AudioDecoderConfig& config,
148 const InitCB& init_cb,
149 const OutputCB& output_cb) {
150 DCHECK(task_runner_->BelongsToCurrentThread());
151 DCHECK(!config.is_encrypted());
153 FFmpegGlue::InitializeFFmpeg();
155 config_ = config;
156 InitCB bound_init_cb = BindToCurrentLoop(init_cb);
158 if (!config.IsValidConfig() || !ConfigureDecoder()) {
159 bound_init_cb.Run(false);
160 return;
163 // Success!
164 output_cb_ = BindToCurrentLoop(output_cb);
165 state_ = kNormal;
166 bound_init_cb.Run(true);
169 void FFmpegAudioDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
170 const DecodeCB& decode_cb) {
171 DCHECK(task_runner_->BelongsToCurrentThread());
172 DCHECK(!decode_cb.is_null());
173 CHECK_NE(state_, kUninitialized);
174 DecodeCB decode_cb_bound = BindToCurrentLoop(decode_cb);
176 if (state_ == kError) {
177 decode_cb_bound.Run(kDecodeError);
178 return;
181 // Do nothing if decoding has finished.
182 if (state_ == kDecodeFinished) {
183 decode_cb_bound.Run(kOk);
184 return;
187 DecodeBuffer(buffer, decode_cb_bound);
190 void FFmpegAudioDecoder::Reset(const base::Closure& closure) {
191 DCHECK(task_runner_->BelongsToCurrentThread());
193 avcodec_flush_buffers(codec_context_.get());
194 state_ = kNormal;
195 ResetTimestampState();
196 task_runner_->PostTask(FROM_HERE, closure);
199 void FFmpegAudioDecoder::DecodeBuffer(
200 const scoped_refptr<DecoderBuffer>& buffer,
201 const DecodeCB& decode_cb) {
202 DCHECK(task_runner_->BelongsToCurrentThread());
203 DCHECK_NE(state_, kUninitialized);
204 DCHECK_NE(state_, kDecodeFinished);
205 DCHECK_NE(state_, kError);
206 DCHECK(buffer.get());
208 // Make sure we are notified if http://crbug.com/49709 returns. Issue also
209 // occurs with some damaged files.
210 if (!buffer->end_of_stream() && buffer->timestamp() == kNoTimestamp()) {
211 DVLOG(1) << "Received a buffer without timestamps!";
212 decode_cb.Run(kDecodeError);
213 return;
216 bool has_produced_frame;
217 do {
218 has_produced_frame = false;
219 if (!FFmpegDecode(buffer, &has_produced_frame)) {
220 state_ = kError;
221 decode_cb.Run(kDecodeError);
222 return;
224 // Repeat to flush the decoder after receiving EOS buffer.
225 } while (buffer->end_of_stream() && has_produced_frame);
227 if (buffer->end_of_stream())
228 state_ = kDecodeFinished;
230 decode_cb.Run(kOk);
233 bool FFmpegAudioDecoder::FFmpegDecode(
234 const scoped_refptr<DecoderBuffer>& buffer,
235 bool* has_produced_frame) {
236 DCHECK(!*has_produced_frame);
238 AVPacket packet;
239 av_init_packet(&packet);
240 if (buffer->end_of_stream()) {
241 packet.data = NULL;
242 packet.size = 0;
243 } else {
244 packet.data = const_cast<uint8*>(buffer->data());
245 packet.size = buffer->data_size();
248 // Each audio packet may contain several frames, so we must call the decoder
249 // until we've exhausted the packet. Regardless of the packet size we always
250 // want to hand it to the decoder at least once, otherwise we would end up
251 // skipping end of stream packets since they have a size of zero.
252 do {
253 int frame_decoded = 0;
254 const int result = avcodec_decode_audio4(
255 codec_context_.get(), av_frame_.get(), &frame_decoded, &packet);
257 if (result < 0) {
258 DCHECK(!buffer->end_of_stream())
259 << "End of stream buffer produced an error! "
260 << "This is quite possibly a bug in the audio decoder not handling "
261 << "end of stream AVPackets correctly.";
263 MEDIA_LOG(DEBUG, media_log_)
264 << "Dropping audio frame which failed decode with timestamp: "
265 << buffer->timestamp().InMicroseconds()
266 << " us, duration: " << buffer->duration().InMicroseconds()
267 << " us, packet size: " << buffer->data_size() << " bytes";
269 break;
272 // Update packet size and data pointer in case we need to call the decoder
273 // with the remaining bytes from this packet.
274 packet.size -= result;
275 packet.data += result;
277 scoped_refptr<AudioBuffer> output;
278 const int channels = DetermineChannels(av_frame_.get());
279 if (frame_decoded) {
280 if (av_frame_->sample_rate != config_.samples_per_second() ||
281 channels != ChannelLayoutToChannelCount(config_.channel_layout()) ||
282 av_frame_->format != av_sample_format_) {
283 DLOG(ERROR) << "Unsupported midstream configuration change!"
284 << " Sample Rate: " << av_frame_->sample_rate << " vs "
285 << config_.samples_per_second()
286 << ", Channels: " << channels << " vs "
287 << ChannelLayoutToChannelCount(config_.channel_layout())
288 << ", Sample Format: " << av_frame_->format << " vs "
289 << av_sample_format_;
291 if (config_.codec() == kCodecAAC &&
292 av_frame_->sample_rate == 2 * config_.samples_per_second()) {
293 MEDIA_LOG(DEBUG, media_log_)
294 << "Implicit HE-AAC signalling is being"
295 << " used. Please use mp4a.40.5 instead of"
296 << " mp4a.40.2 in the mimetype.";
298 // This is an unrecoverable error, so bail out.
299 av_frame_unref(av_frame_.get());
300 return false;
303 // Get the AudioBuffer that the data was decoded into. Adjust the number
304 // of frames, in case fewer than requested were actually decoded.
305 output = reinterpret_cast<AudioBuffer*>(
306 av_buffer_get_opaque(av_frame_->buf[0]));
308 DCHECK_EQ(ChannelLayoutToChannelCount(config_.channel_layout()),
309 output->channel_count());
310 const int unread_frames = output->frame_count() - av_frame_->nb_samples;
311 DCHECK_GE(unread_frames, 0);
312 if (unread_frames > 0)
313 output->TrimEnd(unread_frames);
314 av_frame_unref(av_frame_.get());
317 // WARNING: |av_frame_| no longer has valid data at this point.
318 const int decoded_frames = frame_decoded ? output->frame_count() : 0;
319 if (IsEndOfStream(result, decoded_frames, buffer)) {
320 DCHECK_EQ(packet.size, 0);
321 } else if (discard_helper_->ProcessBuffers(buffer, output)) {
322 *has_produced_frame = true;
323 output_cb_.Run(output);
325 } while (packet.size > 0);
327 return true;
330 void FFmpegAudioDecoder::ReleaseFFmpegResources() {
331 codec_context_.reset();
332 av_frame_.reset();
335 bool FFmpegAudioDecoder::ConfigureDecoder() {
336 if (!config_.IsValidConfig()) {
337 DLOG(ERROR) << "Invalid audio stream -"
338 << " codec: " << config_.codec()
339 << " channel layout: " << config_.channel_layout()
340 << " bits per channel: " << config_.bits_per_channel()
341 << " samples per second: " << config_.samples_per_second();
342 return false;
345 if (config_.is_encrypted()) {
346 DLOG(ERROR) << "Encrypted audio stream not supported";
347 return false;
350 // Release existing decoder resources if necessary.
351 ReleaseFFmpegResources();
353 // Initialize AVCodecContext structure.
354 codec_context_.reset(avcodec_alloc_context3(NULL));
355 AudioDecoderConfigToAVCodecContext(config_, codec_context_.get());
357 codec_context_->opaque = this;
358 codec_context_->get_buffer2 = GetAudioBuffer;
359 codec_context_->refcounted_frames = 1;
361 AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
362 if (!codec || avcodec_open2(codec_context_.get(), codec, NULL) < 0) {
363 DLOG(ERROR) << "Could not initialize audio decoder: "
364 << codec_context_->codec_id;
365 ReleaseFFmpegResources();
366 state_ = kUninitialized;
367 return false;
370 // Success!
371 av_frame_.reset(av_frame_alloc());
372 av_sample_format_ = codec_context_->sample_fmt;
374 if (codec_context_->channels !=
375 ChannelLayoutToChannelCount(config_.channel_layout())) {
376 DLOG(ERROR) << "Audio configuration specified "
377 << ChannelLayoutToChannelCount(config_.channel_layout())
378 << " channels, but FFmpeg thinks the file contains "
379 << codec_context_->channels << " channels";
380 ReleaseFFmpegResources();
381 state_ = kUninitialized;
382 return false;
385 ResetTimestampState();
386 return true;
389 void FFmpegAudioDecoder::ResetTimestampState() {
390 discard_helper_.reset(new AudioDiscardHelper(config_.samples_per_second(),
391 config_.codec_delay()));
392 discard_helper_->Reset(config_.codec_delay());
395 } // namespace media