File: audio_output.cpp

package info (click to toggle)
bino 1.6.6-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 4,636 kB
  • sloc: cpp: 21,288; sh: 4,849; makefile: 314; sed: 16
file content (497 lines) | stat: -rw-r--r-- 14,980 bytes parent folder | download | duplicates (2)
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
 * This file is part of bino, a 3D video player.
 *
 * Copyright (C) 2010, 2011, 2012, 2013, 2015
 * Martin Lambers <marlam@marlam.de>
 * Gabriele Greco <gabrielegreco@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <limits>

#include "audio_output.h"
#include "lib_versions.h"

#include "base/exc.h"
#include "base/str.h"
#include "base/msg.h"
#include "base/tmr.h"
#include "base/dbg.h"

#include "base/gettext.h"
#define _(string) gettext(string)


/* This code is adapted from the alffmpeg.c example available here:
 * http://kcat.strangesoft.net/alffmpeg.c (as of 2010-09-12). */

// These number should fit for most formats; see comments in the alffmpeg.c example.
const size_t audio_output::_num_buffers = 3;
const size_t audio_output::_buffer_size = 20160 * 2;

audio_output::audio_output() : controller(), _initialized(false)
{
    const char *p = NULL;
    if (alcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT"))
    {
        p = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
    }
    else if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))
    {
        p = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
    }
    while (p && *p)
    {
        _devices.push_back(p);
        p += _devices.back().length() + 1;
    }
    msg::dbg("%d OpenAL devices available:", devices());
    for (size_t i = 0; i < _devices.size(); i++)
    {
        msg::dbg(4, _devices[i]);
    }
}

audio_output::~audio_output()
{
    deinit();
}

int audio_output::devices() const
{
    return _devices.size();
}

const std::string &audio_output::device_name(int i) const
{
    assert(i >= 0 && i < devices());
    return _devices[i];
}

void audio_output::init(int i)
{
    if (!_initialized)
    {
        if (i < 0)
        {
            if (!(_device = alcOpenDevice(NULL)))
            {
                throw exc(_("No OpenAL device available."));
            }
        }
        else if (i >= static_cast<int>(_devices.size()))
        {
            throw exc(str::asprintf(_("OpenAL device '%s' is not available."), _("unknown")));
        }
        else
        {
            if (!(_device = alcOpenDevice(_devices[i].c_str())))
            {
                throw exc(str::asprintf(_("OpenAL device '%s' is not available."),
                            _devices[i].c_str()));
            }
        }
        if (!(_context = alcCreateContext(_device, NULL)))
        {
            alcCloseDevice(_device);
            throw exc(_("No OpenAL context available."));
        }
        alcMakeContextCurrent(_context);
        set_openal_versions();
        _buffers.resize(_num_buffers);
        alGenBuffers(_num_buffers, &(_buffers[0]));
        if (alGetError() != AL_NO_ERROR)
        {
            alcMakeContextCurrent(NULL);
            alcDestroyContext(_context);
            alcCloseDevice(_device);
            throw exc(_("Cannot create OpenAL buffers."));
        }
        alGenSources(1, &_source);
        if (alGetError() != AL_NO_ERROR)
        {
            alDeleteBuffers(_num_buffers, &(_buffers[0]));
            alcMakeContextCurrent(NULL);
            alcDestroyContext(_context);
            alcCloseDevice(_device);
            throw exc(_("Cannot create OpenAL source."));
        }
        /* Comment from alffmpeg.c:
         * "Set parameters so mono sources won't distance attenuate" */
        alSourcei(_source, AL_SOURCE_RELATIVE, AL_TRUE);
        alSourcei(_source, AL_ROLLOFF_FACTOR, 0);
        if (alGetError() != AL_NO_ERROR)
        {
            alDeleteSources(1, &_source);
            alDeleteBuffers(_num_buffers, &(_buffers[0]));
            alcMakeContextCurrent(NULL);
            alcDestroyContext(_context);
            alcCloseDevice(_device);
            throw exc(_("Cannot set OpenAL source parameters."));
        }
        _state = 0;
        _initialized = true;
    }
}

void audio_output::deinit()
{
    if (_initialized)
    {
        do
        {
            alGetSourcei(_source, AL_SOURCE_STATE, &_state);
        }
        while (alGetError() == AL_NO_ERROR && _state == AL_PLAYING);
        alDeleteSources(1, &_source);
        alDeleteBuffers(_num_buffers, &(_buffers[0]));
        alcMakeContextCurrent(NULL);
        alcDestroyContext(_context);
        alcCloseDevice(_device);
        _initialized = false;
    }
}

size_t audio_output::required_initial_data_size() const
{
    return _num_buffers * _buffer_size;
}

size_t audio_output::required_update_data_size() const
{
    return _buffer_size;
}

