]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kenc.c
Merge commit '97bf7c03b1338a867da52c159a2afecbdedcfa88'
[ffmpeg] / libavcodec / j2kenc.c
1 /*
2  * JPEG2000 image encoder
3  * Copyright (c) 2007 Kamil Nowosad
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * JPEG2000 image encoder
24  * @file
25  * @author Kamil Nowosad
26  */
27
28 #include <float.h>
29 #include "avcodec.h"
30 #include "internal.h"
31 #include "bytestream.h"
32 #include "j2k.h"
33 #include "libavutil/common.h"
34
35 #define NMSEDEC_BITS 7
36 #define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
37 #define WMSEDEC_SHIFT 13 ///< must be >= 13
38 #define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
39
40 static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
41            lut_nmsedec_ref0[1<<NMSEDEC_BITS],
42            lut_nmsedec_sig [1<<NMSEDEC_BITS],
43            lut_nmsedec_sig0[1<<NMSEDEC_BITS];
44
45 static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
46     {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
47      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
48      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
49      {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
50
51     {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
52      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
53      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
54      { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
55 };
56
57 typedef struct {
58    J2kComponent *comp;
59 } J2kTile;
60
61 typedef struct {
62     AVCodecContext *avctx;
63     AVFrame picture;
64
65     int width, height; ///< image width and height
66     uint8_t cbps[4]; ///< bits per sample in particular components
67     int chroma_shift[2];
68     uint8_t planar;
69     int ncomponents;
70     int tile_width, tile_height; ///< tile size
71     int numXtiles, numYtiles;
72
73     uint8_t *buf_start;
74     uint8_t *buf;
75     uint8_t *buf_end;
76     int bit_index;
77
78     int64_t lambda;
79
80     J2kCodingStyle codsty;
81     J2kQuantStyle  qntsty;
82
83     J2kTile *tile;
84 } J2kEncoderContext;
85
86
87 /* debug */
88 #if 0
89 #undef ifprintf
90 #undef printf
91
92 static void nspaces(FILE *fd, int n)
93 {
94     while(n--) putc(' ', fd);
95 }
96
97 static void printv(int *tab, int l)
98 {
99     int i;
100     for (i = 0; i < l; i++)
101         printf("%.3d ", tab[i]);
102     printf("\n");
103 }
104
105 static void printu(uint8_t *tab, int l)
106 {
107     int i;
108     for (i = 0; i < l; i++)
109         printf("%.3hd ", tab[i]);
110     printf("\n");
111 }
112
113 static void printcomp(J2kComponent *comp)
114 {
115     int i;
116     for (i = 0; i < comp->y1 - comp->y0; i++)
117         printv(comp->data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
118 }
119
120 static void dump(J2kEncoderContext *s, FILE *fd)
121 {
122     int tileno, compno, reslevelno, bandno, precno;
123     fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
124                 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
125                 "tiles:\n",
126             s->width, s->height, s->tile_width, s->tile_height,
127             s->numXtiles, s->numYtiles, s->ncomponents);
128     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
129         J2kTile *tile = s->tile + tileno;
130         nspaces(fd, 2);
131         fprintf(fd, "tile %d:\n", tileno);
132         for(compno = 0; compno < s->ncomponents; compno++){
133             J2kComponent *comp = tile->comp + compno;
134             nspaces(fd, 4);
135             fprintf(fd, "component %d:\n", compno);
136             nspaces(fd, 4);
137             fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
138                         comp->x0, comp->x1, comp->y0, comp->y1);
139             for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
140                 J2kResLevel *reslevel = comp->reslevel + reslevelno;
141                 nspaces(fd, 6);
142                 fprintf(fd, "reslevel %d:\n", reslevelno);
143                 nspaces(fd, 6);
144                 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
145                         reslevel->x0, reslevel->x1, reslevel->y0,
146                         reslevel->y1, reslevel->nbands);
147                 for(bandno = 0; bandno < reslevel->nbands; bandno++){
148                     J2kBand *band = reslevel->band + bandno;
149                     nspaces(fd, 8);
150                     fprintf(fd, "band %d:\n", bandno);
151                     nspaces(fd, 8);
152                     fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
153                                 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
154                                 band->x0, band->x1,
155                                 band->y0, band->y1,
156                                 band->codeblock_width, band->codeblock_height,
157                                 band->cblknx, band->cblkny);
158                     for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
159                         J2kPrec *prec = band->prec + precno;
160                         nspaces(fd, 10);
161                         fprintf(fd, "prec %d:\n", precno);
162                         nspaces(fd, 10);
163                         fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
164                                      prec->xi0, prec->xi1, prec->yi0, prec->yi1);
165                     }
166                 }
167             }
168         }
169     }
170 }
171 #endif
172
173 /* bitstream routines */
174
175 /** put n times val bit */
176 static void put_bits(J2kEncoderContext *s, int val, int n) // TODO: optimize
177 {
178     while (n-- > 0){
179         if (s->bit_index == 8)
180         {
181             s->bit_index = *s->buf == 0xff;
182             *(++s->buf) = 0;
183         }
184         *s->buf |= val << (7 - s->bit_index++);
185     }
186 }
187
188 /** put n least significant bits of a number num */
189 static void put_num(J2kEncoderContext *s, int num, int n)
190 {
191     while(--n >= 0)
192         put_bits(s, (num >> n) & 1, 1);
193 }
194
195 /** flush the bitstream */
196 static void j2k_flush(J2kEncoderContext *s)
197 {
198     if (s->bit_index){
199         s->bit_index = 0;
200         s->buf++;
201     }
202 }
203
204 /* tag tree routines */
205
206 /** code the value stored in node */
207 static void tag_tree_code(J2kEncoderContext *s, J2kTgtNode *node, int threshold)
208 {
209     J2kTgtNode *stack[30];
210     int sp = 1, curval = 0;
211     stack[0] = node;
212
213     node = node->parent;
214     while(node){
215         if (node->vis){
216             curval = node->val;
217             break;
218         }
219         node->vis++;
220         stack[sp++] = node;
221         node = node->parent;
222     }
223     while(--sp >= 0){
224         if (stack[sp]->val >= threshold){
225             put_bits(s, 0, threshold - curval);
226             break;
227         }
228         put_bits(s, 0, stack[sp]->val - curval);
229         put_bits(s, 1, 1);
230         curval = stack[sp]->val;
231     }
232 }
233
234 /** update the value in node */
235 static void tag_tree_update(J2kTgtNode *node)
236 {
237     int lev = 0;
238     while (node->parent){
239         if (node->parent->val <= node->val)
240             break;
241         node->parent->val = node->val;
242         node = node->parent;
243         lev++;
244     }
245 }
246
247 static int put_siz(J2kEncoderContext *s)
248 {
249     int i;
250
251     if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
252         return -1;
253
254     bytestream_put_be16(&s->buf, J2K_SIZ);
255     bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
256     bytestream_put_be16(&s->buf, 0); // Rsiz
257     bytestream_put_be32(&s->buf, s->width); // width
258     bytestream_put_be32(&s->buf, s->height); // height
259     bytestream_put_be32(&s->buf, 0); // X0Siz
260     bytestream_put_be32(&s->buf, 0); // Y0Siz
261
262     bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
263     bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
264     bytestream_put_be32(&s->buf, 0); // XT0Siz
265     bytestream_put_be32(&s->buf, 0); // YT0Siz
266     bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
267
268     for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
269         bytestream_put_byte(&s->buf, 7);
270         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
271         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
272     }
273     return 0;
274 }
275
276 static int put_cod(J2kEncoderContext *s)
277 {
278     J2kCodingStyle *codsty = &s->codsty;
279
280     if (s->buf_end - s->buf < 14)
281         return -1;
282
283     bytestream_put_be16(&s->buf, J2K_COD);
284     bytestream_put_be16(&s->buf, 12); // Lcod
285     bytestream_put_byte(&s->buf, 0);  // Scod
286     // SGcod
287     bytestream_put_byte(&s->buf, 0); // progression level
288     bytestream_put_be16(&s->buf, 1); // num of layers
289     if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
290         bytestream_put_byte(&s->buf, 2); // ICT
291     }else{
292         bytestream_put_byte(&s->buf, 0); // unspecified
293     }
294     // SPcod
295     bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
296     bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
297     bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
298     bytestream_put_byte(&s->buf, 0); // cblk style
299     bytestream_put_byte(&s->buf, codsty->transform); // transformation
300     return 0;
301 }
302
303 static int put_qcd(J2kEncoderContext *s, int compno)
304 {
305     int i, size;
306     J2kCodingStyle *codsty = &s->codsty;
307     J2kQuantStyle  *qntsty = &s->qntsty;
308
309     if (qntsty->quantsty == J2K_QSTY_NONE)
310         size = 4 + 3 * (codsty->nreslevels-1);
311     else // QSTY_SE
312         size = 5 + 6 * (codsty->nreslevels-1);
313
314     if (s->buf_end - s->buf < size + 2)
315         return -1;
316
317     bytestream_put_be16(&s->buf, J2K_QCD);
318     bytestream_put_be16(&s->buf, size);  // LQcd
319     bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
320     if (qntsty->quantsty == J2K_QSTY_NONE)
321         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
322             bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
323     else // QSTY_SE
324         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
325             bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
326     return 0;
327 }
328
329 static uint8_t *put_sot(J2kEncoderContext *s, int tileno)
330 {
331     uint8_t *psotptr;
332
333     if (s->buf_end - s->buf < 12)
334         return NULL;
335
336     bytestream_put_be16(&s->buf, J2K_SOT);
337     bytestream_put_be16(&s->buf, 10); // Lsot
338     bytestream_put_be16(&s->buf, tileno); // Isot
339
340     psotptr = s->buf;
341     bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
342
343     bytestream_put_byte(&s->buf, 0); // TPsot
344     bytestream_put_byte(&s->buf, 1); // TNsot
345     return psotptr;
346 }
347
348 /**
349  * compute the sizes of tiles, resolution levels, bands, etc.
350  * allocate memory for them
351  * divide the input image into tile-components
352  */
353 static int init_tiles(J2kEncoderContext *s)
354 {
355     int tileno, tilex, tiley, compno;
356     J2kCodingStyle *codsty = &s->codsty;
357     J2kQuantStyle  *qntsty = &s->qntsty;
358
359     s->numXtiles = ff_j2k_ceildiv(s->width, s->tile_width);
360     s->numYtiles = ff_j2k_ceildiv(s->height, s->tile_height);
361
362     s->tile = av_malloc(s->numXtiles * s->numYtiles * sizeof(J2kTile));
363     if (!s->tile)
364         return AVERROR(ENOMEM);
365     for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
366         for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
367             J2kTile *tile = s->tile + tileno;
368
369             tile->comp = av_malloc(s->ncomponents * sizeof(J2kComponent));
370             if (!tile->comp)
371                 return AVERROR(ENOMEM);
372             for (compno = 0; compno < s->ncomponents; compno++){
373                 J2kComponent *comp = tile->comp + compno;
374                 int ret, i, j;
375
376                 comp->coord[0][0] = tilex * s->tile_width;
377                 comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
378                 comp->coord[1][0] = tiley * s->tile_height;
379                 comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
380                 if (compno > 0)
381                     for (i = 0; i < 2; i++)
382                         for (j = 0; j < 2; j++)
383                             comp->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
384
385                 if (ret = ff_j2k_init_component(comp, codsty, qntsty, s->cbps[compno], compno?1<<s->chroma_shift[0]:1, compno?1<<s->chroma_shift[1]:1))
386                     return ret;
387             }
388         }
389     return 0;
390 }
391
392 static void copy_frame(J2kEncoderContext *s)
393 {
394     int tileno, compno, i, y, x;
395     uint8_t *line;
396     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
397         J2kTile *tile = s->tile + tileno;
398         if (s->planar){
399             for (compno = 0; compno < s->ncomponents; compno++){
400                 J2kComponent *comp = tile->comp + compno;
401                 int *dst = comp->data;
402                 line = s->picture.data[compno]
403                        + comp->coord[1][0] * s->picture.linesize[compno]
404                        + comp->coord[0][0];
405                 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
406                     uint8_t *ptr = line;
407                     for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
408                         *dst++ = *ptr++ - (1 << 7);
409                     line += s->picture.linesize[compno];
410                 }
411             }
412         } else{
413             line = s->picture.data[0] + tile->comp[0].coord[1][0] * s->picture.linesize[0]
414                    + tile->comp[0].coord[0][0] * s->ncomponents;
415
416             i = 0;
417             for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
418                 uint8_t *ptr = line;
419                 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
420                     for (compno = 0; compno < s->ncomponents; compno++){
421                         tile->comp[compno].data[i] = *ptr++  - (1 << 7);
422                     }
423                 }
424                 line += s->picture.linesize[0];
425             }
426         }
427     }
428 }
429
430 static void init_quantization(J2kEncoderContext *s)
431 {
432     int compno, reslevelno, bandno;
433     J2kQuantStyle  *qntsty = &s->qntsty;
434     J2kCodingStyle *codsty = &s->codsty;
435
436     for (compno = 0; compno < s->ncomponents; compno++){
437         int gbandno = 0;
438         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
439             int nbands, lev = codsty->nreslevels - reslevelno - 1;
440             nbands = reslevelno ? 3 : 1;
441             for (bandno = 0; bandno < nbands; bandno++, gbandno++){
442                 int expn, mant;
443
444                 if (codsty->transform == FF_DWT97){
445                     int bandpos = bandno + (reslevelno>0),
446                         ss = 81920000 / dwt_norms[0][bandpos][lev],
447                         log = av_log2(ss);
448                     mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
449                     expn = s->cbps[compno] - log + 13;
450                 } else
451                     expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
452
453                 qntsty->expn[gbandno] = expn;
454                 qntsty->mant[gbandno] = mant;
455             }
456         }
457     }
458 }
459
460 static void init_luts(void)
461 {
462     int i, a,
463         mask = ~((1<<NMSEDEC_FRACBITS)-1);
464
465     for (i = 0; i < (1 << NMSEDEC_BITS); i++){
466         lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
467         lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
468
469         a = (i >> (NMSEDEC_BITS-2)&2) + 1;
470         lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
471                                     << 13-NMSEDEC_FRACBITS, 0);
472         lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
473                                     << 1, 0);
474     }
475 }
476
477 /* tier-1 routines */
478 static int getnmsedec_sig(int x, int bpno)
479 {
480     if (bpno > NMSEDEC_FRACBITS)
481         return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
482     return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
483 }
484
485 static int getnmsedec_ref(int x, int bpno)
486 {
487     if (bpno > NMSEDEC_FRACBITS)
488         return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
489     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
490 }
491
492 static void encode_sigpass(J2kT1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
493 {
494     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
495     int vert_causal_ctx_csty_loc_symbol;
496     for (y0 = 0; y0 < height; y0 += 4)
497         for (x = 0; x < width; x++)
498             for (y = y0; y < height && y < y0+4; y++){
499                 if (!(t1->flags[y+1][x+1] & J2K_T1_SIG) && (t1->flags[y+1][x+1] & J2K_T1_SIG_NB)){
500                     int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno, vert_causal_ctx_csty_loc_symbol),
501                         bit = t1->data[y][x] & mask ? 1 : 0;
502                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
503                     if (bit){
504                         int xorbit;
505                         int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
506                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
507                         *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
508                         ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
509                     }
510                     t1->flags[y+1][x+1] |= J2K_T1_VIS;
511                 }
512             }
513 }
514
515 static void encode_refpass(J2kT1Context *t1, int width, int height, int *nmsedec, int bpno)
516 {
517     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
518     for (y0 = 0; y0 < height; y0 += 4)
519         for (x = 0; x < width; x++)
520             for (y = y0; y < height && y < y0+4; y++)
521                 if ((t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)) == J2K_T1_SIG){
522                     int ctxno = ff_j2k_getrefctxno(t1->flags[y+1][x+1]);
523                     *nmsedec += getnmsedec_ref(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
524                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
525                     t1->flags[y+1][x+1] |= J2K_T1_REF;
526                 }
527 }
528
529 static void encode_clnpass(J2kT1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
530 {
531     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
532     int vert_causal_ctx_csty_loc_symbol;
533     for (y0 = 0; y0 < height; y0 += 4)
534         for (x = 0; x < width; x++){
535             if (y0 + 3 < height && !(
536             (t1->flags[y0+1][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
537             (t1->flags[y0+2][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
538             (t1->flags[y0+3][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
539             (t1->flags[y0+4][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG))))
540             {
541                 // aggregation mode
542                 int rlen;
543                 for (rlen = 0; rlen < 4; rlen++)
544                     if (t1->data[y0+rlen][x] & mask)
545                         break;
546                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
547                 if (rlen == 4)
548                     continue;
549                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
550                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
551                 for (y = y0 + rlen; y < y0 + 4; y++){
552                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
553                         int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno, vert_causal_ctx_csty_loc_symbol);
554                         if (y > y0 + rlen)
555                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
556                         if (t1->data[y][x] & mask){ // newly significant
557                             int xorbit;
558                             int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
559                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
560                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
561                             ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
562                         }
563                     }
564                     t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
565                 }
566             } else{
567                 for (y = y0; y < y0 + 4 && y < height; y++){
568                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
569                         int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno, vert_causal_ctx_csty_loc_symbol);
570                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
571                         if (t1->data[y][x] & mask){ // newly significant
572                             int xorbit;
573                             int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
574                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
575                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
576                             ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
577                         }
578                     }
579                     t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
580                 }
581             }
582         }
583 }
584
585 static void encode_cblk(J2kEncoderContext *s, J2kT1Context *t1, J2kCblk *cblk, J2kTile *tile,
586                         int width, int height, int bandpos, int lev)
587 {
588     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
589     int64_t wmsedec = 0;
590
591     for (y = 0; y < height+2; y++)
592         memset(t1->flags[y], 0, (width+2)*sizeof(int));
593
594     for (y = 0; y < height; y++){
595         for (x = 0; x < width; x++){
596             if (t1->data[y][x] < 0){
597                 t1->flags[y+1][x+1] |= J2K_T1_SGN;
598                 t1->data[y][x] = -t1->data[y][x];
599             }
600             max = FFMAX(max, t1->data[y][x]);
601         }
602     }
603
604     if (max == 0){
605         cblk->nonzerobits = 0;
606         bpno = 0;
607     } else{
608         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
609         bpno = cblk->nonzerobits - 1;
610     }
611
612     ff_mqc_initenc(&t1->mqc, cblk->data);
613
614     for (passno = 0; bpno >= 0; passno++){
615         nmsedec=0;
616
617         switch(pass_t){
618             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
619                     break;
620             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
621                     break;
622             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
623                     break;
624         }
625
626         cblk->passes[passno].rate = 3 + ff_mqc_length(&t1->mqc);
627         wmsedec += (int64_t)nmsedec << (2*bpno);
628         cblk->passes[passno].disto = wmsedec;
629
630         if (++pass_t == 3){
631             pass_t = 0;
632             bpno--;
633         }
634     }
635     cblk->npasses = passno;
636     cblk->ninclpasses = passno;
637
638     // TODO: optional flush on each pass
639     cblk->passes[passno-1].rate = ff_mqc_flush(&t1->mqc);
640 }
641
642 /* tier-2 routines: */
643
644 static void putnumpasses(J2kEncoderContext *s, int n)
645 {
646     if (n == 1)
647         put_num(s, 0, 1);
648     else if (n == 2)
649         put_num(s, 2, 2);
650     else if (n <= 5)
651         put_num(s, 0xc | (n-3), 4);
652     else if (n <= 36)
653         put_num(s, 0x1e0 | (n-6), 9);
654     else
655         put_num(s, 0xff80 | (n-37), 16);
656 }
657
658
659 static int encode_packet(J2kEncoderContext *s, J2kResLevel *rlevel, int precno,
660                           uint8_t *expn, int numgbits)
661 {
662     int bandno, empty = 1;
663
664     // init bitstream
665     *s->buf = 0;
666     s->bit_index = 0;
667
668     // header
669
670     // is the packet empty?
671     for (bandno = 0; bandno < rlevel->nbands; bandno++){
672         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
673         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
674             empty = 0;
675             break;
676         }
677     }
678
679     put_bits(s, !empty, 1);
680     if (empty){
681         j2k_flush(s);
682         return 0;
683     }
684
685     for (bandno = 0; bandno < rlevel->nbands; bandno++){
686         J2kBand *band = rlevel->band + bandno;
687         J2kPrec *prec = band->prec + precno;
688         int yi, xi, pos;
689         int cblknw = prec->xi1 - prec->xi0;
690
691         if (band->coord[0][0] == band->coord[0][1]
692         ||  band->coord[1][0] == band->coord[1][1])
693             continue;
694
695         for (pos=0, yi = prec->yi0; yi < prec->yi1; yi++){
696             for (xi = prec->xi0; xi < prec->xi1; xi++, pos++){
697                 prec->cblkincl[pos].val = band->cblk[yi * cblknw + xi].ninclpasses == 0;
698                 tag_tree_update(prec->cblkincl + pos);
699                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - band->cblk[yi * cblknw + xi].nonzerobits;
700                 tag_tree_update(prec->zerobits + pos);
701             }
702         }
703
704         for (pos=0, yi = prec->yi0; yi < prec->yi1; yi++){
705             for (xi = prec->xi0; xi < prec->xi1; xi++, pos++){
706                 int pad = 0, llen, length;
707                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
708
709                 if (s->buf_end - s->buf < 20) // approximately
710                     return -1;
711
712                 // inclusion information
713                 tag_tree_code(s, prec->cblkincl + pos, 1);
714                 if (!cblk->ninclpasses)
715                     continue;
716                 // zerobits information
717                 tag_tree_code(s, prec->zerobits + pos, 100);
718                 // number of passes
719                 putnumpasses(s, cblk->ninclpasses);
720
721                 length = cblk->passes[cblk->ninclpasses-1].rate;
722                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
723                 if (llen < 0){
724                     pad = -llen;
725                     llen = 0;
726                 }
727                 // length of code block
728                 put_bits(s, 1, llen);
729                 put_bits(s, 0, 1);
730                 put_num(s, length, av_log2(length)+1+pad);
731             }
732         }
733     }
734     j2k_flush(s);
735     for (bandno = 0; bandno < rlevel->nbands; bandno++){
736         J2kBand *band = rlevel->band + bandno;
737         J2kPrec *prec = band->prec + precno;
738         int yi, cblknw = prec->xi1 - prec->xi0;
739         for (yi = prec->yi0; yi < prec->yi1; yi++){
740             int xi;
741             for (xi = prec->xi0; xi < prec->xi1; xi++){
742                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
743                 if (cblk->ninclpasses){
744                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
745                         return -1;
746                     bytestream_put_buffer(&s->buf, cblk->data, cblk->passes[cblk->ninclpasses-1].rate);
747                 }
748             }
749         }
750     }
751     return 0;
752 }
753
754 static int encode_packets(J2kEncoderContext *s, J2kTile *tile, int tileno)
755 {
756     int compno, reslevelno, ret;
757     J2kCodingStyle *codsty = &s->codsty;
758     J2kQuantStyle  *qntsty = &s->qntsty;
759
760     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
761     // lay-rlevel-comp-pos progression
762     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
763         for (compno = 0; compno < s->ncomponents; compno++){
764             int precno;
765             J2kResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
766             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
767                 if (ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
768                               qntsty->nguardbits))
769                     return ret;
770             }
771         }
772     }
773     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
774     return 0;
775 }
776
777 static int getcut(J2kCblk *cblk, int64_t lambda, int dwt_norm)
778 {
779     int passno, res = 0;
780     for (passno = 0; passno < cblk->npasses; passno++){
781         int dr;
782         int64_t dd;
783
784         dr = cblk->passes[passno].rate
785            - (res ? cblk->passes[res-1].rate:0);
786         dd = cblk->passes[passno].disto
787            - (res ? cblk->passes[res-1].disto:0);
788
789         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
790             res = passno+1;
791     }
792     return res;
793 }
794
795 static void truncpasses(J2kEncoderContext *s, J2kTile *tile)
796 {
797     int compno, reslevelno, bandno, cblkno, lev;
798     J2kCodingStyle *codsty = &s->codsty;
799
800     for (compno = 0; compno < s->ncomponents; compno++){
801         J2kComponent *comp = tile->comp + compno;
802
803         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
804             J2kResLevel *reslevel = comp->reslevel + reslevelno;
805
806             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
807                 int bandpos = bandno + (reslevelno > 0);
808                 J2kBand *band = reslevel->band + bandno;
809
810                 for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++){
811                     J2kCblk *cblk = band->cblk + cblkno;
812
813                     cblk->ninclpasses = getcut(cblk, s->lambda,
814                             (int64_t)dwt_norms[codsty->transform][bandpos][lev] * (int64_t)band->stepsize >> 13);
815                 }
816             }
817         }
818     }
819 }
820
821 static int encode_tile(J2kEncoderContext *s, J2kTile *tile, int tileno)
822 {
823     int compno, reslevelno, bandno, ret;
824     J2kT1Context t1;
825     J2kCodingStyle *codsty = &s->codsty;
826     for (compno = 0; compno < s->ncomponents; compno++){
827         J2kComponent *comp = s->tile[tileno].comp + compno;
828
829         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
830         if (ret = ff_j2k_dwt_encode(&comp->dwt, comp->data))
831             return ret;
832         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
833
834         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
835             J2kResLevel *reslevel = comp->reslevel + reslevelno;
836
837             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
838                 J2kBand *band = reslevel->band + bandno;
839                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
840                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
841                 y0 = yy0;
842                 yy1 = FFMIN(ff_j2k_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,
843                             band->coord[1][1]) - band->coord[1][0] + yy0;
844
845                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
846                     continue;
847
848                 bandpos = bandno + (reslevelno > 0);
849
850                 for (cblky = 0; cblky < band->cblkny; cblky++){
851                     if (reslevelno == 0 || bandno == 1)
852                         xx0 = 0;
853                     else
854                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
855                     x0 = xx0;
856                     xx1 = FFMIN(ff_j2k_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,
857                                 band->coord[0][1]) - band->coord[0][0] + xx0;
858
859                     for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++){
860                         int y, x;
861                         if (codsty->transform == FF_DWT53){
862                             for (y = yy0; y < yy1; y++){
863                                 int *ptr = t1.data[y-yy0];
864                                 for (x = xx0; x < xx1; x++){
865                                     *ptr++ = comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
866                                 }
867                             }
868                         } else{
869                             for (y = yy0; y < yy1; y++){
870                                 int *ptr = t1.data[y-yy0];
871                                 for (x = xx0; x < xx1; x++){
872                                     *ptr = (comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
873                                     *ptr = (int64_t)*ptr * (int64_t)(8192 * 8192 / band->stepsize) >> 13 - NMSEDEC_FRACBITS;
874                                     ptr++;
875                                 }
876                             }
877                         }
878                         encode_cblk(s, &t1, band->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
879                                     bandpos, codsty->nreslevels - reslevelno - 1);
880                         xx0 = xx1;
881                         xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);
882                     }
883                     yy0 = yy1;
884                     yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);
885                 }
886             }
887         }
888         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
889     }
890
891     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
892     truncpasses(s, tile);
893     if (ret = encode_packets(s, tile, tileno))
894         return ret;
895     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
896     return 0;
897 }
898
899 static void cleanup(J2kEncoderContext *s)
900 {
901     int tileno, compno;
902     J2kCodingStyle *codsty = &s->codsty;
903
904     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
905         for (compno = 0; compno < s->ncomponents; compno++){
906             J2kComponent *comp = s->tile[tileno].comp + compno;
907             ff_j2k_cleanup(comp, codsty);
908         }
909         av_freep(&s->tile[tileno].comp);
910     }
911     av_freep(&s->tile);
912 }
913
914 static void reinit(J2kEncoderContext *s)
915 {
916     int tileno, compno;
917     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
918         J2kTile *tile = s->tile + tileno;
919         for (compno = 0; compno < s->ncomponents; compno++)
920             ff_j2k_reinit(tile->comp + compno, &s->codsty);
921     }
922 }
923
924 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
925                         const AVFrame *pict, int *got_packet)
926 {
927     int tileno, ret;
928     J2kEncoderContext *s = avctx->priv_data;
929
930     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + FF_MIN_BUFFER_SIZE)) < 0)
931         return ret;
932
933     // init:
934     s->buf = s->buf_start = pkt->data;
935     s->buf_end = pkt->data + pkt->size;
936
937     s->picture = *pict;
938     avctx->coded_frame= &s->picture;
939
940     s->lambda = s->picture.quality * LAMBDA_SCALE;
941
942     copy_frame(s);
943     reinit(s);
944
945     if (s->buf_end - s->buf < 2)
946         return -1;
947     bytestream_put_be16(&s->buf, J2K_SOC);
948     if (ret = put_siz(s))
949         return ret;
950     if (ret = put_cod(s))
951         return ret;
952     if (ret = put_qcd(s, 0))
953         return ret;
954
955     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
956         uint8_t *psotptr;
957         if (!(psotptr = put_sot(s, tileno)))
958             return -1;
959         if (s->buf_end - s->buf < 2)
960             return -1;
961         bytestream_put_be16(&s->buf, J2K_SOD);
962         if (ret = encode_tile(s, s->tile + tileno, tileno))
963             return ret;
964         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
965     }
966     if (s->buf_end - s->buf < 2)
967         return -1;
968     bytestream_put_be16(&s->buf, J2K_EOC);
969
970     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
971     pkt->size = s->buf - s->buf_start;
972     pkt->flags |= AV_PKT_FLAG_KEY;
973     *got_packet = 1;
974
975     return 0;
976 }
977
978 static av_cold int j2kenc_init(AVCodecContext *avctx)
979 {
980     int i, ret;
981     J2kEncoderContext *s = avctx->priv_data;
982     J2kCodingStyle *codsty = &s->codsty;
983     J2kQuantStyle  *qntsty = &s->qntsty;
984
985     s->avctx = avctx;
986     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
987
988     // defaults:
989     // TODO: implement setting non-standard precinct size
990     codsty->log2_prec_width  = 15;
991     codsty->log2_prec_height = 15;
992     codsty->nreslevels       = 7;
993     codsty->log2_cblk_width  = 4;
994     codsty->log2_cblk_height = 4;
995     codsty->transform        = 1;
996
997     qntsty->nguardbits       = 1;
998
999     s->tile_width            = 256;
1000     s->tile_height           = 256;
1001
1002     if (codsty->transform == FF_DWT53)
1003         qntsty->quantsty = J2K_QSTY_NONE;
1004     else
1005         qntsty->quantsty = J2K_QSTY_SE;
1006
1007     s->width = avctx->width;
1008     s->height = avctx->height;
1009
1010     for (i = 0; i < 3; i++)
1011         s->cbps[i] = 8;
1012
1013     if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
1014         s->ncomponents = 3;
1015     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
1016         s->ncomponents = 1;
1017     } else{ // planar YUV
1018         s->planar = 1;
1019         s->ncomponents = 3;
1020         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
1021                 s->chroma_shift, s->chroma_shift + 1);
1022     }
1023
1024     ff_j2k_init_tier1_luts();
1025
1026     init_luts();
1027
1028     init_quantization(s);
1029     if (ret=init_tiles(s))
1030         return ret;
1031
1032     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1033
1034     return 0;
1035 }
1036
1037 static int j2kenc_destroy(AVCodecContext *avctx)
1038 {
1039     J2kEncoderContext *s = avctx->priv_data;
1040
1041     cleanup(s);
1042     return 0;
1043 }
1044
1045 AVCodec ff_jpeg2000_encoder = {
1046     .name           = "j2k",
1047     .type           = AVMEDIA_TYPE_VIDEO,
1048     .id             = AV_CODEC_ID_JPEG2000,
1049     .priv_data_size = sizeof(J2kEncoderContext),
1050     .init           = j2kenc_init,
1051     .encode2        = encode_frame,
1052     .close          = j2kenc_destroy,
1053     .capabilities   = CODEC_CAP_EXPERIMENTAL,
1054     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1055     .pix_fmts       = (const enum AVPixelFormat[]) {
1056         AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1057 /*      AV_PIX_FMT_YUV420P,
1058         AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
1059         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,*/
1060         AV_PIX_FMT_NONE
1061     }
1062 };