]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kenc.c
Merge commit '5d8bea3bb2357bb304f8f771a4107039037c5549'
[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 int put_com(Jpeg2000EncoderContext *s, int compno)
321 {
322     int size = 4 + strlen(LIBAVCODEC_IDENT);
323
324     if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
325         return 0;
326
327     if (s->buf_end - s->buf < size + 2)
328         return -1;
329
330     bytestream_put_be16(&s->buf, JPEG2000_COM);
331     bytestream_put_be16(&s->buf, size);
332     bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
333
334     bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
335
336     return 0;
337 }
338
339 static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
340 {
341     uint8_t *psotptr;
342
343     if (s->buf_end - s->buf < 12)
344         return NULL;
345
346     bytestream_put_be16(&s->buf, JPEG2000_SOT);
347     bytestream_put_be16(&s->buf, 10); // Lsot
348     bytestream_put_be16(&s->buf, tileno); // Isot
349
350     psotptr = s->buf;
351     bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
352
353     bytestream_put_byte(&s->buf, 0); // TPsot
354     bytestream_put_byte(&s->buf, 1); // TNsot
355     return psotptr;
356 }
357
358 /**
359  * compute the sizes of tiles, resolution levels, bands, etc.
360  * allocate memory for them
361  * divide the input image into tile-components
362  */
363 static int init_tiles(Jpeg2000EncoderContext *s)
364 {
365     int tileno, tilex, tiley, compno;
366     Jpeg2000CodingStyle *codsty = &s->codsty;
367     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
368
369     s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
370     s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
371
372     s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
373     if (!s->tile)
374         return AVERROR(ENOMEM);
375     for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
376         for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
377             Jpeg2000Tile *tile = s->tile + tileno;
378
379             tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
380             if (!tile->comp)
381                 return AVERROR(ENOMEM);
382             for (compno = 0; compno < s->ncomponents; compno++){
383                 Jpeg2000Component *comp = tile->comp + compno;
384                 int ret, i, j;
385
386                 comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
387                 comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
388                 comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
389                 comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
390                 if (compno > 0)
391                     for (i = 0; i < 2; i++)
392                         for (j = 0; j < 2; j++)
393                             comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
394
395                 if ((ret = ff_jpeg2000_init_component(comp,
396                                                 codsty,
397                                                 qntsty,
398                                                 s->cbps[compno],
399                                                 compno?1<<s->chroma_shift[0]:1,
400                                                 compno?1<<s->chroma_shift[1]:1,
401                                                 s->avctx
402                                                )) < 0)
403                     return ret;
404             }
405         }
406     return 0;
407 }
408
409 static void copy_frame(Jpeg2000EncoderContext *s)
410 {
411     int tileno, compno, i, y, x;
412     uint8_t *line;
413     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
414         Jpeg2000Tile *tile = s->tile + tileno;
415         if (s->planar){
416             for (compno = 0; compno < s->ncomponents; compno++){
417                 Jpeg2000Component *comp = tile->comp + compno;
418                 int *dst = comp->i_data;
419                 line = s->picture->data[compno]
420                        + comp->coord[1][0] * s->picture->linesize[compno]
421                        + comp->coord[0][0];
422                 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
423                     uint8_t *ptr = line;
424                     for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
425                         *dst++ = *ptr++ - (1 << 7);
426                     line += s->picture->linesize[compno];
427                 }
428             }
429         } else{
430             line = s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0]
431                    + tile->comp[0].coord[0][0] * s->ncomponents;
432
433             i = 0;
434             for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
435                 uint8_t *ptr = line;
436                 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
437                     for (compno = 0; compno < s->ncomponents; compno++){
438                         tile->comp[compno].i_data[i] = *ptr++  - (1 << 7);
439                     }
440                 }
441                 line += s->picture->linesize[0];
442             }
443         }
444     }
445 }
446
447 static void init_quantization(Jpeg2000EncoderContext *s)
448 {
449     int compno, reslevelno, bandno;
450     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
451     Jpeg2000CodingStyle *codsty = &s->codsty;
452
453     for (compno = 0; compno < s->ncomponents; compno++){
454         int gbandno = 0;
455         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
456             int nbands, lev = codsty->nreslevels - reslevelno - 1;
457             nbands = reslevelno ? 3 : 1;
458             for (bandno = 0; bandno < nbands; bandno++, gbandno++){
459                 int expn, mant = 0;
460
461                 if (codsty->transform == FF_DWT97_INT){
462                     int bandpos = bandno + (reslevelno>0),
463                         ss = 81920000 / dwt_norms[0][bandpos][lev],
464                         log = av_log2(ss);
465                     mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
466                     expn = s->cbps[compno] - log + 13;
467                 } else
468                     expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
469
470                 qntsty->expn[gbandno] = expn;
471                 qntsty->mant[gbandno] = mant;
472             }
473         }
474     }
475 }
476
477 static void init_luts(void)
478 {
479     int i, a,
480         mask = ~((1<<NMSEDEC_FRACBITS)-1);
481
482     for (i = 0; i < (1 << NMSEDEC_BITS); i++){
483         lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
484         lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
485
486         a = (i >> (NMSEDEC_BITS-2)&2) + 1;
487         lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
488                                     << 13-NMSEDEC_FRACBITS, 0);
489         lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
490                                     << 1, 0);
491     }
492 }
493
494 /* tier-1 routines */
495 static int getnmsedec_sig(int x, int bpno)
496 {
497     if (bpno > NMSEDEC_FRACBITS)
498         return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
499     return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
500 }
501
502 static int getnmsedec_ref(int x, int bpno)
503 {
504     if (bpno > NMSEDEC_FRACBITS)
505         return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
506     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
507 }
508
509 static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
510 {
511     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
512     for (y0 = 0; y0 < height; y0 += 4)
513         for (x = 0; x < width; x++)
514             for (y = y0; y < height && y < y0+4; y++){
515                 if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
516                     int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
517                         bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
518                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
519                     if (bit){
520                         int xorbit;
521                         int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
522                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
523                         *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
524                         ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
525                     }
526                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
527                 }
528             }
529 }
530
531 static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
532 {
533     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
534     for (y0 = 0; y0 < height; y0 += 4)
535         for (x = 0; x < width; x++)
536             for (y = y0; y < height && y < y0+4; y++)
537                 if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
538                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
539                     *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
540                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
541                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
542                 }
543 }
544
545 static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
546 {
547     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
548     for (y0 = 0; y0 < height; y0 += 4)
549         for (x = 0; x < width; x++){
550             if (y0 + 3 < height && !(
551             (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
552             (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
553             (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
554             (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
555             {
556                 // aggregation mode
557                 int rlen;
558                 for (rlen = 0; rlen < 4; rlen++)
559                     if (t1->data[(y0+rlen) * t1->stride + x] & mask)
560                         break;
561                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
562                 if (rlen == 4)
563                     continue;
564                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
565                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
566                 for (y = y0 + rlen; y < y0 + 4; y++){
567                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
568                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
569                         if (y > y0 + rlen)
570                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
571                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
572                             int xorbit;
573                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
574                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
575                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
576                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
577                         }
578                     }
579                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
580                 }
581             } else{
582                 for (y = y0; y < y0 + 4 && y < height; y++){
583                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
584                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
585                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
586                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
587                             int xorbit;
588                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
589                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
590                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
591                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
592                         }
593                     }
594                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
595                 }
596             }
597         }
598 }
599
600 static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
601                         int width, int height, int bandpos, int lev)
602 {
603     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
604     int64_t wmsedec = 0;
605
606     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
607
608     for (y = 0; y < height; y++){
609         for (x = 0; x < width; x++){
610             if (t1->data[(y) * t1->stride + x] < 0){
611                 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
612                 t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
613             }
614             max = FFMAX(max, t1->data[(y) * t1->stride + x]);
615         }
616     }
617
618     if (max == 0){
619         cblk->nonzerobits = 0;
620         bpno = 0;
621     } else{
622         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
623         bpno = cblk->nonzerobits - 1;
624     }
625
626     ff_mqc_initenc(&t1->mqc, cblk->data);
627
628     for (passno = 0; bpno >= 0; passno++){
629         nmsedec=0;
630
631         switch(pass_t){
632             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
633                     break;
634             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
635                     break;
636             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
637                     break;
638         }
639
640         cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
641         wmsedec += (int64_t)nmsedec << (2*bpno);
642         cblk->passes[passno].disto = wmsedec;
643
644         if (++pass_t == 3){
645             pass_t = 0;
646             bpno--;
647         }
648     }
649     cblk->npasses = passno;
650     cblk->ninclpasses = passno;
651
652     cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
653 }
654
655 /* tier-2 routines: */
656
657 static void putnumpasses(Jpeg2000EncoderContext *s, int n)
658 {
659     if (n == 1)
660         put_num(s, 0, 1);
661     else if (n == 2)
662         put_num(s, 2, 2);
663     else if (n <= 5)
664         put_num(s, 0xc | (n-3), 4);
665     else if (n <= 36)
666         put_num(s, 0x1e0 | (n-6), 9);
667     else
668         put_num(s, 0xff80 | (n-37), 16);
669 }
670
671
672 static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
673                           uint8_t *expn, int numgbits)
674 {
675     int bandno, empty = 1;
676
677     // init bitstream
678     *s->buf = 0;
679     s->bit_index = 0;
680
681     // header
682
683     // is the packet empty?
684     for (bandno = 0; bandno < rlevel->nbands; bandno++){
685         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
686         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
687             empty = 0;
688             break;
689         }
690     }
691
692     put_bits(s, !empty, 1);
693     if (empty){
694         j2k_flush(s);
695         return 0;
696     }
697
698     for (bandno = 0; bandno < rlevel->nbands; bandno++){
699         Jpeg2000Band *band = rlevel->band + bandno;
700         Jpeg2000Prec *prec = band->prec + precno;
701         int yi, xi, pos;
702         int cblknw = prec->nb_codeblocks_width;
703
704         if (band->coord[0][0] == band->coord[0][1]
705         ||  band->coord[1][0] == band->coord[1][1])
706             continue;
707
708         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
709             for (xi = 0; xi < cblknw; xi++, pos++){
710                 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
711                 tag_tree_update(prec->cblkincl + pos);
712                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
713                 tag_tree_update(prec->zerobits + pos);
714             }
715         }
716
717         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
718             for (xi = 0; xi < cblknw; xi++, pos++){
719                 int pad = 0, llen, length;
720                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
721
722                 if (s->buf_end - s->buf < 20) // approximately
723                     return -1;
724
725                 // inclusion information
726                 tag_tree_code(s, prec->cblkincl + pos, 1);
727                 if (!cblk->ninclpasses)
728                     continue;
729                 // zerobits information
730                 tag_tree_code(s, prec->zerobits + pos, 100);
731                 // number of passes
732                 putnumpasses(s, cblk->ninclpasses);
733
734                 length = cblk->passes[cblk->ninclpasses-1].rate;
735                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
736                 if (llen < 0){
737                     pad = -llen;
738                     llen = 0;
739                 }
740                 // length of code block
741                 put_bits(s, 1, llen);
742                 put_bits(s, 0, 1);
743                 put_num(s, length, av_log2(length)+1+pad);
744             }
745         }
746     }
747     j2k_flush(s);
748     for (bandno = 0; bandno < rlevel->nbands; bandno++){
749         Jpeg2000Band *band = rlevel->band + bandno;
750         Jpeg2000Prec *prec = band->prec + precno;
751         int yi, cblknw = prec->nb_codeblocks_width;
752         for (yi =0; yi < prec->nb_codeblocks_height; yi++){
753             int xi;
754             for (xi = 0; xi < cblknw; xi++){
755                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
756                 if (cblk->ninclpasses){
757                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
758                         return -1;
759                     bytestream_put_buffer(&s->buf, cblk->data,   cblk->passes[cblk->ninclpasses-1].rate
760                                                                - cblk->passes[cblk->ninclpasses-1].flushed_len);
761                     bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
762                                                    cblk->passes[cblk->ninclpasses-1].flushed_len);
763                 }
764             }
765         }
766     }
767     return 0;
768 }
769
770 static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
771 {
772     int compno, reslevelno, ret;
773     Jpeg2000CodingStyle *codsty = &s->codsty;
774     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
775
776     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
777     // lay-rlevel-comp-pos progression
778     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
779         for (compno = 0; compno < s->ncomponents; compno++){
780             int precno;
781             Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
782             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
783                 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
784                               qntsty->nguardbits)) < 0)
785                     return ret;
786             }
787         }
788     }
789     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
790     return 0;
791 }
792
793 static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
794 {
795     int passno, res = 0;
796     for (passno = 0; passno < cblk->npasses; passno++){
797         int dr;
798         int64_t dd;
799
800         dr = cblk->passes[passno].rate
801            - (res ? cblk->passes[res-1].rate:0);
802         dd = cblk->passes[passno].disto
803            - (res ? cblk->passes[res-1].disto:0);
804
805         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
806             res = passno+1;
807     }
808     return res;
809 }
810
811 static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
812 {
813     int precno, compno, reslevelno, bandno, cblkno, lev;
814     Jpeg2000CodingStyle *codsty = &s->codsty;
815
816     for (compno = 0; compno < s->ncomponents; compno++){
817         Jpeg2000Component *comp = tile->comp + compno;
818
819         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
820             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
821
822             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
823                 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
824                     int bandpos = bandno + (reslevelno > 0);
825                     Jpeg2000Band *band = reslevel->band + bandno;
826                     Jpeg2000Prec *prec = band->prec + precno;
827
828                     for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
829                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
830
831                         cblk->ninclpasses = getcut(cblk, s->lambda,
832                                 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
833                     }
834                 }
835             }
836         }
837     }
838 }
839
840 static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
841 {
842     int compno, reslevelno, bandno, ret;
843     Jpeg2000T1Context t1;
844     Jpeg2000CodingStyle *codsty = &s->codsty;
845     for (compno = 0; compno < s->ncomponents; compno++){
846         Jpeg2000Component *comp = s->tile[tileno].comp + compno;
847
848         t1.stride = (1<<codsty->log2_cblk_width) + 2;
849
850         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
851         if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
852             return ret;
853         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
854
855         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
856             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
857
858             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
859                 Jpeg2000Band *band = reslevel->band + bandno;
860                 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
861                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
862                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
863                 y0 = yy0;
864                 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
865                             band->coord[1][1]) - band->coord[1][0] + yy0;
866
867                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
868                     continue;
869
870                 bandpos = bandno + (reslevelno > 0);
871
872                 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
873                     if (reslevelno == 0 || bandno == 1)
874                         xx0 = 0;
875                     else
876                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
877                     x0 = xx0;
878                     xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
879                                 band->coord[0][1]) - band->coord[0][0] + xx0;
880
881                     for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
882                         int y, x;
883                         if (codsty->transform == FF_DWT53){
884                             for (y = yy0; y < yy1; y++){
885                                 int *ptr = t1.data + (y-yy0)*t1.stride;
886                                 for (x = xx0; x < xx1; x++){
887                                     *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
888                                 }
889                             }
890                         } else{
891                             for (y = yy0; y < yy1; y++){
892                                 int *ptr = t1.data + (y-yy0)*t1.stride;
893                                 for (x = xx0; x < xx1; x++){
894                                     *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
895                                     *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
896                                     ptr++;
897                                 }
898                             }
899                         }
900                         encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
901                                     bandpos, codsty->nreslevels - reslevelno - 1);
902                         xx0 = xx1;
903                         xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
904                     }
905                     yy0 = yy1;
906                     yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
907                 }
908             }
909         }
910         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
911     }
912
913     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
914     truncpasses(s, tile);
915     if ((ret = encode_packets(s, tile, tileno)) < 0)
916         return ret;
917     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
918     return 0;
919 }
920
921 static void cleanup(Jpeg2000EncoderContext *s)
922 {
923     int tileno, compno;
924     Jpeg2000CodingStyle *codsty = &s->codsty;
925
926     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
927         for (compno = 0; compno < s->ncomponents; compno++){
928             Jpeg2000Component *comp = s->tile[tileno].comp + compno;
929             ff_jpeg2000_cleanup(comp, codsty);
930         }
931         av_freep(&s->tile[tileno].comp);
932     }
933     av_freep(&s->tile);
934 }
935
936 static void reinit(Jpeg2000EncoderContext *s)
937 {
938     int tileno, compno;
939     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
940         Jpeg2000Tile *tile = s->tile + tileno;
941         for (compno = 0; compno < s->ncomponents; compno++)
942             ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
943     }
944 }
945
946 static void update_size(uint8_t *size, const uint8_t *end)
947 {
948     AV_WB32(size, end-size);
949 }
950
951 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
952                         const AVFrame *pict, int *got_packet)
953 {
954     int tileno, ret;
955     Jpeg2000EncoderContext *s = avctx->priv_data;
956     uint8_t *chunkstart, *jp2cstart, *jp2hstart;
957
958     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
959         return ret;
960
961     // init:
962     s->buf = s->buf_start = pkt->data;
963     s->buf_end = pkt->data + pkt->size;
964
965     s->picture = pict;
966
967     s->lambda = s->picture->quality * LAMBDA_SCALE;
968
969     copy_frame(s);
970     reinit(s);
971
972     if (s->format == CODEC_JP2) {
973         av_assert0(s->buf == pkt->data);
974
975         bytestream_put_be32(&s->buf, 0x0000000C);
976         bytestream_put_be32(&s->buf, 0x6A502020);
977         bytestream_put_be32(&s->buf, 0x0D0A870A);
978
979         chunkstart = s->buf;
980         bytestream_put_be32(&s->buf, 0);
981         bytestream_put_buffer(&s->buf, "ftyp", 4);
982         bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
983         bytestream_put_be32(&s->buf, 0);
984         bytestream_put_buffer(&s->buf, "jp2\040", 4);
985         update_size(chunkstart, s->buf);
986
987         jp2hstart = s->buf;
988         bytestream_put_be32(&s->buf, 0);
989         bytestream_put_buffer(&s->buf, "jp2h", 4);
990
991         chunkstart = s->buf;
992         bytestream_put_be32(&s->buf, 0);
993         bytestream_put_buffer(&s->buf, "ihdr", 4);
994         bytestream_put_be32(&s->buf, avctx->height);
995         bytestream_put_be32(&s->buf, avctx->width);
996         bytestream_put_be16(&s->buf, s->ncomponents);
997         bytestream_put_byte(&s->buf, s->cbps[0]);
998         bytestream_put_byte(&s->buf, 7);
999         bytestream_put_byte(&s->buf, 0);
1000         bytestream_put_byte(&s->buf, 0);
1001         update_size(chunkstart, s->buf);
1002
1003         chunkstart = s->buf;
1004         bytestream_put_be32(&s->buf, 0);
1005         bytestream_put_buffer(&s->buf, "colr", 4);
1006         bytestream_put_byte(&s->buf, 1);
1007         bytestream_put_byte(&s->buf, 0);
1008         bytestream_put_byte(&s->buf, 0);
1009         if (s->ncomponents == 1) {
1010             bytestream_put_be32(&s->buf, 17);
1011         } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
1012             bytestream_put_be32(&s->buf, 16);
1013         } else {
1014             bytestream_put_be32(&s->buf, 18);
1015         }
1016         update_size(chunkstart, s->buf);
1017         update_size(jp2hstart, s->buf);
1018
1019         jp2cstart = s->buf;
1020         bytestream_put_be32(&s->buf, 0);
1021         bytestream_put_buffer(&s->buf, "jp2c", 4);
1022     }
1023
1024     if (s->buf_end - s->buf < 2)
1025         return -1;
1026     bytestream_put_be16(&s->buf, JPEG2000_SOC);
1027     if ((ret = put_siz(s)) < 0)
1028         return ret;
1029     if ((ret = put_cod(s)) < 0)
1030         return ret;
1031     if ((ret = put_qcd(s, 0)) < 0)
1032         return ret;
1033     if ((ret = put_com(s, 0)) < 0)
1034         return ret;
1035
1036     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1037         uint8_t *psotptr;
1038         if (!(psotptr = put_sot(s, tileno)))
1039             return -1;
1040         if (s->buf_end - s->buf < 2)
1041             return -1;
1042         bytestream_put_be16(&s->buf, JPEG2000_SOD);
1043         if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1044             return ret;
1045         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1046     }
1047     if (s->buf_end - s->buf < 2)
1048         return -1;
1049     bytestream_put_be16(&s->buf, JPEG2000_EOC);
1050
1051     if (s->format == CODEC_JP2)
1052         update_size(jp2cstart, s->buf);
1053
1054     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1055     pkt->size = s->buf - s->buf_start;
1056     pkt->flags |= AV_PKT_FLAG_KEY;
1057     *got_packet = 1;
1058
1059     return 0;
1060 }
1061
1062 static av_cold int j2kenc_init(AVCodecContext *avctx)
1063 {
1064     int i, ret;
1065     Jpeg2000EncoderContext *s = avctx->priv_data;
1066     Jpeg2000CodingStyle *codsty = &s->codsty;
1067     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1068
1069     s->avctx = avctx;
1070     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1071
1072     // defaults:
1073     // TODO: implement setting non-standard precinct size
1074     memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1075     memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1076     codsty->nreslevels2decode=
1077     codsty->nreslevels       = 7;
1078     codsty->log2_cblk_width  = 4;
1079     codsty->log2_cblk_height = 4;
1080     codsty->transform        = avctx->prediction_method ? FF_DWT53 : FF_DWT97_INT;
1081
1082     qntsty->nguardbits       = 1;
1083
1084     if ((s->tile_width  & (s->tile_width -1)) ||
1085         (s->tile_height & (s->tile_height-1))) {
1086         av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
1087     }
1088
1089     if (codsty->transform == FF_DWT53)
1090         qntsty->quantsty = JPEG2000_QSTY_NONE;
1091     else
1092         qntsty->quantsty = JPEG2000_QSTY_SE;
1093
1094     s->width = avctx->width;
1095     s->height = avctx->height;
1096
1097     for (i = 0; i < 3; i++)
1098         s->cbps[i] = 8;
1099
1100     if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
1101         s->ncomponents = 3;
1102     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
1103         s->ncomponents = 1;
1104     } else{ // planar YUV
1105         s->planar = 1;
1106         s->ncomponents = 3;
1107         avcodec_get_chroma_sub_sample(avctx->pix_fmt,
1108                 s->chroma_shift, s->chroma_shift + 1);
1109     }
1110
1111     ff_jpeg2000_init_tier1_luts();
1112     ff_mqc_init_context_tables();
1113     init_luts();
1114
1115     init_quantization(s);
1116     if ((ret=init_tiles(s)) < 0)
1117         return ret;
1118
1119     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1120
1121     return 0;
1122 }
1123
1124 static int j2kenc_destroy(AVCodecContext *avctx)
1125 {
1126     Jpeg2000EncoderContext *s = avctx->priv_data;
1127
1128     cleanup(s);
1129     return 0;
1130 }
1131
1132 // taken from the libopenjpeg wraper so it matches
1133
1134 #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1135 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1136 static const AVOption options[] = {
1137     { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
1138     { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
1139     { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
1140     { "tile_width",    "Tile Width",        OFFSET(tile_width),    AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1141     { "tile_height",   "Tile Height",       OFFSET(tile_height),   AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1142
1143     { NULL }
1144 };
1145
1146 static const AVClass j2k_class = {
1147     .class_name = "jpeg 2000 encoder",
1148     .item_name  = av_default_item_name,
1149     .option     = options,
1150     .version    = LIBAVUTIL_VERSION_INT,
1151 };
1152
1153 AVCodec ff_jpeg2000_encoder = {
1154     .name           = "jpeg2000",
1155     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1156     .type           = AVMEDIA_TYPE_VIDEO,
1157     .id             = AV_CODEC_ID_JPEG2000,
1158     .priv_data_size = sizeof(Jpeg2000EncoderContext),
1159     .init           = j2kenc_init,
1160     .encode2        = encode_frame,
1161     .close          = j2kenc_destroy,
1162     .capabilities   = AV_CODEC_CAP_EXPERIMENTAL,
1163     .pix_fmts       = (const enum AVPixelFormat[]) {
1164         AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1165         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
1166         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
1167         AV_PIX_FMT_NONE
1168     },
1169     .priv_class     = &j2k_class,
1170 };