YARP
Yet Another Robot Platform
CircularAudioBuffer.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2006-2020 Istituto Italiano di Tecnologia (IIT)
3  * All rights reserved.
4  *
5  * This software may be modified and distributed under the terms of the
6  * BSD-3-Clause license. See the accompanying LICENSE file for details.
7  */
8 
9 #ifndef YARP_DEV_CIRCULARAUDIOBUFFER_H
10 #define YARP_DEV_CIRCULARAUDIOBUFFER_H
11 
12 #include <yarp/os/Log.h>
14 #include <cstdio>
15 #include <string>
16 
17 #include <yarp/os/LogStream.h>
18 
19 namespace yarp {
20 namespace dev {
21 
22 
23 template <typename SAMPLE>
25 {
26  std::string name;
28  size_t start;
29  size_t end;
30  SAMPLE *elems;
31 
32  public:
33  bool isFull()
34  {
35  return (end + 1) % maxsize.size == start;
36  }
37 
38  const SAMPLE* getRawData()
39  {
40  return elems;
41  }
42 
43  bool isEmpty()
44  {
45  return end == start;
46  }
47 
48  void write(SAMPLE elem)
49  {
50  elems[end] = elem;
51  end = (end + 1) % maxsize.size;
52  if (end == start)
53  {
54  printf ("ERROR: %s buffer overrun!\n", name.c_str());
55  start = (start + 1) % maxsize.size; // full, overwrite
56  }
57  }
58 
60  {
61  size_t i;
62  if (end>start)
63  i = end-start;
64  else if (end==start)
65  i = 0;
66  else
67  i = maxsize.size - start + end;
68  return AudioBufferSize(i/maxsize.m_channels, maxsize.m_channels, sizeof(SAMPLE));
69  }
70 
72  {
73  if (end == start)
74  {
75  printf ("ERROR: %s buffer underrun!\n", name.c_str());
76  }
77  SAMPLE elem = elems[start];
78  start = (start + 1) % maxsize.size;
79  return elem;
80  }
81 
83  {
84  return maxsize;
85  }
86 
87  void clear()
88  {
89  start = 0;
90  end = 0;
91  }
92 
93  CircularAudioBuffer(std::string buffer_name, yarp::dev::AudioBufferSize bufferSize) :
94  name{buffer_name},
95  maxsize{bufferSize},
96  start{0},
97  end{0},
98  elems{static_cast<SAMPLE*>(calloc(maxsize.size, sizeof(SAMPLE)))}
99  {
100  static_assert (std::is_same<unsigned char, SAMPLE>::value ||
101  std::is_same<unsigned short int, SAMPLE>::value ||
102  std::is_same<unsigned int, SAMPLE>::value,
103  "CircularAudioBuffer can be specialized only as <unsigned char>, <unsigned short int>, <unsigned int>");
104 
105  yAssert(bufferSize.m_depth == sizeof(SAMPLE));
106 
107  maxsize.size += 1;
108  }
109 
111  {
112  free(elems);
113  }
114 
115 };
116 
120 
121 } // namespace dev
122 } // namespace yarp
123 
124 #endif // YARP_DEV_CIRCULARAUDIOBUFFER_H
#define yAssert(x)
Definition: Log.h:297
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: environment.h:18