j2kenc.c 45.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * JPEG2000 image encoder
 * Copyright (c) 2007 Kamil Nowosad
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 *
 * **********************************************************************************************************************
 *
 *
 *
 * This source code incorporates work covered by the following copyright and
 * permission notice:
 *
 * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
 * Copyright (c) 2002-2007, Professor Benoit Macq
 * Copyright (c) 2001-2003, David Janssens
 * Copyright (c) 2002-2003, Yannick Verschueren
 * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
 * Copyright (c) 2005, Herve Drolon, FreeImage Team
 * Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
57 58
 */

59

60 61 62 63 64 65 66 67
/**
 * JPEG2000 image encoder
 * @file
 * @author Kamil Nowosad
 */

#include <float.h>
#include "avcodec.h"
68
#include "internal.h"
69
#include "bytestream.h"
70
#include "jpeg2000.h"
71
#include "libavutil/common.h"
72
#include "libavutil/opt.h"
73 74 75 76 77 78

#define NMSEDEC_BITS 7
#define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
#define WMSEDEC_SHIFT 13 ///< must be >= 13
#define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))

79 80 81
#define CODEC_JP2 1
#define CODEC_J2K 0

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
           lut_nmsedec_ref0[1<<NMSEDEC_BITS],
           lut_nmsedec_sig [1<<NMSEDEC_BITS],
           lut_nmsedec_sig0[1<<NMSEDEC_BITS];

static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
    {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
     {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
     {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
     {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},

    {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
     {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
     {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
     { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
};

typedef struct {
100 101
   Jpeg2000Component *comp;
} Jpeg2000Tile;
102 103

typedef struct {
104
    AVClass *class;
105
    AVCodecContext *avctx;
106
    const AVFrame *picture;
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    int width, height; ///< image width and height
    uint8_t cbps[4]; ///< bits per sample in particular components
    int chroma_shift[2];
    uint8_t planar;
    int ncomponents;
    int tile_width, tile_height; ///< tile size
    int numXtiles, numYtiles;

    uint8_t *buf_start;
    uint8_t *buf;
    uint8_t *buf_end;
    int bit_index;

    int64_t lambda;

123 124
    Jpeg2000CodingStyle codsty;
    Jpeg2000QuantStyle  qntsty;
125

126
    Jpeg2000Tile *tile;
127 128

    int format;
129
    int pred;
130
} Jpeg2000EncoderContext;
131 132 133 134 135 136 137 138 139 140 141 142


/* debug */
#if 0
#undef ifprintf
#undef printf

static void nspaces(FILE *fd, int n)
{
    while(n--) putc(' ', fd);
}

143
static void printcomp(Jpeg2000Component *comp)
144 145 146
{
    int i;
    for (i = 0; i < comp->y1 - comp->y0; i++)
147
        ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
148 149
}

150
static void dump(Jpeg2000EncoderContext *s, FILE *fd)
151 152 153 154 155 156 157 158
{
    int tileno, compno, reslevelno, bandno, precno;
    fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
                "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
                "tiles:\n",
            s->width, s->height, s->tile_width, s->tile_height,
            s->numXtiles, s->numYtiles, s->ncomponents);
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
159
        Jpeg2000Tile *tile = s->tile + tileno;
160 161 162
        nspaces(fd, 2);
        fprintf(fd, "tile %d:\n", tileno);
        for(compno = 0; compno < s->ncomponents; compno++){
163
            Jpeg2000Component *comp = tile->comp + compno;
164 165 166 167 168 169
            nspaces(fd, 4);
            fprintf(fd, "component %d:\n", compno);
            nspaces(fd, 4);
            fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
                        comp->x0, comp->x1, comp->y0, comp->y1);
            for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
170
                Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
171 172 173 174 175 176 177
                nspaces(fd, 6);
                fprintf(fd, "reslevel %d:\n", reslevelno);
                nspaces(fd, 6);
                fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
                        reslevel->x0, reslevel->x1, reslevel->y0,
                        reslevel->y1, reslevel->nbands);
                for(bandno = 0; bandno < reslevel->nbands; bandno++){
178
                    Jpeg2000Band *band = reslevel->band + bandno;
179 180 181 182 183 184 185 186 187 188
                    nspaces(fd, 8);
                    fprintf(fd, "band %d:\n", bandno);
                    nspaces(fd, 8);
                    fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
                                "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
                                band->x0, band->x1,
                                band->y0, band->y1,
                                band->codeblock_width, band->codeblock_height,
                                band->cblknx, band->cblkny);
                    for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
189
                        Jpeg2000Prec *prec = band->prec + precno;
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
                        nspaces(fd, 10);
                        fprintf(fd, "prec %d:\n", precno);
                        nspaces(fd, 10);
                        fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
                                     prec->xi0, prec->xi1, prec->yi0, prec->yi1);
                    }
                }
            }
        }
    }
}
#endif

