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

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

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

Powered by Google App Engine
This is Rietveld 408576698