blob: 15eb1f844e51a1a3be594b032dae400dfe499e4a [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.
Niels Möller767efab2019-06-27 12:15:06 +0200111bool FindWaveChunk(ChunkHeader* chunk_header,
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100112 ReadableWav* readable,
113 const std::string sought_chunk_id) {
114 RTC_DCHECK_EQ(sought_chunk_id.size(), 4);
Niels Möller767efab2019-06-27 12:15:06 +0200115 while (true) {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100116 if (readable->Read(chunk_header, sizeof(*chunk_header)) !=
117 sizeof(*chunk_header))
Niels Möller767efab2019-06-27 12:15:06 +0200118 return false; // EOF.
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100119 if (ReadFourCC(chunk_header->ID) == sought_chunk_id)
Niels Möller767efab2019-06-27 12:15:06 +0200120 return true; // Sought chunk found.
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100121 // Ignore current chunk by skipping its payload.
122 if (!readable->SeekForward(chunk_header->Size))
Niels Möller767efab2019-06-27 12:15:06 +0200123 return false; // EOF or error.
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100124 }
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100125}
126
127bool ReadFmtChunkData(FmtSubchunk* fmt_subchunk, ReadableWav* readable) {
128 // Reads "fmt " chunk payload.
129 if (readable->Read(&(fmt_subchunk->AudioFormat), kFmtSubchunkSize) !=
130 kFmtSubchunkSize)
131 return false;
132 const uint32_t fmt_size = ReadLE32(fmt_subchunk->header.Size);
133 if (fmt_size != kFmtSubchunkSize) {
134 // There is an optional two-byte extension field permitted to be present
135 // with PCM, but which must be zero.
136 int16_t ext_size;
137 if (kFmtSubchunkSize + sizeof(ext_size) != fmt_size)
138 return false;
139 if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
140 return false;
141 if (ext_size != 0)
142 return false;
143 }
144 return true;
145}
146
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000147} // namespace
148
Peter Kasting69558702016-01-12 16:26:35 -0800149bool CheckWavParameters(size_t num_channels,
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000150 int sample_rate,
151 WavFormat format,
pkasting25702cb2016-01-08 13:50:27 -0800152 size_t bytes_per_sample,
153 size_t num_samples) {
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000154 // num_channels, sample_rate, and bytes_per_sample must be positive, must fit
155 // in their respective fields, and their product must fit in the 32-bit
156 // ByteRate field.
Peter Kasting69558702016-01-12 16:26:35 -0800157 if (num_channels == 0 || sample_rate <= 0 || bytes_per_sample == 0)
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000158 return false;
159 if (static_cast<uint64_t>(sample_rate) > std::numeric_limits<uint32_t>::max())
160 return false;
Peter Kasting69558702016-01-12 16:26:35 -0800161 if (num_channels > std::numeric_limits<uint16_t>::max())
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000162 return false;
163 if (static_cast<uint64_t>(bytes_per_sample) * 8 >
164 std::numeric_limits<uint16_t>::max())
165 return false;
166 if (static_cast<uint64_t>(sample_rate) * num_channels * bytes_per_sample >
167 std::numeric_limits<uint32_t>::max())
168 return false;
169
170 // format and bytes_per_sample must agree.
171 switch (format) {
172 case kWavFormatPcm:
173 // Other values may be OK, but for now we're conservative:
174 if (bytes_per_sample != 1 && bytes_per_sample != 2)
175 return false;
176 break;
177 case kWavFormatALaw:
178 case kWavFormatMuLaw:
179 if (bytes_per_sample != 1)
180 return false;
181 break;
182 default:
183 return false;
184 }
185
186 // The number of bytes in the file, not counting the first ChunkHeader, must
187 // be less than 2^32; otherwise, the ChunkSize field overflows.
pkasting25702cb2016-01-08 13:50:27 -0800188 const size_t header_size = kWavHeaderSize - sizeof(ChunkHeader);
189 const size_t max_samples =
190 (std::numeric_limits<uint32_t>::max() - header_size) / bytes_per_sample;
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000191 if (num_samples > max_samples)
192 return false;
193
194 // Each channel must have the same number of samples.
195 if (num_samples % num_channels != 0)
196 return false;
197
198 return true;
199}
200
andrew@webrtc.orgf866b2d2014-11-03 18:20:06 +0000201void WriteWavHeader(uint8_t* buf,
Peter Kasting69558702016-01-12 16:26:35 -0800202 size_t num_channels,
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000203 int sample_rate,
204 WavFormat format,
pkasting25702cb2016-01-08 13:50:27 -0800205 size_t bytes_per_sample,
206 size_t num_samples) {
henrikg91d6ede2015-09-17 00:24:34 -0700207 RTC_CHECK(CheckWavParameters(num_channels, sample_rate, format,
208 bytes_per_sample, num_samples));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000209
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100210 auto header = rtc::MsanUninitialized<WavHeader>({});
pkasting25702cb2016-01-08 13:50:27 -0800211 const size_t bytes_in_payload = bytes_per_sample * num_samples;
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000212
213 WriteFourCC(&header.riff.header.ID, 'R', 'I', 'F', 'F');
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000214 WriteLE32(&header.riff.header.Size, RiffChunkSize(bytes_in_payload));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000215 WriteFourCC(&header.riff.Format, 'W', 'A', 'V', 'E');
216
217 WriteFourCC(&header.fmt.header.ID, 'f', 'm', 't', ' ');
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000218 WriteLE32(&header.fmt.header.Size, kFmtSubchunkSize);
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000219 WriteLE16(&header.fmt.AudioFormat, format);
pkasting25702cb2016-01-08 13:50:27 -0800220 WriteLE16(&header.fmt.NumChannels, static_cast<uint16_t>(num_channels));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000221 WriteLE32(&header.fmt.SampleRate, sample_rate);
Yves Gerey665174f2018-06-19 15:03:05 +0200222 WriteLE32(&header.fmt.ByteRate,
223 ByteRate(num_channels, sample_rate, bytes_per_sample));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000224 WriteLE16(&header.fmt.BlockAlign, BlockAlign(num_channels, bytes_per_sample));
pkasting25702cb2016-01-08 13:50:27 -0800225 WriteLE16(&header.fmt.BitsPerSample,
226 static_cast<uint16_t>(8 * bytes_per_sample));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000227
228 WriteFourCC(&header.data.header.ID, 'd', 'a', 't', 'a');
pkasting25702cb2016-01-08 13:50:27 -0800229 WriteLE32(&header.data.header.Size, static_cast<uint32_t>(bytes_in_payload));
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000230
231 // Do an extra copy rather than writing everything to buf directly, since buf
232 // might not be correctly aligned.
233 memcpy(buf, &header, kWavHeaderSize);
234}
235
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000236bool ReadWavHeader(ReadableWav* readable,
Peter Kasting69558702016-01-12 16:26:35 -0800237 size_t* num_channels,
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000238 int* sample_rate,
239 WavFormat* format,
pkasting25702cb2016-01-08 13:50:27 -0800240 size_t* bytes_per_sample,
241 size_t* num_samples) {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100242 auto header = rtc::MsanUninitialized<WavHeader>({});
243
244 // Read RIFF chunk.
245 if (readable->Read(&header.riff, sizeof(header.riff)) != sizeof(header.riff))
246 return false;
247 if (ReadFourCC(header.riff.header.ID) != "RIFF")
248 return false;
249 if (ReadFourCC(header.riff.Format) != "WAVE")
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000250 return false;
251
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100252 // Find "fmt " and "data" chunks. While the official Wave file specification
253 // does not put requirements on the chunks order, it is uncommon to find the
254 // "data" chunk before the "fmt " one. The code below fails if this is not the
255 // case.
Niels Möller767efab2019-06-27 12:15:06 +0200256 if (!FindWaveChunk(&header.fmt.header, readable, "fmt ")) {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100257 RTC_LOG(LS_ERROR) << "Cannot find 'fmt ' chunk.";
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000258 return false;
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100259 }
260 if (!ReadFmtChunkData(&header.fmt, readable)) {
261 RTC_LOG(LS_ERROR) << "Cannot read 'fmt ' chunk.";
262 return false;
263 }
Niels Möller767efab2019-06-27 12:15:06 +0200264 if (!FindWaveChunk(&header.data.header, readable, "data")) {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +0100265 RTC_LOG(LS_ERROR) << "Cannot find 'data' chunk.";
266 return false;
267 }
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000268
269 // Parse needed fields.
270 *format = static_cast<WavFormat>(ReadLE16(header.fmt.AudioFormat));
271 *num_channels = ReadLE16(header.fmt.NumChannels);
272 *sample_rate = ReadLE32(header.fmt.SampleRate);
273 *bytes_per_sample = ReadLE16(header.fmt.BitsPerSample) / 8;
pkasting25702cb2016-01-08 13:50:27 -0800274 const size_t bytes_in_payload = ReadLE32(header.data.header.Size);
275 if (*bytes_per_sample == 0)
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000276 return false;
277 *num_samples = bytes_in_payload / *bytes_per_sample;
278
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000279 if (ReadLE32(header.riff.header.Size) < RiffChunkSize(bytes_in_payload))
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000280 return false;
281 if (ReadLE32(header.fmt.ByteRate) !=
282 ByteRate(*num_channels, *sample_rate, *bytes_per_sample))
283 return false;
284 if (ReadLE16(header.fmt.BlockAlign) !=
285 BlockAlign(*num_channels, *bytes_per_sample))
286 return false;
287
288 return CheckWavParameters(*num_channels, *sample_rate, *format,
289 *bytes_per_sample, *num_samples);
290}
291
kwiberg@webrtc.org877083c2014-08-20 07:42:46 +0000292} // namespace webrtc