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 1;
46 bufferHead = bufferTail = 0;
53 bufferHead = bufferTail = 0;
56 int Stream::put(UCHAR* inbuf, int len)
59 int localTail = bufferTail;
60 if (localTail == 0) localTail = bufferSize;
61 if (len == 0) return ret;
63 if (bufferHead >= localTail)
65 // We have free rein to the end of the buffer
66 if (len < (bufferSize - bufferHead))
68 // We won't reach the end of the buffer.
69 memcpy(outbuf + bufferHead, inbuf, len);
71 ret += len; return ret;
74 // We'll reach the end of the buffer and loop round.
75 memcpy(outbuf + bufferHead, inbuf, (bufferSize - bufferHead));
76 inbuf += (bufferSize - bufferHead);
77 ret += (bufferSize - bufferHead);
78 len -= (bufferSize - bufferHead);
80 if (len == 0) return ret;
84 if (localTail - bufferHead == 1) return ret; // Full
86 // We can advance the head up to the tail
87 // If we reach it, we are full.
88 if (len < (localTail - bufferHead - 1))
90 // We'll fall short of the tail.
91 memcpy(outbuf + bufferHead, inbuf, len);
93 ret += len; return ret;
96 // We'll hit the tail.
97 memcpy(outbuf + bufferHead, inbuf, (localTail - bufferHead - 1));
98 ret += (localTail - bufferHead - 1);
99 bufferHead = localTail - 1;
104 int Stream::drain(int fd)
107 int localHead = bufferHead;
110 if (localHead < bufferTail)
112 // Drain to the end of the buffer
113 written = write(fd, outbuf + bufferTail, (bufferSize - bufferTail));
114 if (written < 0) return ret;
116 if (written == (bufferSize - bufferTail))
120 bufferTail += written;
125 if (localHead == bufferTail) return ret; // Empty
127 written = write(fd, outbuf + bufferTail, (localHead - bufferTail));
128 if (written < 0) return ret;
130 bufferTail += written;