]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kenc.c
Fix compilation without HAVE_AVX, HAVE_YASM etc.
[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     if(s->avctx->pix_fmt == PIX_FMT_YUV444P){
289         bytestream_put_byte(&s->buf, 2); // ICT
290     }else{
291         bytestream_put_byte(&s->buf, 0); // unspecified
292     }
293     // SPcod
294     bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
295     bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
296     bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
297     bytestream_put_byte(&s->buf, 0); // cblk style
298     bytestream_put_byte(&s->buf, codsty->transform); // transformation
299     return 0;
300 }
301
302 static int put_qcd(J2kEncoderContext *s, int compno)
303 {
304     int i, size;
305     J2kCodingStyle *codsty = &s->codsty;
306     J2kQuantStyle  *qntsty = &s->qntsty;
307
308     if (qntsty->quantsty == J2K_QSTY_NONE)
309         size = 4 + 3 * (codsty->nreslevels-1);
310     else // QSTY_SE
311         size = 5 + 6 * (codsty->nreslevels-1);
312
313     if (s->buf_end - s->buf < size + 2)
314         return -1;
315
316     bytestream_put_be16(&s->buf, J2K_QCD);
317     bytestream_put_be16(&s->buf, size);  // LQcd
318     bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
319     if (qntsty->quantsty == J2K_QSTY_NONE)
320         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
321             bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
322     else // QSTY_SE
323         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
324             bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
325     return 0;
326 }
327
328 static uint8_t *put_sot(J2kEncoderContext *s, int tileno)
329 {
330     uint8_t *psotptr;
331
332     if (s->buf_end - s->buf < 12)
333         return NULL;
334
335     bytestream_put_be16(&s->buf, J2K_SOT);
336     bytestream_put_be16(&s->buf, 10); // Lsot
337     bytestream_put_be16(&s->buf, tileno); // Isot
338
339     psotptr = s->buf;
340     bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
341
342     bytestream_put_byte(&s->buf, 0); // TPsot
343     bytestream_put_byte(&s->buf, 1); // TNsot
344     return psotptr;
345 }
346
347 /**
348  * compute the sizes of tiles, resolution levels, bands, etc.
349  * allocate memory for them
350  * divide the input image into tile-components
351  */
352 static int init_tiles(J2kEncoderContext *s)
353 {
354     int tileno, tilex, tiley, compno;
355     J2kCodingStyle *codsty = &s->codsty;
356     J2kQuantStyle  *qntsty = &s->qntsty;
357
358     s->numXtiles = ff_j2k_ceildiv(s->width, s->tile_width);
359     s->numYtiles = ff_j2k_ceildiv(s->height, s->tile_height);
360
361     s->tile = av_malloc(s->numXtiles * s->numYtiles * sizeof(J2kTile));
362     if (!s->tile)
363         return AVERROR(ENOMEM);
364     for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
365         for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
366             J2kTile *tile = s->tile + tileno;
367
368             tile->comp = av_malloc(s->ncomponents * sizeof(J2kComponent));
369             if (!tile->comp)
370                 return AVERROR(ENOMEM);
371             for (compno = 0; compno < s->ncomponents; compno++){
372                 J2kComponent *comp = tile->comp + compno;
373                 int ret, i, j;
374
375                 comp->coord[0][0] = tilex * s->tile_width;
376                 comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
377                 comp->coord[1][0] = tiley * s->tile_height;
378                 comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
379                 if (compno > 0)
380                     for (i = 0; i < 2; i++)
381                         for (j = 0; j < 2; j++)
382                             comp->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
383
384                 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))
385                     return ret;
386             }
387         }
388     return 0;
389 }
390
391 static void copy_frame(J2kEncoderContext *s)
392 {
393     int tileno, compno, i, y, x;
394     uint8_t *line;
395     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
396         J2kTile *tile = s->tile + tileno;
397         if (s->planar){
398             for (compno = 0; compno < s->ncomponents; compno++){
399                 J2kComponent *comp = tile->comp + compno;
400                 int *dst = comp->data;
401                 line = s->picture.data[compno]
402                        + comp->coord[1][0] * s->picture.linesize[compno]
403                        + comp->coord[0][0];
404                 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
405                     uint8_t *ptr = line;
406                     for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
407                         *dst++ = *ptr++ - (1 << 7);
408                     line += s->picture.linesize[compno];
409                 }
410             }
411         } else{
412             line = s->picture.data[0] + tile->comp[0].coord[1][0] * s->picture.linesize[0]
413                    + tile->comp[0].coord[0][0] * s->ncomponents;
414
415             i = 0;
416             for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
417                 uint8_t *ptr = line;
418                 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
419                     for (compno = 0; compno < s->ncomponents; compno++){
420                         tile->comp[compno].data[i] = *ptr++  - (1 << 7);
421                     }
422                 }
423                 line += s->picture.linesize[0];
424             }
425         }
426     }
427 }
428
429 static void init_quantization(J2kEncoderContext *s)
430 {
431     int compno, reslevelno, bandno;
432     J2kQuantStyle  *qntsty = &s->qntsty;
433     J2kCodingStyle *codsty = &s->codsty;
434
435     for (compno = 0; compno < s->ncomponents; compno++){
436         int gbandno = 0;
437         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
438             int nbands, lev = codsty->nreslevels - reslevelno - 1;
439             nbands = reslevelno ? 3 : 1;
440             for (bandno = 0; bandno < nbands; bandno++, gbandno++){
441                 int expn, mant;
442
443                 if (codsty->transform == FF_DWT97){
444                     int bandpos = bandno + (reslevelno>0),
445                         ss = 81920000 / dwt_norms[0][bandpos][lev],
446                         log = av_log2(ss);
447                     mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
448                     expn = s->cbps[compno] - log + 13;
449                 } else
450                     expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
451
452                 qntsty->expn[gbandno] = expn;
453                 qntsty->mant[gbandno] = mant;
454             }
455         }
456     }
457 }
458
459 static void init_luts()
460 {
461     int i, a,
462         mask = ~((1<<NMSEDEC_FRACBITS)-1);
463
464     for (i = 0; i < (1 << NMSEDEC_BITS); i++){
465         lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
466         lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
467
468         a = (i >> (NMSEDEC_BITS-2)&2) + 1;
469         lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
470                                     << 13-NMSEDEC_FRACBITS, 0);
471         lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
472                                     << 1, 0);
473     }
474 }
475
476 /* tier-1 routines */
477 static int getnmsedec_sig(int x, int bpno)
478 {
479     if (bpno > NMSEDEC_FRACBITS)
480         return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
481     return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
482 }
483
484 static int getnmsedec_ref(int x, int bpno)
485 {
486     if (bpno > NMSEDEC_FRACBITS)
487         return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
488     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
489 }
490
491 static void encode_sigpass(J2kT1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
492 {
493     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
494     int vert_causal_ctx_csty_loc_symbol;
495     for (y0 = 0; y0 < height; y0 += 4)
496         for (x = 0; x < width; x++)
497             for (y = y0; y < height && y < y0+4; y++){
498                 if (!(t1->flags[y+1][x+1] & J2K_T1_SIG) && (t1->flags[y+1][x+1] & J2K_T1_SIG_NB)){
499                     int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno, vert_causal_ctx_csty_loc_symbol),
500                         bit = t1->data[y][x] & mask ? 1 : 0;
501                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
502                     if (bit){
503                         int xorbit;
504                         int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
505                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
506                         *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
507                         ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
508                     }
509                     t1->flags[y+1][x+1] |= J2K_T1_VIS;
510                 }
511             }
512 }
513
514 static void encode_refpass(J2kT1Context *t1, int width, int height, int *nmsedec, int bpno)
515 {
516     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
517     for (y0 = 0; y0 < height; y0 += 4)
518         for (x = 0; x < width; x++)
519             for (y = y0; y < height && y < y0+4; y++)
520                 if ((t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)) == J2K_T1_SIG){
521                     int ctxno = ff_j2k_getrefctxno(t1->flags[y+1][x+1]);
522                     *nmsedec += getnmsedec_ref(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
523                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
524                     t1->flags[y+1][x+1] |= J2K_T1_REF;
525                 }
526 }
527
528 static void encode_clnpass(J2kT1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
529 {
530     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
531     int vert_causal_ctx_csty_loc_symbol;
532     for (y0 = 0; y0 < height; y0 += 4)
533         for (x = 0; x < width; x++){
534             if (y0 + 3 < height && !(
535             (t1->flags[y0+1][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
536             (t1->flags[y0+2][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
537             (t1->flags[y0+3][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
538             (t1->flags[y0+4][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG))))
539             {
540                 // aggregation mode
541                 int rlen;
542                 for (rlen = 0; rlen < 4; rlen++)
543                     if (t1->data[y0+rlen][x] & mask)
544                         break;
545                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
546                 if (rlen == 4)
547                     continue;
548                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
549                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
550                 for (y = y0 + rlen; y < y0 + 4; y++){
551                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
552                         int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno, vert_causal_ctx_csty_loc_symbol);
553                         if (y > y0 + rlen)
554                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
555                         if (t1->data[y][x] & mask){ // newly significant
556                             int xorbit;
557                             int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
558                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
559                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
560                             ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
561                         }
562                     }
563                     t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
564                 }
565             } else{
566                 for (y = y0; y < y0 + 4 && y < height; y++){
567                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
568                         int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno, vert_causal_ctx_csty_loc_symbol);
569                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
570                         if (t1->data[y][x] & mask){ // newly significant
571                             int xorbit;
572                             int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
573                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
574                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
575                             ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
576                         }
577                     }
578                     t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
579                 }
580             }
581         }
582 }
583
584 static void encode_cblk(J2kEncoderContext *s, J2kT1Context *t1, J2kCblk *cblk, J2kTile *tile,
585                         int width, int height, int bandpos, int lev)
586 {
587     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
588     int64_t wmsedec = 0;
589
590     for (y = 0; y < height+2; y++)
591         memset(t1->flags[y], 0, (width+2)*sizeof(int));
592
593     for (y = 0; y < height; y++){
594         for (x = 0; x < width; x++){
595             if (t1->data[y][x] < 0){
596                 t1->flags[y+1][x+1] |= J2K_T1_SGN;
597                 t1->data[y][x] = -t1->data[y][x];
598             }
599             max = FFMAX(max, t1->data[y][x]);
600         }
601     }
602
603     if (max == 0){
604         cblk->nonzerobits = 0;
605         bpno = 0;
606     } else{
607         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
608         bpno = cblk->nonzerobits - 1;
609     }
610
611     ff_mqc_initenc(&t1->mqc, cblk->data);
612
613     for (passno = 0; bpno >= 0; passno++){
614         nmsedec=0;
615
616         switch(pass_t){
617             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
618                     break;
619             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
620                     break;
621             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
622                     break;
623         }
624
625         cblk->passes[passno].rate = 3 + ff_mqc_length(&t1->mqc);
626         wmsedec += (int64_t)nmsedec << (2*bpno);
627         cblk->passes[passno].disto = wmsedec;
628
629         if (++pass_t == 3){
630             pass_t = 0;
631             bpno--;
632         }
633     }
634     cblk->npasses = passno;
635     cblk->ninclpasses = passno;
636
637     // TODO: optional flush on each pass
638     cblk->passes[passno-1].rate = ff_mqc_flush(&t1->mqc);
639 }
640
641 /* tier-2 routines: */
642
643 static void putnumpasses(J2kEncoderContext *s, int n)
644 {
645     if (n == 1)
646         put_num(s, 0, 1);
647     else if (n == 2)
648         put_num(s, 2, 2);
649     else if (n <= 5)
650         put_num(s, 0xc | (n-3), 4);
651     else if (n <= 36)
652         put_num(s, 0x1e0 | (n-6), 9);
653     else
654         put_num(s, 0xff80 | (n-37), 16);
655 }
656
657
658 static int encode_packet(J2kEncoderContext *s, J2kResLevel *rlevel, int precno,
659                           uint8_t *expn, int numgbits)
660 {
661     int bandno, empty = 1;
662
663     // init bitstream
664     *s->buf = 0;
665     s->bit_index = 0;
666
667     // header
668
669     // is the packet empty?
670     for (bandno = 0; bandno < rlevel->nbands; bandno++){
671         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
672         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
673             empty = 0;
674             break;
675         }
676     }
677
678     put_bits(s, !empty, 1);
679     if (empty){
680         j2k_flush(s);
681         return 0;
682     }
683
684     for (bandno = 0; bandno < rlevel->nbands; bandno++){
685         J2kBand *band = rlevel->band + bandno;
686         J2kPrec *prec = band->prec + precno;
687         int yi, xi, pos;
688         int cblknw = prec->xi1 - prec->xi0;
689
690         if (band->coord[0][0] == band->coord[0][1]
691         ||  band->coord[1][0] == band->coord[1][1])
692             continue;
693
694         for (pos=0, yi = prec->yi0; yi < prec->yi1; yi++){
695             for (xi = prec->xi0; xi < prec->xi1; xi++, pos++){
696                 prec->cblkincl[pos].val = band->cblk[yi * cblknw + xi].ninclpasses == 0;
697                 tag_tree_update(prec->cblkincl + pos);
698                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - band->cblk[yi * cblknw + xi].nonzerobits;
699                 tag_tree_update(prec->zerobits + pos);
700             }
701         }
702
703         for (pos=0, yi = prec->yi0; yi < prec->yi1; yi++){
704             for (xi = prec->xi0; xi < prec->xi1; xi++, pos++){
705                 int pad = 0, llen, length;
706                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
707
708                 if (s->buf_end - s->buf < 20) // approximately
709                     return -1;
710
711                 // inclusion information
712                 tag_tree_code(s, prec->cblkincl + pos, 1);
713                 if (!cblk->ninclpasses)
714                     continue;
715                 // zerobits information
716                 tag_tree_code(s, prec->zerobits + pos, 100);
717                 // number of passes
718                 putnumpasses(s, cblk->ninclpasses);
719
720                 length = cblk->passes[cblk->ninclpasses-1].rate;
721                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
722                 if (llen < 0){
723                     pad = -llen;
724                     llen = 0;
725                 }
726                 // length of code block
727                 put_bits(s, 1, llen);
728                 put_bits(s, 0, 1);
729                 put_num(s, length, av_log2(length)+1+pad);
730             }
731         }
732     }
733     j2k_flush(s);
734     for (bandno = 0; bandno < rlevel->nbands; bandno++){
735         J2kBand *band = rlevel->band + bandno;
736         J2kPrec *prec = band->prec + precno;
737         int yi, cblknw = prec->xi1 - prec->xi0;
738         for (yi = prec->yi0; yi < prec->yi1; yi++){
739             int xi;
740             for (xi = prec->xi0; xi < prec->xi1; xi++){
741                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
742                 if (cblk->ninclpasses){
743                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
744                         return -1;
745                     bytestream_put_buffer(&s->buf, cblk->data, cblk->passes[cblk->ninclpasses-1].rate);
746                 }
747             }
748         }
749     }
750     return 0;
751 }
752
753 static int encode_packets(J2kEncoderContext *s, J2kTile *tile, int tileno)
754 {
755     int compno, reslevelno, ret;
756     J2kCodingStyle *codsty = &s->codsty;
757     J2kQuantStyle  *qntsty = &s->qntsty;
758
759     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
760     // lay-rlevel-comp-pos progression
761     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
762         for (compno = 0; compno < s->ncomponents; compno++){
763             int precno;
764             J2kResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
765             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
766                 if (ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
767                               qntsty->nguardbits))
768                     return ret;
769             }
770         }
771     }
772     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
773     return 0;
774 }
775
776 static int getcut(J2kCblk *cblk, int64_t lambda, int dwt_norm)
777 {
778     int passno, res = 0;
779     for (passno = 0; passno < cblk->npasses; passno++){
780         int dr;
781         int64_t dd;
782
783         dr = cblk->passes[passno].rate
784            - (res ? cblk->passes[res-1].rate:0);
785         dd = cblk->passes[passno].disto
786            - (res ? cblk->passes[res-1].disto:0);
787
788         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
789             res = passno+1;
790     }
791     return res;
792 }
793
794 static void truncpasses(J2kEncoderContext *s, J2kTile *tile)
795 {
796     int compno, reslevelno, bandno, cblkno, lev;
797     J2kCodingStyle *codsty = &s->codsty;
798
799     for (compno = 0; compno < s->ncomponents; compno++){
800         J2kComponent *comp = tile->comp + compno;
801
802         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
803             J2kResLevel *reslevel = comp->reslevel + reslevelno;
804
805             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
806                 int bandpos = bandno + (reslevelno > 0);
807                 J2kBand *band = reslevel->band + bandno;
808
809                 for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++){
810                     J2kCblk *cblk = band->cblk + cblkno;
811
812                     cblk->ninclpasses = getcut(cblk, s->lambda,
813                             (int64_t)dwt_norms[codsty->transform][bandpos][lev] * (int64_t)band->stepsize >> 13);
814                 }
815             }
816         }
817     }
818 }
819
820 static int encode_tile(J2kEncoderContext *s, J2kTile *tile, int tileno)
821 {
822     int compno, reslevelno, bandno, ret;
823     J2kT1Context t1;
824     J2kCodingStyle *codsty = &s->codsty;
825     for (compno = 0; compno < s->ncomponents; compno++){
826         J2kComponent *comp = s->tile[tileno].comp + compno;
827
828         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
829         if (ret = ff_j2k_dwt_encode(&comp->dwt, comp->data))
830             return ret;
831         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
832
833         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
834             J2kResLevel *reslevel = comp->reslevel + reslevelno;
835
836             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
837                 J2kBand *band = reslevel->band + bandno;
838                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
839                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
840                 y0 = yy0;
841                 yy1 = FFMIN(ff_j2k_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,
842                             band->coord[1][1]) - band->coord[1][0] + yy0;
843
844                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
845                     continue;
846
847                 bandpos = bandno + (reslevelno > 0);
848
849                 for (cblky = 0; cblky < band->cblkny; cblky++){
850                     if (reslevelno == 0 || bandno == 1)
851                         xx0 = 0;
852                     else
853                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
854                     x0 = xx0;
855                     xx1 = FFMIN(ff_j2k_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,
856                                 band->coord[0][1]) - band->coord[0][0] + xx0;
857
858                     for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++){
859                         int y, x;
860                         if (codsty->transform == FF_DWT53){
861                             for (y = yy0; y < yy1; y++){
862                                 int *ptr = t1.data[y-yy0];
863                                 for (x = xx0; x < xx1; x++){
864                                     *ptr++ = comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
865                                 }
866                             }
867                         } else{
868                             for (y = yy0; y < yy1; y++){
869                                 int *ptr = t1.data[y-yy0];
870                                 for (x = xx0; x < xx1; x++){
871                                     *ptr = (comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
872                                     *ptr = (int64_t)*ptr * (int64_t)(8192 * 8192 / band->stepsize) >> 13 - NMSEDEC_FRACBITS;
873                                     *ptr++;
874                                 }
875                             }
876                         }
877                         encode_cblk(s, &t1, band->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
878                                     bandpos, codsty->nreslevels - reslevelno - 1);
879                         xx0 = xx1;
880                         xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);
881                     }
882                     yy0 = yy1;
883                     yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);
884                 }
885             }
886         }
887         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
888     }
889
890     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
891     truncpasses(s, tile);
892     if (ret = encode_packets(s, tile, tileno))
893         return ret;
894     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
895     return 0;
896 }
897
898 static void cleanup(J2kEncoderContext *s)
899 {
900     int tileno, compno;
901     J2kCodingStyle *codsty = &s->codsty;
902
903     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
904         for (compno = 0; compno < s->ncomponents; compno++){
905             J2kComponent *comp = s->tile[tileno].comp + compno;
906             ff_j2k_cleanup(comp, codsty);
907         }
908         av_freep(&s->tile[tileno].comp);
909     }
910     av_freep(&s->tile);
911 }
912
913 static void reinit(J2kEncoderContext *s)
914 {
915     int tileno, compno;
916     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
917         J2kTile *tile = s->tile + tileno;
918         for (compno = 0; compno < s->ncomponents; compno++)
919             ff_j2k_reinit(tile->comp + compno, &s->codsty);
920     }
921 }
922
923 static int encode_frame(AVCodecContext *avctx,
924                         uint8_t *buf, int buf_size,
925                         void *data)
926 {
927     int tileno, ret;
928     J2kEncoderContext *s = avctx->priv_data;
929
930     // init:
931     s->buf = s->buf_start = buf;
932     s->buf_end = buf + buf_size;
933
934     s->picture = *(AVFrame*)data;
935     avctx->coded_frame= &s->picture;
936
937     s->lambda = s->picture.quality * LAMBDA_SCALE;
938
939     copy_frame(s);
940     reinit(s);
941
942     if (s->buf_end - s->buf < 2)
943         return -1;
944     bytestream_put_be16(&s->buf, J2K_SOC);
945     if (ret = put_siz(s))
946         return ret;
947     if (ret = put_cod(s))
948         return ret;
949     if (ret = put_qcd(s, 0))
950         return ret;
951
952     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
953         uint8_t *psotptr;
954         if (!(psotptr = put_sot(s, tileno)))
955             return -1;
956         if (s->buf_end - s->buf < 2)
957             return -1;
958         bytestream_put_be16(&s->buf, J2K_SOD);
959         if (ret = encode_tile(s, s->tile + tileno, tileno))
960             return ret;
961         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
962     }
963     if (s->buf_end - s->buf < 2)
964         return -1;
965     bytestream_put_be16(&s->buf, J2K_EOC);
966
967     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
968     return s->buf - s->buf_start;
969 }
970
971 static av_cold int j2kenc_init(AVCodecContext *avctx)
972 {
973     int i, ret;
974     J2kEncoderContext *s = avctx->priv_data;
975     J2kCodingStyle *codsty = &s->codsty;
976     J2kQuantStyle  *qntsty = &s->qntsty;
977
978     s->avctx = avctx;
979     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
980
981     // defaults:
982     // TODO: implement setting non-standard precinct size
983     codsty->log2_prec_width  = 15;
984     codsty->log2_prec_height = 15;
985     codsty->nreslevels       = 7;
986     codsty->log2_cblk_width  = 4;
987     codsty->log2_cblk_height = 4;
988     codsty->transform        = 1;
989
990     qntsty->nguardbits       = 1;
991
992     s->tile_width            = 256;
993     s->tile_height           = 256;
994
995     if (codsty->transform == FF_DWT53)
996         qntsty->quantsty = J2K_QSTY_NONE;
997     else
998         qntsty->quantsty = J2K_QSTY_SE;
999
1000     s->width = avctx->width;
1001     s->height = avctx->height;
1002
1003     for (i = 0; i < 3; i++)
1004         s->cbps[i] = 8;
1005
1006     if (avctx->pix_fmt == PIX_FMT_RGB24){
1007         s->ncomponents = 3;
1008     } else if (avctx->pix_fmt == PIX_FMT_GRAY8){
1009         s->ncomponents = 1;
1010     } else{ // planar YUV
1011         s->planar = 1;
1012         s->ncomponents = 3;
1013         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
1014                 s->chroma_shift, s->chroma_shift + 1);
1015     }
1016
1017     ff_j2k_init_tier1_luts();
1018
1019     init_luts();
1020
1021     init_quantization(s);
1022     if (ret=init_tiles(s))
1023         return ret;
1024
1025     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1026
1027     return 0;
1028 }
1029
1030 static int j2kenc_destroy(AVCodecContext *avctx)
1031 {
1032     J2kEncoderContext *s = avctx->priv_data;
1033
1034     cleanup(s);
1035     return 0;
1036 }
1037
1038 AVCodec ff_jpeg2000_encoder = {
1039     .name           = "j2k",
1040     .type           = AVMEDIA_TYPE_VIDEO,
1041     .id             = CODEC_ID_JPEG2000,
1042     .priv_data_size = sizeof(J2kEncoderContext),
1043     .init           = j2kenc_init,
1044     .encode         = encode_frame,
1045     .close          = j2kenc_destroy,
1046     .capabilities= CODEC_CAP_EXPERIMENTAL,
1047     .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1048     .pix_fmts =
1049         (const enum PixelFormat[]) {PIX_FMT_RGB24, PIX_FMT_YUV444P, PIX_FMT_GRAY8,
1050 /*                              PIX_FMT_YUV420P,
1051                               PIX_FMT_YUV422P, PIX_FMT_YUV444P,
1052                               PIX_FMT_YUV410P, PIX_FMT_YUV411P,*/
1053                               -1}
1054 };