Coverage Report

Created: 2025-08-28 07:12

/src/ffmpeg/libavcodec/j2kenc.c
Line
Count
Source (jump to first uncovered line)
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
 * Copyright (c) 2020, Gautam Ramakrishnan <gautamramk@gmail.com>
36
 * All rights reserved.
37
 *
38
 * Redistribution and use in source and binary forms, with or without
39
 * modification, are permitted provided that the following conditions
40
 * are met:
41
 * 1. Redistributions of source code must retain the above copyright
42
 *    notice, this list of conditions and the following disclaimer.
43
 * 2. Redistributions in binary form must reproduce the above copyright
44
 *    notice, this list of conditions and the following disclaimer in the
45
 *    documentation and/or other materials provided with the distribution.
46
 *
47
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
48
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
51
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
52
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
53
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
54
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
55
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
56
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
57
 * POSSIBILITY OF SUCH DAMAGE.
58
 */
59
60
61
/**
62
 * JPEG2000 image encoder
63
 * @file
64
 * @author Kamil Nowosad
65
 */
66
67
#include <float.h>
68
#include "avcodec.h"
69
#include "codec_internal.h"
70
#include "encode.h"
71
#include "bytestream.h"
72
#include "jpeg2000.h"
73
#include "version.h"
74
#include "libavutil/common.h"
75
#include "libavutil/mem.h"
76
#include "libavutil/pixdesc.h"
77
#include "libavutil/opt.h"
78
#include "libavutil/intreadwrite.h"
79
#include "libavutil/avstring.h"
80
#include "libavutil/thread.h"
81
82
952M
#define NMSEDEC_BITS 7
83
735M
#define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
84
1.84M
#define WMSEDEC_SHIFT 13 ///< must be >= 13
85
7.97k
#define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
86
87
16.0k
#define CODEC_JP2 1
88
#define CODEC_J2K 0
89
90
static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
91
           lut_nmsedec_ref0[1<<NMSEDEC_BITS],
92
           lut_nmsedec_sig [1<<NMSEDEC_BITS],
93
           lut_nmsedec_sig0[1<<NMSEDEC_BITS];
94
95
static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
96
    {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
97
     {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
98
     {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
99
     {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
100
101
    {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
102
     {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
103
     {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
104
     { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
105
};
106
107
typedef struct {
108
   Jpeg2000Component *comp;
109
   double *layer_rates;
110
} Jpeg2000Tile;
111
112
typedef struct {
113
    AVClass *class;
114
    AVCodecContext *avctx;
115
    const AVFrame *picture;
116
117
    int width, height; ///< image width and height
118
    uint8_t cbps[4]; ///< bits per sample in particular components
119
    uint8_t comp_remap[4];
120
    int chroma_shift[2];
121
    uint8_t planar;
122
    int ncomponents;
123
    int tile_width, tile_height; ///< tile size
124
    int numXtiles, numYtiles;
125
126
    uint8_t *buf_start;
127
    uint8_t *buf;
128
    uint8_t *buf_end;
129
    int bit_index;
130
131
    uint64_t lambda;
132
133
    Jpeg2000CodingStyle codsty;
134
    Jpeg2000QuantStyle  qntsty;
135
136
    Jpeg2000Tile *tile;
137
    int layer_rates[100];
138
    uint8_t compression_rate_enc; ///< Is compression done using compression ratio?
139
140
    int format;
141
    int pred;
142
    int sop;
143
    int eph;
144
    int prog;
145
    int nlayers;
146
    char *lr_str;
147
} Jpeg2000EncoderContext;
148
149
150
/* debug */
151
#if 0
152
#undef ifprintf
153
#undef printf
154
155
static void nspaces(FILE *fd, int n)
156
{
157
    while(n--) putc(' ', fd);
158
}
159
160
static void printcomp(Jpeg2000Component *comp)
161
{
162
    int i;
163
    for (i = 0; i < comp->y1 - comp->y0; i++)
164
        ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
165
}
166
167
static void dump(Jpeg2000EncoderContext *s, FILE *fd)
168
{
169
    int tileno, compno, reslevelno, bandno, precno;
170
    fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
171
                "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
172
                "tiles:\n",
173
            s->width, s->height, s->tile_width, s->tile_height,
174
            s->numXtiles, s->numYtiles, s->ncomponents);
175
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
176
        Jpeg2000Tile *tile = s->tile + tileno;
177
        nspaces(fd, 2);
178
        fprintf(fd, "tile %d:\n", tileno);
179
        for(compno = 0; compno < s->ncomponents; compno++){
180
            Jpeg2000Component *comp = tile->comp + compno;
181
            nspaces(fd, 4);
182
            fprintf(fd, "component %d:\n", compno);
183
            nspaces(fd, 4);
184
            fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
185
                        comp->x0, comp->x1, comp->y0, comp->y1);
186
            for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
187
                Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
188
                nspaces(fd, 6);
189
                fprintf(fd, "reslevel %d:\n", reslevelno);
190
                nspaces(fd, 6);
191
                fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
192
                        reslevel->x0, reslevel->x1, reslevel->y0,
193
                        reslevel->y1, reslevel->nbands);
194
                for(bandno = 0; bandno < reslevel->nbands; bandno++){
195
                    Jpeg2000Band *band = reslevel->band + bandno;
196
                    nspaces(fd, 8);
197
                    fprintf(fd, "band %d:\n", bandno);
198
                    nspaces(fd, 8);
199
                    fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
200
                                "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
201
                                band->x0, band->x1,
202
                                band->y0, band->y1,
203
                                band->codeblock_width, band->codeblock_height,
204
                                band->cblknx, band->cblkny);
205
                    for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
206
                        Jpeg2000Prec *prec = band->prec + precno;
207
                        nspaces(fd, 10);
208
                        fprintf(fd, "prec %d:\n", precno);
209
                        nspaces(fd, 10);
210
                        fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
211
                                     prec->xi0, prec->xi1, prec->yi0, prec->yi1);
212
                    }
213
                }
214
            }
215
        }
216
    }
217
}
218
#endif
219
220
/* bitstream routines */
221
222
/** put n times val bit */
223
static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
224
39.6M
{
225
74.5M
    while (n-- > 0){
226
34.9M
        if (s->bit_index == 8)
227
4.11M
        {
228
4.11M
            s->bit_index = *s->buf == 0xff;
229
4.11M
            *(++s->buf) = 0;
230
4.11M
        }
231
34.9M
        *s->buf |= val << (7 - s->bit_index++);
232
34.9M
    }
233
39.6M
}
234
235
/** put n least significant bits of a number num */
236
static void put_num(Jpeg2000EncoderContext *s, int num, int n)
237
2.89M
{
238
24.9M
    while(--n >= 0)
239
22.0M
        put_bits(s, (num >> n) & 1, 1);
240
2.89M
}
241
242
/** flush the bitstream */
243
static void j2k_flush(Jpeg2000EncoderContext *s)
244
678k
{
245
678k
    if (s->bit_index){
246
678k
        s->bit_index = 0;
247
678k
        s->buf++;
248
678k
    }
249
678k
}
250
251
/* tag tree routines */
252
253
/** code the value stored in node */
254
static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
255
3.16M
{
256
3.16M
    Jpeg2000TgtNode *stack[30];
257
3.16M
    int sp = -1, curval = 0;
258
259
9.40M
    while(node->parent){
260
6.23M
        stack[++sp] = node;
261
6.23M
        node = node->parent;
262
6.23M
    }
263
264
9.40M
    while (1) {
265
9.40M
        if (curval > node->temp_val)
266
2.18M
            node->temp_val = curval;
267
7.21M
        else {
268
7.21M
            curval = node->temp_val;
269
7.21M
        }
270
271
9.40M
        if (node->val >= threshold) {
272
922k
            put_bits(s, 0, threshold - curval);
273
922k
            curval = threshold;
274
8.47M
        } else {
275
8.47M
            put_bits(s, 0, node->val - curval);
276
8.47M
            curval = node->val;
277
8.47M
            if (!node->vis) {
278
4.65M
                put_bits(s, 1, 1);
279
4.65M
                node->vis = 1;
280
4.65M
            }
281
8.47M
        }
282
283
9.40M
        node->temp_val = curval;
284
9.40M
        if (sp < 0)
285
3.16M
            break;
286
6.23M
        node = stack[sp--];
287
6.23M
    }
288
3.16M
}
289
290
/** update the value in node */
291
static void tag_tree_update(Jpeg2000TgtNode *node)
292
5.41M
{
293
9.03M
    while (node->parent){
294
7.19M
        if (node->parent->val <= node->val)
295
3.58M
            break;
296
3.61M
        node->parent->val = node->val;
297
3.61M
        node = node->parent;
298
3.61M
    }
299
5.41M
}
300
301
static int put_siz(Jpeg2000EncoderContext *s)
302
7.97k
{
303
7.97k
    int i;
304
305
7.97k
    if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
306
0
        return -1;
307
308
7.97k
    bytestream_put_be16(&s->buf, JPEG2000_SIZ);
309
7.97k
    bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
310
7.97k
    bytestream_put_be16(&s->buf, 0); // Rsiz
311
7.97k
    bytestream_put_be32(&s->buf, s->width); // width
312
7.97k
    bytestream_put_be32(&s->buf, s->height); // height
313
7.97k
    bytestream_put_be32(&s->buf, 0); // X0Siz
314
7.97k
    bytestream_put_be32(&s->buf, 0); // Y0Siz
315
316
7.97k
    bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
317
7.97k
    bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
318
7.97k
    bytestream_put_be32(&s->buf, 0); // XT0Siz
319
7.97k
    bytestream_put_be32(&s->buf, 0); // YT0Siz
320
7.97k
    bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
321
322
24.3k
    for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
323
16.4k
        bytestream_put_byte(&s->buf, s->cbps[i] - 1);
324
16.4k
        bytestream_put_byte(&s->buf, (i+1&2)?1<<s->chroma_shift[0]:1);
325
16.4k
        bytestream_put_byte(&s->buf, (i+1&2)?1<<s->chroma_shift[1]:1);
326
16.4k
    }
327
7.97k
    return 0;
