1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000-2009  Josh Coalson
3  * Copyright (C) 2011-2014  Xiph.Org Foundation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * - Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * - Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  *
16  * - Neither the name of the Xiph.org Foundation nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #ifdef HAVE_CONFIG_H
34 #  include <config.h>
35 #endif
36 
37 #include <stdlib.h>
38 #include <string.h>
39 #include "private/bitwriter.h"
40 #include "private/crc.h"
41 #include "private/macros.h"
42 #include "FLAC/assert.h"
43 #include "share/alloc.h"
44 #include "share/compat.h"
45 #include "share/endswap.h"
46 
47 /* Things should be fastest when this matches the machine word size */
48 /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
49 /* WATCHOUT: there are a few places where the code will not work unless uint32_t is >= 32 bits wide */
50 #define FLAC__BYTES_PER_WORD 4
51 #define FLAC__BITS_PER_WORD 32
52 #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
53 /* SWAP_BE_WORD_TO_HOST swaps bytes in a uint32_t (which is always big-endian) if necessary to match host byte order */
54 #if WORDS_BIGENDIAN
55 #define SWAP_BE_WORD_TO_HOST(x) (x)
56 #else
57 #define SWAP_BE_WORD_TO_HOST(x) ENDSWAP_32(x)
58 #endif
59 
60 /*
61  * The default capacity here doesn't matter too much.  The buffer always grows
62  * to hold whatever is written to it.  Usually the encoder will stop adding at
63  * a frame or metadata block, then write that out and clear the buffer for the
64  * next one.
65  */
66 static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(uint32_t); /* size in words */
67 /* When growing, increment 4K at a time */
68 static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(uint32_t); /* size in words */
69 
70 #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
71 #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
72 
73 struct FLAC__BitWriter {
74 	uint32_t *buffer;
75 	uint32_t accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
76 	unsigned capacity; /* capacity of buffer in words */
77 	unsigned words; /* # of complete words in buffer */
78 	unsigned bits; /* # of used bits in accum */
79 };
80 
81 /* * WATCHOUT: The current implementation only grows the buffer. */
82 #ifndef __SUNPRO_C
83 static
84 #endif
bitwriter_grow_(FLAC__BitWriter * bw,unsigned bits_to_add)85 FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
86 {
87 	unsigned new_capacity;
88 	uint32_t *new_buffer;
89 
90 	FLAC__ASSERT(0 != bw);
91 	FLAC__ASSERT(0 != bw->buffer);
92 
93 	/* calculate total words needed to store 'bits_to_add' additional bits */
94 	new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
95 
96 	/* it's possible (due to pessimism in the growth estimation that
97 	 * leads to this call) that we don't actually need to grow
98 	 */
99 	if(bw->capacity >= new_capacity)
100 		return true;
101 
102 	/* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
103 	if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
104 		new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
105 	/* make sure we got everything right */
106 	FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
107 	FLAC__ASSERT(new_capacity > bw->capacity);
108 	FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
109 
110 	new_buffer = safe_realloc_mul_2op_(bw->buffer, sizeof(uint32_t), /*times*/new_capacity);
111 	if(new_buffer == 0)
112 		return false;
113 	bw->buffer = new_buffer;
114 	bw->capacity = new_capacity;
115 	return true;
116 }
117 
118 
119 /***********************************************************************
120  *
121  * Class constructor/destructor
122  *
123  ***********************************************************************/
124 
FLAC__bitwriter_new(void)125 FLAC__BitWriter *FLAC__bitwriter_new(void)
126 {
127 	FLAC__BitWriter *bw = calloc(1, sizeof(FLAC__BitWriter));
128 	/* note that calloc() sets all members to 0 for us */
129 	return bw;
130 }
131 
FLAC__bitwriter_delete(FLAC__BitWriter * bw)132 void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
133 {
134 	FLAC__ASSERT(0 != bw);
135 
136 	FLAC__bitwriter_free(bw);
137 	free(bw);
138 }
139 
140 /***********************************************************************
141  *
142  * Public class methods
143  *
144  ***********************************************************************/
145 
FLAC__bitwriter_init(FLAC__BitWriter * bw)146 FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
147 {
148 	FLAC__ASSERT(0 != bw);
149 
150 	bw->words = bw->bits = 0;
151 	bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
152 	bw->buffer = malloc(sizeof(uint32_t) * bw->capacity);
153 	if(bw->buffer == 0)
154 		return false;
155 
156 	return true;
157 }
158 
FLAC__bitwriter_free(FLAC__BitWriter * bw)159 void FLAC__bitwriter_free(FLAC__BitWriter *bw)
160 {
161 	FLAC__ASSERT(0 != bw);
162 
163 	if(0 != bw->buffer)
164 		free(bw->buffer);
165 	bw->buffer = 0;
166 	bw->capacity = 0;
167 	bw->words = bw->bits = 0;
168 }
169 
FLAC__bitwriter_clear(FLAC__BitWriter * bw)170 void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
171 {
172 	bw->words = bw->bits = 0;
173 }
174 
FLAC__bitwriter_dump(const FLAC__BitWriter * bw,FILE * out)175 void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
176 {
177 	unsigned i, j;
178 	if(bw == 0) {
179 		fprintf(out, "bitwriter is NULL\n");
180 	}
181 	else {
182 		fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
183 
184 		for(i = 0; i < bw->words; i++) {
185 			fprintf(out, "%08X: ", i);
186 			for(j = 0; j < FLAC__BITS_PER_WORD; j++)
187 				fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
188 			fprintf(out, "\n");
189 		}
190 		if(bw->bits > 0) {
191 			fprintf(out, "%08X: ", i);
192 			for(j = 0; j < bw->bits; j++)
193 				fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
194 			fprintf(out, "\n");
195 		}
196 	}
197 }
198 
FLAC__bitwriter_get_write_crc16(FLAC__BitWriter * bw,FLAC__uint16 * crc)199 FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
200 {
201 	const FLAC__byte *buffer;
202 	size_t bytes;
203 
204 	FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
205 
206 	if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
207 		return false;
208 
209 	*crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
210 	FLAC__bitwriter_release_buffer(bw);
211 	return true;
212 }
213 
FLAC__bitwriter_get_write_crc8(FLAC__BitWriter * bw,FLAC__byte * crc)214 FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
215 {
216 	const FLAC__byte *buffer;
217 	size_t bytes;
218 
219 	FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
220 
221 	if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
222 		return false;
223 
224 	*crc = FLAC__crc8(buffer, bytes);
225 	FLAC__bitwriter_release_buffer(bw);
226 	return true;
227 }
228 
FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter * bw)229 FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
230 {
231 	return ((bw->bits & 7) == 0);
232 }
233 
FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter * bw)234 unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
235 {
236 	return FLAC__TOTAL_BITS(bw);
237 }
238 
FLAC__bitwriter_get_buffer(FLAC__BitWriter * bw,const FLAC__byte ** buffer,size_t * bytes)239 FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
240 {
241 	FLAC__ASSERT((bw->bits & 7) == 0);
242 	/* double protection */
243 	if(bw->bits & 7)
244 		return false;
245 	/* if we have bits in the accumulator we have to flush those to the buffer first */
246 	if(bw->bits) {
247 		FLAC__ASSERT(bw->words <= bw->capacity);
248 		if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
249 			return false;
250 		/* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
251 		bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
252 	}
253 	/* now we can just return what we have */
254 	*buffer = (FLAC__byte*)bw->buffer;
255 	*bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
256 	return true;
257 }
258 
FLAC__bitwriter_release_buffer(FLAC__BitWriter * bw)259 void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
260 {
261 	/* nothing to do.  in the future, strict checking of a 'writer-is-in-
262 	 * get-mode' flag could be added everywhere and then cleared here
263 	 */
264 	(void)bw;
265 }
266 
FLAC__bitwriter_write_zeroes(FLAC__BitWriter * bw,unsigned bits)267 inline FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
268 {
269 	unsigned n;
270 
271 	FLAC__ASSERT(0 != bw);
272 	FLAC__ASSERT(0 != bw->buffer);
273 
274 	if(bits == 0)
275 		return true;
276 	/* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
277 	if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
278 		return false;
279 	/* first part gets to word alignment */
280 	if(bw->bits) {
281 		n = flac_min(FLAC__BITS_PER_WORD - bw->bits, bits);
282 		bw->accum <<= n;
283 		bits -= n;
284 		bw->bits += n;
285 		if(bw->bits == FLAC__BITS_PER_WORD) {
286 			bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
287 			bw->bits = 0;
288 		}
289 		else
290 			return true;
291 	}
292 	/* do whole words */
293 	while(bits >= FLAC__BITS_PER_WORD) {
294 		bw->buffer[bw->words++] = 0;
295 		bits -= FLAC__BITS_PER_WORD;
296 	}
297 	/* do any leftovers */
298 	if(bits > 0) {
299 		bw->accum = 0;
300 		bw->bits = bits;
301 	}
302 	return true;
303 }
304 
FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter * bw,FLAC__uint32 val,unsigned bits)305 inline FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
306 {
307 	register unsigned left;
308 
309 	/* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
310 	FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
311 
312 	FLAC__ASSERT(0 != bw);
313 	FLAC__ASSERT(0 != bw->buffer);
314 
315 	FLAC__ASSERT(bits <= 32);
316 	if(bits == 0)
317 		return true;
318 
319 	/* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
320 	if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
321 		return false;
322 
323 	left = FLAC__BITS_PER_WORD - bw->bits;
324 	if(bits < left) {
325 		bw->accum <<= bits;
326 		bw->accum |= val;
327 		bw->bits += bits;
328 	}
329 	else if(bw->bits) { /* WATCHOUT: if bw->bits == 0, left==FLAC__BITS_PER_WORD and bw->accum<<=left is a NOP instead of setting to 0 */
330 		bw->accum <<= left;
331 		bw->accum |= val >> (bw->bits = bits - left);
332 		bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
333 		bw->accum = val;
334 	}
335 	else {
336 		bw->accum = val;
337 		bw->bits = 0;
338 		bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
339 	}
340 
341 	return true;
342 }
343 
FLAC__bitwriter_write_raw_int32(FLAC__BitWriter * bw,FLAC__int32 val,unsigned bits)344 inline FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
345 {
346 	/* zero-out unused bits */
347 	if(bits < 32)
348 		val &= (~(0xffffffff << bits));
349 
350 	return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
351 }
352 
FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter * bw,FLAC__uint64 val,unsigned bits)353 inline FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
354 {
355 	/* this could be a little faster but it's not used for much */
356 	if(bits > 32) {
357 		return
358 			FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
359 			FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
360 	}
361 	else
362 		return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
363 }
364 
FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter * bw,FLAC__uint32 val)365 inline FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
366 {
367 	/* this doesn't need to be that fast as currently it is only used for vorbis comments */
368 
369 	if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
370 		return false;
371 	if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
372 		return false;
373 	if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
374 		return false;
375 	if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
376 		return false;
377 
378 	return true;
379 }
380 
FLAC__bitwriter_write_byte_block(FLAC__BitWriter * bw,const FLAC__byte vals[],unsigned nvals)381 inline FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
382 {
383 	unsigned i;
384 
385 	/* this could be faster but currently we don't need it to be since it's only used for writing metadata */
386 	for(i = 0; i < nvals; i++) {
387 		if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
388 			return false;
389 	}
390 
391 	return true;
392 }
393 
FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter * bw,unsigned val)394 FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
395 {
396 	if(val < 32)
397 		return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
398 	else
399 		return
400 			FLAC__bitwriter_write_zeroes(bw, val) &&
401 			FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
402 }
403 
FLAC__bitwriter_rice_bits(FLAC__int32 val,unsigned parameter)404 unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
405 {
406 	FLAC__uint32 uval;
407 
408 	FLAC__ASSERT(parameter < sizeof(unsigned)*8);
409 
410 	/* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
411 	uval = (val<<1) ^ (val>>31);
412 
413 	return 1 + parameter + (uval >> parameter);
414 }
415 
416 #if 0 /* UNUSED */
417 unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
418 {
419 	unsigned bits, msbs, uval;
420 	unsigned k;
421 
422 	FLAC__ASSERT(parameter > 0);
423 
424 	/* fold signed to unsigned */
425 	if(val < 0)
426 		uval = (unsigned)(((-(++val)) << 1) + 1);
427 	else
428 		uval = (unsigned)(val << 1);
429 
430 	k = FLAC__bitmath_ilog2(parameter);
431 	if(parameter == 1u<<k) {
432 		FLAC__ASSERT(k <= 30);
433 
434 		msbs = uval >> k;
435 		bits = 1 + k + msbs;
436 	}
437 	else {
438 		unsigned q, r, d;
439 
440 		d = (1 << (k+1)) - parameter;
441 		q = uval / parameter;
442 		r = uval - (q * parameter);
443 
444 		bits = 1 + q + k;
445 		if(r >= d)
446 			bits++;
447 	}
448 	return bits;
449 }
450 
451 unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
452 {
453 	unsigned bits, msbs;
454 	unsigned k;
455 
456 	FLAC__ASSERT(parameter > 0);
457 
458 	k = FLAC__bitmath_ilog2(parameter);
459 	if(parameter == 1u<<k) {
460 		FLAC__ASSERT(k <= 30);
461 
462 		msbs = uval >> k;
463 		bits = 1 + k + msbs;
464 	}
465 	else {
466 		unsigned q, r, d;
467 
468 		d = (1 << (k+1)) - parameter;
469 		q = uval / parameter;
470 		r = uval - (q * parameter);
471 
472 		bits = 1 + q + k;
473 		if(r >= d)
474 			bits++;
475 	}
476 	return bits;
477 }
478 #endif /* UNUSED */
479 
FLAC__bitwriter_write_rice_signed(FLAC__BitWriter * bw,FLAC__int32 val,unsigned parameter)480 FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
481 {
482 	unsigned total_bits, interesting_bits, msbs;
483 	FLAC__uint32 uval, pattern;
484 
485 	FLAC__ASSERT(0 != bw);
486 	FLAC__ASSERT(0 != bw->buffer);
487 	FLAC__ASSERT(parameter < 8*sizeof(uval));
488 
489 	/* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
490 	uval = (val<<1) ^ (val>>31);
491 
492 	msbs = uval >> parameter;
493 	interesting_bits = 1 + parameter;
494 	total_bits = interesting_bits + msbs;
495 	pattern = 1 << parameter; /* the unary end bit */
496 	pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
497 
498 	if(total_bits <= 32)
499 		return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
500 	else
501 		return
502 			FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
503 			FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
504 }
505 
FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter * bw,const FLAC__int32 * vals,unsigned nvals,unsigned parameter)506 FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
507 {
508 	const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
509 	const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
510 	FLAC__uint32 uval;
511 	unsigned left;
512 	const unsigned lsbits = 1 + parameter;
513 	unsigned msbits;
514 
515 	FLAC__ASSERT(0 != bw);
516 	FLAC__ASSERT(0 != bw->buffer);
517 	FLAC__ASSERT(parameter < 8*sizeof(uint32_t)-1);
518 	/* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
519 	FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
520 
521 	while(nvals) {
522 		/* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
523 		uval = (*vals<<1) ^ (*vals>>31);
524 
525 		msbits = uval >> parameter;
526 
527 		if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current uint32_t */
528 			/* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free uint32_t to work in */
529 			bw->bits = bw->bits + msbits + lsbits;
530 			uval |= mask1; /* set stop bit */
531 			uval &= mask2; /* mask off unused top bits */
532 			bw->accum <<= msbits + lsbits;
533 			bw->accum |= uval;
534 		}
535 		else {
536 			/* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
537 			/* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
538 			if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 uint32_t*/ && !bitwriter_grow_(bw, msbits+lsbits))
539 				return false;
540 
541 			if(msbits) {
542 				/* first part gets to word alignment */
543 				if(bw->bits) {
544 					left = FLAC__BITS_PER_WORD - bw->bits;
545 					if(msbits < left) {
546 						bw->accum <<= msbits;
547 						bw->bits += msbits;
548 						goto break1;
549 					}
550 					else {
551 						bw->accum <<= left;
552 						msbits -= left;
553 						bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
554 						bw->bits = 0;
555 					}
556 				}
557 				/* do whole words */
558 				while(msbits >= FLAC__BITS_PER_WORD) {
559 					bw->buffer[bw->words++] = 0;
560 					msbits -= FLAC__BITS_PER_WORD;
561 				}
562 				/* do any leftovers */
563 				if(msbits > 0) {
564 					bw->accum = 0;
565 					bw->bits = msbits;
566 				}
567 			}
568 break1:
569 			uval |= mask1; /* set stop bit */
570 			uval &= mask2; /* mask off unused top bits */
571 
572 			left = FLAC__BITS_PER_WORD - bw->bits;
573 			if(lsbits < left) {
574 				bw->accum <<= lsbits;
575 				bw->accum |= uval;
576 				bw->bits += lsbits;
577 			}
578 			else {
579 				/* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
580 				 * be > lsbits (because of previous assertions) so it would have
581 				 * triggered the (lsbits<left) case above.
582 				 */
583 				FLAC__ASSERT(bw->bits);
584 				FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
585 				bw->accum <<= left;
586 				bw->accum |= uval >> (bw->bits = lsbits - left);
587 				bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
588 				bw->accum = uval;
589 			}
590 		}
591 		vals++;
592 		nvals--;
593 	}
594 	return true;
595 }
596 
597 #if 0 /* UNUSED */
598 FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
599 {
600 	unsigned total_bits, msbs, uval;
601 	unsigned k;
602 
603 	FLAC__ASSERT(0 != bw);
604 	FLAC__ASSERT(0 != bw->buffer);
605 	FLAC__ASSERT(parameter > 0);
606 
607 	/* fold signed to unsigned */
608 	if(val < 0)
609 		uval = (unsigned)(((-(++val)) << 1) + 1);
610 	else
611 		uval = (unsigned)(val << 1);
612 
613 	k = FLAC__bitmath_ilog2(parameter);
614 	if(parameter == 1u<<k) {
615 		unsigned pattern;
616 
617 		FLAC__ASSERT(k <= 30);
618 
619 		msbs = uval >> k;
620 		total_bits = 1 + k + msbs;
621 		pattern = 1 << k; /* the unary end bit */
622 		pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
623 
624 		if(total_bits <= 32) {
625 			if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
626 				return false;
627 		}
628 		else {
629 			/* write the unary MSBs */
630 			if(!FLAC__bitwriter_write_zeroes(bw, msbs))
631 				return false;
632 			/* write the unary end bit and binary LSBs */
633 			if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
634 				return false;
635 		}
636 	}
637 	else {
638 		unsigned q, r, d;
639 
640 		d = (1 << (k+1)) - parameter;
641 		q = uval / parameter;
642 		r = uval - (q * parameter);
643 		/* write the unary MSBs */
644 		if(!FLAC__bitwriter_write_zeroes(bw, q))
645 			return false;
646 		/* write the unary end bit */
647 		if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
648 			return false;
649 		/* write the binary LSBs */
650 		if(r >= d) {
651 			if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
652 				return false;
653 		}
654 		else {
655 			if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
656 				return false;
657 		}
658 	}
659 	return true;
660 }
661 
662 FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
663 {
664 	unsigned total_bits, msbs;
665 	unsigned k;
666 
667 	FLAC__ASSERT(0 != bw);
668 	FLAC__ASSERT(0 != bw->buffer);
669 	FLAC__ASSERT(parameter > 0);
670 
671 	k = FLAC__bitmath_ilog2(parameter);
672 	if(parameter == 1u<<k) {
673 		unsigned pattern;
674 
675 		FLAC__ASSERT(k <= 30);
676 
677 		msbs = uval >> k;
678 		total_bits = 1 + k + msbs;
679 		pattern = 1 << k; /* the unary end bit */
680 		pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
681 
682 		if(total_bits <= 32) {
683 			if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
684 				return false;
685 		}
686 		else {
687 			/* write the unary MSBs */
688 			if(!FLAC__bitwriter_write_zeroes(bw, msbs))
689 				return false;
690 			/* write the unary end bit and binary LSBs */
691 			if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
692 				return false;
693 		}
694 	}
695 	else {
696 		unsigned q, r, d;
697 
698 		d = (1 << (k+1)) - parameter;
699 		q = uval / parameter;
700 		r = uval - (q * parameter);
701 		/* write the unary MSBs */
702 		if(!FLAC__bitwriter_write_zeroes(bw, q))
703 			return false;
704 		/* write the unary end bit */
705 		if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
706 			return false;
707 		/* write the binary LSBs */
708 		if(r >= d) {
709 			if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
710 				return false;
711 		}
712 		else {
713 			if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
714 				return false;
715 		}
716 	}
717 	return true;
718 }
719 #endif /* UNUSED */
720 
FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter * bw,FLAC__uint32 val)721 FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
722 {
723 	FLAC__bool ok = 1;
724 
725 	FLAC__ASSERT(0 != bw);
726 	FLAC__ASSERT(0 != bw->buffer);
727 
728 	FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
729 
730 	if(val < 0x80) {
731 		return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
732 	}
733 	else if(val < 0x800) {
734 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
735 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
736 	}
737 	else if(val < 0x10000) {
738 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
739 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
740 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
741 	}
742 	else if(val < 0x200000) {
743 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
744 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
745 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
746 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
747 	}
748 	else if(val < 0x4000000) {
749 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
750 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
751 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
752 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
753 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
754 	}
755 	else {
756 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
757 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
758 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
759 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
760 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
761 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
762 	}
763 
764 	return ok;
765 }
766 
FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter * bw,FLAC__uint64 val)767 FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
768 {
769 	FLAC__bool ok = 1;
770 
771 	FLAC__ASSERT(0 != bw);
772 	FLAC__ASSERT(0 != bw->buffer);
773 
774 	FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
775 
776 	if(val < 0x80) {
777 		return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
778 	}
779 	else if(val < 0x800) {
780 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
781 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
782 	}
783 	else if(val < 0x10000) {
784 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
785 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
786 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
787 	}
788 	else if(val < 0x200000) {
789 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
790 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
791 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
792 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
793 	}
794 	else if(val < 0x4000000) {
795 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
796 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
797 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
798 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
799 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
800 	}
801 	else if(val < 0x80000000) {
802 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
803 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
804 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
805 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
806 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
807 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
808 	}
809 	else {
810 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
811 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
812 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
813 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
814 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
815 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
816 		ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
817 	}
818 
819 	return ok;
820 }
821 
FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter * bw)822 FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
823 {
824 	/* 0-pad to byte boundary */
825 	if(bw->bits & 7u)
826 		return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
827 	else
828 		return true;
829 }
830 
831 /* These functions are declared inline in this file but are also callable as
832  * externs from elsewhere.
833  * According to the C99 spec, section 6.7.4, simply providing a function
834  * prototype in a header file without 'inline' and making the function inline
835  * in this file should be sufficient.
836  * Unfortunately, the Microsoft VS compiler doesn't pick them up externally. To
837  * fix that we add extern declarations here.
838  */
839 extern FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
840 extern FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
841 extern FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
842 extern FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val);
843 extern FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
844