Avoid class templates for the POPCNT64/CTZ64 macros
[openal-soft.git] / alc / backends / wave.cpp
blob473d0314db5d09f0ddb0f6d0aa01f197e9746aa6
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 "backends/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 "AL/al.h"
38 #include "albyte.h"
39 #include "alcmain.h"
40 #include "alconfig.h"
41 #include "alexcpt.h"
42 #include "almalloc.h"
43 #include "alnumeric.h"
44 #include "alu.h"
45 #include "compat.h"
46 #include "endiantest.h"
47 #include "logging.h"
48 #include "strutils.h"
49 #include "threads.h"
50 #include "vector.h"
53 namespace {
55 using std::chrono::seconds;
56 using std::chrono::milliseconds;
57 using std::chrono::nanoseconds;
59 constexpr ALCchar waveDevice[] = "Wave File Writer";
61 constexpr ALubyte SUBTYPE_PCM[]{
62 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
63 0x00, 0x38, 0x9b, 0x71
65 constexpr ALubyte SUBTYPE_FLOAT[]{
66 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
67 0x00, 0x38, 0x9b, 0x71
70 constexpr ALubyte SUBTYPE_BFORMAT_PCM[]{
71 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
72 0xca, 0x00, 0x00, 0x00
75 constexpr ALubyte SUBTYPE_BFORMAT_FLOAT[]{
76 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
77 0xca, 0x00, 0x00, 0x00
80 void fwrite16le(ALushort val, FILE *f)
82 ALubyte data[2]{ static_cast<ALubyte>(val&0xff), static_cast<ALubyte>((val>>8)&0xff) };
83 fwrite(data, 1, 2, f);
86 void fwrite32le(ALuint val, FILE *f)
88 ALubyte data[4]{ static_cast<ALubyte>(val&0xff), static_cast<ALubyte>((val>>8)&0xff),
89 static_cast<ALubyte>((val>>16)&0xff), static_cast<ALubyte>((val>>24)&0xff) };
90 fwrite(data, 1, 4, f);
94 struct WaveBackend final : public BackendBase {
95 WaveBackend(ALCdevice *device) noexcept : BackendBase{device} { }
96 ~WaveBackend() override;
98 int mixerProc();
100 void open(const ALCchar *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 ALuint 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 /*constexpr*/(!IS_LITTLE_ENDIAN)
154 const ALuint bytesize{mDevice->bytesFromFmt()};
156 if(bytesize == 2)
158 ALushort *samples = reinterpret_cast<ALushort*>(mBuffer.data());
159 const size_t len{mBuffer.size() / 2};
160 for(size_t i{0};i < len;i++)
162 const ALushort samp{samples[i]};
163 samples[i] = static_cast<ALushort>((samp>>8) | (samp<<8));
166 else if(bytesize == 4)
168 ALuint *samples = reinterpret_cast<ALuint*>(mBuffer.data());
169 const size_t len{mBuffer.size() / 4};
170 for(size_t i{0};i < len;i++)
172 const ALuint samp{samples[i]};
173 samples[i] = (samp>>24) | ((samp>>8)&0x0000ff00) |
174 ((samp<<8)&0x00ff0000) | (samp<<24);
179 size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->UpdateSize, mFile)};
180 (void)fs;
181 if(ferror(mFile))
183 ERR("Error writing to file\n");
184 mDevice->handleDisconnect("Failed to write playback samples");
185 break;
189 /* For every completed second, increment the start time and reduce the
190 * samples done. This prevents the difference between the start time
191 * and current time from growing too large, while maintaining the
192 * correct number of samples to render.
194 if(done >= mDevice->Frequency)
196 seconds s{done/mDevice->Frequency};
197 start += s;
198 done -= mDevice->Frequency*s.count();
202 return 0;
205 void WaveBackend::open(const ALCchar *name)
207 const char *fname{GetConfigValue(nullptr, "wave", "file", "")};
208 if(!fname[0]) throw al::backend_exception{ALC_INVALID_VALUE, "No wave output filename"};
210 if(!name)
211 name = waveDevice;
212 else if(strcmp(name, waveDevice) != 0)
213 throw al::backend_exception{ALC_INVALID_VALUE, "Device name \"%s\" not found", name};
215 #ifdef _WIN32
217 std::wstring wname = utf8_to_wstr(fname);
218 mFile = _wfopen(wname.c_str(), L"wb");
220 #else
221 mFile = fopen(fname, "wb");
222 #endif
223 if(!mFile)
224 throw al::backend_exception{ALC_INVALID_VALUE, "Could not open file '%s': %s", fname,
225 strerror(errno)};
227 mDevice->DeviceName = name;
230 bool WaveBackend::reset()
232 ALuint channels=0, bytes=0, chanmask=0;
233 int isbformat = 0;
234 size_t val;
236 fseek(mFile, 0, SEEK_SET);
237 clearerr(mFile);
239 if(GetConfigValueBool(nullptr, "wave", "bformat", 0))
241 mDevice->FmtChans = DevFmtAmbi3D;
242 mDevice->mAmbiOrder = 1;
245 switch(mDevice->FmtType)
247 case DevFmtByte:
248 mDevice->FmtType = DevFmtUByte;
249 break;
250 case DevFmtUShort:
251 mDevice->FmtType = DevFmtShort;
252 break;
253 case DevFmtUInt:
254 mDevice->FmtType = DevFmtInt;
255 break;
256 case DevFmtUByte:
257 case DevFmtShort:
258 case DevFmtInt:
259 case DevFmtFloat:
260 break;
262 switch(mDevice->FmtChans)
264 case DevFmtMono: chanmask = 0x04; break;
265 case DevFmtStereo: chanmask = 0x01 | 0x02; break;
266 case DevFmtQuad: chanmask = 0x01 | 0x02 | 0x10 | 0x20; break;
267 case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break;
268 case DevFmtX51Rear: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020; break;
269 case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break;
270 case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
271 case DevFmtAmbi3D:
272 /* .amb output requires FuMa */
273 mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3);
274 mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
275 mDevice->mAmbiScale = DevAmbiScaling::FuMa;
276 isbformat = 1;
277 chanmask = 0;
278 break;
280 bytes = mDevice->bytesFromFmt();
281 channels = mDevice->channelsFromFmt();
283 rewind(mFile);
285 fputs("RIFF", mFile);
286 fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close
288 fputs("WAVE", mFile);
290 fputs("fmt ", mFile);
291 fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE
293 // 16-bit val, format type id (extensible: 0xFFFE)
294 fwrite16le(0xFFFE, mFile);
295 // 16-bit val, channel count
296 fwrite16le(static_cast<ALushort>(channels), mFile);
297 // 32-bit val, frequency
298 fwrite32le(mDevice->Frequency, mFile);
299 // 32-bit val, bytes per second
300 fwrite32le(mDevice->Frequency * channels * bytes, mFile);
301 // 16-bit val, frame size
302 fwrite16le(static_cast<ALushort>(channels * bytes), mFile);
303 // 16-bit val, bits per sample
304 fwrite16le(static_cast<ALushort>(bytes * 8), mFile);
305 // 16-bit val, extra byte count
306 fwrite16le(22, mFile);
307 // 16-bit val, valid bits per sample
308 fwrite16le(static_cast<ALushort>(bytes * 8), mFile);
309 // 32-bit val, channel mask
310 fwrite32le(chanmask, mFile);
311 // 16 byte GUID, sub-type format
312 val = fwrite((mDevice->FmtType == DevFmtFloat) ?
313 (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) :
314 (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile);
315 (void)val;
317 fputs("data", mFile);
318 fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close
320 if(ferror(mFile))
322 ERR("Error writing header: %s\n", strerror(errno));
323 return false;
325 mDataStart = ftell(mFile);
327 setDefaultWFXChannelOrder();
329 const ALuint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
330 mBuffer.resize(bufsize);
332 return true;
335 void WaveBackend::start()
337 try {
338 mKillNow.store(false, std::memory_order_release);
339 mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
341 catch(std::exception& e) {
342 throw al::backend_exception{ALC_INVALID_DEVICE, "Failed to start mixing thread: %s",
343 e.what()};
347 void WaveBackend::stop()
349 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
350 return;
351 mThread.join();
353 long size{ftell(mFile)};
354 if(size > 0)
356 long dataLen{size - mDataStart};
357 if(fseek(mFile, mDataStart-4, SEEK_SET) == 0)
358 fwrite32le(static_cast<ALuint>(dataLen), mFile); // 'data' header len
359 if(fseek(mFile, 4, SEEK_SET) == 0)
360 fwrite32le(static_cast<ALuint>(size-8), mFile); // 'WAVE' header len
364 } // namespace
367 bool WaveBackendFactory::init()
368 { return true; }
370 bool WaveBackendFactory::querySupport(BackendType type)
371 { return type == BackendType::Playback; }
373 std::string WaveBackendFactory::probe(BackendType type)
375 std::string outnames;
376 switch(type)
378 case BackendType::Playback:
379 /* Includes null char. */
380 outnames.append(waveDevice, sizeof(waveDevice));
381 break;
382 case BackendType::Capture:
383 break;
385 return outnames;
388 BackendPtr WaveBackendFactory::createBackend(ALCdevice *device, BackendType type)
390 if(type == BackendType::Playback)
391 return BackendPtr{new WaveBackend{device}};
392 return nullptr;
395 BackendFactory &WaveBackendFactory::getFactory()
397 static WaveBackendFactory factory{};
398 return factory;