2 This file is part of CaptureMJPEG.
4 CaptureMJPEG is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 CaptureMJPEG 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 Public License for more details.
14 You should have received a copy of the GNU Lesser Public License
15 along with CaptureMJPEG. If not, see <http://www.gnu.org/licenses/>.
17 Copyright (c) 2008 - Alessio Caiazza, Cosimo Cecchi
19 package it
.lilik
.capturemjpeg
;
21 import java
.io
.ByteArrayInputStream
;
24 * A circular buffer of {@link java.io.ByteArrayInputStream}
26 * @author Alessio Caiazza
27 * @author Cosimo Cecchi
30 class CircularBuffer
{
33 private ByteArrayInputStream buffer
[];
34 /** last item in <code>CircularBuffer</code> */
36 /** first valid item in <code>CircularBuffer</code> */
38 /** size of <code>CircularBuffer</code> */
41 private boolean empty
;
44 static final int DEFAULT_SIZE
= 5;
47 * Creates a new <code>CircularBuffer</code> with
49 * @param size the size of the buffer.
51 public CircularBuffer(int size
) {
56 this.buffer
= new ByteArrayInputStream
[size
];
60 * Creates a <code>CircularBuffer</code> with
62 * {@link it.lilik.capturemjpeg.CircularBuffer#DEFAULT_SIZE}
64 public CircularBuffer() {
65 this(CircularBuffer
.DEFAULT_SIZE
);
69 * Adds a an element to the <code>CircularBuffer</code>
71 * @param data the new element
73 public synchronized void push(ByteArrayInputStream data
) {
74 buffer
[this.lastIdx
] = data
;
75 if( this.lastIdx
== this.firstIdx
&& !this.empty
) {
76 //we have overwritten an element
77 //System.out.print("overwrite ");
79 this.firstIdx
%= this.size
;
84 this.lastIdx
%= this.size
;
85 //System.out.println("Pushed (" + getLength() + ")");
89 * Returns the number of elements into the buffer
90 * @return the number of valid elements
92 public synchronized int getLength() {
95 int len
= this.lastIdx
- this.firstIdx
;
97 len
= this.size
+ len
;
98 return len
== 0 ?
this.size
-1 : len
;
103 * Gets the first available element.
105 * @return the first element
106 * @throws IndexOutOfBoundsExceptions
108 public synchronized ByteArrayInputStream
pop() {
110 //TODO:change Exception type
111 throw new IndexOutOfBoundsException("Empty buffer");
113 ByteArrayInputStream res
= buffer
[this.firstIdx
];
114 buffer
[this.firstIdx
] = null;
116 this.firstIdx
%= this.size
;
117 if (this.firstIdx
== this.lastIdx
)
119 //System.out.println("Popped (" + getLength() + ")");
124 * Returns the status of the buffer.
125 * @return <code>true</code> if empty, otherwise <code>false</code>
127 public synchronized boolean isEmpty() {
132 * Returns the size of the buffer.
134 * @return the size of the buffer.
136 public int getSize() {