YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
CircularAudioBuffer.h
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2023-2023 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=nullptr;
27
28 public:
29 bool isFull()
30 {
31 return (end + 1) % maxsize.getBufferElements() == 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.getBufferElements();
48 if (end == start)
49 {
50 printf ("ERROR: %s buffer overrun!\n", name.c_str());
51 start = (start + 1) % maxsize.getBufferElements(); // 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.getBufferElements() - start + end;
64 }
65 return yarp::sig::AudioBufferSize(i/maxsize.getChannels(), maxsize.getChannels(), 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.getBufferElements();
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::sig::AudioBufferSize bufferSize) :
91 name{buffer_name},
92 maxsize{bufferSize},
93 start{0},
94 end{0},
95 elems{static_cast<SAMPLE*>(calloc(maxsize.getBufferElements(), 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.getDepth() == sizeof(SAMPLE));
103 }
104
106 {
107 if (elems)
108 {
109 free(elems);
110 elems =nullptr;
111 }
112 }
113
114};
115
119
120} // namespace yarp::dev
121
122#endif // YARP_DEV_CIRCULARAUDIOBUFFER_H
#define yAssert(x)
Definition Log.h:388
yarp::sig::AudioBufferSize size()
yarp::sig::AudioBufferSize getMaxSize()
CircularAudioBuffer(std::string buffer_name, yarp::sig::AudioBufferSize bufferSize)
A mini-server for performing network communication in the background.
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