int64_t audio_output::status(bool *need_data)
{
    if (_state == 0)
    {
        if (need_data)
        {
            *need_data = true;
        }
        return std::numeric_limits<int64_t>::min();
    }
    else
    {
        ALint processed = 0;
        alGetSourcei(_source, AL_BUFFERS_PROCESSED, &processed);
        if (processed == 0)
        {
            alGetSourcei(_source, AL_SOURCE_STATE, &_state);
            if (alGetError() != AL_NO_ERROR)
            {
                throw exc(_("Cannot check OpenAL source state."));
            }
            if (_state != AL_PLAYING)
            {
                alSourcePlay(_source);
                if (alGetError() != AL_NO_ERROR)
                {
                    throw exc(_("Cannot restart OpenAL source playback."));
                }
            }
            if (need_data)
            {
                *need_data = false;
            }
        }
        else
        {
            if (need_data)
            {
                *need_data = true;
            }
        }
        ALint offset;
        alGetSourcei(_source, AL_SAMPLE_OFFSET, &offset);
        /* The time inside the current buffer */
        int64_t timestamp = static_cast<int64_t>(offset) * 1000000 / _buffer_rates[0];
        /* Add the time for all past buffers */
        timestamp += _past_time;
        /* This timestamp unfortunately only grows in relatively large steps. This is
         * too imprecise for syncing a video stream with. Therefore, we use an external
         * time source between two timestamp steps. In case this external time runs
         * faster than the audio time, we also need to make sure that we do not report
         * timestamps that run backwards. */
        if (timestamp != _last_timestamp)
        {
            _last_timestamp = timestamp;
            _ext_timer_at_last_timestamp = timer::get(timer::monotonic);
            _last_reported_timestamp = std::max(_last_reported_timestamp, timestamp);
            return _last_reported_timestamp;
        }
        else
        {
            _last_reported_timestamp = _last_timestamp + (timer::get(timer::monotonic) - _ext_timer_at_last_timestamp);
            return _last_reported_timestamp;
        }
    }
}

ALenum audio_output::get_al_format(const audio_blob &blob)
{
    ALenum format = 0;
    if (blob.sample_format == audio_blob::u8)
    {
        if (blob.channels == 1)
        {
            format = AL_FORMAT_MONO8;
        }
        else if (blob.channels == 2)
        {
            format = AL_FORMAT_STEREO8;
        }
        else if (alIsExtensionPresent("AL_EXT_MCFORMATS"))
        {
            if (blob.channels == 4)
            {
                format = alGetEnumValue("AL_FORMAT_QUAD8");
            }
            else if (blob.channels == 6)
            {
                format = alGetEnumValue("AL_FORMAT_51CHN8");
            }
            else if (blob.channels == 7)
            {
                format = alGetEnumValue("AL_FORMAT_71CHN8");
            }
            else if (blob.channels == 8)
            {
                format = alGetEnumValue("AL_FORMAT_81CHN8");
            }
        }
    }
    else if (blob.sample_format == audio_blob::s16)
    {
        if (blob.channels == 1)
        {
            format = AL_FORMAT_MONO16;
        }
        else if (blob.channels == 2)
        {
            format = AL_FORMAT_STEREO16;
        }
        else if (alIsExtensionPresent("AL_EXT_MCFORMATS"))
        {
            if (blob.channels == 4)
            {
                format = alGetEnumValue("AL_FORMAT_QUAD16");
            }
            else if (blob.channels == 6)
            {
                format = alGetEnumValue("AL_FORMAT_51CHN16");
            }
            else if (blob.channels == 7)
            {
                format = alGetEnumValue("AL_FORMAT_61CHN16");
            }
            else if (blob.channels == 8)
            {
                format = alGetEnumValue("AL_FORMAT_71CHN16");
            }
        }
    }
    else if (blob.sample_format == audio_blob::f32)
    {
        if (alIsExtensionPresent("AL_EXT_float32"))
        {
            if (blob.channels == 1)
            {
                format = alGetEnumValue("AL_FORMAT_MONO_FLOAT32");
            }
            else if (blob.channels == 2)
            {
                format = alGetEnumValue("AL_FORMAT_STEREO_FLOAT32");
            }
            else if (alIsExtensionPresent("AL_EXT_MCFORMATS"))
            {
                if (blob.channels == 4)
                {
                    format = alGetEnumValue("AL_FORMAT_QUAD32");
                }
                else if (blob.channels == 6)
                {
                    format = alGetEnumValue("AL_FORMAT_51CHN32");
                }
                else if (blob.channels == 7)
                {
                    format = alGetEnumValue("AL_FORMAT_61CHN32");
                }
                else if (blob.channels == 8)
                {
                    format = alGetEnumValue("AL_FORMAT_71CHN32");
                }
            }
        }
    }
    else if (blob.sample_format == audio_blob::d64)
    {
        if (alIsExtensionPresent("AL_EXT_double"))
        {
            if (blob.channels == 1)
            {
                format = alGetEnumValue("AL_FORMAT_MONO_DOUBLE_EXT");
            }
            else if (blob.channels == 2)
            {
                format = alGetEnumValue("AL_FORMAT_STEREO_DOUBLE_EXT");
            }
        }
    }
    if (format == 0)
    {
        throw exc(str::asprintf(_("No OpenAL format available for "
                        "audio data format %s."), blob.format_name().c_str()));
    }
    return format;
}

