blob: 3f2aa7e50f7b4625e499d4b92f74440967c403e4 [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>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000015#include <algorithm>
16#include <cstdio>
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010017#include <type_traits>
Niels Möller19a1d502019-06-13 14:08:24 +020018#include <utility>
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "common_audio/include/audio_util.h"
21#include "common_audio/wav_header.h"
22#include "rtc_base/checks.h"
Artem Titove62f6002018-03-19 15:40:00 +010023#include "rtc_base/logging.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020024#include "rtc_base/system/arch.h"
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000025
26namespace webrtc {
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010027namespace {
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000028
29// We write 16-bit PCM WAV files.
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010030constexpr WavFormat kWavFormat = kWavFormatPcm;
31static_assert(std::is_trivially_destructible<WavFormat>::value, "");
32constexpr size_t kBytesPerSample = 2;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000033
andrew@webrtc.org048c5022014-12-16 20:17:21 +000034// Doesn't take ownership of the file handle and won't close it.
35class ReadableWavFile : public ReadableWav {
36 public:
37 explicit ReadableWavFile(FILE* file) : file_(file) {}
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010038 ReadableWavFile(const ReadableWavFile&) = delete;
39 ReadableWavFile& operator=(const ReadableWavFile&) = delete;
Mirko Bonadei91df0912018-07-17 11:08:15 +020040 size_t Read(void* buf, size_t num_bytes) override {
andrew@webrtc.org048c5022014-12-16 20:17:21 +000041 return fread(buf, 1, num_bytes, file_);
42 }
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010043 bool SeekForward(uint32_t num_bytes) override {
44 return fseek(file_, num_bytes, SEEK_CUR) == 0;
45 }
andrew@webrtc.org048c5022014-12-16 20:17:21 +000046
47 private:
48 FILE* file_;
49};
50
Alessio Bazzicaa33c7af2018-11-08 12:16:11 +010051} // namespace
52
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000053WavReader::WavReader(const std::string& filename)
Artem Titove62f6002018-03-19 15:40:00 +010054 : WavReader(rtc::OpenPlatformFileReadOnly(filename)) {}
55
56WavReader::WavReader(rtc::PlatformFile file) {
57 RTC_CHECK_NE(file, rtc::kInvalidPlatformFileValue)
58 << "Invalid file. Could not create file handle for wav file.";
59 file_handle_ = rtc::FdopenPlatformFile(file, "rb");
60 if (!file_handle_) {
61 RTC_LOG(LS_ERROR) << "Could not open wav file for reading: " << errno;
62 // Even though we failed to open a FILE*, the file is still open
63 // and needs to be closed.
64 if (!rtc::ClosePlatformFile(file)) {
65 RTC_LOG(LS_ERROR) << "Can't close file.";
66 }
67 FATAL() << "Could not open wav file for reading.";
68 }
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000069
andrew@webrtc.org048c5022014-12-16 20:17:21 +000070 ReadableWavFile readable(file_handle_);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000071 WavFormat format;
pkasting25702cb2016-01-08 13:50:27 -080072 size_t bytes_per_sample;
henrikg91d6ede2015-09-17 00:24:34 -070073 RTC_CHECK(ReadWavHeader(&readable, &num_channels_, &sample_rate_, &format,
74 &bytes_per_sample, &num_samples_));
andrew@webrtc.org048c5022014-12-16 20:17:21 +000075 num_samples_remaining_ = num_samples_;
henrikg91d6ede2015-09-17 00:24:34 -070076 RTC_CHECK_EQ(kWavFormat, format);
77 RTC_CHECK_EQ(kBytesPerSample, bytes_per_sample);
Artem Titov153056b2019-04-16 16:49:32 +020078 RTC_CHECK_EQ(0, fgetpos(file_handle_, &data_start_pos_))
79 << "Failed to get WAV data position from file";
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +000080}
81
82WavReader::~WavReader() {
83 Close();
84}
85
Artem Titov153056b2019-04-16 16:49:32 +020086void WavReader::Reset() {
87 RTC_CHECK_EQ(0, fsetpos(file_handle_, &data_start_pos_))
88 << "Failed to set position in the file to WAV data start position";
89 num_samples_remaining_ = num_samples_;
90}
91
peahd1f718b2016-02-22 02:13:28 -080092int WavReader::sample_rate() const {
93 return sample_rate_;
94}
95
96size_t WavReader::num_channels() const {
97 return num_channels_;
98}
99
100size_t WavReader::num_samples() const {
101 return num_samples_;
102}
103
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000104size_t WavReader::ReadSamples(size_t num_samples, int16_t* samples) {
105#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
106#error "Need to convert samples to big-endian when reading from WAV file"
107#endif
andrew@webrtc.org048c5022014-12-16 20:17:21 +0000108 // There could be metadata after the audio; ensure we don't read it.
pkasting25702cb2016-01-08 13:50:27 -0800109 num_samples = std::min(num_samples, num_samples_remaining_);
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000110 const size_t read =
111 fread(samples, sizeof(*samples), num_samples, file_handle_);
112 // If we didn't read what was requested, ensure we've reached the EOF.
henrikg91d6ede2015-09-17 00:24:34 -0700113 RTC_CHECK(read == num_samples || feof(file_handle_));
114 RTC_CHECK_LE(read, num_samples_remaining_);
pkasting25702cb2016-01-08 13:50:27 -0800115 num_samples_remaining_ -= read;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000116 return read;
117}
118
119size_t WavReader::ReadSamples(size_t num_samples, float* samples) {
120 static const size_t kChunksize = 4096 / sizeof(uint16_t);
121 size_t read = 0;
122 for (size_t i = 0; i < num_samples; i += kChunksize) {
123 int16_t isamples[kChunksize];
124 size_t chunk = std::min(kChunksize, num_samples - i);
125 chunk = ReadSamples(chunk, isamples);
126 for (size_t j = 0; j < chunk; ++j)
127 samples[i + j] = isamples[j];
128 read += chunk;
129 }
130 return read;
131}
132
133void WavReader::Close() {
henrikg91d6ede2015-09-17 00:24:34 -0700134 RTC_CHECK_EQ(0, fclose(file_handle_));
deadbeef922246a2017-02-26 04:18:12 -0800135 file_handle_ = nullptr;
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000136}
137
Artem Titove62f6002018-03-19 15:40:00 +0100138WavWriter::WavWriter(const std::string& filename,
139 int sample_rate,
Peter Kasting69558702016-01-12 16:26:35 -0800140 size_t num_channels)
Artem Titove62f6002018-03-19 15:40:00 +0100141 // Unlike plain fopen, CreatePlatformFile takes care of filename utf8 ->
142 // wchar conversion on windows.
Niels Möller19a1d502019-06-13 14:08:24 +0200143 : WavWriter(FileWrapper::OpenWriteOnly(filename),
144 sample_rate,
145 num_channels) {}
Artem Titove62f6002018-03-19 15:40:00 +0100146
Niels Möller19a1d502019-06-13 14:08:24 +0200147WavWriter::WavWriter(FileWrapper file, int sample_rate, size_t num_channels)
148 : sample_rate_(sample_rate),
149 num_channels_(num_channels),
150 num_samples_(0),
151 file_(std::move(file)) {
Artem Titove62f6002018-03-19 15:40:00 +0100152 // Handle errors from the CreatePlatformFile call in above constructor.
Niels Möller19a1d502019-06-13 14:08:24 +0200153 RTC_CHECK(file_.is_open()) << "Invalid file. Could not create wav file.";
Artem Titove62f6002018-03-19 15:40:00 +0100154
henrikg91d6ede2015-09-17 00:24:34 -0700155 RTC_CHECK(CheckWavParameters(num_channels_, sample_rate_, kWavFormat,
156 kBytesPerSample, num_samples_));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000157
158 // Write a blank placeholder header, since we need to know the total number
159 // of samples before we can fill in the real data.
160 static const uint8_t blank_header[kWavHeaderSize] = {0};
Niels Möller19a1d502019-06-13 14:08:24 +0200161 RTC_CHECK(file_.Write(blank_header, kWavHeaderSize));
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000162}
163
164WavWriter::~WavWriter() {
165 Close();
166}
167
peahd1f718b2016-02-22 02:13:28 -0800168int WavWriter::sample_rate() const {
169 return sample_rate_;
170}
171
172size_t WavWriter::num_channels() const {
173 return num_channels_;
174}
175
176size_t WavWriter::num_samples() const {
177 return num_samples_;
178}
179
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000180void WavWriter::WriteSamples(const int16_t* samples, size_t num_samples) {
181#ifndef WEBRTC_ARCH_LITTLE_ENDIAN
182#error "Need to convert samples to little-endian when writing to WAV file"
183#endif
Niels Möller19a1d502019-06-13 14:08:24 +0200184 RTC_CHECK(file_.Write(samples, sizeof(*samples) * num_samples));
185 num_samples_ += num_samples;
186 RTC_CHECK(num_samples_ >= num_samples); // detect size_t overflow
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000187}
188
189void WavWriter::WriteSamples(const float* samples, size_t num_samples) {
190 static const size_t kChunksize = 4096 / sizeof(uint16_t);
191 for (size_t i = 0; i < num_samples; i += kChunksize) {
192 int16_t isamples[kChunksize];
193 const size_t chunk = std::min(kChunksize, num_samples - i);
194 FloatS16ToS16(samples + i, chunk, isamples);
195 WriteSamples(isamples, chunk);
196 }
197}
198
199void WavWriter::Close() {
Niels Möller19a1d502019-06-13 14:08:24 +0200200 RTC_CHECK(file_.Rewind());
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000201 uint8_t header[kWavHeaderSize];
andrew@webrtc.orgf866b2d2014-11-03 18:20:06 +0000202 WriteWavHeader(header, num_channels_, sample_rate_, kWavFormat,
203 kBytesPerSample, num_samples_);
Niels Möller19a1d502019-06-13 14:08:24 +0200204 RTC_CHECK(file_.Write(header, kWavHeaderSize));
205 RTC_CHECK(file_.Close());
andrew@webrtc.orga3ed7132014-10-31 21:51:03 +0000206}
207
208} // namespace webrtc