-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcircular_buffer.cpp
More file actions
87 lines (74 loc) · 1.95 KB
/
Copy pathcircular_buffer.cpp
File metadata and controls
87 lines (74 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/****************************************************************************/
// Original author: kode54 //
/****************************************************************************/
#include "circular_buffer.h"
#include <algorithm>
auto constexpr silence_threshold = 8;
CircularBuffer::CircularBuffer(unsigned int p_size) :
readptr(0), writeptr(0), size(p_size), used(0)
{
buffer.reserve(p_size);
}
unsigned CircularBuffer::data_available() noexcept
{
return used;
}
unsigned CircularBuffer::free_space() noexcept
{
return size - used;
}
bool CircularBuffer::write(const int16_t* src, unsigned int count)
{
if (count > free_space()) {
return false;
}
while (count) {
unsigned delta = size - writeptr;
if (delta > count) {
delta = count;
}
std::copy(src, src + delta, buffer.begin() + writeptr);
used += delta;
writeptr = (writeptr + delta) % size;
src += delta;
count -= delta;
}
return true;
}
unsigned CircularBuffer::read(int16_t* dst, unsigned int count)
{
unsigned done = 0;
for (;;) {
unsigned delta = size - readptr;
if (delta > used) delta = used;
if (delta > count) delta = count;
if (!delta) break;
std::copy(buffer.begin() + readptr, buffer.begin() + readptr + delta, dst);
dst += delta;
done += delta;
readptr = (readptr + delta) % size;
count -= delta;
used -= delta;
}
return done;
}
void CircularBuffer::reset() noexcept
{
readptr = writeptr = used = 0;
}
void CircularBuffer::resize(unsigned int p_size)
{
size = p_size;
buffer.reserve(p_size);
reset();
}
bool CircularBuffer::test_silence() const noexcept
{
int16_t* begin = (int16_t*)&buffer[0];
int16_t first = *begin;
*begin = silence_threshold * 2;
int16_t* p = begin + size;
while ((unsigned int)(*--p + silence_threshold) <= (unsigned int)silence_threshold * 2) {}
*begin = first;
return p == begin && ((unsigned int)(first + silence_threshold) <= (unsigned int)silence_threshold * 2);
}