/* bitstream routines */

/** put n times val bit */
206
static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
207 208 209 210 211 212 213 214 215 216 217 218
{
    while (n-- > 0){
        if (s->bit_index == 8)
        {
            s->bit_index = *s->buf == 0xff;
            *(++s->buf) = 0;
        }
        *s->buf |= val << (7 - s->bit_index++);
    }
}

/** put n least significant bits of a number num */
219
static void put_num(Jpeg2000EncoderContext *s, int num, int n)
220 221 222 223 224 225
{
    while(--n >= 0)
        put_bits(s, (num >> n) & 1, 1);
}

/** flush the bitstream */
226
static void j2k_flush(Jpeg2000EncoderContext *s)
227 228 229 230 231 232 233 234 235 236
{
    if (s->bit_index){
        s->bit_index = 0;
        s->buf++;
    }
}

/* tag tree routines */

/** code the value stored in node */
237
static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
238
{
239
    Jpeg2000TgtNode *stack[30];
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    int sp = 1, curval = 0;
    stack[0] = node;

    node = node->parent;
    while(node){
        if (node->vis){
            curval = node->val;
            break;
        }
        node->vis++;
        stack[sp++] = node;
        node = node->parent;
    }
    while(--sp >= 0){
        if (stack[sp]->val >= threshold){
            put_bits(s, 0, threshold - curval);
            break;
        }
        put_bits(s, 0, stack[sp]->val - curval);
        put_bits(s, 1, 1);
        curval = stack[sp]->val;
    }
}

/** update the value in node */
265
static void tag_tree_update(Jpeg2000TgtNode *node)
266 267 268 269 270 271 272 273 274 275 276
{
    int lev = 0;
    while (node->parent){
        if (node->parent->val <= node->val)
            break;
        node->parent->val = node->val;
        node = node->parent;
        lev++;
    }
}

277
static int put_siz(Jpeg2000EncoderContext *s)
278 279 280 281 282 283
{
    int i;

    if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
        return -1;

284
    bytestream_put_be16(&s->buf, JPEG2000_SIZ);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
    bytestream_put_be16(&s->buf, 0); // Rsiz
    bytestream_put_be32(&s->buf, s->width); // width
    bytestream_put_be32(&s->buf, s->height); // height
    bytestream_put_be32(&s->buf, 0); // X0Siz
    bytestream_put_be32(&s->buf, 0); // Y0Siz

    bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
    bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
    bytestream_put_be32(&s->buf, 0); // XT0Siz
    bytestream_put_be32(&s->buf, 0); // YT0Siz
    bytestream_put_be16(&s->buf, s->ncomponents); // CSiz

    for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
        bytestream_put_byte(&s->buf, 7);
        bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
        bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
    }
    return 0;
}

306
static int put_cod(Jpeg2000EncoderContext *s)
307
{
308
    Jpeg2000CodingStyle *codsty = &s->codsty;
309 310 311 312

    if (s->buf_end - s->buf < 14)
        return -1;

313
    bytestream_put_be16(&s->buf, JPEG2000_COD);
314 315 316 317 318
    bytestream_put_be16(&s->buf, 12); // Lcod
    bytestream_put_byte(&s->buf, 0);  // Scod
    // SGcod
    bytestream_put_byte(&s->buf, 0); // progression level
    bytestream_put_be16(&s->buf, 1); // num of layers
319
    if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
320
        bytestream_put_byte(&s->buf, 0); // unspecified
321 322 323
    }else{
        bytestream_put_byte(&s->buf, 0); // unspecified
    }
324 325 326 327 328
    // SPcod
    bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
    bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
    bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
    bytestream_put_byte(&s->buf, 0); // cblk style
329
    bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
330 331 332
    return 0;
}

