blob: 1217e40ba79fc71008b828960a8c9768693591f0 [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
13#include <algorithm>
14#include <cstdio>
15#include <limits>
aluebsb0ad43b2015-11-20 00:11:53 -080016#include <sstream>
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"
Karl Wiberge40468b2017-11-22 10:42:26 +010022#include "rtc_base/numerics/safe_conversions.h"
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000023
24namespace webrtc {
25
26// We write 16-bit PCM WAV files.
27static const WavFormat kWavFormat = kWavFormatPcm;
pkasting25702cb2016-01-08 13:50:27 -080028static const size_t kBytesPerSample = 2;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000029
andrew@webrtc.org048c5022014-12-16 20:17:21 +000030// Doesn't take ownership of the file handle and won't close it.
31class ReadableWavFile : public ReadableWav {
32 public:
33 explicit ReadableWavFile(FILE* file) : file_(file) {}
34 virtual size_t Read(void* buf, size_t num_bytes) {
35 return fread(buf, 1, num_bytes, file_);
36 }
37
38 private:
39 FILE* file_;
40};
41
aluebsb0ad43b2015-11-20 00:11:53 -080042std::string WavFile::FormatAsString() const {
43 std::ostringstream s;
44 s << "Sample rate: " << sample_rate() << " Hz, Channels: " << num_channels()
45 << ", Duration: "
46 << (1.f * num_samples()) / (num_channels() * sample_rate()) << " s";
47 return s.str();
48}
49
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000050WavReader::WavReader(const std::string& filename)
Artem Titove62f6002018-03-19 15:40:00 +010051 : WavReader(rtc::OpenPlatformFileReadOnly(filename)) {}
52
53WavReader::WavReader(rtc::PlatformFile file) {
54 RTC_CHECK_NE(file, rtc::kInvalidPlatformFileValue)
55 << "Invalid file. Could not create file handle for wav file.";
56 file_handle_ = rtc::FdopenPlatformFile(file, "rb");
57 if (!file_handle_) {
58 RTC_LOG(LS_ERROR) << "Could not open wav file for reading: " << errno;
59 // Even though we failed to open a FILE*, the file is still open
60 // and needs to be closed.
61 if (!rtc::ClosePlatformFile(file)) {
62 RTC_LOG(LS_ERROR) << "Can't close file.";
63 }
64 FATAL() << "Could not open wav file for reading.";
65 }
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000066
andrew@webrtc.org048c5022014-12-16 20:17:21 +000067 ReadableWavFile readable(file_handle_);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000068 WavFormat format;
pkasting25702cb2016-01-08 13:50:27 -080069 size_t bytes_per_sample;
henrikg91d6ede2015-09-17 00:24:34 -070070 RTC_CHECK(ReadWavHeader(&readable, &num_channels_, &sample_rate_, &format,
71 &bytes_per_sample, &num_samples_));
andrew@webrtc.org048c5022014-12-16 20:17:21 +000072 num_samples_remaining_ = num_samples_;
henrikg91d6ede2015-09-17 00:24:34 -070073 RTC_CHECK_EQ(kWavFormat, format);
74 RTC_CHECK_EQ(kBytesPerSample, bytes_per_sample);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000075}
76
77WavReader::~WavReader() {
78 Close();
79}
80
peahd1f718b2016-02-22 02:13:28 -080081int WavReader::sample_rate() const {
82 return sample_rate_;
83}
84
85size_t WavReader::num_channels() const {
86 return num_channels_;
87}
88
89size_t WavReader::num_samples() const {
90 return num_samples_;
91}
92
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000093size_t WavReader::ReadSamples(size_t num_samples, int16_t* samples) {
94#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
95#error "Need to convert samples to big-endian when reading from WAV file"
96#endif
andrew@webrtc.org048c5022014-12-16 20:17:21 +000097 // There could be metadata after the audio; ensure we don't read it.
pkasting25702cb2016-01-08 13:50:27 -080098 num_samples = std::min(num_samples, num_samples_remaining_);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000099 const size_t read =
100 fread(samples, sizeof(*samples), num_samples, file_handle_);
101 // If we didn't read what was requested, ensure we've reached the EOF.
henrikg91d6ede2015-09-17 00:24:34 -0700102 RTC_CHECK(read == num_samples || feof(file_handle_));
103 RTC_CHECK_LE(read, num_samples_remaining_);
pkasting25702cb2016-01-08 13:50:27 -0800104 num_samples_remaining_ -= read;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000105 return read;
106}
107
108size_t WavReader::ReadSamples(size_t num_samples, float* samples) {
109 static const size_t kChunksize = 4096 / sizeof(uint16_t);
110 size_t read = 0;
111 for (size_t i = 0; i < num_samples; i += kChunksize) {
112 int16_t isamples[kChunksize];
113 size_t chunk = std::min(kChunksize, num_samples - i);
114 chunk = ReadSamples(chunk, isamples);
115 for (size_t j = 0; j < chunk; ++j)
116 samples[i + j] = isamples[j];
117 read += chunk;
118 }
119 return read;
120}
121
122void WavReader::Close() {
henrikg91d6ede2015-09-17 00:24:34 -0700123 RTC_CHECK_EQ(0, fclose(file_handle_));
deadbeef922246a2017-02-26 04:18:12 -0800124 file_handle_ = nullptr;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000125}
126
Artem Titove62f6002018-03-19 15:40:00 +0100127WavWriter::WavWriter(const std::string& filename,
128 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800129 size_t num_channels)
Artem Titove62f6002018-03-19 15:40:00 +0100130 // Unlike plain fopen, CreatePlatformFile takes care of filename utf8 ->
131 // wchar conversion on windows.
132 : WavWriter(rtc::CreatePlatformFile(filename), sample_rate, num_channels) {}
133
134WavWriter::WavWriter(rtc::PlatformFile file,
135 int sample_rate,
136 size_t num_channels)
137 : sample_rate_(sample_rate), num_channels_(num_channels), num_samples_(0) {
138 // Handle errors from the CreatePlatformFile call in above constructor.
139 RTC_CHECK_NE(file, rtc::kInvalidPlatformFileValue)
140 << "Invalid file. Could not create wav file.";
141 file_handle_ = rtc::FdopenPlatformFile(file, "wb");
142 if (!file_handle_) {
143 RTC_LOG(LS_ERROR) << "Could not open wav file for writing.";
144 // Even though we failed to open a FILE*, the file is still open
145 // and needs to be closed.
146 if (!rtc::ClosePlatformFile(file)) {
147 RTC_LOG(LS_ERROR) << "Can't close file.";
148 }
149 FATAL() << "Could not open wav file for writing.";
150 }
151
henrikg91d6ede2015-09-17 00:24:34 -0700152 RTC_CHECK(CheckWavParameters(num_channels_, sample_rate_, kWavFormat,
153 kBytesPerSample, num_samples_));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000154
155 // Write a blank placeholder header, since we need to know the total number
156 // of samples before we can fill in the real data.
157 static const uint8_t blank_header[kWavHeaderSize] = {0};
kwibergaf476c72016-11-28 15:21:39 -0800158 RTC_CHECK_EQ(1, fwrite(blank_header, kWavHeaderSize, 1, file_handle_));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000159}
160
161WavWriter::~WavWriter() {
162 Close();
163}
164
peahd1f718b2016-02-22 02:13:28 -0800165int WavWriter::sample_rate() const {
166 return sample_rate_;
167}
168
169size_t WavWriter::num_channels() const {
170 return num_channels_;
171}
172
173size_t WavWriter::num_samples() const {
174 return num_samples_;
175}
176
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000177void WavWriter::WriteSamples(const int16_t* samples, size_t num_samples) {
178#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
179#error "Need to convert samples to little-endian when writing to WAV file"
180#endif
181 const size_t written =
182 fwrite(samples, sizeof(*samples), num_samples, file_handle_);
henrikg91d6ede2015-09-17 00:24:34 -0700183 RTC_CHECK_EQ(num_samples, written);
pkasting25702cb2016-01-08 13:50:27 -0800184 num_samples_ += written;
185 RTC_CHECK(num_samples_ >= written); // detect size_t overflow
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000186}
187
188void WavWriter::WriteSamples(const float* samples, size_t num_samples) {
189 static const size_t kChunksize = 4096 / sizeof(uint16_t);
190 for (size_t i = 0; i < num_samples; i += kChunksize) {
191 int16_t isamples[kChunksize];
192 const size_t chunk = std::min(kChunksize, num_samples - i);
193 FloatS16ToS16(samples + i, chunk, isamples);
194 WriteSamples(isamples, chunk);
195 }
196}
197
198void WavWriter::Close() {
henrikg91d6ede2015-09-17 00:24:34 -0700199 RTC_CHECK_EQ(0, fseek(file_handle_, 0, SEEK_SET));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000200 uint8_t header[kWavHeaderSize];
andrew@webrtc.orgf866b2d2014-11-03 18:20:06 +0000201 WriteWavHeader(header, num_channels_, sample_rate_, kWavFormat,
202 kBytesPerSample, num_samples_);
kwibergaf476c72016-11-28 15:21:39 -0800203 RTC_CHECK_EQ(1, fwrite(header, kWavHeaderSize, 1, file_handle_));
henrikg91d6ede2015-09-17 00:24:34 -0700204 RTC_CHECK_EQ(0, fclose(file_handle_));
deadbeef922246a2017-02-26 04:18:12 -0800205 file_handle_ = nullptr;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000206}
207
208} // namespace webrtc
209
210rtc_WavWriter* rtc_WavOpen(const char* filename,
211 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800212 size_t num_channels) {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000213 return reinterpret_cast<rtc_WavWriter*>(
214 new webrtc::WavWriter(filename, sample_rate, num_channels));
215}
216
217void rtc_WavClose(rtc_WavWriter* wf) {
218 delete reinterpret_cast<webrtc::WavWriter*>(wf);
219}
220
221void rtc_WavWriteSamples(rtc_WavWriter* wf,
222 const float* samples,
223 size_t num_samples) {
224 reinterpret_cast<webrtc::WavWriter*>(wf)->WriteSamples(samples, num_samples);
225}
226
227int rtc_WavSampleRate(const rtc_WavWriter* wf) {
228 return reinterpret_cast<const webrtc::WavWriter*>(wf)->sample_rate();
229}
230
Peter Kasting69558702016-01-12 16:26:35 -0800231size_t rtc_WavNumChannels(const rtc_WavWriter* wf) {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000232 return reinterpret_cast<const webrtc::WavWriter*>(wf)->num_channels();
233}
234
pkasting25702cb2016-01-08 13:50:27 -0800235size_t rtc_WavNumSamples(const rtc_WavWriter* wf) {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000236 return reinterpret_cast<const webrtc::WavWriter*>(wf)->num_samples();
237}