-
Notifications
You must be signed in to change notification settings - Fork 1
/
memring.h
146 lines (109 loc) · 2.94 KB
/
memring.h
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#ifndef MEMRING_H
#define MEMRING_H
#include <stddef.h>
extern "C" {
#include <libavutil/avutil.h>
}
#include "avexception.h"
template<typename T> class MemRing {
public:
explicit MemRing(size_t size):
_buff(0), _w_ptr(0), _r_ptr(0),
_size(0), _size_mask(0)
{
if (!size)
throw AVException("memRing: wat?");
size += 1; // reserve at least 1 element for internal purposes
size_t power_of_two = 1;
for (; (1u << power_of_two) < size; power_of_two++) ;
_size = _size_mask = 1 << power_of_two;
_size_mask -= 1;
_buff = reinterpret_cast<T*>(av_malloc(_size * sizeof(T)));
if (!_buff)
throw AVException("memRing: cannot allocate memory");
}
~MemRing() {
if (_buff)
av_free(_buff);
}
size_t readSpace()
{
size_t w, r;
w = _w_ptr;
r = _r_ptr;
if (w > r) {
return w - r;
} else {
return (w - r + _size) & _size_mask;
}
}
size_t writeSpace()
{
size_t w, r;
w = _w_ptr;
r = _r_ptr;
if (w > r) {
return ((r - w + _size) & _size_mask) - 1;
} else if (w < r) {
return (r - w) - 1;
} else {
return _size - 1;
}
}
inline void reset() { _r_ptr = _w_ptr = 0; }
size_t pull(T* data, size_t len)
{
size_t read_space = readSpace();
if (!read_space)
return 0;
size_t to_read = len > read_space ? read_space : len;
size_t n0, n1, n2, r_ptr = _r_ptr;
n0 = r_ptr + to_read;
if (n0 > _size) {
n1 = _size - r_ptr;
n2 = n0 & _size_mask;
} else {
n1 = to_read;
n2 = 0;
}
memcpy (data, _buff + r_ptr, n1 * sizeof(T));
r_ptr = (r_ptr + n1) & _size_mask;
if (n2) {
memcpy (data + n1, &(_buff[r_ptr]), n2 * sizeof(T));
r_ptr = (r_ptr + n2) & _size_mask;
}
_r_ptr = r_ptr;
return to_read;
}
size_t push(T* data, size_t len)
{
size_t write_space = writeSpace();
if (!write_space)
return 0;
size_t to_write;
size_t n0, n1, n2, w_ptr = _w_ptr;
to_write = len > write_space ? write_space : len;
n0 = w_ptr + to_write;
if (n0 > _size) {
n1 = _size - w_ptr;
n2 = n0 & _size_mask;
} else {
n1 = to_write;
n2 = 0;
}
memcpy(_buff + w_ptr, data, n1 * sizeof(T));
w_ptr = (w_ptr + n1) & _size_mask;
if (n2) {
memcpy(_buff + w_ptr, data + n1, n2 * sizeof(T));
w_ptr = (w_ptr + n2) & _size_mask;
}
_w_ptr = w_ptr;
return to_write;
}
private:
T* _buff;
volatile size_t _w_ptr;
volatile size_t _r_ptr;
size_t _size, _size_mask;
};
#endif // MEMRING_H