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(const WavHeaderPcm&) = default;
84   WavHeaderPcm& operator=(const WavHeaderPcm&) = default;
85   RiffHeader riff;
86   FmtPcmSubchunk fmt;
87   struct {
88     ChunkHeader header;
89   } data;
90 };
91 static_assert(sizeof(WavHeaderPcm) == kPcmWavHeaderSize,
92               "no padding in header");
93 
94 // IEEE Float Wav header, includes extra chunks necessary for proper non-PCM
95 // WAV implementation.
96 #pragma pack(2)
97 struct WavHeaderIeeeFloat {
98   WavHeaderIeeeFloat(const WavHeaderIeeeFloat&) = default;
99   WavHeaderIeeeFloat& operator=(const WavHeaderIeeeFloat&) = default;
100   RiffHeader riff;
101   FmtIeeeFloatSubchunk fmt;
102   struct {
103     ChunkHeader header;
104     uint32_t SampleLength;
105   } fact;
106   struct {
107     ChunkHeader header;
108   } data;
109 };
110 static_assert(sizeof(WavHeaderIeeeFloat) == kIeeeFloatWavHeaderSize,
111               "no padding in header");
112 
PackFourCC(char a,char b,char c,char d)113 uint32_t PackFourCC(char a, char b, char c, char d) {
114   uint32_t packed_value =
115       static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 |
116       static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24;
117   return packed_value;
118 }
119 
ReadFourCC(uint32_t x)120 std::string ReadFourCC(uint32_t x) {
121   return std::string(reinterpret_cast<char*>(&x), 4);
122 }
123 
MapWavFormatToHeaderField(WavFormat format)124 uint16_t MapWavFormatToHeaderField(WavFormat format) {
125   switch (format) {
126     case WavFormat::kWavFormatPcm:
127       return 1;
128     case WavFormat::kWavFormatIeeeFloat:
129       return 3;
130     case WavFormat::kWavFormatALaw:
131       return 6;
132     case WavFormat::kWavFormatMuLaw:
133       return 7;
134   }
135   RTC_CHECK(false);
136 }
137 
MapHeaderFieldToWavFormat(uint16_t format_header_value)138 WavFormat MapHeaderFieldToWavFormat(uint16_t format_header_value) {
139   if (format_header_value == 1) {
140     return WavFormat::kWavFormatPcm;
141   }
142   if (format_header_value == 3) {
143     return WavFormat::kWavFormatIeeeFloat;
144   }
145 
146   RTC_CHECK(false) << "Unsupported WAV format";
147 }
148 
RiffChunkSize(size_t bytes_in_payload,size_t header_size)149 uint32_t RiffChunkSize(size_t bytes_in_payload, size_t header_size) {
150   return static_cast<uint32_t>(bytes_in_payload + header_size -
151                                sizeof(ChunkHeader));
152 }
153 
ByteRate(size_t num_channels,int sample_rate,size_t bytes_per_sample)154 uint32_t ByteRate(size_t num_channels,
155                   int sample_rate,
156                   size_t bytes_per_sample) {
157   return static_cast<uint32_t>(num_channels * sample_rate * bytes_per_sample);
158 }
159 
BlockAlign(size_t num_channels,size_t bytes_per_sample)160 uint16_t BlockAlign(size_t num_channels, size_t bytes_per_sample) {
161   return static_cast<uint16_t>(num_channels * bytes_per_sample);
162 }
163 
164 // Finds a chunk having the sought ID. If found, then |readable| points to the
165 // first byte of the sought chunk data. If not found, the end of the file is
166 // reached.
FindWaveChunk(ChunkHeader * chunk_header,WavHeaderReader * readable,const std::string sought_chunk_id)167 bool FindWaveChunk(ChunkHeader* chunk_header,
168                    WavHeaderReader* readable,
169                    const std::string sought_chunk_id) {
170   RTC_DCHECK_EQ(sought_chunk_id.size(), 4);
171   while (true) {
172     if (readable->Read(chunk_header, sizeof(*chunk_header)) !=
173         sizeof(*chunk_header))
174       return false;  // EOF.
175     if (ReadFourCC(chunk_header->ID) == sought_chunk_id)
176       return true;  // Sought chunk found.
177     // Ignore current chunk by skipping its payload.
178     if (!readable->SeekForward(chunk_header->Size))
179       return false;  // EOF or error.
180   }
181 }
182 
ReadFmtChunkData(FmtPcmSubchunk * fmt_subchunk,WavHeaderReader * readable)183 bool ReadFmtChunkData(FmtPcmSubchunk* fmt_subchunk, WavHeaderReader* readable) {
184   // Reads "fmt " chunk payload.
185   if (readable->Read(&(fmt_subchunk->AudioFormat), kFmtPcmSubchunkSize) !=
186       kFmtPcmSubchunkSize)
187     return false;
188   const uint32_t fmt_size = fmt_subchunk->header.Size;
189   if (fmt_size != kFmtPcmSubchunkSize) {
190     // There is an optional two-byte extension field permitted to be present
191     // with PCM, but which must be zero.
192     int16_t ext_size;
193     if (kFmtPcmSubchunkSize + sizeof(ext_size) != fmt_size)
194       return false;
195     if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
196       return false;
197     if (ext_size != 0)
198       return false;
199   }
200   return true;
201 }
202 
WritePcmWavHeader(size_t num_channels,int sample_rate,size_t bytes_per_sample,size_t num_samples,uint8_t * buf,size_t * header_size)203 void WritePcmWavHeader(size_t num_channels,
204                        int sample_rate,
205                        size_t bytes_per_sample,
206                        size_t num_samples,
207                        uint8_t* buf,
208                        size_t* header_size) {
209   RTC_CHECK(buf);
210   RTC_CHECK(header_size);
211   *header_size = kPcmWavHeaderSize;
212   auto header = rtc::MsanUninitialized<WavHeaderPcm>({});
213   const size_t bytes_in_payload = bytes_per_sample * num_samples;
214 
215   header.riff.header.ID = PackFourCC('R', 'I', 'F', 'F');
216   header.riff.header.Size = RiffChunkSize(bytes_in_payload, *header_size);
217   header.riff.Format = PackFourCC('W', 'A', 'V', 'E');
218   header.fmt.header.ID = PackFourCC('f', 'm', 't', ' ');
219   header.fmt.header.Size = kFmtPcmSubchunkSize;
220   header.fmt.AudioFormat = MapWavFormatToHeaderField(WavFormat::kWavFormatPcm);
221   header.fmt.NumChannels = static_cast<uint16_t>(num_channels);
222   header.fmt.SampleRate = sample_rate;
223   header.fmt.ByteRate = ByteRate(num_channels, sample_rate, bytes_per_sample);
224   header.fmt.BlockAlign = BlockAlign(num_channels, bytes_per_sample);
225   header.fmt.BitsPerSample = static_cast<uint16_t>(8 * bytes_per_sample);
226   header.data.header.ID = PackFourCC('d', 'a', 't', 'a');
227   header.data.header.Size = static_cast<uint32_t>(bytes_in_payload);
228 
229   // Do an extra copy rather than writing everything to buf directly, since buf
230   // might not be correctly aligned.
231   memcpy(buf, &header, *header_size);
232 }
233 
WriteIeeeFloatWavHeader(size_t num_channels,int sample_rate,size_t bytes_per_sample,size_t num_samples,uint8_t * buf,size_t * header_size)234 void WriteIeeeFloatWavHeader(size_t num_channels,
235                              int sample_rate,
236                              size_t bytes_per_sample,
237                              size_t num_samples,
238                              uint8_t* buf,
239                              size_t* header_size) {
240   RTC_CHECK(buf);
241   RTC_CHECK(header_size);
242   *header_size = kIeeeFloatWavHeaderSize;
243   auto header = rtc::MsanUninitialized<WavHeaderIeeeFloat>({});
244   const size_t bytes_in_payload = bytes_per_sample * num_samples;
245 
246   header.riff.header.ID = PackFourCC('R', 'I', 'F', 'F');
247   header.riff.header.Size = RiffChunkSize(bytes_in_payload, *header_size);
248   header.riff.Format = PackFourCC('W', 'A', 'V', 'E');
249   header.fmt.header.ID = PackFourCC('f', 'm', 't', ' ');
250   header.fmt.header.Size = kFmtIeeeFloatSubchunkSize;
251   header.fmt.AudioFormat =
252       MapWavFormatToHeaderField(WavFormat::kWavFormatIeeeFloat);
253   header.fmt.NumChannels = static_cast<uint16_t>(num_channels);
254   header.fmt.SampleRate = sample_rate;
255   header.fmt.ByteRate = ByteRate(num_channels, sample_rate, bytes_per_sample);
256   header.fmt.BlockAlign = BlockAlign(num_channels, bytes_per_sample);
257   header.fmt.BitsPerSample = static_cast<uint16_t>(8 * bytes_per_sample);
258   header.fmt.ExtensionSize = 0;
259   header.fact.header.ID = PackFourCC('f', 'a', 'c', 't');
260   header.fact.header.Size = 4;
261   header.fact.SampleLength = static_cast<uint32_t>(num_channels * num_samples);
262   header.data.header.ID = PackFourCC('d', 'a', 't', 'a');
263   header.data.header.Size = static_cast<uint32_t>(bytes_in_payload);
264 
265   // Do an extra copy rather than writing everything to buf directly, since buf
266   // might not be correctly aligned.
267   memcpy(buf, &header, *header_size);
268 }
269 
270 // Returns the number of bytes per sample for the format.
GetFormatBytesPerSample(WavFormat format)271 size_t GetFormatBytesPerSample(WavFormat format) {
272   switch (format) {
273     case WavFormat::kWavFormatPcm:
274       // Other values may be OK, but for now we're conservative.
275       return 2;
276     case WavFormat::kWavFormatALaw:
277     case WavFormat::kWavFormatMuLaw:
278       return 1;
279     case WavFormat::kWavFormatIeeeFloat:
280       return 4;
281     default:
282       RTC_CHECK(false);
283       return 2;
284   }
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