328
7.97k
}
329
330
static int put_cod(Jpeg2000EncoderContext *s)
331
7.97k
{
332
7.97k
    Jpeg2000CodingStyle *codsty = &s->codsty;
333
7.97k
    uint8_t scod = 0;
334
335
7.97k
    if (s->buf_end - s->buf < 14)
336
0
        return -1;
337
338
7.97k
    bytestream_put_be16(&s->buf, JPEG2000_COD);
339
7.97k
    bytestream_put_be16(&s->buf, 12); // Lcod
340
7.97k
    if (s->sop)
341
0
        scod |= JPEG2000_CSTY_SOP;
342
7.97k
    if (s->eph)
343
0
        scod |= JPEG2000_CSTY_EPH;
344
7.97k
    bytestream_put_byte(&s->buf, scod);  // Scod
345
    // SGcod
346
7.97k
    bytestream_put_byte(&s->buf, s->prog); // progression level
347
7.97k
    bytestream_put_be16(&s->buf, s->nlayers); // num of layers
348
7.97k
    if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
349
2
        bytestream_put_byte(&s->buf, 0); // unspecified
350
7.97k
    }else{
351
7.97k
        bytestream_put_byte(&s->buf, 0); // unspecified
352
7.97k
    }
353
    // SPcod
354
7.97k
    bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
355
7.97k
    bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
356
7.97k
    bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
357
7.97k
    bytestream_put_byte(&s->buf, 0); // cblk style
358
7.97k
    bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
359
7.97k
    return 0;
360
7.97k
}
361
362
static int put_qcd(Jpeg2000EncoderContext *s, int compno)
363
7.97k
{
364
7.97k
    int i, size;
365
7.97k
    Jpeg2000CodingStyle *codsty = &s->codsty;
366
7.97k
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
367
368
7.97k
    if (qntsty->quantsty == JPEG2000_QSTY_NONE)
369
2.11k
        size = 4 + 3 * (codsty->nreslevels-1);
370
5.86k
    else // QSTY_SE
371
5.86k
        size = 5 + 6 * (codsty->nreslevels-1);
372
373
7.97k
    if (s->buf_end - s->buf < size + 2)
374
0
        return -1;
375
376
7.97k
    bytestream_put_be16(&s->buf, JPEG2000_QCD);
377
7.97k
    bytestream_put_be16(&s->buf, size);  // LQcd
378
7.97k
    bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
379
7.97k
    if (qntsty->quantsty == JPEG2000_QSTY_NONE)
380
42.3k
        for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
381
40.2k
            bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
382
5.86k
    else // QSTY_SE
383
117k
        for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
384
111k
            bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
385
7.97k
    return 0;
386
7.97k
}
387
388
static int put_com(Jpeg2000EncoderContext *s, int compno)
389
7.97k
{
390
7.97k
    int size = 4 + strlen(LIBAVCODEC_IDENT);
391
392
7.97k
    if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
393
0
        return 0;
394
395
7.97k
    if (s->buf_end - s->buf < size + 2)
396
0
        return -1;
397
398
7.97k
    bytestream_put_be16(&s->buf, JPEG2000_COM);
399
7.97k
    bytestream_put_be16(&s->buf, size);
400
7.97k
    bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
401
402
7.97k
    bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
403
404
7.97k
    return 0;
405
7.97k
}
406
407
static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
408
37.6k
{
409
37.6k
    uint8_t *psotptr;
410
411
37.6k
    if (s->buf_end - s->buf < 12)
412
3
        return NULL;
413
414
37.6k
    bytestream_put_be16(&s->buf, JPEG2000_SOT);
415
37.6k
    bytestream_put_be16(&s->buf, 10); // Lsot
416
37.6k
    bytestream_put_be16(&s->buf, tileno); // Isot
417
418
37.6k
    psotptr = s->buf;
419
37.6k
    bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
420
421
37.6k
    bytestream_put_byte(&s->buf, 0); // TPsot
422
37.6k
    bytestream_put_byte(&s->buf, 1); // TNsot
423
37.6k
    return psotptr;
424
37.6k
}
425
426
static void compute_rates(Jpeg2000EncoderContext* s)
427
570
{
428
570
    int i, j;
429
570
    int layno, compno;
430
12.4k
    for (i = 0; i < s->numYtiles; i++) {
431
42.1k
        for (j = 0; j < s->numXtiles; j++) {
432
30.2k
            Jpeg2000Tile *tile = &s->tile[s->numXtiles * i + j];
433
112k
            for (compno = 0; compno < s->ncomponents; compno++) {
434
82.0k
                int tilew = tile->comp[compno].coord[0][1] - tile->comp[compno].coord[0][0];
435
82.0k
                int tileh = tile->comp[compno].coord[1][1] - tile->comp[compno].coord[1][0];
436
82.0k
                int scale = ((compno+1&2)?1 << s->chroma_shift[0]:1) * ((compno+1&2)?1 << s->chroma_shift[1]:1);
437
164k
                for (layno = 0; layno < s->nlayers; layno++) {
438
82.0k
                    if (s->layer_rates[layno] > 0) {
439
0
                        tile->layer_rates[layno] += (double)(tilew * tileh) * s->ncomponents * s->cbps[compno] /
440
0
                                                    (double)(s->layer_rates[layno] * 8 * scale);
441
82.0k
                    } else {
442
82.0k
                        tile->layer_rates[layno] = 0.0;
443
82.0k
                    }
444
82.0k
                }
445
82.0k
            }
446
30.2k
        }
447
11.8k
    }
448
449
570
}
450
451
/**
452
 * compute the sizes of tiles, resolution levels, bands, etc.
453
 * allocate memory for them
454
 * divide the input image into tile-components
455
 */
456
static int init_tiles(Jpeg2000EncoderContext *s)
457
570
{
458
570
    int tileno, tilex, tiley, compno;
459
570
    Jpeg2000CodingStyle *codsty = &s->codsty;
460
570
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
461
462
570
    s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
463
570
    s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
464
465
570
    s->tile = av_calloc(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
466
570
    if (!s->tile)
467
0
        return AVERROR(ENOMEM);
468
12.4k
    for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
469
42.1k
        for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
470
30.2k
            Jpeg2000Tile *tile = s->tile + tileno;
471
472
30.2k
            tile->comp = av_calloc(s->ncomponents, sizeof(*tile->comp));
473
30.2k
            if (!tile->comp)
474
0
                return AVERROR(ENOMEM);
475
476
30.2k
            tile->layer_rates = av_calloc(s->nlayers, sizeof(*tile->layer_rates));
477
30.2k
            if (!tile->layer_rates)
478
0
                return AVERROR(ENOMEM);
479
480
112k
            for (compno = 0; compno < s->ncomponents; compno++){
481
82.0k
                Jpeg2000Component *comp = tile->comp + compno;
482
82.0k
                int ret, i, j;
483
484
82.0k
                comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
485
82.0k
                comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
486
82.0k
                comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
487
82.0k
                comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
488
82.0k
                if (compno + 1 & 2)
489
131k
                    for (i = 0; i < 2; i++)
490
262k
                        for (j = 0; j < 2; j++)
491
174k
                            comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
492
493
82.0k
                if ((ret = ff_jpeg2000_init_component(comp,
494
82.0k
                                                codsty,
495
82.0k
                                                qntsty,
496
82.0k
                                                s->cbps[compno],
497
82.0k
                                                (compno+1&2)?1<<s->chroma_shift[0]:1,
498
82.0k
                                                (compno+1&2)?1<<s->chroma_shift[1]:1,
499
82.0k
                                                s->avctx
500
82.0k
                                               )) < 0)
501
0
                    return ret;
502
82.0k
            }
503
30.2k
        }
504
570
    compute_rates(s);
505
570
    return 0;
506
570
}
507
508
#define COPY_FRAME(D, PIXEL)                                                                                                \
509
    static void copy_frame_ ##D(Jpeg2000EncoderContext *s)                                                                  \
510
7.97k
    {                                                                                                                       \
511
7.97k
        int tileno, compno, i, y, x;                                                                                        \
512
7.97k
        const PIXEL *line;                                                                                                  \
513
45.6k
        for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){                                                   \
514
37.6k
            Jpeg2000Tile *tile = s->tile + tileno;                                                                          \
515
37.6k
            if (s->planar){                                                                                                 \
516
49.9k
                for (compno = 0; compno < s->ncomponents; compno++){                                                        \
517
38.3k
                    int icompno = s->comp_remap[compno];                                                                    \
518
38.3k
                    Jpeg2000Component *comp = tile->comp + compno;                                                          \
519
38.3k
                    int *dst = comp->i_data;                                                                                \
520
38.3k
                    int cbps = s->cbps[compno];                                                                             \
521
38.3k
                    line = (const PIXEL*)s->picture->data[icompno]                                                           \
522
38.3k
                           + comp->coord[1][0] * (s->picture->linesize[icompno] / sizeof(PIXEL))                             \
523
38.3k
                           + comp->coord[0][0];                                                                             \
524
3.85M
                    for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){                                                \
525
3.81M
                        const PIXEL *ptr = line;                                                                            \
526
35.2M
                        for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)                                             \
527
31.4M
                            *dst++ = *ptr++ - (1 << (cbps - 1));                                                            \
528
3.81M
                        line += s->picture->linesize[icompno] / sizeof(PIXEL);                                               \
529
3.81M
                    }                                                                                                       \
530
38.3k
                }                                                                                                           \
531
26.0k
            } else{                                                                                                         \
532
26.0k
                line = (const PIXEL*)(s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0])            \
533
26.0k
                       + tile->comp[0].coord[0][0] * s->ncomponents;                                                        \
534
26.0k
                                                                                                                            \
535
26.0k
                i = 0;                                                                                                      \
536
1.68M
                for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){                                    \
537
1.66M
                    const PIXEL *ptr = line;                                                                                \
538
22.7M
                    for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){                           \
539
74.5M
                        for (compno = 0; compno < s->ncomponents; compno++){                                                \
540
53.5M
                            int cbps = s->cbps[compno];                                                                     \
541
53.5M
                            tile->comp[compno].i_data[i] = *ptr++  - (1 << (cbps - 1));                                     \
542
53.5M
                        }                                                                                                   \
543
21.0M
                    }                                                                                                       \
544
1.66M
                    line += s->picture->linesize[0] / sizeof(PIXEL);                                                        \
545
1.66M
                }                                                                                                           \
546
26.0k
            }                                                                                                               \
547
37.6k
        }                                                                                                                   \
548
7.97k
    }
