2 Copyright 2005 Mark Calderbank
4 This file is part of VOMP.
6 VOMP is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 VOMP is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with VOMP; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 void Stream::shutdown()
41 int Stream::init(int bufsize)
43 outbuf = (UCHAR*) malloc(bufsize);
44 if (!outbuf) return 0;
46 bufferHead = bufferTail = 0;
53 bufferHead = bufferTail = 0;
56 int Stream::put(UCHAR* inbuf, int len)
60 int localTail = bufferTail;
61 if (localTail == 0) localTail = bufferSize;
62 if (len == 0) return ret;
64 freespace = localTail - bufferHead - 1;
65 if (freespace < 0) freespace += bufferSize;
66 if (len > freespace) return ret;
68 if (bufferHead >= localTail)
70 // We have free rein to the end of the buffer
71 if (len < (bufferSize - bufferHead))
73 // We won't reach the end of the buffer.
74 memcpy(outbuf + bufferHead, inbuf, len);
76 ret += len; return ret;
79 // We'll reach the end of the buffer and loop round.
80 memcpy(outbuf + bufferHead, inbuf, (bufferSize - bufferHead));
81 inbuf += (bufferSize - bufferHead);
82 ret += (bufferSize - bufferHead);
83 len -= (bufferSize - bufferHead);
85 if (len == 0) return ret;
89 if (localTail - bufferHead == 1) return ret; // Full
91 // We can advance the head up to the tail
92 // If we reach it, we are full.
93 if (len < (localTail - bufferHead - 1))
95 // We'll fall short of the tail.
96 memcpy(outbuf + bufferHead, inbuf, len);
98 ret += len; return ret;
101 // We'll hit the tail.
102 memcpy(outbuf + bufferHead, inbuf, (localTail - bufferHead - 1));
103 ret += (localTail - bufferHead - 1);
104 bufferHead = localTail - 1;
109 int Stream::drain(int fd)
112 int localHead = bufferHead;
115 if (localHead < bufferTail)
117 // Drain to the end of the buffer
118 written = write(fd, outbuf + bufferTail, (bufferSize - bufferTail));
119 if (written < 0) return ret;
121 if (written == (bufferSize - bufferTail))
125 bufferTail += written;
130 if (localHead == bufferTail) return ret; // Empty
132 written = write(fd, outbuf + bufferTail, (localHead - bufferTail));
133 if (written < 0) return ret;
135 bufferTail += written;