1 // Copyright (c) the JPEG XL Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
6 #include "lib/jpegli/bit_writer.h"
8 #include "lib/jpegli/encode_internal.h"
12 void JpegBitWriterInit(j_compress_ptr cinfo) {
13 jpeg_comp_master* m = cinfo->master;
14 JpegBitWriter* bw = &m->bw;
15 size_t buffer_size = m->blocks_per_iMCU_row * (DCTSIZE2 * 16 + 8) + (1 << 16);
17 bw->data = Allocate<uint8_t>(cinfo, buffer_size, JPOOL_IMAGE);
18 bw->len = buffer_size;
26 bool EmptyBitWriterBuffer(JpegBitWriter* bw) {
27 while (bw->output_pos < bw->pos) {
28 j_compress_ptr cinfo = bw->cinfo;
29 if (cinfo->dest->free_in_buffer == 0 &&
30 !(*cinfo->dest->empty_output_buffer)(cinfo)) {
33 size_t buflen = bw->pos - bw->output_pos;
34 size_t copylen = std::min<size_t>(cinfo->dest->free_in_buffer, buflen);
35 memcpy(cinfo->dest->next_output_byte, bw->data + bw->output_pos, copylen);
36 bw->output_pos += copylen;
37 cinfo->dest->free_in_buffer -= copylen;
38 cinfo->dest->next_output_byte += copylen;
40 bw->output_pos = bw->pos = 0;
44 void JumpToByteBoundary(JpegBitWriter* bw) {
45 size_t n_bits = bw->free_bits & 7u;
47 WriteBits(bw, n_bits, (1u << n_bits) - 1);
49 bw->put_buffer <<= bw->free_bits;
50 while (bw->free_bits <= 56) {
51 int c = (bw->put_buffer >> 56) & 0xFF;