Clean up the debug example a little
[openal-soft.git] / alc / backends / wave.cpp
blob30618f9f85db3e41b870e11d30fe5ba369827856
1 /**
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
21 #include "config.h"
23 #include "wave.h"
25 #include <algorithm>
26 #include <atomic>
27 #include <cerrno>
28 #include <chrono>
29 #include <cstdint>
30 #include <cstdio>
31 #include <cstring>
32 #include <exception>
33 #include <functional>
34 #include <system_error>
35 #include <thread>
36 #include <vector>
38 #include "albit.h"
39 #include "alc/alconfig.h"
40 #include "almalloc.h"
41 #include "alnumeric.h"
42 #include "alstring.h"
43 #include "althrd_setname.h"
44 #include "core/device.h"
45 #include "core/helpers.h"
46 #include "core/logging.h"
47 #include "opthelpers.h"
48 #include "strutils.h"
51 namespace {
53 using namespace std::string_view_literals;
54 using std::chrono::seconds;
55 using std::chrono::milliseconds;
56 using std::chrono::nanoseconds;
58 using ubyte = unsigned char;
59 using ushort = unsigned short;
61 struct FileDeleter {
62 void operator()(gsl::owner<FILE*> f) { fclose(f); }
64 using FilePtr = std::unique_ptr<FILE,FileDeleter>;
66 [[nodiscard]] constexpr auto GetDeviceName() noexcept { return "Wave File Writer"sv; }
68 constexpr std::array<ubyte,16> SUBTYPE_PCM{{
69 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
70 0x00, 0x38, 0x9b, 0x71
71 }};
72 constexpr std::array<ubyte,16> SUBTYPE_FLOAT{{
73 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
74 0x00, 0x38, 0x9b, 0x71
75 }};
77 constexpr std::array<ubyte,16> SUBTYPE_BFORMAT_PCM{{
78 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
79 0xca, 0x00, 0x00, 0x00
80 }};
82 constexpr std::array<ubyte,16> SUBTYPE_BFORMAT_FLOAT{{
83 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
84 0xca, 0x00, 0x00, 0x00
85 }};
87 void fwrite16le(ushort val, FILE *f)
89 std::array data{static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff)};
90 fwrite(data.data(), 1, data.size(), f);
93 void fwrite32le(uint val, FILE *f)
95 std::array data{static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff),
96 static_cast<ubyte>((val>>16)&0xff), static_cast<ubyte>((val>>24)&0xff)};
97 fwrite(data.data(), 1, data.size(), f);
101 struct WaveBackend final : public BackendBase {
102 WaveBackend(DeviceBase *device) noexcept : BackendBase{device} { }
103 ~WaveBackend() override;
105 int mixerProc();
107 void open(std::string_view name) override;
108 bool reset() override;
109 void start() override;
110 void stop() override;
112 FilePtr mFile{nullptr};
113 long mDataStart{-1};
115 std::vector<std::byte> mBuffer;
117 std::atomic<bool> mKillNow{true};
118 std::thread mThread;
121 WaveBackend::~WaveBackend() = default;
123 int WaveBackend::mixerProc()
125 const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2};
127 althrd_setname(GetMixerThreadName());
129 const size_t frameStep{mDevice->channelsFromFmt()};
130 const size_t frameSize{mDevice->frameSizeFromFmt()};
132 int64_t done{0};
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);
145 continue;
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()};
156 if(bytesize == 2)
158 const size_t len{mBuffer.size() & ~1_uz};
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() & ~3_uz};
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.get())};
174 if(fs < mDevice->UpdateSize || ferror(mFile.get()))
176 ERR("Error writing to file\n");
177 mDevice->handleDisconnect("Failed to write playback samples");
178 break;
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;
191 start += s;
195 return 0;
198 void WaveBackend::open(std::string_view name)
200 auto fname = ConfigValueStr({}, "wave", "file");
201 if(!fname) throw al::backend_exception{al::backend_error::NoDevice,
202 "No wave output filename"};
204 if(name.empty())
205 name = GetDeviceName();
206 else if(name != GetDeviceName())
207 throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%.*s\" not found",
208 al::sizei(name), name.data()};
210 /* There's only one "device", so if it's already open, we're done. */
211 if(mFile) return;
213 #ifdef _WIN32
215 std::wstring wname{utf8_to_wstr(fname.value())};
216 mFile = FilePtr{_wfopen(wname.c_str(), L"wb")};
218 #else
219 mFile = FilePtr{fopen(fname->c_str(), "wb")};
220 #endif
221 if(!mFile)
222 throw al::backend_exception{al::backend_error::DeviceError, "Could not open file '%s': %s",
223 fname->c_str(), std::generic_category().message(errno).c_str()};
225 mDeviceName = name;
228 bool WaveBackend::reset()
230 uint channels{0}, bytes{0}, chanmask{0};
231 bool isbformat{false};
233 fseek(mFile.get(), 0, SEEK_SET);
234 clearerr(mFile.get());
236 if(GetConfigValueBool({}, "wave", "bformat", false))
238 mDevice->FmtChans = DevFmtAmbi3D;
239 mDevice->mAmbiOrder = 1;
242 switch(mDevice->FmtType)
244 case DevFmtByte:
245 mDevice->FmtType = DevFmtUByte;
246 break;
247 case DevFmtUShort:
248 mDevice->FmtType = DevFmtShort;
249 break;
250 case DevFmtUInt:
251 mDevice->FmtType = DevFmtInt;
252 break;
253 case DevFmtUByte:
254 case DevFmtShort:
255 case DevFmtInt:
256 case DevFmtFloat:
257 break;
259 switch(mDevice->FmtChans)
261 case DevFmtMono: chanmask = 0x04; break;
262 case DevFmtStereo: chanmask = 0x01 | 0x02; break;
263 case DevFmtQuad: chanmask = 0x01 | 0x02 | 0x10 | 0x20; break;
264 case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break;
265 case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break;
266 case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
267 case DevFmtX7144:
268 mDevice->FmtChans = DevFmtX714;
269 [[fallthrough]];
270 case DevFmtX714:
271 chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400 | 0x1000 | 0x4000
272 | 0x8000 | 0x20000;
273 break;
274 /* NOTE: Same as 7.1. */
275 case DevFmtX3D71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
276 case DevFmtAmbi3D:
277 /* .amb output requires FuMa */
278 mDevice->mAmbiOrder = std::min(mDevice->mAmbiOrder, 3u);
279 mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
280 mDevice->mAmbiScale = DevAmbiScaling::FuMa;
281 isbformat = true;
282 chanmask = 0;
283 break;
285 bytes = mDevice->bytesFromFmt();
286 channels = mDevice->channelsFromFmt();
288 rewind(mFile.get());
290 fputs("RIFF", mFile.get());
291 fwrite32le(0xFFFFFFFF, mFile.get()); // 'RIFF' header len; filled in at close
293 fputs("WAVE", mFile.get());
295 fputs("fmt ", mFile.get());
296 fwrite32le(40, mFile.get()); // 'fmt ' header len; 40 bytes for EXTENSIBLE
298 // 16-bit val, format type id (extensible: 0xFFFE)
299 fwrite16le(0xFFFE, mFile.get());
300 // 16-bit val, channel count
301 fwrite16le(static_cast<ushort>(channels), mFile.get());
302 // 32-bit val, frequency
303 fwrite32le(mDevice->Frequency, mFile.get());
304 // 32-bit val, bytes per second
305 fwrite32le(mDevice->Frequency * channels * bytes, mFile.get());
306 // 16-bit val, frame size
307 fwrite16le(static_cast<ushort>(channels * bytes), mFile.get());
308 // 16-bit val, bits per sample
309 fwrite16le(static_cast<ushort>(bytes * 8), mFile.get());
310 // 16-bit val, extra byte count
311 fwrite16le(22, mFile.get());
312 // 16-bit val, valid bits per sample
313 fwrite16le(static_cast<ushort>(bytes * 8), mFile.get());
314 // 32-bit val, channel mask
315 fwrite32le(chanmask, mFile.get());
316 // 16 byte GUID, sub-type format
317 std::ignore = fwrite((mDevice->FmtType == DevFmtFloat) ?
318 (isbformat ? SUBTYPE_BFORMAT_FLOAT.data() : SUBTYPE_FLOAT.data()) :
319 (isbformat ? SUBTYPE_BFORMAT_PCM.data() : SUBTYPE_PCM.data()), 1, 16, mFile.get());
321 fputs("data", mFile.get());
322 fwrite32le(0xFFFFFFFF, mFile.get()); // 'data' header len; filled in at close
324 if(ferror(mFile.get()))
326 ERR("Error writing header: %s\n", std::generic_category().message(errno).c_str());
327 return false;
329 mDataStart = ftell(mFile.get());
331 setDefaultWFXChannelOrder();
333 const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
334 mBuffer.resize(bufsize);
336 return true;
339 void WaveBackend::start()
341 if(mDataStart > 0 && fseek(mFile.get(), 0, SEEK_END) != 0)
342 WARN("Failed to seek on output file\n");
343 try {
344 mKillNow.store(false, std::memory_order_release);
345 mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
347 catch(std::exception& e) {
348 throw al::backend_exception{al::backend_error::DeviceError,
349 "Failed to start mixing thread: %s", e.what()};
353 void WaveBackend::stop()
355 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
356 return;
357 mThread.join();
359 if(mDataStart > 0)
361 long size{ftell(mFile.get())};
362 if(size > 0)
364 long dataLen{size - mDataStart};
365 if(fseek(mFile.get(), 4, SEEK_SET) == 0)
366 fwrite32le(static_cast<uint>(size-8), mFile.get()); // 'WAVE' header len
367 if(fseek(mFile.get(), mDataStart-4, SEEK_SET) == 0)
368 fwrite32le(static_cast<uint>(dataLen), mFile.get()); // 'data' header len
373 } // namespace
376 bool WaveBackendFactory::init()
377 { return true; }
379 bool WaveBackendFactory::querySupport(BackendType type)
380 { return type == BackendType::Playback; }
382 auto WaveBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
384 switch(type)
386 case BackendType::Playback:
387 return std::vector{std::string{GetDeviceName()}};
388 case BackendType::Capture:
389 break;
391 return {};
394 BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
396 if(type == BackendType::Playback)
397 return BackendPtr{new WaveBackend{device}};
398 return nullptr;
401 BackendFactory &WaveBackendFactory::getFactory()
403 static WaveBackendFactory factory{};
404 return factory;