1/*
2 * Copyright (c) 1999-2000, Image Power, Inc. and the University of
3 *   British Columbia.
4 * Copyright (c) 2001-2002 Michael David Adams.
5 * All rights reserved.
6 */
7
8/* __START_OF_JASPER_LICENSE__
9 *
10 * JasPer Software License
11 *
12 * IMAGE POWER JPEG-2000 PUBLIC LICENSE
13 * ************************************
14 *
15 * GRANT:
16 *
17 * Permission is hereby granted, free of charge, to any person (the "User")
18 * obtaining a copy of this software and associated documentation, to deal
19 * in the JasPer Software without restriction, including without limitation
20 * the right to use, copy, modify, merge, publish, distribute, sublicense,
21 * and/or sell copies of the JasPer Software (in source and binary forms),
22 * and to permit persons to whom the JasPer Software is furnished to do so,
23 * provided further that the License Conditions below are met.
24 *
25 * License Conditions
26 * ******************
27 *
28 * A.  Redistributions of source code must retain the above copyright notice,
29 * and this list of conditions, and the following disclaimer.
30 *
31 * B.  Redistributions in binary form must reproduce the above copyright
32 * notice, and this list of conditions, and the following disclaimer in
33 * the documentation and/or other materials provided with the distribution.
34 *
35 * C.  Neither the name of Image Power, Inc. nor any other contributor
36 * (including, but not limited to, the University of British Columbia and
37 * Michael David Adams) may be used to endorse or promote products derived
38 * from this software without specific prior written permission.
39 *
40 * D.  User agrees that it shall not commence any action against Image Power,
41 * Inc., the University of British Columbia, Michael David Adams, or any
42 * other contributors (collectively "Licensors") for infringement of any
43 * intellectual property rights ("IPR") held by the User in respect of any
44 * technology that User owns or has a right to license or sublicense and
45 * which is an element required in order to claim compliance with ISO/IEC
46 * 15444-1 (i.e., JPEG-2000 Part 1).  "IPR" means all intellectual property
47 * rights worldwide arising under statutory or common law, and whether
48 * or not perfected, including, without limitation, all (i) patents and
49 * patent applications owned or licensable by User; (ii) rights associated
50 * with works of authorship including copyrights, copyright applications,
51 * copyright registrations, mask work rights, mask work applications,
52 * mask work registrations; (iii) rights relating to the protection of
53 * trade secrets and confidential information; (iv) any right analogous
54 * to those set forth in subsections (i), (ii), or (iii) and any other
55 * proprietary rights relating to intangible property (other than trademark,
56 * trade dress, or service mark rights); and (v) divisions, continuations,
57 * renewals, reissues and extensions of the foregoing (as and to the extent
58 * applicable) now existing, hereafter filed, issued or acquired.
59 *
60 * E.  If User commences an infringement action against any Licensor(s) then
61 * such Licensor(s) shall have the right to terminate User's license and
62 * all sublicenses that have been granted hereunder by User to other parties.
63 *
64 * F.  This software is for use only in hardware or software products that
65 * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
66 * or right to this Software is granted for products that do not comply
67 * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
68 * from the ISO.
69 *
70 * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
71 * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
72 * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
73 * CONTRIBUTORS UNDER THIS LICENSE ON AN ``AS-IS'' BASIS, WITHOUT WARRANTY
74 * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION,
75 * WARRANTIES THAT THE JASPER SOFTWARE IS FREE OF DEFECTS, IS MERCHANTABLE,
76 * IS FIT FOR A PARTICULAR PURPOSE OR IS NON-INFRINGING.  THOSE INTENDING
77 * TO USE THE JASPER SOFTWARE OR MODIFICATIONS THEREOF FOR USE IN HARDWARE
78 * OR SOFTWARE PRODUCTS ARE ADVISED THAT THEIR USE MAY INFRINGE EXISTING
79 * PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER INTELLECTUAL PROPERTY RIGHTS.
80 * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE JASPER SOFTWARE
81 * IS WITH THE USER.  SHOULD ANY PART OF THE JASPER SOFTWARE PROVE DEFECTIVE
82 * IN ANY RESPECT, THE USER (AND NOT THE INITIAL DEVELOPERS, THE UNIVERSITY
83 * OF BRITISH COLUMBIA, IMAGE POWER, INC., MICHAEL DAVID ADAMS, OR ANY
84 * OTHER CONTRIBUTOR) SHALL ASSUME THE COST OF ANY NECESSARY SERVICING,
85 * REPAIR OR CORRECTION.  UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY,
86 * WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE
87 * INITIAL DEVELOPER, THE UNIVERSITY OF BRITISH COLUMBIA, IMAGE POWER, INC.,
88 * MICHAEL DAVID ADAMS, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF THE
89 * JASPER SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO
90 * THE USER OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
91 * CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION,
92 * DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR
93 * MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF
94 * SUCH PARTY HAD BEEN INFORMED, OR OUGHT TO HAVE KNOWN, OF THE POSSIBILITY
95 * OF SUCH DAMAGES.  THE JASPER SOFTWARE AND UNDERLYING TECHNOLOGY ARE NOT
96 * FAULT-TOLERANT AND ARE NOT DESIGNED, MANUFACTURED OR INTENDED FOR USE OR
97 * RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING
98 * FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES,
99 * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT
100 * LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
101 * JASPER SOFTWARE OR UNDERLYING TECHNOLOGY OR PRODUCT COULD LEAD DIRECTLY
102 * TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE
103 * ("HIGH RISK ACTIVITIES").  LICENSOR SPECIFICALLY DISCLAIMS ANY EXPRESS
104 * OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.  USER WILL NOT
105 * KNOWINGLY USE, DISTRIBUTE OR RESELL THE JASPER SOFTWARE OR UNDERLYING
106 * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
107 * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
108 * NOTICE SPECIFIED IN THIS SECTION.
109 *
110 * __END_OF_JASPER_LICENSE__
111 */
112
113/*
114 * Bit Stream Class
115 *
116 * $Id: jpc_bs.c 14449 2005-10-20 12:15:56Z stippi $
117 */
118
119/******************************************************************************\
120* Includes.
121\******************************************************************************/
122
123#include <assert.h>
124#include <stdlib.h>
125#include <stdarg.h>
126
127#include "jasper/jas_malloc.h"
128#include "jasper/jas_math.h"
129#include "jasper/jas_debug.h"
130
131#include "jpc_bs.h"
132
133/******************************************************************************\
134* Local function prototypes.
135\******************************************************************************/
136
137static jpc_bitstream_t *jpc_bitstream_alloc();
138
139/******************************************************************************\
140* Code for opening and closing bit streams.
141\******************************************************************************/
142
143/* Open a bit stream from a stream. */
144jpc_bitstream_t *jpc_bitstream_sopen(jas_stream_t *stream, char *mode)
145{
146	jpc_bitstream_t *bitstream;
147
148	/* Ensure that the open mode is valid. */
149	assert(!strcmp(mode, "r") || !strcmp(mode, "w") || !strcmp(mode, "r+")
150	  || !strcmp(mode, "w+"));
151
152	if (!(bitstream = jpc_bitstream_alloc())) {
153		return 0;
154	}
155
156	/* By default, do not close the underlying (character) stream, upon
157	  the close of the bit stream. */
158	bitstream->flags_ = JPC_BITSTREAM_NOCLOSE;
159
160	bitstream->stream_ = stream;
161	bitstream->openmode_ = (mode[0] == 'w') ? JPC_BITSTREAM_WRITE :
162	  JPC_BITSTREAM_READ;
163
164	/* Mark the data buffer as empty. */
165	bitstream->cnt_ = (bitstream->openmode_ == JPC_BITSTREAM_READ) ? 0 : 8;
166	bitstream->buf_ = 0;
167
168	return bitstream;
169}
170
171/* Close a bit stream. */
172int jpc_bitstream_close(jpc_bitstream_t *bitstream)
173{
174	int ret = 0;
175
176	/* Align to the next byte boundary while considering the effects of
177	  bit stuffing. */
178	if (jpc_bitstream_align(bitstream)) {
179		ret = -1;
180	}
181
182	/* If necessary, close the underlying (character) stream. */
183	if (!(bitstream->flags_ & JPC_BITSTREAM_NOCLOSE) && bitstream->stream_) {
184		if (jas_stream_close(bitstream->stream_)) {
185			ret = -1;
186		}
187		bitstream->stream_ = 0;
188	}
189
190	jas_free(bitstream);
191	return ret;
192}
193
194/* Allocate a new bit stream. */
195static jpc_bitstream_t *jpc_bitstream_alloc()
196{
197	jpc_bitstream_t *bitstream;
198
199	/* Allocate memory for the new bit stream object. */
200	if (!(bitstream = jas_malloc(sizeof(jpc_bitstream_t)))) {
201		return 0;
202	}
203	/* Initialize all of the data members. */
204	bitstream->stream_ = 0;
205	bitstream->cnt_ = 0;
206	bitstream->flags_ = 0;
207	bitstream->openmode_ = 0;
208
209	return bitstream;
210}
211
212/******************************************************************************\
213* Code for reading/writing from/to bit streams.
214\******************************************************************************/
215
216/* Get a bit from a bit stream. */
217int jpc_bitstream_getbit_func(jpc_bitstream_t *bitstream)
218{
219	int ret;
220	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func(%p)\n", bitstream));
221	ret = jpc_bitstream_getbit_macro(bitstream);
222	JAS_DBGLOG(1000, ("jpc_bitstream_getbit_func -> %d\n", ret));
223	return ret;
224}
225
226/* Put a bit to a bit stream. */
227int jpc_bitstream_putbit_func(jpc_bitstream_t *bitstream, int b)
228{
229	int ret;
230	JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func(%p, %d)\n", bitstream, b));
231	ret = jpc_bitstream_putbit_macro(bitstream, b);
232	JAS_DBGLOG(1000, ("jpc_bitstream_putbit_func() -> %d\n", ret));
233	return ret;
234}
235
236/* Get one or more bits from a bit stream. */
237long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n)
238{
239	long v;
240	int u;
241
242	/* We can reliably get at most 31 bits since ISO/IEC 9899 only
243	  guarantees that a long can represent values up to 2^31-1. */
244	assert(n >= 0 && n < 32);
245
246	/* Get the number of bits requested from the specified bit stream. */
247	v = 0;
248	while (--n >= 0) {
249		if ((u = jpc_bitstream_getbit(bitstream)) < 0) {
250			return -1;
251		}
252		v = (v << 1) | u;
253	}
254	return v;
255}
256
257/* Put one or more bits to a bit stream. */
258int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
259{
260	int m;
261
262	/* We can reliably put at most 31 bits since ISO/IEC 9899 only
263	  guarantees that a long can represent values up to 2^31-1. */
264	assert(n >= 0 && n < 32);
265	/* Ensure that only the bits to be output are nonzero. */
266	assert(!(v & (~JAS_ONES(n))));
267
268	/* Put the desired number of bits to the specified bit stream. */
269	m = n - 1;
270	while (--n >= 0) {
271		if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
272			return EOF;
273		}
274		v <<= 1;
275	}
276	return 0;
277}
278
279/******************************************************************************\
280* Code for buffer filling and flushing.
281\******************************************************************************/
282
283/* Fill the buffer for a bit stream. */
284int jpc_bitstream_fillbuf(jpc_bitstream_t *bitstream)
285{
286	int c;
287	/* Note: The count has already been decremented by the caller. */
288	assert(bitstream->openmode_ & JPC_BITSTREAM_READ);
289	assert(bitstream->cnt_ <= 0);
290
291	if (bitstream->flags_ & JPC_BITSTREAM_ERR) {
292		bitstream->cnt_ = 0;
293		return -1;
294	}
295
296	if (bitstream->flags_ & JPC_BITSTREAM_EOF) {
297		bitstream->buf_ = 0x7f;
298		bitstream->cnt_ = 7;
299		return 1;
300	}
301
302	bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
303	if ((c = jas_stream_getc((bitstream)->stream_)) == EOF) {
304		bitstream->flags_ |= JPC_BITSTREAM_EOF;
305		return 1;
306	}
307	bitstream->cnt_ = (bitstream->buf_ == 0xff00) ? 6 : 7;
308	bitstream->buf_ |= c & ((1 << (bitstream->cnt_ + 1)) - 1);
309	return (bitstream->buf_ >> bitstream->cnt_) & 1;
310}
311
312
313/******************************************************************************\
314* Code related to flushing.
315\******************************************************************************/
316
317/* Does the bit stream need to be aligned to a byte boundary (considering
318  the effects of bit stuffing)? */
319int jpc_bitstream_needalign(jpc_bitstream_t *bitstream)
320{
321	if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
322		/* The bit stream is open for reading. */
323		/* If there are any bits buffered for reading, or the
324		  previous byte forced a stuffed bit, alignment is
325		  required. */
326		if ((bitstream->cnt_ < 8 && bitstream->cnt_ > 0) ||
327		  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
328			return 1;
329		}
330	} else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
331		/* The bit stream is open for writing. */
332		/* If there are any bits buffered for writing, or the
333		  previous byte forced a stuffed bit, alignment is
334		  required. */
335		if ((bitstream->cnt_ < 8 && bitstream->cnt_ >= 0) ||
336		  ((bitstream->buf_ >> 8) & 0xff) == 0xff) {
337			return 1;
338		}
339	} else {
340		/* This should not happen.  Famous last words, eh? :-) */
341		assert(0);
342		return -1;
343	}
344	return 0;
345}
346
347/* How many additional bytes would be output if we align the bit stream? */
348int jpc_bitstream_pending(jpc_bitstream_t *bitstream)
349{
350	if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
351		/* The bit stream is being used for writing. */
352#if 1
353		/* XXX - Is this really correct?  Check someday... */
354		if (bitstream->cnt_ < 8) {
355			return 1;
356		}
357#else
358		if (bitstream->cnt_ < 8) {
359			if (((bitstream->buf_ >> 8) & 0xff) == 0xff) {
360				return 2;
361			}
362			return 1;
363		}
364#endif
365		return 0;
366	} else {
367		/* This operation should not be invoked on a bit stream that
368		  is being used for reading. */
369		return -1;
370	}
371}
372
373/* Align the bit stream to a byte boundary. */
374int jpc_bitstream_align(jpc_bitstream_t *bitstream)
375{
376	int ret;
377	if (bitstream->openmode_ & JPC_BITSTREAM_READ) {
378		ret = jpc_bitstream_inalign(bitstream, 0, 0);
379	} else if (bitstream->openmode_ & JPC_BITSTREAM_WRITE) {
380		ret = jpc_bitstream_outalign(bitstream, 0);
381	}
382	return ret;
383}
384
385/* Align a bit stream in the input case. */
386int jpc_bitstream_inalign(jpc_bitstream_t *bitstream, int fillmask,
387  int filldata)
388{
389	int n;
390	int v;
391	int u;
392	int numfill;
393	int m;
394
395	numfill = 7;
396	m = 0;
397	v = 0;
398	if (bitstream->cnt_ > 0) {
399		n = bitstream->cnt_;
400	} else if (!bitstream->cnt_) {
401		n = ((bitstream->buf_ & 0xff) == 0xff) ? 7 : 0;
402	} else {
403		n = 0;
404	}
405	if (n > 0) {
406		if ((u = jpc_bitstream_getbits(bitstream, n)) < 0) {
407			return -1;
408		}
409		m += n;
410		v = (v << n) | u;
411	}
412	if ((bitstream->buf_ & 0xff) == 0xff) {
413		if ((u = jpc_bitstream_getbits(bitstream, 7)) < 0) {
414			return -1;
415		}
416		v = (v << 7) | u;
417		m += 7;
418	}
419	if (m > numfill) {
420		v >>= m - numfill;
421	} else {
422		filldata >>= numfill - m;
423		fillmask >>= numfill - m;
424	}
425	if (((~(v ^ filldata)) & fillmask) != fillmask) {
426		/* The actual fill pattern does not match the expected one. */
427		return 1;
428	}
429
430	return 0;
431}
432
433/* Align a bit stream in the output case. */
434int jpc_bitstream_outalign(jpc_bitstream_t *bitstream, int filldata)
435{
436	int n;
437	int v;
438
439	/* Ensure that this bit stream is open for writing. */
440	assert(bitstream->openmode_ & JPC_BITSTREAM_WRITE);
441
442	/* Ensure that the first bit of fill data is zero. */
443	/* Note: The first bit of fill data must be zero.  If this were not
444	  the case, the fill data itself could cause further bit stuffing to
445	  be required (which would cause numerous complications). */
446	assert(!(filldata & (~0x3f)));
447
448	if (!bitstream->cnt_) {
449		if ((bitstream->buf_ & 0xff) == 0xff) {
450			n = 7;
451			v = filldata;
452		} else {
453			n = 0;
454			v = 0;
455		}
456	} else if (bitstream->cnt_ > 0 && bitstream->cnt_ < 8) {
457		n = bitstream->cnt_;
458		v = filldata >> (7 - n);
459	} else {
460		n = 0;
461		v = 0;
462		return 0;
463	}
464
465	/* Write the appropriate fill data to the bit stream. */
466	if (n > 0) {
467		if (jpc_bitstream_putbits(bitstream, n, v)) {
468			return -1;
469		}
470	}
471	if (bitstream->cnt_ < 8) {
472		assert(bitstream->cnt_ >= 0 && bitstream->cnt_ < 8);
473		assert((bitstream->buf_ & 0xff) != 0xff);
474		/* Force the pending byte of output to be written to the
475		  underlying (character) stream. */
476		if (jas_stream_putc(bitstream->stream_, bitstream->buf_ & 0xff) == EOF) {
477			return -1;
478		}
479		bitstream->cnt_ = 8;
480		bitstream->buf_ = (bitstream->buf_ << 8) & 0xffff;
481	}
482
483	return 0;
484}
485