333
static int put_qcd(Jpeg2000EncoderContext *s, int compno)
334 335
{
    int i, size;
336 337
    Jpeg2000CodingStyle *codsty = &s->codsty;
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
338

339
    if (qntsty->quantsty == JPEG2000_QSTY_NONE)
340 341 342 343 344 345 346
        size = 4 + 3 * (codsty->nreslevels-1);
    else // QSTY_SE
        size = 5 + 6 * (codsty->nreslevels-1);

    if (s->buf_end - s->buf < size + 2)
        return -1;

347
    bytestream_put_be16(&s->buf, JPEG2000_QCD);
348 349
    bytestream_put_be16(&s->buf, size);  // LQcd
    bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
350
    if (qntsty->quantsty == JPEG2000_QSTY_NONE)
351 352 353 354 355 356 357 358
        for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
            bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
    else // QSTY_SE
        for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
            bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
    return 0;
}

359 360 361 362
static int put_com(Jpeg2000EncoderContext *s, int compno)
{
    int size = 4 + strlen(LIBAVCODEC_IDENT);

363
    if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
364 365 366 367 368 369 370 371 372 373 374 375 376 377
        return 0;

    if (s->buf_end - s->buf < size + 2)
        return -1;

    bytestream_put_be16(&s->buf, JPEG2000_COM);
    bytestream_put_be16(&s->buf, size);
    bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)

    bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));

    return 0;
}

378
static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
379 380 381 382
{
    uint8_t *psotptr;

    if (s->buf_end - s->buf < 12)
383
        return NULL;
384

385
    bytestream_put_be16(&s->buf, JPEG2000_SOT);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    bytestream_put_be16(&s->buf, 10); // Lsot
    bytestream_put_be16(&s->buf, tileno); // Isot

    psotptr = s->buf;
    bytestream_put_be32(&s->buf, 0); // Psot (filled in later)

    bytestream_put_byte(&s->buf, 0); // TPsot
    bytestream_put_byte(&s->buf, 1); // TNsot
    return psotptr;
}

/**
 * compute the sizes of tiles, resolution levels, bands, etc.
 * allocate memory for them
 * divide the input image into tile-components
 */
402
static int init_tiles(Jpeg2000EncoderContext *s)
403 404
{
    int tileno, tilex, tiley, compno;
405 406
    Jpeg2000CodingStyle *codsty = &s->codsty;
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
407

408 409
    s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
    s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
410

411
    s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
412 413 414 415
    if (!s->tile)
        return AVERROR(ENOMEM);
    for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
        for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
416
            Jpeg2000Tile *tile = s->tile + tileno;
417

418
            tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
419 420 421
            if (!tile->comp)
                return AVERROR(ENOMEM);
            for (compno = 0; compno < s->ncomponents; compno++){
422
                Jpeg2000Component *comp = tile->comp + compno;
423 424
                int ret, i, j;

425 426 427 428
                comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
                comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
                comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
                comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
429 430 431
                if (compno > 0)
                    for (i = 0; i < 2; i++)
                        for (j = 0; j < 2; j++)
432
                            comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
433

434
                if ((ret = ff_jpeg2000_init_component(comp,
435 436 437 438 439 440
                                                codsty,
                                                qntsty,
                                                s->cbps[compno],
                                                compno?1<<s->chroma_shift[0]:1,
                                                compno?1<<s->chroma_shift[1]:1,
                                                s->avctx
441
                                               )) < 0)
442 443 444 445 446 447
                    return ret;
            }
        }
    return 0;
}

448
static void copy_frame(Jpeg2000EncoderContext *s)
449 450 451 452
{
    int tileno, compno, i, y, x;
    uint8_t *line;
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
453
        Jpeg2000Tile *tile = s->tile + tileno;
454 455
        if (s->planar){
            for (compno = 0; compno < s->ncomponents; compno++){
456
                Jpeg2000Component *comp = tile->comp + compno;
457
                int *dst = comp->i_data;
458 459
                line = s->picture->data[compno]
                       + comp->coord[1][0] * s->picture->linesize[compno]
460 461 462 463 464
                       + comp->coord[0][0];
                for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
                    uint8_t *ptr = line;
                    for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
                        *dst++ = *ptr++ - (1 << 7);
465
                    line += s->picture->linesize[compno];
466 467 468
                }
            }
        } else{
469
            line = s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0]
470 471 472 473 474 475 476
                   + tile->comp[0].coord[0][0] * s->ncomponents;

            i = 0;
            for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
                uint8_t *ptr = line;
                for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
                    for (compno = 0; compno < s->ncomponents; compno++){
477
                        tile->comp[compno].i_data[i] = *ptr++  - (1 << 7);
478 479
                    }
                }
