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