j2kenc.c:copy_frame_16
Line
Count
Source
510
3.45k
    {                                                                                                                       \
511
3.45k
        int tileno, compno, i, y, x;                                                                                        \
512
3.45k
        const PIXEL *line;                                                                                                  \
513
24.1k
        for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){                                                   \
514
20.6k
            Jpeg2000Tile *tile = s->tile + tileno;                                                                          \
515
20.6k
            if (s->planar){                                                                                                 \
516
34.5k
                for (compno = 0; compno < s->ncomponents; compno++){                                                        \
517
26.3k
                    int icompno = s->comp_remap[compno];                                                                    \
518
26.3k
                    Jpeg2000Component *comp = tile->comp + compno;                                                          \
519
26.3k
                    int *dst = comp->i_data;                                                                                \
520
26.3k
                    int cbps = s->cbps[compno];                                                                             \
521
26.3k
                    line = (const PIXEL*)s->picture->data[icompno]                                                           \
522
26.3k
                           + comp->coord[1][0] * (s->picture->linesize[icompno] / sizeof(PIXEL))                             \
523
26.3k
                           + comp->coord[0][0];                                                                             \
524
2.56M
                    for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){                                                \
525
2.53M
                        const PIXEL *ptr = line;                                                                            \
526
25.5M
                        for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)                                             \
527
22.9M
                            *dst++ = *ptr++ - (1 << (cbps - 1));                                                            \
528
2.53M
                        line += s->picture->linesize[icompno] / sizeof(PIXEL);                                               \
529
2.53M
                    }                                                                                                       \
530
26.3k
                }                                                                                                           \
531
12.4k
            } else{                                                                                                         \
532
12.4k
                line = (const PIXEL*)(s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0])            \
533
12.4k
                       + tile->comp[0].coord[0][0] * s->ncomponents;                                                        \
534
12.4k
                                                                                                                            \
535
12.4k
                i = 0;                                                                                                      \
536
693k
                for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){                                    \
537
681k
                    const PIXEL *ptr = line;                                                                                \
538
11.1M
                    for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){                           \
539
42.1M
                        for (compno = 0; compno < s->ncomponents; compno++){                                                \
540
31.6M
                            int cbps = s->cbps[compno];                                                                     \
541
31.6M
                            tile->comp[compno].i_data[i] = *ptr++  - (1 << (cbps - 1));                                     \
542
31.6M
                        }                                                                                                   \
543
10.5M
                    }                                                                                                       \
544
681k
                    line += s->picture->linesize[0] / sizeof(PIXEL);                                                        \
545
681k
                }                                                                                                           \
546
12.4k
            }                                                                                                               \
547
20.6k
        }                                                                                                                   \
548
3.45k
    }
j2kenc.c:copy_frame_8
Line
Count
Source
510
4.52k
    {                                                                                                                       \
511
4.52k
        int tileno, compno, i, y, x;                                                                                        \
512
4.52k
        const PIXEL *line;                                                                                                  \
513
21.5k
        for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){                                                   \
514
17.0k
            Jpeg2000Tile *tile = s->tile + tileno;                                                                          \
515
17.0k
            if (s->planar){                                                                                                 \
516
15.4k
                for (compno = 0; compno < s->ncomponents; compno++){                                                        \
517
11.9k
                    int icompno = s->comp_remap[compno];                                                                    \
518
11.9k
                    Jpeg2000Component *comp = tile->comp + compno;                                                          \
519
11.9k
                    int *dst = comp->i_data;                                                                                \
520
11.9k
                    int cbps = s->cbps[compno];                                                                             \
521
11.9k
                    line = (const PIXEL*)s->picture->data[icompno]                                                           \
522
11.9k
                           + comp->coord[1][0] * (s->picture->linesize[icompno] / sizeof(PIXEL))                             \
523
11.9k
                           + comp->coord[0][0];                                                                             \
524
1.29M
                    for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){                                                \
525
1.28M
                        const PIXEL *ptr = line;                                                                            \
526
9.76M
                        for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)                                             \
527
8.48M
                            *dst++ = *ptr++ - (1 << (cbps - 1));                                                            \
528
1.28M
                        line += s->picture->linesize[icompno] / sizeof(PIXEL);                                               \
529
1.28M
                    }                                                                                                       \
530
11.9k
                }                                                                                                           \
531
13.5k
            } else{                                                                                                         \
532
13.5k
                line = (const PIXEL*)(s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0])            \
533
13.5k
                       + tile->comp[0].coord[0][0] * s->ncomponents;                                                        \
534
13.5k
                                                                                                                            \
535
13.5k
                i = 0;                                                                                                      \
536
992k
                for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){                                    \
537
979k
                    const PIXEL *ptr = line;                                                                                \
538
11.5M
                    for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){                           \
539
32.4M
                        for (compno = 0; compno < s->ncomponents; compno++){                                                \
540
21.8M
                            int cbps = s->cbps[compno];                                                                     \
541
21.8M
                            tile->comp[compno].i_data[i] = *ptr++  - (1 << (cbps - 1));                                     \
542
21.8M
                        }                                                                                                   \
543
10.5M
                    }                                                                                                       \
544
979k
                    line += s->picture->linesize[0] / sizeof(PIXEL);                                                        \
545
979k
                }                                                                                                           \
546
13.5k
            }                                                                                                               \
547
17.0k
        }                                                                                                                   \
548
4.52k
    }
549
550
COPY_FRAME(8, uint8_t)
551
COPY_FRAME(16, uint16_t)
552
553
static void init_quantization(Jpeg2000EncoderContext *s)
554
570
{
555
570
    int compno, reslevelno, bandno;
556
570
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
557
570
    Jpeg2000CodingStyle *codsty = &s->codsty;
558
559
2.02k
    for (compno = 0; compno < s->ncomponents; compno++){
560
1.45k
        int gbandno = 0;
561
11.6k
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
562
10.2k
            int nbands, lev = codsty->nreslevels - reslevelno - 1;
563
10.2k
            nbands = reslevelno ? 3 : 1;
564
37.9k
            for (bandno = 0; bandno < nbands; bandno++, gbandno++){
565
27.7k
                int expn, mant = 0;
566
567
27.7k
                if (codsty->transform == FF_DWT97_INT){
568
26.0k
                    int bandpos = bandno + (reslevelno>0),
569
26.0k
                        ss = 81920000 / dwt_norms[0][bandpos][lev],
570
26.0k
                        log = av_log2(ss);
571
26.0k
                    mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
572
26.0k
                    expn = s->cbps[compno] - log + 13;
573
26.0k
                } else
574
1.61k
                    expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
575
576
27.7k
                qntsty->expn[gbandno] = expn;
577
27.7k
                qntsty->mant[gbandno] = mant;
578
27.7k
            }
579
10.2k
        }
580
1.45k
    }
581
570
}
582
583
static void init_luts(void)
584
1
{
585
1
    int i, a,
586
1
        mask = ~((1<<NMSEDEC_FRACBITS)-1);
587
588
129
    for (i = 0; i < (1 << NMSEDEC_BITS); i++){
589
128
        lut_nmsedec_sig[i]  = FFMAX((3 * i << (13 - NMSEDEC_FRACBITS)) - (9 << 11), 0);
590
128
        lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
591
592
128
        a = (i >> (NMSEDEC_BITS-2)&2) + 1;
593
128
        lut_nmsedec_ref[i]  = FFMAX((a - 2) * (i << (13 - NMSEDEC_FRACBITS)) +
594
128
                                    (1 << 13) - (a * a << 11), 0);
595
128
        lut_nmsedec_ref0[i] = FFMAX(((i * i - (i << NMSEDEC_BITS) + (1 << 2 * NMSEDEC_FRACBITS) + (1 << (NMSEDEC_FRACBITS - 1))) & mask)
596
128
                                    << 1, 0);
597
128
    }
598
1
    ff_jpeg2000_init_tier1_luts();
599
1
}
600
601
/* tier-1 routines */
602
static int getnmsedec_sig(int x, int bpno)
603
36.3M
{
604
36.3M
    if (bpno > NMSEDEC_FRACBITS)
605
21.6M
        return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
606
14.6M
    return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
607
36.3M
}
608
609
static int getnmsedec_ref(int x, int bpno)
610
180M
{
611
180M
    if (bpno > NMSEDEC_FRACBITS)
612
159M
        return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
613
21.6M
    return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
614
180M
}
615
616
static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
617
10.8M
{
618
10.8M
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
619
22.7M
    for (y0 = 0; y0 < height; y0 += 4)
620
152M
        for (x = 0; x < width; x++)
621
390M
            for (y = y0; y < height && y < y0+4; y++){
622
250M
                if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
623
35.9M
                    int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
624
35.9M
                        bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
625
35.9M
                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
626
35.9M
                    if (bit){
627
12.1M
                        int xorbit;
628
12.1M
                        int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
629
12.1M
                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
630
12.1M
                        *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
631
12.1M
                        ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
632
12.1M
                    }
633
35.9M
                    t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
634
35.9M
                }
635
250M
            }
636
10.8M
}
637
638
static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
639
10.8M
{
640
10.8M
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
641
22.7M
    for (y0 = 0; y0 < height; y0 += 4)
642
152M
        for (x = 0; x < width; x++)
643
390M
            for (y = y0; y < height && y < y0+4; y++)
644
250M
                if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
645
180M
                    int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
646
180M
                    *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
647
180M
                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
648
180M
                    t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
649
180M
                }