480
                line += s->picture->linesize[0];
481 482 483 484 485
            }
        }
    }
}

486
static void init_quantization(Jpeg2000EncoderContext *s)
487 488
{
    int compno, reslevelno, bandno;
489 490
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
    Jpeg2000CodingStyle *codsty = &s->codsty;
491 492 493 494 495 496 497

    for (compno = 0; compno < s->ncomponents; compno++){
        int gbandno = 0;
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
            int nbands, lev = codsty->nreslevels - reslevelno - 1;
            nbands = reslevelno ? 3 : 1;
            for (bandno = 0; bandno < nbands; bandno++, gbandno++){
498
                int expn, mant = 0;
499

500
                if (codsty->transform == FF_DWT97_INT){
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
                    int bandpos = bandno + (reslevelno>0),
                        ss = 81920000 / dwt_norms[0][bandpos][lev],
                        log = av_log2(ss);
                    mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
                    expn = s->cbps[compno] - log + 13;
                } else
                    expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];

                qntsty->expn[gbandno] = expn;
                qntsty->mant[gbandno] = mant;
            }
        }
    }
}

516
static void init_luts(void)
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
{
    int i, a,
        mask = ~((1<<NMSEDEC_FRACBITS)-1);

    for (i = 0; i < (1 << NMSEDEC_BITS); i++){
        lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
        lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);

        a = (i >> (NMSEDEC_BITS-2)&2) + 1;
        lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
                                    << 13-NMSEDEC_FRACBITS, 0);
        lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
                                    << 1, 0);
    }
}

/* tier-1 routines */
static int getnmsedec_sig(int x, int bpno)
{
    if (bpno > NMSEDEC_FRACBITS)
        return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
    return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
}

static int getnmsedec_ref(int x, int bpno)
{
    if (bpno > NMSEDEC_FRACBITS)
        return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
    return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
}

548
static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
549 550 551 552 553
{
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
    for (y0 = 0; y0 < height; y0 += 4)
        for (x = 0; x < width; x++)
            for (y = y0; y < height && y < y0+4; y++){
554 555 556
                if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
                    int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
                        bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
557 558 559
                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
                    if (bit){
                        int xorbit;
560 561 562 563
                        int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
                        *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
                        ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
564
                    }
565
                    t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
566 567 568 569
                }
            }
}

570
static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
571 572 573 574 575
{
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
    for (y0 = 0; y0 < height; y0 += 4)
        for (x = 0; x < width; x++)
            for (y = y0; y < height && y < y0+4; y++)
576 577 578 579 580
                if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
                    int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
                    *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
                    t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
581 582 583
                }
}

