]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kenc.c
Merge remote-tracking branch 'qatar/master'
[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]))
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     for (y0 = 0; y0 < height; y0 += 4)
491         for (x = 0; x < width; x++)
492             for (y = y0; y < height && y < y0+4; y++){
493                 if (!(t1->flags[y+1][x+1] & J2K_T1_SIG) && (t1->flags[y+1][x+1] & J2K_T1_SIG_NB)){
494                     int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno),
495                         bit = t1->data[y][x] & mask ? 1 : 0;
496                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
497                     if (bit){
498                         int xorbit;
499                         int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
500                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
501                         *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
502                         ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
503                     }
504                     t1->flags[y+1][x+1] |= J2K_T1_VIS;
505                 }
506             }
507 }
508
509 static void encode_refpass(J2kT1Context *t1, int width, int height, int *nmsedec, int bpno)
510 {
511     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
512     for (y0 = 0; y0 < height; y0 += 4)
513         for (x = 0; x < width; x++)
514             for (y = y0; y < height && y < y0+4; y++)
515                 if ((t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)) == J2K_T1_SIG){
516                     int ctxno = ff_j2k_getrefctxno(t1->flags[y+1][x+1]);
517                     *nmsedec += getnmsedec_ref(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
518                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
519                     t1->flags[y+1][x+1] |= J2K_T1_REF;
520                 }
521 }
522
523 static void encode_clnpass(J2kT1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
524 {
525     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
526     for (y0 = 0; y0 < height; y0 += 4)
527         for (x = 0; x < width; x++){
528             if (y0 + 3 < height && !(
529             (t1->flags[y0+1][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
530             (t1->flags[y0+2][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
531             (t1->flags[y0+3][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
532             (t1->flags[y0+4][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG))))
533             {
534                 // aggregation mode
535                 int rlen;
536                 for (rlen = 0; rlen < 4; rlen++)
537                     if (t1->data[y0+rlen][x] & mask)
538                         break;
539                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
540                 if (rlen == 4)
541                     continue;
542                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
543                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
544                 for (y = y0 + rlen; y < y0 + 4; y++){
545                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
546                         int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno);
547                         if (y > y0 + rlen)
548                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
549                         if (t1->data[y][x] & mask){ // newly significant
550                             int xorbit;
551                             int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
552                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
553                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
554                             ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
555                         }
556                     }
557                     t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
558                 }
559             } else{
560                 for (y = y0; y < y0 + 4 && y < height; y++){
561                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
562                         int ctxno = ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno);
563                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
564                         if (t1->data[y][x] & mask){ // newly significant
565                             int xorbit;
566                             int ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
567                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
568                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
569                             ff_j2k_set_significant(t1, x, y, t1->flags[y+1][x+1] >> 15);
570                         }
571                     }
572                     t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
573                 }
574             }
575         }
576 }
577
578 static void encode_cblk(J2kEncoderContext *s, J2kT1Context *t1, J2kCblk *cblk, J2kTile *tile,
579                         int width, int height, int bandpos, int lev)
580 {
581     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
582     int64_t wmsedec = 0;
583
584     for (y = 0; y < height+2; y++)
585         memset(t1->flags[y], 0, (width+2)*sizeof(int));
586
587     for (y = 0; y < height; y++){
588         for (x = 0; x < width; x++){
589             if (t1->data[y][x] < 0){
590                 t1->flags[y+1][x+1] |= J2K_T1_SGN;
591                 t1->data[y][x] = -t1->data[y][x];
592             }
593             max = FFMAX(max, t1->data[y][x]);
594         }
595     }
596
597     if (max == 0){
598         cblk->nonzerobits = 0;
599         bpno = 0;
600     } else{
601         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
602         bpno = cblk->nonzerobits - 1;
603     }
604
605     ff_mqc_initenc(&t1->mqc, cblk->data);
606
607     for (passno = 0; bpno >= 0; passno++){
608         nmsedec=0;
609
610         switch(pass_t){
611             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
612                     break;
613             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
614                     break;
615             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
616                     break;
617         }
618
619         cblk->passes[passno].rate = 3 + ff_mqc_length(&t1->mqc);
620         wmsedec += (int64_t)nmsedec << (2*bpno);
621         cblk->passes[passno].disto = wmsedec;
622
623         if (++pass_t == 3){
624             pass_t = 0;
625             bpno--;
626         }
627     }
628     cblk->npasses = passno;
629     cblk->ninclpasses = passno;
630
631     // TODO: optional flush on each pass
632     cblk->passes[passno-1].rate = ff_mqc_flush(&t1->mqc);
633 }
634
635 /* tier-2 routines: */
636
637 static void putnumpasses(J2kEncoderContext *s, int n)
638 {
639     if (n == 1)
640         put_num(s, 0, 1);
641     else if (n == 2)
642         put_num(s, 2, 2);
643     else if (n <= 5)
644         put_num(s, 0xc | (n-3), 4);
645     else if (n <= 36)
646         put_num(s, 0x1e0 | (n-6), 9);
647     else
648         put_num(s, 0xff80 | (n-37), 16);
649 }
650
651
652 static int encode_packet(J2kEncoderContext *s, J2kResLevel *rlevel, int precno,
653                           uint8_t *expn, int numgbits)
654 {
655     int bandno, empty = 1;
656
657     // init bitstream
658     *s->buf = 0;
659     s->bit_index = 0;
660
661     // header
662
663     // is the packet empty?
664     for (bandno = 0; bandno < rlevel->nbands; bandno++){
665         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
666         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
667             empty = 0;
668             break;
669         }
670     }
671
672     put_bits(s, !empty, 1);
673     if (empty){
674         j2k_flush(s);
675         return 0;
676     }
677
678     for (bandno = 0; bandno < rlevel->nbands; bandno++){
679         J2kBand *band = rlevel->band + bandno;
680         J2kPrec *prec = band->prec + precno;
681         int yi, xi, pos;
682         int cblknw = prec->xi1 - prec->xi0;
683
684         if (band->coord[0][0] == band->coord[0][1]
685         ||  band->coord[1][0] == band->coord[1][1])
686             continue;
687
688         for (pos=0, yi = prec->yi0; yi < prec->yi1; yi++){
689             for (xi = prec->xi0; xi < prec->xi1; xi++, pos++){
690                 prec->cblkincl[pos].val = band->cblk[yi * cblknw + xi].ninclpasses == 0;
691                 tag_tree_update(prec->cblkincl + pos);
692                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - band->cblk[yi * cblknw + xi].nonzerobits;
693                 tag_tree_update(prec->zerobits + pos);
694             }
695         }
696
697         for (pos=0, yi = prec->yi0; yi < prec->yi1; yi++){
698             for (xi = prec->xi0; xi < prec->xi1; xi++, pos++){
699                 int pad = 0, llen, length;
700                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
701
702                 if (s->buf_end - s->buf < 20) // approximately
703                     return -1;
704
705                 // inclusion information
706                 tag_tree_code(s, prec->cblkincl + pos, 1);
707                 if (!cblk->ninclpasses)
708                     continue;
709                 // zerobits information
710                 tag_tree_code(s, prec->zerobits + pos, 100);
711                 // number of passes
712                 putnumpasses(s, cblk->ninclpasses);
713
714                 length = cblk->passes[cblk->ninclpasses-1].rate;
715                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
716                 if (llen < 0){
717                     pad = -llen;
718                     llen = 0;
719                 }
720                 // length of code block
721                 put_bits(s, 1, llen);
722                 put_bits(s, 0, 1);
723                 put_num(s, length, av_log2(length)+1+pad);
724             }
725         }
726     }
727     j2k_flush(s);
728     for (bandno = 0; bandno < rlevel->nbands; bandno++){
729         J2kBand *band = rlevel->band + bandno;
730         J2kPrec *prec = band->prec + precno;
731         int yi, cblknw = prec->xi1 - prec->xi0;
732         for (yi = prec->yi0; yi < prec->yi1; yi++){
733             int xi;
734             for (xi = prec->xi0; xi < prec->xi1; xi++){
735                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
736                 if (cblk->ninclpasses){
737                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
738                         return -1;
739                     bytestream_put_buffer(&s->buf, cblk->data, cblk->passes[cblk->ninclpasses-1].rate);
740                 }
741             }
742         }
743     }
744     return 0;
745 }
746
747 static int encode_packets(J2kEncoderContext *s, J2kTile *tile, int tileno)
748 {
749     int compno, reslevelno, ret;
750     J2kCodingStyle *codsty = &s->codsty;
751     J2kQuantStyle  *qntsty = &s->qntsty;
752
753     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
754     // lay-rlevel-comp-pos progression
755     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
756         for (compno = 0; compno < s->ncomponents; compno++){
757             int precno;
758             J2kResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
759             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
760                 if (ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
761                               qntsty->nguardbits))
762                     return ret;
763             }
764         }
765     }
766     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
767     return 0;
768 }
769
770 static int getcut(J2kCblk *cblk, int64_t lambda, int dwt_norm)
771 {
772     int passno, res = 0;
773     for (passno = 0; passno < cblk->npasses; passno++){
774         int dr;
775         int64_t dd;
776
777         dr = cblk->passes[passno].rate
778            - (res ? cblk->passes[res-1].rate:0);
779         dd = cblk->passes[passno].disto
780            - (res ? cblk->passes[res-1].disto:0);
781
782         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
783             res = passno+1;
784     }
785     return res;
786 }
787
788 static void truncpasses(J2kEncoderContext *s, J2kTile *tile)
789 {
790     int compno, reslevelno, bandno, cblkno, lev;
791     J2kCodingStyle *codsty = &s->codsty;
792
793     for (compno = 0; compno < s->ncomponents; compno++){
794         J2kComponent *comp = tile->comp + compno;
795
796         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
797             J2kResLevel *reslevel = comp->reslevel + reslevelno;
798
799             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
800                 int bandpos = bandno + (reslevelno > 0);
801                 J2kBand *band = reslevel->band + bandno;
802
803                 for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++){
804                     J2kCblk *cblk = band->cblk + cblkno;
805
806                     cblk->ninclpasses = getcut(cblk, s->lambda,
807                             (int64_t)dwt_norms[codsty->transform][bandpos][lev] * (int64_t)band->stepsize >> 13);
808                 }
809             }
810         }
811     }
812 }
813
814 static int encode_tile(J2kEncoderContext *s, J2kTile *tile, int tileno)
815 {
816     int compno, reslevelno, bandno, ret;
817     J2kT1Context t1;
818     J2kCodingStyle *codsty = &s->codsty;
819     for (compno = 0; compno < s->ncomponents; compno++){
820         J2kComponent *comp = s->tile[tileno].comp + compno;
821
822         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
823         if (ret = ff_dwt_encode(&comp->dwt, comp->data))
824             return ret;
825         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
826
827         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
828             J2kResLevel *reslevel = comp->reslevel + reslevelno;
829
830             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
831                 J2kBand *band = reslevel->band + bandno;
832                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
833                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
834                 y0 = yy0;
835                 yy1 = FFMIN(ff_j2k_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,
836                             band->coord[1][1]) - band->coord[1][0] + yy0;
837
838                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
839                     continue;
840
841                 bandpos = bandno + (reslevelno > 0);
842
843                 for (cblky = 0; cblky < band->cblkny; cblky++){
844                     if (reslevelno == 0 || bandno == 1)
845                         xx0 = 0;
846                     else
847                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
848                     x0 = xx0;
849                     xx1 = FFMIN(ff_j2k_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,
850                                 band->coord[0][1]) - band->coord[0][0] + xx0;
851
852                     for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++){
853                         int y, x;
854                         if (codsty->transform == FF_DWT53){
855                             for (y = yy0; y < yy1; y++){
856                                 int *ptr = t1.data[y-yy0];
857                                 for (x = xx0; x < xx1; x++){
858                                     *ptr++ = comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
859                                 }
860                             }
861                         } else{
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]);
866                                     *ptr++ = (int64_t)*ptr * (int64_t)(8192 * 8192 / band->stepsize) >> 13 - NMSEDEC_FRACBITS;
867                                 }
868                             }
869                         }
870                         encode_cblk(s, &t1, band->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
871                                     bandpos, codsty->nreslevels - reslevelno - 1);
872                         xx0 = xx1;
873                         xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);
874                     }
875                     yy0 = yy1;
876                     yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);
877                 }
878             }
879         }
880         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
881     }
882
883     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
884     truncpasses(s, tile);
885     if (ret = encode_packets(s, tile, tileno))
886         return ret;
887     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
888     return 0;
889 }
890
891 void cleanup(J2kEncoderContext *s)
892 {
893     int tileno, compno;
894     J2kCodingStyle *codsty = &s->codsty;
895
896     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
897         for (compno = 0; compno < s->ncomponents; compno++){
898             J2kComponent *comp = s->tile[tileno].comp + compno;
899             ff_j2k_cleanup(comp, codsty);
900         }
901         av_freep(&s->tile[tileno].comp);
902     }
903     av_freep(&s->tile);
904 }
905
906 static void reinit(J2kEncoderContext *s)
907 {
908     int tileno, compno;
909     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
910         J2kTile *tile = s->tile + tileno;
911         for (compno = 0; compno < s->ncomponents; compno++)
912             ff_j2k_reinit(tile->comp + compno, &s->codsty);
913     }
914 }
915
916 static int encode_frame(AVCodecContext *avctx,
917                         uint8_t *buf, int buf_size,
918                         void *data)
919 {
920     int tileno, ret;
921     J2kEncoderContext *s = avctx->priv_data;
922
923     // init:
924     s->buf = s->buf_start = buf;
925     s->buf_end = buf + buf_size;
926
927     s->picture = data;
928
929     s->lambda = s->picture->quality * LAMBDA_SCALE;
930
931     copy_frame(s);
932     reinit(s);
933
934     if (s->buf_end - s->buf < 2)
935         return -1;
936     bytestream_put_be16(&s->buf, J2K_SOC);
937     if (ret = put_siz(s))
938         return ret;
939     if (ret = put_cod(s))
940         return ret;
941     if (ret = put_qcd(s, 0))
942         return ret;
943
944     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
945         uint8_t *psotptr;
946         if ((psotptr = put_sot(s, tileno)) < 0)
947             return psotptr;
948         if (s->buf_end - s->buf < 2)
949             return -1;
950         bytestream_put_be16(&s->buf, J2K_SOD);
951         if (ret = encode_tile(s, s->tile + tileno, tileno))
952             return ret;
953         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
954     }
955     if (s->buf_end - s->buf < 2)
956         return -1;
957     bytestream_put_be16(&s->buf, J2K_EOC);
958
959     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
960     return s->buf - s->buf_start;
961 }
962
963 static av_cold int j2kenc_init(AVCodecContext *avctx)
964 {
965     int i, ret;
966     J2kEncoderContext *s = avctx->priv_data;
967     J2kCodingStyle *codsty = &s->codsty;
968     J2kQuantStyle  *qntsty = &s->qntsty;
969
970     s->avctx = avctx;
971     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
972
973     // defaults:
974     // TODO: implement setting non-standard precinct size
975     codsty->log2_prec_width  = 15;
976     codsty->log2_prec_height = 15;
977     codsty->nreslevels       = 7;
978     codsty->log2_cblk_width  = 4;
979     codsty->log2_cblk_height = 4;
980     codsty->transform        = 1;
981
982     qntsty->nguardbits       = 1;
983
984     s->tile_width            = 256;
985     s->tile_height           = 256;
986
987     if (codsty->transform == FF_DWT53)
988         qntsty->quantsty = J2K_QSTY_NONE;
989     else
990         qntsty->quantsty = J2K_QSTY_SE;
991
992     s->width = avctx->width;
993     s->height = avctx->height;
994
995     for (i = 0; i < 3; i++)
996         s->cbps[i] = 8;
997
998     if (avctx->pix_fmt == PIX_FMT_RGB24){
999         s->ncomponents = 3;
1000     } else if (avctx->pix_fmt == PIX_FMT_GRAY8){
1001         s->ncomponents = 1;
1002     } else{ // planar YUV
1003         s->planar = 1;
1004         s->ncomponents = 3;
1005         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
1006                 s->chroma_shift, s->chroma_shift + 1);
1007     }
1008
1009     ff_j2k_init_tier1_luts();
1010
1011     init_luts();
1012
1013     init_quantization(s);
1014     if (ret=init_tiles(s))
1015         return ret;
1016
1017     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1018
1019     return 0;
1020 }
1021
1022 static int j2kenc_destroy(AVCodecContext *avctx)
1023 {
1024     J2kEncoderContext *s = avctx->priv_data;
1025
1026     cleanup(s);
1027     return 0;
1028 }
1029
1030 AVCodec jpeg2000_encoder = {
1031     "j2k",
1032     CODEC_TYPE_VIDEO,
1033     CODEC_ID_JPEG2000,
1034     sizeof(J2kEncoderContext),
1035     j2kenc_init,
1036     encode_frame,
1037     j2kenc_destroy,
1038     NULL,
1039     0,
1040     .pix_fmts =
1041         (enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_RGB24,
1042                               PIX_FMT_YUV422P, PIX_FMT_YUV444P,
1043                               PIX_FMT_YUV410P, PIX_FMT_YUV411P,
1044                               -1}
1045 };