Avoid a stateful unique_ptr deleter
[openal-soft.git] / alc / backends / wave.cpp
blob6360166ca803c5f91f654d8c98bc86843d6a40c7
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 <thread>
36 #include "albit.h"
37 #include "albyte.h"
38 #include "alc/alconfig.h"
39 #include "almalloc.h"
40 #include "alnumeric.h"
41 #include "core/device.h"
42 #include "core/helpers.h"
43 #include "core/logging.h"
44 #include "opthelpers.h"
45 #include "strutils.h"
46 #include "threads.h"
47 #include "vector.h"
50 namespace {
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;
98 int mixerProc();
100 void open(const char *name) override;
101 bool reset() override;
102 void start() override;
103 void stop() override;
105 FILE *mFile{nullptr};
106 long mDataStart{-1};
108 al::vector<al::byte> mBuffer;
110 std::atomic<bool> mKillNow{true};
111 std::thread mThread;
113 DEF_NEWDEL(WaveBackend)
116 WaveBackend::~WaveBackend()
118 if(mFile)
119 fclose(mFile);
120 mFile = nullptr;
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()};
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() & ~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");
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(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"};
204 if(!name)
205 name = waveDevice;
206 else if(strcmp(name, waveDevice) != 0)
207 throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
208 name};
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->c_str())};
216 mFile = _wfopen(wname.c_str(), L"wb");
218 #else
219 mFile = 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(), strerror(errno)};
225 mDevice->DeviceName = name;
228 bool WaveBackend::reset()
230 uint channels{0}, bytes{0}, chanmask{0};
231 bool isbformat{false};
232 size_t val;
234 fseek(mFile, 0, SEEK_SET);
235 clearerr(mFile);
237 if(GetConfigValueBool(nullptr, "wave", "bformat", 0))
239 mDevice->FmtChans = DevFmtAmbi3D;
240 mDevice->mAmbiOrder = 1;
243 switch(mDevice->FmtType)
245 case DevFmtByte:
246 mDevice->FmtType = DevFmtUByte;
247 break;
248 case DevFmtUShort:
249 mDevice->FmtType = DevFmtShort;
250 break;
251 case DevFmtUInt:
252 mDevice->FmtType = DevFmtInt;
253 break;
254 case DevFmtUByte:
255 case DevFmtShort:
256 case DevFmtInt:
257 case DevFmtFloat:
258 break;
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;
268 case DevFmtAmbi3D:
269 /* .amb output requires FuMa */
270 mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3);
271 mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
272 mDevice->mAmbiScale = DevAmbiScaling::FuMa;
273 isbformat = true;
274 chanmask = 0;
275 break;
277 bytes = mDevice->bytesFromFmt();
278 channels = mDevice->channelsFromFmt();
280 rewind(mFile);
282 fputs("RIFF", mFile);
283 fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close
285 fputs("WAVE", mFile);
287 fputs("fmt ", mFile);
288 fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE
290 // 16-bit val, format type id (extensible: 0xFFFE)
291 fwrite16le(0xFFFE, mFile);
292 // 16-bit val, channel count
293 fwrite16le(static_cast<ushort>(channels), mFile);
294 // 32-bit val, frequency
295 fwrite32le(mDevice->Frequency, mFile);
296 // 32-bit val, bytes per second
297 fwrite32le(mDevice->Frequency * channels * bytes, mFile);
298 // 16-bit val, frame size
299 fwrite16le(static_cast<ushort>(channels * bytes), mFile);
300 // 16-bit val, bits per sample
301 fwrite16le(static_cast<ushort>(bytes * 8), mFile);
302 // 16-bit val, extra byte count
303 fwrite16le(22, mFile);
304 // 16-bit val, valid bits per sample
305 fwrite16le(static_cast<ushort>(bytes * 8), mFile);
306 // 32-bit val, channel mask
307 fwrite32le(chanmask, mFile);
308 // 16 byte GUID, sub-type format
309 val = fwrite((mDevice->FmtType == DevFmtFloat) ?
310 (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) :
311 (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile);
312 (void)val;
314 fputs("data", mFile);
315 fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close
317 if(ferror(mFile))
319 ERR("Error writing header: %s\n", strerror(errno));
320 return false;
322 mDataStart = ftell(mFile);
324 setDefaultWFXChannelOrder();
326 const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
327 mBuffer.resize(bufsize);
329 return true;
332 void WaveBackend::start()
334 if(mDataStart > 0 && fseek(mFile, 0, SEEK_END) != 0)
335 WARN("Failed to seek on output file\n");
336 try {
337 mKillNow.store(false, std::memory_order_release);
338 mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
340 catch(std::exception& e) {
341 throw al::backend_exception{al::backend_error::DeviceError,
342 "Failed to start mixing thread: %s", e.what()};
346 void WaveBackend::stop()
348 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
349 return;
350 mThread.join();
352 if(mDataStart > 0)
354 long size{ftell(mFile)};
355 if(size > 0)
357 long dataLen{size - mDataStart};
358 if(fseek(mFile, 4, SEEK_SET) == 0)
359 fwrite32le(static_cast<uint>(size-8), mFile); // 'WAVE' header len
360 if(fseek(mFile, mDataStart-4, SEEK_SET) == 0)
361 fwrite32le(static_cast<uint>(dataLen), mFile); // 'data' header len
366 } // namespace
369 bool WaveBackendFactory::init()
370 { return true; }
372 bool WaveBackendFactory::querySupport(BackendType type)
373 { return type == BackendType::Playback; }
375 std::string WaveBackendFactory::probe(BackendType type)
377 std::string outnames;
378 switch(type)
380 case BackendType::Playback:
381 /* Includes null char. */
382 outnames.append(waveDevice, sizeof(waveDevice));
383 break;
384 case BackendType::Capture:
385 break;
387 return outnames;
390 BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
392 if(type == BackendType::Playback)
393 return BackendPtr{new WaveBackend{device}};
394 return nullptr;
397 BackendFactory &WaveBackendFactory::getFactory()
399 static WaveBackendFactory factory{};
400 return factory;