584
static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
585 586 587 588 589
{
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
    for (y0 = 0; y0 < height; y0 += 4)
        for (x = 0; x < width; x++){
            if (y0 + 3 < height && !(
590 591 592 593
            (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
            (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
            (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
            (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
594 595 596 597
            {
                // aggregation mode
                int rlen;
                for (rlen = 0; rlen < 4; rlen++)
598
                    if (t1->data[(y0+rlen) * t1->stride + x] & mask)
599 600 601 602 603 604 605
                        break;
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
                if (rlen == 4)
                    continue;
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
                for (y = y0 + rlen; y < y0 + 4; y++){
606 607
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
608
                        if (y > y0 + rlen)
609 610
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
                        if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
611
                            int xorbit;
612 613 614 615
                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
                            *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
616 617
                        }
                    }
618
                    t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
619 620 621
                }
            } else{
                for (y = y0; y < y0 + 4 && y < height; y++){
622 623 624 625
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
                        if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
626
                            int xorbit;
627 628 629 630
                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
                            *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
631 632
                        }
                    }
633
                    t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
634 635 636 637 638
                }
            }
        }
}

639
static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
640 641 642 643 644
                        int width, int height, int bandpos, int lev)
{
    int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
    int64_t wmsedec = 0;

645
    memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
646 647 648

    for (y = 0; y < height; y++){
        for (x = 0; x < width; x++){
649 650 651
            if (t1->data[(y) * t1->stride + x] < 0){
                t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
                t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
652
            }
653
            max = FFMAX(max, t1->data[(y) * t1->stride + x]);
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        }
    }

    if (max == 0){
        cblk->nonzerobits = 0;
        bpno = 0;
    } else{
        cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
        bpno = cblk->nonzerobits - 1;
    }

    ff_mqc_initenc(&t1->mqc, cblk->data);

    for (passno = 0; bpno >= 0; passno++){
        nmsedec=0;

        switch(pass_t){
            case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
                    break;
            case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
                    break;
            case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
                    break;
        }

679
        cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
680 681 682 683 684 685 686 687 688 689 690
        wmsedec += (int64_t)nmsedec << (2*bpno);
        cblk->passes[passno].disto = wmsedec;

        if (++pass_t == 3){
            pass_t = 0;
            bpno--;
        }
    }
    cblk->npasses = passno;
    cblk->ninclpasses = passno;

691
    cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
692 693 694 695
}

/* tier-2 routines: */

696
static void putnumpasses(Jpeg2000EncoderContext *s, int n)
697 698 699 700 701 702 703 704 705 706 707 708 709 710
{
    if (n == 1)
        put_num(s, 0, 1);
    else if (n == 2)
        put_num(s, 2, 2);
    else if (n <= 5)
        put_num(s, 0xc | (n-3), 4);
    else if (n <= 36)
        put_num(s, 0x1e0 | (n-6), 9);
    else
        put_num(s, 0xff80 | (n-37), 16);
}


711
static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                          uint8_t *expn, int numgbits)
{
    int bandno, empty = 1;

    // init bitstream
    *s->buf = 0;
    s->bit_index = 0;

    // header

    // is the packet empty?
    for (bandno = 0; bandno < rlevel->nbands; bandno++){
        if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
        &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
            empty = 0;
            break;
        }
    }

    put_bits(s, !empty, 1);
    if (empty){
        j2k_flush(s);
        return 0;
    }

    for (bandno = 0; bandno < rlevel->nbands; bandno++){
738 739
        Jpeg2000Band *band = rlevel->band + bandno;
        Jpeg2000Prec *prec = band->prec + precno;
740
        int yi, xi, pos;
741
        int cblknw = prec->nb_codeblocks_width;
742 743 744 745 746

        if (band->coord[0][0] == band->coord[0][1]
        ||  band->coord[1][0] == band->coord[1][1])
            continue;

747 748
        for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
            for (xi = 0; xi < cblknw; xi++, pos++){
749
                prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
750
                tag_tree_update(prec->cblkincl + pos);
751
                prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
752 753 754 755
                tag_tree_update(prec->zerobits + pos);
            }
        }

756 757
        for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
            for (xi = 0; xi < cblknw; xi++, pos++){
758
                int pad = 0, llen, length;
759
                Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787

                if (s->buf_end - s->buf < 20) // approximately
                    return -1;

                // inclusion information
                tag_tree_code(s, prec->cblkincl + pos, 1);
                if (!cblk->ninclpasses)
                    continue;
                // zerobits information
                tag_tree_code(s, prec->zerobits + pos, 100);
                // number of passes
                putnumpasses(s, cblk->ninclpasses);

                length = cblk->passes[cblk->ninclpasses-1].rate;
                llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
                if (llen < 0){
                    pad = -llen;
                    llen = 0;
                }
                // length of code block
                put_bits(s, 1, llen);
                put_bits(s, 0, 1);
                put_num(s, length, av_log2(length)+1+pad);
            }
        }
    }
    j2k_flush(s);
    for (bandno = 0; bandno < rlevel->nbands; bandno++){
788 789
        Jpeg2000Band *band = rlevel->band + bandno;
        Jpeg2000Prec *prec = band->prec + precno;
790 791
        int yi, cblknw = prec->nb_codeblocks_width;
        for (yi =0; yi < prec->nb_codeblocks_height; yi++){
792
            int xi;
793
            for (xi = 0; xi < cblknw; xi++){
794
                Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
795 796 797
                if (cblk->ninclpasses){
                    if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
                        return -1;
798 799 800 801
                    bytestream_put_buffer(&s->buf, cblk->data,   cblk->passes[cblk->ninclpasses-1].rate
                                                               - cblk->passes[cblk->ninclpasses-1].flushed_len);
                    bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
                                                   cblk->passes[cblk->ninclpasses-1].flushed_len);
802 803 804 805 806 807 808
                }
            }
        }
    }
    return 0;
}

