2 * JPEG2000 image encoder
3 * Copyright (c) 2007 Kamil Nowosad
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 * **********************************************************************************************************************
25 * This source code incorporates work covered by the following copyright and
28 * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
29 * Copyright (c) 2002-2007, Professor Benoit Macq
30 * Copyright (c) 2001-2003, David Janssens
31 * Copyright (c) 2002-2003, Yannick Verschueren
32 * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
33 * Copyright (c) 2005, Herve Drolon, FreeImage Team
34 * Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
35 * All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
46 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
47 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
50 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56 * POSSIBILITY OF SUCH DAMAGE.
61 * JPEG2000 image encoder
63 * @author Kamil Nowosad
69 #include "bytestream.h"
71 #include "libavutil/common.h"
72 #include "libavutil/pixdesc.h"
73 #include "libavutil/opt.h"
74 #include "libavutil/intreadwrite.h"
76 #define NMSEDEC_BITS 7
77 #define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
78 #define WMSEDEC_SHIFT 13 ///< must be >= 13
79 #define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
84 static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
85 lut_nmsedec_ref0[1<<NMSEDEC_BITS],
86 lut_nmsedec_sig [1<<NMSEDEC_BITS],
87 lut_nmsedec_sig0[1<<NMSEDEC_BITS];
89 static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
90 {{10000, 19650, 41770, 84030, 169000, 338400, 676900, 1353000, 2706000, 5409000},
91 {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
92 {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
93 {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
95 {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
96 {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
97 {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
98 { 7186, 9218, 15860, 30430, 60190, 120100, 240000, 479700, 959300}}
102 Jpeg2000Component *comp;
107 AVCodecContext *avctx;
108 const AVFrame *picture;
110 int width, height; ///< image width and height
111 uint8_t cbps[4]; ///< bits per sample in particular components
115 int tile_width, tile_height; ///< tile size
116 int numXtiles, numYtiles;
125 Jpeg2000CodingStyle codsty;
126 Jpeg2000QuantStyle qntsty;
135 } Jpeg2000EncoderContext;
143 static void nspaces(FILE *fd, int n)
145 while(n--) putc(' ', fd);
148 static void printcomp(Jpeg2000Component *comp)
151 for (i = 0; i < comp->y1 - comp->y0; i++)
152 ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
155 static void dump(Jpeg2000EncoderContext *s, FILE *fd)
157 int tileno, compno, reslevelno, bandno, precno;
158 fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
159 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
161 s->width, s->height, s->tile_width, s->tile_height,
162 s->numXtiles, s->numYtiles, s->ncomponents);
163 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
164 Jpeg2000Tile *tile = s->tile + tileno;
166 fprintf(fd, "tile %d:\n", tileno);
167 for(compno = 0; compno < s->ncomponents; compno++){
168 Jpeg2000Component *comp = tile->comp + compno;
170 fprintf(fd, "component %d:\n", compno);
172 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
173 comp->x0, comp->x1, comp->y0, comp->y1);
174 for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
175 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
177 fprintf(fd, "reslevel %d:\n", reslevelno);
179 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
180 reslevel->x0, reslevel->x1, reslevel->y0,
181 reslevel->y1, reslevel->nbands);
182 for(bandno = 0; bandno < reslevel->nbands; bandno++){
183 Jpeg2000Band *band = reslevel->band + bandno;
185 fprintf(fd, "band %d:\n", bandno);
187 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
188 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
191 band->codeblock_width, band->codeblock_height,
192 band->cblknx, band->cblkny);
193 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
194 Jpeg2000Prec *prec = band->prec + precno;
196 fprintf(fd, "prec %d:\n", precno);
198 fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
199 prec->xi0, prec->xi1, prec->yi0, prec->yi1);
208 /* bitstream routines */
210 /** put n times val bit */
211 static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
214 if (s->bit_index == 8)
216 s->bit_index = *s->buf == 0xff;
219 *s->buf |= val << (7 - s->bit_index++);
223 /** put n least significant bits of a number num */
224 static void put_num(Jpeg2000EncoderContext *s, int num, int n)
227 put_bits(s, (num >> n) & 1, 1);
230 /** flush the bitstream */
231 static void j2k_flush(Jpeg2000EncoderContext *s)
239 /* tag tree routines */
241 /** code the value stored in node */
242 static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
244 Jpeg2000TgtNode *stack[30];
245 int sp = 1, curval = 0;
259 if (stack[sp]->val >= threshold){
260 put_bits(s, 0, threshold - curval);
263 put_bits(s, 0, stack[sp]->val - curval);
265 curval = stack[sp]->val;
269 /** update the value in node */
270 static void tag_tree_update(Jpeg2000TgtNode *node)
273 while (node->parent){
274 if (node->parent->val <= node->val)
276 node->parent->val = node->val;
282 static int put_siz(Jpeg2000EncoderContext *s)
286 if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
289 bytestream_put_be16(&s->buf, JPEG2000_SIZ);
290 bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
291 bytestream_put_be16(&s->buf, 0); // Rsiz
292 bytestream_put_be32(&s->buf, s->width); // width
293 bytestream_put_be32(&s->buf, s->height); // height
294 bytestream_put_be32(&s->buf, 0); // X0Siz
295 bytestream_put_be32(&s->buf, 0); // Y0Siz
297 bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
298 bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
299 bytestream_put_be32(&s->buf, 0); // XT0Siz
300 bytestream_put_be32(&s->buf, 0); // YT0Siz
301 bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
303 for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
304 bytestream_put_byte(&s->buf, s->cbps[i] - 1);
305 bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
306 bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
311 static int put_cod(Jpeg2000EncoderContext *s)
313 Jpeg2000CodingStyle *codsty = &s->codsty;
316 if (s->buf_end - s->buf < 14)
319 bytestream_put_be16(&s->buf, JPEG2000_COD);
320 bytestream_put_be16(&s->buf, 12); // Lcod
322 scod |= JPEG2000_CSTY_SOP;
324 scod |= JPEG2000_CSTY_EPH;
325 bytestream_put_byte(&s->buf, scod); // Scod
327 bytestream_put_byte(&s->buf, s->prog); // progression level
328 bytestream_put_be16(&s->buf, 1); // num of layers
329 if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
330 bytestream_put_byte(&s->buf, 0); // unspecified
332 bytestream_put_byte(&s->buf, 0); // unspecified
335 bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
336 bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
337 bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
338 bytestream_put_byte(&s->buf, 0); // cblk style
339 bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
343 static int put_qcd(Jpeg2000EncoderContext *s, int compno)
346 Jpeg2000CodingStyle *codsty = &s->codsty;
347 Jpeg2000QuantStyle *qntsty = &s->qntsty;
349 if (qntsty->quantsty == JPEG2000_QSTY_NONE)
350 size = 4 + 3 * (codsty->nreslevels-1);
352 size = 5 + 6 * (codsty->nreslevels-1);
354 if (s->buf_end - s->buf < size + 2)
357 bytestream_put_be16(&s->buf, JPEG2000_QCD);
358 bytestream_put_be16(&s->buf, size); // LQcd
359 bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty); // Sqcd
360 if (qntsty->quantsty == JPEG2000_QSTY_NONE)
361 for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
362 bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
364 for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
365 bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
369 static int put_com(Jpeg2000EncoderContext *s, int compno)
371 int size = 4 + strlen(LIBAVCODEC_IDENT);
373 if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
376 if (s->buf_end - s->buf < size + 2)
379 bytestream_put_be16(&s->buf, JPEG2000_COM);
380 bytestream_put_be16(&s->buf, size);
381 bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
383 bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
388 static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
392 if (s->buf_end - s->buf < 12)
395 bytestream_put_be16(&s->buf, JPEG2000_SOT);
396 bytestream_put_be16(&s->buf, 10); // Lsot
397 bytestream_put_be16(&s->buf, tileno); // Isot
400 bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
402 bytestream_put_byte(&s->buf, 0); // TPsot
403 bytestream_put_byte(&s->buf, 1); // TNsot
408 * compute the sizes of tiles, resolution levels, bands, etc.
409 * allocate memory for them
410 * divide the input image into tile-components
412 static int init_tiles(Jpeg2000EncoderContext *s)
414 int tileno, tilex, tiley, compno;
415 Jpeg2000CodingStyle *codsty = &s->codsty;
416 Jpeg2000QuantStyle *qntsty = &s->qntsty;
418 s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
419 s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
421 s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
423 return AVERROR(ENOMEM);
424 for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
425 for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
426 Jpeg2000Tile *tile = s->tile + tileno;
428 tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
430 return AVERROR(ENOMEM);
431 for (compno = 0; compno < s->ncomponents; compno++){
432 Jpeg2000Component *comp = tile->comp + compno;
435 comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
436 comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
437 comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
438 comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
440 for (i = 0; i < 2; i++)
441 for (j = 0; j < 2; j++)
442 comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
444 if ((ret = ff_jpeg2000_init_component(comp,
448 compno?1<<s->chroma_shift[0]:1,
449 compno?1<<s->chroma_shift[1]:1,
458 #define COPY_FRAME(D, PIXEL) \
459 static void copy_frame_ ##D(Jpeg2000EncoderContext *s) \
461 int tileno, compno, i, y, x; \
463 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){ \
464 Jpeg2000Tile *tile = s->tile + tileno; \
466 for (compno = 0; compno < s->ncomponents; compno++){ \
467 Jpeg2000Component *comp = tile->comp + compno; \
468 int *dst = comp->i_data; \
469 int cbps = s->cbps[compno]; \
470 line = (PIXEL*)s->picture->data[compno] \
471 + comp->coord[1][0] * (s->picture->linesize[compno] / sizeof(PIXEL)) \
472 + comp->coord[0][0]; \
473 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){ \
475 for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++) \
476 *dst++ = *ptr++ - (1 << (cbps - 1)); \
477 line += s->picture->linesize[compno] / sizeof(PIXEL); \
481 line = (PIXEL*)s->picture->data[0] + tile->comp[0].coord[1][0] * (s->picture->linesize[0] / sizeof(PIXEL)) \
482 + tile->comp[0].coord[0][0] * s->ncomponents; \
485 for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){ \
487 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){ \
488 for (compno = 0; compno < s->ncomponents; compno++){ \
489 int cbps = s->cbps[compno]; \
490 tile->comp[compno].i_data[i] = *ptr++ - (1 << (cbps - 1)); \
493 line += s->picture->linesize[0] / sizeof(PIXEL); \
499 COPY_FRAME(8, uint8_t)
500 COPY_FRAME(16, uint16_t)
502 static void init_quantization(Jpeg2000EncoderContext *s)
504 int compno, reslevelno, bandno;
505 Jpeg2000QuantStyle *qntsty = &s->qntsty;
506 Jpeg2000CodingStyle *codsty = &s->codsty;
508 for (compno = 0; compno < s->ncomponents; compno++){
510 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
511 int nbands, lev = codsty->nreslevels - reslevelno - 1;
512 nbands = reslevelno ? 3 : 1;
513 for (bandno = 0; bandno < nbands; bandno++, gbandno++){
516 if (codsty->transform == FF_DWT97_INT){
517 int bandpos = bandno + (reslevelno>0),
518 ss = 81920000 / dwt_norms[0][bandpos][lev],
520 mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
521 expn = s->cbps[compno] - log + 13;
523 expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
525 qntsty->expn[gbandno] = expn;
526 qntsty->mant[gbandno] = mant;
532 static void init_luts(void)
535 mask = ~((1<<NMSEDEC_FRACBITS)-1);
537 for (i = 0; i < (1 << NMSEDEC_BITS); i++){
538 lut_nmsedec_sig[i] = FFMAX((3 * i << (13 - NMSEDEC_FRACBITS)) - (9 << 11), 0);
539 lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
541 a = (i >> (NMSEDEC_BITS-2)&2) + 1;
542 lut_nmsedec_ref[i] = FFMAX((a - 2) * (i << (13 - NMSEDEC_FRACBITS)) +
543 (1 << 13) - (a * a << 11), 0);
544 lut_nmsedec_ref0[i] = FFMAX(((i * i - (i << NMSEDEC_BITS) + (1 << 2 * NMSEDEC_FRACBITS) + (1 << (NMSEDEC_FRACBITS - 1))) & mask)
549 /* tier-1 routines */
550 static int getnmsedec_sig(int x, int bpno)
552 if (bpno > NMSEDEC_FRACBITS)
553 return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
554 return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
557 static int getnmsedec_ref(int x, int bpno)
559 if (bpno > NMSEDEC_FRACBITS)
560 return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
561 return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
564 static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
566 int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
567 for (y0 = 0; y0 < height; y0 += 4)
568 for (x = 0; x < width; x++)
569 for (y = y0; y < height && y < y0+4; y++){
570 if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
571 int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
572 bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
573 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
576 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
577 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
578 *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
579 ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
581 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
586 static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
588 int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
589 for (y0 = 0; y0 < height; y0 += 4)
590 for (x = 0; x < width; x++)
591 for (y = y0; y < height && y < y0+4; y++)
592 if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
593 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
594 *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
595 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
596 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
600 static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
602 int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
603 for (y0 = 0; y0 < height; y0 += 4)
604 for (x = 0; x < width; x++){
605 if (y0 + 3 < height && !(
606 (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
607 (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
608 (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
609 (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
613 for (rlen = 0; rlen < 4; rlen++)
614 if (t1->data[(y0+rlen) * t1->stride + x] & mask)
616 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
619 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
620 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
621 for (y = y0 + rlen; y < y0 + 4; y++){
622 if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
623 int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
625 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
626 if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
628 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
629 *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
630 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
631 ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
634 t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
637 for (y = y0; y < y0 + 4 && y < height; y++){
638 if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
639 int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
640 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
641 if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
643 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
644 *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
645 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
646 ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
649 t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
655 static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
656 int width, int height, int bandpos, int lev)
658 int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
661 memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
663 for (y = 0; y < height; y++){
664 for (x = 0; x < width; x++){
665 if (t1->data[(y) * t1->stride + x] < 0){
666 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
667 t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
669 max = FFMAX(max, t1->data[(y) * t1->stride + x]);
674 cblk->nonzerobits = 0;
677 cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
678 bpno = cblk->nonzerobits - 1;
682 ff_mqc_initenc(&t1->mqc, cblk->data + 1);
684 for (passno = 0; bpno >= 0; passno++){
688 case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
690 case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
692 case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
696 cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
697 wmsedec += (int64_t)nmsedec << (2*bpno);
698 cblk->passes[passno].disto = wmsedec;
705 cblk->npasses = passno;
706 cblk->ninclpasses = passno;
709 cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
712 /* tier-2 routines: */
714 static void putnumpasses(Jpeg2000EncoderContext *s, int n)
721 put_num(s, 0xc | (n-3), 4);
723 put_num(s, 0x1e0 | (n-6), 9);
725 put_num(s, 0xff80 | (n-37), 16);
729 static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
730 uint8_t *expn, int numgbits, int packetno)
732 int bandno, empty = 1;
738 bytestream_put_be16(&s->buf, JPEG2000_SOP);
739 bytestream_put_be16(&s->buf, 4);
740 bytestream_put_be16(&s->buf, packetno);
744 // is the packet empty?
745 for (bandno = 0; bandno < rlevel->nbands; bandno++){
746 if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
747 && rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
753 put_bits(s, !empty, 1);
759 for (bandno = 0; bandno < rlevel->nbands; bandno++){
760 Jpeg2000Band *band = rlevel->band + bandno;
761 Jpeg2000Prec *prec = band->prec + precno;
763 int cblknw = prec->nb_codeblocks_width;
765 if (band->coord[0][0] == band->coord[0][1]
766 || band->coord[1][0] == band->coord[1][1])
769 for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
770 for (xi = 0; xi < cblknw; xi++, pos++){
771 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
772 tag_tree_update(prec->cblkincl + pos);
773 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
774 tag_tree_update(prec->zerobits + pos);
778 for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
779 for (xi = 0; xi < cblknw; xi++, pos++){
780 int pad = 0, llen, length;
781 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
783 if (s->buf_end - s->buf < 20) // approximately
786 // inclusion information
787 tag_tree_code(s, prec->cblkincl + pos, 1);
788 if (!cblk->ninclpasses)
790 // zerobits information
791 tag_tree_code(s, prec->zerobits + pos, 100);
793 putnumpasses(s, cblk->ninclpasses);
795 length = cblk->passes[cblk->ninclpasses-1].rate;
796 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
801 // length of code block
802 put_bits(s, 1, llen);
804 put_num(s, length, av_log2(length)+1+pad);
810 bytestream_put_be16(&s->buf, JPEG2000_EPH);
813 for (bandno = 0; bandno < rlevel->nbands; bandno++){
814 Jpeg2000Band *band = rlevel->band + bandno;
815 Jpeg2000Prec *prec = band->prec + precno;
816 int yi, cblknw = prec->nb_codeblocks_width;
817 for (yi =0; yi < prec->nb_codeblocks_height; yi++){
819 for (xi = 0; xi < cblknw; xi++){
820 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
821 if (cblk->ninclpasses){
822 if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
824 bytestream_put_buffer(&s->buf, cblk->data + 1, cblk->passes[cblk->ninclpasses-1].rate
825 - cblk->passes[cblk->ninclpasses-1].flushed_len);
826 bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
827 cblk->passes[cblk->ninclpasses-1].flushed_len);
835 static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
837 int compno, reslevelno, ret;
838 Jpeg2000CodingStyle *codsty = &s->codsty;
839 Jpeg2000QuantStyle *qntsty = &s->qntsty;
843 int tile_coord[2][2];
844 int col = tileno % s->numXtiles;
845 int row = tileno / s->numXtiles;
847 tile_coord[0][0] = col * s->tile_width;
848 tile_coord[0][1] = FFMIN(tile_coord[0][0] + s->tile_width, s->width);
849 tile_coord[1][0] = row * s->tile_height;
850 tile_coord[1][1] = FFMIN(tile_coord[1][0] + s->tile_height, s->height);
852 av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
853 // lay-rlevel-comp-pos progression
855 case JPEG2000_PGOD_LRCP:
856 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
857 for (compno = 0; compno < s->ncomponents; compno++){
859 Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
860 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
861 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
862 qntsty->nguardbits, packetno++)) < 0)
868 case JPEG2000_PGOD_RLCP:
869 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
870 for (compno = 0; compno < s->ncomponents; compno++){
872 Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
873 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
874 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
875 qntsty->nguardbits, packetno++)) < 0)
881 case JPEG2000_PGOD_RPCL:
882 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
886 for (compno = 0; compno < s->ncomponents; compno++) {
887 Jpeg2000Component *comp = tile->comp + compno;
888 if (reslevelno < codsty->nreslevels) {
889 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
890 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
891 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
892 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
898 for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
899 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
900 for (compno = 0; compno < s->ncomponents; compno++) {
901 Jpeg2000Component *comp = tile->comp + compno;
902 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
903 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
904 int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
908 trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
909 try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
911 if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
912 (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
915 if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
916 (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
919 // check if a precinct exists
920 prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
921 prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
922 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
923 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
924 precno = prcx + reslevel->num_precincts_x * prcy;
926 if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
927 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
928 prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
932 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
933 qntsty->nguardbits, packetno++)) < 0)
940 case JPEG2000_PGOD_PCRL:
943 for (compno = 0; compno < s->ncomponents; compno++) {
944 Jpeg2000Component *comp = tile->comp + compno;
946 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
947 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
948 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
949 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
950 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
953 if (step_x >= 31 || step_y >= 31){
954 avpriv_request_sample(s->avctx, "PCRL with large step");
955 return AVERROR_PATCHWELCOME;
960 for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
961 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
962 for (compno = 0; compno < s->ncomponents; compno++) {
963 Jpeg2000Component *comp = tile->comp + compno;
964 int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
966 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
969 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
970 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
973 trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
974 try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
976 if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
977 (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
980 if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
981 (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
984 // check if a precinct exists
985 prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
986 prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
987 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
988 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
990 precno = prcx + reslevel->num_precincts_x * prcy;
992 if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
993 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
994 prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
997 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
998 qntsty->nguardbits, packetno++)) < 0)
1005 case JPEG2000_PGOD_CPRL:
1006 for (compno = 0; compno < s->ncomponents; compno++) {
1007 Jpeg2000Component *comp = tile->comp + compno;
1008 int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
1012 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1013 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1014 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1015 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
1016 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1018 if (step_x >= 31 || step_y >= 31){
1019 avpriv_request_sample(s->avctx, "CPRL with large step");
1020 return AVERROR_PATCHWELCOME;
1025 for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
1026 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
1027 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1028 unsigned prcx, prcy;
1031 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1032 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1034 trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
1035 try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
1037 if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
1038 (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
1041 if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
1042 (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
1045 // check if a precinct exists
1046 prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
1047 prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
1048 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
1049 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
1051 precno = prcx + reslevel->num_precincts_x * prcy;
1053 if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1054 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1055 prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1058 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1059 qntsty->nguardbits, packetno++)) < 0)
1068 av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
1072 static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
1074 int passno, res = 0;
1075 for (passno = 0; passno < cblk->npasses; passno++){
1079 dr = cblk->passes[passno].rate
1080 - (res ? cblk->passes[res-1].rate:0);
1081 dd = cblk->passes[passno].disto
1082 - (res ? cblk->passes[res-1].disto:0);
1084 if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
1090 static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
1092 int precno, compno, reslevelno, bandno, cblkno, lev;
1093 Jpeg2000CodingStyle *codsty = &s->codsty;
1095 for (compno = 0; compno < s->ncomponents; compno++){
1096 Jpeg2000Component *comp = tile->comp + compno;
1098 for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
1099 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1101 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
1102 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1103 int bandpos = bandno + (reslevelno > 0);
1104 Jpeg2000Band *band = reslevel->band + bandno;
1105 Jpeg2000Prec *prec = band->prec + precno;
1107 for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
1108 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1110 cblk->ninclpasses = getcut(cblk, s->lambda,
1111 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
1119 static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
1121 int compno, reslevelno, bandno, ret;
1122 Jpeg2000T1Context t1;
1123 Jpeg2000CodingStyle *codsty = &s->codsty;
1124 for (compno = 0; compno < s->ncomponents; compno++){
1125 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1127 t1.stride = (1<<codsty->log2_cblk_width) + 2;
1129 av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
1130 if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
1132 av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
1134 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
1135 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1137 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1138 Jpeg2000Band *band = reslevel->band + bandno;
1139 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
1140 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
1141 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
1143 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
1144 band->coord[1][1]) - band->coord[1][0] + yy0;
1146 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
1149 bandpos = bandno + (reslevelno > 0);
1151 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
1152 if (reslevelno == 0 || bandno == 1)
1155 xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
1157 xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
1158 band->coord[0][1]) - band->coord[0][0] + xx0;
1160 for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
1162 if (codsty->transform == FF_DWT53){
1163 for (y = yy0; y < yy1; y++){
1164 int *ptr = t1.data + (y-yy0)*t1.stride;
1165 for (x = xx0; x < xx1; x++){
1166 *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] * (1 << NMSEDEC_FRACBITS);
1170 for (y = yy0; y < yy1; y++){
1171 int *ptr = t1.data + (y-yy0)*t1.stride;
1172 for (x = xx0; x < xx1; x++){
1173 *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
1174 *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
1179 if (!prec->cblk[cblkno].data)
1180 prec->cblk[cblkno].data = av_malloc(1 + 8192);
1181 if (!prec->cblk[cblkno].passes)
1182 prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
1183 if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
1184 return AVERROR(ENOMEM);
1185 encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
1186 bandpos, codsty->nreslevels - reslevelno - 1);
1188 xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
1191 yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
1195 av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
1198 av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
1199 truncpasses(s, tile);
1200 if ((ret = encode_packets(s, tile, tileno)) < 0)
1202 av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
1206 static void cleanup(Jpeg2000EncoderContext *s)
1209 Jpeg2000CodingStyle *codsty = &s->codsty;
1211 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1212 for (compno = 0; compno < s->ncomponents; compno++){
1213 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1214 ff_jpeg2000_cleanup(comp, codsty);
1216 av_freep(&s->tile[tileno].comp);
1221 static void reinit(Jpeg2000EncoderContext *s)
1224 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1225 Jpeg2000Tile *tile = s->tile + tileno;
1226 for (compno = 0; compno < s->ncomponents; compno++)
1227 ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
1231 static void update_size(uint8_t *size, const uint8_t *end)
1233 AV_WB32(size, end-size);
1236 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1237 const AVFrame *pict, int *got_packet)
1240 Jpeg2000EncoderContext *s = avctx->priv_data;
1241 uint8_t *chunkstart, *jp2cstart, *jp2hstart;
1243 if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
1247 s->buf = s->buf_start = pkt->data;
1248 s->buf_end = pkt->data + pkt->size;
1252 s->lambda = s->picture->quality * LAMBDA_SCALE;
1254 if (avctx->pix_fmt == AV_PIX_FMT_BGR48 || avctx->pix_fmt == AV_PIX_FMT_GRAY16)
1261 if (s->format == CODEC_JP2) {
1262 av_assert0(s->buf == pkt->data);
1264 bytestream_put_be32(&s->buf, 0x0000000C);
1265 bytestream_put_be32(&s->buf, 0x6A502020);
1266 bytestream_put_be32(&s->buf, 0x0D0A870A);
1268 chunkstart = s->buf;
1269 bytestream_put_be32(&s->buf, 0);
1270 bytestream_put_buffer(&s->buf, "ftyp", 4);
1271 bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
1272 bytestream_put_be32(&s->buf, 0);
1273 bytestream_put_buffer(&s->buf, "jp2\040", 4);
1274 update_size(chunkstart, s->buf);
1277 bytestream_put_be32(&s->buf, 0);
1278 bytestream_put_buffer(&s->buf, "jp2h", 4);
1280 chunkstart = s->buf;
1281 bytestream_put_be32(&s->buf, 0);
1282 bytestream_put_buffer(&s->buf, "ihdr", 4);
1283 bytestream_put_be32(&s->buf, avctx->height);
1284 bytestream_put_be32(&s->buf, avctx->width);
1285 bytestream_put_be16(&s->buf, s->ncomponents);
1286 bytestream_put_byte(&s->buf, s->cbps[0]);
1287 bytestream_put_byte(&s->buf, 7);
1288 bytestream_put_byte(&s->buf, 0);
1289 bytestream_put_byte(&s->buf, 0);
1290 update_size(chunkstart, s->buf);
1292 chunkstart = s->buf;
1293 bytestream_put_be32(&s->buf, 0);
1294 bytestream_put_buffer(&s->buf, "colr", 4);
1295 bytestream_put_byte(&s->buf, 1);
1296 bytestream_put_byte(&s->buf, 0);
1297 bytestream_put_byte(&s->buf, 0);
1298 if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1299 bytestream_put_be32(&s->buf, 16);
1300 } else if (s->ncomponents == 1) {
1301 bytestream_put_be32(&s->buf, 17);
1303 bytestream_put_be32(&s->buf, 18);
1305 update_size(chunkstart, s->buf);
1306 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1308 uint8_t *palette = pict->data[1];
1309 chunkstart = s->buf;
1310 bytestream_put_be32(&s->buf, 0);
1311 bytestream_put_buffer(&s->buf, "pclr", 4);
1312 bytestream_put_be16(&s->buf, AVPALETTE_COUNT);
1313 bytestream_put_byte(&s->buf, 3); // colour channels
1314 bytestream_put_be24(&s->buf, 0x070707); //colour depths
1315 for (i = 0; i < AVPALETTE_COUNT; i++) {
1316 bytestream_put_be24(&s->buf, HAVE_BIGENDIAN ? AV_RB24(palette + 1) : AV_RL24(palette));
1319 update_size(chunkstart, s->buf);
1320 chunkstart = s->buf;
1321 bytestream_put_be32(&s->buf, 0);
1322 bytestream_put_buffer(&s->buf, "cmap", 4);
1323 for (i = 0; i < 3; i++) {
1324 bytestream_put_be16(&s->buf, 0); // component
1325 bytestream_put_byte(&s->buf, 1); // palette mapping
1326 bytestream_put_byte(&s->buf, i); // index
1328 update_size(chunkstart, s->buf);
1330 update_size(jp2hstart, s->buf);
1333 bytestream_put_be32(&s->buf, 0);
1334 bytestream_put_buffer(&s->buf, "jp2c", 4);
1337 if (s->buf_end - s->buf < 2)
1339 bytestream_put_be16(&s->buf, JPEG2000_SOC);
1340 if ((ret = put_siz(s)) < 0)
1342 if ((ret = put_cod(s)) < 0)
1344 if ((ret = put_qcd(s, 0)) < 0)
1346 if ((ret = put_com(s, 0)) < 0)
1349 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1351 if (!(psotptr = put_sot(s, tileno)))
1353 if (s->buf_end - s->buf < 2)
1355 bytestream_put_be16(&s->buf, JPEG2000_SOD);
1356 if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1358 bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1360 if (s->buf_end - s->buf < 2)
1362 bytestream_put_be16(&s->buf, JPEG2000_EOC);
1364 if (s->format == CODEC_JP2)
1365 update_size(jp2cstart, s->buf);
1367 av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1368 pkt->size = s->buf - s->buf_start;
1369 pkt->flags |= AV_PKT_FLAG_KEY;
1375 static av_cold int j2kenc_init(AVCodecContext *avctx)
1378 Jpeg2000EncoderContext *s = avctx->priv_data;
1379 Jpeg2000CodingStyle *codsty = &s->codsty;
1380 Jpeg2000QuantStyle *qntsty = &s->qntsty;
1383 av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1385 #if FF_API_PRIVATE_OPT
1386 FF_DISABLE_DEPRECATION_WARNINGS
1387 if (avctx->prediction_method)
1388 s->pred = avctx->prediction_method;
1389 FF_ENABLE_DEPRECATION_WARNINGS
1392 if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (s->pred != FF_DWT97_INT || s->format != CODEC_JP2)) {
1393 av_log(s->avctx, AV_LOG_WARNING, "Forcing lossless jp2 for pal8\n");
1394 s->pred = FF_DWT97_INT;
1395 s->format = CODEC_JP2;
1399 // TODO: implement setting non-standard precinct size
1400 memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1401 memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1402 codsty->nreslevels2decode=
1403 codsty->nreslevels = 7;
1404 codsty->log2_cblk_width = 4;
1405 codsty->log2_cblk_height = 4;
1406 codsty->transform = s->pred ? FF_DWT53 : FF_DWT97_INT;
1408 qntsty->nguardbits = 1;
1410 if ((s->tile_width & (s->tile_width -1)) ||
1411 (s->tile_height & (s->tile_height-1))) {
1412 av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
1415 if (codsty->transform == FF_DWT53)
1416 qntsty->quantsty = JPEG2000_QSTY_NONE;
1418 qntsty->quantsty = JPEG2000_QSTY_SE;
1420 s->width = avctx->width;
1421 s->height = avctx->height;
1423 for (i = 0; i < 3; i++) {
1424 if (avctx->pix_fmt == AV_PIX_FMT_GRAY16 || avctx->pix_fmt == AV_PIX_FMT_RGB48)
1430 if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_RGB48){
1432 } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16){
1434 } else{ // planar YUV
1437 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
1438 s->chroma_shift, s->chroma_shift + 1);
1443 ff_jpeg2000_init_tier1_luts();
1444 ff_mqc_init_context_tables();
1447 init_quantization(s);
1448 if ((ret=init_tiles(s)) < 0)
1451 av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1456 static int j2kenc_destroy(AVCodecContext *avctx)
1458 Jpeg2000EncoderContext *s = avctx->priv_data;
1464 // taken from the libopenjpeg wraper so it matches
1466 #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1467 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1468 static const AVOption options[] = {
1469 { "format", "Codec Format", OFFSET(format), AV_OPT_TYPE_INT, { .i64 = CODEC_JP2 }, CODEC_J2K, CODEC_JP2, VE, "format" },
1470 { "j2k", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K }, 0, 0, VE, "format" },
1471 { "jp2", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2 }, 0, 0, VE, "format" },
1472 { "tile_width", "Tile Width", OFFSET(tile_width), AV_OPT_TYPE_INT, { .i64 = 256 }, 1, 1<<30, VE, },
1473 { "tile_height", "Tile Height", OFFSET(tile_height), AV_OPT_TYPE_INT, { .i64 = 256 }, 1, 1<<30, VE, },
1474 { "pred", "DWT Type", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, "pred" },
1475 { "dwt97int", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
1476 { "dwt53", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
1477 { "sop", "SOP marker", OFFSET(sop), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, },
1478 { "eph", "EPH marker", OFFSET(eph), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, },
1479 { "prog", "Progression Order", OFFSET(prog), AV_OPT_TYPE_INT, { .i64 = 0 }, JPEG2000_PGOD_LRCP, JPEG2000_PGOD_CPRL, VE, "prog" },
1480 { "lrcp", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_LRCP }, 0, 0, VE, "prog" },
1481 { "rlcp", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_RLCP }, 0, 0, VE, "prog" },
1482 { "rpcl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_RPCL }, 0, 0, VE, "prog" },
1483 { "pcrl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_PCRL }, 0, 0, VE, "prog" },
1484 { "cprl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_CPRL }, 0, 0, VE, "prog" },
1488 static const AVClass j2k_class = {
1489 .class_name = "jpeg 2000 encoder",
1490 .item_name = av_default_item_name,
1492 .version = LIBAVUTIL_VERSION_INT,
1495 AVCodec ff_jpeg2000_encoder = {
1497 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1498 .type = AVMEDIA_TYPE_VIDEO,
1499 .id = AV_CODEC_ID_JPEG2000,
1500 .priv_data_size = sizeof(Jpeg2000EncoderContext),
1501 .init = j2kenc_init,
1502 .encode2 = encode_frame,
1503 .close = j2kenc_destroy,
1504 .pix_fmts = (const enum AVPixelFormat[]) {
1505 AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1506 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
1507 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
1509 AV_PIX_FMT_RGB48, AV_PIX_FMT_GRAY16,
1512 .priv_class = &j2k_class,