aboutsummaryrefslogtreecommitdiffstats
path: root/alc/backends/wave.cpp
blob: 60cebd7fac4f2a9064489ffc746a0b324282a44b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/**
 * OpenAL cross platform audio library
 * Copyright (C) 1999-2007 by authors.
 * This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 *  License along with this library; if not, write to the
 *  Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * Or go to http://www.gnu.org/copyleft/lgpl.html
 */

#include "config.h"

#include "wave.h"

#include <algorithm>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <exception>
#include <functional>
#include <thread>
#include <vector>

#include "albit.h"
#include "alc/alconfig.h"
#include "almalloc.h"
#include "alnumeric.h"
#include "althrd_setname.h"
#include "core/device.h"
#include "core/helpers.h"
#include "core/logging.h"
#include "opthelpers.h"
#include "strutils.h"


namespace {

using std::chrono::seconds;
using std::chrono::milliseconds;
using std::chrono::nanoseconds;

using ubyte = unsigned char;
using ushort = unsigned short;

struct FileDeleter {
    void operator()(FILE *f) { fclose(f); }
};
using FilePtr = std::unique_ptr<FILE,FileDeleter>;

/* NOLINTNEXTLINE(*-avoid-c-arrays) */
constexpr char waveDevice[] = "Wave File Writer";

constexpr std::array<ubyte,16> SUBTYPE_PCM{{
    0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
    0x00, 0x38, 0x9b, 0x71
}};
constexpr std::array<ubyte,16> SUBTYPE_FLOAT{{
    0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa,
    0x00, 0x38, 0x9b, 0x71
}};

constexpr std::array<ubyte,16> SUBTYPE_BFORMAT_PCM{{
    0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
    0xca, 0x00, 0x00, 0x00
}};

constexpr std::array<ubyte,16> SUBTYPE_BFORMAT_FLOAT{{
    0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
    0xca, 0x00, 0x00, 0x00
}};

void fwrite16le(ushort val, FILE *f)
{
    std::array data{static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff)};
    fwrite(data.data(), 1, data.size(), f);
}

void fwrite32le(uint val, FILE *f)
{
    std::array data{static_cast<ubyte>(val&0xff), static_cast<ubyte>((val>>8)&0xff),
        static_cast<ubyte>((val>>16)&0xff), static_cast<ubyte>((val>>24)&0xff)};
    fwrite(data.data(), 1, data.size(), f);
}


struct WaveBackend final : public BackendBase {
    WaveBackend(DeviceBase *device) noexcept : BackendBase{device} { }
    ~WaveBackend() override;

    int mixerProc();

    void open(std::string_view name) override;
    bool reset() override;
    void start() override;
    void stop() override;

    FilePtr mFile{nullptr};
    long mDataStart{-1};

    std::vector<std::byte> mBuffer;

    std::atomic<bool> mKillNow{true};
    std::thread mThread;
};

WaveBackend::~WaveBackend() = default;

