Coverage Report

Created: 2026-01-16 07:48

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