]> git.sesse.net Git - ffmpeg/blob - libavcodec/j2kenc.c
avcodec/cbs_av1: fix setting FrameWidth in frame_size_with_refs()
[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  *
24  *
25  * This source code incorporates work covered by the following copyright and
26  * permission notice:
27  *
28  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
29  * Copyright (c) 2002-2007, Professor Benoit Macq
30  * Copyright (c) 2001-2003, David Janssens
31  * Copyright (c) 2002-2003, Yannick Verschueren
32  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
33  * Copyright (c) 2005, Herve Drolon, FreeImage Team
34  * Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
47  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
50  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56  * POSSIBILITY OF SUCH DAMAGE.
57  */
58
59
60 /**
61  * JPEG2000 image encoder
62  * @file
63  * @author Kamil Nowosad
64  */
65
66 #include <float.h>
67 #include "avcodec.h"
68 #include "internal.h"
69 #include "bytestream.h"
70 #include "jpeg2000.h"
71 #include "libavutil/common.h"
72 #include "libavutil/pixdesc.h"
73 #include "libavutil/opt.h"
74 #include "libavutil/intreadwrite.h"
75
76 #define NMSEDEC_BITS 7
77 #define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
78 #define WMSEDEC_SHIFT 13 ///< must be >= 13
79 #define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
80
81 #define CODEC_JP2 1
82 #define CODEC_J2K 0
83
84 static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
85            lut_nmsedec_ref0[1<<NMSEDEC_BITS],
86            lut_nmsedec_sig [1<<NMSEDEC_BITS],
87            lut_nmsedec_sig0[1<<NMSEDEC_BITS];
88
89 static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
90     {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
91      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
92      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
93      {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
94
95     {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
96      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
97      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
98      { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
99 };
100
101 typedef struct {
102    Jpeg2000Component *comp;
103 } Jpeg2000Tile;
104
105 typedef struct {
106     AVClass *class;
107     AVCodecContext *avctx;
108     const AVFrame *picture;
109
110     int width, height; ///< image width and height
111     uint8_t cbps[4]; ///< bits per sample in particular components
112     int chroma_shift[2];
113     uint8_t planar;
114     int ncomponents;
115     int tile_width, tile_height; ///< tile size
116     int numXtiles, numYtiles;
117
118     uint8_t *buf_start;
119     uint8_t *buf;
120     uint8_t *buf_end;
121     int bit_index;
122
123     int64_t lambda;
124
125     Jpeg2000CodingStyle codsty;
126     Jpeg2000QuantStyle  qntsty;
127
128     Jpeg2000Tile *tile;
129
130     int format;
131     int pred;
132     int sop;
133     int eph;
134     int prog;
135 } Jpeg2000EncoderContext;
136
137
138 /* debug */
139 #if 0
140 #undef ifprintf
141 #undef printf
142
143 static void nspaces(FILE *fd, int n)
144 {
145     while(n--) putc(' ', fd);
146 }
147
148 static void printcomp(Jpeg2000Component *comp)
149 {
150     int i;
151     for (i = 0; i < comp->y1 - comp->y0; i++)
152         ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
153 }
154
155 static void dump(Jpeg2000EncoderContext *s, FILE *fd)
156 {
157     int tileno, compno, reslevelno, bandno, precno;
158     fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
159                 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
160                 "tiles:\n",
161             s->width, s->height, s->tile_width, s->tile_height,
162             s->numXtiles, s->numYtiles, s->ncomponents);
163     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
164         Jpeg2000Tile *tile = s->tile + tileno;
165         nspaces(fd, 2);
166         fprintf(fd, "tile %d:\n", tileno);
167         for(compno = 0; compno < s->ncomponents; compno++){
168             Jpeg2000Component *comp = tile->comp + compno;
169             nspaces(fd, 4);
170             fprintf(fd, "component %d:\n", compno);
171             nspaces(fd, 4);
172             fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
173                         comp->x0, comp->x1, comp->y0, comp->y1);
174             for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
175                 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
176                 nspaces(fd, 6);
177                 fprintf(fd, "reslevel %d:\n", reslevelno);
178                 nspaces(fd, 6);
179                 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
180                         reslevel->x0, reslevel->x1, reslevel->y0,
181                         reslevel->y1, reslevel->nbands);
182                 for(bandno = 0; bandno < reslevel->nbands; bandno++){
183                     Jpeg2000Band *band = reslevel->band + bandno;
184                     nspaces(fd, 8);
185                     fprintf(fd, "band %d:\n", bandno);
186                     nspaces(fd, 8);
187                     fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
188                                 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
189                                 band->x0, band->x1,
190                                 band->y0, band->y1,
191                                 band->codeblock_width, band->codeblock_height,
192                                 band->cblknx, band->cblkny);
193                     for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
194                         Jpeg2000Prec *prec = band->prec + precno;
195                         nspaces(fd, 10);
196                         fprintf(fd, "prec %d:\n", precno);
197                         nspaces(fd, 10);
198                         fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
199                                      prec->xi0, prec->xi1, prec->yi0, prec->yi1);
200                     }
201                 }
202             }
203         }
204     }
205 }
206 #endif
207
208 /* bitstream routines */
209
210 /** put n times val bit */
211 static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
212 {
213     while (n-- > 0){
214         if (s->bit_index == 8)
215         {
216             s->bit_index = *s->buf == 0xff;
217             *(++s->buf) = 0;
218         }
219         *s->buf |= val << (7 - s->bit_index++);
220     }
221 }
222
223 /** put n least significant bits of a number num */
224 static void put_num(Jpeg2000EncoderContext *s, int num, int n)
225 {
226     while(--n >= 0)
227         put_bits(s, (num >> n) & 1, 1);
228 }
229
230 /** flush the bitstream */
231 static void j2k_flush(Jpeg2000EncoderContext *s)
232 {
233     if (s->bit_index){
234         s->bit_index = 0;
235         s->buf++;
236     }
237 }
238
239 /* tag tree routines */
240
241 /** code the value stored in node */
242 static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
243 {
244     Jpeg2000TgtNode *stack[30];
245     int sp = 1, curval = 0;
246     stack[0] = node;
247
248     node = node->parent;
249     while(node){
250         if (node->vis){
251             curval = node->val;
252             break;
253         }
254         node->vis++;
255         stack[sp++] = node;
256         node = node->parent;
257     }
258     while(--sp >= 0){
259         if (stack[sp]->val >= threshold){
260             put_bits(s, 0, threshold - curval);
261             break;
262         }
263         put_bits(s, 0, stack[sp]->val - curval);
264         put_bits(s, 1, 1);
265         curval = stack[sp]->val;
266     }
267 }
268
269 /** update the value in node */
270 static void tag_tree_update(Jpeg2000TgtNode *node)
271 {
272     int lev = 0;
273     while (node->parent){
274         if (node->parent->val <= node->val)
275             break;
276         node->parent->val = node->val;
277         node = node->parent;
278         lev++;
279     }
280 }
281
282 static int put_siz(Jpeg2000EncoderContext *s)
283 {
284     int i;
285
286     if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
287         return -1;
288
289     bytestream_put_be16(&s->buf, JPEG2000_SIZ);
290     bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
291     bytestream_put_be16(&s->buf, 0); // Rsiz
292     bytestream_put_be32(&s->buf, s->width); // width
293     bytestream_put_be32(&s->buf, s->height); // height
294     bytestream_put_be32(&s->buf, 0); // X0Siz
295     bytestream_put_be32(&s->buf, 0); // Y0Siz
296
297     bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
298     bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
299     bytestream_put_be32(&s->buf, 0); // XT0Siz
300     bytestream_put_be32(&s->buf, 0); // YT0Siz
301     bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
302
303     for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
304         bytestream_put_byte(&s->buf, s->cbps[i] - 1);
305         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
306         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
307     }
308     return 0;
309 }
310
311 static int put_cod(Jpeg2000EncoderContext *s)
312 {
313     Jpeg2000CodingStyle *codsty = &s->codsty;
314     uint8_t scod = 0;
315
316     if (s->buf_end - s->buf < 14)
317         return -1;
318
319     bytestream_put_be16(&s->buf, JPEG2000_COD);
320     bytestream_put_be16(&s->buf, 12); // Lcod
321     if (s->sop)
322         scod |= JPEG2000_CSTY_SOP;
323     if (s->eph)
324         scod |= JPEG2000_CSTY_EPH;
325     bytestream_put_byte(&s->buf, scod);  // Scod
326     // SGcod
327     bytestream_put_byte(&s->buf, s->prog); // progression level
328     bytestream_put_be16(&s->buf, 1); // num of layers
329     if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
330         bytestream_put_byte(&s->buf, 0); // unspecified
331     }else{
332         bytestream_put_byte(&s->buf, 0); // unspecified
333     }
334     // SPcod
335     bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
336     bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
337     bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
338     bytestream_put_byte(&s->buf, 0); // cblk style
339     bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
340     return 0;
341 }
342
343 static int put_qcd(Jpeg2000EncoderContext *s, int compno)
344 {
345     int i, size;
346     Jpeg2000CodingStyle *codsty = &s->codsty;
347     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
348
349     if (qntsty->quantsty == JPEG2000_QSTY_NONE)
350         size = 4 + 3 * (codsty->nreslevels-1);
351     else // QSTY_SE
352         size = 5 + 6 * (codsty->nreslevels-1);
353
354     if (s->buf_end - s->buf < size + 2)
355         return -1;
356
357     bytestream_put_be16(&s->buf, JPEG2000_QCD);
358     bytestream_put_be16(&s->buf, size);  // LQcd
359     bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
360     if (qntsty->quantsty == JPEG2000_QSTY_NONE)
361         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
362             bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
363     else // QSTY_SE
364         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
365             bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
366     return 0;
367 }
368
369 static int put_com(Jpeg2000EncoderContext *s, int compno)
370 {
371     int size = 4 + strlen(LIBAVCODEC_IDENT);
372
373     if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
374         return 0;
375
376     if (s->buf_end - s->buf < size + 2)
377         return -1;
378
379     bytestream_put_be16(&s->buf, JPEG2000_COM);
380     bytestream_put_be16(&s->buf, size);
381     bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
382
383     bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
384
385     return 0;
386 }
387
388 static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
389 {
390     uint8_t *psotptr;
391
392     if (s->buf_end - s->buf < 12)
393         return NULL;
394
395     bytestream_put_be16(&s->buf, JPEG2000_SOT);
396     bytestream_put_be16(&s->buf, 10); // Lsot
397     bytestream_put_be16(&s->buf, tileno); // Isot
398
399     psotptr = s->buf;
400     bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
401
402     bytestream_put_byte(&s->buf, 0); // TPsot
403     bytestream_put_byte(&s->buf, 1); // TNsot
404     return psotptr;
405 }
406
407 /**
408  * compute the sizes of tiles, resolution levels, bands, etc.
409  * allocate memory for them
410  * divide the input image into tile-components
411  */
412 static int init_tiles(Jpeg2000EncoderContext *s)
413 {
414     int tileno, tilex, tiley, compno;
415     Jpeg2000CodingStyle *codsty = &s->codsty;
416     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
417
418     s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
419     s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
420
421     s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
422     if (!s->tile)
423         return AVERROR(ENOMEM);
424     for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
425         for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
426             Jpeg2000Tile *tile = s->tile + tileno;
427
428             tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
429             if (!tile->comp)
430                 return AVERROR(ENOMEM);
431             for (compno = 0; compno < s->ncomponents; compno++){
432                 Jpeg2000Component *comp = tile->comp + compno;
433                 int ret, i, j;
434
435                 comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
436                 comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
437                 comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
438                 comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
439                 if (compno > 0)
440                     for (i = 0; i < 2; i++)
441                         for (j = 0; j < 2; j++)
442                             comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
443
444                 if ((ret = ff_jpeg2000_init_component(comp,
445                                                 codsty,
446                                                 qntsty,
447                                                 s->cbps[compno],
448                                                 compno?1<<s->chroma_shift[0]:1,
449                                                 compno?1<<s->chroma_shift[1]:1,
450                                                 s->avctx
451                                                )) < 0)
452                     return ret;
453             }
454         }
455     return 0;
456 }
457
458 #define COPY_FRAME(D, PIXEL)                                                                                                \
459     static void copy_frame_ ##D(Jpeg2000EncoderContext *s)                                                                  \
460     {                                                                                                                       \
461         int tileno, compno, i, y, x;                                                                                        \
462         PIXEL *line;                                                                                                        \
463         for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){                                                   \
464             Jpeg2000Tile *tile = s->tile + tileno;                                                                          \
465             if (s->planar){                                                                                                 \
466                 for (compno = 0; compno < s->ncomponents; compno++){                                                        \
467                     Jpeg2000Component *comp = tile->comp + compno;                                                          \
468                     int *dst = comp->i_data;                                                                                \
469                     int cbps = s->cbps[compno];                                                                             \
470                     line = (PIXEL*)s->picture->data[compno]                                                                 \
471                            + comp->coord[1][0] * (s->picture->linesize[compno] / sizeof(PIXEL))                             \
472                            + comp->coord[0][0];                                                                             \
473                     for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){                                                \
474                         PIXEL *ptr = line;                                                                                  \
475                         for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)                                             \
476                             *dst++ = *ptr++ - (1 << (cbps - 1));                                                            \
477                         line += s->picture->linesize[compno] / sizeof(PIXEL);                                               \
478                     }                                                                                                       \
479                 }                                                                                                           \
480             } else{                                                                                                         \
481                 line = (PIXEL*)s->picture->data[0] + tile->comp[0].coord[1][0] * (s->picture->linesize[0] / sizeof(PIXEL))  \
482                        + tile->comp[0].coord[0][0] * s->ncomponents;                                                        \
483                                                                                                                             \
484                 i = 0;                                                                                                      \
485                 for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){                                    \
486                     PIXEL *ptr = line;                                                                                      \
487                     for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){                           \
488                         for (compno = 0; compno < s->ncomponents; compno++){                                                \
489                             int cbps = s->cbps[compno];                                                                     \
490                             tile->comp[compno].i_data[i] = *ptr++  - (1 << (cbps - 1));                                     \
491                         }                                                                                                   \
492                     }                                                                                                       \
493                     line += s->picture->linesize[0] / sizeof(PIXEL);                                                        \
494                 }                                                                                                           \
495             }                                                                                                               \
496         }                                                                                                                   \
497     }
498
499 COPY_FRAME(8, uint8_t)
500 COPY_FRAME(16, uint16_t)
501
502 static void init_quantization(Jpeg2000EncoderContext *s)
503 {
504     int compno, reslevelno, bandno;
505     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
506     Jpeg2000CodingStyle *codsty = &s->codsty;
507
508     for (compno = 0; compno < s->ncomponents; compno++){
509         int gbandno = 0;
510         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
511             int nbands, lev = codsty->nreslevels - reslevelno - 1;
512             nbands = reslevelno ? 3 : 1;
513             for (bandno = 0; bandno < nbands; bandno++, gbandno++){
514                 int expn, mant = 0;
515
516                 if (codsty->transform == FF_DWT97_INT){
517                     int bandpos = bandno + (reslevelno>0),
518                         ss = 81920000 / dwt_norms[0][bandpos][lev],
519                         log = av_log2(ss);
520                     mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
521                     expn = s->cbps[compno] - log + 13;
522                 } else
523                     expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
524
525                 qntsty->expn[gbandno] = expn;
526                 qntsty->mant[gbandno] = mant;
527             }
528         }
529     }
530 }
531
532 static void init_luts(void)
533 {
534     int i, a,
535         mask = ~((1<<NMSEDEC_FRACBITS)-1);
536
537     for (i = 0; i < (1 << NMSEDEC_BITS); i++){
538         lut_nmsedec_sig[i]  = FFMAX((3 * i << (13 - NMSEDEC_FRACBITS)) - (9 << 11), 0);
539         lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
540
541         a = (i >> (NMSEDEC_BITS-2)&2) + 1;
542         lut_nmsedec_ref[i]  = FFMAX((a - 2) * (i << (13 - NMSEDEC_FRACBITS)) +
543                                     (1 << 13) - (a * a << 11), 0);
544         lut_nmsedec_ref0[i] = FFMAX(((i * i - (i << NMSEDEC_BITS) + (1 << 2 * NMSEDEC_FRACBITS) + (1 << (NMSEDEC_FRACBITS - 1))) & mask)
545                                     << 1, 0);
546     }
547 }
548
549 /* tier-1 routines */
550 static int getnmsedec_sig(int x, int bpno)
551 {
552     if (bpno > NMSEDEC_FRACBITS)
553         return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
554     return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
555 }
556
557 static int getnmsedec_ref(int x, int bpno)
558 {
559     if (bpno > NMSEDEC_FRACBITS)
560         return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
561     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
562 }
563
564 static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
565 {
566     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
567     for (y0 = 0; y0 < height; y0 += 4)
568         for (x = 0; x < width; x++)
569             for (y = y0; y < height && y < y0+4; y++){
570                 if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
571                     int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
572                         bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
573                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
574                     if (bit){
575                         int xorbit;
576                         int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
577                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
578                         *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
579                         ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
580                     }
581                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
582                 }
583             }
584 }
585
586 static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
587 {
588     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
589     for (y0 = 0; y0 < height; y0 += 4)
590         for (x = 0; x < width; x++)
591             for (y = y0; y < height && y < y0+4; y++)
592                 if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
593                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
594                     *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
595                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
596                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
597                 }
598 }
599
600 static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
601 {
602     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
603     for (y0 = 0; y0 < height; y0 += 4)
604         for (x = 0; x < width; x++){
605             if (y0 + 3 < height && !(
606             (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
607             (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
608             (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
609             (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
610             {
611                 // aggregation mode
612                 int rlen;
613                 for (rlen = 0; rlen < 4; rlen++)
614                     if (t1->data[(y0+rlen) * t1->stride + x] & mask)
615                         break;
616                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
617                 if (rlen == 4)
618                     continue;
619                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
620                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
621                 for (y = y0 + rlen; y < y0 + 4; y++){
622                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
623                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
624                         if (y > y0 + rlen)
625                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
626                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
627                             int xorbit;
628                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
629                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
630                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
631                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
632                         }
633                     }
634                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
635                 }
636             } else{
637                 for (y = y0; y < y0 + 4 && y < height; y++){
638                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
639                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
640                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
641                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
642                             int xorbit;
643                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
644                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
645                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
646                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
647                         }
648                     }
649                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
650                 }
651             }
652         }
653 }
654
655 static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
656                         int width, int height, int bandpos, int lev)
657 {
658     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
659     int64_t wmsedec = 0;
660
661     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
662
663     for (y = 0; y < height; y++){
664         for (x = 0; x < width; x++){
665             if (t1->data[(y) * t1->stride + x] < 0){
666                 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
667                 t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
668             }
669             max = FFMAX(max, t1->data[(y) * t1->stride + x]);
670         }
671     }
672
673     if (max == 0){
674         cblk->nonzerobits = 0;
675         bpno = 0;
676     } else{
677         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
678         bpno = cblk->nonzerobits - 1;
679     }
680
681     cblk->data[0] = 0;
682     ff_mqc_initenc(&t1->mqc, cblk->data + 1);
683
684     for (passno = 0; bpno >= 0; passno++){
685         nmsedec=0;
686
687         switch(pass_t){
688             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
689                     break;
690             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
691                     break;
692             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
693                     break;
694         }
695
696         cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
697         wmsedec += (int64_t)nmsedec << (2*bpno);
698         cblk->passes[passno].disto = wmsedec;
699
700         if (++pass_t == 3){
701             pass_t = 0;
702             bpno--;
703         }
704     }
705     cblk->npasses = passno;
706     cblk->ninclpasses = passno;
707
708     if (passno)
709         cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
710 }
711
712 /* tier-2 routines: */
713
714 static void putnumpasses(Jpeg2000EncoderContext *s, int n)
715 {
716     if (n == 1)
717         put_num(s, 0, 1);
718     else if (n == 2)
719         put_num(s, 2, 2);
720     else if (n <= 5)
721         put_num(s, 0xc | (n-3), 4);
722     else if (n <= 36)
723         put_num(s, 0x1e0 | (n-6), 9);
724     else
725         put_num(s, 0xff80 | (n-37), 16);
726 }
727
728
729 static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
730                           uint8_t *expn, int numgbits, int packetno)
731 {
732     int bandno, empty = 1;
733     // init bitstream
734     *s->buf = 0;
735     s->bit_index = 0;
736
737     if (s->sop) {
738         bytestream_put_be16(&s->buf, JPEG2000_SOP);
739         bytestream_put_be16(&s->buf, 4);
740         bytestream_put_be16(&s->buf, packetno);
741     }
742     // header
743
744     // is the packet empty?
745     for (bandno = 0; bandno < rlevel->nbands; bandno++){
746         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
747         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
748             empty = 0;
749             break;
750         }
751     }
752
753     put_bits(s, !empty, 1);
754     if (empty){
755         j2k_flush(s);
756         return 0;
757     }
758
759     for (bandno = 0; bandno < rlevel->nbands; bandno++){
760         Jpeg2000Band *band = rlevel->band + bandno;
761         Jpeg2000Prec *prec = band->prec + precno;
762         int yi, xi, pos;
763         int cblknw = prec->nb_codeblocks_width;
764
765         if (band->coord[0][0] == band->coord[0][1]
766         ||  band->coord[1][0] == band->coord[1][1])
767             continue;
768
769         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
770             for (xi = 0; xi < cblknw; xi++, pos++){
771                 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
772                 tag_tree_update(prec->cblkincl + pos);
773                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
774                 tag_tree_update(prec->zerobits + pos);
775             }
776         }
777
778         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
779             for (xi = 0; xi < cblknw; xi++, pos++){
780                 int pad = 0, llen, length;
781                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
782
783                 if (s->buf_end - s->buf < 20) // approximately
784                     return -1;
785
786                 // inclusion information
787                 tag_tree_code(s, prec->cblkincl + pos, 1);
788                 if (!cblk->ninclpasses)
789                     continue;
790                 // zerobits information
791                 tag_tree_code(s, prec->zerobits + pos, 100);
792                 // number of passes
793                 putnumpasses(s, cblk->ninclpasses);
794
795                 length = cblk->passes[cblk->ninclpasses-1].rate;
796                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
797                 if (llen < 0){
798                     pad = -llen;
799                     llen = 0;
800                 }
801                 // length of code block
802                 put_bits(s, 1, llen);
803                 put_bits(s, 0, 1);
804                 put_num(s, length, av_log2(length)+1+pad);
805             }
806         }
807     }
808     j2k_flush(s);
809     if (s->eph) {
810         bytestream_put_be16(&s->buf, JPEG2000_EPH);
811     }
812
813     for (bandno = 0; bandno < rlevel->nbands; bandno++){
814         Jpeg2000Band *band = rlevel->band + bandno;
815         Jpeg2000Prec *prec = band->prec + precno;
816         int yi, cblknw = prec->nb_codeblocks_width;
817         for (yi =0; yi < prec->nb_codeblocks_height; yi++){
818             int xi;
819             for (xi = 0; xi < cblknw; xi++){
820                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
821                 if (cblk->ninclpasses){
822                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
823                         return -1;
824                     bytestream_put_buffer(&s->buf, cblk->data + 1,   cblk->passes[cblk->ninclpasses-1].rate
825                                                                - cblk->passes[cblk->ninclpasses-1].flushed_len);
826                     bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
827                                                    cblk->passes[cblk->ninclpasses-1].flushed_len);
828                 }
829             }
830         }
831     }
832     return 0;
833 }
834
835 static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
836 {
837     int compno, reslevelno, ret;
838     Jpeg2000CodingStyle *codsty = &s->codsty;
839     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
840     int packetno = 0;
841     int step_x, step_y;
842     int x, y;
843     int tile_coord[2][2];
844     int col = tileno % s->numXtiles;
845     int row = tileno / s->numXtiles;
846
847     tile_coord[0][0] = col * s->tile_width;
848     tile_coord[0][1] = FFMIN(tile_coord[0][0] + s->tile_width, s->width);
849     tile_coord[1][0] = row * s->tile_height;
850     tile_coord[1][1] = FFMIN(tile_coord[1][0] + s->tile_height, s->height);
851
852     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
853     // lay-rlevel-comp-pos progression
854     switch (s->prog) {
855     case JPEG2000_PGOD_LRCP:
856     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
857         for (compno = 0; compno < s->ncomponents; compno++){
858             int precno;
859             Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
860             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
861                 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
862                               qntsty->nguardbits, packetno++)) < 0)
863                     return ret;
864             }
865         }
866     }
867     break;
868     case JPEG2000_PGOD_RLCP:
869     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
870         for (compno = 0; compno < s->ncomponents; compno++){
871             int precno;
872             Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
873             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
874                 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
875                               qntsty->nguardbits, packetno++)) < 0)
876                     return ret;
877             }
878         }
879     }
880     break;
881     case JPEG2000_PGOD_RPCL:
882     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
883         int precno;
884         step_x = 30;
885         step_y = 30;
886         for (compno = 0; compno < s->ncomponents; compno++) {
887             Jpeg2000Component *comp     = tile->comp + compno;
888             if (reslevelno < codsty->nreslevels) {
889                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
890                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
891                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
892                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
893             }
894         }
895
896         step_x = 1<<step_x;
897         step_y = 1<<step_y;
898         for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
899             for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
900                 for (compno = 0; compno < s->ncomponents; compno++) {
901                     Jpeg2000Component *comp     = tile->comp + compno;
902                     uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
903                     Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
904                     int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
905                     unsigned prcx, prcy;
906                     int trx0, try0;
907
908                     trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
909                     try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
910
911                     if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
912                         (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
913                         continue;
914
915                     if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
916                         (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
917                         continue;
918
919                     // check if a precinct exists
920                     prcx   = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
921                     prcy   = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
922                     prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
923                     prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
924                     precno = prcx + reslevel->num_precincts_x * prcy;
925
926                     if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
927                         av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
928                                prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
929                         continue;
930                     }
931
932                     if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
933                               qntsty->nguardbits, packetno++)) < 0)
934                         return ret;
935                     }
936                 }
937             }
938     }
939     break;
940     case JPEG2000_PGOD_PCRL:
941         step_x = 32;
942         step_y = 32;
943         for (compno = 0; compno < s->ncomponents; compno++) {
944             Jpeg2000Component *comp     = tile->comp + compno;
945
946             for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
947                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
948                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
949                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
950                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
951             }
952         }
953         if (step_x >= 31 || step_y >= 31){
954             avpriv_request_sample(s->avctx, "PCRL with large step");
955             return AVERROR_PATCHWELCOME;
956         }
957         step_x = 1<<step_x;
958         step_y = 1<<step_y;
959
960         for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
961             for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
962                 for (compno = 0; compno < s->ncomponents; compno++) {
963                     Jpeg2000Component *comp     = tile->comp + compno;
964                     int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
965
966                     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
967                         unsigned prcx, prcy;
968                         int precno;
969                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
970                         Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
971                         int trx0, try0;
972
973                         trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
974                         try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
975
976                         if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
977                             (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
978                             continue;
979
980                         if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
981                             (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
982                             continue;
983
984                         // check if a precinct exists
985                         prcx   = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
986                         prcy   = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
987                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
988                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
989
990                         precno = prcx + reslevel->num_precincts_x * prcy;
991
992                         if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
993                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
994                                    prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
995                             continue;
996                         }
997                         if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
998                                   qntsty->nguardbits, packetno++)) < 0)
999                             return ret;
1000                     }
1001                 }
1002             }
1003         }
1004     break;
1005     case JPEG2000_PGOD_CPRL:
1006         for (compno = 0; compno < s->ncomponents; compno++) {
1007             Jpeg2000Component *comp     = tile->comp + compno;
1008             int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
1009             step_x = 32;
1010             step_y = 32;
1011
1012             for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1013                 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1014                 Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1015                 step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1016                 step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1017             }
1018             if (step_x >= 31 || step_y >= 31){
1019                 avpriv_request_sample(s->avctx, "CPRL with large step");
1020                 return AVERROR_PATCHWELCOME;
1021             }
1022             step_x = 1<<step_x;
1023             step_y = 1<<step_y;
1024
1025             for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
1026                 for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
1027                     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1028                         unsigned prcx, prcy;
1029                         int precno;
1030                         int trx0, try0;
1031                         uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1032                         Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1033
1034                         trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
1035                         try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
1036
1037                         if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
1038                             (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
1039                             continue;
1040
1041                         if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
1042                             (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
1043                             continue;
1044
1045                         // check if a precinct exists
1046                         prcx   = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
1047                         prcy   = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
1048                         prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
1049                         prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
1050
1051                         precno = prcx + reslevel->num_precincts_x * prcy;
1052
1053                         if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1054                             av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1055                                    prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1056                             continue;
1057                         }
1058                         if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1059                                   qntsty->nguardbits, packetno++)) < 0)
1060                             return ret;
1061                     }
1062                 }
1063             }
1064         }
1065
1066     }
1067
1068     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
1069     return 0;
1070 }
1071
1072 static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
1073 {
1074     int passno, res = 0;
1075     for (passno = 0; passno < cblk->npasses; passno++){
1076         int dr;
1077         int64_t dd;
1078
1079         dr = cblk->passes[passno].rate
1080            - (res ? cblk->passes[res-1].rate:0);
1081         dd = cblk->passes[passno].disto
1082            - (res ? cblk->passes[res-1].disto:0);
1083
1084         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
1085             res = passno+1;
1086     }
1087     return res;
1088 }
1089
1090 static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
1091 {
1092     int precno, compno, reslevelno, bandno, cblkno, lev;
1093     Jpeg2000CodingStyle *codsty = &s->codsty;
1094
1095     for (compno = 0; compno < s->ncomponents; compno++){
1096         Jpeg2000Component *comp = tile->comp + compno;
1097
1098         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
1099             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1100
1101             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
1102                 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1103                     int bandpos = bandno + (reslevelno > 0);
1104                     Jpeg2000Band *band = reslevel->band + bandno;
1105                     Jpeg2000Prec *prec = band->prec + precno;
1106
1107                     for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
1108                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1109
1110                         cblk->ninclpasses = getcut(cblk, s->lambda,
1111                                 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
1112                     }
1113                 }
1114             }
1115         }
1116     }
1117 }
1118
1119 static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
1120 {
1121     int compno, reslevelno, bandno, ret;
1122     Jpeg2000T1Context t1;
1123     Jpeg2000CodingStyle *codsty = &s->codsty;
1124     for (compno = 0; compno < s->ncomponents; compno++){
1125         Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1126
1127         t1.stride = (1<<codsty->log2_cblk_width) + 2;
1128
1129         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
1130         if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
1131             return ret;
1132         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
1133
1134         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
1135             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1136
1137             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1138                 Jpeg2000Band *band = reslevel->band + bandno;
1139                 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
1140                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
1141                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
1142                 y0 = yy0;
1143                 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
1144                             band->coord[1][1]) - band->coord[1][0] + yy0;
1145
1146                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
1147                     continue;
1148
1149                 bandpos = bandno + (reslevelno > 0);
1150
1151                 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
1152                     if (reslevelno == 0 || bandno == 1)
1153                         xx0 = 0;
1154                     else
1155                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
1156                     x0 = xx0;
1157                     xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
1158                                 band->coord[0][1]) - band->coord[0][0] + xx0;
1159
1160                     for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
1161                         int y, x;
1162                         if (codsty->transform == FF_DWT53){
1163                             for (y = yy0; y < yy1; y++){
1164                                 int *ptr = t1.data + (y-yy0)*t1.stride;
1165                                 for (x = xx0; x < xx1; x++){
1166                                     *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] * (1 << NMSEDEC_FRACBITS);
1167                                 }
1168                             }
1169                         } else{
1170                             for (y = yy0; y < yy1; y++){
1171                                 int *ptr = t1.data + (y-yy0)*t1.stride;
1172                                 for (x = xx0; x < xx1; x++){
1173                                     *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
1174                                     *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
1175                                     ptr++;
1176                                 }
1177                             }
1178                         }
1179                         if (!prec->cblk[cblkno].data)
1180                             prec->cblk[cblkno].data = av_malloc(1 + 8192);
1181                         if (!prec->cblk[cblkno].passes)
1182                             prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
1183                         if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
1184                             return AVERROR(ENOMEM);
1185                         encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
1186                                     bandpos, codsty->nreslevels - reslevelno - 1);
1187                         xx0 = xx1;
1188                         xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
1189                     }
1190                     yy0 = yy1;
1191                     yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
1192                 }
1193             }
1194         }
1195         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
1196     }
1197
1198     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
1199     truncpasses(s, tile);
1200     if ((ret = encode_packets(s, tile, tileno)) < 0)
1201         return ret;
1202     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
1203     return 0;
1204 }
1205
1206 static void cleanup(Jpeg2000EncoderContext *s)
1207 {
1208     int tileno, compno;
1209     Jpeg2000CodingStyle *codsty = &s->codsty;
1210
1211     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1212         for (compno = 0; compno < s->ncomponents; compno++){
1213             Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1214             ff_jpeg2000_cleanup(comp, codsty);
1215         }
1216         av_freep(&s->tile[tileno].comp);
1217     }
1218     av_freep(&s->tile);
1219 }
1220
1221 static void reinit(Jpeg2000EncoderContext *s)
1222 {
1223     int tileno, compno;
1224     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1225         Jpeg2000Tile *tile = s->tile + tileno;
1226         for (compno = 0; compno < s->ncomponents; compno++)
1227             ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
1228     }
1229 }
1230
1231 static void update_size(uint8_t *size, const uint8_t *end)
1232 {
1233     AV_WB32(size, end-size);
1234 }
1235
1236 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1237                         const AVFrame *pict, int *got_packet)
1238 {
1239     int tileno, ret;
1240     Jpeg2000EncoderContext *s = avctx->priv_data;
1241     uint8_t *chunkstart, *jp2cstart, *jp2hstart;
1242
1243     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
1244         return ret;
1245
1246     // init:
1247     s->buf = s->buf_start = pkt->data;
1248     s->buf_end = pkt->data + pkt->size;
1249
1250     s->picture = pict;
1251
1252     s->lambda = s->picture->quality * LAMBDA_SCALE;
1253
1254     if (avctx->pix_fmt == AV_PIX_FMT_BGR48 || avctx->pix_fmt == AV_PIX_FMT_GRAY16)
1255         copy_frame_16(s);
1256     else
1257         copy_frame_8(s);
1258
1259     reinit(s);
1260
1261     if (s->format == CODEC_JP2) {
1262         av_assert0(s->buf == pkt->data);
1263
1264         bytestream_put_be32(&s->buf, 0x0000000C);
1265         bytestream_put_be32(&s->buf, 0x6A502020);
1266         bytestream_put_be32(&s->buf, 0x0D0A870A);
1267
1268         chunkstart = s->buf;
1269         bytestream_put_be32(&s->buf, 0);
1270         bytestream_put_buffer(&s->buf, "ftyp", 4);
1271         bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
1272         bytestream_put_be32(&s->buf, 0);
1273         bytestream_put_buffer(&s->buf, "jp2\040", 4);
1274         update_size(chunkstart, s->buf);
1275
1276         jp2hstart = s->buf;
1277         bytestream_put_be32(&s->buf, 0);
1278         bytestream_put_buffer(&s->buf, "jp2h", 4);
1279
1280         chunkstart = s->buf;
1281         bytestream_put_be32(&s->buf, 0);
1282         bytestream_put_buffer(&s->buf, "ihdr", 4);
1283         bytestream_put_be32(&s->buf, avctx->height);
1284         bytestream_put_be32(&s->buf, avctx->width);
1285         bytestream_put_be16(&s->buf, s->ncomponents);
1286         bytestream_put_byte(&s->buf, s->cbps[0]);
1287         bytestream_put_byte(&s->buf, 7);
1288         bytestream_put_byte(&s->buf, 0);
1289         bytestream_put_byte(&s->buf, 0);
1290         update_size(chunkstart, s->buf);
1291
1292         chunkstart = s->buf;
1293         bytestream_put_be32(&s->buf, 0);
1294         bytestream_put_buffer(&s->buf, "colr", 4);
1295         bytestream_put_byte(&s->buf, 1);
1296         bytestream_put_byte(&s->buf, 0);
1297         bytestream_put_byte(&s->buf, 0);
1298         if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1299             bytestream_put_be32(&s->buf, 16);
1300         } else if (s->ncomponents == 1) {
1301             bytestream_put_be32(&s->buf, 17);
1302         } else {
1303             bytestream_put_be32(&s->buf, 18);
1304         }
1305         update_size(chunkstart, s->buf);
1306         if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1307             int i;
1308             uint8_t *palette = pict->data[1];
1309             chunkstart = s->buf;
1310             bytestream_put_be32(&s->buf, 0);
1311             bytestream_put_buffer(&s->buf, "pclr", 4);
1312             bytestream_put_be16(&s->buf, AVPALETTE_COUNT);
1313             bytestream_put_byte(&s->buf, 3); // colour channels
1314             bytestream_put_be24(&s->buf, 0x070707); //colour depths
1315             for (i = 0; i < AVPALETTE_COUNT; i++) {
1316                 bytestream_put_be24(&s->buf, HAVE_BIGENDIAN ? AV_RB24(palette + 1) : AV_RL24(palette));
1317                 palette += 4;
1318             }
1319             update_size(chunkstart, s->buf);
1320             chunkstart = s->buf;
1321             bytestream_put_be32(&s->buf, 0);
1322             bytestream_put_buffer(&s->buf, "cmap", 4);
1323             for (i = 0; i < 3; i++) {
1324                 bytestream_put_be16(&s->buf, 0); // component
1325                 bytestream_put_byte(&s->buf, 1); // palette mapping
1326                 bytestream_put_byte(&s->buf, i); // index
1327             }
1328             update_size(chunkstart, s->buf);
1329         }
1330         update_size(jp2hstart, s->buf);
1331
1332         jp2cstart = s->buf;
1333         bytestream_put_be32(&s->buf, 0);
1334         bytestream_put_buffer(&s->buf, "jp2c", 4);
1335     }
1336
1337     if (s->buf_end - s->buf < 2)
1338         return -1;
1339     bytestream_put_be16(&s->buf, JPEG2000_SOC);
1340     if ((ret = put_siz(s)) < 0)
1341         return ret;
1342     if ((ret = put_cod(s)) < 0)
1343         return ret;
1344     if ((ret = put_qcd(s, 0)) < 0)
1345         return ret;
1346     if ((ret = put_com(s, 0)) < 0)
1347         return ret;
1348
1349     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1350         uint8_t *psotptr;
1351         if (!(psotptr = put_sot(s, tileno)))
1352             return -1;
1353         if (s->buf_end - s->buf < 2)
1354             return -1;
1355         bytestream_put_be16(&s->buf, JPEG2000_SOD);
1356         if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1357             return ret;
1358         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1359     }
1360     if (s->buf_end - s->buf < 2)
1361         return -1;
1362     bytestream_put_be16(&s->buf, JPEG2000_EOC);
1363
1364     if (s->format == CODEC_JP2)
1365         update_size(jp2cstart, s->buf);
1366
1367     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1368     pkt->size = s->buf - s->buf_start;
1369     pkt->flags |= AV_PKT_FLAG_KEY;
1370     *got_packet = 1;
1371
1372     return 0;
1373 }
1374
1375 static av_cold int j2kenc_init(AVCodecContext *avctx)
1376 {
1377     int i, ret;
1378     Jpeg2000EncoderContext *s = avctx->priv_data;
1379     Jpeg2000CodingStyle *codsty = &s->codsty;
1380     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1381
1382     s->avctx = avctx;
1383     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1384
1385 #if FF_API_PRIVATE_OPT
1386 FF_DISABLE_DEPRECATION_WARNINGS
1387     if (avctx->prediction_method)
1388         s->pred = avctx->prediction_method;
1389 FF_ENABLE_DEPRECATION_WARNINGS
1390 #endif
1391
1392     if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (s->pred != FF_DWT97_INT || s->format != CODEC_JP2)) {
1393         av_log(s->avctx, AV_LOG_WARNING, "Forcing lossless jp2 for pal8\n");
1394         s->pred = FF_DWT97_INT;
1395         s->format = CODEC_JP2;
1396     }
1397
1398     // defaults:
1399     // TODO: implement setting non-standard precinct size
1400     memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1401     memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1402     codsty->nreslevels2decode=
1403     codsty->nreslevels       = 7;
1404     codsty->log2_cblk_width  = 4;
1405     codsty->log2_cblk_height = 4;
1406     codsty->transform        = s->pred ? FF_DWT53 : FF_DWT97_INT;
1407
1408     qntsty->nguardbits       = 1;
1409
1410     if ((s->tile_width  & (s->tile_width -1)) ||
1411         (s->tile_height & (s->tile_height-1))) {
1412         av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
1413     }
1414
1415     if (codsty->transform == FF_DWT53)
1416         qntsty->quantsty = JPEG2000_QSTY_NONE;
1417     else
1418         qntsty->quantsty = JPEG2000_QSTY_SE;
1419
1420     s->width = avctx->width;
1421     s->height = avctx->height;
1422
1423     for (i = 0; i < 3; i++) {
1424         if (avctx->pix_fmt == AV_PIX_FMT_GRAY16 || avctx->pix_fmt == AV_PIX_FMT_RGB48)
1425             s->cbps[i] = 16;
1426         else
1427             s->cbps[i] = 8;
1428     }
1429
1430     if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_RGB48){
1431         s->ncomponents = 3;
1432     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16){
1433         s->ncomponents = 1;
1434     } else{ // planar YUV
1435         s->planar = 1;
1436         s->ncomponents = 3;
1437         ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
1438                                                s->chroma_shift, s->chroma_shift + 1);
1439         if (ret)
1440             return ret;
1441     }
1442
1443     ff_jpeg2000_init_tier1_luts();
1444     ff_mqc_init_context_tables();
1445     init_luts();
1446
1447     init_quantization(s);
1448     if ((ret=init_tiles(s)) < 0)
1449         return ret;
1450
1451     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1452
1453     return 0;
1454 }
1455
1456 static int j2kenc_destroy(AVCodecContext *avctx)
1457 {
1458     Jpeg2000EncoderContext *s = avctx->priv_data;
1459
1460     cleanup(s);
1461     return 0;
1462 }
1463
1464 // taken from the libopenjpeg wraper so it matches
1465
1466 #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1467 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1468 static const AVOption options[] = {
1469     { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
1470     { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
1471     { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
1472     { "tile_width",    "Tile Width",        OFFSET(tile_width),    AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1473     { "tile_height",   "Tile Height",       OFFSET(tile_height),   AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1474     { "pred",          "DWT Type",          OFFSET(pred),          AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, "pred"        },
1475     { "dwt97int",      NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
1476     { "dwt53",         NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
1477     { "sop",           "SOP marker",        OFFSET(sop),           AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, },
1478     { "eph",           "EPH marker",        OFFSET(eph),           AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, },
1479     { "prog",          "Progression Order", OFFSET(prog),          AV_OPT_TYPE_INT,   { .i64 = 0           }, JPEG2000_PGOD_LRCP,         JPEG2000_PGOD_CPRL,           VE, "prog" },
1480     { "lrcp",          NULL,                OFFSET(prog),          AV_OPT_TYPE_CONST,   { .i64 = JPEG2000_PGOD_LRCP           }, 0,         0,           VE, "prog" },
1481     { "rlcp",          NULL,                OFFSET(prog),          AV_OPT_TYPE_CONST,   { .i64 = JPEG2000_PGOD_RLCP            }, 0,         0,           VE, "prog" },
1482     { "rpcl",          NULL,                OFFSET(prog),          AV_OPT_TYPE_CONST,   { .i64 = JPEG2000_PGOD_RPCL            }, 0,         0,           VE, "prog" },
1483     { "pcrl",          NULL,                OFFSET(prog),          AV_OPT_TYPE_CONST,   { .i64 = JPEG2000_PGOD_PCRL            }, 0,         0,           VE, "prog" },
1484     { "cprl",          NULL,                OFFSET(prog),          AV_OPT_TYPE_CONST,   { .i64 = JPEG2000_PGOD_CPRL            }, 0,         0,           VE, "prog" },
1485     { NULL }
1486 };
1487
1488 static const AVClass j2k_class = {
1489     .class_name = "jpeg 2000 encoder",
1490     .item_name  = av_default_item_name,
1491     .option     = options,
1492     .version    = LIBAVUTIL_VERSION_INT,
1493 };
1494
1495 AVCodec ff_jpeg2000_encoder = {
1496     .name           = "jpeg2000",
1497     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1498     .type           = AVMEDIA_TYPE_VIDEO,
1499     .id             = AV_CODEC_ID_JPEG2000,
1500     .priv_data_size = sizeof(Jpeg2000EncoderContext),
1501     .init           = j2kenc_init,
1502     .encode2        = encode_frame,
1503     .close          = j2kenc_destroy,
1504     .pix_fmts       = (const enum AVPixelFormat[]) {
1505         AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1506         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
1507         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
1508         AV_PIX_FMT_PAL8,
1509         AV_PIX_FMT_RGB48, AV_PIX_FMT_GRAY16,
1510         AV_PIX_FMT_NONE
1511     },
1512     .priv_class     = &j2k_class,
1513 };