650
10.8M
}
651
652
static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
653
12.2M
{
654
12.2M
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
655
26.4M
    for (y0 = 0; y0 < height; y0 += 4)
656
173M
        for (x = 0; x < width; x++){
657
159M
            if (y0 + 3 < height && !(
658
16.4M
            (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
659
16.4M
            (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
660
16.4M
            (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
661
16.4M
            (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
662
5.09M
            {
663
                // aggregation mode
664
5.09M
                int rlen;
665
23.7M
                for (rlen = 0; rlen < 4; rlen++)
666
19.1M
                    if (t1->data[(y0+rlen) * t1->stride + x] & mask)
667
468k
                        break;
668
5.09M
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
669
5.09M
                if (rlen == 4)
670
4.63M
                    continue;
671
468k
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
672
468k
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
673
2.16M
                for (y = y0 + rlen; y < y0 + 4; y++){
674
1.69M
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
675
1.69M
                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
676
1.69M
                        if (y > y0 + rlen)
677
1.23M
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
678
1.69M
                        if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
679
1.32M
                            int xorbit;
680
1.32M
                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
681
1.32M
                            *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
682
1.32M
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
683
1.32M
                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
684
1.32M
                        }
685
1.69M
                    }
686
1.69M
                    t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
687
1.69M
                }
688
154M
            } else{
689
422M
                for (y = y0; y < y0 + 4 && y < height; y++){
690
268M
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
691
51.5M
                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
692
51.5M
                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
693
51.5M
                        if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
694
22.8M
                            int xorbit;
695
22.8M
                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
696
22.8M
                            *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
697
22.8M
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
698
22.8M
                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
699
22.8M
                        }
700
51.5M
                    }
701
268M
                    t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
702
268M
                }
703
154M
            }
704
159M
        }
705
12.2M
}
706
707
static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
708
                        int width, int height, int bandpos, int lev)
709
2.70M
{
710
2.70M
    int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
711
2.70M
    int64_t wmsedec = 0;
712
713
2.70M
    memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
714
715
18.0M
    for (y = 0; y < height; y++){
716
100M
        for (x = 0; x < width; x++){
717
84.8M
            if (t1->data[(y) * t1->stride + x] < 0){
718
8.61M
                t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
719
8.61M
                t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
720
8.61M
            }
721
84.8M
            max = FFMAX(max, t1->data[(y) * t1->stride + x]);
722
84.8M
        }
723
15.2M
    }
724
725
2.70M
    if (max == 0){
726
1.25M
        cblk->nonzerobits = 0;
727
1.45M
    } else{
728
1.45M
        cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
729
1.45M
    }
730
2.70M
    bpno = cblk->nonzerobits - 1;
731
732
2.70M
    cblk->data[0] = 0;
733
2.70M
    ff_mqc_initenc(&t1->mqc, cblk->data + 1);
734
735
36.6M
    for (passno = 0; bpno >= 0; passno++){
736
33.9M
        nmsedec=0;
737
738
33.9M
        switch(pass_t){
739
10.8M
            case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
740
10.8M
                    break;
741
10.8M
            case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
742
10.8M
                    break;
743
12.2M
            case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
744
12.2M
                    break;
745
33.9M
        }
746
747
33.9M
        cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
748
33.9M
        cblk->passes[passno].rate -= cblk->passes[passno].flushed_len;
749
750
33.9M
        wmsedec += (int64_t)nmsedec << (2*bpno);
751
33.9M
        cblk->passes[passno].disto = wmsedec;
752
753
33.9M
        if (++pass_t == 3){
754
12.2M
            pass_t = 0;
755
12.2M
            bpno--;
756
12.2M
        }
757
33.9M
    }
758
2.70M
    cblk->npasses = passno;
759
2.70M
    cblk->ninclpasses = passno;
760
761
2.70M
    if (passno) {
762
1.45M
        cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
763
1.45M
        cblk->passes[passno-1].rate -= cblk->passes[passno-1].flushed_len;
764
1.45M
    }
765
2.70M
}
766
767
/* tier-2 routines: */
768
769
static void putnumpasses(Jpeg2000EncoderContext *s, int n)
770
1.44M
{
771
1.44M
    if (n == 1)
772
378k
        put_num(s, 0, 1);
773
1.07M
    else if (n == 2)
774
0
        put_num(s, 2, 2);
775
1.07M
    else if (n <= 5)
776
181k
        put_num(s, 0xc | (n-3), 4);
777
889k
    else if (n <= 36)
778
291k
        put_num(s, 0x1e0 | (n-6), 9);
779
598k
    else
780
598k
        put_num(s, 0xff80 | (n-37), 16);
781
1.44M
}
782
783
784
static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int layno,
785
                         int precno, const uint8_t *expn, int numgbits, int packetno,
786
                         int nlayers)
787
678k
{
788
678k
    int bandno, empty = 1;
789
678k
    int i;
790
    // init bitstream
791
678k
    *s->buf = 0;
792
678k
    s->bit_index = 0;
793
794
678k
    if (s->sop) {
795
0
        bytestream_put_be16(&s->buf, JPEG2000_SOP);
796
0
        bytestream_put_be16(&s->buf, 4);
797
0
        bytestream_put_be16(&s->buf, packetno);
798
0
    }
799
    // header
800
801
678k
    if (!layno) {
802
2.51M
        for (bandno = 0; bandno < rlevel->nbands; bandno++) {
803
1.84M
            Jpeg2000Band *band = rlevel->band + bandno;
804
1.84M
            if (band->coord[0][0] < band->coord[0][1]
805
1.84M
            &&  band->coord[1][0] < band->coord[1][1]) {
806
902k
                Jpeg2000Prec *prec = band->prec + precno;
807
902k
                int nb_cblks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
808
902k
                int pos;
809
902k
                ff_tag_tree_zero(prec->zerobits, prec->nb_codeblocks_width, prec->nb_codeblocks_height, 99);
810
902k
                ff_tag_tree_zero(prec->cblkincl, prec->nb_codeblocks_width, prec->nb_codeblocks_height, 99);
811
3.61M
                for (pos = 0; pos < nb_cblks; pos++) {
812
2.70M
                    Jpeg2000Cblk *cblk = &prec->cblk[pos];
813
2.70M
                    prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - cblk->nonzerobits;
814
2.70M
                    cblk->incl = 0;
815
2.70M
                    cblk->lblock = 3;
816
2.70M
                    tag_tree_update(prec->zerobits + pos);
817
3.96M
                    for (i = 0; i < nlayers; i++) {
818
2.70M
                        if (cblk->layers[i].npasses > 0) {
819
1.44M
                            prec->cblkincl[pos].val = i;
820
1.44M
                            break;
821
1.44M
                        }
822
2.70M
                    }
823
2.70M
                    if (i == nlayers)
824
1.25M
                        prec->cblkincl[pos].val = i;
825
2.70M
                    tag_tree_update(prec->cblkincl + pos);
826
2.70M
                }
827
902k
            }
828
1.84M
        }
829
678k
    }
830
831
    // is the packet empty?
832
1.55M
    for (bandno = 0; bandno < rlevel->nbands; bandno++){
833
1.28M
        Jpeg2000Band *band = rlevel->band + bandno;
834
1.28M
        if (band->coord[0][0] < band->coord[0][1]
835
1.28M
        &&  band->coord[1][0] < band->coord[1][1]) {
836
707k
            Jpeg2000Prec *prec = band->prec + precno;
837
707k
            int nb_cblks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
838
707k
            int pos;
839
1.70M
            for (pos = 0; pos < nb_cblks; pos++) {
840
1.40M
                Jpeg2000Cblk *cblk = &prec->cblk[pos];
841
1.40M
                if (cblk->layers[layno].npasses) {
842
407k
                    empty = 0;
843
407k
                    break;
844
407k
                }
845
1.40M
            }
846
707k
            if (!empty)
847
407k
                break;
848
707k
        }
849
1.28M
    }
850
851
678k
    put_bits(s, !empty, 1);
852
678k
    if (empty){
853
270k
        j2k_flush(s);
854
270k
        if (s->eph)
855
0
            bytestream_put_be16(&s->buf, JPEG2000_EPH);
856
270k
        return 0;
857
270k
    }
858
859
1.43M
    for (bandno = 0; bandno < rlevel->nbands; bandno++) {
860
1.02M
        Jpeg2000Band *band = rlevel->band + bandno;
861
1.02M
        Jpeg2000Prec *prec = band->prec + precno;
862
1.02M
        int yi, xi, pos;
863
1.02M
        int cblknw = prec->nb_codeblocks_width;
864
865
1.02M
        if (band->coord[0][0] == band->coord[0][1]
866
1.02M
        ||  band->coord[1][0] == band->coord[1][1])
867
426k
            continue;
868
869
1.42M
        for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++) {
870
2.53M
            for (xi = 0; xi < cblknw; xi++, pos++){
871
1.71M
                int llen = 0, length;
872
1.71M
                Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
873
874
1.71M
                if (s->buf_end - s->buf < 20) // approximately
875
10
                    return -1;
876
877
                // inclusion information
878
1.71M
                if (!cblk->incl)
879
1.71M
                    tag_tree_code(s, prec->cblkincl + pos, layno + 1);
880
0
                else {
881
0
                    put_bits(s, cblk->layers[layno].npasses > 0, 1);
882
0
                }
883
884
1.71M
                if (!cblk->layers[layno].npasses)
885
264k
                    continue;
886
887
                // zerobits information
888
1.44M
                if (!cblk->incl) {
889
1.44M
                    tag_tree_code(s, prec->zerobits + pos, 100);
890
1.44M
                    cblk->incl = 1;
891
1.44M
                }
892
893
                // number of passes
894
1.44M
                putnumpasses(s, cblk->layers[layno].npasses);
895
896
1.44M
                length = cblk->layers[layno].data_len;
897
1.44M
                if (layno == nlayers - 1 && cblk->layers[layno].cum_passes){
898
1.44M
                    length += cblk->passes[cblk->layers[layno].cum_passes-1].flushed_len;
899
1.44M
                }
900
1.44M
                if (cblk->lblock + av_log2(cblk->layers[layno].npasses) < av_log2(length) + 1) {
901
7.76k
                    llen = av_log2(length) + 1 - cblk->lblock - av_log2(cblk->layers[layno].npasses);
902
7.76k
                }
903
904
                // length of code block
905
1.44M
                cblk->lblock += llen;
906
1.44M
                put_bits(s, 1, llen);
907
1.44M
                put_bits(s, 0, 1);
908
1.44M
                put_num(s, length, cblk->lblock + av_log2(cblk->layers[layno].npasses));
909
1.44M
            }
910
820k
        }
911
602k
    }
912
407k
    j2k_flush(s);
913
407k
    if (s->eph) {
914
0
        bytestream_put_be16(&s->buf, JPEG2000_EPH);
915
0
    }