809
static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
810 811
{
    int compno, reslevelno, ret;
812 813
    Jpeg2000CodingStyle *codsty = &s->codsty;
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
814 815 816 817 818 819

    av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
    // lay-rlevel-comp-pos progression
    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
        for (compno = 0; compno < s->ncomponents; compno++){
            int precno;
820
            Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
821
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
822 823
                if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
                              qntsty->nguardbits)) < 0)
824 825 826 827 828 829 830 831
                    return ret;
            }
        }
    }
    av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
    return 0;
}

832
static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
{
    int passno, res = 0;
    for (passno = 0; passno < cblk->npasses; passno++){
        int dr;
        int64_t dd;

        dr = cblk->passes[passno].rate
           - (res ? cblk->passes[res-1].rate:0);
        dd = cblk->passes[passno].disto
           - (res ? cblk->passes[res-1].disto:0);

        if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
            res = passno+1;
    }
    return res;
}

850
static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
851
{
852
    int precno, compno, reslevelno, bandno, cblkno, lev;
853
    Jpeg2000CodingStyle *codsty = &s->codsty;
854 855

    for (compno = 0; compno < s->ncomponents; compno++){
856
        Jpeg2000Component *comp = tile->comp + compno;
857 858

        for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
859
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
860

861 862 863 864 865
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
                for (bandno = 0; bandno < reslevel->nbands ; bandno++){
                    int bandpos = bandno + (reslevelno > 0);
                    Jpeg2000Band *band = reslevel->band + bandno;
                    Jpeg2000Prec *prec = band->prec + precno;
866

867 868
                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;
869

870
                        cblk->ninclpasses = getcut(cblk, s->lambda,
871
                                (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
872
                    }
873 874 875 876 877 878
                }
            }
        }
    }
}

879
static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
880 881
{
    int compno, reslevelno, bandno, ret;
882 883
    Jpeg2000T1Context t1;
    Jpeg2000CodingStyle *codsty = &s->codsty;
884
    for (compno = 0; compno < s->ncomponents; compno++){
885
        Jpeg2000Component *comp = s->tile[tileno].comp + compno;
886

887 888
        t1.stride = (1<<codsty->log2_cblk_width) + 2;

889
        av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
890
        if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
891 892 893 894
            return ret;
        av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");

        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
895
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
896 897

            for (bandno = 0; bandno < reslevel->nbands ; bandno++){
898
                Jpeg2000Band *band = reslevel->band + bandno;
899
                Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
900 901 902
                int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
                yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
                y0 = yy0;
903
                yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
904 905 906 907 908 909 910
                            band->coord[1][1]) - band->coord[1][0] + yy0;

                if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
                    continue;

                bandpos = bandno + (reslevelno > 0);

911
                for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
912 913 914 915 916
                    if (reslevelno == 0 || bandno == 1)
                        xx0 = 0;
                    else
                        xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
                    x0 = xx0;
917
                    xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
918 919
                                band->coord[0][1]) - band->coord[0][0] + xx0;

920
                    for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
921 922 923
                        int y, x;
                        if (codsty->transform == FF_DWT53){
                            for (y = yy0; y < yy1; y++){
924
                                int *ptr = t1.data + (y-yy0)*t1.stride;
925
                                for (x = xx0; x < xx1; x++){
926
                                    *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
927 928 929 930
                                }
                            }
                        } else{
                            for (y = yy0; y < yy1; y++){
931
                                int *ptr = t1.data + (y-yy0)*t1.stride;
932
                                for (x = xx0; x < xx1; x++){
933
                                    *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
934
                                    *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
935
                                    ptr++;
936 937 938
                                }
                            }
                        }
939
                        encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
940 941
                                    bandpos, codsty->nreslevels - reslevelno - 1);
                        xx0 = xx1;
942
                        xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
943 944
                    }
                    yy0 = yy1;
945
                    yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
946 947 948 949 950 951 952 953
                }
            }
        }
        av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
    }

    av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
    truncpasses(s, tile);
954
    if ((ret = encode_packets(s, tile, tileno)) < 0)
955 956 957 958 959
        return ret;
    av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
    return 0;
}

960
static void cleanup(Jpeg2000EncoderContext *s)
961 962
{
    int tileno, compno;
963
    Jpeg2000CodingStyle *codsty = &s->codsty;
964 965 966

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
        for (compno = 0; compno < s->ncomponents; compno++){
967
            Jpeg2000Component *comp = s->tile[tileno].comp + compno;
968
            ff_jpeg2000_cleanup(comp, codsty);
969 970 971 972 973 974
        }
        av_freep(&s->tile[tileno].comp);
    }
    av_freep(&s->tile);
}

