ebf8cc7f7dac5054901ac4edc4753a9d44a7f8e9
[ffmpeg.git] / libavcodec / j2kenc.c
1 /*
2  * JPEG2000 image encoder
3  * Copyright (c) 2007 Kamil Nowosad
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * JPEG2000 image encoder
24  * @file
25  * @author Kamil Nowosad
26  */
27
28 #include <float.h>
29 #include "avcodec.h"
30 #include "internal.h"
31 #include "bytestream.h"
32 #include "jpeg2000.h"
33 #include "libavutil/common.h"
34 #include "libavutil/opt.h"
35
36 #define NMSEDEC_BITS 7
37 #define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
38 #define WMSEDEC_SHIFT 13 ///< must be >= 13
39 #define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
40
41 #define CODEC_JP2 1
42 #define CODEC_J2K 0
43
44 static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
45            lut_nmsedec_ref0[1<<NMSEDEC_BITS],
46            lut_nmsedec_sig [1<<NMSEDEC_BITS],
47            lut_nmsedec_sig0[1<<NMSEDEC_BITS];
48
49 static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
50     {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
51      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
52      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
53      {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
54
55     {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
56      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
57      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
58      { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
59 };
60
61 typedef struct {
62    Jpeg2000Component *comp;
63 } Jpeg2000Tile;
64
65 typedef struct {
66     AVClass *class;
67     AVCodecContext *avctx;
68     const AVFrame *picture;
69
70     int width, height; ///< image width and height
71     uint8_t cbps[4]; ///< bits per sample in particular components
72     int chroma_shift[2];
73     uint8_t planar;
74     int ncomponents;
75     int tile_width, tile_height; ///< tile size
76     int numXtiles, numYtiles;
77
78     uint8_t *buf_start;
79     uint8_t *buf;
80     uint8_t *buf_end;
81     int bit_index;
82
83     int64_t lambda;
84
85     Jpeg2000CodingStyle codsty;
86     Jpeg2000QuantStyle  qntsty;
87
88     Jpeg2000Tile *tile;
89
90     int format;
91 } Jpeg2000EncoderContext;
92
93
94 /* debug */
95 #if 0
96 #undef ifprintf
97 #undef printf
98
99 static void nspaces(FILE *fd, int n)
100 {
101     while(n--) putc(' ', fd);
102 }
103
104 static void printcomp(Jpeg2000Component *comp)
105 {
106     int i;
107     for (i = 0; i < comp->y1 - comp->y0; i++)
108         ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
109 }
110
111 static void dump(Jpeg2000EncoderContext *s, FILE *fd)
112 {
113     int tileno, compno, reslevelno, bandno, precno;
114     fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
115                 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
116                 "tiles:\n",
117             s->width, s->height, s->tile_width, s->tile_height,
118             s->numXtiles, s->numYtiles, s->ncomponents);
119     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
120         Jpeg2000Tile *tile = s->tile + tileno;
121         nspaces(fd, 2);
122         fprintf(fd, "tile %d:\n", tileno);
123         for(compno = 0; compno < s->ncomponents; compno++){
124             Jpeg2000Component *comp = tile->comp + compno;
125             nspaces(fd, 4);
126             fprintf(fd, "component %d:\n", compno);
127             nspaces(fd, 4);
128             fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
129                         comp->x0, comp->x1, comp->y0, comp->y1);
130             for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
131                 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
132                 nspaces(fd, 6);
133                 fprintf(fd, "reslevel %d:\n", reslevelno);
134                 nspaces(fd, 6);
135                 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
136                         reslevel->x0, reslevel->x1, reslevel->y0,
137                         reslevel->y1, reslevel->nbands);
138                 for(bandno = 0; bandno < reslevel->nbands; bandno++){
139                     Jpeg2000Band *band = reslevel->band + bandno;
140                     nspaces(fd, 8);
141                     fprintf(fd, "band %d:\n", bandno);
142                     nspaces(fd, 8);
143                     fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
144                                 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
145                                 band->x0, band->x1,
146                                 band->y0, band->y1,
147                                 band->codeblock_width, band->codeblock_height,
148                                 band->cblknx, band->cblkny);
149                     for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
150                         Jpeg2000Prec *prec = band->prec + precno;
151                         nspaces(fd, 10);
152                         fprintf(fd, "prec %d:\n", precno);
153                         nspaces(fd, 10);
154                         fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
155                                      prec->xi0, prec->xi1, prec->yi0, prec->yi1);
156                     }
157                 }
158             }
159         }
160     }
161 }
162 #endif
163
164 /* bitstream routines */
165
166 /** put n times val bit */
167 static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
168 {
169     while (n-- > 0){
170         if (s->bit_index == 8)
171         {
172             s->bit_index = *s->buf == 0xff;
173             *(++s->buf) = 0;
174         }
175         *s->buf |= val << (7 - s->bit_index++);
176     }
177 }
178
179 /** put n least significant bits of a number num */
180 static void put_num(Jpeg2000EncoderContext *s, int num, int n)
181 {
182     while(--n >= 0)
183         put_bits(s, (num >> n) & 1, 1);
184 }
185
186 /** flush the bitstream */
187 static void j2k_flush(Jpeg2000EncoderContext *s)
188 {
189     if (s->bit_index){
190         s->bit_index = 0;
191         s->buf++;
192     }
193 }
194
195 /* tag tree routines */
196
197 /** code the value stored in node */
198 static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
199 {
200     Jpeg2000TgtNode *stack[30];
201     int sp = 1, curval = 0;
202     stack[0] = node;
203
204     node = node->parent;
205     while(node){
206         if (node->vis){
207             curval = node->val;
208             break;
209         }
210         node->vis++;
211         stack[sp++] = node;
212         node = node->parent;
213     }
214     while(--sp >= 0){
215         if (stack[sp]->val >= threshold){
216             put_bits(s, 0, threshold - curval);
217             break;
218         }
219         put_bits(s, 0, stack[sp]->val - curval);
220         put_bits(s, 1, 1);
221         curval = stack[sp]->val;
222     }
223 }
224
225 /** update the value in node */
226 static void tag_tree_update(Jpeg2000TgtNode *node)
227 {
228     int lev = 0;
229     while (node->parent){
230         if (node->parent->val <= node->val)
231             break;
232         node->parent->val = node->val;
233         node = node->parent;
234         lev++;
235     }
236 }
237
238 static int put_siz(Jpeg2000EncoderContext *s)
239 {
240     int i;
241
242     if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
243         return -1;
244
245     bytestream_put_be16(&s->buf, JPEG2000_SIZ);
246     bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
247     bytestream_put_be16(&s->buf, 0); // Rsiz
248     bytestream_put_be32(&s->buf, s->width); // width
249     bytestream_put_be32(&s->buf, s->height); // height
250     bytestream_put_be32(&s->buf, 0); // X0Siz
251     bytestream_put_be32(&s->buf, 0); // Y0Siz
252
253     bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
254     bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
255     bytestream_put_be32(&s->buf, 0); // XT0Siz
256     bytestream_put_be32(&s->buf, 0); // YT0Siz
257     bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
258
259     for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
260         bytestream_put_byte(&s->buf, 7);
261         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
262         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
263     }
264     return 0;
265 }
266
267 static int put_cod(Jpeg2000EncoderContext *s)
268 {
269     Jpeg2000CodingStyle *codsty = &s->codsty;
270
271     if (s->buf_end - s->buf < 14)
272         return -1;
273
274     bytestream_put_be16(&s->buf, JPEG2000_COD);
275     bytestream_put_be16(&s->buf, 12); // Lcod
276     bytestream_put_byte(&s->buf, 0);  // Scod
277     // SGcod
278     bytestream_put_byte(&s->buf, 0); // progression level
279     bytestream_put_be16(&s->buf, 1); // num of layers
280     if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
281         bytestream_put_byte(&s->buf, 0); // unspecified
282     }else{
283         bytestream_put_byte(&s->buf, 0); // unspecified
284     }
285     // SPcod
286     bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
287     bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
288     bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
289     bytestream_put_byte(&s->buf, 0); // cblk style
290     bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
291     return 0;
292 }
293
294 static int put_qcd(Jpeg2000EncoderContext *s, int compno)
295 {
296     int i, size;
297     Jpeg2000CodingStyle *codsty = &s->codsty;
298     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
299
300     if (qntsty->quantsty == JPEG2000_QSTY_NONE)
301         size = 4 + 3 * (codsty->nreslevels-1);
302     else // QSTY_SE
303         size = 5 + 6 * (codsty->nreslevels-1);
304
305     if (s->buf_end - s->buf < size + 2)
306         return -1;
307
308     bytestream_put_be16(&s->buf, JPEG2000_QCD);
309     bytestream_put_be16(&s->buf, size);  // LQcd
310     bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
311     if (qntsty->quantsty == JPEG2000_QSTY_NONE)
312         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
313             bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
314     else // QSTY_SE
315         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
316             bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
317     return 0;
318 }
319
320 static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
321 {
322     uint8_t *psotptr;
323
324     if (s->buf_end - s->buf < 12)
325         return NULL;
326
327     bytestream_put_be16(&s->buf, JPEG2000_SOT);
328     bytestream_put_be16(&s->buf, 10); // Lsot
329     bytestream_put_be16(&s->buf, tileno); // Isot
330
331     psotptr = s->buf;
332     bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
333
334     bytestream_put_byte(&s->buf, 0); // TPsot
335     bytestream_put_byte(&s->buf, 1); // TNsot
336     return psotptr;
337 }
338
339 /**
340  * compute the sizes of tiles, resolution levels, bands, etc.
341  * allocate memory for them
342  * divide the input image into tile-components
343  */
344 static int init_tiles(Jpeg2000EncoderContext *s)
345 {
346     int tileno, tilex, tiley, compno;
347     Jpeg2000CodingStyle *codsty = &s->codsty;
348     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
349
350     s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
351     s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
352
353     s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
354     if (!s->tile)
355         return AVERROR(ENOMEM);
356     for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
357         for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
358             Jpeg2000Tile *tile = s->tile + tileno;
359
360             tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
361             if (!tile->comp)
362                 return AVERROR(ENOMEM);
363             for (compno = 0; compno < s->ncomponents; compno++){
364                 Jpeg2000Component *comp = tile->comp + compno;
365                 int ret, i, j;
366
367                 comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
368                 comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
369                 comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
370                 comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
371                 if (compno > 0)
372                     for (i = 0; i < 2; i++)
373                         for (j = 0; j < 2; j++)
374                             comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
375
376                 if ((ret = ff_jpeg2000_init_component(comp,
377                                                 codsty,
378                                                 qntsty,
379                                                 s->cbps[compno],
380                                                 compno?1<<s->chroma_shift[0]:1,
381                                                 compno?1<<s->chroma_shift[1]:1,
382                                                 s->avctx
383                                                )) < 0)
384                     return ret;
385             }
386         }
387     return 0;
388 }
389
390 static void copy_frame(Jpeg2000EncoderContext *s)
391 {
392     int tileno, compno, i, y, x;
393     uint8_t *line;
394     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
395         Jpeg2000Tile *tile = s->tile + tileno;
396         if (s->planar){
397             for (compno = 0; compno < s->ncomponents; compno++){
398                 Jpeg2000Component *comp = tile->comp + compno;
399                 int *dst = comp->i_data;
400                 line = s->picture->data[compno]
401                        + comp->coord[1][0] * s->picture->linesize[compno]
402                        + comp->coord[0][0];
403                 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
404                     uint8_t *ptr = line;
405                     for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
406                         *dst++ = *ptr++ - (1 << 7);
407                     line += s->picture->linesize[compno];
408                 }
409             }
410         } else{
411             line = s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0]
412                    + tile->comp[0].coord[0][0] * s->ncomponents;
413
414             i = 0;
415             for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
416                 uint8_t *ptr = line;
417                 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
418                     for (compno = 0; compno < s->ncomponents; compno++){
419                         tile->comp[compno].i_data[i] = *ptr++  - (1 << 7);
420                     }
421                 }
422                 line += s->picture->linesize[0];
423             }
424         }
425     }
426 }
427
428 static void init_quantization(Jpeg2000EncoderContext *s)
429 {
430     int compno, reslevelno, bandno;
431     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
432     Jpeg2000CodingStyle *codsty = &s->codsty;
433
434     for (compno = 0; compno < s->ncomponents; compno++){
435         int gbandno = 0;
436         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
437             int nbands, lev = codsty->nreslevels - reslevelno - 1;
438             nbands = reslevelno ? 3 : 1;
439             for (bandno = 0; bandno < nbands; bandno++, gbandno++){
440                 int expn, mant = 0;
441
442                 if (codsty->transform == FF_DWT97_INT){
443                     int bandpos = bandno + (reslevelno>0),
444                         ss = 81920000 / dwt_norms[0][bandpos][lev],
445                         log = av_log2(ss);
446                     mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
447                     expn = s->cbps[compno] - log + 13;
448                 } else
449                     expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
450
451                 qntsty->expn[gbandno] = expn;
452                 qntsty->mant[gbandno] = mant;
453             }
454         }
455     }
456 }
457
458 static void init_luts(void)
459 {
460     int i, a,
461         mask = ~((1<<NMSEDEC_FRACBITS)-1);
462
463     for (i = 0; i < (1 << NMSEDEC_BITS); i++){
464         lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
465         lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
466
467         a = (i >> (NMSEDEC_BITS-2)&2) + 1;
468         lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
469                                     << 13-NMSEDEC_FRACBITS, 0);
470         lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
471                                     << 1, 0);
472     }
473 }
474
475 /* tier-1 routines */
476 static int getnmsedec_sig(int x, int bpno)
477 {
478     if (bpno > NMSEDEC_FRACBITS)
479         return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
480     return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
481 }
482
483 static int getnmsedec_ref(int x, int bpno)
484 {
485     if (bpno > NMSEDEC_FRACBITS)
486         return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
487     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
488 }
489
490 static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
491 {
492     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
493     for (y0 = 0; y0 < height; y0 += 4)
494         for (x = 0; x < width; x++)
495             for (y = y0; y < height && y < y0+4; y++){
496                 if (!(t1->flags[y+1][x+1] & JPEG2000_T1_SIG) && (t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)){
497                     int ctxno = ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1], bandno),
498                         bit = t1->data[y][x] & mask ? 1 : 0;
499                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
500                     if (bit){
501                         int xorbit;
502                         int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
503                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
504                         *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
505                         ff_jpeg2000_set_significance(t1, x, y, t1->flags[y+1][x+1] >> 15);
506                     }
507                     t1->flags[y+1][x+1] |= JPEG2000_T1_VIS;
508                 }
509             }
510 }
511
512 static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
513 {
514     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
515     for (y0 = 0; y0 < height; y0 += 4)
516         for (x = 0; x < width; x++)
517             for (y = y0; y < height && y < y0+4; y++)
518                 if ((t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
519                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y+1][x+1]);
520                     *nmsedec += getnmsedec_ref(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
521                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
522                     t1->flags[y+1][x+1] |= JPEG2000_T1_REF;
523                 }
524 }
525
526 static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
527 {
528     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
529     for (y0 = 0; y0 < height; y0 += 4)
530         for (x = 0; x < width; x++){
531             if (y0 + 3 < height && !(
532             (t1->flags[y0+1][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
533             (t1->flags[y0+2][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
534             (t1->flags[y0+3][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
535             (t1->flags[y0+4][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
536             {
537                 // aggregation mode
538                 int rlen;
539                 for (rlen = 0; rlen < 4; rlen++)
540                     if (t1->data[y0+rlen][x] & mask)
541                         break;
542                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
543                 if (rlen == 4)
544                     continue;
545                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
546                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
547                 for (y = y0 + rlen; y < y0 + 4; y++){
548                     if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
549                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1], bandno);
550                         if (y > y0 + rlen)
551                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
552                         if (t1->data[y][x] & mask){ // newly significant
553                             int xorbit;
554                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
555                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
556                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
557                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[y+1][x+1] >> 15);
558                         }
559                     }
560                     t1->flags[y+1][x+1] &= ~JPEG2000_T1_VIS;
561                 }
562             } else{
563                 for (y = y0; y < y0 + 4 && y < height; y++){
564                     if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
565                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1], bandno);
566                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);
567                         if (t1->data[y][x] & mask){ // newly significant
568                             int xorbit;
569                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
570                             *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);
571                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);
572                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[y+1][x+1] >> 15);
573                         }
574                     }
575                     t1->flags[y+1][x+1] &= ~JPEG2000_T1_VIS;
576                 }
577             }
578         }
579 }
580
581 static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
582                         int width, int height, int bandpos, int lev)
583 {
584     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
585     int64_t wmsedec = 0;
586
587     for (y = 0; y < height+2; y++)
588         memset(t1->flags[y], 0, (width+2)*sizeof(int));
589
590     for (y = 0; y < height; y++){
591         for (x = 0; x < width; x++){
592             if (t1->data[y][x] < 0){
593                 t1->flags[y+1][x+1] |= JPEG2000_T1_SGN;
594                 t1->data[y][x] = -t1->data[y][x];
595             }
596             max = FFMAX(max, t1->data[y][x]);
597         }
598     }
599
600     if (max == 0){
601         cblk->nonzerobits = 0;
602         bpno = 0;
603     } else{
604         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
605         bpno = cblk->nonzerobits - 1;
606     }
607
608     ff_mqc_initenc(&t1->mqc, cblk->data);
609
610     for (passno = 0; bpno >= 0; passno++){
611         nmsedec=0;
612
613         switch(pass_t){
614             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
615                     break;
616             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
617                     break;
618             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
619                     break;
620         }
621
622         cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
623         wmsedec += (int64_t)nmsedec << (2*bpno);
624         cblk->passes[passno].disto = wmsedec;
625
626         if (++pass_t == 3){
627             pass_t = 0;
628             bpno--;
629         }
630     }
631     cblk->npasses = passno;
632     cblk->ninclpasses = passno;
633
634     cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
635 }
636
637 /* tier-2 routines: */
638
639 static void putnumpasses(Jpeg2000EncoderContext *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(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *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         Jpeg2000Band *band = rlevel->band + bandno;
682         Jpeg2000Prec *prec = band->prec + precno;
683         int yi, xi, pos;
684         int cblknw = prec->nb_codeblocks_width;
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 = 0; yi < prec->nb_codeblocks_height; yi++){
691             for (xi = 0; xi < cblknw; xi++, pos++){
692                 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
693                 tag_tree_update(prec->cblkincl + pos);
694                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
695                 tag_tree_update(prec->zerobits + pos);
696             }
697         }
698
699         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
700             for (xi = 0; xi < cblknw; xi++, pos++){
701                 int pad = 0, llen, length;
702                 Jpeg2000Cblk *cblk = prec->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         Jpeg2000Band *band = rlevel->band + bandno;
732         Jpeg2000Prec *prec = band->prec + precno;
733         int yi, cblknw = prec->nb_codeblocks_width;
734         for (yi =0; yi < prec->nb_codeblocks_height; yi++){
735             int xi;
736             for (xi = 0; xi < cblknw; xi++){
737                 Jpeg2000Cblk *cblk = prec->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                                                                - cblk->passes[cblk->ninclpasses-1].flushed_len);
743                     bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
744                                                    cblk->passes[cblk->ninclpasses-1].flushed_len);
745                 }
746             }
747         }
748     }
749     return 0;
750 }
751
752 static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
753 {
754     int compno, reslevelno, ret;
755     Jpeg2000CodingStyle *codsty = &s->codsty;
756     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
757
758     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
759     // lay-rlevel-comp-pos progression
760     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
761         for (compno = 0; compno < s->ncomponents; compno++){
762             int precno;
763             Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
764             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
765                 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
766                               qntsty->nguardbits)) < 0)
767                     return ret;
768             }
769         }
770     }
771     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
772     return 0;
773 }
774
775 static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
776 {
777     int passno, res = 0;
778     for (passno = 0; passno < cblk->npasses; passno++){
779         int dr;
780         int64_t dd;
781
782         dr = cblk->passes[passno].rate
783            - (res ? cblk->passes[res-1].rate:0);
784         dd = cblk->passes[passno].disto
785            - (res ? cblk->passes[res-1].disto:0);
786
787         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
788             res = passno+1;
789     }
790     return res;
791 }
792
793 static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
794 {
795     int precno, compno, reslevelno, bandno, cblkno, lev;
796     Jpeg2000CodingStyle *codsty = &s->codsty;
797
798     for (compno = 0; compno < s->ncomponents; compno++){
799         Jpeg2000Component *comp = tile->comp + compno;
800
801         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
802             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
803
804             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
805                 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
806                     int bandpos = bandno + (reslevelno > 0);
807                     Jpeg2000Band *band = reslevel->band + bandno;
808                     Jpeg2000Prec *prec = band->prec + precno;
809
810                     for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
811                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
812
813                         cblk->ninclpasses = getcut(cblk, s->lambda,
814                                 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
815                     }
816                 }
817             }
818         }
819     }
820 }
821
822 static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
823 {
824     int compno, reslevelno, bandno, ret;
825     Jpeg2000T1Context t1;
826     Jpeg2000CodingStyle *codsty = &s->codsty;
827     for (compno = 0; compno < s->ncomponents; compno++){
828         Jpeg2000Component *comp = s->tile[tileno].comp + compno;
829
830         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
831         if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
832             return ret;
833         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
834
835         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
836             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
837
838             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
839                 Jpeg2000Band *band = reslevel->band + bandno;
840                 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
841                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
842                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
843                 y0 = yy0;
844                 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
845                             band->coord[1][1]) - band->coord[1][0] + yy0;
846
847                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
848                     continue;
849
850                 bandpos = bandno + (reslevelno > 0);
851
852                 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
853                     if (reslevelno == 0 || bandno == 1)
854                         xx0 = 0;
855                     else
856                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
857                     x0 = xx0;
858                     xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
859                                 band->coord[0][1]) - band->coord[0][0] + xx0;
860
861                     for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
862                         int y, x;
863                         if (codsty->transform == FF_DWT53){
864                             for (y = yy0; y < yy1; y++){
865                                 int *ptr = t1.data[y-yy0];
866                                 for (x = xx0; x < xx1; x++){
867                                     *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
868                                 }
869                             }
870                         } else{
871                             for (y = yy0; y < yy1; y++){
872                                 int *ptr = t1.data[y-yy0];
873                                 for (x = xx0; x < xx1; x++){
874                                     *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
875                                     *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
876                                     ptr++;
877                                 }
878                             }
879                         }
880                         encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
881                                     bandpos, codsty->nreslevels - reslevelno - 1);
882                         xx0 = xx1;
883                         xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
884                     }
885                     yy0 = yy1;
886                     yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
887                 }
888             }
889         }
890         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
891     }
892
893     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
894     truncpasses(s, tile);
895     if ((ret = encode_packets(s, tile, tileno)) < 0)
896         return ret;
897     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
898     return 0;
899 }
900
901 static void cleanup(Jpeg2000EncoderContext *s)
902 {
903     int tileno, compno;
904     Jpeg2000CodingStyle *codsty = &s->codsty;
905
906     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
907         for (compno = 0; compno < s->ncomponents; compno++){
908             Jpeg2000Component *comp = s->tile[tileno].comp + compno;
909             ff_jpeg2000_cleanup(comp, codsty);
910         }
911         av_freep(&s->tile[tileno].comp);
912     }
913     av_freep(&s->tile);
914 }
915
916 static void reinit(Jpeg2000EncoderContext *s)
917 {
918     int tileno, compno;
919     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
920         Jpeg2000Tile *tile = s->tile + tileno;
921         for (compno = 0; compno < s->ncomponents; compno++)
922             ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
923     }
924 }
925
926 static void update_size(uint8_t *size, const uint8_t *end)
927 {
928     AV_WB32(size, end-size);
929 }
930
931 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
932                         const AVFrame *pict, int *got_packet)
933 {
934     int tileno, ret;
935     Jpeg2000EncoderContext *s = avctx->priv_data;
936     uint8_t *chunkstart, *jp2cstart, *jp2hstart;
937
938     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + FF_MIN_BUFFER_SIZE)) < 0)
939         return ret;
940
941     // init:
942     s->buf = s->buf_start = pkt->data;
943     s->buf_end = pkt->data + pkt->size;
944
945     s->picture = pict;
946
947     s->lambda = s->picture->quality * LAMBDA_SCALE;
948
949     copy_frame(s);
950     reinit(s);
951
952     if (s->format == CODEC_JP2) {
953         av_assert0(s->buf == pkt->data);
954
955         bytestream_put_be32(&s->buf, 0x0000000C);
956         bytestream_put_be32(&s->buf, 0x6A502020);
957         bytestream_put_be32(&s->buf, 0x0D0A870A);
958
959         chunkstart = s->buf;
960         bytestream_put_be32(&s->buf, 0);
961         bytestream_put_buffer(&s->buf, "ftyp", 4);
962         bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
963         bytestream_put_be32(&s->buf, 0);
964         update_size(chunkstart, s->buf);
965
966         jp2hstart = s->buf;
967         bytestream_put_be32(&s->buf, 0);
968         bytestream_put_buffer(&s->buf, "jp2h", 4);
969
970         chunkstart = s->buf;
971         bytestream_put_be32(&s->buf, 0);
972         bytestream_put_buffer(&s->buf, "ihdr", 4);
973         bytestream_put_be32(&s->buf, avctx->height);
974         bytestream_put_be32(&s->buf, avctx->width);
975         bytestream_put_be16(&s->buf, s->ncomponents);
976         bytestream_put_byte(&s->buf, s->cbps[0]);
977         bytestream_put_byte(&s->buf, 7);
978         bytestream_put_byte(&s->buf, 0);
979         bytestream_put_byte(&s->buf, 0);
980         update_size(chunkstart, s->buf);
981
982         chunkstart = s->buf;
983         bytestream_put_be32(&s->buf, 0);
984         bytestream_put_buffer(&s->buf, "colr", 4);
985         bytestream_put_byte(&s->buf, 1);
986         bytestream_put_byte(&s->buf, 0);
987         bytestream_put_byte(&s->buf, 0);
988         if (s->ncomponents == 1) {
989             bytestream_put_be32(&s->buf, 17);
990         } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
991             bytestream_put_be32(&s->buf, 16);
992         } else {
993             bytestream_put_be32(&s->buf, 18);
994         }
995         update_size(chunkstart, s->buf);
996         update_size(jp2hstart, s->buf);
997
998         jp2cstart = s->buf;
999         bytestream_put_be32(&s->buf, 0);
1000         bytestream_put_buffer(&s->buf, "jp2c", 4);
1001     }
1002
1003     if (s->buf_end - s->buf < 2)
1004         return -1;
1005     bytestream_put_be16(&s->buf, JPEG2000_SOC);
1006     if ((ret = put_siz(s)) < 0)
1007         return ret;
1008     if ((ret = put_cod(s)) < 0)
1009         return ret;
1010     if ((ret = put_qcd(s, 0)) < 0)
1011         return ret;
1012
1013     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1014         uint8_t *psotptr;
1015         if (!(psotptr = put_sot(s, tileno)))
1016             return -1;
1017         if (s->buf_end - s->buf < 2)
1018             return -1;
1019         bytestream_put_be16(&s->buf, JPEG2000_SOD);
1020         if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1021             return ret;
1022         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1023     }
1024     if (s->buf_end - s->buf < 2)
1025         return -1;
1026     bytestream_put_be16(&s->buf, JPEG2000_EOC);
1027
1028     if (s->format == CODEC_JP2)
1029         update_size(jp2cstart, s->buf);
1030
1031     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1032     pkt->size = s->buf - s->buf_start;
1033     pkt->flags |= AV_PKT_FLAG_KEY;
1034     *got_packet = 1;
1035
1036     return 0;
1037 }
1038
1039 static av_cold int j2kenc_init(AVCodecContext *avctx)
1040 {
1041     int i, ret;
1042     Jpeg2000EncoderContext *s = avctx->priv_data;
1043     Jpeg2000CodingStyle *codsty = &s->codsty;
1044     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1045
1046     s->avctx = avctx;
1047     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1048
1049     // defaults:
1050     // TODO: implement setting non-standard precinct size
1051     memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1052     memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1053     codsty->nreslevels2decode=
1054     codsty->nreslevels       = 7;
1055     codsty->log2_cblk_width  = 4;
1056     codsty->log2_cblk_height = 4;
1057     codsty->transform        = avctx->prediction_method ? FF_DWT53 : FF_DWT97_INT;
1058
1059     qntsty->nguardbits       = 1;
1060
1061     s->tile_width            = 256;
1062     s->tile_height           = 256;
1063
1064     if (codsty->transform == FF_DWT53)
1065         qntsty->quantsty = JPEG2000_QSTY_NONE;
1066     else
1067         qntsty->quantsty = JPEG2000_QSTY_SE;
1068
1069     s->width = avctx->width;
1070     s->height = avctx->height;
1071
1072     for (i = 0; i < 3; i++)
1073         s->cbps[i] = 8;
1074
1075     if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
1076         s->ncomponents = 3;
1077     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
1078         s->ncomponents = 1;
1079     } else{ // planar YUV
1080         s->planar = 1;
1081         s->ncomponents = 3;
1082         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
1083                 s->chroma_shift, s->chroma_shift + 1);
1084     }
1085
1086     ff_jpeg2000_init_tier1_luts();
1087     ff_mqc_init_context_tables();
1088     init_luts();
1089
1090     init_quantization(s);
1091     if ((ret=init_tiles(s)) < 0)
1092         return ret;
1093
1094     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1095
1096     return 0;
1097 }
1098
1099 static int j2kenc_destroy(AVCodecContext *avctx)
1100 {
1101     Jpeg2000EncoderContext *s = avctx->priv_data;
1102
1103     cleanup(s);
1104     return 0;
1105 }
1106
1107 // taken from the libopenjpeg wraper so it matches
1108
1109 #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1110 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1111 static const AVOption options[] = {
1112     { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_J2K   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
1113     { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
1114     { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
1115     { NULL }
1116 };
1117
1118 static const AVClass j2k_class = {
1119     .class_name = "jpeg 2000 encoder",
1120     .item_name  = av_default_item_name,
1121     .option     = options,
1122     .version    = LIBAVUTIL_VERSION_INT,
1123 };
1124
1125 AVCodec ff_jpeg2000_encoder = {
1126     .name           = "jpeg2000",
1127     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1128     .type           = AVMEDIA_TYPE_VIDEO,
1129     .id             = AV_CODEC_ID_JPEG2000,
1130     .priv_data_size = sizeof(Jpeg2000EncoderContext),
1131     .init           = j2kenc_init,
1132     .encode2        = encode_frame,
1133     .close          = j2kenc_destroy,
1134     .capabilities   = CODEC_CAP_EXPERIMENTAL,
1135     .pix_fmts       = (const enum AVPixelFormat[]) {
1136         AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1137 /*      AV_PIX_FMT_YUV420P,
1138         AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
1139         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,*/
1140         AV_PIX_FMT_NONE
1141     },
1142     .priv_class     = &j2k_class,
1143 };