916
917
1.43M
    for (bandno = 0; bandno < rlevel->nbands; bandno++) {
918
1.02M
        Jpeg2000Band *band = rlevel->band + bandno;
919
1.02M
        Jpeg2000Prec *prec = band->prec + precno;
920
1.02M
        int yi, cblknw = prec->nb_codeblocks_width;
921
2.05M
        for (yi =0; yi < prec->nb_codeblocks_height; yi++) {
922
1.02M
            int xi;
923
2.73M
            for (xi = 0; xi < cblknw; xi++){
924
1.71M
                Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
925
1.71M
                if (cblk->layers[layno].npasses) {
926
1.44M
                    if (s->buf_end - s->buf < cblk->layers[layno].data_len + 2)
927
10
                        return -1;
928
1.44M
                    bytestream_put_buffer(&s->buf, cblk->layers[layno].data_start + 1, cblk->layers[layno].data_len);
929
1.44M
                    if (layno == nlayers - 1 && cblk->layers[layno].cum_passes) {
930
1.44M
                        bytestream_put_buffer(&s->buf, cblk->passes[cblk->layers[layno].cum_passes-1].flushed,
931
1.44M
                                                       cblk->passes[cblk->layers[layno].cum_passes-1].flushed_len);
932
1.44M
                    }
933
1.44M
                }
934
1.71M
            }
935
1.02M
        }
936
1.02M
    }
937
407k
    return 0;
938
407k
}
939
940
static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno, int nlayers)
941
37.6k
{
942
37.6k
    int compno, reslevelno, layno, ret;
943
37.6k
    Jpeg2000CodingStyle *codsty = &s->codsty;
944
37.6k
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
945
37.6k
    int packetno = 0;
946
37.6k
    int step_x, step_y;
947
37.6k
    int x, y;
948
37.6k
    int tile_coord[2][2];
949
37.6k
    int col = tileno % s->numXtiles;
950
37.6k
    int row = tileno / s->numXtiles;
951
952
37.6k
    tile_coord[0][0] = col * s->tile_width;
953
37.6k
    tile_coord[0][1] = FFMIN(tile_coord[0][0] + s->tile_width, s->width);
954
37.6k
    tile_coord[1][0] = row * s->tile_height;
955
37.6k
    tile_coord[1][1] = FFMIN(tile_coord[1][0] + s->tile_height, s->height);
956
957
37.6k
    av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
958
    // lay-rlevel-comp-pos progression
959
37.6k
    switch (s->prog) {
960
37.6k
    case JPEG2000_PGOD_LRCP:
961
75.2k
    for (layno = 0; layno < nlayers; layno++) {
962
301k
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
963
941k
            for (compno = 0; compno < s->ncomponents; compno++){
964
678k
                int precno;
965
678k
                Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
966
1.35M
                for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
967
678k
                    if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
968
678k
                                qntsty->nguardbits, packetno++, nlayers)) < 0)
969
20
                        return ret;
970
678k
                }
971
678k
            }
972
263k
        }
973
37.6k
    }
974
37.6k
    break;
975
37.6k
    case JPEG2000_PGOD_RLCP:
976
0
    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
977
0
        for (layno = 0; layno < nlayers; layno++) {
978
0
            for (compno = 0; compno < s->ncomponents; compno++){
979
0
                int precno;
980
0
                Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
981
0
                for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
982
0
                    if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
983
0
                                qntsty->nguardbits, packetno++, nlayers)) < 0)
984
0
                        return ret;
985
0
                }
986
0
            }
987
0
        }
988
0
    }
989
0
    break;
990
0
    case JPEG2000_PGOD_RPCL:
991
0
    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
992
0
        int precno;
993
0
        step_x = 30;
994
0
        step_y = 30;
995
0
        for (compno = 0; compno < s->ncomponents; compno++) {
996
0
            Jpeg2000Component *comp     = tile->comp + compno;
997
0
            if (reslevelno < codsty->nreslevels) {
998
0
                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
999
0
                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1000
0
                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1001
0
                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1002
0
            }
1003
0
        }
1004
1005
0
        step_x = 1<<step_x;
1006
0
        step_y = 1<<step_y;
1007
0
        for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
1008
0
            for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
1009
0
                for (compno = 0; compno < s->ncomponents; compno++) {
1010
0
                    Jpeg2000Component *comp     = tile->comp + compno;
1011
0
                    uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1012
0
                    Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1013
0
                    int log_subsampling[2] = { (compno+1&2)?s->chroma_shift[0]:0, (compno+1&2)?s->chroma_shift[1]:0};
1014
0
                    unsigned prcx, prcy;
1015
0
                    int trx0, try0;
1016
1017
0
                    trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
1018
0
                    try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
1019
1020
0
                    if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
1021
0
                        (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
1022
0
                        continue;
1023
1024
0
                    if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
1025
0
                        (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
1026
0
                        continue;
1027
1028
                    // check if a precinct exists
1029
0
                    prcx   = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
1030
0
                    prcy   = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
1031
0
                    prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
1032
0
                    prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
1033
0
                    precno = prcx + reslevel->num_precincts_x * prcy;
1034
1035
0
                    if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1036
0
                        av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1037
0
                               prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1038
0
                        continue;
1039
0
                    }
1040
0
                    for (layno = 0; layno < nlayers; layno++) {
1041
0
                        if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1042
0
                                qntsty->nguardbits, packetno++, nlayers)) < 0)
1043
0
                            return ret;
1044
0
                        }
1045
0
                    }
1046
0
                }
1047
0
            }
1048
0
    }
1049
0
    break;
1050
0
    case JPEG2000_PGOD_PCRL:
1051
0
        step_x = 32;
1052
0
        step_y = 32;
1053
0
        for (compno = 0; compno < s->ncomponents; compno++) {
1054
0
            Jpeg2000Component *comp     = tile->comp + compno;
1055
1056
0
            for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1057
0
                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1058
0
                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1059
0
                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1060
0
                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1061
0
            }
1062
0
        }
1063
0
        if (step_x >= 31 || step_y >= 31){
1064
0
            avpriv_request_sample(s->avctx, "PCRL with large step");
1065
0
            return AVERROR_PATCHWELCOME;
1066
0
        }
1067
0
        step_x = 1<<step_x;
1068
0
        step_y = 1<<step_y;
1069
1070
0
        for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
1071
0
            for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
1072
0
                for (compno = 0; compno < s->ncomponents; compno++) {
1073
0
                    Jpeg2000Component *comp     = tile->comp + compno;
1074
0
                    int log_subsampling[2] = { (compno+1&2)?s->chroma_shift[0]:0, (compno+1&2)?s->chroma_shift[1]:0};
1075
1076
0
                    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1077
0
                        unsigned prcx, prcy;
1078
0
                        int precno;
1079
0
                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1080
0
                        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1081
0
                        int trx0, try0;
1082
1083
0
                        trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
1084
0
                        try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
1085
1086
0
                        if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
1087
0
                            (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
1088
0
                            continue;
1089
1090
0
                        if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
1091
0
                            (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
1092
0
                            continue;
1093
1094
                        // check if a precinct exists
1095
0
                        prcx   = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
1096
0
                        prcy   = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
1097
0
                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
1098
0
                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
1099
1100
0
                        precno = prcx + reslevel->num_precincts_x * prcy;
1101
1102
0
                        if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1103
0
                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1104
0
                                   prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1105
0
                            continue;
1106
0
                        }
1107
0
                        for (layno = 0; layno < nlayers; layno++) {
1108
0
                            if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1109
0
                                    qntsty->nguardbits, packetno++, nlayers)) < 0)
1110
0
                                return ret;
1111
0
                        }
1112
0
                    }
1113
0
                }
1114
0
            }
1115
0
        }
1116
0
    break;
1117
0
    case JPEG2000_PGOD_CPRL:
1118
0
        for (compno = 0; compno < s->ncomponents; compno++) {
1119
0
            Jpeg2000Component *comp     = tile->comp + compno;
1120
0
            int log_subsampling[2] = { (compno+1&2)?s->chroma_shift[0]:0, (compno+1&2)?s->chroma_shift[1]:0};
1121
0
            step_x = 32;
1122
0
            step_y = 32;
1123
1124
0
            for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1125
0
                uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1126
0
                Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
1127
0
                step_x = FFMIN(step_x, rlevel->log2_prec_width  + reducedresno);
1128
0
                step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
1129
0
            }
1130
0
            if (step_x >= 31 || step_y >= 31){
1131
0
                avpriv_request_sample(s->avctx, "CPRL with large step");
1132
0
                return AVERROR_PATCHWELCOME;
1133
0
            }
1134
0
            step_x = 1<<step_x;
1135
0
            step_y = 1<<step_y;
1136
1137
0
            for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
1138
0
                for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
1139
0
                    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
1140
0
                        unsigned prcx, prcy;
1141
0
                        int precno;
1142
0
                        int trx0, try0;
1143
0
                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r
1144
0
                        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1145
1146
0
                        trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
1147
0
                        try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
1148
1149
0
                        if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
1150
0
                            (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
1151
0
                            continue;
1152
1153
0
                        if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
1154
0
                            (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
1155
0
                            continue;
1156
1157
                        // check if a precinct exists
1158
0
                        prcx   = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
1159
0
                        prcy   = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
1160
0
                        prcx  -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
1161
0
                        prcy  -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
1162
1163
0
                        precno = prcx + reslevel->num_precincts_x * prcy;
1164
1165
0
                        if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
1166
0
                            av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
1167
0
                                   prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
1168
0
                            continue;
1169
0
                        }
1170
0
                        for (layno = 0; layno < nlayers; layno++) {
1171
0
                            if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
1172
0
                                    qntsty->nguardbits, packetno++, nlayers)) < 0)
1173
0
                                return ret;
1174
0
                        }
1175
0
                    }
1176
0
                }
1177
0
            }
1178
0
        }
1179
1180
37.6k
    }
1181
1182
37.6k
    av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
1183
37.6k
    return 0;
