Revert of Set defaultPageScaleLimits before setIgnoreViewportTagScaleLimits (patchset...
[chromium-blink-merge.git] / media / filters / audio_decoder_unittest.cc
blob42b00ee13b8118448597b277e622f1387856a10b
1 // Copyright 2014 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 <deque>
7 #include "base/bind.h"
8 #include "base/format_macros.h"
9 #include "base/md5.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/run_loop.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/sys_byteorder.h"
14 #include "build/build_config.h"
15 #include "media/base/audio_buffer.h"
16 #include "media/base/audio_bus.h"
17 #include "media/base/audio_hash.h"
18 #include "media/base/decoder_buffer.h"
19 #include "media/base/test_data_util.h"
20 #include "media/base/test_helpers.h"
21 #include "media/ffmpeg/ffmpeg_common.h"
22 #include "media/filters/audio_file_reader.h"
23 #include "media/filters/ffmpeg_audio_decoder.h"
24 #include "media/filters/in_memory_url_protocol.h"
25 #include "media/filters/opus_audio_decoder.h"
26 #include "testing/gtest/include/gtest/gtest.h"
28 namespace media {
30 // The number of packets to read and then decode from each file.
31 static const size_t kDecodeRuns = 3;
32 static const uint8_t kOpusExtraData[] = {
33 0x4f, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64, 0x01, 0x02,
34 // The next two bytes represent the codec delay.
35 0x00, 0x00, 0x80, 0xbb, 0x00, 0x00, 0x00, 0x00, 0x00};
37 enum AudioDecoderType {
38 FFMPEG,
39 OPUS,
42 struct DecodedBufferExpectations {
43 const int64 timestamp;
44 const int64 duration;
45 const char* hash;
48 struct DecoderTestData {
49 const AudioDecoderType decoder_type;
50 const AudioCodec codec;
51 const char* filename;
52 const DecodedBufferExpectations* expectations;
53 const int first_packet_pts;
54 const int samples_per_second;
55 const ChannelLayout channel_layout;
58 // Tells gtest how to print our DecoderTestData structure.
59 std::ostream& operator<<(std::ostream& os, const DecoderTestData& data) {
60 return os << data.filename;
63 // Marks negative timestamp buffers for discard or transfers FFmpeg's built in
64 // discard metadata in favor of setting DiscardPadding on the DecoderBuffer.
65 // Allows better testing of AudioDiscardHelper usage.
66 static void SetDiscardPadding(AVPacket* packet,
67 const scoped_refptr<DecoderBuffer> buffer,
68 double samples_per_second) {
69 // Discard negative timestamps.
70 if (buffer->timestamp() + buffer->duration() < base::TimeDelta()) {
71 buffer->set_discard_padding(
72 std::make_pair(kInfiniteDuration(), base::TimeDelta()));
73 return;
75 if (buffer->timestamp() < base::TimeDelta()) {
76 buffer->set_discard_padding(
77 std::make_pair(-buffer->timestamp(), base::TimeDelta()));
78 return;
81 // If the timestamp is positive, try to use FFmpeg's discard data.
82 int skip_samples_size = 0;
83 const uint32* skip_samples_ptr =
84 reinterpret_cast<const uint32*>(av_packet_get_side_data(
85 packet, AV_PKT_DATA_SKIP_SAMPLES, &skip_samples_size));
86 if (skip_samples_size < 4)
87 return;
88 buffer->set_discard_padding(std::make_pair(
89 base::TimeDelta::FromSecondsD(base::ByteSwapToLE32(*skip_samples_ptr) /
90 samples_per_second),
91 base::TimeDelta()));
94 class AudioDecoderTest : public testing::TestWithParam<DecoderTestData> {
95 public:
96 AudioDecoderTest()
97 : pending_decode_(false),
98 pending_reset_(false),
99 last_decode_status_(AudioDecoder::kDecodeError) {
100 switch (GetParam().decoder_type) {
101 case FFMPEG:
102 decoder_.reset(new FFmpegAudioDecoder(
103 message_loop_.message_loop_proxy(), LogCB()));
104 break;
105 case OPUS:
106 decoder_.reset(
107 new OpusAudioDecoder(message_loop_.message_loop_proxy()));
108 break;
112 virtual ~AudioDecoderTest() {
113 EXPECT_FALSE(pending_decode_);
114 EXPECT_FALSE(pending_reset_);
117 protected:
118 void DecodeBuffer(const scoped_refptr<DecoderBuffer>& buffer) {
119 ASSERT_FALSE(pending_decode_);
120 pending_decode_ = true;
121 last_decode_status_ = AudioDecoder::kDecodeError;
122 decoder_->Decode(
123 buffer,
124 base::Bind(&AudioDecoderTest::DecodeFinished, base::Unretained(this)));
125 base::RunLoop().RunUntilIdle();
126 ASSERT_FALSE(pending_decode_);
129 void SendEndOfStream() {
130 DecodeBuffer(DecoderBuffer::CreateEOSBuffer());
133 void Initialize() {
134 // Load the test data file.
135 data_ = ReadTestDataFile(GetParam().filename);
136 protocol_.reset(
137 new InMemoryUrlProtocol(data_->data(), data_->data_size(), false));
138 reader_.reset(new AudioFileReader(protocol_.get()));
139 ASSERT_TRUE(reader_->OpenDemuxerForTesting());
141 // Load the first packet and check its timestamp.
142 AVPacket packet;
143 ASSERT_TRUE(reader_->ReadPacketForTesting(&packet));
144 EXPECT_EQ(GetParam().first_packet_pts, packet.pts);
145 start_timestamp_ = ConvertFromTimeBase(
146 reader_->GetAVStreamForTesting()->time_base, packet.pts);
147 av_free_packet(&packet);
149 // Seek back to the beginning.
150 ASSERT_TRUE(reader_->SeekForTesting(start_timestamp_));
152 AudioDecoderConfig config;
153 AVCodecContextToAudioDecoderConfig(
154 reader_->codec_context_for_testing(), false, &config, false);
156 EXPECT_EQ(GetParam().codec, config.codec());
157 EXPECT_EQ(GetParam().samples_per_second, config.samples_per_second());
158 EXPECT_EQ(GetParam().channel_layout, config.channel_layout());
160 InitializeDecoder(config);
163 void InitializeDecoder(const AudioDecoderConfig& config) {
164 InitializeDecoderWithStatus(config, PIPELINE_OK);
167 void InitializeDecoderWithStatus(const AudioDecoderConfig& config,
168 PipelineStatus status) {
169 decoder_->Initialize(
170 config,
171 NewExpectedStatusCB(status),
172 base::Bind(&AudioDecoderTest::OnDecoderOutput, base::Unretained(this)));
173 base::RunLoop().RunUntilIdle();
176 void Decode() {
177 AVPacket packet;
178 ASSERT_TRUE(reader_->ReadPacketForTesting(&packet));
180 // Split out packet metadata before making a copy.
181 av_packet_split_side_data(&packet);
183 scoped_refptr<DecoderBuffer> buffer =
184 DecoderBuffer::CopyFrom(packet.data, packet.size);
185 buffer->set_timestamp(ConvertFromTimeBase(
186 reader_->GetAVStreamForTesting()->time_base, packet.pts));
187 buffer->set_duration(ConvertFromTimeBase(
188 reader_->GetAVStreamForTesting()->time_base, packet.duration));
189 if (packet.flags & AV_PKT_FLAG_KEY)
190 buffer->set_is_key_frame(true);
192 // Don't set discard padding for Opus, it already has discard behavior set
193 // based on the codec delay in the AudioDecoderConfig.
194 if (GetParam().decoder_type == FFMPEG)
195 SetDiscardPadding(&packet, buffer, GetParam().samples_per_second);
197 // DecodeBuffer() shouldn't need the original packet since it uses the copy.
198 av_free_packet(&packet);
199 DecodeBuffer(buffer);
202 void Reset() {
203 ASSERT_FALSE(pending_reset_);
204 pending_reset_ = true;
205 decoder_->Reset(
206 base::Bind(&AudioDecoderTest::ResetFinished, base::Unretained(this)));
207 base::RunLoop().RunUntilIdle();
208 ASSERT_FALSE(pending_reset_);
211 void Seek(base::TimeDelta seek_time) {
212 Reset();
213 decoded_audio_.clear();
214 ASSERT_TRUE(reader_->SeekForTesting(seek_time));
217 void OnDecoderOutput(const scoped_refptr<AudioBuffer>& buffer) {
218 EXPECT_FALSE(buffer->end_of_stream());
219 decoded_audio_.push_back(buffer);
222 void DecodeFinished(AudioDecoder::Status status) {
223 EXPECT_TRUE(pending_decode_);
224 EXPECT_FALSE(pending_reset_);
225 pending_decode_ = false;
226 last_decode_status_ = status;
229 void ResetFinished() {
230 EXPECT_TRUE(pending_reset_);
231 EXPECT_FALSE(pending_decode_);
232 pending_reset_ = false;
235 // Generates an MD5 hash of the audio signal. Should not be used for checks
236 // across platforms as audio varies slightly across platforms.
237 std::string GetDecodedAudioMD5(size_t i) {
238 CHECK_LT(i, decoded_audio_.size());
239 const scoped_refptr<AudioBuffer>& buffer = decoded_audio_[i];
241 scoped_ptr<AudioBus> output =
242 AudioBus::Create(buffer->channel_count(), buffer->frame_count());
243 buffer->ReadFrames(buffer->frame_count(), 0, 0, output.get());
245 base::MD5Context context;
246 base::MD5Init(&context);
247 for (int ch = 0; ch < output->channels(); ++ch) {
248 base::MD5Update(
249 &context,
250 base::StringPiece(reinterpret_cast<char*>(output->channel(ch)),
251 output->frames() * sizeof(*output->channel(ch))));
253 base::MD5Digest digest;
254 base::MD5Final(&digest, &context);
255 return base::MD5DigestToBase16(digest);
258 void ExpectDecodedAudio(size_t i, const std::string& exact_hash) {
259 CHECK_LT(i, decoded_audio_.size());
260 const scoped_refptr<AudioBuffer>& buffer = decoded_audio_[i];
262 const DecodedBufferExpectations& sample_info = GetParam().expectations[i];
263 EXPECT_EQ(sample_info.timestamp, buffer->timestamp().InMicroseconds());
264 EXPECT_EQ(sample_info.duration, buffer->duration().InMicroseconds());
265 EXPECT_FALSE(buffer->end_of_stream());
267 scoped_ptr<AudioBus> output =
268 AudioBus::Create(buffer->channel_count(), buffer->frame_count());
269 buffer->ReadFrames(buffer->frame_count(), 0, 0, output.get());
271 // Generate a lossy hash of the audio used for comparison across platforms.
272 AudioHash audio_hash;
273 audio_hash.Update(output.get(), output->frames());
274 EXPECT_EQ(sample_info.hash, audio_hash.ToString());
276 if (!exact_hash.empty()) {
277 EXPECT_EQ(exact_hash, GetDecodedAudioMD5(i));
279 // Verify different hashes are being generated. None of our test data
280 // files have audio that hashes out exactly the same.
281 if (i > 0)
282 EXPECT_NE(exact_hash, GetDecodedAudioMD5(i - 1));
286 size_t decoded_audio_size() const { return decoded_audio_.size(); }
287 base::TimeDelta start_timestamp() const { return start_timestamp_; }
288 const scoped_refptr<AudioBuffer>& decoded_audio(size_t i) {
289 return decoded_audio_[i];
291 AudioDecoder::Status last_decode_status() const {
292 return last_decode_status_;
295 private:
296 base::MessageLoop message_loop_;
297 scoped_refptr<DecoderBuffer> data_;
298 scoped_ptr<InMemoryUrlProtocol> protocol_;
299 scoped_ptr<AudioFileReader> reader_;
301 scoped_ptr<AudioDecoder> decoder_;
302 bool pending_decode_;
303 bool pending_reset_;
304 AudioDecoder::Status last_decode_status_;
306 std::deque<scoped_refptr<AudioBuffer> > decoded_audio_;
307 base::TimeDelta start_timestamp_;
309 DISALLOW_COPY_AND_ASSIGN(AudioDecoderTest);
312 class OpusAudioDecoderBehavioralTest : public AudioDecoderTest {};
313 class FFmpegAudioDecoderBehavioralTest : public AudioDecoderTest {};
315 TEST_P(AudioDecoderTest, Initialize) {
316 ASSERT_NO_FATAL_FAILURE(Initialize());
319 // Verifies decode audio as well as the Decode() -> Reset() sequence.
320 TEST_P(AudioDecoderTest, ProduceAudioSamples) {
321 ASSERT_NO_FATAL_FAILURE(Initialize());
323 // Run the test multiple times with a seek back to the beginning in between.
324 std::vector<std::string> decoded_audio_md5_hashes;
325 for (int i = 0; i < 2; ++i) {
326 for (size_t j = 0; j < kDecodeRuns; ++j) {
327 do {
328 Decode();
329 ASSERT_EQ(last_decode_status(), AudioDecoder::kOk);
330 // Some codecs have a multiple buffer delay and require an extra
331 // Decode() step to extract the desired number of output buffers.
332 } while (j == 0 && decoded_audio_size() == 0);
334 // On the first pass record the exact MD5 hash for each decoded buffer.
335 if (i == 0)
336 decoded_audio_md5_hashes.push_back(GetDecodedAudioMD5(j));
339 ASSERT_EQ(kDecodeRuns, decoded_audio_size());
341 // On the first pass verify the basic audio hash and sample info. On the
342 // second, verify the exact MD5 sum for each packet. It shouldn't change.
343 for (size_t j = 0; j < kDecodeRuns; ++j) {
344 SCOPED_TRACE(base::StringPrintf("i = %d, j = %" PRIuS, i, j));
345 ExpectDecodedAudio(j, i == 0 ? "" : decoded_audio_md5_hashes[j]);
348 SendEndOfStream();
349 ASSERT_EQ(kDecodeRuns, decoded_audio_size());
351 // Seek back to the beginning. Calls Reset() on the decoder.
352 Seek(start_timestamp());
356 TEST_P(AudioDecoderTest, Decode) {
357 ASSERT_NO_FATAL_FAILURE(Initialize());
358 Decode();
359 EXPECT_EQ(AudioDecoder::kOk, last_decode_status());
362 TEST_P(AudioDecoderTest, Reset) {
363 ASSERT_NO_FATAL_FAILURE(Initialize());
364 Reset();
367 TEST_P(AudioDecoderTest, NoTimestamp) {
368 ASSERT_NO_FATAL_FAILURE(Initialize());
369 scoped_refptr<DecoderBuffer> buffer(new DecoderBuffer(0));
370 buffer->set_timestamp(kNoTimestamp());
371 DecodeBuffer(buffer);
372 EXPECT_EQ(AudioDecoder::kDecodeError, last_decode_status());
375 TEST_P(OpusAudioDecoderBehavioralTest, InitializeWithNoCodecDelay) {
376 ASSERT_EQ(GetParam().decoder_type, OPUS);
377 AudioDecoderConfig decoder_config;
378 decoder_config.Initialize(kCodecOpus,
379 kSampleFormatF32,
380 CHANNEL_LAYOUT_STEREO,
381 48000,
382 kOpusExtraData,
383 arraysize(kOpusExtraData),
384 false,
385 false,
386 base::TimeDelta::FromMilliseconds(80),
388 InitializeDecoder(decoder_config);
391 TEST_P(OpusAudioDecoderBehavioralTest, InitializeWithBadCodecDelay) {
392 ASSERT_EQ(GetParam().decoder_type, OPUS);
393 AudioDecoderConfig decoder_config;
394 decoder_config.Initialize(
395 kCodecOpus,
396 kSampleFormatF32,
397 CHANNEL_LAYOUT_STEREO,
398 48000,
399 kOpusExtraData,
400 arraysize(kOpusExtraData),
401 false,
402 false,
403 base::TimeDelta::FromMilliseconds(80),
404 // Use a different codec delay than in the extradata.
405 100);
406 InitializeDecoderWithStatus(decoder_config, DECODER_ERROR_NOT_SUPPORTED);
409 TEST_P(FFmpegAudioDecoderBehavioralTest, InitializeWithBadConfig) {
410 const AudioDecoderConfig decoder_config(kCodecVorbis,
411 kSampleFormatF32,
412 CHANNEL_LAYOUT_STEREO,
413 // Invalid sample rate of zero.
415 NULL,
417 false);
418 InitializeDecoderWithStatus(decoder_config, DECODER_ERROR_NOT_SUPPORTED);
421 const DecodedBufferExpectations kSfxOpusExpectations[] = {
422 {0, 13500, "-2.70,-1.41,-0.78,-1.27,-2.56,-3.73,"},
423 {13500, 20000, "5.48,5.93,6.04,5.83,5.54,5.45,"},
424 {33500, 20000, "-3.45,-3.35,-3.57,-4.12,-4.74,-5.14,"},
427 const DecodedBufferExpectations kBearOpusExpectations[] = {
428 {500, 3500, "-0.26,0.87,1.36,0.84,-0.30,-1.22,"},
429 {4000, 10000, "0.09,0.23,0.21,0.03,-0.17,-0.24,"},
430 {14000, 10000, "0.10,0.24,0.23,0.04,-0.14,-0.23,"},
433 const DecoderTestData kOpusTests[] = {
434 {OPUS, kCodecOpus, "sfx-opus.ogg", kSfxOpusExpectations, -312, 48000,
435 CHANNEL_LAYOUT_MONO},
436 {OPUS, kCodecOpus, "bear-opus.ogg", kBearOpusExpectations, 24, 48000,
437 CHANNEL_LAYOUT_STEREO},
440 // Dummy data for behavioral tests.
441 const DecoderTestData kOpusBehavioralTest[] = {
442 {OPUS, kUnknownAudioCodec, "", NULL, 0, 0, CHANNEL_LAYOUT_NONE},
445 INSTANTIATE_TEST_CASE_P(OpusAudioDecoderTest,
446 AudioDecoderTest,
447 testing::ValuesIn(kOpusTests));
448 INSTANTIATE_TEST_CASE_P(OpusAudioDecoderBehavioralTest,
449 OpusAudioDecoderBehavioralTest,
450 testing::ValuesIn(kOpusBehavioralTest));
452 #if defined(USE_PROPRIETARY_CODECS)
453 const DecodedBufferExpectations kSfxMp3Expectations[] = {
454 {0, 1065, "2.81,3.99,4.53,4.10,3.08,2.46,"},
455 {1065, 26122, "-3.81,-4.14,-3.90,-3.36,-3.03,-3.23,"},
456 {27188, 26122, "4.24,3.95,4.22,4.78,5.13,4.93,"},
459 const DecodedBufferExpectations kSfxAdtsExpectations[] = {
460 {0, 23219, "-1.90,-1.53,-0.15,1.28,1.23,-0.33,"},
461 {23219, 23219, "0.54,0.88,2.19,3.54,3.24,1.63,"},
462 {46439, 23219, "1.42,1.69,2.95,4.23,4.02,2.36,"},
464 #endif
466 #if defined(OS_CHROMEOS)
467 const DecodedBufferExpectations kSfxFlacExpectations[] = {
468 {0, 104489, "-2.42,-1.12,0.71,1.70,1.09,-0.68,"},
469 {104489, 104489, "-1.99,-0.67,1.18,2.19,1.60,-0.16,"},
470 {208979, 79433, "2.84,2.70,3.23,4.06,4.59,4.44,"},
472 #endif
474 const DecodedBufferExpectations kSfxWaveExpectations[] = {
475 {0, 23219, "-1.23,-0.87,0.47,1.85,1.88,0.29,"},
476 {23219, 23219, "0.75,1.10,2.43,3.78,3.53,1.93,"},
477 {46439, 23219, "1.27,1.56,2.83,4.13,3.87,2.23,"},
480 const DecodedBufferExpectations kFourChannelWaveExpectations[] = {
481 {0, 11609, "-1.68,1.68,0.89,-3.45,1.52,1.15,"},
482 {11609, 11609, "43.26,9.06,18.27,35.98,19.45,7.46,"},
483 {23219, 11609, "36.37,9.45,16.04,27.67,18.81,10.15,"},
486 const DecodedBufferExpectations kSfxOggExpectations[] = {
487 {0, 13061, "-0.33,1.25,2.86,3.26,2.09,0.14,"},
488 {13061, 23219, "-2.79,-2.42,-1.06,0.33,0.93,-0.64,"},
489 {36281, 23219, "-1.19,-0.80,0.57,1.97,2.08,0.51,"},
492 const DecodedBufferExpectations kBearOgvExpectations[] = {
493 {0, 13061, "-1.25,0.10,2.11,2.29,1.50,-0.68,"},
494 {13061, 23219, "-1.80,-1.41,-0.13,1.30,1.65,0.01,"},
495 {36281, 23219, "-1.43,-1.25,0.11,1.29,1.86,0.14,"},
498 const DecoderTestData kFFmpegTests[] = {
499 #if defined(USE_PROPRIETARY_CODECS)
500 {FFMPEG, kCodecMP3, "sfx.mp3", kSfxMp3Expectations, 0, 44100,
501 CHANNEL_LAYOUT_MONO},
502 {FFMPEG, kCodecAAC, "sfx.adts", kSfxAdtsExpectations, 0, 44100,
503 CHANNEL_LAYOUT_MONO},
504 #endif
505 #if defined(OS_CHROMEOS)
506 {FFMPEG, kCodecFLAC, "sfx.flac", kSfxFlacExpectations, 0, 44100,
507 CHANNEL_LAYOUT_MONO},
508 #endif
509 {FFMPEG, kCodecPCM, "sfx_f32le.wav", kSfxWaveExpectations, 0, 44100,
510 CHANNEL_LAYOUT_MONO},
511 {FFMPEG, kCodecPCM, "4ch.wav", kFourChannelWaveExpectations, 0, 44100,
512 CHANNEL_LAYOUT_QUAD},
513 {FFMPEG, kCodecVorbis, "sfx.ogg", kSfxOggExpectations, 0, 44100,
514 CHANNEL_LAYOUT_MONO},
515 // Note: bear.ogv is incorrectly muxed such that valid samples are given
516 // negative timestamps, this marks them for discard per the ogg vorbis spec.
517 {FFMPEG, kCodecVorbis, "bear.ogv", kBearOgvExpectations, -704, 44100,
518 CHANNEL_LAYOUT_STEREO},
521 // Dummy data for behavioral tests.
522 const DecoderTestData kFFmpegBehavioralTest[] = {
523 {FFMPEG, kUnknownAudioCodec, "", NULL, 0, 0, CHANNEL_LAYOUT_NONE},
526 INSTANTIATE_TEST_CASE_P(FFmpegAudioDecoderTest,
527 AudioDecoderTest,
528 testing::ValuesIn(kFFmpegTests));
529 INSTANTIATE_TEST_CASE_P(FFmpegAudioDecoderBehavioralTest,
530 FFmpegAudioDecoderBehavioralTest,
531 testing::ValuesIn(kFFmpegBehavioralTest));
533 } // namespace media