summaryrefslogtreecommitdiffstats
path: root/src/bbuffer.c
blob: c0aff259325261b0d3ba0fc2f1a553c5260ed404 (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
/***
  This file is part of libsydney.

  Copyright 2007-2008 Lennart Poettering

  libsydney is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation, either version 2.1 of the
  License, or (at your option) any later version.

  libsydney 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
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with libsydney. If not, see
  <http://www.gnu.org/licenses/>.
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <sys/types.h>

#include "bbuffer.h"
#include "sydney.h"
#include "malloc.h"
#include "macro.h"

int sa_bbuffer_init(sa_bbuffer_t *b, unsigned nchannels, size_t sample_size) {
    sa_assert(b);
    sa_assert(nchannels > 0);
    sa_assert(sample_size > 0);

    b->nchannels = nchannels;
    b->sample_size = sample_size;

    if (!(b->data = sa_new0(void *, nchannels))) {
        b->size = NULL;
        return SA_ERROR_OOM;
    }

    if (!(b->size = sa_new0(size_t, nchannels))) {
        sa_free(b->data);
        b->data = NULL;
        return SA_ERROR_OOM;
    }

    return SA_SUCCESS;
}

void sa_bbuffer_done(sa_bbuffer_t *b) {
    unsigned i;
    sa_assert(b);

    if (b->data) {
        for (i = 0; i < b->nchannels; i++)
            sa_free(b->data[i]);

        sa_free(b->data);
    }

    sa_free(b->size);

    b->data = NULL;
    b->size = NULL;
}

void* sa_bbuffer_get(sa_bbuffer_t *b, unsigned channel, size_t size, sa_bool_t interleave) {
    sa_assert(b);
    sa_assert(channel < b->nchannels);
    sa_assert(size > 0);

    if (interleave) {

        if (!b->data[0] || size * b->nchannels > b->size[0]) {
            sa_free(b->data[0]);
            b->size[0] = size * b->nchannels;

            if (!(b->data[0] = sa_malloc(b->size[0])))
                return NULL;
        }

        return (uint8_t*) b->data[0] + (b->sample_size * channel);

    } else {

        if (!b->data[channel] || size > b->size[channel]) {

            sa_free(b->data[channel]);
            b->size[channel] = size;

            if (!(b->data[channel] = sa_malloc(size)))
                return NULL;
        }

        return b->data[channel];
    }
}