1184
37.6k
}
1185
1186
static void makelayer(Jpeg2000EncoderContext *s, int layno, double thresh, Jpeg2000Tile* tile, int final)
1187
0
{
1188
0
    int compno, resno, bandno, precno, cblkno;
1189
0
    int passno;
1190
1191
0
    for (compno = 0; compno < s->ncomponents; compno++) {
1192
0
        Jpeg2000Component *comp = &tile->comp[compno];
1193
1194
0
        for (resno = 0; resno < s->codsty.nreslevels; resno++) {
1195
0
            Jpeg2000ResLevel *reslevel = comp->reslevel + resno;
1196
1197
0
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
1198
0
                for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1199
0
                    Jpeg2000Band *band = reslevel->band + bandno;
1200
0
                    Jpeg2000Prec *prec = band->prec + precno;
1201
1202
0
                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
1203
0
                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1204
0
                        Jpeg2000Layer *layer = &cblk->layers[layno];
1205
0
                        int n;
1206
1207
0
                        if (layno == 0) {
1208
0
                            cblk->ninclpasses = 0;
1209
0
                        }
1210
1211
0
                        n = cblk->ninclpasses;
1212
1213
0
                        if (thresh < 0) {
1214
0
                            n = cblk->npasses;
1215
0
                        } else {
1216
0
                            for (passno = cblk->ninclpasses; passno < cblk->npasses; passno++) {
1217
0
                                int32_t dr;
1218
0
                                double dd;
1219
0
                                Jpeg2000Pass *pass = &cblk->passes[passno];
1220
1221
0
                                if (n == 0) {
1222
0
                                    dr = pass->rate;
1223
0
                                    dd = pass->disto;
1224
0
                                } else {
1225
0
                                    dr = pass->rate - cblk->passes[n - 1].rate;
1226
0
                                    dd = pass->disto - cblk->passes[n-1].disto;
1227
0
                                }
1228
1229
0
                                if (!dr) {
1230
0
                                    if (dd != 0.0) {
1231
0
                                        n = passno + 1;
1232
0
                                    }
1233
0
                                    continue;
1234
0
                                }
1235
1236
0
                                if (thresh - (dd / dr) < DBL_EPSILON)
1237
0
                                    n = passno + 1;
1238
0
                            }
1239
0
                        }
1240
0
                        layer->npasses = n - cblk->ninclpasses;
1241
0
                        layer->cum_passes = n;
1242
1243
0
                        if (layer->npasses == 0) {
1244
0
                            layer->disto = 0;
1245
0
                            layer->data_len = 0;
1246
0
                            continue;
1247
0
                        }
1248
1249
0
                        if (cblk->ninclpasses == 0) {
1250
0
                            layer->data_len = cblk->passes[n - 1].rate;
1251
0
                            layer->data_start = cblk->data;
1252
0
                            layer->disto = cblk->passes[n - 1].disto;
1253
0
                        } else {
1254
0
                            layer->data_len = cblk->passes[n - 1].rate - cblk->passes[cblk->ninclpasses - 1].rate;
1255
0
                            layer->data_start = cblk->data + cblk->passes[cblk->ninclpasses - 1].rate;
1256
0
                            layer->disto = cblk->passes[n - 1].disto -
1257
0
                                           cblk->passes[cblk->ninclpasses - 1].disto;
1258
0
                        }
1259
0
                        if (final) {
1260
0
                            cblk->ninclpasses = n;
1261
0
                        }
1262
0
                    }
1263
0
                }
1264
0
            }
1265
0
        }
1266
0
    }
1267
0
}
1268
1269
static void makelayers(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
1270
0
{
1271
0
    int precno, compno, reslevelno, bandno, cblkno, passno, layno;
1272
0
    int i;
1273
0
    double min = DBL_MAX;
1274
0
    double max = 0;
1275
0
    double thresh;
1276
1277
0
    Jpeg2000CodingStyle *codsty = &s->codsty;
1278
1279
0
    for (compno = 0; compno < s->ncomponents; compno++){
1280
0
        Jpeg2000Component *comp = tile->comp + compno;
1281
1282
0
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
1283
0
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1284
1285
0
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
1286
0
                for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1287
0
                    Jpeg2000Band *band = reslevel->band + bandno;
1288
0
                    Jpeg2000Prec *prec = band->prec + precno;
1289
1290
0
                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
1291
0
                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1292
0
                        for (passno = 0; passno < cblk->npasses; passno++) {
1293
0
                            Jpeg2000Pass *pass = &cblk->passes[passno];
1294
0
                            int dr;
1295
0
                            double dd, drslope;
1296
1297
0
                            if (passno == 0) {
1298
0
                                dr = (int32_t)pass->rate;
1299
0
                                dd = pass->disto;
1300
0
                            } else {
1301
0
                                dr = (int32_t)(pass->rate - cblk->passes[passno - 1].rate);
1302
0
                                dd = pass->disto - cblk->passes[passno - 1].disto;
1303
0
                            }
1304
1305
0
                            if (dr <= 0)
1306
0
                                continue;
1307
1308
0
                            drslope = dd / dr;
1309
0
                            if (drslope < min)
1310
0
                                min = drslope;
1311
1312
0
                            if (drslope > max)
1313
0
                                max = drslope;
1314
0
                        }
1315
0
                    }
1316
0
                }
1317
0
            }
1318
0
        }
1319
0
    }
1320
1321
0
    for (layno = 0; layno < s->nlayers; layno++) {
1322
0
        double lo = min;
1323
0
        double hi = max;
1324
0
        double stable_thresh = 0.0;
1325
0
        double good_thresh = 0.0;
1326
0
        if (!s->layer_rates[layno]) {
1327
0
            good_thresh = -1.0;
1328
0
        } else {
1329
0
            for (i = 0; i < 128; i++) {
1330
0
                uint8_t *stream_pos = s->buf;
1331
0
                int ret;
1332
0
                thresh = (lo + hi) / 2;
1333
0
                makelayer(s, layno, thresh, tile, 0);
1334
0
                ret = encode_packets(s, tile, (int)(tile - s->tile), layno + 1);
1335
0
                memset(stream_pos, 0, s->buf - stream_pos);
1336
0
                if ((s->buf - stream_pos > ceil(tile->layer_rates[layno])) || ret < 0) {
1337
0
                    lo = thresh;
1338
0
                    s->buf = stream_pos;
1339
0
                    continue;
1340
0
                }
1341
0
                hi = thresh;
1342
0
                stable_thresh = thresh;
1343
0
                s->buf = stream_pos;
1344
0
            }
1345
0
        }
1346
0
        if (good_thresh >= 0.0)
1347
0
            good_thresh = stable_thresh == 0.0 ? thresh : stable_thresh;
1348
0
        makelayer(s, layno, good_thresh, tile, 1);
1349
0
    }
1350
0
}
1351
1352
static int getcut(Jpeg2000Cblk *cblk, uint64_t lambda)
1353
2.71M
{
1354
2.71M
    int passno, res = 0;
1355
36.6M
    for (passno = 0; passno < cblk->npasses; passno++){
1356
33.9M
        int dr;
1357
33.9M
        int64_t dd;
1358
1359
33.9M
        dr = cblk->passes[passno].rate
1360
33.9M
           - (res ? cblk->passes[res-1].rate : 0);
1361
33.9M
        dd = cblk->passes[passno].disto
1362
33.9M
           - (res ? cblk->passes[res-1].disto : 0);
1363
1364
33.9M
        if (dd  >= dr * lambda)
1365
33.9M
            res = passno+1;
1366
33.9M
    }
1367
2.71M
    return res;
1368
2.71M
}
1369
1370
static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
1371
37.6k
{
1372
37.6k
    int precno, compno, reslevelno, bandno, cblkno, lev;
1373
37.6k
    Jpeg2000CodingStyle *codsty = &s->codsty;
1374
1375
134k
    for (compno = 0; compno < s->ncomponents; compno++){
1376
96.8k
        Jpeg2000Component *comp = tile->comp + compno;
1377
1378
775k
        for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
1379
678k
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1380
1381
1.35M
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
1382
2.51M
                for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1383
1.84M
                    int bandpos = bandno + (reslevelno > 0);
1384
1.84M
                    Jpeg2000Band *band = reslevel->band + bandno;
1385
1.84M
                    Jpeg2000Prec *prec = band->prec + precno;
1386
1387
1.84M
                    int64_t dwt_norm = dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15;
1388
1.84M
                    int64_t lambda_prime = av_rescale(s->lambda, 1 << WMSEDEC_SHIFT, dwt_norm * dwt_norm);
1389
4.55M
                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
1390
2.71M
                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;
1391
1392
2.71M
                        cblk->ninclpasses = getcut(cblk, lambda_prime);
1393
2.71M
                        cblk->layers[0].data_start = cblk->data;
1394
2.71M
                        cblk->layers[0].cum_passes = cblk->ninclpasses;
1395
2.71M
                        cblk->layers[0].npasses = cblk->ninclpasses;
1396
2.71M
                        if (cblk->ninclpasses)
1397
1.45M
                            cblk->layers[0].data_len = cblk->passes[cblk->ninclpasses - 1].rate;
1398
2.71M
                    }
1399
1.84M
                }
1400
678k
            }
1401
678k
        }
1402
96.8k
    }
1403
37.6k
}
1404
1405
static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
1406
37.6k
{
1407
37.6k
    int compno, reslevelno, bandno, ret;
1408
37.6k
    Jpeg2000T1Context t1;
1409
37.6k
    Jpeg2000CodingStyle *codsty = &s->codsty;
1410
134k
    for (compno = 0; compno < s->ncomponents; compno++){
1411
96.8k
        Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1412
1413
96.8k
        t1.stride = (1<<codsty->log2_cblk_width) + 2;
1414
1415
96.8k
        av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
1416
96.8k
        if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
1417
0
            return ret;
1418
96.8k
        av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
1419
1420
775k
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
1421
678k
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
1422
1423
2.51M
            for (bandno = 0; bandno < reslevel->nbands ; bandno++){
1424
1.84M
                Jpeg2000Band *band = reslevel->band + bandno;
1425
1.84M
                Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
1426
1.84M
                int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
1427
1.84M
                yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
1428
1.84M
                y0 = yy0;
1429
1.84M
                yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
1430
1.84M
                            band->coord[1][1]) - band->coord[1][0] + yy0;
1431
1432
1.84M
                if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
1433
938k
                    continue;
1434
1435
902k
                bandpos = bandno + (reslevelno > 0);
1436
1437
2.30M
                for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
1438
1.40M
                    if (reslevelno == 0 || bandno == 1)
1439
645k
                        xx0 = 0;
1440
754k
                    else
1441
754k
                        xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
1442
1.40M
                    x0 = xx0;
1443
1.40M
                    xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
1444
1.40M
                                band->coord[0][1]) - band->coord[0][0] + xx0;
1445
1446
4.11M
                    for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
1447
2.70M
                        int y, x;
1448
2.70M
                        if (codsty->transform == FF_DWT53){
1449
1.15M
                            for (y = yy0; y < yy1; y++){
1450
1.00M
                                int *ptr = t1.data + (y-yy0)*t1.stride;
1451
4.70M
                                for (x = xx0; x < xx1; x++){
1452
3.70M
                                    *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] * (1 << NMSEDEC_FRACBITS);
1453
3.70M
                                }
1454
1.00M
                            }
1455
2.55M
                        } else{
1456
16.8M
                            for (y = yy0; y < yy1; y++){
1457
14.2M
                                int *ptr = t1.data + (y-yy0)*t1.stride;
1458
95.4M
                                for (x = xx0; x < xx1; x++){
1459
81.1M
                                    *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
1460
81.1M
                                    *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
1461
81.1M
                                    ptr++;
1462
81.1M
                                }
1463
14.2M
                            }
1464
2.55M
                        }