975
static void reinit(Jpeg2000EncoderContext *s)
976 977 978
{
    int tileno, compno;
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
979
        Jpeg2000Tile *tile = s->tile + tileno;
980
        for (compno = 0; compno < s->ncomponents; compno++)
981
            ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
982 983 984
    }
}

985 986 987 988 989
static void update_size(uint8_t *size, const uint8_t *end)
{
    AV_WB32(size, end-size);
}

990 991
static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                        const AVFrame *pict, int *got_packet)
992 993
{
    int tileno, ret;
994
    Jpeg2000EncoderContext *s = avctx->priv_data;
995
    uint8_t *chunkstart, *jp2cstart, *jp2hstart;
996

997
    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
998 999
        return ret;

1000
    // init:
1001 1002
    s->buf = s->buf_start = pkt->data;
    s->buf_end = pkt->data + pkt->size;
1003

1004
    s->picture = pict;
1005

1006
    s->lambda = s->picture->quality * LAMBDA_SCALE;
1007 1008 1009 1010

    copy_frame(s);
    reinit(s);

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    if (s->format == CODEC_JP2) {
        av_assert0(s->buf == pkt->data);

        bytestream_put_be32(&s->buf, 0x0000000C);
        bytestream_put_be32(&s->buf, 0x6A502020);
        bytestream_put_be32(&s->buf, 0x0D0A870A);

        chunkstart = s->buf;
        bytestream_put_be32(&s->buf, 0);
        bytestream_put_buffer(&s->buf, "ftyp", 4);
        bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
        bytestream_put_be32(&s->buf, 0);
1023
        bytestream_put_buffer(&s->buf, "jp2\040", 4);
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        update_size(chunkstart, s->buf);

        jp2hstart = s->buf;
        bytestream_put_be32(&s->buf, 0);
        bytestream_put_buffer(&s->buf, "jp2h", 4);

        chunkstart = s->buf;
        bytestream_put_be32(&s->buf, 0);
        bytestream_put_buffer(&s->buf, "ihdr", 4);
        bytestream_put_be32(&s->buf, avctx->height);
        bytestream_put_be32(&s->buf, avctx->width);
        bytestream_put_be16(&s->buf, s->ncomponents);
        bytestream_put_byte(&s->buf, s->cbps[0]);
        bytestream_put_byte(&s->buf, 7);
        bytestream_put_byte(&s->buf, 0);
        bytestream_put_byte(&s->buf, 0);
        update_size(chunkstart, s->buf);

        chunkstart = s->buf;
        bytestream_put_be32(&s->buf, 0);
        bytestream_put_buffer(&s->buf, "colr", 4);
        bytestream_put_byte(&s->buf, 1);
        bytestream_put_byte(&s->buf, 0);
        bytestream_put_byte(&s->buf, 0);
        if (s->ncomponents == 1) {
            bytestream_put_be32(&s->buf, 17);
        } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
            bytestream_put_be32(&s->buf, 16);
        } else {
            bytestream_put_be32(&s->buf, 18);
        }
        update_size(chunkstart, s->buf);
        update_size(jp2hstart, s->buf);

        jp2cstart = s->buf;
        bytestream_put_be32(&s->buf, 0);
        bytestream_put_buffer(&s->buf, "jp2c", 4);
    }

1063 1064
    if (s->buf_end - s->buf < 2)
        return -1;
1065
    bytestream_put_be16(&s->buf, JPEG2000_SOC);
1066
    if ((ret = put_siz(s)) < 0)
1067
        return ret;
1068
    if ((ret = put_cod(s)) < 0)
1069
        return ret;
1070
    if ((ret = put_qcd(s, 0)) < 0)
1071
        return ret;
1072 1073
    if ((ret = put_com(s, 0)) < 0)
        return ret;
1074 1075 1076

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
        uint8_t *psotptr;
1077 1078
        if (!(psotptr = put_sot(s, tileno)))
            return -1;
1079 1080
        if (s->buf_end - s->buf < 2)
            return -1;
1081
        bytestream_put_be16(&s->buf, JPEG2000_SOD);
1082
        if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1083 1084 1085 1086 1087
            return ret;
        bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
    }
    if (s->buf_end - s->buf < 2)
        return -1;
1088
    bytestream_put_be16(&s->buf, JPEG2000_EOC);
