1 /*
2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 // Based on the WAV file format documentation at
12 // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ and
13 // http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
14
15 #include "common_audio/wav_header.h"
16
17 #include <cstring>
18 #include <limits>
19 #include <string>
20
21 #include "rtc_base/checks.h"
22 #include "rtc_base/logging.h"
23 #include "rtc_base/sanitizer.h"
24 #include "rtc_base/system/arch.h"
25
26 namespace webrtc {
27 namespace {
28
29 #ifndef WEBRTC_ARCH_LITTLE_ENDIAN
30 #error "Code not working properly for big endian platforms."
31 #endif
32
33 #pragma pack(2)
34 struct ChunkHeader {
35 uint32_t ID;
36 uint32_t Size;
37 };
38 static_assert(sizeof(ChunkHeader) == 8, "ChunkHeader size");
39
40 #pragma pack(2)
41 struct RiffHeader {
42 ChunkHeader header;
43 uint32_t Format;
44 };
45 static_assert(sizeof(RiffHeader) == sizeof(ChunkHeader) + 4, "RiffHeader size");
46
47 // We can't nest this definition in WavHeader, because VS2013 gives an error
48 // on sizeof(WavHeader::fmt): "error C2070: 'unknown': illegal sizeof operand".
49 #pragma pack(2)
50 struct FmtPcmSubchunk {
51 ChunkHeader header;
52 uint16_t AudioFormat;
53 uint16_t NumChannels;
54 uint32_t SampleRate;
55 uint32_t ByteRate;
56 uint16_t BlockAlign;
57 uint16_t BitsPerSample;
58 };
59 static_assert(sizeof(FmtPcmSubchunk) == 24, "FmtPcmSubchunk size");
60 const uint32_t kFmtPcmSubchunkSize =
61 sizeof(FmtPcmSubchunk) - sizeof(ChunkHeader);
62
63 // Pack struct to avoid additional padding bytes.
64 #pragma pack(2)
65 struct FmtIeeeFloatSubchunk {
66 ChunkHeader header;
67 uint16_t AudioFormat;
68 uint16_t NumChannels;
69 uint32_t SampleRate;
70 uint32_t ByteRate;
71 uint16_t BlockAlign;
72 uint16_t BitsPerSample;
73 uint16_t ExtensionSize;
74 };
75 static_assert(sizeof(FmtIeeeFloatSubchunk) == 26, "FmtIeeeFloatSubchunk size");
76 const uint32_t kFmtIeeeFloatSubchunkSize =
77 sizeof(FmtIeeeFloatSubchunk) - sizeof(ChunkHeader);
78
79 // Simple PCM wav header. It does not include chunks that are not essential to
80 // read audio samples.
81 #pragma pack(2)
82 struct WavHeaderPcm {
83 WavHeaderPcm() = default;
84 WavHeaderPcm(const WavHeaderPcm&) = default;
85 WavHeaderPcm& operator=(const WavHeaderPcm&) = default;
86 RiffHeader riff;
87 FmtPcmSubchunk fmt;
88 struct {
89 ChunkHeader header;
90 } data;
91 };
92 static_assert(sizeof(WavHeaderPcm) == kPcmWavHeaderSize,
93 "no padding in header");
94
95 // IEEE Float Wav header, includes extra chunks necessary for proper non-PCM
96 // WAV implementation.
97 #pragma pack(2)
98 struct WavHeaderIeeeFloat {
99 WavHeaderIeeeFloat() = default;
100 WavHeaderIeeeFloat(const WavHeaderIeeeFloat&) = default;
101 WavHeaderIeeeFloat& operator=(const WavHeaderIeeeFloat&) = default;
102 RiffHeader riff;
103 FmtIeeeFloatSubchunk fmt;
104 struct {
105 ChunkHeader header;
106 uint32_t SampleLength;
107 } fact;
108 struct {
109 ChunkHeader header;
110 } data;
111 };
112 static_assert(sizeof(WavHeaderIeeeFloat) == kIeeeFloatWavHeaderSize,
113 "no padding in header");
114
PackFourCC(char a,char b,char c,char d)115 uint32_t PackFourCC(char a, char b, char c, char d) {
116 uint32_t packed_value =
117 static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 |
118 static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24;
119 return packed_value;
120 }
121
ReadFourCC(uint32_t x)122 std::string ReadFourCC(uint32_t x) {
123 return std::string(reinterpret_cast<char*>(&x), 4);
124 }
125
MapWavFormatToHeaderField(WavFormat format)126 uint16_t MapWavFormatToHeaderField(WavFormat format) {
127 switch (format) {
128 case WavFormat::kWavFormatPcm:
129 return 1;
130 case WavFormat::kWavFormatIeeeFloat:
131 return 3;
132 case WavFormat::kWavFormatALaw:
133 return 6;
134 case WavFormat::kWavFormatMuLaw:
135 return 7;
136 }
137 RTC_CHECK_NOTREACHED();
138 }
139
MapHeaderFieldToWavFormat(uint16_t format_header_value)140 WavFormat MapHeaderFieldToWavFormat(uint16_t format_header_value) {
141 if (format_header_value == 1) {
142 return WavFormat::kWavFormatPcm;
143 }
144 if (format_header_value == 3) {
145 return WavFormat::kWavFormatIeeeFloat;
146 }
147
148 RTC_CHECK(false) << "Unsupported WAV format";
149 }
150
RiffChunkSize(size_t bytes_in_payload,size_t header_size)151 uint32_t RiffChunkSize(size_t bytes_in_payload, size_t header_size) {
152 return static_cast<uint32_t>(bytes_in_payload + header_size -
153 sizeof(ChunkHeader));
154 }
155
ByteRate(size_t num_channels,int sample_rate,size_t bytes_per_sample)156 uint32_t ByteRate(size_t num_channels,
157 int sample_rate,
158 size_t bytes_per_sample) {
159 return static_cast<uint32_t>(num_channels * sample_rate * bytes_per_sample);
160 }
161
BlockAlign(size_t num_channels,size_t bytes_per_sample)162 uint16_t BlockAlign(size_t num_channels, size_t bytes_per_sample) {
163 return static_cast<uint16_t>(num_channels * bytes_per_sample);
164 }
165
166 // Finds a chunk having the sought ID. If found, then |readable| points to the
167 // first byte of the sought chunk data. If not found, the end of the file is
168 // reached.
FindWaveChunk(ChunkHeader * chunk_header,WavHeaderReader * readable,const std::string sought_chunk_id)169 bool FindWaveChunk(ChunkHeader* chunk_header,
170 WavHeaderReader* readable,
171 const std::string sought_chunk_id) {
172 RTC_DCHECK_EQ(sought_chunk_id.size(), 4);
173 while (true) {
174 if (readable->Read(chunk_header, sizeof(*chunk_header)) !=
175 sizeof(*chunk_header))
176 return false; // EOF.
177 if (ReadFourCC(chunk_header->ID) == sought_chunk_id)
178 return true; // Sought chunk found.
179 // Ignore current chunk by skipping its payload.
180 if (!readable->SeekForward(chunk_header->Size))
181 return false; // EOF or error.
182 }
183 }
184
ReadFmtChunkData(FmtPcmSubchunk * fmt_subchunk,WavHeaderReader * readable)185 bool ReadFmtChunkData(FmtPcmSubchunk* fmt_subchunk, WavHeaderReader* readable) {
186 // Reads "fmt " chunk payload.
187 if (readable->Read(&(fmt_subchunk->AudioFormat), kFmtPcmSubchunkSize) !=
188 kFmtPcmSubchunkSize)
189 return false;
190 const uint32_t fmt_size = fmt_subchunk->header.Size;
191 if (fmt_size != kFmtPcmSubchunkSize) {
192 // There is an optional two-byte extension field permitted to be present
193 // with PCM, but which must be zero.
194 int16_t ext_size;
195 if (kFmtPcmSubchunkSize + sizeof(ext_size) != fmt_size)
196 return false;
197 if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
198 return false;
199 if (ext_size != 0)
200 return false;
201 }
202 return true;
203 }
204
WritePcmWavHeader(size_t num_channels,int sample_rate,size_t bytes_per_sample,size_t num_samples,uint8_t * buf,size_t * header_size)205 void WritePcmWavHeader(size_t num_channels,
206 int sample_rate,
207 size_t bytes_per_sample,
208 size_t num_samples,
209 uint8_t* buf,
210 size_t* header_size) {
211 RTC_CHECK(buf);
212 RTC_CHECK(header_size);
213 *header_size = kPcmWavHeaderSize;
214 auto header = rtc::MsanUninitialized<WavHeaderPcm>({});
215 const size_t bytes_in_payload = bytes_per_sample * num_samples;
216
217 header.riff.header.ID = PackFourCC('R', 'I', 'F', 'F');
218 header.riff.header.Size = RiffChunkSize(bytes_in_payload, *header_size);
219 header.riff.Format = PackFourCC('W', 'A', 'V', 'E');
220 header.fmt.header.ID = PackFourCC('f', 'm', 't', ' ');
221 header.fmt.header.Size = kFmtPcmSubchunkSize;
222 header.fmt.AudioFormat = MapWavFormatToHeaderField(WavFormat::kWavFormatPcm);
223 header.fmt.NumChannels = static_cast<uint16_t>(num_channels);
224 header.fmt.SampleRate = sample_rate;
225 header.fmt.ByteRate = ByteRate(num_channels, sample_rate, bytes_per_sample);
226 header.fmt.BlockAlign = BlockAlign(num_channels, bytes_per_sample);
227 header.fmt.BitsPerSample = static_cast<uint16_t>(8 * bytes_per_sample);
228 header.data.header.ID = PackFourCC('d', 'a', 't', 'a');
229 header.data.header.Size = static_cast<uint32_t>(bytes_in_payload);
230
231 // Do an extra copy rather than writing everything to buf directly, since buf
232 // might not be correctly aligned.
233 memcpy(buf, &header, *header_size);
234 }
235
WriteIeeeFloatWavHeader(size_t num_channels,int sample_rate,size_t bytes_per_sample,size_t num_samples,uint8_t * buf,size_t * header_size)236 void WriteIeeeFloatWavHeader(size_t num_channels,
237 int sample_rate,
238 size_t bytes_per_sample,
239 size_t num_samples,
240 uint8_t* buf,
241 size_t* header_size) {
242 RTC_CHECK(buf);
243 RTC_CHECK(header_size);
244 *header_size = kIeeeFloatWavHeaderSize;
245 auto header = rtc::MsanUninitialized<WavHeaderIeeeFloat>({});
246 const size_t bytes_in_payload = bytes_per_sample * num_samples;
247
248 header.riff.header.ID = PackFourCC('R', 'I', 'F', 'F');
249 header.riff.header.Size = RiffChunkSize(bytes_in_payload, *header_size);
250 header.riff.Format = PackFourCC('W', 'A', 'V', 'E');
251 header.fmt.header.ID = PackFourCC('f', 'm', 't', ' ');
252 header.fmt.header.Size = kFmtIeeeFloatSubchunkSize;
253 header.fmt.AudioFormat =
254 MapWavFormatToHeaderField(WavFormat::kWavFormatIeeeFloat);
255 header.fmt.NumChannels = static_cast<uint16_t>(num_channels);
256 header.fmt.SampleRate = sample_rate;
257 header.fmt.ByteRate = ByteRate(num_channels, sample_rate, bytes_per_sample);
258 header.fmt.BlockAlign = BlockAlign(num_channels, bytes_per_sample);
259 header.fmt.BitsPerSample = static_cast<uint16_t>(8 * bytes_per_sample);
260 header.fmt.ExtensionSize = 0;
261 header.fact.header.ID = PackFourCC('f', 'a', 'c', 't');
262 header.fact.header.Size = 4;
263 header.fact.SampleLength = static_cast<uint32_t>(num_channels * num_samples);
264 header.data.header.ID = PackFourCC('d', 'a', 't', 'a');
265 header.data.header.Size = static_cast<uint32_t>(bytes_in_payload);
266
267 // Do an extra copy rather than writing everything to buf directly, since buf
268 // might not be correctly aligned.
269 memcpy(buf, &header, *header_size);
270 }
271
272 // Returns the number of bytes per sample for the format.
GetFormatBytesPerSample(WavFormat format)273 size_t GetFormatBytesPerSample(WavFormat format) {
274 switch (format) {
275 case WavFormat::kWavFormatPcm:
276 // Other values may be OK, but for now we're conservative.
277 return 2;
278 case WavFormat::kWavFormatALaw:
279 case WavFormat::kWavFormatMuLaw:
280 return 1;
281 case WavFormat::kWavFormatIeeeFloat:
282 return 4;
283 }
284 RTC_CHECK_NOTREACHED();
285 }
286
CheckWavParameters(size_t num_channels,int sample_rate,WavFormat format,size_t bytes_per_sample,size_t num_samples)287 bool CheckWavParameters(size_t num_channels,
288 int sample_rate,
289 WavFormat format,
290 size_t bytes_per_sample,
291 size_t num_samples) {
292 // num_channels, sample_rate, and bytes_per_sample must be positive, must fit
293 // in their respective fields, and their product must fit in the 32-bit
294 // ByteRate field.
295 if (num_channels == 0 || sample_rate <= 0 || bytes_per_sample == 0)
296 return false;
297 if (static_cast<uint64_t>(sample_rate) > std::numeric_limits<uint32_t>::max())
298 return false;
299 if (num_channels > std::numeric_limits<uint16_t>::max())
300 return false;
301 if (static_cast<uint64_t>(bytes_per_sample) * 8 >
302 std::numeric_limits<uint16_t>::max())
303 return false;
304 if (static_cast<uint64_t>(sample_rate) * num_channels * bytes_per_sample >
305 std::numeric_limits<uint32_t>::max())
306 return false;
307
308 // format and bytes_per_sample must agree.
309 switch (format) {
310 case WavFormat::kWavFormatPcm:
311 // Other values may be OK, but for now we're conservative:
312 if (bytes_per_sample != 1 && bytes_per_sample != 2)
313 return false;
314 break;
315 case WavFormat::kWavFormatALaw:
316 case WavFormat::kWavFormatMuLaw:
317 if (bytes_per_sample != 1)
318 return false;
319 break;
320 case WavFormat::kWavFormatIeeeFloat:
321 if (bytes_per_sample != 4)
322 return false;
323 break;
324 default:
325 return false;
326 }
327
328 // The number of bytes in the file, not counting the first ChunkHeader, must
329 // be less than 2^32; otherwise, the ChunkSize field overflows.
330 const size_t header_size = kPcmWavHeaderSize - sizeof(ChunkHeader);
331 const size_t max_samples =
332 (std::numeric_limits<uint32_t>::max() - header_size) / bytes_per_sample;
333 if (num_samples > max_samples)
334 return false;
335
336 // Each channel must have the same number of samples.
337 if (num_samples % num_channels != 0)
338 return false;
339
340 return true;
341 }
342
343 } // namespace
344
CheckWavParameters(size_t num_channels,int sample_rate,WavFormat format,size_t num_samples)345 bool CheckWavParameters(size_t num_channels,
346 int sample_rate,
347 WavFormat format,
348 size_t num_samples) {
349 return CheckWavParameters(num_channels, sample_rate, format,
350 GetFormatBytesPerSample(format), num_samples);
351 }
352
WriteWavHeader(size_t num_channels,int sample_rate,WavFormat format,size_t num_samples,uint8_t * buf,size_t * header_size)353 void WriteWavHeader(size_t num_channels,
354 int sample_rate,
355 WavFormat format,
356 size_t num_samples,
357 uint8_t* buf,
358 size_t* header_size) {
359 RTC_CHECK(buf);
360 RTC_CHECK(header_size);
361
362 const size_t bytes_per_sample = GetFormatBytesPerSample(format);
363 RTC_CHECK(CheckWavParameters(num_channels, sample_rate, format,
364 bytes_per_sample, num_samples));
365 if (format == WavFormat::kWavFormatPcm) {
366 WritePcmWavHeader(num_channels, sample_rate, bytes_per_sample, num_samples,
367 buf, header_size);
368 } else {
369 RTC_CHECK_EQ(format, WavFormat::kWavFormatIeeeFloat);
370 WriteIeeeFloatWavHeader(num_channels, sample_rate, bytes_per_sample,
371 num_samples, buf, header_size);
372 }
373 }
374
ReadWavHeader(WavHeaderReader * readable,size_t * num_channels,int * sample_rate,WavFormat * format,size_t * bytes_per_sample,size_t * num_samples,int64_t * data_start_pos)375 bool ReadWavHeader(WavHeaderReader* readable,
376 size_t* num_channels,
377 int* sample_rate,
378 WavFormat* format,
379 size_t* bytes_per_sample,
380 size_t* num_samples,
381 int64_t* data_start_pos) {
382 // Read using the PCM header, even though it might be float Wav file
383 auto header = rtc::MsanUninitialized<WavHeaderPcm>({});
384
385 // Read RIFF chunk.
386 if (readable->Read(&header.riff, sizeof(header.riff)) != sizeof(header.riff))
387 return false;
388 if (ReadFourCC(header.riff.header.ID) != "RIFF")
389 return false;
390 if (ReadFourCC(header.riff.Format) != "WAVE")
391 return false;
392
393 // Find "fmt " and "data" chunks. While the official Wave file specification
394 // does not put requirements on the chunks order, it is uncommon to find the
395 // "data" chunk before the "fmt " one. The code below fails if this is not the
396 // case.
397 if (!FindWaveChunk(&header.fmt.header, readable, "fmt ")) {
398 RTC_LOG(LS_ERROR) << "Cannot find 'fmt ' chunk.";
399 return false;
400 }
401 if (!ReadFmtChunkData(&header.fmt, readable)) {
402 RTC_LOG(LS_ERROR) << "Cannot read 'fmt ' chunk.";
403 return false;
404 }
405 if (!FindWaveChunk(&header.data.header, readable, "data")) {
406 RTC_LOG(LS_ERROR) << "Cannot find 'data' chunk.";
407 return false;
408 }
409
410 // Parse needed fields.
411 *format = MapHeaderFieldToWavFormat(header.fmt.AudioFormat);
412 *num_channels = header.fmt.NumChannels;
413 *sample_rate = header.fmt.SampleRate;
414 *bytes_per_sample = header.fmt.BitsPerSample / 8;
415 const size_t bytes_in_payload = header.data.header.Size;
416 if (*bytes_per_sample == 0)
417 return false;
418 *num_samples = bytes_in_payload / *bytes_per_sample;
419
420 const size_t header_size = *format == WavFormat::kWavFormatPcm
421 ? kPcmWavHeaderSize
422 : kIeeeFloatWavHeaderSize;
423
424 if (header.riff.header.Size < RiffChunkSize(bytes_in_payload, header_size))
425 return false;
426 if (header.fmt.ByteRate !=
427 ByteRate(*num_channels, *sample_rate, *bytes_per_sample))
428 return false;
429 if (header.fmt.BlockAlign != BlockAlign(*num_channels, *bytes_per_sample))
430 return false;
431
432 if (!CheckWavParameters(*num_channels, *sample_rate, *format,
433 *bytes_per_sample, *num_samples)) {
434 return false;
435 }
436
437 *data_start_pos = readable->GetPosition();
438 return true;
439 }
440
441 } // namespace webrtc
442