summaryrefslogtreecommitdiffstats
path: root/src/synth.c
blob: a482875a275f35b37d7dd589d98b983fbe1e1652 (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
#include <stdlib.h>

#include <xas/synth.h>

static ssize_t synth_fill(xas_synth *synth,
                          int16_t *samples,
                          size_t count,
                          xas_audio_stream *stream) {
    size_t i;

    for (i=0; i<count; i++) {
        samples[i] = synth->sample(synth, synth->ctx);
    }

    return count;
}

static void synth_cleanup(xas_synth *synth, xas_audio_stream *stream) {
    if (synth->cleanup) {
        synth->cleanup(synth, synth->ctx);
    }

    free(synth);
}

xas_audio_stream *xas_synth_new(size_t sample_size,
                                    size_t sample_rate,
                                    size_t buffer_size,
                                    xas_synth_callback_sample  sample,
                                    xas_synth_callback_cleanup cleanup,
                                    void *ctx) {
    xas_audio_stream *stream;
    xas_synth *synth;

    if ((synth = malloc(sizeof(*synth))) == NULL) {
        goto error_malloc_synth;
    }

    synth->sample_size = sample_size;
    synth->sample_rate = sample_rate;
    synth->sample      = sample;
    synth->cleanup     = cleanup;
    synth->ctx         = ctx;

    if ((stream = xas_audio_stream_new_source((xas_audio_fill)synth_fill,
                                                (xas_audio_cleanup)synth_cleanup,
                                                synth,
                                                sample_size,
                                                sample_rate,
                                                XAS_AUDIO_STREAM_MONO,
                                                buffer_size)) == NULL) {
        goto error_audio_stream_new_source;
    }

    return stream;

error_audio_stream_new_source:
    free(synth);

error_malloc_synth:
    return NULL;
}