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 
16 namespace yarp {
17 namespace dev {
18 
19 
20 template <typename SAMPLE>
22 {
23  std::string name;
25  size_t start;
26  size_t end;
27  SAMPLE *elems;
28 
29  public:
30  bool isFull()
31  {
32  return (end + 1) % maxsize.size == start;
33  }
34 
35  const SAMPLE* getRawData()
36  {
37  return elems;
38  }
39 
40  bool isEmpty()
41  {
42  return end == start;
43  }
44 
45  void write(SAMPLE elem)
46  {
47  elems[end] = elem;
48  end = (end + 1) % maxsize.size;
49  if (end == start)
50  {
51  printf ("ERROR: %s buffer overrun!\n", name.c_str());
52  start = (start + 1) % maxsize.size; // full, overwrite
53  }
54  }
55 
57  {
58  size_t i;
59  if (end > start) {
60  i = end-start;
61  } else if (end == start) {
62  i = 0;
63  } else {
64  i = maxsize.size - start + end;
65  }
66  return AudioBufferSize(i/maxsize.m_channels, maxsize.m_channels, sizeof(SAMPLE));
67  }
68 
70  {
71  if (end == start)
72  {
73  printf ("ERROR: %s buffer underrun!\n", name.c_str());
74  }
75  SAMPLE elem = elems[start];
76  start = (start + 1) % maxsize.size;
77  return elem;
78  }
79 
81  {
82  return maxsize;
83  }
84 
85  void clear()
86  {
87  start = 0;
88  end = 0;
89  }
90 
91  CircularAudioBuffer(std::string buffer_name, yarp::dev::AudioBufferSize bufferSize) :
92  name{buffer_name},
93  maxsize{bufferSize},
94  start{0},
95  end{0},
96  elems{static_cast<SAMPLE*>(calloc(maxsize.size, sizeof(SAMPLE)))}
97  {
98  static_assert (std::is_same<unsigned char, SAMPLE>::value ||
99  std::is_same<unsigned short int, SAMPLE>::value ||
100  std::is_same<unsigned int, SAMPLE>::value,
101  "CircularAudioBuffer can be specialized only as <unsigned char>, <unsigned short int>, <unsigned int>");
102 
103  yAssert(bufferSize.m_depth == sizeof(SAMPLE));
104 
105  maxsize.size += 1;
106  }
107 
109  {
110  free(elems);
111  }
112 
113 };
114 
118 
119 } // namespace dev
120 } // namespace yarp
121 
122 #endif // YARP_DEV_CIRCULARAUDIOBUFFER_H
#define yAssert(x)
Definition: Log.h:294
short SAMPLE
CircularAudioBuffer(std::string buffer_name, yarp::dev::AudioBufferSize bufferSize)
yarp::dev::AudioBufferSize getMaxSize()
yarp::dev::CircularAudioBuffer< unsigned char > CircularAudioBuffer_8t
yarp::dev::CircularAudioBuffer< unsigned int > CircularAudioBuffer_32t
yarp::dev::CircularAudioBuffer< unsigned short int > CircularAudioBuffer_16t
The main, catch-all namespace for YARP.
Definition: dirs.h:16