blob: 77b46e72e14220fbe98b92f321b353729102dda9 [file] [log] [blame]
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "common_audio/wav_file.h"
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000012
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <errno.h>
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000014#include <algorithm>
15#include <cstdio>
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010016#include <type_traits>
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "common_audio/include/audio_util.h"
19#include "common_audio/wav_header.h"
20#include "rtc_base/checks.h"
Artem Titove62f6002018-03-19 15:40:00 +010021#include "rtc_base/logging.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020022#include "rtc_base/system/arch.h"
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000023
24namespace webrtc {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010025namespace {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000026
27// We write 16-bit PCM WAV files.
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010028constexpr WavFormat kWavFormat = kWavFormatPcm;
29static_assert(std::is_trivially_destructible<WavFormat>::value, "");
30constexpr size_t kBytesPerSample = 2;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000031
andrew@webrtc.org048c5022014-12-16 20:17:21 +000032// Doesn't take ownership of the file handle and won't close it.
33class ReadableWavFile : public ReadableWav {
34 public:
35 explicit ReadableWavFile(FILE* file) : file_(file) {}
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010036 ReadableWavFile(const ReadableWavFile&) = delete;
37 ReadableWavFile& operator=(const ReadableWavFile&) = delete;
Mirko Bonadei91df0912018-07-17 11:08:15 +020038 size_t Read(void* buf, size_t num_bytes) override {
andrew@webrtc.org048c5022014-12-16 20:17:21 +000039 return fread(buf, 1, num_bytes, file_);
40 }
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010041 bool Eof() const override { return feof(file_) != 0; }
42 bool SeekForward(uint32_t num_bytes) override {
43 return fseek(file_, num_bytes, SEEK_CUR) == 0;
44 }
andrew@webrtc.org048c5022014-12-16 20:17:21 +000045
46 private:
47 FILE* file_;
48};
49
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010050} // namespace
51
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000052WavReader::WavReader(const std::string& filename)
Artem Titove62f6002018-03-19 15:40:00 +010053 : WavReader(rtc::OpenPlatformFileReadOnly(filename)) {}
54
55WavReader::WavReader(rtc::PlatformFile file) {
56 RTC_CHECK_NE(file, rtc::kInvalidPlatformFileValue)
57 << "Invalid file. Could not create file handle for wav file.";
58 file_handle_ = rtc::FdopenPlatformFile(file, "rb");
59 if (!file_handle_) {
60 RTC_LOG(LS_ERROR) << "Could not open wav file for reading: " << errno;
61 // Even though we failed to open a FILE*, the file is still open
62 // and needs to be closed.
63 if (!rtc::ClosePlatformFile(file)) {
64 RTC_LOG(LS_ERROR) << "Can't close file.";
65 }
66 FATAL() << "Could not open wav file for reading.";
67 }
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000068
andrew@webrtc.org048c5022014-12-16 20:17:21 +000069 ReadableWavFile readable(file_handle_);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000070 WavFormat format;
pkasting25702cb2016-01-08 13:50:27 -080071 size_t bytes_per_sample;
henrikg91d6ede2015-09-17 00:24:34 -070072 RTC_CHECK(ReadWavHeader(&readable, &num_channels_, &sample_rate_, &format,
73 &bytes_per_sample, &num_samples_));
andrew@webrtc.org048c5022014-12-16 20:17:21 +000074 num_samples_remaining_ = num_samples_;
henrikg91d6ede2015-09-17 00:24:34 -070075 RTC_CHECK_EQ(kWavFormat, format);
76 RTC_CHECK_EQ(kBytesPerSample, bytes_per_sample);
Artem Titov153056b2019-04-16 16:49:32 +020077 RTC_CHECK_EQ(0, fgetpos(file_handle_, &data_start_pos_))
78 << "Failed to get WAV data position from file";
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000079}
80
81WavReader::~WavReader() {
82 Close();
83}
84
Artem Titov153056b2019-04-16 16:49:32 +020085void WavReader::Reset() {
86 RTC_CHECK_EQ(0, fsetpos(file_handle_, &data_start_pos_))
87 << "Failed to set position in the file to WAV data start position";
88 num_samples_remaining_ = num_samples_;
89}
90
peahd1f718b2016-02-22 02:13:28 -080091int WavReader::sample_rate() const {
92 return sample_rate_;
93}
94
95size_t WavReader::num_channels() const {
96 return num_channels_;
97}
98
99size_t WavReader::num_samples() const {
100 return num_samples_;
101}
102
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000103size_t WavReader::ReadSamples(size_t num_samples, int16_t* samples) {
104#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
105#error "Need to convert samples to big-endian when reading from WAV file"
106#endif
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000107 // There could be metadata after the audio; ensure we don't read it.
pkasting25702cb2016-01-08 13:50:27 -0800108 num_samples = std::min(num_samples, num_samples_remaining_);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000109 const size_t read =
110 fread(samples, sizeof(*samples), num_samples, file_handle_);
111 // If we didn't read what was requested, ensure we've reached the EOF.
henrikg91d6ede2015-09-17 00:24:34 -0700112 RTC_CHECK(read == num_samples || feof(file_handle_));
113 RTC_CHECK_LE(read, num_samples_remaining_);
pkasting25702cb2016-01-08 13:50:27 -0800114 num_samples_remaining_ -= read;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000115 return read;
116}
117
118size_t WavReader::ReadSamples(size_t num_samples, float* samples) {
119 static const size_t kChunksize = 4096 / sizeof(uint16_t);
120 size_t read = 0;
121 for (size_t i = 0; i < num_samples; i += kChunksize) {
122 int16_t isamples[kChunksize];
123 size_t chunk = std::min(kChunksize, num_samples - i);
124 chunk = ReadSamples(chunk, isamples);
125 for (size_t j = 0; j < chunk; ++j)
126 samples[i + j] = isamples[j];
127 read += chunk;
128 }
129 return read;
130}
131
132void WavReader::Close() {
henrikg91d6ede2015-09-17 00:24:34 -0700133 RTC_CHECK_EQ(0, fclose(file_handle_));
deadbeef922246a2017-02-26 04:18:12 -0800134 file_handle_ = nullptr;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000135}
136
Artem Titove62f6002018-03-19 15:40:00 +0100137WavWriter::WavWriter(const std::string& filename,
138 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800139 size_t num_channels)
Artem Titove62f6002018-03-19 15:40:00 +0100140 // Unlike plain fopen, CreatePlatformFile takes care of filename utf8 ->
141 // wchar conversion on windows.
142 : WavWriter(rtc::CreatePlatformFile(filename), sample_rate, num_channels) {}
143
144WavWriter::WavWriter(rtc::PlatformFile file,
145 int sample_rate,
146 size_t num_channels)
147 : sample_rate_(sample_rate), num_channels_(num_channels), num_samples_(0) {
148 // Handle errors from the CreatePlatformFile call in above constructor.
149 RTC_CHECK_NE(file, rtc::kInvalidPlatformFileValue)
150 << "Invalid file. Could not create wav file.";
151 file_handle_ = rtc::FdopenPlatformFile(file, "wb");
152 if (!file_handle_) {
153 RTC_LOG(LS_ERROR) << "Could not open wav file for writing.";
154 // Even though we failed to open a FILE*, the file is still open
155 // and needs to be closed.
156 if (!rtc::ClosePlatformFile(file)) {
157 RTC_LOG(LS_ERROR) << "Can't close file.";
158 }
159 FATAL() << "Could not open wav file for writing.";
160 }
161
henrikg91d6ede2015-09-17 00:24:34 -0700162 RTC_CHECK(CheckWavParameters(num_channels_, sample_rate_, kWavFormat,
163 kBytesPerSample, num_samples_));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000164
165 // Write a blank placeholder header, since we need to know the total number
166 // of samples before we can fill in the real data.
167 static const uint8_t blank_header[kWavHeaderSize] = {0};
kwibergaf476c72016-11-28 15:21:39 -0800168 RTC_CHECK_EQ(1, fwrite(blank_header, kWavHeaderSize, 1, file_handle_));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000169}
170
171WavWriter::~WavWriter() {
172 Close();
173}
174
peahd1f718b2016-02-22 02:13:28 -0800175int WavWriter::sample_rate() const {
176 return sample_rate_;
177}
178
179size_t WavWriter::num_channels() const {
180 return num_channels_;
181}
182
183size_t WavWriter::num_samples() const {
184 return num_samples_;
185}
186
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000187void WavWriter::WriteSamples(const int16_t* samples, size_t num_samples) {
188#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
189#error "Need to convert samples to little-endian when writing to WAV file"
190#endif
191 const size_t written =
192 fwrite(samples, sizeof(*samples), num_samples, file_handle_);
henrikg91d6ede2015-09-17 00:24:34 -0700193 RTC_CHECK_EQ(num_samples, written);
pkasting25702cb2016-01-08 13:50:27 -0800194 num_samples_ += written;
195 RTC_CHECK(num_samples_ >= written); // detect size_t overflow
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000196}
197
198void WavWriter::WriteSamples(const float* samples, size_t num_samples) {
199 static const size_t kChunksize = 4096 / sizeof(uint16_t);
200 for (size_t i = 0; i < num_samples; i += kChunksize) {
201 int16_t isamples[kChunksize];
202 const size_t chunk = std::min(kChunksize, num_samples - i);
203 FloatS16ToS16(samples + i, chunk, isamples);
204 WriteSamples(isamples, chunk);
205 }
206}
207
208void WavWriter::Close() {
henrikg91d6ede2015-09-17 00:24:34 -0700209 RTC_CHECK_EQ(0, fseek(file_handle_, 0, SEEK_SET));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000210 uint8_t header[kWavHeaderSize];
andrew@webrtc.orgf866b2d2014-11-03 18:20:06 +0000211 WriteWavHeader(header, num_channels_, sample_rate_, kWavFormat,
212 kBytesPerSample, num_samples_);
kwibergaf476c72016-11-28 15:21:39 -0800213 RTC_CHECK_EQ(1, fwrite(header, kWavHeaderSize, 1, file_handle_));
henrikg91d6ede2015-09-17 00:24:34 -0700214 RTC_CHECK_EQ(0, fclose(file_handle_));
deadbeef922246a2017-02-26 04:18:12 -0800215 file_handle_ = nullptr;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000216}
217
218} // namespace webrtc
219
220rtc_WavWriter* rtc_WavOpen(const char* filename,
221 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800222 size_t num_channels) {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000223 return reinterpret_cast<rtc_WavWriter*>(
224 new webrtc::WavWriter(filename, sample_rate, num_channels));
225}
226
227void rtc_WavClose(rtc_WavWriter* wf) {
228 delete reinterpret_cast<webrtc::WavWriter*>(wf);
229}
230
231void rtc_WavWriteSamples(rtc_WavWriter* wf,
232 const float* samples,
233 size_t num_samples) {
234 reinterpret_cast<webrtc::WavWriter*>(wf)->WriteSamples(samples, num_samples);
235}
236
237int rtc_WavSampleRate(const rtc_WavWriter* wf) {
238 return reinterpret_cast<const webrtc::WavWriter*>(wf)->sample_rate();
239}
240
Peter Kasting69558702016-01-12 16:26:35 -0800241size_t rtc_WavNumChannels(const rtc_WavWriter* wf) {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000242 return reinterpret_cast<const webrtc::WavWriter*>(wf)->num_channels();
243}
244
pkasting25702cb2016-01-08 13:50:27 -0800245size_t rtc_WavNumSamples(const rtc_WavWriter* wf) {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000246 return reinterpret_cast<const webrtc::WavWriter*>(wf)->num_samples();
247}