Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(50)

Side by Side Diff: content/browser/renderer_host/media/audio_debug_file_writer.cc

Issue 2702323002: Move AudioDebugFileWriter from content/ to media/. (Closed)
Patch Set: Code review, unit test fix and rebase. Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 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 "content/browser/renderer_host/media/audio_debug_file_writer.h"
6
7 #include <stdint.h>
8 #include <array>
9 #include <utility>
10
11 #include "base/logging.h"
12 #include "base/memory/ptr_util.h"
13 #include "base/sys_byteorder.h"
14 #include "content/public/browser/browser_thread.h"
15 #include "media/base/audio_bus.h"
16
17 namespace content {
18
19 namespace {
20
21 // Windows WAVE format header
22 // Byte order: Little-endian
23 // Offset Length Content
24 // 0 4 "RIFF"
25 // 4 4 <file length - 8>
26 // 8 4 "WAVE"
27 // 12 4 "fmt "
28 // 16 4 <length of the fmt data> (=16)
29 // 20 2 <WAVE file encoding tag>
30 // 22 2 <channels>
31 // 24 4 <sample rate>
32 // 28 4 <bytes per second> (sample rate * block align)
33 // 32 2 <block align> (channels * bits per sample / 8)
34 // 34 2 <bits per sample>
35 // 36 4 "data"
36 // 40 4 <sample data size(n)>
37 // 44 (n) <sample data>
38
39 // We write 16 bit PCM only.
40 static const uint16_t kBytesPerSample = 2;
41
42 static const uint32_t kWavHeaderSize = 44;
43 static const uint32_t kFmtChunkSize = 16;
44 // 4 bytes for ID + 4 bytes for size.
45 static const uint32_t kChunkHeaderSize = 8;
46 static const uint16_t kWavFormatPcm = 1;
47
48 static const char kRiff[] = {'R', 'I', 'F', 'F'};
49 static const char kWave[] = {'W', 'A', 'V', 'E'};
50 static const char kFmt[] = {'f', 'm', 't', ' '};
51 static const char kData[] = {'d', 'a', 't', 'a'};
52
53 typedef std::array<char, kWavHeaderSize> WavHeaderBuffer;
54
55 class CharBufferWriter {
56 public:
57 CharBufferWriter(char* buf, int max_size)
58 : buf_(buf), max_size_(max_size), size_(0) {}
59
60 void Write(const char* data, int data_size) {
61 CHECK_LE(size_ + data_size, max_size_);
62 memcpy(&buf_[size_], data, data_size);
63 size_ += data_size;
64 }
65
66 void Write(const char(&data)[4]) { Write(static_cast<const char*>(data), 4); }
67
68 void WriteLE16(uint16_t data) {
69 uint16_t val = base::ByteSwapToLE16(data);
70 Write(reinterpret_cast<const char*>(&val), sizeof(val));
71 }
72
73 void WriteLE32(uint32_t data) {
74 uint32_t val = base::ByteSwapToLE32(data);
75 Write(reinterpret_cast<const char*>(&val), sizeof(val));
76 }
77
78 private:
79 char* buf_;
80 const int max_size_;
81 int size_;
82
83 DISALLOW_COPY_AND_ASSIGN(CharBufferWriter);
84 };
85
86 // Writes Wave header to the specified address, there should be at least
87 // kWavHeaderSize bytes allocated for it.
88 void WriteWavHeader(WavHeaderBuffer* buf,
89 uint32_t channels,
90 uint32_t sample_rate,
91 uint64_t samples) {
92 // We'll need to add (kWavHeaderSize - kChunkHeaderSize) to payload to
93 // calculate Riff chunk size.
94 static const uint32_t kMaxBytesInPayload =
95 std::numeric_limits<uint32_t>::max() -
96 (kWavHeaderSize - kChunkHeaderSize);
97 const uint64_t bytes_in_payload_64 = samples * kBytesPerSample;
98
99 // In case payload is too large and causes uint32_t overflow, we just specify
100 // the maximum possible value; all the payload above that count will be
101 // interpreted as garbage.
102 const uint32_t bytes_in_payload = bytes_in_payload_64 > kMaxBytesInPayload
103 ? kMaxBytesInPayload
104 : bytes_in_payload_64;
105 LOG_IF(WARNING, bytes_in_payload < bytes_in_payload_64)
106 << "Number of samples is too large and will be clipped by Wave header,"
107 << " all the data above " << kMaxBytesInPayload
108 << " bytes will appear as junk";
109 const uint32_t block_align = channels * kBytesPerSample;
110 const uint32_t byte_rate = channels * sample_rate * kBytesPerSample;
111 const uint32_t riff_chunk_size =
112 bytes_in_payload + kWavHeaderSize - kChunkHeaderSize;
113
114 CharBufferWriter writer(&(*buf)[0], kWavHeaderSize);
115
116 writer.Write(kRiff);
117 writer.WriteLE32(riff_chunk_size);
118 writer.Write(kWave);
119 writer.Write(kFmt);
120 writer.WriteLE32(kFmtChunkSize);
121 writer.WriteLE16(kWavFormatPcm);
122 writer.WriteLE16(channels);
123 writer.WriteLE32(sample_rate);
124 writer.WriteLE32(byte_rate);
125 writer.WriteLE16(block_align);
126 writer.WriteLE16(kBytesPerSample * 8);
127 writer.Write(kData);
128 writer.WriteLE32(bytes_in_payload);
129 }
130
131 } // namespace
132
133 // Manages the debug recording file and writes to it. Can be created on any
134 // thread. All the operations must be executed on FILE thread. Must be destroyed
135 // on FILE thread.
136 class AudioDebugFileWriter::AudioFileWriter {
137 public:
138 static AudioFileWriterUniquePtr Create(const base::FilePath& file_name,
139 const media::AudioParameters& params);
140
141 ~AudioFileWriter();
142
143 // Write data from |data| to file.
144 void Write(const media::AudioBus* data);
145
146 private:
147 AudioFileWriter(const media::AudioParameters& params);
148
149 // Write wave header to file. Called on the FILE thread twice: on construction
150 // of AudioFileWriter size of the wave data is unknown, so the header is
151 // written with zero sizes; then on destruction it is re-written with the
152 // actual size info accumulated throughout the object lifetime.
153 void WriteHeader();
154
155 void CreateRecordingFile(const base::FilePath& file_name);
156
157 // The file to write to.
158 base::File file_;
159
160 // Number of written samples.
161 uint64_t samples_;
162
163 // Input audio parameters required to build wave header.
164 const media::AudioParameters params_;
165
166 // Intermediate buffer to be written to file. Interleaved 16 bit audio data.
167 std::unique_ptr<int16_t[]> interleaved_data_;
168 int interleaved_data_size_;
169 };
170
171 // static
172 AudioDebugFileWriter::AudioFileWriterUniquePtr
173 AudioDebugFileWriter::AudioFileWriter::Create(
174 const base::FilePath& file_name,
175 const media::AudioParameters& params) {
176 AudioFileWriterUniquePtr file_writer(new AudioFileWriter(params));
177
178 // base::Unretained is safe, because destructor is called on FILE thread or on
179 // FILE message loop destruction.
180 BrowserThread::PostTask(
181 BrowserThread::FILE, FROM_HERE,
182 base::Bind(&AudioFileWriter::CreateRecordingFile,
183 base::Unretained(file_writer.get()), file_name));
184 return file_writer;
185 }
186
187 AudioDebugFileWriter::AudioFileWriter::AudioFileWriter(
188 const media::AudioParameters& params)
189 : samples_(0), params_(params), interleaved_data_size_(0) {
190 DCHECK_EQ(params.bits_per_sample(), kBytesPerSample * 8);
191 }
192
193 AudioDebugFileWriter::AudioFileWriter::~AudioFileWriter() {
194 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
195 if (file_.IsValid())
196 WriteHeader();
197 }
198
199 void AudioDebugFileWriter::AudioFileWriter::Write(
200 const media::AudioBus* data) {
201 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
202 if (!file_.IsValid())
203 return;
204
205 // Convert to 16 bit audio and write to file.
206 int data_size = data->frames() * data->channels();
207 if (!interleaved_data_ || interleaved_data_size_ < data_size) {
208 interleaved_data_.reset(new int16_t[data_size]);
209 interleaved_data_size_ = data_size;
210 }
211 samples_ += data_size;
212 data->ToInterleaved(data->frames(), sizeof(interleaved_data_[0]),
213 interleaved_data_.get());
214
215 #ifndef ARCH_CPU_LITTLE_ENDIAN
216 static_assert(sizeof(interleaved_data_[0]) == sizeof(uint16_t),
217 "Only 2 bytes per channel is supported.");
218 for (int i = 0; i < data_size; ++i)
219 interleaved_data_[i] = base::ByteSwapToLE16(interleaved_data_[i]);
220 #endif
221
222 file_.WriteAtCurrentPos(reinterpret_cast<char*>(interleaved_data_.get()),
223 data_size * sizeof(interleaved_data_[0]));
224 }
225
226 void AudioDebugFileWriter::AudioFileWriter::WriteHeader() {
227 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
228 if (!file_.IsValid())
229 return;
230 WavHeaderBuffer buf;
231 WriteWavHeader(&buf, params_.channels(), params_.sample_rate(), samples_);
232 file_.Write(0, &buf[0], kWavHeaderSize);
233
234 // Write() does not move the cursor if file is not in APPEND mode; Seek() so
235 // that the header is not overwritten by the following writes.
236 file_.Seek(base::File::FROM_BEGIN, kWavHeaderSize);
237 }
238
239 void AudioDebugFileWriter::AudioFileWriter::CreateRecordingFile(
240 const base::FilePath& file_name) {
241 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
242 DCHECK(!file_.IsValid());
243
244 file_ = base::File(file_name,
245 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
246
247 if (file_.IsValid()) {
248 WriteHeader();
249 return;
250 }
251
252 // Note that we do not inform AudioDebugFileWriter that the file creation
253 // fails, so it will continue to post data to be recorded, which won't
254 // be written to the file. This also won't be reflected in WillWrite(). It's
255 // fine, because this situation is rare, and all the posting is expected to
256 // happen in case of success anyways. This allows us to save on thread hops
257 // for error reporting and to avoid dealing with lifetime issues. It also
258 // means file_.IsValid() should always be checked before issuing writes to it.
259 PLOG(ERROR) << "Could not open debug recording file, error="
260 << file_.error_details();
261 }
262
263 AudioDebugFileWriter::AudioDebugFileWriter(
264 const media::AudioParameters& params)
265 : params_(params) {
266 client_sequence_checker_.DetachFromSequence();
267 }
268
269 AudioDebugFileWriter::~AudioDebugFileWriter() {
270 // |file_writer_| will be deleted on FILE thread.
271 }
272
273 void AudioDebugFileWriter::Start(const base::FilePath& file_name) {
274 DCHECK(client_sequence_checker_.CalledOnValidSequence());
275 DCHECK(!file_writer_);
276 file_writer_ = AudioFileWriter::Create(file_name, params_);
277 }
278
279 void AudioDebugFileWriter::Stop() {
280 DCHECK(client_sequence_checker_.CalledOnValidSequence());
281 // |file_writer_| is deleted on FILE thread.
282 file_writer_.reset();
283 client_sequence_checker_.DetachFromSequence();
284 }
285
286 void AudioDebugFileWriter::Write(std::unique_ptr<media::AudioBus> data) {
287 DCHECK(client_sequence_checker_.CalledOnValidSequence());
288 if (!file_writer_)
289 return;
290
291 // base::Unretained for |file_writer_| is safe, see the destructor.
292 BrowserThread::PostTask(
293 BrowserThread::FILE, FROM_HERE,
294 // Callback takes ownership of |data|:
295 base::Bind(&AudioFileWriter::Write, base::Unretained(file_writer_.get()),
296 base::Owned(data.release())));
297 }
298
299 bool AudioDebugFileWriter::WillWrite() {
300 // Note that if this is called from any place other than
301 // |client_sequence_checker_| then there is a data race here, but it's fine,
302 // because Write() will check for |file_writer_|. So, we are not very precise
303 // here, but it's fine: we can afford missing some data or scheduling some
304 // no-op writes.
305 return !!file_writer_;
306 }
307
308 } // namspace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698