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
34 #include <system_error>
39 #include "alc/alconfig.h"
41 #include "alnumeric.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"
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;
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
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
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
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
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
;
107 void open(std::string_view name
) override
;
108 bool reset() override
;
109 void start() override
;
110 void stop() override
;
112 FilePtr mFile
{nullptr};
115 std::vector
<std::byte
> mBuffer
;
117 std::atomic
<bool> mKillNow
{true};
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()};
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() & ~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");
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(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"};
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. */
215 std::wstring wname
{utf8_to_wstr(fname
.value())};
216 mFile
= FilePtr
{_wfopen(wname
.c_str(), L
"wb")};
219 mFile
= FilePtr
{fopen(fname
->c_str(), "wb")};
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()};
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
)
245 mDevice
->FmtType
= DevFmtUByte
;
248 mDevice
->FmtType
= DevFmtShort
;
251 mDevice
->FmtType
= DevFmtInt
;
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;
268 mDevice
->FmtChans
= DevFmtX714
;
271 chanmask
= 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400 | 0x1000 | 0x4000
274 /* NOTE: Same as 7.1. */
275 case DevFmtX3D71
: chanmask
= 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
277 /* .amb output requires FuMa */
278 mDevice
->mAmbiOrder
= std::min(mDevice
->mAmbiOrder
, 3u);
279 mDevice
->mAmbiLayout
= DevAmbiLayout::FuMa
;
280 mDevice
->mAmbiScale
= DevAmbiScaling::FuMa
;
285 bytes
= mDevice
->bytesFromFmt();
286 channels
= mDevice
->channelsFromFmt();
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());
329 mDataStart
= ftell(mFile
.get());
331 setDefaultWFXChannelOrder();
333 const uint bufsize
{mDevice
->frameSizeFromFmt() * mDevice
->UpdateSize
};
334 mBuffer
.resize(bufsize
);
339 void WaveBackend::start()
341 if(mDataStart
> 0 && fseek(mFile
.get(), 0, SEEK_END
) != 0)
342 WARN("Failed to seek on output file\n");
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())
361 long size
{ftell(mFile
.get())};
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
376 bool WaveBackendFactory::init()
379 bool WaveBackendFactory::querySupport(BackendType type
)
380 { return type
== BackendType::Playback
; }
382 auto WaveBackendFactory::enumerate(BackendType type
) -> std::vector
<std::string
>
386 case BackendType::Playback
:
387 return std::vector
{std::string
{GetDeviceName()}};
388 case BackendType::Capture
:
394 BackendPtr
WaveBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
396 if(type
== BackendType::Playback
)
397 return BackendPtr
{new WaveBackend
{device
}};
401 BackendFactory
&WaveBackendFactory::getFactory()
403 static WaveBackendFactory factory
{};