blob: 9d602e9a010d365ff5d857e358b1aeadaf6f301b [file] [log] [blame]
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "common_audio/wav_header.h"
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +000016
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +000017#include <cstring>
18#include <limits>
andrew@webrtc.org048c5022014-12-16 20:17:21 +000019#include <string>
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +000020
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/checks.h"
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010022#include "rtc_base/logging.h"
23#include "rtc_base/sanitizer.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020024#include "rtc_base/system/arch.h"
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +000025
26namespace webrtc {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000027namespace {
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +000028
29struct ChunkHeader {
30 uint32_t ID;
31 uint32_t Size;
32};
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +000033static_assert(sizeof(ChunkHeader) == 8, "ChunkHeader size");
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +000034
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010035struct RiffHeader {
36 ChunkHeader header;
37 uint32_t Format;
38};
39
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000040// We can't nest this definition in WavHeader, because VS2013 gives an error
41// on sizeof(WavHeader::fmt): "error C2070: 'unknown': illegal sizeof operand".
42struct FmtSubchunk {
43 ChunkHeader header;
44 uint16_t AudioFormat;
45 uint16_t NumChannels;
46 uint32_t SampleRate;
47 uint32_t ByteRate;
48 uint16_t BlockAlign;
49 uint16_t BitsPerSample;
50};
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +000051static_assert(sizeof(FmtSubchunk) == 24, "FmtSubchunk size");
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000052const uint32_t kFmtSubchunkSize = sizeof(FmtSubchunk) - sizeof(ChunkHeader);
53
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010054// Simple wav header. It does not include chunks that are not essential to read
55// audio samples.
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000056struct WavHeader {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010057 WavHeader(const WavHeader&) = default;
58 WavHeader& operator=(const WavHeader&) = default;
59 RiffHeader riff;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000060 FmtSubchunk fmt;
61 struct {
62 ChunkHeader header;
63 } data;
64};
kwiberg@webrtc.org2ebfac52015-01-14 10:51:54 +000065static_assert(sizeof(WavHeader) == kWavHeaderSize, "no padding in header");
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000066
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010067#ifdef WEBRTC_ARCH_LITTLE_ENDIAN
68static inline void WriteLE16(uint16_t* f, uint16_t x) {
69 *f = x;
70}
71static inline void WriteLE32(uint32_t* f, uint32_t x) {
72 *f = x;
73}
74static inline void WriteFourCC(uint32_t* f, char a, char b, char c, char d) {
75 *f = static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 |
76 static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24;
77}
78
79static inline uint16_t ReadLE16(uint16_t x) {
80 return x;
81}
82static inline uint32_t ReadLE32(uint32_t x) {
83 return x;
84}
85static inline std::string ReadFourCC(uint32_t x) {
86 return std::string(reinterpret_cast<char*>(&x), 4);
87}
88#else
89#error "Write be-to-le conversion functions"
90#endif
91
92static inline uint32_t RiffChunkSize(size_t bytes_in_payload) {
93 return static_cast<uint32_t>(bytes_in_payload + kWavHeaderSize -
94 sizeof(ChunkHeader));
95}
96
97static inline uint32_t ByteRate(size_t num_channels,
98 int sample_rate,
99 size_t bytes_per_sample) {
100 return static_cast<uint32_t>(num_channels * sample_rate * bytes_per_sample);
101}
102
103static inline uint16_t BlockAlign(size_t num_channels,
104 size_t bytes_per_sample) {
105 return static_cast<uint16_t>(num_channels * bytes_per_sample);
106}
107
108// Finds a chunk having the sought ID. If found, then |readable| points to the
109// first byte of the sought chunk data. If not found, the end of the file is
110// reached.
111void FindWaveChunk(ChunkHeader* chunk_header,
112 ReadableWav* readable,
113 const std::string sought_chunk_id) {
114 RTC_DCHECK_EQ(sought_chunk_id.size(), 4);
115 while (!readable->Eof()) {
116 if (readable->Read(chunk_header, sizeof(*chunk_header)) !=
117 sizeof(*chunk_header))
118 return; // EOF.
119 if (ReadFourCC(chunk_header->ID) == sought_chunk_id)
120 return; // Sought chunk found.
121 // Ignore current chunk by skipping its payload.
122 if (!readable->SeekForward(chunk_header->Size))
123 return; // EOF or error.
124 }
Benjamin Wright8965fbc2019-03-14 14:39:02 -0700125 // EOF.
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100126}
127
128bool ReadFmtChunkData(FmtSubchunk* fmt_subchunk, ReadableWav* readable) {
129 // Reads "fmt " chunk payload.
130 if (readable->Read(&(fmt_subchunk->AudioFormat), kFmtSubchunkSize) !=
131 kFmtSubchunkSize)
132 return false;
133 const uint32_t fmt_size = ReadLE32(fmt_subchunk->header.Size);
134 if (fmt_size != kFmtSubchunkSize) {
135 // There is an optional two-byte extension field permitted to be present
136 // with PCM, but which must be zero.
137 int16_t ext_size;
138 if (kFmtSubchunkSize + sizeof(ext_size) != fmt_size)
139 return false;
140 if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
141 return false;
142 if (ext_size != 0)
143 return false;
144 }
145 return true;
146}
147
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000148} // namespace
149
Peter Kasting69558702016-01-12 16:26:35 -0800150bool CheckWavParameters(size_t num_channels,
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000151 int sample_rate,
152 WavFormat format,
pkasting25702cb2016-01-08 13:50:27 -0800153 size_t bytes_per_sample,
154 size_t num_samples) {
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000155 // num_channels, sample_rate, and bytes_per_sample must be positive, must fit
156 // in their respective fields, and their product must fit in the 32-bit
157 // ByteRate field.
Peter Kasting69558702016-01-12 16:26:35 -0800158 if (num_channels == 0 || sample_rate <= 0 || bytes_per_sample == 0)
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000159 return false;
160 if (static_cast<uint64_t>(sample_rate) > std::numeric_limits<uint32_t>::max())
161 return false;
Peter Kasting69558702016-01-12 16:26:35 -0800162 if (num_channels > std::numeric_limits<uint16_t>::max())
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000163 return false;
164 if (static_cast<uint64_t>(bytes_per_sample) * 8 >
165 std::numeric_limits<uint16_t>::max())
166 return false;
167 if (static_cast<uint64_t>(sample_rate) * num_channels * bytes_per_sample >
168 std::numeric_limits<uint32_t>::max())
169 return false;
170
171 // format and bytes_per_sample must agree.
172 switch (format) {
173 case kWavFormatPcm:
174 // Other values may be OK, but for now we're conservative:
175 if (bytes_per_sample != 1 && bytes_per_sample != 2)
176 return false;
177 break;
178 case kWavFormatALaw:
179 case kWavFormatMuLaw:
180 if (bytes_per_sample != 1)
181 return false;
182 break;
183 default:
184 return false;
185 }
186
187 // The number of bytes in the file, not counting the first ChunkHeader, must
188 // be less than 2^32; otherwise, the ChunkSize field overflows.
pkasting25702cb2016-01-08 13:50:27 -0800189 const size_t header_size = kWavHeaderSize - sizeof(ChunkHeader);
190 const size_t max_samples =
191 (std::numeric_limits<uint32_t>::max() - header_size) / bytes_per_sample;
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000192 if (num_samples > max_samples)
193 return false;
194
195 // Each channel must have the same number of samples.
196 if (num_samples % num_channels != 0)
197 return false;
198
199 return true;
200}
201
andrew@webrtc.orgf866b2d2014-11-03 18:20:06 +0000202void WriteWavHeader(uint8_t* buf,
Peter Kasting69558702016-01-12 16:26:35 -0800203 size_t num_channels,
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000204 int sample_rate,
205 WavFormat format,
pkasting25702cb2016-01-08 13:50:27 -0800206 size_t bytes_per_sample,
207 size_t num_samples) {
henrikg91d6ede2015-09-17 00:24:34 -0700208 RTC_CHECK(CheckWavParameters(num_channels, sample_rate, format,
209 bytes_per_sample, num_samples));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000210
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100211 auto header = rtc::MsanUninitialized<WavHeader>({});
pkasting25702cb2016-01-08 13:50:27 -0800212 const size_t bytes_in_payload = bytes_per_sample * num_samples;
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000213
214 WriteFourCC(&header.riff.header.ID, 'R', 'I', 'F', 'F');
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000215 WriteLE32(&header.riff.header.Size, RiffChunkSize(bytes_in_payload));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000216 WriteFourCC(&header.riff.Format, 'W', 'A', 'V', 'E');
217
218 WriteFourCC(&header.fmt.header.ID, 'f', 'm', 't', ' ');
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000219 WriteLE32(&header.fmt.header.Size, kFmtSubchunkSize);
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000220 WriteLE16(&header.fmt.AudioFormat, format);
pkasting25702cb2016-01-08 13:50:27 -0800221 WriteLE16(&header.fmt.NumChannels, static_cast<uint16_t>(num_channels));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000222 WriteLE32(&header.fmt.SampleRate, sample_rate);
Yves Gerey665174f2018-06-19 15:03:05 +0200223 WriteLE32(&header.fmt.ByteRate,
224 ByteRate(num_channels, sample_rate, bytes_per_sample));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000225 WriteLE16(&header.fmt.BlockAlign, BlockAlign(num_channels, bytes_per_sample));
pkasting25702cb2016-01-08 13:50:27 -0800226 WriteLE16(&header.fmt.BitsPerSample,
227 static_cast<uint16_t>(8 * bytes_per_sample));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000228
229 WriteFourCC(&header.data.header.ID, 'd', 'a', 't', 'a');
pkasting25702cb2016-01-08 13:50:27 -0800230 WriteLE32(&header.data.header.Size, static_cast<uint32_t>(bytes_in_payload));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000231
232 // Do an extra copy rather than writing everything to buf directly, since buf
233 // might not be correctly aligned.
234 memcpy(buf, &header, kWavHeaderSize);
235}
236
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000237bool ReadWavHeader(ReadableWav* readable,
Peter Kasting69558702016-01-12 16:26:35 -0800238 size_t* num_channels,
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000239 int* sample_rate,
240 WavFormat* format,
pkasting25702cb2016-01-08 13:50:27 -0800241 size_t* bytes_per_sample,
242 size_t* num_samples) {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100243 auto header = rtc::MsanUninitialized<WavHeader>({});
244
245 // Read RIFF chunk.
246 if (readable->Read(&header.riff, sizeof(header.riff)) != sizeof(header.riff))
247 return false;
248 if (ReadFourCC(header.riff.header.ID) != "RIFF")
249 return false;
250 if (ReadFourCC(header.riff.Format) != "WAVE")
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000251 return false;
252
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100253 // Find "fmt " and "data" chunks. While the official Wave file specification
254 // does not put requirements on the chunks order, it is uncommon to find the
255 // "data" chunk before the "fmt " one. The code below fails if this is not the
256 // case.
257 FindWaveChunk(&header.fmt.header, readable, "fmt ");
258 if (ReadFourCC(header.fmt.header.ID) != "fmt ") {
259 RTC_LOG(LS_ERROR) << "Cannot find 'fmt ' chunk.";
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000260 return false;
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100261 }
262 if (!ReadFmtChunkData(&header.fmt, readable)) {
263 RTC_LOG(LS_ERROR) << "Cannot read 'fmt ' chunk.";
264 return false;
265 }
266 if (readable->Eof()) {
267 RTC_LOG(LS_ERROR) << "'fmt ' chunk placed after 'data' chunk.";
268 return false;
269 }
270 FindWaveChunk(&header.data.header, readable, "data");
271 if (ReadFourCC(header.data.header.ID) != "data") {
272 RTC_LOG(LS_ERROR) << "Cannot find 'data' chunk.";
273 return false;
274 }
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000275
276 // Parse needed fields.
277 *format = static_cast<WavFormat>(ReadLE16(header.fmt.AudioFormat));
278 *num_channels = ReadLE16(header.fmt.NumChannels);
279 *sample_rate = ReadLE32(header.fmt.SampleRate);
280 *bytes_per_sample = ReadLE16(header.fmt.BitsPerSample) / 8;
pkasting25702cb2016-01-08 13:50:27 -0800281 const size_t bytes_in_payload = ReadLE32(header.data.header.Size);
282 if (*bytes_per_sample == 0)
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000283 return false;
284 *num_samples = bytes_in_payload / *bytes_per_sample;
285
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000286 if (ReadLE32(header.riff.header.Size) < RiffChunkSize(bytes_in_payload))
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000287 return false;
288 if (ReadLE32(header.fmt.ByteRate) !=
289 ByteRate(*num_channels, *sample_rate, *bytes_per_sample))
290 return false;
291 if (ReadLE16(header.fmt.BlockAlign) !=
292 BlockAlign(*num_channels, *bytes_per_sample))
293 return false;
294
295 return CheckWavParameters(*num_channels, *sample_rate, *format,
296 *bytes_per_sample, *num_samples);
297}
298
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000299} // namespace webrtc