1465
2.70M
                        if (!prec->cblk[cblkno].data)
1466
2.58M
                            prec->cblk[cblkno].data = av_malloc(1 + 8192);
1467
2.70M
                        if (!prec->cblk[cblkno].passes)
1468
2.58M
                            prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
1469
2.70M
                        if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
1470
0
                            return AVERROR(ENOMEM);
1471
2.70M
                        encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
1472
2.70M
                                    bandpos, codsty->nreslevels - reslevelno - 1);
1473
2.70M
                        xx0 = xx1;
1474
2.70M
                        xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
1475
2.70M
                    }
1476
1.40M
                    yy0 = yy1;
1477
1.40M
                    yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
1478
1.40M
                }
1479
902k
            }
1480
678k
        }
1481
96.8k
        av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
1482
96.8k
    }
1483
1484
37.6k
    av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
1485
37.6k
    if (s->compression_rate_enc)
1486
0
        makelayers(s, tile);
1487
37.6k
    else
1488
37.6k
        truncpasses(s, tile);
1489
1490
37.6k
    if ((ret = encode_packets(s, tile, tileno, s->nlayers)) < 0)
1491
20
        return ret;
1492
37.6k
    av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
1493
37.6k
    return 0;
1494
37.6k
}
1495
1496
static void cleanup(Jpeg2000EncoderContext *s)
1497
570
{
1498
570
    int tileno, compno;
1499
570
    Jpeg2000CodingStyle *codsty = &s->codsty;
1500
1501
570
    if (!s->tile)
1502
0
        return;
1503
30.8k
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1504
30.2k
        if (s->tile[tileno].comp) {
1505
112k
            for (compno = 0; compno < s->ncomponents; compno++){
1506
82.0k
                Jpeg2000Component *comp = s->tile[tileno].comp + compno;
1507
82.0k
                ff_jpeg2000_cleanup(comp, codsty);
1508
82.0k
            }
1509
30.2k
            av_freep(&s->tile[tileno].comp);
1510
30.2k
        }
1511
30.2k
        av_freep(&s->tile[tileno].layer_rates);
1512
30.2k
    }
1513
570
    av_freep(&s->tile);
1514
570
}
1515
1516
static void reinit(Jpeg2000EncoderContext *s)
1517
7.97k
{
1518
7.97k
    int tileno, compno;
1519
45.6k
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1520
37.6k
        Jpeg2000Tile *tile = s->tile + tileno;
1521
134k
        for (compno = 0; compno < s->ncomponents; compno++)
1522
97.0k
            ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
1523
37.6k
    }
1524
7.97k
}
1525
1526
static void update_size(uint8_t *size, const uint8_t *end)
1527
44.0k
{
1528
44.0k
    AV_WB32(size, end-size);
1529
44.0k
}
1530
1531
static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1532
                        const AVFrame *pict, int *got_packet)
1533
7.97k
{
1534
7.97k
    int tileno, ret;
1535
7.97k
    Jpeg2000EncoderContext *s = avctx->priv_data;
1536
7.97k
    uint8_t *chunkstart, *jp2cstart, *jp2hstart;
1537
7.97k
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1538
1539
7.97k
    if ((ret = ff_alloc_packet(avctx, pkt, avctx->width*avctx->height*9 + FF_INPUT_BUFFER_MIN_SIZE)) < 0)
1540
0
        return ret;
1541
1542
    // init:
1543
7.97k
    s->buf = s->buf_start = pkt->data;
1544
7.97k
    s->buf_end = pkt->data + pkt->size;
1545
1546
7.97k
    s->picture = pict;
1547
1548
7.97k
    s->lambda = s->picture->quality * LAMBDA_SCALE;
1549
1550
7.97k
    if (s->cbps[0] > 8)
1551
3.45k
        copy_frame_16(s);
1552
4.52k
    else
1553
4.52k
        copy_frame_8(s);
1554
1555
7.97k
    reinit(s);
1556
1557
7.97k
    if (s->format == CODEC_JP2) {
1558
7.97k
        av_assert0(s->buf == pkt->data);
1559
1560
7.97k
        bytestream_put_be32(&s->buf, 0x0000000C);
1561
7.97k
        bytestream_put_be32(&s->buf, 0x6A502020);
1562
7.97k
        bytestream_put_be32(&s->buf, 0x0D0A870A);
1563
1564
7.97k
        chunkstart = s->buf;
1565
7.97k
        bytestream_put_be32(&s->buf, 0);
1566
7.97k
        bytestream_put_buffer(&s->buf, "ftyp", 4);
1567
7.97k
        bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
1568
7.97k
        bytestream_put_be32(&s->buf, 0);
1569
7.97k
        bytestream_put_buffer(&s->buf, "jp2\040", 4);
1570
7.97k
        update_size(chunkstart, s->buf);
1571
1572
7.97k
        jp2hstart = s->buf;
1573
7.97k
        bytestream_put_be32(&s->buf, 0);
1574
7.97k
        bytestream_put_buffer(&s->buf, "jp2h", 4);
1575
1576
7.97k
        chunkstart = s->buf;
1577
7.97k
        bytestream_put_be32(&s->buf, 0);
1578
7.97k
        bytestream_put_buffer(&s->buf, "ihdr", 4);
1579
7.97k
        bytestream_put_be32(&s->buf, avctx->height);
1580
7.97k
        bytestream_put_be32(&s->buf, avctx->width);
1581
7.97k
        bytestream_put_be16(&s->buf, s->ncomponents);
1582
7.97k
        bytestream_put_byte(&s->buf, s->cbps[0]);
1583
7.97k
        bytestream_put_byte(&s->buf, 7);
1584
7.97k
        bytestream_put_byte(&s->buf, 0);
1585
7.97k
        bytestream_put_byte(&s->buf, 0);
1586
7.97k
        update_size(chunkstart, s->buf);
1587
1588
7.97k
        chunkstart = s->buf;
1589
7.97k
        bytestream_put_be32(&s->buf, 0);
1590
7.97k
        bytestream_put_buffer(&s->buf, "colr", 4);
1591
7.97k
        bytestream_put_byte(&s->buf, 1);
1592
7.97k
        bytestream_put_byte(&s->buf, 0);
1593
7.97k
        bytestream_put_byte(&s->buf, 0);
1594
7.97k
        if ((desc->flags & AV_PIX_FMT_FLAG_RGB) || avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1595
4.36k
            bytestream_put_be32(&s->buf, 16);
1596
4.36k
        } else if (s->ncomponents == 1) {
1597
2.71k
            bytestream_put_be32(&s->buf, 17);
1598
2.71k
        } else {
1599
904
            bytestream_put_be32(&s->buf, 18);
1600
904
        }
1601
7.97k
        update_size(chunkstart, s->buf);
1602
7.97k
        if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1603
2.11k
            int i;
1604
2.11k
            const uint8_t *palette = pict->data[1];
1605
2.11k
            chunkstart = s->buf;
1606
2.11k
            bytestream_put_be32(&s->buf, 0);
1607
2.11k
            bytestream_put_buffer(&s->buf, "pclr", 4);
1608
2.11k
            bytestream_put_be16(&s->buf, AVPALETTE_COUNT);
1609
2.11k
            bytestream_put_byte(&s->buf, 3); // colour channels
1610
2.11k
            bytestream_put_be24(&s->buf, 0x070707); //colour depths
1611
544k
            for (i = 0; i < AVPALETTE_COUNT; i++) {
1612
542k
                bytestream_put_be24(&s->buf, HAVE_BIGENDIAN ? AV_RB24(palette + 1) : AV_RL24(palette));
1613
542k
                palette += 4;
1614
542k
            }
1615
2.11k
            update_size(chunkstart, s->buf);
1616
2.11k
            chunkstart = s->buf;
1617
2.11k
            bytestream_put_be32(&s->buf, 0);
1618
2.11k
            bytestream_put_buffer(&s->buf, "cmap", 4);
1619
8.47k
            for (i = 0; i < 3; i++) {
1620
6.35k
                bytestream_put_be16(&s->buf, 0); // component
1621
6.35k
                bytestream_put_byte(&s->buf, 1); // palette mapping
1622
6.35k
                bytestream_put_byte(&s->buf, i); // index
1623
6.35k
            }
1624
2.11k
            update_size(chunkstart, s->buf);
1625
2.11k
        }
1626
7.97k
        update_size(jp2hstart, s->buf);
1627
1628
7.97k
        jp2cstart = s->buf;
1629
7.97k
        bytestream_put_be32(&s->buf, 0);
1630
7.97k
        bytestream_put_buffer(&s->buf, "jp2c", 4);
1631
7.97k
    }
1632
1633
7.97k
    if (s->buf_end - s->buf < 2)
1634
0
        return -1;
1635
7.97k
    bytestream_put_be16(&s->buf, JPEG2000_SOC);
1636
7.97k
    if ((ret = put_siz(s)) < 0)
1637
0
        return ret;
1638
7.97k
    if ((ret = put_cod(s)) < 0)
1639
0
        return ret;
1640
7.97k
    if ((ret = put_qcd(s, 0)) < 0)
1641
0
        return ret;
1642
7.97k
    if ((ret = put_com(s, 0)) < 0)
1643
0
        return ret;
1644
1645
45.5k
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1646
37.6k
        uint8_t *psotptr;
1647
37.6k
        if (!(psotptr = put_sot(s, tileno)))
1648
3
            return -1;
1649
37.6k
        if (s->buf_end - s->buf < 2)
1650
1
            return -1;
1651
37.6k
        bytestream_put_be16(&s->buf, JPEG2000_SOD);
1652
37.6k
        if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1653
20
            return ret;
1654
37.6k
        bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1655