int WaveBackend::mixerProc()
{
    const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2};

    althrd_setname(MIXER_THREAD_NAME);

    const size_t frameStep{mDevice->channelsFromFmt()};
    const size_t frameSize{mDevice->frameSizeFromFmt()};

    int64_t done{0};
    auto start = std::chrono::steady_clock::now();
    while(!mKillNow.load(std::memory_order_acquire)
        && mDevice->Connected.load(std::memory_order_acquire))
    {
        auto now = std::chrono::steady_clock::now();

        /* This converts from nanoseconds to nanosamples, then to samples. */
        int64_t avail{std::chrono::duration_cast<seconds>((now-start) *
            mDevice->Frequency).count()};
        if(avail-done < mDevice->UpdateSize)
        {
            std::this_thread::sleep_for(restTime);
            continue;
        }
        while(avail-done >= mDevice->UpdateSize)
        {
            mDevice->renderSamples(mBuffer.data(), mDevice->UpdateSize, frameStep);
            done += mDevice->UpdateSize;

            if(al::endian::native != al::endian::little)
            {
                const uint bytesize{mDevice->bytesFromFmt()};

                if(bytesize == 2)
                {
                    const size_t len{mBuffer.size() & ~1_uz};
                    for(size_t i{0};i < len;i+=2)
                        std::swap(mBuffer[i], mBuffer[i+1]);
                }
                else if(bytesize == 4)
                {
                    const size_t len{mBuffer.size() & ~3_uz};
                    for(size_t i{0};i < len;i+=4)
                    {
                        std::swap(mBuffer[i  ], mBuffer[i+3]);
                        std::swap(mBuffer[i+1], mBuffer[i+2]);
                    }
                }
            }

            const size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->UpdateSize, mFile.get())};
            if(fs < mDevice->UpdateSize || ferror(mFile.get()))
            {
                ERR("Error writing to file\n");
                mDevice->handleDisconnect("Failed to write playback samples");
                break;
            }
        }

        /* For every completed second, increment the start time and reduce the
         * samples done. This prevents the difference between the start time
         * and current time from growing too large, while maintaining the
         * correct number of samples to render.
         */
        if(done >= mDevice->Frequency)
        {
            seconds s{done/mDevice->Frequency};
            done %= mDevice->Frequency;
            start += s;
        }
    }

    return 0;
}

void WaveBackend::open(std::string_view name)
{
    auto fname = ConfigValueStr({}, "wave", "file");
    if(!fname) throw al::backend_exception{al::backend_error::NoDevice,
        "No wave output filename"};

    if(name.empty())
        name = waveDevice;
    else if(name != waveDevice)
        throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%.*s\" not found",
            static_cast<int>(name.length()), name.data()};

    /* There's only one "device", so if it's already open, we're done. */
    if(mFile) return;

#ifdef _WIN32
    {
        std::wstring wname{utf8_to_wstr(fname.value())};
        mFile.reset(_wfopen(wname.c_str(), L"wb"));
    }
#else
    mFile.reset(fopen(fname->c_str(), "wb"));
#endif
    if(!mFile)
        throw al::backend_exception{al::backend_error::DeviceError, "Could not open file '%s': %s",
            fname->c_str(), strerror(errno)};

    mDevice->DeviceName = name;
}

