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