]> git.tdb.fi Git - ext/openal.git/blob - alc/backends/wave.cpp
Import OpenAL Soft 1.23.1 sources
[ext/openal.git] / alc / backends / wave.cpp
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.
8  *
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.
13  *
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
19  */
20
21 #include "config.h"
22
23 #include "wave.h"
24
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>
35
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"
48
49
50 namespace {
51
52 using std::chrono::seconds;
53 using std::chrono::milliseconds;
54 using std::chrono::nanoseconds;
55
56 using ubyte = unsigned char;
57 using ushort = unsigned short;
58
59 constexpr char waveDevice[] = "Wave File Writer";
60
61 constexpr ubyte SUBTYPE_PCM[]{
62     0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
63     0x00, 0x38, 0x9b, 0x71
64 };
65 constexpr ubyte SUBTYPE_FLOAT[]{
66     0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
67     0x00, 0x38, 0x9b, 0x71
68 };
69
70 constexpr ubyte SUBTYPE_BFORMAT_PCM[]{
71     0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
72     0xca, 0x00, 0x00, 0x00
73 };
74
75 constexpr ubyte SUBTYPE_BFORMAT_FLOAT[]{
76     0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
77     0xca, 0x00, 0x00, 0x00
78 };
79
80 void fwrite16le(ushort val, FILE *f)
81 {
82     ubyte data[2]{ static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff) };
83     fwrite(data, 1, 2, f);
84 }
85
86 void fwrite32le(uint val, FILE *f)
87 {
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);
91 }
92
93
94 struct WaveBackend final : public BackendBase {
95     WaveBackend(DeviceBase *device) noexcept : BackendBase{device} { }
96     ~WaveBackend() override;
97
98     int mixerProc();
99
100     void open(const char *name) override;
101     bool reset() override;
102     void start() override;
103     void stop() override;
104
105     FILE *mFile{nullptr};
106     long mDataStart{-1};
107
108     al::vector<al::byte> mBuffer;
109
110     std::atomic<bool> mKillNow{true};
111     std::thread mThread;
112
113     DEF_NEWDEL(WaveBackend)
114 };
115
116 WaveBackend::~WaveBackend()
117 {
118     if(mFile)
119         fclose(mFile);
120     mFile = nullptr;
121 }
122
123 int WaveBackend::mixerProc()
124 {
125     const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2};
126
127     althrd_setname(MIXER_THREAD_NAME);
128
129     const size_t frameStep{mDevice->channelsFromFmt()};
130     const size_t frameSize{mDevice->frameSizeFromFmt()};
131
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))
136     {
137         auto now = std::chrono::steady_clock::now();
138
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)
143         {
144             std::this_thread::sleep_for(restTime);
145             continue;
146         }
147         while(avail-done >= mDevice->UpdateSize)
148         {
149             mDevice->renderSamples(mBuffer.data(), mDevice->UpdateSize, frameStep);
150             done += mDevice->UpdateSize;
151
152             if(al::endian::native != al::endian::little)
153             {
154                 const uint bytesize{mDevice->bytesFromFmt()};
155
156                 if(bytesize == 2)
157                 {
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]);
161                 }
162                 else if(bytesize == 4)
163                 {
164                     const size_t len{mBuffer.size() & ~size_t{3}};
165                     for(size_t i{0};i < len;i+=4)
166                     {
167                         std::swap(mBuffer[i  ], mBuffer[i+3]);
168                         std::swap(mBuffer[i+1], mBuffer[i+2]);
169                     }
170                 }
171             }
172
173             const size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->UpdateSize, mFile)};
174             if(fs < mDevice->UpdateSize || ferror(mFile))
175             {
176                 ERR("Error writing to file\n");
177                 mDevice->handleDisconnect("Failed to write playback samples");
178                 break;
179             }
180         }
181
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.
186          */
187         if(done >= mDevice->Frequency)
188         {
189             seconds s{done/mDevice->Frequency};
190             done %= mDevice->Frequency;
191             start += s;
192         }
193     }
194
195     return 0;
196 }
197
198 void WaveBackend::open(const char *name)
199 {
200     auto fname = ConfigValueStr(nullptr, "wave", "file");
201     if(!fname) throw al::backend_exception{al::backend_error::NoDevice,
202         "No wave output filename"};
203
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};
209
210     /* There's only one "device", so if it's already open, we're done. */
211     if(mFile) return;
212
213 #ifdef _WIN32
214     {
215         std::wstring wname{utf8_to_wstr(fname->c_str())};
216         mFile = _wfopen(wname.c_str(), L"wb");
217     }
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)};
224
225     mDevice->DeviceName = name;
226 }
227
228 bool WaveBackend::reset()
229 {
230     uint channels{0}, bytes{0}, chanmask{0};
231     bool isbformat{false};
232     size_t val;
233
234     fseek(mFile, 0, SEEK_SET);
235     clearerr(mFile);
236
237     if(GetConfigValueBool(nullptr, "wave", "bformat", false))
238     {
239         mDevice->FmtChans = DevFmtAmbi3D;
240         mDevice->mAmbiOrder = 1;
241     }
242
243     switch(mDevice->FmtType)
244     {
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;
259     }
260     switch(mDevice->FmtChans)
261     {
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 DevFmtX714:
269         chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400 | 0x1000 | 0x4000
270             | 0x8000 | 0x20000;
271         break;
272     /* NOTE: Same as 7.1. */
273     case DevFmtX3D71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
274     case DevFmtAmbi3D:
275         /* .amb output requires FuMa */
276         mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3);
277         mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
278         mDevice->mAmbiScale = DevAmbiScaling::FuMa;
279         isbformat = true;
280         chanmask = 0;
281         break;
282     }
283     bytes = mDevice->bytesFromFmt();
284     channels = mDevice->channelsFromFmt();
285
286     rewind(mFile);
287
288     fputs("RIFF", mFile);
289     fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close
290
291     fputs("WAVE", mFile);
292
293     fputs("fmt ", mFile);
294     fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE
295
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);
318     (void)val;
319
320     fputs("data", mFile);
321     fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close
322
323     if(ferror(mFile))
324     {
325         ERR("Error writing header: %s\n", strerror(errno));
326         return false;
327     }
328     mDataStart = ftell(mFile);
329
330     setDefaultWFXChannelOrder();
331
332     const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
333     mBuffer.resize(bufsize);
334
335     return true;
336 }
337
338 void WaveBackend::start()
339 {
340     if(mDataStart > 0 && fseek(mFile, 0, SEEK_END) != 0)
341         WARN("Failed to seek on output file\n");
342     try {
343         mKillNow.store(false, std::memory_order_release);
344         mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
345     }
346     catch(std::exception& e) {
347         throw al::backend_exception{al::backend_error::DeviceError,
348             "Failed to start mixing thread: %s", e.what()};
349     }
350 }
351
352 void WaveBackend::stop()
353 {
354     if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
355         return;
356     mThread.join();
357
358     if(mDataStart > 0)
359     {
360         long size{ftell(mFile)};
361         if(size > 0)
362         {
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
368         }
369     }
370 }
371
372 } // namespace
373
374
375 bool WaveBackendFactory::init()
376 { return true; }
377
378 bool WaveBackendFactory::querySupport(BackendType type)
379 { return type == BackendType::Playback; }
380
381 std::string WaveBackendFactory::probe(BackendType type)
382 {
383     std::string outnames;
384     switch(type)
385     {
386     case BackendType::Playback:
387         /* Includes null char. */
388         outnames.append(waveDevice, sizeof(waveDevice));
389         break;
390     case BackendType::Capture:
391         break;
392     }
393     return outnames;
394 }
395
396 BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
397 {
398     if(type == BackendType::Playback)
399         return BackendPtr{new WaveBackend{device}};
400     return nullptr;
401 }
402
403 BackendFactory &WaveBackendFactory::getFactory()
404 {
405     static WaveBackendFactory factory{};
406     return factory;
407 }