bool WaveBackend::reset()
{
    uint channels{0}, bytes{0}, chanmask{0};
    bool isbformat{false};

    fseek(mFile.get(), 0, SEEK_SET);
    clearerr(mFile.get());

    if(GetConfigValueBool({}, "wave", "bformat", false))
    {
        mDevice->FmtChans = DevFmtAmbi3D;
        mDevice->mAmbiOrder = 1;
    }

    switch(mDevice->FmtType)
    {
    case DevFmtByte:
        mDevice->FmtType = DevFmtUByte;
        break;
    case DevFmtUShort:
        mDevice->FmtType = DevFmtShort;
        break;
    case DevFmtUInt:
        mDevice->FmtType = DevFmtInt;
        break;
    case DevFmtUByte:
    case DevFmtShort:
    case DevFmtInt:
    case DevFmtFloat:
        break;
    }
    switch(mDevice->FmtChans)
    {
    case DevFmtMono:   chanmask = 0x04; break;
    case DevFmtStereo: chanmask = 0x01 | 0x02; break;
    case DevFmtQuad:   chanmask = 0x01 | 0x02 | 0x10 | 0x20; break;
    case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break;
    case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break;
    case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
    case DevFmtX714:
        chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400 | 0x1000 | 0x4000
            | 0x8000 | 0x20000;
        break;
    /* NOTE: Same as 7.1. */
    case DevFmtX3D71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break;
    case DevFmtAmbi3D:
        /* .amb output requires FuMa */
        mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3);
        mDevice->mAmbiLayout = DevAmbiLayout::FuMa;
        mDevice->mAmbiScale = DevAmbiScaling::FuMa;
        isbformat = true;
        chanmask = 0;
        break;
    }
    bytes = mDevice->bytesFromFmt();
    channels = mDevice->channelsFromFmt();

    rewind(mFile.get());

    fputs("RIFF", mFile.get());
    fwrite32le(0xFFFFFFFF, mFile.get()); // 'RIFF' header len; filled in at close

    fputs("WAVE", mFile.get());

    fputs("fmt ", mFile.get());
    fwrite32le(40, mFile.get()); // 'fmt ' header len; 40 bytes for EXTENSIBLE

    // 16-bit val, format type id (extensible: 0xFFFE)
    fwrite16le(0xFFFE, mFile.get());
    // 16-bit val, channel count
    fwrite16le(static_cast<ushort>(channels), mFile.get());
    // 32-bit val, frequency
    fwrite32le(mDevice->Frequency, mFile.get());
    // 32-bit val, bytes per second
    fwrite32le(mDevice->Frequency * channels * bytes, mFile.get());
    // 16-bit val, frame size
    fwrite16le(static_cast<ushort>(channels * bytes), mFile.get());
    // 16-bit val, bits per sample
    fwrite16le(static_cast<ushort>(bytes * 8), mFile.get());
    // 16-bit val, extra byte count
    fwrite16le(22, mFile.get());
    // 16-bit val, valid bits per sample
    fwrite16le(static_cast<ushort>(bytes * 8), mFile.get());
    // 32-bit val, channel mask
    fwrite32le(chanmask, mFile.get());
    // 16 byte GUID, sub-type format
    std::ignore = fwrite((mDevice->FmtType == DevFmtFloat) ?
        (isbformat ? SUBTYPE_BFORMAT_FLOAT.data() : SUBTYPE_FLOAT.data()) :
        (isbformat ? SUBTYPE_BFORMAT_PCM.data() : SUBTYPE_PCM.data()), 1, 16, mFile.get());

    fputs("data", mFile.get());
    fwrite32le(0xFFFFFFFF, mFile.get()); // 'data' header len; filled in at close

    if(ferror(mFile.get()))
    {
        ERR("Error writing header: %s\n", strerror(errno));
        return false;
    }
    mDataStart = ftell(mFile.get());

    setDefaultWFXChannelOrder();

    const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize};
    mBuffer.resize(bufsize);

    return true;
}

void WaveBackend::start()
{
    if(mDataStart > 0 && fseek(mFile.get(), 0, SEEK_END) != 0)
        WARN("Failed to seek on output file\n");
    try {
        mKillNow.store(false, std::memory_order_release);
        mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this};
    }
    catch(std::exception& e) {
        throw al::backend_exception{al::backend_error::DeviceError,
            "Failed to start mixing thread: %s", e.what()};
    }
}

void WaveBackend::stop()
{
    if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
        return;
    mThread.join();

    if(mDataStart > 0)
    {
        long size{ftell(mFile.get())};
        if(size > 0)
        {
            long dataLen{size - mDataStart};
            if(fseek(mFile.get(), 4, SEEK_SET) == 0)
                fwrite32le(static_cast<uint>(size-8), mFile.get()); // 'WAVE' header len
            if(fseek(mFile.get(), mDataStart-4, SEEK_SET) == 0)
                fwrite32le(static_cast<uint>(dataLen), mFile.get()); // 'data' header len
        }
    }
}

} // namespace


bool WaveBackendFactory::init()
{ return true; }

bool WaveBackendFactory::querySupport(BackendType type)
{ return type == BackendType::Playback; }

std::string WaveBackendFactory::probe(BackendType type)
{
    std::string outnames;
    switch(type)
    {
    case BackendType::Playback:
        /* Includes null char. */
        outnames.append(waveDevice, sizeof(waveDevice));
        break;
    case BackendType::Capture:
        break;
    }
    return outnames;
}

BackendPtr WaveBackendFactory::createBackend(DeviceBase *device, BackendType type)
{
    if(type == BackendType::Playback)
        return BackendPtr{new WaveBackend{device}};
    return nullptr;
}

BackendFactory &WaveBackendFactory::getFactory()
{
    static WaveBackendFactory factory{};
    return factory;
}