1 /*
2     Copyright (C) 2004 Florian Schmidt
3 
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU Lesser General Public License as published by
6     the Free Software Foundation; either version 2.1 of the License, or
7     (at your option) any later version.
8 
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU Lesser General Public License for more details.
13 
14     You should have received a copy of the GNU Lesser General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18 
19 #include "convolve.h"
20 #include <stdlib.h>
21 #include "ringbuffer.h"
22 
ringbuffer_init(ringbuffer_t * rb,unsigned int elements)23 void ringbuffer_init(ringbuffer_t *rb, unsigned int elements)
24 {
25 	rb->buffer = (rb_data_t*)malloc(elements*sizeof(rb_data_t));
26 	rb->data_count = 0;
27 	rb->read_index = 0;
28 	rb->write_index = 0;
29 	rb->size = elements;
30 }
31 
ringbuffer_uninit(ringbuffer_t * rb)32 void ringbuffer_uninit(ringbuffer_t*rb)
33 {
34 	free(rb->buffer);
35 }
36 
ringbuffer_get_read_avail(ringbuffer_t * rb)37 int  ringbuffer_get_read_avail(ringbuffer_t *rb)
38 {
39 	return rb->data_count;
40 }
41 
ringbuffer_get_write_space(ringbuffer_t * rb)42 int  ringbuffer_get_write_space(ringbuffer_t *rb)
43 {
44 	return rb->size - ringbuffer_get_read_avail(rb);
45 }
46 
47 // copies the data over to the ringbuffer and advances the write pointer
48 // and increases the data_count.
ringbuffer_write(ringbuffer_t * rb,rb_data_t * data,unsigned int count)49 void ringbuffer_write(ringbuffer_t *rb, rb_data_t *data, unsigned int count)
50 {
51 	unsigned int index;
52 
53 	for (index = 0; index < count; ++index) {
54 		rb->buffer[rb->write_index] = *(data + index);
55 		++(rb->data_count);
56 		rb->write_index++;
57 		rb->write_index %= rb->size - 1;
58 	}
59 }
60 
61 // returns a pointer into the ringbuffer and increases the read_ptr and
62 // decreases the data_count.
ringbuffer_read(ringbuffer_t * rb,rb_data_t * target,unsigned int count)63 void ringbuffer_read(ringbuffer_t *rb, rb_data_t *target, unsigned int count)
64 {
65 	unsigned int tmp_index, index;
66 
67 	for (index = 0; index < count; ++index) {
68 		target[index] = rb->buffer[rb->read_index];
69 		--(rb->data_count);
70 		++(rb->read_index);
71 		rb->read_index %= rb->size - 1;
72 	}
73 }
74