]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kenc.c
Merge commit '92fdc80cab2acad9f171ba38a08aa89b392bdadd'
[ffmpeg] / libavcodec / j2kenc.c
1 /*
2  * JPEG2000 image encoder
3  * Copyright (c) 2007 Kamil Nowosad
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * JPEG2000 image encoder
24  * @file
25  * @author Kamil Nowosad
26  */
27
28 #include <float.h>
29 #include "avcodec.h"
30 #include "internal.h"
31 #include "bytestream.h"
32 #include "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) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
497                     int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
498                         bit = t1->data[(y) * t1->stride + 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) * t1->stride + x+1], &xorbit);
503                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
504                         *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
505                         ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
506                     }
507                     t1->flags[(y+1) * t1->stride + 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) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
519                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
520                     *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
521                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
522                     t1->flags[(y+1) * t1->stride + 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) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
533             (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
534             (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
535             (t1->flags[(y0+4) * t1->stride + 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) * t1->stride + 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) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
549                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
550                         if (y > y0 + rlen)
551                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
552                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
553                             int xorbit;
554                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
555                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
556                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
557                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
558                         }
559                     }
560                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
561                 }
562             } else{
563                 for (y = y0; y < y0 + 4 && y < height; y++){
564                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
565                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
566                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
567                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
568                             int xorbit;
569                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
570                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
571                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
572                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
573                         }
574                     }
575                     t1->flags[(y+1) * t1->stride + 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     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
588
589     for (y = 0; y < height; y++){
590         for (x = 0; x < width; x++){
591             if (t1->data[(y) * t1->stride + x] < 0){
592                 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
593                 t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
594             }
595             max = FFMAX(max, t1->data[(y) * t1->stride + x]);
596         }
597     }
598
599     if (max == 0){
600         cblk->nonzerobits = 0;
601         bpno = 0;
602     } else{
603         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
604         bpno = cblk->nonzerobits - 1;
605     }
606
607     ff_mqc_initenc(&t1->mqc, cblk->data);
608
609     for (passno = 0; bpno >= 0; passno++){
610         nmsedec=0;
611
612         switch(pass_t){
613             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
614                     break;
615             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
616                     break;
617             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
618                     break;
619         }
620
621         cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
622         wmsedec += (int64_t)nmsedec << (2*bpno);
623         cblk->passes[passno].disto = wmsedec;
624
625         if (++pass_t == 3){
626             pass_t = 0;
627             bpno--;
628         }
629     }
630     cblk->npasses = passno;
631     cblk->ninclpasses = passno;
632
633     cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
634 }
635
636 /* tier-2 routines: */
637
638 static void putnumpasses(Jpeg2000EncoderContext *s, int n)
639 {
640     if (n == 1)
641         put_num(s, 0, 1);
642     else if (n == 2)
643         put_num(s, 2, 2);
644     else if (n <= 5)
645         put_num(s, 0xc | (n-3), 4);
646     else if (n <= 36)
647         put_num(s, 0x1e0 | (n-6), 9);
648     else
649         put_num(s, 0xff80 | (n-37), 16);
650 }
651
652
653 static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
654                           uint8_t *expn, int numgbits)
655 {
656     int bandno, empty = 1;
657
658     // init bitstream
659     *s->buf = 0;
660     s->bit_index = 0;
661
662     // header
663
664     // is the packet empty?
665     for (bandno = 0; bandno < rlevel->nbands; bandno++){
666         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
667         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
668             empty = 0;
669             break;
670         }
671     }
672
673     put_bits(s, !empty, 1);
674     if (empty){
675         j2k_flush(s);
676         return 0;
677     }
678
679     for (bandno = 0; bandno < rlevel->nbands; bandno++){
680         Jpeg2000Band *band = rlevel->band + bandno;
681         Jpeg2000Prec *prec = band->prec + precno;
682         int yi, xi, pos;
683         int cblknw = prec->nb_codeblocks_width;
684
685         if (band->coord[0][0] == band->coord[0][1]
686         ||  band->coord[1][0] == band->coord[1][1])
687             continue;
688
689         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
690             for (xi = 0; xi < cblknw; xi++, pos++){
691                 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
692                 tag_tree_update(prec->cblkincl + pos);
693                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
694                 tag_tree_update(prec->zerobits + pos);
695             }
696         }
697
698         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
699             for (xi = 0; xi < cblknw; xi++, pos++){
700                 int pad = 0, llen, length;
701                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
702
703                 if (s->buf_end - s->buf < 20) // approximately
704                     return -1;
705
706                 // inclusion information
707                 tag_tree_code(s, prec->cblkincl + pos, 1);
708                 if (!cblk->ninclpasses)
709                     continue;
710                 // zerobits information
711                 tag_tree_code(s, prec->zerobits + pos, 100);
712                 // number of passes
713                 putnumpasses(s, cblk->ninclpasses);
714
715                 length = cblk->passes[cblk->ninclpasses-1].rate;
716                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
717                 if (llen < 0){
718                     pad = -llen;
719                     llen = 0;
720                 }
721                 // length of code block
722                 put_bits(s, 1, llen);
723                 put_bits(s, 0, 1);
724                 put_num(s, length, av_log2(length)+1+pad);
725             }
726         }
727     }
728     j2k_flush(s);
729     for (bandno = 0; bandno < rlevel->nbands; bandno++){
730         Jpeg2000Band *band = rlevel->band + bandno;
731         Jpeg2000Prec *prec = band->prec + precno;
732         int yi, cblknw = prec->nb_codeblocks_width;
733         for (yi =0; yi < prec->nb_codeblocks_height; yi++){
734             int xi;
735             for (xi = 0; xi < cblknw; xi++){
736                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
737                 if (cblk->ninclpasses){
738                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
739                         return -1;
740                     bytestream_put_buffer(&s->buf, cblk->data,   cblk->passes[cblk->ninclpasses-1].rate
741                                                                - cblk->passes[cblk->ninclpasses-1].flushed_len);
742                     bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
743                                                    cblk->passes[cblk->ninclpasses-1].flushed_len);
744                 }
745             }
746         }
747     }
748     return 0;
749 }
750
751 static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
752 {
753     int compno, reslevelno, ret;
754     Jpeg2000CodingStyle *codsty = &s->codsty;
755     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
756
757     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
758     // lay-rlevel-comp-pos progression
759     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
760         for (compno = 0; compno < s->ncomponents; compno++){
761             int precno;
762             Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
763             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
764                 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
765                               qntsty->nguardbits)) < 0)
766                     return ret;
767             }
768         }
769     }
770     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
771     return 0;
772 }
773
774 static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
775 {
776     int passno, res = 0;
777     for (passno = 0; passno < cblk->npasses; passno++){
778         int dr;
779         int64_t dd;
780
781         dr = cblk->passes[passno].rate
782            - (res ? cblk->passes[res-1].rate:0);
783         dd = cblk->passes[passno].disto
784            - (res ? cblk->passes[res-1].disto:0);
785
786         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
787             res = passno+1;
788     }
789     return res;
790 }
791
792 static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
793 {
794     int precno, compno, reslevelno, bandno, cblkno, lev;
795     Jpeg2000CodingStyle *codsty = &s->codsty;
796
797     for (compno = 0; compno < s->ncomponents; compno++){
798         Jpeg2000Component *comp = tile->comp + compno;
799
800         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
801             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
802
803             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
804                 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
805                     int bandpos = bandno + (reslevelno > 0);
806                     Jpeg2000Band *band = reslevel->band + bandno;
807                     Jpeg2000Prec *prec = band->prec + precno;
808
809                     for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
810                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
811
812                         cblk->ninclpasses = getcut(cblk, s->lambda,
813                                 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
814                     }
815                 }
816             }
817         }
818     }
819 }
820
821 static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
822 {
823     int compno, reslevelno, bandno, ret;
824     Jpeg2000T1Context t1;
825     Jpeg2000CodingStyle *codsty = &s->codsty;
826     for (compno = 0; compno < s->ncomponents; compno++){
827         Jpeg2000Component *comp = s->tile[tileno].comp + compno;
828
829         t1.stride = (1<<codsty->log2_cblk_width) + 2;
830
831         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
832         if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
833             return ret;
834         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
835
836         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
837             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
838
839             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
840                 Jpeg2000Band *band = reslevel->band + bandno;
841                 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
842                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
843                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
844                 y0 = yy0;
845                 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
846                             band->coord[1][1]) - band->coord[1][0] + yy0;
847
848                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
849                     continue;
850
851                 bandpos = bandno + (reslevelno > 0);
852
853                 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
854                     if (reslevelno == 0 || bandno == 1)
855                         xx0 = 0;
856                     else
857                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
858                     x0 = xx0;
859                     xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
860                                 band->coord[0][1]) - band->coord[0][0] + xx0;
861
862                     for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
863                         int y, x;
864                         if (codsty->transform == FF_DWT53){
865                             for (y = yy0; y < yy1; y++){
866                                 int *ptr = t1.data + (y-yy0)*t1.stride;
867                                 for (x = xx0; x < xx1; x++){
868                                     *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
869                                 }
870                             }
871                         } else{
872                             for (y = yy0; y < yy1; y++){
873                                 int *ptr = t1.data + (y-yy0)*t1.stride;
874                                 for (x = xx0; x < xx1; x++){
875                                     *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
876                                     *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
877                                     ptr++;
878                                 }
879                             }
880                         }
881                         encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
882                                     bandpos, codsty->nreslevels - reslevelno - 1);
883                         xx0 = xx1;
884                         xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
885                     }
886                     yy0 = yy1;
887                     yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
888                 }
889             }
890         }
891         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
892     }
893
894     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
895     truncpasses(s, tile);
896     if ((ret = encode_packets(s, tile, tileno)) < 0)
897         return ret;
898     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
899     return 0;
900 }
901
902 static void cleanup(Jpeg2000EncoderContext *s)
903 {
904     int tileno, compno;
905     Jpeg2000CodingStyle *codsty = &s->codsty;
906
907     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
908         for (compno = 0; compno < s->ncomponents; compno++){
909             Jpeg2000Component *comp = s->tile[tileno].comp + compno;
910             ff_jpeg2000_cleanup(comp, codsty);
911         }
912         av_freep(&s->tile[tileno].comp);
913     }
914     av_freep(&s->tile);
915 }
916
917 static void reinit(Jpeg2000EncoderContext *s)
918 {
919     int tileno, compno;
920     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
921         Jpeg2000Tile *tile = s->tile + tileno;
922         for (compno = 0; compno < s->ncomponents; compno++)
923             ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
924     }
925 }
926
927 static void update_size(uint8_t *size, const uint8_t *end)
928 {
929     AV_WB32(size, end-size);
930 }
931
932 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
933                         const AVFrame *pict, int *got_packet)
934 {
935     int tileno, ret;
936     Jpeg2000EncoderContext *s = avctx->priv_data;
937     uint8_t *chunkstart, *jp2cstart, *jp2hstart;
938
939     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + FF_MIN_BUFFER_SIZE)) < 0)
940         return ret;
941
942     // init:
943     s->buf = s->buf_start = pkt->data;
944     s->buf_end = pkt->data + pkt->size;
945
946     s->picture = pict;
947
948     s->lambda = s->picture->quality * LAMBDA_SCALE;
949
950     copy_frame(s);
951     reinit(s);
952
953     if (s->format == CODEC_JP2) {
954         av_assert0(s->buf == pkt->data);
955
956         bytestream_put_be32(&s->buf, 0x0000000C);
957         bytestream_put_be32(&s->buf, 0x6A502020);
958         bytestream_put_be32(&s->buf, 0x0D0A870A);
959
960         chunkstart = s->buf;
961         bytestream_put_be32(&s->buf, 0);
962         bytestream_put_buffer(&s->buf, "ftyp", 4);
963         bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
964         bytestream_put_be32(&s->buf, 0);
965         update_size(chunkstart, s->buf);
966
967         jp2hstart = s->buf;
968         bytestream_put_be32(&s->buf, 0);
969         bytestream_put_buffer(&s->buf, "jp2h", 4);
970
971         chunkstart = s->buf;
972         bytestream_put_be32(&s->buf, 0);
973         bytestream_put_buffer(&s->buf, "ihdr", 4);
974         bytestream_put_be32(&s->buf, avctx->height);
975         bytestream_put_be32(&s->buf, avctx->width);
976         bytestream_put_be16(&s->buf, s->ncomponents);
977         bytestream_put_byte(&s->buf, s->cbps[0]);
978         bytestream_put_byte(&s->buf, 7);
979         bytestream_put_byte(&s->buf, 0);
980         bytestream_put_byte(&s->buf, 0);
981         update_size(chunkstart, s->buf);
982
983         chunkstart = s->buf;
984         bytestream_put_be32(&s->buf, 0);
985         bytestream_put_buffer(&s->buf, "colr", 4);
986         bytestream_put_byte(&s->buf, 1);
987         bytestream_put_byte(&s->buf, 0);
988         bytestream_put_byte(&s->buf, 0);
989         if (s->ncomponents == 1) {
990             bytestream_put_be32(&s->buf, 17);
991         } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
992             bytestream_put_be32(&s->buf, 16);
993         } else {
994             bytestream_put_be32(&s->buf, 18);
995         }
996         update_size(chunkstart, s->buf);
997         update_size(jp2hstart, s->buf);
998
999         jp2cstart = s->buf;
1000         bytestream_put_be32(&s->buf, 0);
1001         bytestream_put_buffer(&s->buf, "jp2c", 4);
1002     }
1003
1004     if (s->buf_end - s->buf < 2)
1005         return -1;
1006     bytestream_put_be16(&s->buf, JPEG2000_SOC);
1007     if ((ret = put_siz(s)) < 0)
1008         return ret;
1009     if ((ret = put_cod(s)) < 0)
1010         return ret;
1011     if ((ret = put_qcd(s, 0)) < 0)
1012         return ret;
1013
1014     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1015         uint8_t *psotptr;
1016         if (!(psotptr = put_sot(s, tileno)))
1017             return -1;
1018         if (s->buf_end - s->buf < 2)
1019             return -1;
1020         bytestream_put_be16(&s->buf, JPEG2000_SOD);
1021         if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1022             return ret;
1023         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1024     }
1025     if (s->buf_end - s->buf < 2)
1026         return -1;
1027     bytestream_put_be16(&s->buf, JPEG2000_EOC);
1028
1029     if (s->format == CODEC_JP2)
1030         update_size(jp2cstart, s->buf);
1031
1032     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1033     pkt->size = s->buf - s->buf_start;
1034     pkt->flags |= AV_PKT_FLAG_KEY;
1035     *got_packet = 1;
1036
1037     return 0;
1038 }
1039
1040 static av_cold int j2kenc_init(AVCodecContext *avctx)
1041 {
1042     int i, ret;
1043     Jpeg2000EncoderContext *s = avctx->priv_data;
1044     Jpeg2000CodingStyle *codsty = &s->codsty;
1045     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1046
1047     s->avctx = avctx;
1048     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1049
1050     // defaults:
1051     // TODO: implement setting non-standard precinct size
1052     memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1053     memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1054     codsty->nreslevels2decode=
1055     codsty->nreslevels       = 7;
1056     codsty->log2_cblk_width  = 4;
1057     codsty->log2_cblk_height = 4;
1058     codsty->transform        = avctx->prediction_method ? FF_DWT53 : FF_DWT97_INT;
1059
1060     qntsty->nguardbits       = 1;
1061
1062     s->tile_width            = 256;
1063     s->tile_height           = 256;
1064
1065     if (codsty->transform == FF_DWT53)
1066         qntsty->quantsty = JPEG2000_QSTY_NONE;
1067     else
1068         qntsty->quantsty = JPEG2000_QSTY_SE;
1069
1070     s->width = avctx->width;
1071     s->height = avctx->height;
1072
1073     for (i = 0; i < 3; i++)
1074         s->cbps[i] = 8;
1075
1076     if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
1077         s->ncomponents = 3;
1078     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
1079         s->ncomponents = 1;
1080     } else{ // planar YUV
1081         s->planar = 1;
1082         s->ncomponents = 3;
1083         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
1084                 s->chroma_shift, s->chroma_shift + 1);
1085     }
1086
1087     ff_jpeg2000_init_tier1_luts();
1088     ff_mqc_init_context_tables();
1089     init_luts();
1090
1091     init_quantization(s);
1092     if ((ret=init_tiles(s)) < 0)
1093         return ret;
1094
1095     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1096
1097     return 0;
1098 }
1099
1100 static int j2kenc_destroy(AVCodecContext *avctx)
1101 {
1102     Jpeg2000EncoderContext *s = avctx->priv_data;
1103
1104     cleanup(s);
1105     return 0;
1106 }
1107
1108 // taken from the libopenjpeg wraper so it matches
1109
1110 #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1111 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1112 static const AVOption options[] = {
1113     { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
1114     { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
1115     { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
1116     { NULL }
1117 };
1118
1119 static const AVClass j2k_class = {
1120     .class_name = "jpeg 2000 encoder",
1121     .item_name  = av_default_item_name,
1122     .option     = options,
1123     .version    = LIBAVUTIL_VERSION_INT,
1124 };
1125
1126 AVCodec ff_jpeg2000_encoder = {
1127     .name           = "jpeg2000",
1128     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1129     .type           = AVMEDIA_TYPE_VIDEO,
1130     .id             = AV_CODEC_ID_JPEG2000,
1131     .priv_data_size = sizeof(Jpeg2000EncoderContext),
1132     .init           = j2kenc_init,
1133     .encode2        = encode_frame,
1134     .close          = j2kenc_destroy,
1135     .capabilities   = CODEC_CAP_EXPERIMENTAL,
1136     .pix_fmts       = (const enum AVPixelFormat[]) {
1137         AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1138 /*      AV_PIX_FMT_YUV420P,
1139         AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
1140         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,*/
1141         AV_PIX_FMT_NONE
1142     },
1143     .priv_class     = &j2k_class,
1144 };