aboutsummaryrefslogtreecommitdiffstats
path: root/examples/alstream.c
blob: 5cbbc2a79c5fff173c291f24bbcf6dbb92a1c068 (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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
 * OpenAL Audio Stream Example
 *
 * Copyright (c) 2011 by Chris Robinson <chris.kcat@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/* This file contains a relatively simple streaming audio player. */

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "sndfile.h"

#include "AL/al.h"
#include "AL/alext.h"

#include "common/alhelpers.h"

#include "win_main_utf8.h"


/* Define the number of buffers and buffer size (in milliseconds) to use. 4
 * buffers at 200ms each gives a nice per-chunk size, and lets the queue last
 * for almost one second.
 */
enum { NumBuffers = 4 };
enum { BufferMillisec = 200 };

typedef enum SampleType {
    Int16, Float, IMA4, MSADPCM
} SampleType;

typedef struct StreamPlayer {
    /* These are the buffers and source to play out through OpenAL with. */
    ALuint buffers[NumBuffers];
    ALuint source;

    /* Handle for the audio file */
    SNDFILE *sndfile;
    SF_INFO sfinfo;
    void *membuf;

    /* The sample type and block/frame size being read for the buffer. */
    SampleType sample_type;
    int byteblockalign;
    int sampleblockalign;
    int block_count;

    /* The format of the output stream (sample rate is in sfinfo) */
    ALenum format;
} StreamPlayer;

static StreamPlayer *NewPlayer(void);
static void DeletePlayer(StreamPlayer *player);
static int OpenPlayerFile(StreamPlayer *player, const char *filename);
static void ClosePlayerFile(StreamPlayer *player);
static int StartPlayer(StreamPlayer *player);
static int UpdatePlayer(StreamPlayer *player);

/* Creates a new player object, and allocates the needed OpenAL source and
 * buffer objects. Error checking is simplified for the purposes of this
 * example, and will cause an abort if needed.
 */
static StreamPlayer *NewPlayer(void)
{
    StreamPlayer *player;

    player = calloc(1, sizeof(*player));
    assert(player != NULL);

    /* Generate the buffers and source */
    alGenBuffers(NumBuffers, player->buffers);
    assert(alGetError() == AL_NO_ERROR && "Could not create buffers");

    alGenSources(1, &player->source);
    assert(alGetError() == AL_NO_ERROR && "Could not create source");

    /* Set parameters so mono sources play out the front-center speaker and
     * won't distance attenuate. */
    alSource3i(player->source, AL_POSITION, 0, 0, -1);
    alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE);
    alSourcei(player->source, AL_ROLLOFF_FACTOR, 0);
    assert(alGetError() == AL_NO_ERROR && "Could not set source parameters");

    return player;
}

/* Destroys a player object, deleting the source and buffers. No error handling
 * since these calls shouldn't fail with a properly-made player object. */
static void DeletePlayer(StreamPlayer *player)
{
    ClosePlayerFile(player);

    alDeleteSources(1, &player->source);
    alDeleteBuffers(NumBuffers, player->buffers);
    if(alGetError() != AL_NO_ERROR)
        fprintf(stderr, "Failed to delete object IDs\n");

    memset(player, 0, sizeof(*player)); /* NOLINT(clang-analyzer-security.insecureAPI.*) */
    free(player);
}


/* Opens the first audio stream of the named file. If a file is already open,
 * it will be closed first. */
