Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / media / filters / ffmpeg_audio_decoder.cc
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/ffmpeg_audio_decoder.h"
6
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/base/sample_format.h"
17 #include "media/ffmpeg/ffmpeg_common.h"
18 #include "media/filters/ffmpeg_glue.h"
19
20 namespace media {
21
22 // Returns true if the decode result was end of stream.
23 static inline bool IsEndOfStream(int result,
24                                  int decoded_size,
25                                  const scoped_refptr<DecoderBuffer>& input) {
26   // Three conditions to meet to declare end of stream for this decoder:
27   // 1. FFmpeg didn't read anything.
28   // 2. FFmpeg didn't output anything.
29   // 3. An end of stream buffer is received.
30   return result == 0 && decoded_size == 0 && input->end_of_stream();
31 }
32
33 // Return the number of channels from the data in |frame|.
34 static inline int DetermineChannels(AVFrame* frame) {
35 #if defined(CHROMIUM_NO_AVFRAME_CHANNELS)
36   // When use_system_ffmpeg==1, libav's AVFrame doesn't have channels field.
37   return av_get_channel_layout_nb_channels(frame->channel_layout);
38 #else
39   return frame->channels;
40 #endif
41 }
42
43 // Called by FFmpeg's allocation routine to free a buffer. |opaque| is the
44 // AudioBuffer allocated, so unref it.
45 static void ReleaseAudioBufferImpl(void* opaque, uint8* data) {
46   scoped_refptr<AudioBuffer> buffer;
47   buffer.swap(reinterpret_cast<AudioBuffer**>(&opaque));
48 }
49
50 // Called by FFmpeg's allocation routine to allocate a buffer. Uses
51 // AVCodecContext.opaque to get the object reference in order to call
52 // GetAudioBuffer() to do the actual allocation.
53 static int GetAudioBuffer(struct AVCodecContext* s, AVFrame* frame, int flags) {
54   DCHECK(s->codec->capabilities & CODEC_CAP_DR1);
55   DCHECK_EQ(s->codec_type, AVMEDIA_TYPE_AUDIO);
56
57   // Since this routine is called by FFmpeg when a buffer is required for audio
58   // data, use the values supplied by FFmpeg (ignoring the current settings).
59   // FFmpegDecode() gets to determine if the buffer is useable or not.
60   AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
61   SampleFormat sample_format = AVSampleFormatToSampleFormat(format);
62   int channels = DetermineChannels(frame);
63   if (channels <= 0 || channels >= limits::kMaxChannels) {
64     DLOG(ERROR) << "Requested number of channels (" << channels
65                 << ") exceeds limit.";
66     return AVERROR(EINVAL);
67   }
68
69   int bytes_per_channel = SampleFormatToBytesPerChannel(sample_format);
70   if (frame->nb_samples <= 0)
71     return AVERROR(EINVAL);
72
73   if (s->channels != channels) {
74     DLOG(ERROR) << "AVCodecContext and AVFrame disagree on channel count.";
75     return AVERROR(EINVAL);
76   }
77
78   // Determine how big the buffer should be and allocate it. FFmpeg may adjust
79   // how big each channel data is in order to meet the alignment policy, so
80   // we need to take this into consideration.
81   int buffer_size_in_bytes =
82       av_samples_get_buffer_size(&frame->linesize[0],
83                                  channels,
84                                  frame->nb_samples,
85                                  format,
86                                  AudioBuffer::kChannelAlignment);
87   // Check for errors from av_samples_get_buffer_size().
88   if (buffer_size_in_bytes < 0)
89     return buffer_size_in_bytes;
90   int frames_required = buffer_size_in_bytes / bytes_per_channel / channels;
91   DCHECK_GE(frames_required, frame->nb_samples);
92   scoped_refptr<AudioBuffer> buffer = AudioBuffer::CreateBuffer(
93       sample_format,
94       ChannelLayoutToChromeChannelLayout(s->channel_layout, s->channels),
95       channels,
96       s->sample_rate,
97       frames_required);
98
99   // Initialize the data[] and extended_data[] fields to point into the memory
100   // allocated for AudioBuffer. |number_of_planes| will be 1 for interleaved
101   // audio and equal to |channels| for planar audio.
102   int number_of_planes = buffer->channel_data().size();
103   if (number_of_planes <= AV_NUM_DATA_POINTERS) {
104     DCHECK_EQ(frame->extended_data, frame->data);
105     for (int i = 0; i < number_of_planes; ++i)
106       frame->data[i] = buffer->channel_data()[i];
107   } else {
108     // There are more channels than can fit into data[], so allocate
109     // extended_data[] and fill appropriately.
110     frame->extended_data = static_cast<uint8**>(
111         av_malloc(number_of_planes * sizeof(*frame->extended_data)));
112     int i = 0;
113     for (; i < AV_NUM_DATA_POINTERS; ++i)
114       frame->extended_data[i] = frame->data[i] = buffer->channel_data()[i];
115     for (; i < number_of_planes; ++i)
116       frame->extended_data[i] = buffer->channel_data()[i];
117   }
118
119   // Now create an AVBufferRef for the data just allocated. It will own the
120   // reference to the AudioBuffer object.
121   void* opaque = NULL;
122   buffer.swap(reinterpret_cast<AudioBuffer**>(&opaque));
123   frame->buf[0] = av_buffer_create(
124       frame->data[0], buffer_size_in_bytes, ReleaseAudioBufferImpl, opaque, 0);
125   return 0;
126 }
127
128 FFmpegAudioDecoder::FFmpegAudioDecoder(
129     const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
130     const LogCB& log_cb)
131     : task_runner_(task_runner),
132       state_(kUninitialized),
133       av_sample_format_(0),
134       log_cb_(log_cb) {
135 }
136
137 FFmpegAudioDecoder::~FFmpegAudioDecoder() {
138   DCHECK_EQ(state_, kUninitialized);
139   DCHECK(!codec_context_);
140   DCHECK(!av_frame_);
141 }
142
143 void FFmpegAudioDecoder::Initialize(const AudioDecoderConfig& config,
144                                     const PipelineStatusCB& status_cb) {
145   DCHECK(task_runner_->BelongsToCurrentThread());
146   DCHECK(!config.is_encrypted());
147
148   FFmpegGlue::InitializeFFmpeg();
149
150   config_ = config;
151   PipelineStatusCB initialize_cb = BindToCurrentLoop(status_cb);
152
153   if (!config.IsValidConfig() || !ConfigureDecoder()) {
154     initialize_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
155     return;
156   }
157
158   // Success!
159   state_ = kNormal;
160   initialize_cb.Run(PIPELINE_OK);
161 }
162
163 void FFmpegAudioDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
164                                 const DecodeCB& decode_cb) {
165   DCHECK(task_runner_->BelongsToCurrentThread());
166   DCHECK(!decode_cb.is_null());
167   CHECK_NE(state_, kUninitialized);
168   DecodeCB decode_cb_bound = BindToCurrentLoop(decode_cb);
169
170   if (state_ == kError) {
171     decode_cb_bound.Run(kDecodeError, NULL);
172     return;
173   }
174
175   // Return empty frames if decoding has finished.
176   if (state_ == kDecodeFinished) {
177     decode_cb_bound.Run(kOk, AudioBuffer::CreateEOSBuffer());
178     return;
179   }
180
181   if (!buffer) {
182     decode_cb_bound.Run(kAborted, NULL);
183     return;
184   }
185
186   DecodeBuffer(buffer, decode_cb_bound);
187 }
188
189 scoped_refptr<AudioBuffer> FFmpegAudioDecoder::GetDecodeOutput() {
190   DCHECK(task_runner_->BelongsToCurrentThread());
191   if (queued_audio_.empty())
192     return NULL;
193   scoped_refptr<AudioBuffer> out = queued_audio_.front();
194   queued_audio_.pop_front();
195   return out;
196 }
197
198 void FFmpegAudioDecoder::Reset(const base::Closure& closure) {
199   DCHECK(task_runner_->BelongsToCurrentThread());
200
201   avcodec_flush_buffers(codec_context_.get());
202   state_ = kNormal;
203   ResetTimestampState();
204   task_runner_->PostTask(FROM_HERE, closure);
205 }
206
207 void FFmpegAudioDecoder::Stop() {
208   DCHECK(task_runner_->BelongsToCurrentThread());
209
210   if (state_ == kUninitialized)
211     return;
212
213   ReleaseFFmpegResources();
214   ResetTimestampState();
215   state_ = kUninitialized;
216 }
217
218 void FFmpegAudioDecoder::DecodeBuffer(
219     const scoped_refptr<DecoderBuffer>& buffer,
220     const DecodeCB& decode_cb) {
221   DCHECK(task_runner_->BelongsToCurrentThread());
222   DCHECK_NE(state_, kUninitialized);
223   DCHECK_NE(state_, kDecodeFinished);
224   DCHECK_NE(state_, kError);
225
226   DCHECK(buffer);
227
228   // During decode, because reads are issued asynchronously, it is possible to
229   // receive multiple end of stream buffers since each decode is acked. When the
230   // first end of stream buffer is read, FFmpeg may still have frames queued
231   // up in the decoder so we need to go through the decode loop until it stops
232   // giving sensible data.  After that, the decoder should output empty
233   // frames.  There are three states the decoder can be in:
234   //
235   //   kNormal: This is the starting state. Buffers are decoded. Decode errors
236   //            are discarded.
237   //   kFlushCodec: There isn't any more input data. Call avcodec_decode_audio4
238   //                until no more data is returned to flush out remaining
239   //                frames. The input buffer is ignored at this point.
240   //   kDecodeFinished: All calls return empty frames.
241   //   kError: Unexpected error happened.
242   //
243   // These are the possible state transitions.
244   //
245   // kNormal -> kFlushCodec:
246   //     When buffer->end_of_stream() is first true.
247   // kNormal -> kError:
248   //     A decoding error occurs and decoding needs to stop.
249   // kFlushCodec -> kDecodeFinished:
250   //     When avcodec_decode_audio4() returns 0 data.
251   // kFlushCodec -> kError:
252   //     When avcodec_decode_audio4() errors out.
253   // (any state) -> kNormal:
254   //     Any time Reset() is called.
255
256   // Make sure we are notified if http://crbug.com/49709 returns.  Issue also
257   // occurs with some damaged files.
258   if (!buffer->end_of_stream() && buffer->timestamp() == kNoTimestamp()) {
259     DVLOG(1) << "Received a buffer without timestamps!";
260     decode_cb.Run(kDecodeError, NULL);
261     return;
262   }
263
264   if (!buffer->end_of_stream() && !discard_helper_->initialized() &&
265       codec_context_->codec_id == AV_CODEC_ID_VORBIS &&
266       buffer->timestamp() < base::TimeDelta()) {
267     // Dropping frames for negative timestamps as outlined in section A.2
268     // in the Vorbis spec. http://xiph.org/vorbis/doc/Vorbis_I_spec.html
269     const int discard_frames =
270         discard_helper_->TimeDeltaToFrames(-buffer->timestamp());
271     discard_helper_->Reset(discard_frames);
272   }
273
274   // Transition to kFlushCodec on the first end of stream buffer.
275   if (state_ == kNormal && buffer->end_of_stream()) {
276     state_ = kFlushCodec;
277   }
278
279   if (!FFmpegDecode(buffer)) {
280     state_ = kError;
281     decode_cb.Run(kDecodeError, NULL);
282     return;
283   }
284
285   if (queued_audio_.empty()) {
286     if (state_ == kFlushCodec) {
287       DCHECK(buffer->end_of_stream());
288       state_ = kDecodeFinished;
289       decode_cb.Run(kOk, AudioBuffer::CreateEOSBuffer());
290       return;
291     }
292
293     decode_cb.Run(kNotEnoughData, NULL);
294     return;
295   }
296
297   decode_cb.Run(kOk, queued_audio_.front());
298   queued_audio_.pop_front();
299 }
300
301 bool FFmpegAudioDecoder::FFmpegDecode(
302     const scoped_refptr<DecoderBuffer>& buffer) {
303   DCHECK(queued_audio_.empty());
304
305   AVPacket packet;
306   av_init_packet(&packet);
307   if (buffer->end_of_stream()) {
308     packet.data = NULL;
309     packet.size = 0;
310   } else {
311     packet.data = const_cast<uint8*>(buffer->data());
312     packet.size = buffer->data_size();
313   }
314
315   // Each audio packet may contain several frames, so we must call the decoder
316   // until we've exhausted the packet.  Regardless of the packet size we always
317   // want to hand it to the decoder at least once, otherwise we would end up
318   // skipping end of stream packets since they have a size of zero.
319   do {
320     int frame_decoded = 0;
321     const int result = avcodec_decode_audio4(
322         codec_context_.get(), av_frame_.get(), &frame_decoded, &packet);
323
324     if (result < 0) {
325       DCHECK(!buffer->end_of_stream())
326           << "End of stream buffer produced an error! "
327           << "This is quite possibly a bug in the audio decoder not handling "
328           << "end of stream AVPackets correctly.";
329
330       DLOG(WARNING)
331           << "Failed to decode an audio frame with timestamp: "
332           << buffer->timestamp().InMicroseconds() << " us, duration: "
333           << buffer->duration().InMicroseconds() << " us, packet size: "
334           << buffer->data_size() << " bytes";
335
336       break;
337     }
338
339     // Update packet size and data pointer in case we need to call the decoder
340     // with the remaining bytes from this packet.
341     packet.size -= result;
342     packet.data += result;
343
344     scoped_refptr<AudioBuffer> output;
345     const int channels = DetermineChannels(av_frame_.get());
346     if (frame_decoded) {
347       if (av_frame_->sample_rate != config_.samples_per_second() ||
348           channels != ChannelLayoutToChannelCount(config_.channel_layout()) ||
349           av_frame_->format != av_sample_format_) {
350         DLOG(ERROR) << "Unsupported midstream configuration change!"
351                     << " Sample Rate: " << av_frame_->sample_rate << " vs "
352                     << config_.samples_per_second()
353                     << ", Channels: " << channels << " vs "
354                     << ChannelLayoutToChannelCount(config_.channel_layout())
355                     << ", Sample Format: " << av_frame_->format << " vs "
356                     << av_sample_format_;
357
358         if (config_.codec() == kCodecAAC &&
359             av_frame_->sample_rate == 2 * config_.samples_per_second()) {
360           MEDIA_LOG(log_cb_) << "Implicit HE-AAC signalling is being used."
361                              << " Please use mp4a.40.5 instead of mp4a.40.2 in"
362                              << " the mimetype.";
363         }
364         // This is an unrecoverable error, so bail out.
365         queued_audio_.clear();
366         av_frame_unref(av_frame_.get());
367         return false;
368       }
369
370       // Get the AudioBuffer that the data was decoded into. Adjust the number
371       // of frames, in case fewer than requested were actually decoded.
372       output = reinterpret_cast<AudioBuffer*>(
373           av_buffer_get_opaque(av_frame_->buf[0]));
374
375       DCHECK_EQ(ChannelLayoutToChannelCount(config_.channel_layout()),
376                 output->channel_count());
377       const int unread_frames = output->frame_count() - av_frame_->nb_samples;
378       DCHECK_GE(unread_frames, 0);
379       if (unread_frames > 0)
380         output->TrimEnd(unread_frames);
381
382       av_frame_unref(av_frame_.get());
383     }
384
385     // WARNING: |av_frame_| no longer has valid data at this point.
386     const int decoded_frames = frame_decoded ? output->frame_count() : 0;
387     if (IsEndOfStream(result, decoded_frames, buffer)) {
388       DCHECK_EQ(packet.size, 0);
389       queued_audio_.push_back(AudioBuffer::CreateEOSBuffer());
390     } else if (discard_helper_->ProcessBuffers(buffer, output)) {
391       queued_audio_.push_back(output);
392     }
393   } while (packet.size > 0);
394
395   return true;
396 }
397
398 void FFmpegAudioDecoder::ReleaseFFmpegResources() {
399   codec_context_.reset();
400   av_frame_.reset();
401 }
402
403 bool FFmpegAudioDecoder::ConfigureDecoder() {
404   if (!config_.IsValidConfig()) {
405     DLOG(ERROR) << "Invalid audio stream -"
406                 << " codec: " << config_.codec()
407                 << " channel layout: " << config_.channel_layout()
408                 << " bits per channel: " << config_.bits_per_channel()
409                 << " samples per second: " << config_.samples_per_second();
410     return false;
411   }
412
413   if (config_.is_encrypted()) {
414     DLOG(ERROR) << "Encrypted audio stream not supported";
415     return false;
416   }
417
418   // Release existing decoder resources if necessary.
419   ReleaseFFmpegResources();
420
421   // Initialize AVCodecContext structure.
422   codec_context_.reset(avcodec_alloc_context3(NULL));
423   AudioDecoderConfigToAVCodecContext(config_, codec_context_.get());
424
425   codec_context_->opaque = this;
426   codec_context_->get_buffer2 = GetAudioBuffer;
427   codec_context_->refcounted_frames = 1;
428
429   AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
430   if (!codec || avcodec_open2(codec_context_.get(), codec, NULL) < 0) {
431     DLOG(ERROR) << "Could not initialize audio decoder: "
432                 << codec_context_->codec_id;
433     ReleaseFFmpegResources();
434     state_ = kUninitialized;
435     return false;
436   }
437
438   // Success!
439   av_frame_.reset(av_frame_alloc());
440   discard_helper_.reset(new AudioDiscardHelper(config_.samples_per_second(),
441                                                config_.codec_delay()));
442   av_sample_format_ = codec_context_->sample_fmt;
443
444   if (codec_context_->channels !=
445       ChannelLayoutToChannelCount(config_.channel_layout())) {
446     DLOG(ERROR) << "Audio configuration specified "
447                 << ChannelLayoutToChannelCount(config_.channel_layout())
448                 << " channels, but FFmpeg thinks the file contains "
449                 << codec_context_->channels << " channels";
450     ReleaseFFmpegResources();
451     state_ = kUninitialized;
452     return false;
453   }
454
455   ResetTimestampState();
456   return true;
457 }
458
459 void FFmpegAudioDecoder::ResetTimestampState() {
460   discard_helper_->Reset(config_.codec_delay());
461 }
462
463 }  // namespace media