LCOV - code coverage report
Current view: top level - libavcodec - j2kenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 576 636 90.6 %
Date: 2017-12-17 16:07:53 Functions: 32 32 100.0 %

          Line data    Source code
       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             : 
      75             : #define NMSEDEC_BITS 7
      76             : #define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
      77             : #define WMSEDEC_SHIFT 13 ///< must be >= 13
      78             : #define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
      79             : 
      80             : #define CODEC_JP2 1
      81             : #define CODEC_J2K 0
      82             : 
      83             : static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
      84             :            lut_nmsedec_ref0[1<<NMSEDEC_BITS],
      85             :            lut_nmsedec_sig [1<<NMSEDEC_BITS],
      86             :            lut_nmsedec_sig0[1<<NMSEDEC_BITS];
      87             : 
      88             : static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
      89             :     {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
      90             :      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
      91             :      {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
      92             :      {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
      93             : 
      94             :     {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
      95             :      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
      96             :      {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
      97             :      { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
      98             : };
      99             : 
     100             : typedef struct {
     101             :    Jpeg2000Component *comp;
     102             : } Jpeg2000Tile;
     103             : 
     104             : typedef struct {
     105             :     AVClass *class;
     106             :     AVCodecContext *avctx;
     107             :     const AVFrame *picture;
     108             : 
     109             :     int width, height; ///< image width and height
     110             :     uint8_t cbps[4]; ///< bits per sample in particular components
     111             :     int chroma_shift[2];
     112             :     uint8_t planar;
     113             :     int ncomponents;
     114             :     int tile_width, tile_height; ///< tile size
     115             :     int numXtiles, numYtiles;
     116             : 
     117             :     uint8_t *buf_start;
     118             :     uint8_t *buf;
     119             :     uint8_t *buf_end;
     120             :     int bit_index;
     121             : 
     122             :     int64_t lambda;
     123             : 
     124             :     Jpeg2000CodingStyle codsty;
     125             :     Jpeg2000QuantStyle  qntsty;
     126             : 
     127             :     Jpeg2000Tile *tile;
     128             : 
     129             :     int format;
     130             :     int pred;
     131             : } Jpeg2000EncoderContext;
     132             : 
     133             : 
     134             : /* debug */
     135             : #if 0
     136             : #undef ifprintf
     137             : #undef printf
     138             : 
     139             : static void nspaces(FILE *fd, int n)
     140             : {
     141             :     while(n--) putc(' ', fd);
     142             : }
     143             : 
     144             : static void printcomp(Jpeg2000Component *comp)
     145             : {
     146             :     int i;
     147             :     for (i = 0; i < comp->y1 - comp->y0; i++)
     148             :         ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
     149             : }
     150             : 
     151             : static void dump(Jpeg2000EncoderContext *s, FILE *fd)
     152             : {
     153             :     int tileno, compno, reslevelno, bandno, precno;
     154             :     fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
     155             :                 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
     156             :                 "tiles:\n",
     157             :             s->width, s->height, s->tile_width, s->tile_height,
     158             :             s->numXtiles, s->numYtiles, s->ncomponents);
     159             :     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
     160             :         Jpeg2000Tile *tile = s->tile + tileno;
     161             :         nspaces(fd, 2);
     162             :         fprintf(fd, "tile %d:\n", tileno);
     163             :         for(compno = 0; compno < s->ncomponents; compno++){
     164             :             Jpeg2000Component *comp = tile->comp + compno;
     165             :             nspaces(fd, 4);
     166             :             fprintf(fd, "component %d:\n", compno);
     167             :             nspaces(fd, 4);
     168             :             fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
     169             :                         comp->x0, comp->x1, comp->y0, comp->y1);
     170             :             for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
     171             :                 Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
     172             :                 nspaces(fd, 6);
     173             :                 fprintf(fd, "reslevel %d:\n", reslevelno);
     174             :                 nspaces(fd, 6);
     175             :                 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
     176             :                         reslevel->x0, reslevel->x1, reslevel->y0,
     177             :                         reslevel->y1, reslevel->nbands);
     178             :                 for(bandno = 0; bandno < reslevel->nbands; bandno++){
     179             :                     Jpeg2000Band *band = reslevel->band + bandno;
     180             :                     nspaces(fd, 8);
     181             :                     fprintf(fd, "band %d:\n", bandno);
     182             :                     nspaces(fd, 8);
     183             :                     fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
     184             :                                 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
     185             :                                 band->x0, band->x1,
     186             :                                 band->y0, band->y1,
     187             :                                 band->codeblock_width, band->codeblock_height,
     188             :                                 band->cblknx, band->cblkny);
     189             :                     for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
     190             :                         Jpeg2000Prec *prec = band->prec + precno;
     191             :                         nspaces(fd, 10);
     192             :                         fprintf(fd, "prec %d:\n", precno);
     193             :                         nspaces(fd, 10);
     194             :                         fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
     195             :                                      prec->xi0, prec->xi1, prec->yi0, prec->yi1);
     196             :                     }
     197             :                 }
     198             :             }
     199             :         }
     200             :     }
     201             : }
     202             : #endif
     203             : 
     204             : /* bitstream routines */
     205             : 
     206             : /** put n times val bit */
     207     7048069 : static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
     208             : {
     209    20922202 :     while (n-- > 0){
     210     6826064 :         if (s->bit_index == 8)
     211             :         {
     212      837227 :             s->bit_index = *s->buf == 0xff;
     213      837227 :             *(++s->buf) = 0;
     214             :         }
     215     6826064 :         *s->buf |= val << (7 - s->bit_index++);
     216             :     }
     217     7048069 : }
     218             : 
     219             : /** put n least significant bits of a number num */
     220      691538 : static void put_num(Jpeg2000EncoderContext *s, int num, int n)
     221             : {
     222     5663808 :     while(--n >= 0)
     223     4280732 :         put_bits(s, (num >> n) & 1, 1);
     224      691538 : }
     225             : 
     226             : /** flush the bitstream */
     227       27300 : static void j2k_flush(Jpeg2000EncoderContext *s)
     228             : {
     229       27300 :     if (s->bit_index){
     230       27300 :         s->bit_index = 0;
     231       27300 :         s->buf++;
     232             :     }
     233       27300 : }
     234             : 
     235             : /* tag tree routines */
     236             : 
     237             : /** code the value stored in node */
     238      759169 : static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
     239             : {
     240             :     Jpeg2000TgtNode *stack[30];
     241      759169 :     int sp = 1, curval = 0;
     242      759169 :     stack[0] = node;
     243             : 
     244      759169 :     node = node->parent;
     245     1817234 :     while(node){
     246      917643 :         if (node->vis){
     247      618747 :             curval = node->val;
     248      618747 :             break;
     249             :         }
     250      298896 :         node->vis++;
     251      298896 :         stack[sp++] = node;
     252      298896 :         node = node->parent;
     253             :     }
     254     2508772 :     while(--sp >= 0){
     255     1058065 :         if (stack[sp]->val >= threshold){
     256       67631 :             put_bits(s, 0, threshold - curval);
     257       67631 :             break;
     258             :         }
     259      990434 :         put_bits(s, 0, stack[sp]->val - curval);
     260      990434 :         put_bits(s, 1, 1);
     261      990434 :         curval = stack[sp]->val;
     262             :     }
     263      759169 : }
     264             : 
     265             : /** update the value in node */
     266      826800 : static void tag_tree_update(Jpeg2000TgtNode *node)
     267             : {
     268      826800 :     int lev = 0;
     269     1653600 :     while (node->parent){
     270      747000 :         if (node->parent->val <= node->val)
     271      747000 :             break;
     272           0 :         node->parent->val = node->val;
     273           0 :         node = node->parent;
     274           0 :         lev++;
     275             :     }
     276      826800 : }
     277             : 
     278         400 : static int put_siz(Jpeg2000EncoderContext *s)
     279             : {
     280             :     int i;
     281             : 
     282         400 :     if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
     283           0 :         return -1;
     284             : 
     285         400 :     bytestream_put_be16(&s->buf, JPEG2000_SIZ);
     286         400 :     bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
     287         400 :     bytestream_put_be16(&s->buf, 0); // Rsiz
     288         400 :     bytestream_put_be32(&s->buf, s->width); // width
     289         400 :     bytestream_put_be32(&s->buf, s->height); // height
     290         400 :     bytestream_put_be32(&s->buf, 0); // X0Siz
     291         400 :     bytestream_put_be32(&s->buf, 0); // Y0Siz
     292             : 
     293         400 :     bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
     294         400 :     bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
     295         400 :     bytestream_put_be32(&s->buf, 0); // XT0Siz
     296         400 :     bytestream_put_be32(&s->buf, 0); // YT0Siz
     297         400 :     bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
     298             : 
     299        1600 :     for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
     300        1200 :         bytestream_put_byte(&s->buf, 7);
     301        1200 :         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
     302        1200 :         bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
     303             :     }
     304         400 :     return 0;
     305             : }
     306             : 
     307         400 : static int put_cod(Jpeg2000EncoderContext *s)
     308             : {
     309         400 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     310             : 
     311         400 :     if (s->buf_end - s->buf < 14)
     312           0 :         return -1;
     313             : 
     314         400 :     bytestream_put_be16(&s->buf, JPEG2000_COD);
     315         400 :     bytestream_put_be16(&s->buf, 12); // Lcod
     316         400 :     bytestream_put_byte(&s->buf, 0);  // Scod
     317             :     // SGcod
     318         400 :     bytestream_put_byte(&s->buf, 0); // progression level
     319         400 :     bytestream_put_be16(&s->buf, 1); // num of layers
     320         400 :     if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
     321           0 :         bytestream_put_byte(&s->buf, 0); // unspecified
     322             :     }else{
     323         400 :         bytestream_put_byte(&s->buf, 0); // unspecified
     324             :     }
     325             :     // SPcod
     326         400 :     bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
     327         400 :     bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
     328         400 :     bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
     329         400 :     bytestream_put_byte(&s->buf, 0); // cblk style
     330         400 :     bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
     331         400 :     return 0;
     332             : }
     333             : 
     334         400 : static int put_qcd(Jpeg2000EncoderContext *s, int compno)
     335             : {
     336             :     int i, size;
     337         400 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     338         400 :     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
     339             : 
     340         400 :     if (qntsty->quantsty == JPEG2000_QSTY_NONE)
     341         200 :         size = 4 + 3 * (codsty->nreslevels-1);
     342             :     else // QSTY_SE
     343         200 :         size = 5 + 6 * (codsty->nreslevels-1);
     344             : 
     345         400 :     if (s->buf_end - s->buf < size + 2)
     346           0 :         return -1;
     347             : 
     348         400 :     bytestream_put_be16(&s->buf, JPEG2000_QCD);
     349         400 :     bytestream_put_be16(&s->buf, size);  // LQcd
     350         400 :     bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
     351         400 :     if (qntsty->quantsty == JPEG2000_QSTY_NONE)
     352        4000 :         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
     353        3800 :             bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
     354             :     else // QSTY_SE
     355        4000 :         for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
     356        3800 :             bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
     357         400 :     return 0;
     358             : }
     359             : 
     360         400 : static int put_com(Jpeg2000EncoderContext *s, int compno)
     361             : {
     362         400 :     int size = 4 + strlen(LIBAVCODEC_IDENT);
     363             : 
     364         400 :     if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
     365         400 :         return 0;
     366             : 
     367           0 :     if (s->buf_end - s->buf < size + 2)
     368           0 :         return -1;
     369             : 
     370           0 :     bytestream_put_be16(&s->buf, JPEG2000_COM);
     371           0 :     bytestream_put_be16(&s->buf, size);
     372           0 :     bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
     373             : 
     374           0 :     bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
     375             : 
     376           0 :     return 0;
     377             : }
     378             : 
     379        1300 : static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
     380             : {
     381             :     uint8_t *psotptr;
     382             : 
     383        1300 :     if (s->buf_end - s->buf < 12)
     384           0 :         return NULL;
     385             : 
     386        1300 :     bytestream_put_be16(&s->buf, JPEG2000_SOT);
     387        1300 :     bytestream_put_be16(&s->buf, 10); // Lsot
     388        1300 :     bytestream_put_be16(&s->buf, tileno); // Isot
     389             : 
     390        1300 :     psotptr = s->buf;
     391        1300 :     bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
     392             : 
     393        1300 :     bytestream_put_byte(&s->buf, 0); // TPsot
     394        1300 :     bytestream_put_byte(&s->buf, 1); // TNsot
     395        1300 :     return psotptr;
     396             : }
     397             : 
     398             : /**
     399             :  * compute the sizes of tiles, resolution levels, bands, etc.
     400             :  * allocate memory for them
     401             :  * divide the input image into tile-components
     402             :  */
     403           8 : static int init_tiles(Jpeg2000EncoderContext *s)
     404             : {
     405             :     int tileno, tilex, tiley, compno;
     406           8 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     407           8 :     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
     408             : 
     409           8 :     s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
     410           8 :     s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
     411             : 
     412           8 :     s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
     413           8 :     if (!s->tile)
     414           0 :         return AVERROR(ENOMEM);
     415          22 :     for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
     416          40 :         for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
     417          26 :             Jpeg2000Tile *tile = s->tile + tileno;
     418             : 
     419          26 :             tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
     420          26 :             if (!tile->comp)
     421           0 :                 return AVERROR(ENOMEM);
     422         104 :             for (compno = 0; compno < s->ncomponents; compno++){
     423          78 :                 Jpeg2000Component *comp = tile->comp + compno;
     424             :                 int ret, i, j;
     425             : 
     426          78 :                 comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
     427          78 :                 comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
     428          78 :                 comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
     429          78 :                 comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
     430          78 :                 if (compno > 0)
     431         156 :                     for (i = 0; i < 2; i++)
     432         312 :                         for (j = 0; j < 2; j++)
     433         208 :                             comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
     434             : 
     435         260 :                 if ((ret = ff_jpeg2000_init_component(comp,
     436             :                                                 codsty,
     437             :                                                 qntsty,
     438          78 :                                                 s->cbps[compno],
     439          52 :                                                 compno?1<<s->chroma_shift[0]:1,
     440          52 :                                                 compno?1<<s->chroma_shift[1]:1,
     441             :                                                 s->avctx
     442             :                                                )) < 0)
     443           0 :                     return ret;
     444             :             }
     445             :         }
     446           8 :     return 0;
     447             : }
     448             : 
     449         400 : static void copy_frame(Jpeg2000EncoderContext *s)
     450             : {
     451             :     int tileno, compno, i, y, x;
     452             :     uint8_t *line;
     453        1700 :     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
     454        1300 :         Jpeg2000Tile *tile = s->tile + tileno;
     455        1300 :         if (s->planar){
     456           0 :             for (compno = 0; compno < s->ncomponents; compno++){
     457           0 :                 Jpeg2000Component *comp = tile->comp + compno;
     458           0 :                 int *dst = comp->i_data;
     459           0 :                 line = s->picture->data[compno]
     460           0 :                        + comp->coord[1][0] * s->picture->linesize[compno]
     461           0 :                        + comp->coord[0][0];
     462           0 :                 for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
     463           0 :                     uint8_t *ptr = line;
     464           0 :                     for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
     465           0 :                         *dst++ = *ptr++ - (1 << 7);
     466           0 :                     line += s->picture->linesize[compno];
     467             :                 }
     468             :             }
     469             :         } else{
     470        2600 :             line = s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0]
     471        1300 :                    + tile->comp[0].coord[0][0] * s->ncomponents;
     472             : 
     473        1300 :             i = 0;
     474      177500 :             for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
     475      176200 :                 uint8_t *ptr = line;
     476    30704600 :                 for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
     477   122113600 :                     for (compno = 0; compno < s->ncomponents; compno++){
     478    91585200 :                         tile->comp[compno].i_data[i] = *ptr++  - (1 << 7);
     479             :                     }
     480             :                 }
     481      176200 :                 line += s->picture->linesize[0];
     482             :             }
     483             :         }
     484             :     }
     485         400 : }
     486             : 
     487           8 : static void init_quantization(Jpeg2000EncoderContext *s)
     488             : {
     489             :     int compno, reslevelno, bandno;
     490           8 :     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
     491           8 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     492             : 
     493          32 :     for (compno = 0; compno < s->ncomponents; compno++){
     494          24 :         int gbandno = 0;
     495         192 :         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
     496         168 :             int nbands, lev = codsty->nreslevels - reslevelno - 1;
     497         168 :             nbands = reslevelno ? 3 : 1;
     498         624 :             for (bandno = 0; bandno < nbands; bandno++, gbandno++){
     499         456 :                 int expn, mant = 0;
     500             : 
     501         456 :                 if (codsty->transform == FF_DWT97_INT){
     502         228 :                     int bandpos = bandno + (reslevelno>0),
     503         228 :                         ss = 81920000 / dwt_norms[0][bandpos][lev],
     504         228 :                         log = av_log2(ss);
     505         228 :                     mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
     506         228 :                     expn = s->cbps[compno] - log + 13;
     507             :                 } else
     508         228 :                     expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
     509             : 
     510         456 :                 qntsty->expn[gbandno] = expn;
     511         456 :                 qntsty->mant[gbandno] = mant;
     512             :             }
     513             :         }
     514             :     }
     515           8 : }
     516             : 
     517           8 : static void init_luts(void)
     518             : {
     519             :     int i, a,
     520           8 :         mask = ~((1<<NMSEDEC_FRACBITS)-1);
     521             : 
     522        1032 :     for (i = 0; i < (1 << NMSEDEC_BITS); i++){
     523        1024 :         lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
     524        1024 :         lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
     525             : 
     526        1024 :         a = (i >> (NMSEDEC_BITS-2)&2) + 1;
     527        1024 :         lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
     528             :                                     << 13-NMSEDEC_FRACBITS, 0);
     529        1024 :         lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
     530             :                                     << 1, 0);
     531             :     }
     532           8 : }
     533             : 
     534             : /* tier-1 routines */
     535    73779107 : static int getnmsedec_sig(int x, int bpno)
     536             : {
     537    73779107 :     if (bpno > NMSEDEC_FRACBITS)
     538    57508511 :         return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
     539    16270596 :     return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
     540             : }
     541             : 
     542   155371831 : static int getnmsedec_ref(int x, int bpno)
     543             : {
     544   155371831 :     if (bpno > NMSEDEC_FRACBITS)
     545    97863320 :         return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
     546    57508511 :     return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
     547             : }
     548             : 
     549     2341659 : static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
     550             : {
     551     2341659 :     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
     552    10642563 :     for (y0 = 0; y0 < height; y0 += 4)
     553   133682311 :         for (x = 0; x < width; x++)
     554   624667412 :             for (y = y0; y < height && y < y0+4; y++){
     555   499286005 :                 if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
     556   163633824 :                     int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
     557   163633824 :                         bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
     558   163633824 :                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
     559   163633824 :                     if (bit){
     560             :                         int xorbit;
     561    59386202 :                         int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
     562    59386202 :                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
     563    59386202 :                         *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
     564    59386202 :                         ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
     565             :                     }
     566   163633824 :                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
     567             :                 }
     568             :             }
     569     2341659 : }
     570             : 
     571     2341659 : static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
     572             : {
     573     2341659 :     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
     574    10642563 :     for (y0 = 0; y0 < height; y0 += 4)
     575   133682311 :         for (x = 0; x < width; x++)
     576   624667412 :             for (y = y0; y < height && y < y0+4; y++)
     577   499286005 :                 if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
     578   155371831 :                     int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
     579   155371831 :                     *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
     580   155371831 :                     ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
     581   155371831 :                     t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
     582             :                 }
     583     2341659 : }
     584             : 
     585     2755058 : static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
     586             : {
     587     2755058 :     int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
     588    12558961 :     for (y0 = 0; y0 < height; y0 += 4)
     589   158157809 :         for (x = 0; x < width; x++){
     590   343987230 :             if (y0 + 3 < height && !(
     591   205201223 :             (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
     592   110521932 :             (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
     593    52649523 :             (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
     594    48304510 :             (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
     595     3619464 :             {
     596             :                 // aggregation mode
     597             :                 int rlen;
     598   221843104 :                 for (rlen = 0; rlen < 4; rlen++)
     599   179323436 :                     if (t1->data[(y0+rlen) * t1->stride + x] & mask)
     600     3619464 :                         break;
     601    46139132 :                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
     602    46139132 :                 if (rlen == 4)
     603    42519668 :                     continue;
     604     3619464 :                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
     605     3619464 :                 ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
     606    12472020 :                 for (y = y0 + rlen; y < y0 + 4; y++){
     607     8852556 :                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
     608     8852556 :                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
     609     8852556 :                         if (y > y0 + rlen)
     610     5233092 :                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
     611     8852556 :                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
     612             :                             int xorbit;
     613     4325058 :                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
     614     4325058 :                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
     615     4325058 :                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
     616     4325058 :                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
     617             :                         }
     618             :                     }
     619     8852556 :                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
     620             :                 }
     621             :             } else{
     622   508529450 :                 for (y = y0; y < y0 + 4 && y < height; y++){
     623   406314676 :                     if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
     624    87309021 :                         int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
     625    87309021 :                         ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
     626    87309021 :                         if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
     627             :                             int xorbit;
     628    10067847 :                             int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
     629    10067847 :                             *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
     630    10067847 :                             ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
     631    10067847 :                             ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
     632             :                         }
     633             :                     }
     634   406314676 :                     t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
     635             :                 }
     636             :             }
     637             :         }
     638     2755058 : }
     639             : 
     640      413400 : static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
     641             :                         int width, int height, int bandpos, int lev)
     642             : {
     643      413400 :     int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
     644      413400 :     int64_t wmsedec = 0;
     645             : 
     646      413400 :     memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
     647             : 
     648     6372900 :     for (y = 0; y < height; y++){
     649    97544700 :         for (x = 0; x < width; x++){
     650    91585200 :             if (t1->data[(y) * t1->stride + x] < 0){
     651    35748311 :                 t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
     652    35748311 :                 t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
     653             :             }
     654    91585200 :             max = FFMAX(max, t1->data[(y) * t1->stride + x]);
     655             :         }
     656             :     }
     657             : 
     658      413400 :     if (max == 0){
     659          51 :         cblk->nonzerobits = 0;
     660          51 :         bpno = 0;
     661             :     } else{
     662      413349 :         cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
     663      413349 :         bpno = cblk->nonzerobits - 1;
     664             :     }
     665             : 
     666      413400 :     cblk->data[0] = 0;
     667      413400 :     ff_mqc_initenc(&t1->mqc, cblk->data + 1);
     668             : 
     669     7851776 :     for (passno = 0; bpno >= 0; passno++){
     670     7438376 :         nmsedec=0;
     671             : 
     672     7438376 :         switch(pass_t){
     673     2341659 :             case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
     674     2341659 :                     break;
     675     2341659 :             case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
     676     2341659 :                     break;
     677     2755058 :             case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
     678     2755058 :                     break;
     679             :         }
     680             : 
     681     7438376 :         cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
     682     7438376 :         wmsedec += (int64_t)nmsedec << (2*bpno);
     683     7438376 :         cblk->passes[passno].disto = wmsedec;
     684             : 
     685     7438376 :         if (++pass_t == 3){
     686     2755058 :             pass_t = 0;
     687     2755058 :             bpno--;
     688             :         }
     689             :     }
     690      413400 :     cblk->npasses = passno;
     691      413400 :     cblk->ninclpasses = passno;
     692             : 
     693      413400 :     if (passno)
     694      413399 :         cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
     695      413400 : }
     696             : 
     697             : /* tier-2 routines: */
     698             : 
     699      345769 : static void putnumpasses(Jpeg2000EncoderContext *s, int n)
     700             : {
     701      345769 :     if (n == 1)
     702       19966 :         put_num(s, 0, 1);
     703      325803 :     else if (n == 2)
     704       12191 :         put_num(s, 2, 2);
     705      313612 :     else if (n <= 5)
     706      103883 :         put_num(s, 0xc | (n-3), 4);
     707      209729 :     else if (n <= 36)
     708      209726 :         put_num(s, 0x1e0 | (n-6), 9);
     709             :     else
     710           3 :         put_num(s, 0xff80 | (n-37), 16);
     711      345769 : }
     712             : 
     713             : 
     714       27300 : static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
     715             :                           uint8_t *expn, int numgbits)
     716             : {
     717       27300 :     int bandno, empty = 1;
     718             : 
     719             :     // init bitstream
     720       27300 :     *s->buf = 0;
     721       27300 :     s->bit_index = 0;
     722             : 
     723             :     // header
     724             : 
     725             :     // is the packet empty?
     726       27300 :     for (bandno = 0; bandno < rlevel->nbands; bandno++){
     727       27300 :         if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
     728       27300 :         &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
     729       27300 :             empty = 0;
     730       27300 :             break;
     731             :         }
     732             :     }
     733             : 
     734       27300 :     put_bits(s, !empty, 1);
     735       27300 :     if (empty){
     736           0 :         j2k_flush(s);
     737           0 :         return 0;
     738             :     }
     739             : 
     740      101400 :     for (bandno = 0; bandno < rlevel->nbands; bandno++){
     741       74100 :         Jpeg2000Band *band = rlevel->band + bandno;
     742       74100 :         Jpeg2000Prec *prec = band->prec + precno;
     743             :         int yi, xi, pos;
     744       74100 :         int cblknw = prec->nb_codeblocks_width;
     745             : 
     746       74100 :         if (band->coord[0][0] == band->coord[0][1]
     747       74100 :         ||  band->coord[1][0] == band->coord[1][1])
     748        3600 :             continue;
     749             : 
     750      201300 :         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
     751      544200 :             for (xi = 0; xi < cblknw; xi++, pos++){
     752      413400 :                 prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
     753      413400 :                 tag_tree_update(prec->cblkincl + pos);
     754      413400 :                 prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
     755      413400 :                 tag_tree_update(prec->zerobits + pos);
     756             :             }
     757             :         }
     758             : 
     759      201300 :         for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
     760      544200 :             for (xi = 0; xi < cblknw; xi++, pos++){
     761      413400 :                 int pad = 0, llen, length;
     762      413400 :                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
     763             : 
     764      413400 :                 if (s->buf_end - s->buf < 20) // approximately
     765           0 :                     return -1;
     766             : 
     767             :                 // inclusion information
     768      413400 :                 tag_tree_code(s, prec->cblkincl + pos, 1);
     769      413400 :                 if (!cblk->ninclpasses)
     770       67631 :                     continue;
     771             :                 // zerobits information
     772      345769 :                 tag_tree_code(s, prec->zerobits + pos, 100);
     773             :                 // number of passes
     774      345769 :                 putnumpasses(s, cblk->ninclpasses);
     775             : 
     776      345769 :                 length = cblk->passes[cblk->ninclpasses-1].rate;
     777      345769 :                 llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
     778      345769 :                 if (llen < 0){
     779       98010 :                     pad = -llen;
     780       98010 :                     llen = 0;
     781             :                 }
     782             :                 // length of code block
     783      345769 :                 put_bits(s, 1, llen);
     784      345769 :                 put_bits(s, 0, 1);
     785      345769 :                 put_num(s, length, av_log2(length)+1+pad);
     786             :             }
     787             :         }
     788             :     }
     789       27300 :     j2k_flush(s);
     790      101400 :     for (bandno = 0; bandno < rlevel->nbands; bandno++){
     791       74100 :         Jpeg2000Band *band = rlevel->band + bandno;
     792       74100 :         Jpeg2000Prec *prec = band->prec + precno;
     793       74100 :         int yi, cblknw = prec->nb_codeblocks_width;
     794      208500 :         for (yi =0; yi < prec->nb_codeblocks_height; yi++){
     795             :             int xi;
     796      551400 :             for (xi = 0; xi < cblknw; xi++){
     797      417000 :                 Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
     798      417000 :                 if (cblk->ninclpasses){
     799      345769 :                     if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
     800           0 :                         return -1;
     801      691538 :                     bytestream_put_buffer(&s->buf, cblk->data + 1,   cblk->passes[cblk->ninclpasses-1].rate
     802      345769 :                                                                - cblk->passes[cblk->ninclpasses-1].flushed_len);
     803      345769 :                     bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
     804      345769 :                                                    cblk->passes[cblk->ninclpasses-1].flushed_len);
     805             :                 }
     806             :             }
     807             :         }
     808             :     }
     809       27300 :     return 0;
     810             : }
     811             : 
     812        1300 : static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
     813             : {
     814             :     int compno, reslevelno, ret;
     815        1300 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     816        1300 :     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
     817             : 
     818        1300 :     av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
     819             :     // lay-rlevel-comp-pos progression
     820       10400 :     for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
     821       36400 :         for (compno = 0; compno < s->ncomponents; compno++){
     822             :             int precno;
     823       27300 :             Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
     824       54600 :             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
     825       27300 :                 if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
     826       27300 :                               qntsty->nguardbits)) < 0)
     827           0 :                     return ret;
     828             :             }
     829             :         }
     830             :     }
     831        1300 :     av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
     832        1300 :     return 0;
     833             : }
     834             : 
     835      417000 : static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
     836             : {
     837      417000 :     int passno, res = 0;
     838     7855376 :     for (passno = 0; passno < cblk->npasses; passno++){
     839             :         int dr;
     840             :         int64_t dd;
     841             : 
     842    14876752 :         dr = cblk->passes[passno].rate
     843     7438376 :            - (res ? cblk->passes[res-1].rate:0);
     844    14876752 :         dd = cblk->passes[passno].disto
     845     7438376 :            - (res ? cblk->passes[res-1].disto:0);
     846             : 
     847     7438376 :         if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
     848     2504255 :             res = passno+1;
     849             :     }
     850      417000 :     return res;
     851             : }
     852             : 
     853        1300 : static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
     854             : {
     855             :     int precno, compno, reslevelno, bandno, cblkno, lev;
     856        1300 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     857             : 
     858        5200 :     for (compno = 0; compno < s->ncomponents; compno++){
     859        3900 :         Jpeg2000Component *comp = tile->comp + compno;
     860             : 
     861       31200 :         for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
     862       27300 :             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
     863             : 
     864       54600 :             for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
     865      101400 :                 for (bandno = 0; bandno < reslevel->nbands ; bandno++){
     866       74100 :                     int bandpos = bandno + (reslevelno > 0);
     867       74100 :                     Jpeg2000Band *band = reslevel->band + bandno;
     868       74100 :                     Jpeg2000Prec *prec = band->prec + precno;
     869             : 
     870      491100 :                     for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
     871      417000 :                         Jpeg2000Cblk *cblk = prec->cblk + cblkno;
     872             : 
     873      417000 :                         cblk->ninclpasses = getcut(cblk, s->lambda,
     874      417000 :                                 (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
     875             :                     }
     876             :                 }
     877             :             }
     878             :         }
     879             :     }
     880        1300 : }
     881             : 
     882        1300 : static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
     883             : {
     884             :     int compno, reslevelno, bandno, ret;
     885             :     Jpeg2000T1Context t1;
     886        1300 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     887        5200 :     for (compno = 0; compno < s->ncomponents; compno++){
     888        3900 :         Jpeg2000Component *comp = s->tile[tileno].comp + compno;
     889             : 
     890        3900 :         t1.stride = (1<<codsty->log2_cblk_width) + 2;
     891             : 
     892        3900 :         av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
     893        3900 :         if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
     894           0 :             return ret;
     895        3900 :         av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
     896             : 
     897       31200 :         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
     898       27300 :             Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
     899             : 
     900      101400 :             for (bandno = 0; bandno < reslevel->nbands ; bandno++){
     901       74100 :                 Jpeg2000Band *band = reslevel->band + bandno;
     902       74100 :                 Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
     903       74100 :                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
     904       74100 :                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
     905       74100 :                 y0 = yy0;
     906      148200 :                 yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
     907       74100 :                             band->coord[1][1]) - band->coord[1][0] + yy0;
     908             : 
     909       74100 :                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
     910        3600 :                     continue;
     911             : 
     912       70500 :                 bandpos = bandno + (reslevelno > 0);
     913             : 
     914      201300 :                 for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
     915      130800 :                     if (reslevelno == 0 || bandno == 1)
     916       45600 :                         xx0 = 0;
     917             :                     else
     918       85200 :                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
     919      130800 :                     x0 = xx0;
     920      261600 :                     xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
     921      130800 :                                 band->coord[0][1]) - band->coord[0][0] + xx0;
     922             : 
     923      544200 :                     for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
     924             :                         int y, x;
     925      413400 :                         if (codsty->transform == FF_DWT53){
     926     3186450 :                             for (y = yy0; y < yy1; y++){
     927     2979750 :                                 int *ptr = t1.data + (y-yy0)*t1.stride;
     928    48772350 :                                 for (x = xx0; x < xx1; x++){
     929    45792600 :                                     *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
     930             :                                 }
     931             :                             }
     932             :                         } else{
     933     3186450 :                             for (y = yy0; y < yy1; y++){
     934     2979750 :                                 int *ptr = t1.data + (y-yy0)*t1.stride;
     935    48772350 :                                 for (x = xx0; x < xx1; x++){
     936    45792600 :                                     *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
     937    45792600 :                                     *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
     938    45792600 :                                     ptr++;
     939             :                                 }
     940             :                             }
     941             :                         }
     942      413400 :                         if (!prec->cblk[cblkno].data)
     943        8268 :                             prec->cblk[cblkno].data = av_malloc(1 + 8192);
     944      413400 :                         if (!prec->cblk[cblkno].passes)
     945        8268 :                             prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
     946      413400 :                         if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
     947           0 :                             return AVERROR(ENOMEM);
     948      413400 :                         encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
     949      413400 :                                     bandpos, codsty->nreslevels - reslevelno - 1);
     950      413400 :                         xx0 = xx1;
     951      413400 :                         xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
     952             :                     }
     953      130800 :                     yy0 = yy1;
     954      130800 :                     yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
     955             :                 }
     956             :             }
     957             :         }
     958        3900 :         av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
     959             :     }
     960             : 
     961        1300 :     av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
     962        1300 :     truncpasses(s, tile);
     963        1300 :     if ((ret = encode_packets(s, tile, tileno)) < 0)
     964           0 :         return ret;
     965        1300 :     av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
     966        1300 :     return 0;
     967             : }
     968             : 
     969           8 : static void cleanup(Jpeg2000EncoderContext *s)
     970             : {
     971             :     int tileno, compno;
     972           8 :     Jpeg2000CodingStyle *codsty = &s->codsty;
     973             : 
     974          34 :     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
     975         104 :         for (compno = 0; compno < s->ncomponents; compno++){
     976          78 :             Jpeg2000Component *comp = s->tile[tileno].comp + compno;
     977          78 :             ff_jpeg2000_cleanup(comp, codsty);
     978             :         }
     979          26 :         av_freep(&s->tile[tileno].comp);
     980             :     }
     981           8 :     av_freep(&s->tile);
     982           8 : }
     983             : 
     984         400 : static void reinit(Jpeg2000EncoderContext *s)
     985             : {
     986             :     int tileno, compno;
     987        1700 :     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
     988        1300 :         Jpeg2000Tile *tile = s->tile + tileno;
     989        5200 :         for (compno = 0; compno < s->ncomponents; compno++)
     990        3900 :             ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
     991             :     }
     992         400 : }
     993             : 
     994        2000 : static void update_size(uint8_t *size, const uint8_t *end)
     995             : {
     996        2000 :     AV_WB32(size, end-size);
     997        2000 : }
     998             : 
     999         400 : static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
    1000             :                         const AVFrame *pict, int *got_packet)
    1001             : {
    1002             :     int tileno, ret;
    1003         400 :     Jpeg2000EncoderContext *s = avctx->priv_data;
    1004             :     uint8_t *chunkstart, *jp2cstart, *jp2hstart;
    1005             : 
    1006         400 :     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
    1007           0 :         return ret;
    1008             : 
    1009             :     // init:
    1010         400 :     s->buf = s->buf_start = pkt->data;
    1011         400 :     s->buf_end = pkt->data + pkt->size;
    1012             : 
    1013         400 :     s->picture = pict;
    1014             : 
    1015         400 :     s->lambda = s->picture->quality * LAMBDA_SCALE;
    1016             : 
    1017         400 :     copy_frame(s);
    1018         400 :     reinit(s);
    1019             : 
    1020         400 :     if (s->format == CODEC_JP2) {
    1021         400 :         av_assert0(s->buf == pkt->data);
    1022             : 
    1023         400 :         bytestream_put_be32(&s->buf, 0x0000000C);
    1024         400 :         bytestream_put_be32(&s->buf, 0x6A502020);
    1025         400 :         bytestream_put_be32(&s->buf, 0x0D0A870A);
    1026             : 
    1027         400 :         chunkstart = s->buf;
    1028         400 :         bytestream_put_be32(&s->buf, 0);
    1029         400 :         bytestream_put_buffer(&s->buf, "ftyp", 4);
    1030         400 :         bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
    1031         400 :         bytestream_put_be32(&s->buf, 0);
    1032         400 :         bytestream_put_buffer(&s->buf, "jp2\040", 4);
    1033         400 :         update_size(chunkstart, s->buf);
    1034             : 
    1035         400 :         jp2hstart = s->buf;
    1036         400 :         bytestream_put_be32(&s->buf, 0);
    1037         400 :         bytestream_put_buffer(&s->buf, "jp2h", 4);
    1038             : 
    1039         400 :         chunkstart = s->buf;
    1040         400 :         bytestream_put_be32(&s->buf, 0);
    1041         400 :         bytestream_put_buffer(&s->buf, "ihdr", 4);
    1042         400 :         bytestream_put_be32(&s->buf, avctx->height);
    1043         400 :         bytestream_put_be32(&s->buf, avctx->width);
    1044         400 :         bytestream_put_be16(&s->buf, s->ncomponents);
    1045         400 :         bytestream_put_byte(&s->buf, s->cbps[0]);
    1046         400 :         bytestream_put_byte(&s->buf, 7);
    1047         400 :         bytestream_put_byte(&s->buf, 0);
    1048         400 :         bytestream_put_byte(&s->buf, 0);
    1049         400 :         update_size(chunkstart, s->buf);
    1050             : 
    1051         400 :         chunkstart = s->buf;
    1052         400 :         bytestream_put_be32(&s->buf, 0);
    1053         400 :         bytestream_put_buffer(&s->buf, "colr", 4);
    1054         400 :         bytestream_put_byte(&s->buf, 1);
    1055         400 :         bytestream_put_byte(&s->buf, 0);
    1056         400 :         bytestream_put_byte(&s->buf, 0);
    1057         400 :         if (s->ncomponents == 1) {
    1058           0 :             bytestream_put_be32(&s->buf, 17);
    1059         400 :         } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
    1060         400 :             bytestream_put_be32(&s->buf, 16);
    1061             :         } else {
    1062           0 :             bytestream_put_be32(&s->buf, 18);
    1063             :         }
    1064         400 :         update_size(chunkstart, s->buf);
    1065         400 :         update_size(jp2hstart, s->buf);
    1066             : 
    1067         400 :         jp2cstart = s->buf;
    1068         400 :         bytestream_put_be32(&s->buf, 0);
    1069         400 :         bytestream_put_buffer(&s->buf, "jp2c", 4);
    1070             :     }
    1071             : 
    1072         400 :     if (s->buf_end - s->buf < 2)
    1073           0 :         return -1;
    1074         400 :     bytestream_put_be16(&s->buf, JPEG2000_SOC);
    1075         400 :     if ((ret = put_siz(s)) < 0)
    1076           0 :         return ret;
    1077         400 :     if ((ret = put_cod(s)) < 0)
    1078           0 :         return ret;
    1079         400 :     if ((ret = put_qcd(s, 0)) < 0)
    1080           0 :         return ret;
    1081         400 :     if ((ret = put_com(s, 0)) < 0)
    1082           0 :         return ret;
    1083             : 
    1084        3400 :     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
    1085             :         uint8_t *psotptr;
    1086        1300 :         if (!(psotptr = put_sot(s, tileno)))
    1087           0 :             return -1;
    1088        1300 :         if (s->buf_end - s->buf < 2)
    1089           0 :             return -1;
    1090        1300 :         bytestream_put_be16(&s->buf, JPEG2000_SOD);
    1091        1300 :         if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
    1092           0 :             return ret;
    1093        1300 :         bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
    1094             :     }
    1095         400 :     if (s->buf_end - s->buf < 2)
    1096           0 :         return -1;
    1097         400 :     bytestream_put_be16(&s->buf, JPEG2000_EOC);
    1098             : 
    1099         400 :     if (s->format == CODEC_JP2)
    1100         400 :         update_size(jp2cstart, s->buf);
    1101             : 
    1102         400 :     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
    1103         400 :     pkt->size = s->buf - s->buf_start;
    1104         400 :     pkt->flags |= AV_PKT_FLAG_KEY;
    1105         400 :     *got_packet = 1;
    1106             : 
    1107         400 :     return 0;
    1108             : }
    1109             : 
    1110           8 : static av_cold int j2kenc_init(AVCodecContext *avctx)
    1111             : {
    1112             :     int i, ret;
    1113           8 :     Jpeg2000EncoderContext *s = avctx->priv_data;
    1114           8 :     Jpeg2000CodingStyle *codsty = &s->codsty;
    1115           8 :     Jpeg2000QuantStyle  *qntsty = &s->qntsty;
    1116             : 
    1117           8 :     s->avctx = avctx;
    1118           8 :     av_log(s->avctx, AV_LOG_DEBUG, "init\n");
    1119             : 
    1120             : #if FF_API_PRIVATE_OPT
    1121             : FF_DISABLE_DEPRECATION_WARNINGS
    1122           8 :     if (avctx->prediction_method)
    1123           0 :         s->pred = avctx->prediction_method;
    1124             : FF_ENABLE_DEPRECATION_WARNINGS
    1125             : #endif
    1126             : 
    1127             :     // defaults:
    1128             :     // TODO: implement setting non-standard precinct size
    1129           8 :     memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
    1130           8 :     memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
    1131           8 :     codsty->nreslevels2decode=
    1132           8 :     codsty->nreslevels       = 7;
    1133           8 :     codsty->log2_cblk_width  = 4;
    1134           8 :     codsty->log2_cblk_height = 4;
    1135           8 :     codsty->transform        = s->pred ? FF_DWT53 : FF_DWT97_INT;
    1136             : 
    1137           8 :     qntsty->nguardbits       = 1;
    1138             : 
    1139          16 :     if ((s->tile_width  & (s->tile_width -1)) ||
    1140           8 :         (s->tile_height & (s->tile_height-1))) {
    1141           0 :         av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
    1142             :     }
    1143             : 
    1144           8 :     if (codsty->transform == FF_DWT53)
    1145           4 :         qntsty->quantsty = JPEG2000_QSTY_NONE;
    1146             :     else
    1147           4 :         qntsty->quantsty = JPEG2000_QSTY_SE;
    1148             : 
    1149           8 :     s->width = avctx->width;
    1150           8 :     s->height = avctx->height;
    1151             : 
    1152          32 :     for (i = 0; i < 3; i++)
    1153          24 :         s->cbps[i] = 8;
    1154             : 
    1155           8 :     if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
    1156           8 :         s->ncomponents = 3;
    1157           0 :     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8){
    1158           0 :         s->ncomponents = 1;
    1159             :     } else{ // planar YUV
    1160           0 :         s->planar = 1;
    1161           0 :         s->ncomponents = 3;
    1162           0 :         ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
    1163           0 :                                                s->chroma_shift, s->chroma_shift + 1);
    1164           0 :         if (ret)
    1165           0 :             return ret;
    1166             :     }
    1167             : 
    1168           8 :     ff_jpeg2000_init_tier1_luts();
    1169           8 :     ff_mqc_init_context_tables();
    1170           8 :     init_luts();
    1171             : 
    1172           8 :     init_quantization(s);
    1173           8 :     if ((ret=init_tiles(s)) < 0)
    1174           0 :         return ret;
    1175             : 
    1176           8 :     av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
    1177             : 
    1178           8 :     return 0;
    1179             : }
    1180             : 
    1181           8 : static int j2kenc_destroy(AVCodecContext *avctx)
    1182             : {
    1183           8 :     Jpeg2000EncoderContext *s = avctx->priv_data;
    1184             : 
    1185           8 :     cleanup(s);
    1186           8 :     return 0;
    1187             : }
    1188             : 
    1189             : // taken from the libopenjpeg wraper so it matches
    1190             : 
    1191             : #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
    1192             : #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
    1193             : static const AVOption options[] = {
    1194             :     { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
    1195             :     { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
    1196             :     { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
    1197             :     { "tile_width",    "Tile Width",        OFFSET(tile_width),    AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
    1198             :     { "tile_height",   "Tile Height",       OFFSET(tile_height),   AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
    1199             :     { "pred",          "DWT Type",          OFFSET(pred),          AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, "pred"        },
    1200             :     { "dwt97int",      NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
    1201             :     { "dwt53",         NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
    1202             : 
    1203             :     { NULL }
    1204             : };
    1205             : 
    1206             : static const AVClass j2k_class = {
    1207             :     .class_name = "jpeg 2000 encoder",
    1208             :     .item_name  = av_default_item_name,
    1209             :     .option     = options,
    1210             :     .version    = LIBAVUTIL_VERSION_INT,
    1211             : };
    1212             : 
    1213             : AVCodec ff_jpeg2000_encoder = {
    1214             :     .name           = "jpeg2000",
    1215             :     .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
    1216             :     .type           = AVMEDIA_TYPE_VIDEO,
    1217             :     .id             = AV_CODEC_ID_JPEG2000,
    1218             :     .priv_data_size = sizeof(Jpeg2000EncoderContext),
    1219             :     .init           = j2kenc_init,
    1220             :     .encode2        = encode_frame,
    1221             :     .close          = j2kenc_destroy,
    1222             :     .pix_fmts       = (const enum AVPixelFormat[]) {
    1223             :         AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
    1224             :         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
    1225             :         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
    1226             :         AV_PIX_FMT_NONE
    1227             :     },
    1228             :     .priv_class     = &j2k_class,
    1229             : };

Generated by: LCOV version 1.13