static int OpenPlayerFile(StreamPlayer *player, const char *filename)
{
    int byteblockalign=0, splblockalign=0;

    ClosePlayerFile(player);

    /* Open the audio file and check that it's usable. */
    player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo);
    if(!player->sndfile)
    {
        fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL));
        return 0;
    }

    /* Detect a suitable format to load. Formats like Vorbis and Opus use float
     * natively, so load as float to avoid clipping when possible. Formats
     * larger than 16-bit can also use float to preserve a bit more precision.
     */
    switch((player->sfinfo.format&SF_FORMAT_SUBMASK))
    {
    case SF_FORMAT_PCM_24:
    case SF_FORMAT_PCM_32:
    case SF_FORMAT_FLOAT:
    case SF_FORMAT_DOUBLE:
    case SF_FORMAT_VORBIS:
    case SF_FORMAT_OPUS:
    case SF_FORMAT_ALAC_20:
    case SF_FORMAT_ALAC_24:
    case SF_FORMAT_ALAC_32:
    case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
    case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
    case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
        if(alIsExtensionPresent("AL_EXT_FLOAT32"))
            player->sample_type = Float;
        break;
    case SF_FORMAT_IMA_ADPCM:
        /* ADPCM formats require setting a block alignment as specified in the
         * file, which needs to be read from the wave 'fmt ' chunk manually
         * since libsndfile doesn't provide it in a format-agnostic way.
         */
        if(player->sfinfo.channels <= 2
            && (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
            && alIsExtensionPresent("AL_EXT_IMA4")
            && alIsExtensionPresent("AL_SOFT_block_alignment"))
            player->sample_type = IMA4;
        break;
    case SF_FORMAT_MS_ADPCM:
        if(player->sfinfo.channels <= 2
            && (player->sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
            && alIsExtensionPresent("AL_SOFT_MSADPCM")
            && alIsExtensionPresent("AL_SOFT_block_alignment"))
            player->sample_type = MSADPCM;
        break;
    }

    if(player->sample_type == IMA4 || player->sample_type == MSADPCM)
    {
        /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
         * WAVEFORMATEX-based structure for the audio format.
         */
        SF_CHUNK_INFO inf = { "fmt ", 4, 0, NULL };
        SF_CHUNK_ITERATOR *iter = sf_get_chunk_iterator(player->sndfile, &inf);

        /* If there's an issue getting the chunk or block alignment, load as
         * 16-bit and have libsndfile do the conversion.
         */
        if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
            player->sample_type = Int16;
        else
        {
            ALubyte *fmtbuf = calloc(inf.datalen, 1);
            inf.data = fmtbuf;
            if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
                player->sample_type = Int16;
            else
            {
                /* Read the nBlockAlign field, and convert from bytes- to
                 * samples-per-block (verifying it's valid by converting back
                 * and comparing to the original value).
                 */
                byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
                if(player->sample_type == IMA4)
                {
                    splblockalign = (byteblockalign/player->sfinfo.channels - 4)/4*8 + 1;
                    if(splblockalign < 1
                        || ((splblockalign-1)/2 + 4)*player->sfinfo.channels != byteblockalign)
                        player->sample_type = Int16;
                }
                else
                {
                    splblockalign = (byteblockalign/player->sfinfo.channels - 7)*2 + 2;
                    if(splblockalign < 2
                        || ((splblockalign-2)/2 + 7)*player->sfinfo.channels != byteblockalign)
                        player->sample_type = Int16;
                }
            }
            free(fmtbuf);
        }
    }

    if(player->sample_type == Int16)
    {
        player->sampleblockalign = 1;
        player->byteblockalign = player->sfinfo.channels * 2;
    }
    else if(player->sample_type == Float)
    {
        player->sampleblockalign = 1;
        player->byteblockalign = player->sfinfo.channels * 4;
    }
    else
    {
        player->sampleblockalign = splblockalign;
        player->byteblockalign = byteblockalign;
    }

    /* Figure out the OpenAL format from the file and desired sample type. */
    player->format = AL_NONE;
    if(player->sfinfo.channels == 1)
    {
        if(player->sample_type == Int16)
            player->format = AL_FORMAT_MONO16;
        else if(player->sample_type == Float)
            player->format = AL_FORMAT_MONO_FLOAT32;
        else if(player->sample_type == IMA4)
            player->format = AL_FORMAT_MONO_IMA4;
        else if(player->sample_type == MSADPCM)
            player->format = AL_FORMAT_MONO_MSADPCM_SOFT;
    }
    else if(player->sfinfo.channels == 2)
    {
        if(player->sample_type == Int16)
            player->format = AL_FORMAT_STEREO16;
        else if(player->sample_type == Float)
            player->format = AL_FORMAT_STEREO_FLOAT32;
        else if(player->sample_type == IMA4)
            player->format = AL_FORMAT_STEREO_IMA4;
        else if(player->sample_type == MSADPCM)
            player->format = AL_FORMAT_STEREO_MSADPCM_SOFT;
    }
    else if(player->sfinfo.channels == 3)
    {
        if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
        {
            if(player->sample_type == Int16)
                player->format = AL_FORMAT_BFORMAT2D_16;
            else if(player->sample_type == Float)
                player->format = AL_FORMAT_BFORMAT2D_FLOAT32;
        }
    }
    else if(player->sfinfo.channels == 4)
    {
        if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT)
        {
            if(player->sample_type == Int16)
                player->format = AL_FORMAT_BFORMAT3D_16;
            else if(player->sample_type == Float)
                player->format = AL_FORMAT_BFORMAT3D_FLOAT32;
        }
    }
    if(!player->format)
    {
        fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels);
        sf_close(player->sndfile);
        player->sndfile = NULL;
        return 0;
    }

    player->block_count = player->sfinfo.samplerate / player->sampleblockalign;
    player->block_count = player->block_count * BufferMillisec / 1000;
    player->membuf = malloc((size_t)(player->block_count * player->byteblockalign));

    return 1;
}

/* Closes the audio file stream */
static void ClosePlayerFile(StreamPlayer *player)
{
    if(player->sndfile)
        sf_close(player->sndfile);
    player->sndfile = NULL;

    free(player->membuf);
    player->membuf = NULL;

    if(player->sampleblockalign > 1)
    {
        ALsizei i;
        for(i = 0;i < NumBuffers;i++)
            alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT, 0);
        player->sampleblockalign = 0;
        player->byteblockalign = 0;
    }
}