1089

1090 1091 1092
    if (s->format == CODEC_JP2)
        update_size(jp2cstart, s->buf);

1093
    av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1094 1095 1096 1097 1098
    pkt->size = s->buf - s->buf_start;
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;

    return 0;
1099 1100 1101 1102 1103
}

static av_cold int j2kenc_init(AVCodecContext *avctx)
{
    int i, ret;
1104 1105 1106
    Jpeg2000EncoderContext *s = avctx->priv_data;
    Jpeg2000CodingStyle *codsty = &s->codsty;
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1107 1108 1109 1110

    s->avctx = avctx;
    av_log(s->avctx, AV_LOG_DEBUG, "init\n");

1111 1112 1113 1114 1115 1116 1117
#if FF_API_PRIVATE_OPT
FF_DISABLE_DEPRECATION_WARNINGS
    if (avctx->prediction_method)
        s->pred = avctx->prediction_method;
FF_ENABLE_DEPRECATION_WARNINGS
#endif

1118 1119
    // defaults:
    // TODO: implement setting non-standard precinct size
1120 1121
    memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
    memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1122
    codsty->nreslevels2decode=
1123 1124 1125
    codsty->nreslevels       = 7;
    codsty->log2_cblk_width  = 4;
    codsty->log2_cblk_height = 4;
1126
    codsty->transform        = s->pred ? FF_DWT53 : FF_DWT97_INT;
1127 1128 1129

    qntsty->nguardbits       = 1;

1130 1131 1132 1133
    if ((s->tile_width  & (s->tile_width -1)) ||
        (s->tile_height & (s->tile_height-1))) {
        av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
    }
1134 1135

    if (codsty->transform == FF_DWT53)
1136
        qntsty->quantsty = JPEG2000_QSTY_NONE;
1137
    else
1138
        qntsty->quantsty = JPEG2000_QSTY_SE;
1139 1140 1141 1142 1143 1144 1145

    s->width = avctx->width;
    s->height = avctx->height;

    for (i = 0; i < 3; i++)
        s->cbps[i] = 8;

1146
    if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
1147
        s->ncomponents = 3;
1148
    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
1149 1150 1151 1152 1153 1154 1155 1156
        s->ncomponents = 1;
    } else{ // planar YUV
        s->planar = 1;
        s->ncomponents = 3;
        avcodec_get_chroma_sub_sample(avctx->pix_fmt,
                s->chroma_shift, s->chroma_shift + 1);
    }

1157
    ff_jpeg2000_init_tier1_luts();
1158
    ff_mqc_init_context_tables();
1159 1160 1161
    init_luts();

    init_quantization(s);
1162
    if ((ret=init_tiles(s)) < 0)
1163 1164 1165 1166 1167 1168 1169 1170 1171
        return ret;

    av_log(s->avctx, AV_LOG_DEBUG, "after init\n");

    return 0;
}

static int j2kenc_destroy(AVCodecContext *avctx)
{
1172
    Jpeg2000EncoderContext *s = avctx->priv_data;
1173 1174 1175 1176 1177

    cleanup(s);
    return 0;
}

1178 1179 1180 1181 1182
// taken from the libopenjpeg wraper so it matches

#define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
1183
    { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
1184 1185
    { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
    { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
1186 1187
    { "tile_width",    "Tile Width",        OFFSET(tile_width),    AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
    { "tile_height",   "Tile Height",       OFFSET(tile_height),   AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1188 1189 1190
    { "pred",          "DWT Type",          OFFSET(pred),          AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, "pred"        },
    { "dwt97int",      NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
    { "dwt53",         NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    { NULL }
};

static const AVClass j2k_class = {
    .class_name = "jpeg 2000 encoder",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

1202 1203
AVCodec ff_jpeg2000_encoder = {
    .name           = "jpeg2000",
1204
    .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1205
    .type           = AVMEDIA_TYPE_VIDEO,
1206
    .id             = AV_CODEC_ID_JPEG2000,
1207
    .priv_data_size = sizeof(Jpeg2000EncoderContext),
1208
    .init           = j2kenc_init,
1209
    .encode2        = encode_frame,
1210
    .close          = j2kenc_destroy,
1211 1212
    .pix_fmts       = (const enum AVPixelFormat[]) {
        AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1213 1214
        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
1215
        AV_PIX_FMT_NONE
1216 1217
    },
    .priv_class     = &j2k_class,
1218
};