void audio_output::set_source_parameters()
{
    float gain = dispatch::parameters().audio_volume();
    if (dispatch::parameters().audio_mute())
    {
        gain = 0.0f;
    }
    alSourcef(_source, AL_GAIN, gain);
    if (alGetError() != AL_NO_ERROR)
    {
        throw exc(_("Cannot set OpenAL audio volume."));
    }
}

void audio_output::data(const audio_blob &blob)
{
    assert(blob.data);
    ALenum format = get_al_format(blob);
    msg::dbg(std::string("Buffering ") + str::from(blob.size) + " bytes of audio data.");
    if (_state == 0)
    {
        set_source_parameters();
        // Initial buffering
        assert(blob.size == _num_buffers * _buffer_size);
        char *data = static_cast<char *>(blob.data);
        for (size_t j = 0; j < _num_buffers; j++)
        {
            _buffer_channels.push_back(blob.channels);
            _buffer_sample_bits.push_back(blob.sample_bits());
            _buffer_rates.push_back(blob.rate);
            alBufferData(_buffers[j], format, data, _buffer_size, blob.rate);
            alSourceQueueBuffers(_source, 1, &(_buffers[j]));
            data += _buffer_size;
        }
        if (alGetError() != AL_NO_ERROR)
        {
            throw exc(_("Cannot buffer initial OpenAL data."));
        }
    }
    else if (blob.size > 0)
    {
        // Replace one buffer
        assert(blob.size == _buffer_size);
        ALuint buf = 0;
        alSourceUnqueueBuffers(_source, 1, &buf);
        assert(buf != 0);
        alBufferData(buf, format, blob.data, _buffer_size, blob.rate);
        alSourceQueueBuffers(_source, 1, &buf);
        if (alGetError() != AL_NO_ERROR)
        {
            throw exc(_("Cannot buffer OpenAL data."));
        }
        // Update the time spent on all past buffers
        int64_t current_buffer_samples = _buffer_size / _buffer_channels[0] * 8 / _buffer_sample_bits[0];
        int64_t current_buffer_time = current_buffer_samples * 1000000 / _buffer_rates[0];
        _past_time += current_buffer_time;
        // Remove current buffer entries
        _buffer_channels.erase(_buffer_channels.begin());
        _buffer_sample_bits.erase(_buffer_sample_bits.begin());
        _buffer_rates.erase(_buffer_rates.begin());
        // Add entries for the new buffer
        _buffer_channels.push_back(blob.channels);
        _buffer_sample_bits.push_back(blob.sample_bits());
        _buffer_rates.push_back(blob.rate);
    }
}

int64_t audio_output::start()
{
    msg::dbg("Starting audio output.");
    assert(_state == 0);
    alSourcePlay(_source);
    alGetSourcei(_source, AL_SOURCE_STATE, &_state);
    if (alGetError() != AL_NO_ERROR)
    {
        throw exc(_("Cannot start OpenAL source playback."));
    }
    _past_time = 0;
    _last_timestamp = 0;
    _ext_timer_at_last_timestamp = timer::get(timer::monotonic);
    _last_reported_timestamp = _last_timestamp;
    return _last_timestamp;
}

void audio_output::pause()
{
    alSourcePause(_source);
    if (alGetError() != AL_NO_ERROR)
    {
        throw exc(_("Cannot pause OpenAL source playback."));
    }
}

void audio_output::unpause()
{
    alSourcePlay(_source);
    if (alGetError() != AL_NO_ERROR)
    {
        throw exc(_("Cannot unpause OpenAL source playback."));
    }
}

void audio_output::stop()
{
    alSourceStop(_source);
    if (alGetError() != AL_NO_ERROR)
    {
        throw exc(_("Cannot stop OpenAL source playback."));
    }
    // flush all buffers and reset the state
    ALint processed_buffers;
    alGetSourcei(_source, AL_BUFFERS_PROCESSED, &processed_buffers);
    while (processed_buffers > 0)
    {
        ALuint buf = 0;
        alSourceUnqueueBuffers(_source, 1, &buf);
        if (alGetError() != AL_NO_ERROR)
        {
            throw exc(_("Cannot unqueue OpenAL source buffers."));
        }
        alGetSourcei(_source, AL_BUFFERS_PROCESSED, &processed_buffers);
    }
    _state = 0;
}

void audio_output::receive_notification(const notification& note)
{
    if (_initialized
            && (note.type == notification::audio_volume
                || note.type == notification::audio_mute))
    {
        set_source_parameters();
    }
}