YARP
Yet Another Robot Platform
CircularAudioBuffer.h
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
6#ifndef YARP_DEV_CIRCULARAUDIOBUFFER_H
7#define YARP_DEV_CIRCULARAUDIOBUFFER_H
8
9#include <yarp/os/Log.h>
11#include <cstdio>
12#include <string>
13
14#include <yarp/os/LogStream.h>
15
16namespace yarp::dev {
17
18
19template <typename SAMPLE>
21{
22 std::string name;
24 size_t start;
25 size_t end;
26 SAMPLE *elems;
27
28 public:
29 bool isFull()
30 {
31 return (end + 1) % maxsize.size == start;
32 }
33
35 {
36 return elems;
37 }
38
39 bool isEmpty()
40 {
41 return end == start;
42 }
43
44 void write(SAMPLE elem)
45 {
46 elems[end] = elem;
47 end = (end + 1) % maxsize.size;
48 if (end == start)
49 {
50 printf ("ERROR: %s buffer overrun!\n", name.c_str());
51 start = (start + 1) % maxsize.size; // full, overwrite
52 }
53 }
54
56 {
57 size_t i;
58 if (end > start) {
59 i = end-start;
60 } else if (end == start) {
61 i = 0;
62 } else {
63 i = maxsize.size - start + end;
64 }
65 return AudioBufferSize(i/maxsize.m_channels, maxsize.m_channels, sizeof(SAMPLE));
66 }
67
69 {
70 if (end == start)
71 {
72 printf ("ERROR: %s buffer underrun!\n", name.c_str());
73 }
74 SAMPLE elem = elems[start];
75 start = (start + 1) % maxsize.size;
76 return elem;
77 }
78
80 {
81 return maxsize;
82 }
83
84 void clear()
85 {
86 start = 0;
87 end = 0;
88 }
89
90 CircularAudioBuffer(std::string buffer_name, yarp::dev::AudioBufferSize bufferSize) :
91 name{buffer_name},
92 maxsize{bufferSize},
93 start{0},
94 end{0},
95 elems{static_cast<SAMPLE*>(calloc(maxsize.size, sizeof(SAMPLE)))}
96 {
97 static_assert (std::is_same<unsigned char, SAMPLE>::value ||
98 std::is_same<unsigned short int, SAMPLE>::value ||
99 std::is_same<unsigned int, SAMPLE>::value,
100 "CircularAudioBuffer can be specialized only as <unsigned char>, <unsigned short int>, <unsigned int>");
101
102 yAssert(bufferSize.m_depth == sizeof(SAMPLE));
103
104 maxsize.size += 1;
105 }
106
108 {
109 free(elems);
110 }
111
112};
113
117
118} // namespace yarp::dev
119
120#endif // YARP_DEV_CIRCULARAUDIOBUFFER_H
#define yAssert(x)
Definition: Log.h:383
short SAMPLE
CircularAudioBuffer(std::string buffer_name, yarp::dev::AudioBufferSize bufferSize)
yarp::dev::AudioBufferSize getMaxSize()
For streams capable of holding different kinds of content, check what they actually have.
yarp::dev::CircularAudioBuffer< unsigned char > CircularAudioBuffer_8t
yarp::dev::CircularAudioBuffer< unsigned int > CircularAudioBuffer_32t
yarp::dev::CircularAudioBuffer< unsigned short int > CircularAudioBuffer_16t