1/***
2  This file is part of PulseAudio.
3
4  PulseAudio is free software; you can redistribute it and/or modify
5  it under the terms of the GNU Lesser General Public License as
6  published by the Free Software Foundation; either version 2.1 of the
7  License, or (at your option) any later version.
8
9  PulseAudio is distributed in the hope that it will be useful, but
10  WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  Lesser General Public License for more details.
13
14  You should have received a copy of the GNU Lesser General Public
15  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
16***/
17
18#ifdef HAVE_CONFIG_H
19#include <config.h>
20#endif
21
22#include <unistd.h>
23#include <sys/types.h>
24#include <errno.h>
25#include <string.h>
26#include <stdlib.h>
27#include <time.h>
28
29#include <pulsecore/core-util.h>
30#include <pulsecore/mcalign.h>
31
32/* A simple program for testing pa_mcalign */
33
34int main(int argc, char *argv[]) {
35    pa_mempool *p;
36    pa_mcalign *a;
37    pa_memchunk c;
38
39    p = pa_mempool_new(PA_MEM_TYPE_PRIVATE, 0, true);
40
41    a = pa_mcalign_new(11);
42
43    pa_memchunk_reset(&c);
44
45    srand((unsigned) time(NULL));
46
47    for (;;) {
48        ssize_t r;
49        size_t l;
50
51        if (!c.memblock) {
52            c.memblock = pa_memblock_new(p, 2048);
53            c.index = c.length = 0;
54        }
55
56        pa_assert(c.index < pa_memblock_get_length(c.memblock));
57
58        l = pa_memblock_get_length(c.memblock) - c.index;
59
60        l = l <= 1 ? l : (size_t) rand() % (l-1) +1;
61
62        p = pa_memblock_acquire(c.memblock);
63
64        if ((r = read(STDIN_FILENO, (uint8_t*) p + c.index, l)) <= 0) {
65            pa_memblock_release(c.memblock);
66            fprintf(stderr, "read() failed: %s\n", r < 0 ? strerror(errno) : "EOF");
67            break;
68        }
69
70        pa_memblock_release(c.memblock);
71
72        c.length = (size_t) r;
73        pa_mcalign_push(a, &c);
74        fprintf(stderr, "Read %zd bytes\n", r);
75
76        c.index += (size_t) r;
77
78        if (c.index >= pa_memblock_get_length(c.memblock)) {
79            pa_memblock_unref(c.memblock);
80            pa_memchunk_reset(&c);
81        }
82
83        for (;;) {
84            pa_memchunk t;
85
86            if (pa_mcalign_pop(a, &t) < 0)
87                break;
88
89            p = pa_memblock_acquire(t.memblock);
90            pa_loop_write(STDOUT_FILENO, (uint8_t*) p + t.index, t.length, NULL);
91            pa_memblock_release(t.memblock);
92            fprintf(stderr, "Wrote %lu bytes.\n", (unsigned long) t.length);
93
94            pa_memblock_unref(t.memblock);
95        }
96    }
97
98    pa_mcalign_free(a);
99
100    if (c.memblock)
101        pa_memblock_unref(c.memblock);
102
103    pa_mempool_unref(p);
104
105    return 0;
106}
107