summaryrefslogtreecommitdiffstats
path: root/src/synth.c
blob: d96c1b50e94f30193fe8519f242fc2e4888f2e90 (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
#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(xas_synth_callback_sample  sample,
                                    xas_synth_callback_cleanup cleanup,
                                    xas_audio_format format,
                                    size_t buffer_size,
                                    void *ctx) {
    xas_audio_stream *stream;
    xas_synth *synth;

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

    synth->format.channels    = XAS_AUDIO_MONO;
    synth->format.sample_size = format.sample_size;
    synth->format.sample_rate = format.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->format,
                                                buffer_size,
                                                synth)) == NULL) {
        goto error_audio_stream_new_source;
    }

    return stream;

error_audio_stream_new_source:
    free(synth);

error_malloc_synth:
    return NULL;
}