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;
253 if (curval > node->temp_val)
254 node->temp_val = curval;
256 curval = node->temp_val;
259 if (node->val >= threshold) {
260 put_bits(s, 0, threshold - curval);
263 put_bits(s, 0, node->val - curval);
271 node->temp_val = curval;
278 /** update the value in node */
279 static void tag_tree_update(Jpeg2000TgtNode *node)
282 while (node->parent){
283 if (node->parent->val <= node->val)
285 node->parent->val = node->val;
291 static int put_siz(Jpeg2000EncoderContext *s)
295 if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
298 bytestream_put_be16(&s->buf, JPEG2000_SIZ);
299 bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
300 bytestream_put_be16(&s->buf, 0); // Rsiz
301 bytestream_put_be32(&s->buf, s->width); // width
302 bytestream_put_be32(&s->buf, s->height); // height
303 bytestream_put_be32(&s->buf, 0); // X0Siz
304 bytestream_put_be32(&s->buf, 0); // Y0Siz
306 bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
307 bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
308 bytestream_put_be32(&s->buf, 0); // XT0Siz
309 bytestream_put_be32(&s->buf, 0); // YT0Siz
310 bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
312 for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
313 bytestream_put_byte(&s->buf, s->cbps[i] - 1);
314 bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
315 bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
320 static int put_cod(Jpeg2000EncoderContext *s)
322 Jpeg2000CodingStyle *codsty = &s->codsty;
325 if (s->buf_end - s->buf < 14)
328 bytestream_put_be16(&s->buf, JPEG2000_COD);
329 bytestream_put_be16(&s->buf, 12); // Lcod
331 scod |= JPEG2000_CSTY_SOP;
333 scod |= JPEG2000_CSTY_EPH;
334 bytestream_put_byte(&s->buf, scod); // Scod
336 bytestream_put_byte(&s->buf, s->prog); // progression level
337 bytestream_put_be16(&s->buf, 1); // num of layers
338 if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
339 bytestream_put_byte(&s->buf, 0); // unspecified
341 bytestream_put_byte(&s->buf, 0); // unspecified
344 bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
345 bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
346 bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
347 bytestream_put_byte(&s->buf, 0); // cblk style
348 bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
352 static int put_qcd(Jpeg2000EncoderContext *s, int compno)
355 Jpeg2000CodingStyle *codsty = &s->codsty;
356 Jpeg2000QuantStyle *qntsty = &s->qntsty;
358 if (qntsty->quantsty == JPEG2000_QSTY_NONE)
359 size = 4 + 3 * (codsty->nreslevels-1);
361 size = 5 + 6 * (codsty->nreslevels-1);
363 if (s->buf_end - s->buf < size + 2)
366 bytestream_put_be16(&s->buf, JPEG2000_QCD);
367 bytestream_put_be16(&s->buf, size); // LQcd
368 bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty); // Sqcd
369 if (qntsty->quantsty == JPEG2000_QSTY_NONE)
370 for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
371 bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
373 for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
374 bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
378 static int put_com(Jpeg2000EncoderContext *s, int compno)
380 int size = 4 + strlen(LIBAVCODEC_IDENT);
382 if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
385 if (s->buf_end - s->buf < size + 2)
388 bytestream_put_be16(&s->buf, JPEG2000_COM);
389 bytestream_put_be16(&s->buf, size);
390 bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
392 bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
397 static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
401 if (s->buf_end - s->buf < 12)
404 bytestream_put_be16(&s->buf, JPEG2000_SOT);
405 bytestream_put_be16(&s->buf, 10); // Lsot
406 bytestream_put_be16(&s->buf, tileno); // Isot
409 bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
411 bytestream_put_byte(&s->buf, 0); // TPsot
412 bytestream_put_byte(&s->buf, 1); // TNsot
417 * compute the sizes of tiles, resolution levels, bands, etc.
418 * allocate memory for them
419 * divide the input image into tile-components
421 static int init_tiles(Jpeg2000EncoderContext *s)
423 int tileno, tilex, tiley, compno;
424 Jpeg2000CodingStyle *codsty = &s->codsty;
425 Jpeg2000QuantStyle *qntsty = &s->qntsty;
427 s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
428 s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
430 s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
432 return AVERROR(ENOMEM);
433 for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
434 for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
435 Jpeg2000Tile *tile = s->tile + tileno;
437 tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
439 return AVERROR(ENOMEM);
440 for (compno = 0; compno < s->ncomponents; compno++){
441 Jpeg2000Component *comp = tile->comp + compno;
444 comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
445 comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
446 comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
447 comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
449 for (i = 0; i < 2; i++)
450 for (j = 0; j < 2; j++)
451 comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
453 if ((ret = ff_jpeg2000_init_component(comp,
457 compno?1<<s->chroma_shift[0]:1,
458 compno?1<<s->chroma_shift[1]:1,
467 #define COPY_FRAME(D, PIXEL) \
468 static void copy_frame_ ##D(Jpeg2000EncoderContext *s) \
470 int tileno, compno, i, y, x; \
472 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){ \
473 Jpeg2000Tile *tile = s->tile + tileno; \
475 for (compno = 0; compno < s->ncomponents; compno++){ \
476 Jpeg2000Component *comp = tile->comp + compno; \
477 int *dst = comp->i_data; \
478 int cbps = s->cbps[compno]; \
479 line = (PIXEL*)s->picture->data[compno] \
480 + comp->coord[1][0] * (s->picture->linesize[compno] / sizeof(PIXEL)) \
481 + comp->coord[0][0]; \
482 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){ \
484 for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++) \
485 *dst++ = *ptr++ - (1 << (cbps - 1)); \
486 line += s->picture->linesize[compno] / sizeof(PIXEL); \
490 line = (PIXEL*)s->picture->data[0] + tile->comp[0].coord[1][0] * (s->picture->linesize[0] / sizeof(PIXEL)) \
491 + tile->comp[0].coord[0][0] * s->ncomponents; \
494 for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){ \
496 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){ \
497 for (compno = 0; compno < s->ncomponents; compno++){ \
498 int cbps = s->cbps[compno]; \
499 tile->comp[compno].i_data[i] = *ptr++ - (1 << (cbps - 1)); \
502 line += s->picture->linesize[0] / sizeof(PIXEL); \
508 COPY_FRAME(8, uint8_t)
509 COPY_FRAME(16, uint16_t)
511 static void init_quantization(Jpeg2000EncoderContext *s)
513 int compno, reslevelno, bandno;
514 Jpeg2000QuantStyle *qntsty = &s->qntsty;
515 Jpeg2000CodingStyle *codsty = &s->codsty;
517 for (compno = 0; compno < s->ncomponents; compno++){
519 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
520 int nbands, lev = codsty->nreslevels - reslevelno - 1;
521 nbands = reslevelno ? 3 : 1;
522 for (bandno = 0; bandno < nbands; bandno++, gbandno++){
525 if (codsty->transform == FF_DWT97_INT){
526 int bandpos = bandno + (reslevelno>0),
527 ss = 81920000 / dwt_norms[0][bandpos][lev],
529 mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
530 expn = s->cbps[compno] - log + 13;
532 expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
534 qntsty->expn[gbandno] = expn;
535 qntsty->mant[gbandno] = mant;
541 static void init_luts(void)
544 mask = ~((1<<NMSEDEC_FRACBITS)-1);
546 for (i = 0; i < (1 << NMSEDEC_BITS); i++){
547 lut_nmsedec_sig[i] = FFMAX((3 * i << (13 - NMSEDEC_FRACBITS)) - (9 << 11), 0);
548 lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
550 a = (i >> (NMSEDEC_BITS-2)&2) + 1;
551 lut_nmsedec_ref[i] = FFMAX((a - 2) * (i << (13 - NMSEDEC_FRACBITS)) +
552 (1 << 13) - (a * a << 11), 0);
553 lut_nmsedec_ref0[i] = FFMAX(((i * i - (i << NMSEDEC_BITS) + (1 << 2 * NMSEDEC_FRACBITS) + (1 << (NMSEDEC_FRACBITS - 1))) & mask)
558 /* tier-1 routines */
559 static int getnmsedec_sig(int x, int bpno)
561 if (bpno > NMSEDEC_FRACBITS)
562 return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
563 return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
566 static int getnmsedec_ref(int x, int bpno)
568 if (bpno > NMSEDEC_FRACBITS)
569 return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
570 return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
573 static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
575 int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
576 for (y0 = 0; y0 < height; y0 += 4)
577 for (x = 0; x < width; x++)
578 for (y = y0; y < height && y < y0+4; y++){
579 if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
580 int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
581 bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
582 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
585 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
586 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
587 *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
588 ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
590 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
595 static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
597 int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
598 for (y0 = 0; y0 < height; y0 += 4)
599 for (x = 0; x < width; x++)
600 for (y = y0; y < height && y < y0+4; y++)
601 if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
602 int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
603 *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
604 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
605 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
609 static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
611 int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
612 for (y0 = 0; y0 < height; y0 += 4)
613 for (x = 0; x < width; x++){
614 if (y0 + 3 < height && !(
615 (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
616 (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
617 (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
618 (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
622 for (rlen = 0; rlen < 4; rlen++)
623 if (t1->data[(y0+rlen) * t1->stride + x] & mask)
625 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
628 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
629 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
630 for (y = y0 + rlen; y < y0 + 4; y++){
631 if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
632 int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
634 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
635 if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
637 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
638 *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
639 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
640 ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
643 t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
646 for (y = y0; y < y0 + 4 && y < height; y++){
647 if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
648 int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
649 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
650 if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
652 int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
653 *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
654 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
655 ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
658 t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
664 static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
665 int width, int height, int bandpos, int lev)
667 int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
670 memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
672 for (y = 0; y < height; y++){
673 for (x = 0; x < width; x++){
674 if (t1->data[(y) * t1->stride + x] < 0){
675 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
676 t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
678 max = FFMAX(max, t1->data[(y) * t1->stride + x]);
683 cblk->nonzerobits = 0;
686 cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
687 bpno = cblk->nonzerobits - 1;
691 ff_mqc_initenc(&t1->mqc, cblk->data + 1);
693 for (passno = 0; bpno >= 0; passno++){
697 case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
699 case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
701 case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
705 cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
706 wmsedec += (int64_t)nmsedec << (2*bpno);
707 cblk->passes[passno].disto = wmsedec;
714 cblk->npasses = passno;
715 cblk->ninclpasses = passno;
718 cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
721 /* tier-2 routines: */
723 static void putnumpasses(Jpeg2000EncoderContext *s, int n)
730 put_num(s, 0xc | (n-3), 4);
732 put_num(s, 0x1e0 | (n-6), 9);
734 put_num(s, 0xff80 | (n-37), 16);
738 static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
739 uint8_t *expn, int numgbits, int packetno)
741 int bandno, empty = 1;
747 bytestream_put_be16(&s->buf, JPEG2000_SOP);
748 bytestream_put_be16(&s->buf, 4);
749 bytestream_put_be16(&s->buf, packetno);
753 // is the packet empty?
754 for (bandno = 0; bandno < rlevel->nbands; bandno++){
755 if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
756 && rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
762 put_bits(s, !empty, 1);
768 for (bandno = 0; bandno < rlevel->nbands; bandno++){
769 Jpeg2000Band *band = rlevel->band + bandno;
770 Jpeg2000Prec *prec = band->prec + precno;
772 int cblknw = prec->nb_codeblocks_width;
774 if (band->coord[0][0] == band->coord[0][1]
775 || band->coord[1][0] == band->coord[1][1])
778 for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
779 for (xi = 0; xi < cblknw; xi++, pos++){
780 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
781 tag_tree_update(prec->cblkincl + pos);
782 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
783 tag_tree_update(prec->zerobits + pos);
787 for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
788 for (xi = 0; xi < cblknw; xi++, pos++){
789 int pad = 0, llen, length;
790 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
792 if (s->buf_end - s->buf < 20) // approximately
795 // inclusion information
796 tag_tree_code(s, prec->cblkincl + pos, 1);
797 if (!cblk->ninclpasses)
799 // zerobits information
800 tag_tree_code(s, prec->zerobits + pos, 100);
802 putnumpasses(s, cblk->ninclpasses);
804 length = cblk->passes[cblk->ninclpasses-1].rate;
805 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
810 // length of code block
811 put_bits(s, 1, llen);
813 put_num(s, length, av_log2(length)+1+pad);
819 bytestream_put_be16(&s->buf, JPEG2000_EPH);
822 for (bandno = 0; bandno < rlevel->nbands; bandno++){
823 Jpeg2000Band *band = rlevel->band + bandno;
824 Jpeg2000Prec *prec = band->prec + precno;
825 int yi, cblknw = prec->nb_codeblocks_width;
826 for (yi =0; yi < prec->nb_codeblocks_height; yi++){
828 for (xi = 0; xi < cblknw; xi++){
829 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
830 if (cblk->ninclpasses){
831 if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
833 bytestream_put_buffer(&s->buf, cblk->data + 1, cblk->passes[cblk->ninclpasses-1].rate
834 - cblk->passes[cblk->ninclpasses-1].flushed_len);
835 bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
836 cblk->passes[cblk->ninclpasses-1].flushed_len);
844 static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
846 int compno, reslevelno, ret;
847 Jpeg2000CodingStyle *codsty = &s->codsty;
848 Jpeg2000QuantStyle *qntsty = &s->qntsty;
852 int tile_coord[2][2];
853 int col = tileno % s->numXtiles;
854 int row = tileno / s->numXtiles;
856 tile_coord[0][0] = col * s->tile_width;
857 tile_coord[0][1] = FFMIN(tile_coord[0][0] + s->tile_width, s->width);
858 tile_coord[1][0] = row * s->tile_height;
859 tile_coord[1][1] = FFMIN(tile_coord[1][0] + s->tile_height, s->height);
861 av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
862 // lay-rlevel-comp-pos progression
864 case JPEG2000_PGOD_LRCP:
865 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
866 for (compno = 0; compno < s->ncomponents; compno++){
868 Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
869 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
870 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
871 qntsty->nguardbits, packetno++)) < 0)
877 case JPEG2000_PGOD_RLCP:
878 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
879 for (compno = 0; compno < s->ncomponents; compno++){
881 Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
882 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
883 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
884 qntsty->nguardbits, packetno++)) < 0)
890 case JPEG2000_PGOD_RPCL:
891 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
895 for (compno = 0; compno < s->ncomponents; compno++) {
896 Jpeg2000Component *comp = tile->comp + compno;
897 if (reslevelno < codsty->nreslevels) {
898 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
899 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
900 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
901 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
907 for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
908 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
909 for (compno = 0; compno < s->ncomponents; compno++) {
910 Jpeg2000Component *comp = tile->comp + compno;
911 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
912 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
913 int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
917 trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
918 try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
920 if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
921 (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
924 if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
925 (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
928 // check if a precinct exists
929 prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
930 prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
931 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
932 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
933 precno = prcx + reslevel->num_precincts_x * prcy;
935 if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
936 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
937 prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
941 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
942 qntsty->nguardbits, packetno++)) < 0)
949 case JPEG2000_PGOD_PCRL:
952 for (compno = 0; compno < s->ncomponents; compno++) {
953 Jpeg2000Component *comp = tile->comp + compno;
955 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
956 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
957 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
958 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
959 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
962 if (step_x >= 31 || step_y >= 31){
963 avpriv_request_sample(s->avctx, "PCRL with large step");
964 return AVERROR_PATCHWELCOME;
969 for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
970 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
971 for (compno = 0; compno < s->ncomponents; compno++) {
972 Jpeg2000Component *comp = tile->comp + compno;
973 int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
975 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
978 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
979 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
982 trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
983 try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
985 if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
986 (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
989 if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
990 (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
993 // check if a precinct exists
994 prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
995 prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
996 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
997 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
999 precno = prcx + reslevel->num_precincts_x * prcy;
1001 if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1002 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1003 prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1006 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1007 qntsty->nguardbits, packetno++)) < 0)
1014 case JPEG2000_PGOD_CPRL:
1015 for (compno = 0; compno < s->ncomponents; compno++) {
1016 Jpeg2000Component *comp = tile->comp + compno;
1017 int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
1021 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1022 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1023 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1024 step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
1025 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1027 if (step_x >= 31 || step_y >= 31){
1028 avpriv_request_sample(s->avctx, "CPRL with large step");
1029 return AVERROR_PATCHWELCOME;
1034 for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
1035 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
1036 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1037 unsigned prcx, prcy;
1040 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
1041 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1043 trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
1044 try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
1046 if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
1047 (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
1050 if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
1051 (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
1054 // check if a precinct exists
1055 prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
1056 prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
1057 prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
1058 prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
1060 precno = prcx + reslevel->num_precincts_x * prcy;
1062 if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1063 av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1064 prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1067 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1068 qntsty->nguardbits, packetno++)) < 0)
1077 av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
1081 static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
1083 int passno, res = 0;
1084 for (passno = 0; passno < cblk->npasses; passno++){
1088 dr = cblk->passes[passno].rate
1089 - (res ? cblk->passes[res-1].rate:0);
1090 dd = cblk->passes[passno].disto
1091 - (res ? cblk->passes[res-1].disto:0);
1093 if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
1099 static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
1101 int precno, compno, reslevelno, bandno, cblkno, lev;
1102 Jpeg2000CodingStyle *codsty = &s->codsty;
1104 for (compno = 0; compno < s->ncomponents; compno++){
1105 Jpeg2000Component *comp = tile->comp + compno;
1107 for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
1108 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1110 for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
1111 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1112 int bandpos = bandno + (reslevelno > 0);
1113 Jpeg2000Band *band = reslevel->band + bandno;
1114 Jpeg2000Prec *prec = band->prec + precno;
1116 for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
1117 Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1119 cblk->ninclpasses = getcut(cblk, s->lambda,
1120 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
1128 static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
1130 int compno, reslevelno, bandno, ret;
1131 Jpeg2000T1Context t1;
1132 Jpeg2000CodingStyle *codsty = &s->codsty;
1133 for (compno = 0; compno < s->ncomponents; compno++){
1134 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1136 t1.stride = (1<<codsty->log2_cblk_width) + 2;
1138 av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
1139 if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
1141 av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
1143 for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
1144 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1146 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1147 Jpeg2000Band *band = reslevel->band + bandno;
1148 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
1149 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
1150 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
1152 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
1153 band->coord[1][1]) - band->coord[1][0] + yy0;
1155 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
1158 bandpos = bandno + (reslevelno > 0);
1160 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
1161 if (reslevelno == 0 || bandno == 1)
1164 xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
1166 xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
1167 band->coord[0][1]) - band->coord[0][0] + xx0;
1169 for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
1171 if (codsty->transform == FF_DWT53){
1172 for (y = yy0; y < yy1; y++){
1173 int *ptr = t1.data + (y-yy0)*t1.stride;
1174 for (x = xx0; x < xx1; x++){
1175 *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] * (1 << NMSEDEC_FRACBITS);
1179 for (y = yy0; y < yy1; y++){
1180 int *ptr = t1.data + (y-yy0)*t1.stride;
1181 for (x = xx0; x < xx1; x++){
1182 *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
1183 *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
1188 if (!prec->cblk[cblkno].data)
1189 prec->cblk[cblkno].data = av_malloc(1 + 8192);
1190 if (!prec->cblk[cblkno].passes)
1191 prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
1192 if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
1193 return AVERROR(ENOMEM);
1194 encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
1195 bandpos, codsty->nreslevels - reslevelno - 1);
1197 xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
1200 yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
1204 av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
1207 av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
1208 truncpasses(s, tile);
1209 if ((ret = encode_packets(s, tile, tileno)) < 0)
1211 av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
1215 static void cleanup(Jpeg2000EncoderContext *s)
1218 Jpeg2000CodingStyle *codsty = &s->codsty;
1220 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1221 for (compno = 0; compno < s->ncomponents; compno++){
1222 Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1223 ff_jpeg2000_cleanup(comp, codsty);
1225 av_freep(&s->tile[tileno].comp);
1230 static void reinit(Jpeg2000EncoderContext *s)
1233 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1234 Jpeg2000Tile *tile = s->tile + tileno;
1235 for (compno = 0; compno < s->ncomponents; compno++)
1236 ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
1240 static void update_size(uint8_t *size, const uint8_t *end)
1242 AV_WB32(size, end-size);
1245 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1246 const AVFrame *pict, int *got_packet)
1249 Jpeg2000EncoderContext *s = avctx->priv_data;
1250 uint8_t *chunkstart, *jp2cstart, *jp2hstart;
1252 if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
1256 s->buf = s->buf_start = pkt->data;
1257 s->buf_end = pkt->data + pkt->size;
1261 s->lambda = s->picture->quality * LAMBDA_SCALE;
1263 if (avctx->pix_fmt == AV_PIX_FMT_BGR48 || avctx->pix_fmt == AV_PIX_FMT_GRAY16)
1270 if (s->format == CODEC_JP2) {
1271 av_assert0(s->buf == pkt->data);
1273 bytestream_put_be32(&s->buf, 0x0000000C);
1274 bytestream_put_be32(&s->buf, 0x6A502020);
1275 bytestream_put_be32(&s->buf, 0x0D0A870A);
1277 chunkstart = s->buf;
1278 bytestream_put_be32(&s->buf, 0);
1279 bytestream_put_buffer(&s->buf, "ftyp", 4);
1280 bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
1281 bytestream_put_be32(&s->buf, 0);
1282 bytestream_put_buffer(&s->buf, "jp2\040", 4);
1283 update_size(chunkstart, s->buf);
1286 bytestream_put_be32(&s->buf, 0);
1287 bytestream_put_buffer(&s->buf, "jp2h", 4);
1289 chunkstart = s->buf;
1290 bytestream_put_be32(&s->buf, 0);
1291 bytestream_put_buffer(&s->buf, "ihdr", 4);
1292 bytestream_put_be32(&s->buf, avctx->height);
1293 bytestream_put_be32(&s->buf, avctx->width);
1294 bytestream_put_be16(&s->buf, s->ncomponents);
1295 bytestream_put_byte(&s->buf, s->cbps[0]);
1296 bytestream_put_byte(&s->buf, 7);
1297 bytestream_put_byte(&s->buf, 0);
1298 bytestream_put_byte(&s->buf, 0);
1299 update_size(chunkstart, s->buf);
1301 chunkstart = s->buf;
1302 bytestream_put_be32(&s->buf, 0);
1303 bytestream_put_buffer(&s->buf, "colr", 4);
1304 bytestream_put_byte(&s->buf, 1);
1305 bytestream_put_byte(&s->buf, 0);
1306 bytestream_put_byte(&s->buf, 0);
1307 if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1308 bytestream_put_be32(&s->buf, 16);
1309 } else if (s->ncomponents == 1) {
1310 bytestream_put_be32(&s->buf, 17);
1312 bytestream_put_be32(&s->buf, 18);
1314 update_size(chunkstart, s->buf);
1315 if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1317 uint8_t *palette = pict->data[1];
1318 chunkstart = s->buf;
1319 bytestream_put_be32(&s->buf, 0);
1320 bytestream_put_buffer(&s->buf, "pclr", 4);
1321 bytestream_put_be16(&s->buf, AVPALETTE_COUNT);
1322 bytestream_put_byte(&s->buf, 3); // colour channels
1323 bytestream_put_be24(&s->buf, 0x070707); //colour depths
1324 for (i = 0; i < AVPALETTE_COUNT; i++) {
1325 bytestream_put_be24(&s->buf, HAVE_BIGENDIAN ? AV_RB24(palette + 1) : AV_RL24(palette));
1328 update_size(chunkstart, s->buf);
1329 chunkstart = s->buf;
1330 bytestream_put_be32(&s->buf, 0);
1331 bytestream_put_buffer(&s->buf, "cmap", 4);
1332 for (i = 0; i < 3; i++) {
1333 bytestream_put_be16(&s->buf, 0); // component
1334 bytestream_put_byte(&s->buf, 1); // palette mapping
1335 bytestream_put_byte(&s->buf, i); // index
1337 update_size(chunkstart, s->buf);
1339 update_size(jp2hstart, s->buf);
1342 bytestream_put_be32(&s->buf, 0);
1343 bytestream_put_buffer(&s->buf, "jp2c", 4);
1346 if (s->buf_end - s->buf < 2)
1348 bytestream_put_be16(&s->buf, JPEG2000_SOC);
1349 if ((ret = put_siz(s)) < 0)
1351 if ((ret = put_cod(s)) < 0)
1353 if ((ret = put_qcd(s, 0)) < 0)
1355 if ((ret = put_com(s, 0)) < 0)
1358 for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1360 if (!(psotptr = put_sot(s, tileno)))
1362 if (s->buf_end - s->buf < 2)
1364 bytestream_put_be16(&s->buf, JPEG2000_SOD);
1365 if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1367 bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1369 if (s->buf_end - s->buf < 2)
1371 bytestream_put_be16(&s->buf, JPEG2000_EOC);
1373 if (s->format == CODEC_JP2)
1374 update_size(jp2cstart, s->buf);
1376 av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1377 pkt->size = s->buf - s->buf_start;
1378 pkt->flags |= AV_PKT_FLAG_KEY;
1384 static av_cold int j2kenc_init(AVCodecContext *avctx)
1387 Jpeg2000EncoderContext *s = avctx->priv_data;
1388 Jpeg2000CodingStyle *codsty = &s->codsty;
1389 Jpeg2000QuantStyle *qntsty = &s->qntsty;
1392 av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1394 #if FF_API_PRIVATE_OPT
1395 FF_DISABLE_DEPRECATION_WARNINGS
1396 if (avctx->prediction_method)
1397 s->pred = avctx->prediction_method;
1398 FF_ENABLE_DEPRECATION_WARNINGS
1401 if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (s->pred != FF_DWT97_INT || s->format != CODEC_JP2)) {
1402 av_log(s->avctx, AV_LOG_WARNING, "Forcing lossless jp2 for pal8\n");
1403 s->pred = FF_DWT97_INT;
1404 s->format = CODEC_JP2;
1408 // TODO: implement setting non-standard precinct size
1409 memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1410 memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1411 codsty->nreslevels2decode=
1412 codsty->nreslevels = 7;
1413 codsty->log2_cblk_width = 4;
1414 codsty->log2_cblk_height = 4;
1415 codsty->transform = s->pred ? FF_DWT53 : FF_DWT97_INT;
1417 qntsty->nguardbits = 1;
1419 if ((s->tile_width & (s->tile_width -1)) ||
1420 (s->tile_height & (s->tile_height-1))) {
1421 av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
1424 if (codsty->transform == FF_DWT53)
1425 qntsty->quantsty = JPEG2000_QSTY_NONE;
1427 qntsty->quantsty = JPEG2000_QSTY_SE;
1429 s->width = avctx->width;
1430 s->height = avctx->height;
1432 for (i = 0; i < 3; i++) {
1433 if (avctx->pix_fmt == AV_PIX_FMT_GRAY16 || avctx->pix_fmt == AV_PIX_FMT_RGB48)
1439 if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_RGB48){
1441 } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16){
1443 } else{ // planar YUV
1446 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
1447 s->chroma_shift, s->chroma_shift + 1);
1452 ff_jpeg2000_init_tier1_luts();
1453 ff_mqc_init_context_tables();
1456 init_quantization(s);
1457 if ((ret=init_tiles(s)) < 0)
1460 av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1465 static int j2kenc_destroy(AVCodecContext *avctx)
1467 Jpeg2000EncoderContext *s = avctx->priv_data;
1473 // taken from the libopenjpeg wraper so it matches
1475 #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1476 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1477 static const AVOption options[] = {
1478 { "format", "Codec Format", OFFSET(format), AV_OPT_TYPE_INT, { .i64 = CODEC_JP2 }, CODEC_J2K, CODEC_JP2, VE, "format" },
1479 { "j2k", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K }, 0, 0, VE, "format" },
1480 { "jp2", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2 }, 0, 0, VE, "format" },
1481 { "tile_width", "Tile Width", OFFSET(tile_width), AV_OPT_TYPE_INT, { .i64 = 256 }, 1, 1<<30, VE, },
1482 { "tile_height", "Tile Height", OFFSET(tile_height), AV_OPT_TYPE_INT, { .i64 = 256 }, 1, 1<<30, VE, },
1483 { "pred", "DWT Type", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, "pred" },
1484 { "dwt97int", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
1485 { "dwt53", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
1486 { "sop", "SOP marker", OFFSET(sop), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, },
1487 { "eph", "EPH marker", OFFSET(eph), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, },
1488 { "prog", "Progression Order", OFFSET(prog), AV_OPT_TYPE_INT, { .i64 = 0 }, JPEG2000_PGOD_LRCP, JPEG2000_PGOD_CPRL, VE, "prog" },
1489 { "lrcp", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_LRCP }, 0, 0, VE, "prog" },
1490 { "rlcp", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_RLCP }, 0, 0, VE, "prog" },
1491 { "rpcl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_RPCL }, 0, 0, VE, "prog" },
1492 { "pcrl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_PCRL }, 0, 0, VE, "prog" },
1493 { "cprl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_CPRL }, 0, 0, VE, "prog" },
1497 static const AVClass j2k_class = {
1498 .class_name = "jpeg 2000 encoder",
1499 .item_name = av_default_item_name,
1501 .version = LIBAVUTIL_VERSION_INT,
1504 AVCodec ff_jpeg2000_encoder = {
1506 .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1507 .type = AVMEDIA_TYPE_VIDEO,
1508 .id = AV_CODEC_ID_JPEG2000,
1509 .priv_data_size = sizeof(Jpeg2000EncoderContext),
1510 .init = j2kenc_init,
1511 .encode2 = encode_frame,
1512 .close = j2kenc_destroy,
1513 .pix_fmts = (const enum AVPixelFormat[]) {
1514 AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1515 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
1516 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
1518 AV_PIX_FMT_RGB48, AV_PIX_FMT_GRAY16,
1521 .priv_class = &j2k_class,