You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

292 lines
9.9 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. // Based on the WAV file format documentation at
  11. // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ and
  12. // http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
  13. #include "common_audio/wav_header.h"
  14. #include <cstring>
  15. #include <limits>
  16. #include <string>
  17. #include "rtc_base/checks.h"
  18. #include "rtc_base/logging.h"
  19. #include "rtc_base/sanitizer.h"
  20. #include "rtc_base/system/arch.h"
  21. namespace webrtc {
  22. namespace {
  23. struct ChunkHeader {
  24. uint32_t ID;
  25. uint32_t Size;
  26. };
  27. static_assert(sizeof(ChunkHeader) == 8, "ChunkHeader size");
  28. struct RiffHeader {
  29. ChunkHeader header;
  30. uint32_t Format;
  31. };
  32. // We can't nest this definition in WavHeader, because VS2013 gives an error
  33. // on sizeof(WavHeader::fmt): "error C2070: 'unknown': illegal sizeof operand".
  34. struct FmtSubchunk {
  35. ChunkHeader header;
  36. uint16_t AudioFormat;
  37. uint16_t NumChannels;
  38. uint32_t SampleRate;
  39. uint32_t ByteRate;
  40. uint16_t BlockAlign;
  41. uint16_t BitsPerSample;
  42. };
  43. static_assert(sizeof(FmtSubchunk) == 24, "FmtSubchunk size");
  44. const uint32_t kFmtSubchunkSize = sizeof(FmtSubchunk) - sizeof(ChunkHeader);
  45. // Simple wav header. It does not include chunks that are not essential to read
  46. // audio samples.
  47. struct WavHeader {
  48. WavHeader(const WavHeader&) = default;
  49. WavHeader& operator=(const WavHeader&) = default;
  50. RiffHeader riff;
  51. FmtSubchunk fmt;
  52. struct {
  53. ChunkHeader header;
  54. } data;
  55. };
  56. static_assert(sizeof(WavHeader) == kWavHeaderSize, "no padding in header");
  57. #ifdef WEBRTC_ARCH_LITTLE_ENDIAN
  58. static inline void WriteLE16(uint16_t* f, uint16_t x) {
  59. *f = x;
  60. }
  61. static inline void WriteLE32(uint32_t* f, uint32_t x) {
  62. *f = x;
  63. }
  64. static inline void WriteFourCC(uint32_t* f, char a, char b, char c, char d) {
  65. *f = static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 |
  66. static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24;
  67. }
  68. static inline uint16_t ReadLE16(uint16_t x) {
  69. return x;
  70. }
  71. static inline uint32_t ReadLE32(uint32_t x) {
  72. return x;
  73. }
  74. static inline std::string ReadFourCC(uint32_t x) {
  75. return std::string(reinterpret_cast<char*>(&x), 4);
  76. }
  77. #else
  78. #error "Write be-to-le conversion functions"
  79. #endif
  80. static inline uint32_t RiffChunkSize(size_t bytes_in_payload) {
  81. return static_cast<uint32_t>(bytes_in_payload + kWavHeaderSize -
  82. sizeof(ChunkHeader));
  83. }
  84. static inline uint32_t ByteRate(size_t num_channels,
  85. int sample_rate,
  86. size_t bytes_per_sample) {
  87. return static_cast<uint32_t>(num_channels * sample_rate * bytes_per_sample);
  88. }
  89. static inline uint16_t BlockAlign(size_t num_channels,
  90. size_t bytes_per_sample) {
  91. return static_cast<uint16_t>(num_channels * bytes_per_sample);
  92. }
  93. // Finds a chunk having the sought ID. If found, then |readable| points to the
  94. // first byte of the sought chunk data. If not found, the end of the file is
  95. // reached.
  96. bool FindWaveChunk(ChunkHeader* chunk_header,
  97. ReadableWav* readable,
  98. const std::string sought_chunk_id) {
  99. RTC_DCHECK_EQ(sought_chunk_id.size(), 4);
  100. while (true) {
  101. if (readable->Read(chunk_header, sizeof(*chunk_header)) !=
  102. sizeof(*chunk_header))
  103. return false; // EOF.
  104. if (ReadFourCC(chunk_header->ID) == sought_chunk_id)
  105. return true; // Sought chunk found.
  106. // Ignore current chunk by skipping its payload.
  107. if (!readable->SeekForward(chunk_header->Size))
  108. return false; // EOF or error.
  109. }
  110. }
  111. bool ReadFmtChunkData(FmtSubchunk* fmt_subchunk, ReadableWav* readable) {
  112. // Reads "fmt " chunk payload.
  113. if (readable->Read(&(fmt_subchunk->AudioFormat), kFmtSubchunkSize) !=
  114. kFmtSubchunkSize)
  115. return false;
  116. const uint32_t fmt_size = ReadLE32(fmt_subchunk->header.Size);
  117. if (fmt_size != kFmtSubchunkSize) {
  118. // There is an optional two-byte extension field permitted to be present
  119. // with PCM, but which must be zero.
  120. int16_t ext_size;
  121. if (kFmtSubchunkSize + sizeof(ext_size) != fmt_size)
  122. return false;
  123. if (readable->Read(&ext_size, sizeof(ext_size)) != sizeof(ext_size))
  124. return false;
  125. if (ext_size != 0)
  126. return false;
  127. }
  128. return true;
  129. }
  130. } // namespace
  131. bool CheckWavParameters(size_t num_channels,
  132. int sample_rate,
  133. WavFormat format,
  134. size_t bytes_per_sample,
  135. size_t num_samples) {
  136. // num_channels, sample_rate, and bytes_per_sample must be positive, must fit
  137. // in their respective fields, and their product must fit in the 32-bit
  138. // ByteRate field.
  139. if (num_channels == 0 || sample_rate <= 0 || bytes_per_sample == 0)
  140. return false;
  141. if (static_cast<uint64_t>(sample_rate) > std::numeric_limits<uint32_t>::max())
  142. return false;
  143. if (num_channels > std::numeric_limits<uint16_t>::max())
  144. return false;
  145. if (static_cast<uint64_t>(bytes_per_sample) * 8 >
  146. std::numeric_limits<uint16_t>::max())
  147. return false;
  148. if (static_cast<uint64_t>(sample_rate) * num_channels * bytes_per_sample >
  149. std::numeric_limits<uint32_t>::max())
  150. return false;
  151. // format and bytes_per_sample must agree.
  152. switch (format) {
  153. case kWavFormatPcm:
  154. // Other values may be OK, but for now we're conservative:
  155. if (bytes_per_sample != 1 && bytes_per_sample != 2)
  156. return false;
  157. break;
  158. case kWavFormatALaw:
  159. case kWavFormatMuLaw:
  160. if (bytes_per_sample != 1)
  161. return false;
  162. break;
  163. default:
  164. return false;
  165. }
  166. // The number of bytes in the file, not counting the first ChunkHeader, must
  167. // be less than 2^32; otherwise, the ChunkSize field overflows.
  168. const size_t header_size = kWavHeaderSize - sizeof(ChunkHeader);
  169. const size_t max_samples =
  170. (std::numeric_limits<uint32_t>::max() - header_size) / bytes_per_sample;
  171. if (num_samples > max_samples)
  172. return false;
  173. // Each channel must have the same number of samples.
  174. if (num_samples % num_channels != 0)
  175. return false;
  176. return true;
  177. }
  178. void WriteWavHeader(uint8_t* buf,
  179. size_t num_channels,
  180. int sample_rate,
  181. WavFormat format,
  182. size_t bytes_per_sample,
  183. size_t num_samples) {
  184. RTC_CHECK(CheckWavParameters(num_channels, sample_rate, format,
  185. bytes_per_sample, num_samples));
  186. auto header = rtc::MsanUninitialized<WavHeader>({});
  187. const size_t bytes_in_payload = bytes_per_sample * num_samples;
  188. WriteFourCC(&header.riff.header.ID, 'R', 'I', 'F', 'F');
  189. WriteLE32(&header.riff.header.Size, RiffChunkSize(bytes_in_payload));
  190. WriteFourCC(&header.riff.Format, 'W', 'A', 'V', 'E');
  191. WriteFourCC(&header.fmt.header.ID, 'f', 'm', 't', ' ');
  192. WriteLE32(&header.fmt.header.Size, kFmtSubchunkSize);
  193. WriteLE16(&header.fmt.AudioFormat, format);
  194. WriteLE16(&header.fmt.NumChannels, static_cast<uint16_t>(num_channels));
  195. WriteLE32(&header.fmt.SampleRate, sample_rate);
  196. WriteLE32(&header.fmt.ByteRate,
  197. ByteRate(num_channels, sample_rate, bytes_per_sample));
  198. WriteLE16(&header.fmt.BlockAlign, BlockAlign(num_channels, bytes_per_sample));
  199. WriteLE16(&header.fmt.BitsPerSample,
  200. static_cast<uint16_t>(8 * bytes_per_sample));
  201. WriteFourCC(&header.data.header.ID, 'd', 'a', 't', 'a');
  202. WriteLE32(&header.data.header.Size, static_cast<uint32_t>(bytes_in_payload));
  203. // Do an extra copy rather than writing everything to buf directly, since buf
  204. // might not be correctly aligned.
  205. memcpy(buf, &header, kWavHeaderSize);
  206. }
  207. bool ReadWavHeader(ReadableWav* readable,
  208. size_t* num_channels,
  209. int* sample_rate,
  210. WavFormat* format,
  211. size_t* bytes_per_sample,
  212. size_t* num_samples) {
  213. auto header = rtc::MsanUninitialized<WavHeader>({});
  214. // Read RIFF chunk.
  215. if (readable->Read(&header.riff, sizeof(header.riff)) != sizeof(header.riff))
  216. return false;
  217. if (ReadFourCC(header.riff.header.ID) != "RIFF")
  218. return false;
  219. if (ReadFourCC(header.riff.Format) != "WAVE")
  220. return false;
  221. // Find "fmt " and "data" chunks. While the official Wave file specification
  222. // does not put requirements on the chunks order, it is uncommon to find the
  223. // "data" chunk before the "fmt " one. The code below fails if this is not the
  224. // case.
  225. if (!FindWaveChunk(&header.fmt.header, readable, "fmt ")) {
  226. RTC_LOG(LS_ERROR) << "Cannot find 'fmt ' chunk.";
  227. return false;
  228. }
  229. if (!ReadFmtChunkData(&header.fmt, readable)) {
  230. RTC_LOG(LS_ERROR) << "Cannot read 'fmt ' chunk.";
  231. return false;
  232. }
  233. if (!FindWaveChunk(&header.data.header, readable, "data")) {
  234. RTC_LOG(LS_ERROR) << "Cannot find 'data' chunk.";
  235. return false;
  236. }
  237. // Parse needed fields.
  238. *format = static_cast<WavFormat>(ReadLE16(header.fmt.AudioFormat));
  239. *num_channels = ReadLE16(header.fmt.NumChannels);
  240. *sample_rate = ReadLE32(header.fmt.SampleRate);
  241. *bytes_per_sample = ReadLE16(header.fmt.BitsPerSample) / 8;
  242. const size_t bytes_in_payload = ReadLE32(header.data.header.Size);
  243. if (*bytes_per_sample == 0)
  244. return false;
  245. *num_samples = bytes_in_payload / *bytes_per_sample;
  246. if (ReadLE32(header.riff.header.Size) < RiffChunkSize(bytes_in_payload))
  247. return false;
  248. if (ReadLE32(header.fmt.ByteRate) !=
  249. ByteRate(*num_channels, *sample_rate, *bytes_per_sample))
  250. return false;
  251. if (ReadLE16(header.fmt.BlockAlign) !=
  252. BlockAlign(*num_channels, *bytes_per_sample))
  253. return false;
  254. return CheckWavParameters(*num_channels, *sample_rate, *format,
  255. *bytes_per_sample, *num_samples);
  256. }
  257. } // namespace webrtc