2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
38 #include "alc/alconfig.h"
40 #include "alnumeric.h"
41 #include "core/device.h"
42 #include "core/helpers.h"
43 #include "core/logging.h"
44 #include "opthelpers.h"
52 using std::chrono::seconds;
53 using std::chrono::milliseconds;
54 using std::chrono::nanoseconds;
56 using ubyte = unsigned char;
57 using ushort = unsigned short;
59 constexpr char waveDevice[] = "Wave File Writer";
61 constexpr ubyte SUBTYPE_PCM[]{
62 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
63 0x00, 0x38, 0x9b, 0x71
65 constexpr ubyte SUBTYPE_FLOAT[]{
66 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
67 0x00, 0x38, 0x9b, 0x71
70 constexpr ubyte SUBTYPE_BFORMAT_PCM[]{
71 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
72 0xca, 0x00, 0x00, 0x00
75 constexpr ubyte SUBTYPE_BFORMAT_FLOAT[]{
76 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
77 0xca, 0x00, 0x00, 0x00
80 void fwrite16le(ushort val, FILE *f)
82 ubyte data[2]{ static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff) };
83 fwrite(data, 1, 2, f);
86 void fwrite32le(uint val, FILE *f)
88 ubyte data[4]{ static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff),
89 static_cast<ubyte>((val>>16)&0xff), static_cast<ubyte>((val>>24)&0xff) };
90 fwrite(data, 1, 4, f);
94 struct WaveBackend final : public BackendBase {
95 WaveBackend(DeviceBase *device) noexcept : BackendBase{device} { }
96 ~WaveBackend() override;
100 void open(const char *name) override;
101 bool reset() override;
102 void start() override;
103 void stop() override;
105 FILE *mFile{nullptr};
108 al::vector<al::byte> mBuffer;
110 std::atomic<bool> mKillNow{true};
113 DEF_NEWDEL(WaveBackend)
116 WaveBackend::~WaveBackend()
123 int WaveBackend::mixerProc()
125 const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2};
127 althrd_setname(MIXER_THREAD_NAME);
129 const size_t frameStep{mDevice->channelsFromFmt()};
130 const size_t frameSize{mDevice->frameSizeFromFmt()};
133 auto start = std::chrono::steady_clock::now();
134 while(!mKillNow.load(std::memory_order_acquire)
135 && mDevice->Connected.load(std::memory_order_acquire))
137 auto now = std::chrono::steady_clock::now();
139 /* This converts from nanoseconds to nanosamples, then to samples. */
140 int64_t avail{std::chrono::duration_cast<seconds>((now-start) *
141 mDevice->Frequency).count()};
142 if(avail-done < mDevice->UpdateSize)
144 std::this_thread::sleep_for(restTime);
147 while(avail-done >= mDevice->UpdateSize)
149 mDevice->renderSamples(mBuffer.data(), mDevice->UpdateSize, frameStep);
150 done += mDevice->UpdateSize;
152 if(al::endian::native != al::endian::little)
154 const uint bytesize{mDevice->bytesFromFmt()};
158 const size_t len{mBuffer.size() & ~size_t{1}};
159 for(size_t i{0};i < len;i+=2)
160 std::swap(mBuffer[i], mBuffer[i+1]);
162 else if(bytesize == 4)
164 const size_t len{mBuffer.size() & ~size_t{3}};
165 for(size_t i{0};i < len;i+=4)
167 std::swap(mBuffer[i ], mBuffer[i+3]);
168 std::swap(mBuffer[i+1], mBuffer[i+2]);
173 const size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->UpdateSize, mFile)};
174 if(fs < mDevice->UpdateSize || ferror(mFile))
176 ERR("Error writing to file\n");
177 mDevice->handleDisconnect("Failed to write playback samples");
182 /* For every completed second, increment the start time and reduce the
183 * samples done. This prevents the difference between the start time
184 * and current time from growing too large, while maintaining the
185 * correct number of samples to render.
187 if(done >= mDevice->Frequency)
189 seconds s{done/mDevice->Frequency};
190 done %= mDevice->Frequency;
198 void WaveBackend::open(const char *name)
200 auto fname = ConfigValueStr(nullptr, "wave", "file");
201 if(!fname) throw al::backend_exception{al::backend_error::NoDevice,
202 "No wave output filename"};
206 else if(strcmp(name, waveDevice) != 0)
207 throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
210 /* There's only one "device", so if it's already open, we're done. */
215 std::wstring wname{utf8_to_wstr(fname->c_str())};
216 mFile = _wfopen(wname.c_str(), L"wb");
219 mFile = fopen(fname->c_str(), "wb");
222 throw al::backend_exception{al::backend_error::DeviceError, "Could not open file '%s': %s",
223 fname->c_str(), strerror(errno)};
225 mDevice->DeviceName = name;
228 bool WaveBackend::reset()
230 uint channels{0}, bytes{0}, chanmask{0};
231 bool isbformat{false};
234 fseek(mFile, 0, SEEK_SET);
237 if(GetConfigValueBool(nullptr, "wave", "bformat", false))
239 mDevice->FmtChans = DevFmtAmbi3D;
240 mDevice->mAmbiOrder = 1;
243 switch(mDevice->FmtType)
246 mDevice->FmtType = DevFmtUByte;
249 mDevice->FmtType = DevFmtShort;
252 mDevice->FmtType = DevFmtInt;
260 switch(mDevice->FmtChans)
262 case DevFmtMono: chanmask = 0x04; break;
263 case DevFmtStereo: chanmask = 0x01 | 0x02; break;
264 case DevFmtQuad: chanmask = 0x01 | 0x02 | 0x10 | 0x20; break;
265 case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break;
266 case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break;
267 case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
269 chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400 | 0x1000 | 0x4000
272 /* NOTE: Same as 7.1. */
273 case DevFmtX3D71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
275 /* .amb output requires FuMa */
276 mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3);
277 mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
278 mDevice->mAmbiScale = DevAmbiScaling::FuMa;
283 bytes = mDevice->bytesFromFmt();
284 channels = mDevice->channelsFromFmt();
288 fputs("RIFF", mFile);
289 fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close
291 fputs("WAVE", mFile);
293 fputs("fmt ", mFile);
294 fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE
296 // 16-bit val, format type id (extensible: 0xFFFE)
297 fwrite16le(0xFFFE, mFile);
298 // 16-bit val, channel count
299 fwrite16le(static_cast<ushort>(channels), mFile);
300 // 32-bit val, frequency
301 fwrite32le(mDevice->Frequency, mFile);
302 // 32-bit val, bytes per second
303 fwrite32le(mDevice->Frequency * channels * bytes, mFile);
304 // 16-bit val, frame size
305 fwrite16le(static_cast<ushort>(channels * bytes), mFile);
306 // 16-bit val, bits per sample
307 fwrite16le(static_cast<ushort>(bytes * 8), mFile);
308 // 16-bit val, extra byte count
309 fwrite16le(22, mFile);
310 // 16-bit val, valid bits per sample
311 fwrite16le(static_cast<ushort>(bytes * 8), mFile);
312 // 32-bit val, channel mask
313 fwrite32le(chanmask, mFile);
314 // 16 byte GUID, sub-type format
315 val = fwrite((mDevice->FmtType == DevFmtFloat) ?
316 (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) :
317 (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile);
320 fputs("data", mFile);
321 fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close
325 ERR("Error writing header: %s\n", strerror(errno));
328 mDataStart = ftell(mFile);
330 setDefaultWFXChannelOrder();
332 const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
333 mBuffer.resize(bufsize);
338 void WaveBackend::start()
340 if(mDataStart > 0 && fseek(mFile, 0, SEEK_END) != 0)
341 WARN("Failed to seek on output file\n");
343 mKillNow.store(false, std::memory_order_release);
344 mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
346 catch(std::exception& e) {
347 throw al::backend_exception{al::backend_error::DeviceError,
348 "Failed to start mixing thread: %s", e.what()};
352 void WaveBackend::stop()
354 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
360 long size{ftell(mFile)};
363 long dataLen{size - mDataStart};
364 if(fseek(mFile, 4, SEEK_SET) == 0)
365 fwrite32le(static_cast<uint>(size-8), mFile); // 'WAVE' header len
366 if(fseek(mFile, mDataStart-4, SEEK_SET) == 0)
367 fwrite32le(static_cast<uint>(dataLen), mFile); // 'data' header len
375 bool WaveBackendFactory::init()
378 bool WaveBackendFactory::querySupport(BackendType type)
379 { return type == BackendType::Playback; }
381 std::string WaveBackendFactory::probe(BackendType type)
383 std::string outnames;
386 case BackendType::Playback:
387 /* Includes null char. */
388 outnames.append(waveDevice, sizeof(waveDevice));
390 case BackendType::Capture:
396 BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
398 if(type == BackendType::Playback)
399 return BackendPtr{new WaveBackend{device}};
403 BackendFactory &WaveBackendFactory::getFactory()
405 static WaveBackendFactory factory{};