• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   RiffHeader riff;
84   FmtPcmSubchunk fmt;
85   struct {
86     ChunkHeader header;
87   } data;
88 };
89 static_assert(sizeof(WavHeaderPcm) == kPcmWavHeaderSize,
90               "no padding in header");
91 
92 // IEEE Float Wav header, includes extra chunks necessary for proper non-PCM
93 // WAV implementation.
94 #pragma pack(2)
95 struct WavHeaderIeeeFloat {
96   RiffHeader riff;
97   FmtIeeeFloatSubchunk fmt;
98   struct {
99     ChunkHeader header;
100     uint32_t SampleLength;
101   } fact;
102   struct {
103     ChunkHeader header;
104   } data;
105 };
106 static_assert(sizeof(WavHeaderIeeeFloat) == kIeeeFloatWavHeaderSize,
107               "no padding in header");
108 
PackFourCC(char a,char b,char c,char d)109 uint32_t PackFourCC(char a, char b, char c, char d) {
110   uint32_t packed_value =
111       static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 |
112       static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24;
113   return packed_value;
114 }
115 
ReadFourCC(uint32_t x)116 std::string ReadFourCC(uint32_t x) {
117   return std::string(reinterpret_cast<char*>(&x), 4);
118 }
119 
MapWavFormatToHeaderField(WavFormat format)120 uint16_t MapWavFormatToHeaderField(WavFormat format) {
121   switch (format) {
122     case WavFormat::kWavFormatPcm:
123       return 1;
124     case WavFormat::kWavFormatIeeeFloat:
125       return 3;
126     case WavFormat::kWavFormatALaw:
127       return 6;
128     case WavFormat::kWavFormatMuLaw:
129       return 7;
130   }
131   RTC_CHECK_NOTREACHED();
132 }
133 
MapHeaderFieldToWavFormat(uint16_t format_header_value)134 WavFormat MapHeaderFieldToWavFormat(uint16_t format_header_value) {
135   if (format_header_value == 1) {
136     return WavFormat::kWavFormatPcm;
137   }
138   if (format_header_value == 3) {
139     return WavFormat::kWavFormatIeeeFloat;
140   }
141 
142   RTC_CHECK(false) << "Unsupported WAV format";
143 }
144 
RiffChunkSize(size_t bytes_in_payload,size_t header_size)145 uint32_t RiffChunkSize(size_t bytes_in_payload, size_t header_size) {
146   return static_cast<uint32_t>(bytes_in_payload + header_size -
147                                sizeof(ChunkHeader));
148 }
149 
ByteRate(size_t num_channels,int sample_rate,size_t bytes_per_sample)150 uint32_t ByteRate(size_t num_channels,
151                   int sample_rate,
152                   size_t bytes_per_sample) {
153   return static_cast<uint32_t>(num_channels * sample_rate * bytes_per_sample);
154 }
155 
BlockAlign(size_t num_channels,size_t bytes_per_sample)156 uint16_t BlockAlign(size_t num_channels, size_t bytes_per_sample) {
157   return static_cast<uint16_t>(num_channels * bytes_per_sample);
158 }
159 
160 // Finds a chunk having the sought ID. If found, then `readable` points to the
161 // first byte of the sought chunk data. If not found, the end of the file is
162 // reached.
FindWaveChunk(ChunkHeader * chunk_header,WavHeaderReader * readable,const std::string sought_chunk_id)163 bool FindWaveChunk(ChunkHeader* chunk_header,
164                    WavHeaderReader* readable,
165                    const std::string sought_chunk_id) {
166   RTC_DCHECK_EQ(sought_chunk_id.size(), 4);
167   while (true) {
168     if (readable->Read(chunk_header, sizeof(*chunk_header)) !=
169         sizeof(*chunk_header))
170       return false;  // EOF.
171     if (ReadFourCC(chunk_header->ID) == sought_chunk_id)
172       return true;  // Sought chunk found.
173     // Ignore current chunk by skipping its payload.
174     if (!readable->SeekForward(chunk_header->Size))
175       return false;  // EOF or error.
176   }
177 }
178 
ReadFmtChunkData(FmtPcmSubchunk * fmt_subchunk,WavHeaderReader * readable)179 bool ReadFmtChunkData(FmtPcmSubchunk* fmt_subchunk, WavHeaderReader* readable) {
180   // Reads "fmt " chunk payload.
181   if (readable->Read(&(fmt_subchunk->AudioFormat), kFmtPcmSubchunkSize) !=
182       kFmtPcmSubchunkSize)
183     return false;
184   const uint32_t fmt_size = fmt_subchunk->header.Size;
185   if (fmt_size != kFmtPcmSubchunkSize) {
186     // There is an optional two-byte extension field permitted to be present
187     // with PCM, but which must be zero.
188     int16_t ext_size;
189     if (kFmtPcmSubchunkSize + sizeof(ext_size) != fmt_size)
190       return false;
191     if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
192       return false;
193     if (ext_size != 0)
194       return false;
195   }
196   return true;
197 }
198 
WritePcmWavHeader(size_t num_channels,int sample_rate,size_t bytes_per_sample,size_t num_samples,uint8_t * buf,size_t * header_size)199 void WritePcmWavHeader(size_t num_channels,
200                        int sample_rate,
201                        size_t bytes_per_sample,
202                        size_t num_samples,
203                        uint8_t* buf,
204                        size_t* header_size) {
205   RTC_CHECK(buf);
206   RTC_CHECK(header_size);
207   *header_size = kPcmWavHeaderSize;
208   auto header = rtc::MsanUninitialized<WavHeaderPcm>({});
209   const size_t bytes_in_payload = bytes_per_sample * num_samples;
210 
211   header.riff.header.ID = PackFourCC('R', 'I', 'F', 'F');
212   header.riff.header.Size = RiffChunkSize(bytes_in_payload, *header_size);
213   header.riff.Format = PackFourCC('W', 'A', 'V', 'E');
214   header.fmt.header.ID = PackFourCC('f', 'm', 't', ' ');
215   header.fmt.header.Size = kFmtPcmSubchunkSize;
216   header.fmt.AudioFormat = MapWavFormatToHeaderField(WavFormat::kWavFormatPcm);
217   header.fmt.NumChannels = static_cast<uint16_t>(num_channels);
218   header.fmt.SampleRate = sample_rate;
219   header.fmt.ByteRate = ByteRate(num_channels, sample_rate, bytes_per_sample);
220   header.fmt.BlockAlign = BlockAlign(num_channels, bytes_per_sample);
221   header.fmt.BitsPerSample = static_cast<uint16_t>(8 * bytes_per_sample);
222   header.data.header.ID = PackFourCC('d', 'a', 't', 'a');
223   header.data.header.Size = static_cast<uint32_t>(bytes_in_payload);
224 
225   // Do an extra copy rather than writing everything to buf directly, since buf
226   // might not be correctly aligned.
227   memcpy(buf, &header, *header_size);
228 }
229 
WriteIeeeFloatWavHeader(size_t num_channels,int sample_rate,size_t bytes_per_sample,size_t num_samples,uint8_t * buf,size_t * header_size)230 void WriteIeeeFloatWavHeader(size_t num_channels,
231                              int sample_rate,
232                              size_t bytes_per_sample,
233                              size_t num_samples,
234                              uint8_t* buf,
235                              size_t* header_size) {
236   RTC_CHECK(buf);
237   RTC_CHECK(header_size);
238   *header_size = kIeeeFloatWavHeaderSize;
239   auto header = rtc::MsanUninitialized<WavHeaderIeeeFloat>({});
240   const size_t bytes_in_payload = bytes_per_sample * num_samples;
241 
242   header.riff.header.ID = PackFourCC('R', 'I', 'F', 'F');
243   header.riff.header.Size = RiffChunkSize(bytes_in_payload, *header_size);
244   header.riff.Format = PackFourCC('W', 'A', 'V', 'E');
245   header.fmt.header.ID = PackFourCC('f', 'm', 't', ' ');
246   header.fmt.header.Size = kFmtIeeeFloatSubchunkSize;
247   header.fmt.AudioFormat =
248       MapWavFormatToHeaderField(WavFormat::kWavFormatIeeeFloat);
249   header.fmt.NumChannels = static_cast<uint16_t>(num_channels);
250   header.fmt.SampleRate = sample_rate;
251   header.fmt.ByteRate = ByteRate(num_channels, sample_rate, bytes_per_sample);
252   header.fmt.BlockAlign = BlockAlign(num_channels, bytes_per_sample);
253   header.fmt.BitsPerSample = static_cast<uint16_t>(8 * bytes_per_sample);
254   header.fmt.ExtensionSize = 0;
255   header.fact.header.ID = PackFourCC('f', 'a', 'c', 't');
256   header.fact.header.Size = 4;
257   header.fact.SampleLength = static_cast<uint32_t>(num_channels * num_samples);
258   header.data.header.ID = PackFourCC('d', 'a', 't', 'a');
259   header.data.header.Size = static_cast<uint32_t>(bytes_in_payload);
260 
261   // Do an extra copy rather than writing everything to buf directly, since buf
262   // might not be correctly aligned.
263   memcpy(buf, &header, *header_size);
264 }
265 
266 // Returns the number of bytes per sample for the format.
GetFormatBytesPerSample(WavFormat format)267 size_t GetFormatBytesPerSample(WavFormat format) {
268   switch (format) {
269     case WavFormat::kWavFormatPcm:
270       // Other values may be OK, but for now we're conservative.
271       return 2;
272     case WavFormat::kWavFormatALaw:
273     case WavFormat::kWavFormatMuLaw:
274       return 1;
275     case WavFormat::kWavFormatIeeeFloat:
276       return 4;
277   }
278   RTC_CHECK_NOTREACHED();
279 }
280 
CheckWavParameters(size_t num_channels,int sample_rate,WavFormat format,size_t bytes_per_sample,size_t num_samples)281 bool CheckWavParameters(size_t num_channels,
282                         int sample_rate,
283                         WavFormat format,
284                         size_t bytes_per_sample,
285                         size_t num_samples) {
286   // num_channels, sample_rate, and bytes_per_sample must be positive, must fit
287   // in their respective fields, and their product must fit in the 32-bit
288   // ByteRate field.
289   if (num_channels == 0 || sample_rate <= 0 || bytes_per_sample == 0)
290     return false;
291   if (static_cast<uint64_t>(sample_rate) > std::numeric_limits<uint32_t>::max())
292     return false;
293   if (num_channels > std::numeric_limits<uint16_t>::max())
294     return false;
295   if (static_cast<uint64_t>(bytes_per_sample) * 8 >
296       std::numeric_limits<uint16_t>::max())
297     return false;
298   if (static_cast<uint64_t>(sample_rate) * num_channels * bytes_per_sample >
299       std::numeric_limits<uint32_t>::max())
300     return false;
301 
302   // format and bytes_per_sample must agree.
303   switch (format) {
304     case WavFormat::kWavFormatPcm:
305       // Other values may be OK, but for now we're conservative:
306       if (bytes_per_sample != 1 && bytes_per_sample != 2)
307         return false;
308       break;
309     case WavFormat::kWavFormatALaw:
310     case WavFormat::kWavFormatMuLaw:
311       if (bytes_per_sample != 1)
312         return false;
313       break;
314     case WavFormat::kWavFormatIeeeFloat:
315       if (bytes_per_sample != 4)
316         return false;
317       break;
318     default:
319       return false;
320   }
321 
322   // The number of bytes in the file, not counting the first ChunkHeader, must
323   // be less than 2^32; otherwise, the ChunkSize field overflows.
324   const size_t header_size = kPcmWavHeaderSize - sizeof(ChunkHeader);
325   const size_t max_samples =
326       (std::numeric_limits<uint32_t>::max() - header_size) / bytes_per_sample;
327   if (num_samples > max_samples)
328     return false;
329 
330   // Each channel must have the same number of samples.
331   if (num_samples % num_channels != 0)
332     return false;
333 
334   return true;
335 }
336 
337 }  // namespace
338 
CheckWavParameters(size_t num_channels,int sample_rate,WavFormat format,size_t num_samples)339 bool CheckWavParameters(size_t num_channels,
340                         int sample_rate,
341                         WavFormat format,
342                         size_t num_samples) {
343   return CheckWavParameters(num_channels, sample_rate, format,
344                             GetFormatBytesPerSample(format), num_samples);
345 }
346 
WriteWavHeader(size_t num_channels,int sample_rate,WavFormat format,size_t num_samples,uint8_t * buf,size_t * header_size)347 void WriteWavHeader(size_t num_channels,
348                     int sample_rate,
349                     WavFormat format,
350                     size_t num_samples,
351                     uint8_t* buf,
352                     size_t* header_size) {
353   RTC_CHECK(buf);
354   RTC_CHECK(header_size);
355 
356   const size_t bytes_per_sample = GetFormatBytesPerSample(format);
357   RTC_CHECK(CheckWavParameters(num_channels, sample_rate, format,
358                                bytes_per_sample, num_samples));
359   if (format == WavFormat::kWavFormatPcm) {
360     WritePcmWavHeader(num_channels, sample_rate, bytes_per_sample, num_samples,
361                       buf, header_size);
362   } else {
363     RTC_CHECK_EQ(format, WavFormat::kWavFormatIeeeFloat);
364     WriteIeeeFloatWavHeader(num_channels, sample_rate, bytes_per_sample,
365                             num_samples, buf, header_size);
366   }
367 }
368 
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)369 bool ReadWavHeader(WavHeaderReader* readable,
370                    size_t* num_channels,
371                    int* sample_rate,
372                    WavFormat* format,
373                    size_t* bytes_per_sample,
374                    size_t* num_samples,
375                    int64_t* data_start_pos) {
376   // Read using the PCM header, even though it might be float Wav file
377   auto header = rtc::MsanUninitialized<WavHeaderPcm>({});
378 
379   // Read RIFF chunk.
380   if (readable->Read(&header.riff, sizeof(header.riff)) != sizeof(header.riff))
381     return false;
382   if (ReadFourCC(header.riff.header.ID) != "RIFF")
383     return false;
384   if (ReadFourCC(header.riff.Format) != "WAVE")
385     return false;
386 
387   // Find "fmt " and "data" chunks. While the official Wave file specification
388   // does not put requirements on the chunks order, it is uncommon to find the
389   // "data" chunk before the "fmt " one. The code below fails if this is not the
390   // case.
391   if (!FindWaveChunk(&header.fmt.header, readable, "fmt ")) {
392     RTC_LOG(LS_ERROR) << "Cannot find 'fmt ' chunk.";
393     return false;
394   }
395   if (!ReadFmtChunkData(&header.fmt, readable)) {
396     RTC_LOG(LS_ERROR) << "Cannot read 'fmt ' chunk.";
397     return false;
398   }
399   if (!FindWaveChunk(&header.data.header, readable, "data")) {
400     RTC_LOG(LS_ERROR) << "Cannot find 'data' chunk.";
401     return false;
402   }
403 
404   // Parse needed fields.
405   *format = MapHeaderFieldToWavFormat(header.fmt.AudioFormat);
406   *num_channels = header.fmt.NumChannels;
407   *sample_rate = header.fmt.SampleRate;
408   *bytes_per_sample = header.fmt.BitsPerSample / 8;
409   const size_t bytes_in_payload = header.data.header.Size;
410   if (*bytes_per_sample == 0)
411     return false;
412   *num_samples = bytes_in_payload / *bytes_per_sample;
413 
414   const size_t header_size = *format == WavFormat::kWavFormatPcm
415                                  ? kPcmWavHeaderSize
416                                  : kIeeeFloatWavHeaderSize;
417 
418   if (header.riff.header.Size < RiffChunkSize(bytes_in_payload, header_size))
419     return false;
420   if (header.fmt.ByteRate !=
421       ByteRate(*num_channels, *sample_rate, *bytes_per_sample))
422     return false;
423   if (header.fmt.BlockAlign != BlockAlign(*num_channels, *bytes_per_sample))
424     return false;
425 
426   if (!CheckWavParameters(*num_channels, *sample_rate, *format,
427                           *bytes_per_sample, *num_samples)) {
428     return false;
429   }
430 
431   *data_start_pos = readable->GetPosition();
432   return true;
433 }
434 
435 }  // namespace webrtc
436