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 "chrome/browser/media/webrtc_browsertest_audio.h"
7 #include "base/files/file.h"
8 #include "base/files/file_path.h"
9 #include "media/audio/audio_power_monitor.h"
10 #include "media/audio/sounds/wav_audio_handler.h"
11 #include "media/base/audio_bus.h"
14 // Opens |wav_filename|, reads it and loads it as a wav file. This function will
15 // bluntly trigger CHECKs if we can't read the file or if it's malformed. The
16 // caller takes ownership of the returned data. The size of the data is stored
18 scoped_ptr
<uint8
[]> ReadWavFile(const base::FilePath
& wav_filename
,
19 size_t* file_length
) {
21 wav_filename
, base::File::FLAG_OPEN
| base::File::FLAG_READ
);
22 if (!wav_file
.IsValid()) {
23 CHECK(false) << "Failed to read " << wav_filename
.value();
27 size_t wav_file_length
= wav_file
.GetLength();
29 uint8
* wav_file_data
= new uint8
[wav_file_length
];
30 size_t read_bytes
= wav_file
.Read(0, reinterpret_cast<char*>(wav_file_data
),
32 if (read_bytes
!= wav_file_length
) {
33 CHECK(false) << "Failed to read all bytes of " << wav_filename
.value();
36 *file_length
= wav_file_length
;
37 return scoped_ptr
<uint8
[]>(wav_file_data
);
40 scoped_ptr
<media::WavAudioHandler
> CreateWavAudioHandler(
41 const base::FilePath
& wav_filename
, const uint8
* wav_file_data
,
42 size_t wav_file_length
) {
43 base::StringPiece
wav_data(reinterpret_cast<const char*>(wav_file_data
),
45 scoped_ptr
<media::WavAudioHandler
> wav_audio_handler(
46 new media::WavAudioHandler(wav_data
));
48 return wav_audio_handler
.Pass();
55 float ComputeAudioEnergyForWavFile(const base::FilePath
& wav_filename
,
56 media::AudioParameters
* file_parameters
) {
57 // Read the file, and put its data in a scoped_ptr so it gets deleted later.
58 size_t file_length
= 0;
59 scoped_ptr
<uint8
[]> wav_file_data
= ReadWavFile(wav_filename
, &file_length
);
60 scoped_ptr
<media::WavAudioHandler
> wav_audio_handler
= CreateWavAudioHandler(
61 wav_filename
, wav_file_data
.get(), file_length
);
63 scoped_ptr
<media::AudioBus
> audio_bus
=
64 media::AudioBus::Create(wav_audio_handler
->params());
65 base::TimeDelta file_duration
=
66 wav_audio_handler
->params().GetBufferDuration();
69 wav_audio_handler
->CopyTo(audio_bus
.get(), 0, &bytes_written
);
70 CHECK_EQ(bytes_written
, wav_audio_handler
->data().size())
71 << "Expected to write entire file into bus.";
73 // Set the filter coefficient to the whole file's duration; this will make the
74 // power monitor take the entire file into account.
75 media::AudioPowerMonitor
power_monitor(
76 wav_audio_handler
->params().sample_rate(), file_duration
);
77 power_monitor
.Scan(*audio_bus
, audio_bus
->frames());
79 *file_parameters
= wav_audio_handler
->params();
80 return power_monitor
.ReadCurrentPowerAndClip().first
;