aboutsummaryrefslogtreecommitdiff
path: root/webrtc/common_audio/wav_header.cc
blob: 402ea1791604943344a524152f350931e41e94a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

// Based on the WAV file format documentation at
// https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ and
// http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html

#include "webrtc/common_audio/wav_header.h"

#include <algorithm>
#include <cstring>
#include <limits>
#include <string>

#include "webrtc/base/checks.h"
#include "webrtc/common_audio/include/audio_util.h"

namespace webrtc {
namespace {

struct ChunkHeader {
  uint32_t ID;
  uint32_t Size;
};
static_assert(sizeof(ChunkHeader) == 8, "ChunkHeader size");

// We can't nest this definition in WavHeader, because VS2013 gives an error
// on sizeof(WavHeader::fmt): "error C2070: 'unknown': illegal sizeof operand".
struct FmtSubchunk {
  ChunkHeader header;
  uint16_t AudioFormat;
  uint16_t NumChannels;
  uint32_t SampleRate;
  uint32_t ByteRate;
  uint16_t BlockAlign;
  uint16_t BitsPerSample;
};
static_assert(sizeof(FmtSubchunk) == 24, "FmtSubchunk size");
const uint32_t kFmtSubchunkSize = sizeof(FmtSubchunk) - sizeof(ChunkHeader);

struct WavHeader {
  struct {
    ChunkHeader header;
    uint32_t Format;
  } riff;
  FmtSubchunk fmt;
  struct {
    ChunkHeader header;
  } data;
};
static_assert(sizeof(WavHeader) == kWavHeaderSize, "no padding in header");

}  // namespace

bool CheckWavParameters(size_t num_channels,
                        int sample_rate,
                        WavFormat format,
                        size_t bytes_per_sample,
                        size_t num_samples) {
  // num_channels, sample_rate, and bytes_per_sample must be positive, must fit
  // in their respective fields, and their product must fit in the 32-bit
  // ByteRate field.
  if (num_channels == 0 || sample_rate <= 0 || bytes_per_sample == 0)
    return false;
  if (static_cast<uint64_t>(sample_rate) > std::numeric_limits<uint32_t>::max())
    return false;
  if (num_channels > std::numeric_limits<uint16_t>::max())
    return false;
  if (static_cast<uint64_t>(bytes_per_sample) * 8 >
      std::numeric_limits<uint16_t>::max())
    return false;
  if (static_cast<uint64_t>(sample_rate) * num_channels * bytes_per_sample >
      std::numeric_limits<uint32_t>::max())
    return false;

  // format and bytes_per_sample must agree.
  switch (format) {
    case kWavFormatPcm:
      // Other values may be OK, but for now we're conservative:
      if (bytes_per_sample != 1 && bytes_per_sample != 2)
        return false;
      break;
    case kWavFormatALaw:
    case kWavFormatMuLaw:
      if (bytes_per_sample != 1)
        return false;
      break;
    default:
      return false;
  }

  // The number of bytes in the file, not counting the first ChunkHeader, must
  // be less than 2^32; otherwise, the ChunkSize field overflows.
  const size_t header_size = kWavHeaderSize - sizeof(ChunkHeader);
  const size_t max_samples =
      (std::numeric_limits<uint32_t>::max() - header_size) / bytes_per_sample;
  if (num_samples > max_samples)
    return false;

  // Each channel must have the same number of samples.
  if (num_samples % num_channels != 0)
    return false;

  return true;
}

#ifdef WEBRTC_ARCH_LITTLE_ENDIAN
static inline void WriteLE16(uint16_t* f, uint16_t x) { *f = x; }
static inline void WriteLE32(uint32_t* f, uint32_t x) { *f = x; }
static inline void WriteFourCC(uint32_t* f, char a, char b, char c, char d) {
  *f = static_cast<uint32_t>(a)
      | static_cast<uint32_t>(b) << 8
      | static_cast<uint32_t>(c) << 16
      | static_cast<uint32_t>(d) << 24;
}

static inline uint16_t ReadLE16(uint16_t x) { return x; }
static inline uint32_t ReadLE32(uint32_t x) { return x; }
static inline std::string ReadFourCC(uint32_t x) {
  return std::string(reinterpret_cast<char*>(&x), 4);
}
#else
#error "Write be-to-le conversion functions"
#endif

static inline uint32_t RiffChunkSize(size_t bytes_in_payload) {
  return static_cast<uint32_t>(
      bytes_in_payload + kWavHeaderSize - sizeof(ChunkHeader));
}

static inline uint32_t ByteRate(size_t num_channels, int sample_rate,
                                size_t bytes_per_sample) {
  return static_cast<uint32_t>(num_channels * sample_rate * bytes_per_sample);
}

static inline uint16_t BlockAlign(size_t num_channels,
                                  size_t bytes_per_sample) {
  return static_cast<uint16_t>(num_channels * bytes_per_sample);
}

void WriteWavHeader(uint8_t* buf,
                    size_t num_channels,
                    int sample_rate,
                    WavFormat format,
                    size_t bytes_per_sample,
                    size_t num_samples) {
  RTC_CHECK(CheckWavParameters(num_channels, sample_rate, format,
                               bytes_per_sample, num_samples));

  WavHeader header;
  const size_t bytes_in_payload = bytes_per_sample * num_samples;

  WriteFourCC(&header.riff.header.ID, 'R', 'I', 'F', 'F');
  WriteLE32(&header.riff.header.Size, RiffChunkSize(bytes_in_payload));
  WriteFourCC(&header.riff.Format, 'W', 'A', 'V', 'E');

  WriteFourCC(&header.fmt.header.ID, 'f', 'm', 't', ' ');
  WriteLE32(&header.fmt.header.Size, kFmtSubchunkSize);
  WriteLE16(&header.fmt.AudioFormat, format);
  WriteLE16(&header.fmt.NumChannels, static_cast<uint16_t>(num_channels));
  WriteLE32(&header.fmt.SampleRate, sample_rate);
  WriteLE32(&header.fmt.ByteRate, ByteRate(num_channels, sample_rate,
                                           bytes_per_sample));
  WriteLE16(&header.fmt.BlockAlign, BlockAlign(num_channels, bytes_per_sample));
  WriteLE16(&header.fmt.BitsPerSample,
            static_cast<uint16_t>(8 * bytes_per_sample));

  WriteFourCC(&header.data.header.ID, 'd', 'a', 't', 'a');
  WriteLE32(&header.data.header.Size, static_cast<uint32_t>(bytes_in_payload));

  // Do an extra copy rather than writing everything to buf directly, since buf
  // might not be correctly aligned.
  memcpy(buf, &header, kWavHeaderSize);
}

bool ReadWavHeader(ReadableWav* readable,
                   size_t* num_channels,
                   int* sample_rate,
                   WavFormat* format,
                   size_t* bytes_per_sample,
                   size_t* num_samples) {
  WavHeader header;
  if (readable->Read(&header, kWavHeaderSize - sizeof(header.data)) !=
      kWavHeaderSize - sizeof(header.data))
    return false;

  const uint32_t fmt_size = ReadLE32(header.fmt.header.Size);
  if (fmt_size != kFmtSubchunkSize) {
    // There is an optional two-byte extension field permitted to be present
    // with PCM, but which must be zero.
    int16_t ext_size;
    if (kFmtSubchunkSize + sizeof(ext_size) != fmt_size)
      return false;
    if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
      return false;
    if (ext_size != 0)
      return false;
  }
  if (readable->Read(&header.data, sizeof(header.data)) != sizeof(header.data))
    return false;

  // Parse needed fields.
  *format = static_cast<WavFormat>(ReadLE16(header.fmt.AudioFormat));
  *num_channels = ReadLE16(header.fmt.NumChannels);
  *sample_rate = ReadLE32(header.fmt.SampleRate);
  *bytes_per_sample = ReadLE16(header.fmt.BitsPerSample) / 8;
  const size_t bytes_in_payload = ReadLE32(header.data.header.Size);
  if (*bytes_per_sample == 0)
    return false;
  *num_samples = bytes_in_payload / *bytes_per_sample;

  // Sanity check remaining fields.
  if (ReadFourCC(header.riff.header.ID) != "RIFF")
    return false;
  if (ReadFourCC(header.riff.Format) != "WAVE")
    return false;
  if (ReadFourCC(header.fmt.header.ID) != "fmt ")
    return false;
  if (ReadFourCC(header.data.header.ID) != "data")
    return false;

  if (ReadLE32(header.riff.header.Size) < RiffChunkSize(bytes_in_payload))
    return false;
  if (ReadLE32(header.fmt.ByteRate) !=
      ByteRate(*num_channels, *sample_rate, *bytes_per_sample))
    return false;
  if (ReadLE16(header.fmt.BlockAlign) !=
      BlockAlign(*num_channels, *bytes_per_sample))
    return false;

  return CheckWavParameters(*num_channels, *sample_rate, *format,
                            *bytes_per_sample, *num_samples);
}


}  // namespace webrtc