37.6k
    }
1656
7.95k
    if (s->buf_end - s->buf < 2)
1657
3
        return -1;
1658
7.95k
    bytestream_put_be16(&s->buf, JPEG2000_EOC);
1659
1660
7.95k
    if (s->format == CODEC_JP2)
1661
7.95k
        update_size(jp2cstart, s->buf);
1662
1663
7.95k
    av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1664
7.95k
    pkt->size = s->buf - s->buf_start;
1665
7.95k
    *got_packet = 1;
1666
1667
7.95k
    return 0;
1668
7.95k
}
1669
1670
static int parse_layer_rates(Jpeg2000EncoderContext *s)
1671
570
{
1672
570
    int i;
1673
570
    char *token;
1674
570
    char *saveptr = NULL;
1675
570
    int rate;
1676
570
    int nlayers = 0;
1677
570
    if (!s->lr_str) {
1678
570
        s->nlayers = 1;
1679
570
        s->layer_rates[0] = 0;
1680
570
        s->compression_rate_enc = 0;
1681
570
        return 0;
1682
570
    }
1683
1684
0
    token = av_strtok(s->lr_str, ",", &saveptr);
1685
0
    if (token && (rate = strtol(token, NULL, 10))) {
1686
0
            s->layer_rates[0] = rate <= 1 ? 0:rate;
1687
0
            nlayers++;
1688
0
    } else {
1689
0
            return AVERROR_INVALIDDATA;
1690
0
    }
1691
1692
0
    while (1) {
1693
0
        token = av_strtok(NULL, ",", &saveptr);
1694
0
        if (!token)
1695
0
            break;
1696
0
        if (rate = strtol(token, NULL, 10)) {
1697
0
            if (nlayers >= 100) {
1698
0
                return AVERROR_INVALIDDATA;
1699
0
            }
1700
0
            s->layer_rates[nlayers] = rate <= 1 ? 0:rate;
1701
0
            nlayers++;
1702
0
        } else {
1703
0
            return AVERROR_INVALIDDATA;
1704
0
        }
1705
0
    }
1706
1707
0
    for (i = 1; i < nlayers; i++) {
1708
0
        if (s->layer_rates[i] >= s->layer_rates[i-1]) {
1709
0
            return AVERROR_INVALIDDATA;
1710
0
        }
1711
0
    }
1712
0
    s->nlayers = nlayers;
1713
0
    s->compression_rate_enc = 1;
1714
0
    return 0;
1715
0
}
1716
1717
static av_cold int j2kenc_init(AVCodecContext *avctx)
1718
570
{
1719
570
    static AVOnce init_static_once = AV_ONCE_INIT;
1720
570
    int i, ret;
1721
570
    Jpeg2000EncoderContext *s = avctx->priv_data;
1722
570
    Jpeg2000CodingStyle *codsty = &s->codsty;
1723
570
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1724
570
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1725
1726
570
    s->avctx = avctx;
1727
570
    av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1728
570
    if (parse_layer_rates(s)) {
1729
0
        av_log(avctx, AV_LOG_WARNING, "Layer rates invalid. Encoding with 1 layer based on quality metric.\n");
1730
0
        s->nlayers = 1;
1731
0
        s->layer_rates[0] = 0;
1732
0
        s->compression_rate_enc = 0;
1733
0
    }
1734
1735
570
    if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (s->pred != FF_DWT97_INT || s->format != CODEC_JP2)) {
1736
85
        av_log(s->avctx, AV_LOG_WARNING, "Forcing lossless jp2 for pal8\n");
1737
85
        s->pred = 1;
1738
85
        s->format = CODEC_JP2;
1739
85
    }
1740
1741
    // defaults:
1742
    // TODO: implement setting non-standard precinct size
1743
570
    memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1744
570
    memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1745
570
    codsty->nreslevels2decode=
1746
570
    codsty->nreslevels       = 7;
1747
570
    codsty->nlayers          = s->nlayers;
1748
570
    codsty->log2_cblk_width  = 4;
1749
570
    codsty->log2_cblk_height = 4;
1750
570
    codsty->transform        = s->pred ? FF_DWT53 : FF_DWT97_INT;
1751
1752
570
    qntsty->nguardbits       = 1;
1753
1754
570
    if ((s->tile_width  & (s->tile_width -1)) ||
1755
570
        (s->tile_height & (s->tile_height-1))) {
1756
0
        av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
1757
0
    }
1758
1759
570
    if (codsty->transform == FF_DWT53)
1760
85
        qntsty->quantsty = JPEG2000_QSTY_NONE;
1761
485
    else
1762
485
        qntsty->quantsty = JPEG2000_QSTY_SE;
1763
1764
570
    s->width = avctx->width;
1765
570
    s->height = avctx->height;
1766
1767
570
    s->ncomponents = desc->nb_components;
1768
2.85k
    for (i = 0; i < 4; i++) {
1769
2.28k
        s->cbps[i] = desc->comp[i].depth;
1770
2.28k
        s->comp_remap[i] = i; //default
1771
2.28k
    }
1772
1773
570
    if ((desc->flags & AV_PIX_FMT_FLAG_PLANAR) && s->ncomponents > 1) {
1774
185
        s->planar = 1;
1775
185
        ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
1776
185
                                               s->chroma_shift, s->chroma_shift + 1);
1777
185
        if (ret)
1778
0
            return ret;
1779
185
        if (desc->flags & AV_PIX_FMT_FLAG_RGB) {
1780
23
            s->comp_remap[0] = 2;
1781
23
            s->comp_remap[1] = 0;
1782
23
            s->comp_remap[2] = 1;
1783
23
        }
1784
185
    }
1785
1786
570
    ff_thread_once(&init_static_once, init_luts);
1787
1788
570
    init_quantization(s);
1789
570
    if ((ret=init_tiles(s)) < 0)
1790
0
        return ret;
1791
1792
570
    av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1793
1794
570
    return 0;
1795
570
}
1796
1797
static int j2kenc_destroy(AVCodecContext *avctx)
1798
570
{
1799
570
    Jpeg2000EncoderContext *s = avctx->priv_data;
1800
1801
570
    cleanup(s);
1802
570
    return 0;
1803
570
}
1804
1805
// taken from the libopenjpeg wrapper so it matches
1806
1807
#define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1808
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1809
static const AVOption options[] = {
1810
    { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, .unit = "format"      },
1811
    { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, .unit = "format"      },
1812
    { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, .unit = "format"      },
1813
    { "tile_width",    "Tile Width",        OFFSET(tile_width),    AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1814
    { "tile_height",   "Tile Height",       OFFSET(tile_height),   AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1815
    { "pred",          "DWT Type",          OFFSET(pred),          AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, .unit = "pred"        },
1816
    { "dwt97int",      NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, .unit = "pred"        },
1817
    { "dwt53",         NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 1           }, INT_MIN, INT_MAX,       VE, .unit = "pred"        },
1818
    { "sop",           "SOP marker",        OFFSET(sop),           AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, },
1819
    { "eph",           "EPH marker",        OFFSET(eph),           AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, },
1820
    { "prog",          "Progression Order", OFFSET(prog),          AV_OPT_TYPE_INT,   { .i64 = 0           }, JPEG2000_PGOD_LRCP,         JPEG2000_PGOD_CPRL,           VE, .unit = "prog" },
1821
    { "lrcp",          NULL,                0,                     AV_OPT_TYPE_CONST,  { .i64 = JPEG2000_PGOD_LRCP }, 0,         0,           VE, .unit = "prog" },
1822
    { "rlcp",          NULL,                0,                     AV_OPT_TYPE_CONST,  { .i64 = JPEG2000_PGOD_RLCP }, 0,         0,           VE, .unit = "prog" },
1823
    { "rpcl",          NULL,                0,                     AV_OPT_TYPE_CONST,  { .i64 = JPEG2000_PGOD_RPCL }, 0,         0,           VE, .unit = "prog" },
1824
    { "pcrl",          NULL,                0,                     AV_OPT_TYPE_CONST,  { .i64 = JPEG2000_PGOD_PCRL }, 0,         0,           VE, .unit = "prog" },
1825
    { "cprl",          NULL,                0,                     AV_OPT_TYPE_CONST,  { .i64 = JPEG2000_PGOD_CPRL }, 0,         0,           VE, .unit = "prog" },
1826
    { "layer_rates",   "Layer Rates",       OFFSET(lr_str),        AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
1827
    { NULL }
1828
};
1829
1830
static const AVClass j2k_class = {
1831
    .class_name = "jpeg 2000 encoder",
1832
    .item_name  = av_default_item_name,
1833
    .option     = options,
1834
    .version    = LIBAVUTIL_VERSION_INT,
1835
};
1836
1837
const FFCodec ff_jpeg2000_encoder = {
1838
    .p.name         = "jpeg2000",
1839
    CODEC_LONG_NAME("JPEG 2000"),
1840
    .p.type         = AVMEDIA_TYPE_VIDEO,
1841
    .p.id           = AV_CODEC_ID_JPEG2000,
1842
    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE |
1843
                      AV_CODEC_CAP_FRAME_THREADS,
1844
    .priv_data_size = sizeof(Jpeg2000EncoderContext),
1845
    .init           = j2kenc_init,
1846
    FF_CODEC_ENCODE_CB(encode_frame),
1847
    .close          = j2kenc_destroy,
1848
    CODEC_PIXFMTS(
1849
        AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB48,
1850
        AV_PIX_FMT_GBR24P,AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
1851
        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
1852
        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV420P16,
1853
        AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV422P16,
1854
        AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV444P9, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV444P16,
1855
        AV_PIX_FMT_YUV440P,                      AV_PIX_FMT_YUV440P10, AV_PIX_FMT_YUV440P12,
1856
        AV_PIX_FMT_YUV411P,
1857
        AV_PIX_FMT_YUV410P,
1858
        AV_PIX_FMT_YA8,                                           AV_PIX_FMT_YA16,
1859
        AV_PIX_FMT_RGBA,                                          AV_PIX_FMT_RGBA64,
1860
        AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
1861
        AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
1862
        AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P16,
1863
        AV_PIX_FMT_YUVA444P, AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P16,
1864
1865
        AV_PIX_FMT_PAL8),
1866
    .color_ranges   = AVCOL_RANGE_MPEG,
1867
    .p.priv_class   = &j2k_class,
1868
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
1869
};