/* Prebuffers some audio from the file, and starts playing the source */
static int StartPlayer(StreamPlayer *player)
{
    ALsizei i;

    /* Rewind the source position and clear the buffer queue */
    alSourceRewind(player->source);
    alSourcei(player->source, AL_BUFFER, 0);

    /* Fill the buffer queue */
    for(i = 0;i < NumBuffers;i++)
    {
        sf_count_t slen;

        /* Get some data to give it to the buffer */
        if(player->sample_type == Int16)
        {
            slen = sf_readf_short(player->sndfile, player->membuf,
                player->block_count * player->sampleblockalign);
            if(slen < 1) break;
            slen *= player->byteblockalign;
        }
        else if(player->sample_type == Float)
        {
            slen = sf_readf_float(player->sndfile, player->membuf,
                player->block_count * player->sampleblockalign);
            if(slen < 1) break;
            slen *= player->byteblockalign;
        }
        else
        {
            slen = sf_read_raw(player->sndfile, player->membuf,
                player->block_count * player->byteblockalign);
            if(slen > 0) slen -= slen%player->byteblockalign;
            if(slen < 1) break;
        }

        if(player->sampleblockalign > 1)
            alBufferi(player->buffers[i], AL_UNPACK_BLOCK_ALIGNMENT_SOFT,
                player->sampleblockalign);

        alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen,
            player->sfinfo.samplerate);
    }
    if(alGetError() != AL_NO_ERROR)
    {
        fprintf(stderr, "Error buffering for playback\n");
        return 0;
    }

    /* Now queue and start playback! */
    alSourceQueueBuffers(player->source, i, player->buffers);
    alSourcePlay(player->source);
    if(alGetError() != AL_NO_ERROR)
    {
        fprintf(stderr, "Error starting playback\n");
        return 0;
    }

    return 1;
}

static int UpdatePlayer(StreamPlayer *player)
{
    ALint processed, state;

    /* Get relevant source info */
    alGetSourcei(player->source, AL_SOURCE_STATE, &state);
    alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed);
    if(alGetError() != AL_NO_ERROR)
    {
        fprintf(stderr, "Error checking source state\n");
        return 0;
    }

    /* Unqueue and handle each processed buffer */
    while(processed > 0)
    {
        ALuint bufid;
        sf_count_t slen;

        alSourceUnqueueBuffers(player->source, 1, &bufid);
        processed--;

        /* Read the next chunk of data, refill the buffer, and queue it
         * back on the source */
        if(player->sample_type == Int16)
        {
            slen = sf_readf_short(player->sndfile, player->membuf,
                player->block_count * player->sampleblockalign);
            if(slen > 0) slen *= player->byteblockalign;
        }
        else if(player->sample_type == Float)
        {
            slen = sf_readf_float(player->sndfile, player->membuf,
                player->block_count * player->sampleblockalign);
            if(slen > 0) slen *= player->byteblockalign;
        }
        else
        {
            slen = sf_read_raw(player->sndfile, player->membuf,
                player->block_count * player->byteblockalign);
            if(slen > 0) slen -= slen%player->byteblockalign;
        }

        if(slen > 0)
        {
            alBufferData(bufid, player->format, player->membuf, (ALsizei)slen,
                player->sfinfo.samplerate);
            alSourceQueueBuffers(player->source, 1, &bufid);
        }
        if(alGetError() != AL_NO_ERROR)
        {
            fprintf(stderr, "Error buffering data\n");
            return 0;
        }
    }

    /* Make sure the source hasn't underrun */
    if(state != AL_PLAYING && state != AL_PAUSED)
    {
        ALint queued;

        /* If no buffers are queued, playback is finished */
        alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued);
        if(queued == 0)
            return 0;

        alSourcePlay(player->source);
        if(alGetError() != AL_NO_ERROR)
        {
            fprintf(stderr, "Error restarting playback\n");
            return 0;
        }
    }

    return 1;
}


int main(int argc, char **argv)
{
    StreamPlayer *player;
    int i;

    /* Print out usage if no arguments were specified */
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s [-device <name>] <filenames...>\n", argv[0]);
        return 1;
    }

    argv++; argc--;
    if(InitAL(&argv, &argc) != 0)
        return 1;

    player = NewPlayer();

    /* Play each file listed on the command line */
    for(i = 0;i < argc;i++)
    {
        const char *namepart;

        if(!OpenPlayerFile(player, argv[i]))
            continue;

        /* Get the name portion, without the path, for display. */
        namepart = strrchr(argv[i], '/');
        if(namepart || (namepart=strrchr(argv[i], '\\')))
            namepart++;
        else
            namepart = argv[i];

        printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format),
            player->sfinfo.samplerate);
        fflush(stdout);

        if(!StartPlayer(player))
        {
            ClosePlayerFile(player);
            continue;
        }

        while(UpdatePlayer(player))
            al_nssleep(10000000);

        /* All done with this file. Close it and go to the next */
        ClosePlayerFile(player);
    }
    printf("Done.\n");

    /* All files done. Delete the player, and close down OpenAL */
    DeletePlayer(player);
    player = NULL;

    CloseAL();

    return 0;
}