GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/j2kenc.c Lines: 577 660 87.4 %
Date: 2019-11-20 04:07:19 Branches: 303 378 80.2 %

Line Branch Exec 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
 * All rights reserved.
36
 *
37
 * Redistribution and use in source and binary forms, with or without
38
 * modification, are permitted provided that the following conditions
39
 * are met:
40
 * 1. Redistributions of source code must retain the above copyright
41
 *    notice, this list of conditions and the following disclaimer.
42
 * 2. Redistributions in binary form must reproduce the above copyright
43
 *    notice, this list of conditions and the following disclaimer in the
44
 *    documentation and/or other materials provided with the distribution.
45
 *
46
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
47
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
50
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
56
 * POSSIBILITY OF SUCH DAMAGE.
57
 */
58
59
60
/**
61
 * JPEG2000 image encoder
62
 * @file
63
 * @author Kamil Nowosad
64
 */
65
66
#include <float.h>
67
#include "avcodec.h"
68
#include "internal.h"
69
#include "bytestream.h"
70
#include "jpeg2000.h"
71
#include "libavutil/common.h"
72
#include "libavutil/pixdesc.h"
73
#include "libavutil/opt.h"
74
#include "libavutil/intreadwrite.h"
75
76
#define NMSEDEC_BITS 7
77
#define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
78
#define WMSEDEC_SHIFT 13 ///< must be >= 13
79
#define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
80
81
#define CODEC_JP2 1
82
#define CODEC_J2K 0
83
84
static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
85
           lut_nmsedec_ref0[1<<NMSEDEC_BITS],
86
           lut_nmsedec_sig [1<<NMSEDEC_BITS],
87
           lut_nmsedec_sig0[1<<NMSEDEC_BITS];
88
89
static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
90
    {{10000, 19650, 41770,  84030, 169000, 338400,  676900, 1353000, 2706000, 5409000},
91
     {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
92
     {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
93
     {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
94
95
    {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
96
     {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
97
     {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
98
     { 7186,  9218, 15860, 30430,  60190, 120100, 240000, 479700,  959300}}
99
};
100
101
typedef struct {
102
   Jpeg2000Component *comp;
103
} Jpeg2000Tile;
104
105
typedef struct {
106
    AVClass *class;
107
    AVCodecContext *avctx;
108
    const AVFrame *picture;
109
110
    int width, height; ///< image width and height
111
    uint8_t cbps[4]; ///< bits per sample in particular components
112
    int chroma_shift[2];
113
    uint8_t planar;
114
    int ncomponents;
115
    int tile_width, tile_height; ///< tile size
116
    int numXtiles, numYtiles;
117
118
    uint8_t *buf_start;
119
    uint8_t *buf;
120
    uint8_t *buf_end;
121
    int bit_index;
122
123
    int64_t lambda;
124
125
    Jpeg2000CodingStyle codsty;
126
    Jpeg2000QuantStyle  qntsty;
127
128
    Jpeg2000Tile *tile;
129
130
    int format;
131
    int pred;
132
} Jpeg2000EncoderContext;
133
134
135
/* debug */
136
#if 0
137
#undef ifprintf
138
#undef printf
139
140
static void nspaces(FILE *fd, int n)
141
{
142
    while(n--) putc(' ', fd);
143
}
144
145
static void printcomp(Jpeg2000Component *comp)
146
{
147
    int i;
148
    for (i = 0; i < comp->y1 - comp->y0; i++)
149
        ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
150
}
151
152
static void dump(Jpeg2000EncoderContext *s, FILE *fd)
153
{
154
    int tileno, compno, reslevelno, bandno, precno;
155
    fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
156
                "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
157
                "tiles:\n",
158
            s->width, s->height, s->tile_width, s->tile_height,
159
            s->numXtiles, s->numYtiles, s->ncomponents);
160
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
161
        Jpeg2000Tile *tile = s->tile + tileno;
162
        nspaces(fd, 2);
163
        fprintf(fd, "tile %d:\n", tileno);
164
        for(compno = 0; compno < s->ncomponents; compno++){
165
            Jpeg2000Component *comp = tile->comp + compno;
166
            nspaces(fd, 4);
167
            fprintf(fd, "component %d:\n", compno);
168
            nspaces(fd, 4);
169
            fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
170
                        comp->x0, comp->x1, comp->y0, comp->y1);
171
            for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
172
                Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
173
                nspaces(fd, 6);
174
                fprintf(fd, "reslevel %d:\n", reslevelno);
175
                nspaces(fd, 6);
176
                fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
177
                        reslevel->x0, reslevel->x1, reslevel->y0,
178
                        reslevel->y1, reslevel->nbands);
179
                for(bandno = 0; bandno < reslevel->nbands; bandno++){
180
                    Jpeg2000Band *band = reslevel->band + bandno;
181
                    nspaces(fd, 8);
182
                    fprintf(fd, "band %d:\n", bandno);
183
                    nspaces(fd, 8);
184
                    fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
185
                                "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
186
                                band->x0, band->x1,
187
                                band->y0, band->y1,
188
                                band->codeblock_width, band->codeblock_height,
189
                                band->cblknx, band->cblkny);
190
                    for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
191
                        Jpeg2000Prec *prec = band->prec + precno;
192
                        nspaces(fd, 10);
193
                        fprintf(fd, "prec %d:\n", precno);
194
                        nspaces(fd, 10);
195
                        fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
196
                                     prec->xi0, prec->xi1, prec->yi0, prec->yi1);
197
                    }
198
                }
199
            }
200
        }
201
    }
202
}
203
#endif
204
205
/* bitstream routines */
206
207
/** put n times val bit */
208
7048069
static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
209
{
210
13874133
    while (n-- > 0){
211
6826064
        if (s->bit_index == 8)
212
        {
213
837227
            s->bit_index = *s->buf == 0xff;
214
837227
            *(++s->buf) = 0;
215
        }
216
6826064
        *s->buf |= val << (7 - s->bit_index++);
217
    }
218
7048069
}
219
220
/** put n least significant bits of a number num */
221
691538
static void put_num(Jpeg2000EncoderContext *s, int num, int n)
222
{
223
4972270
    while(--n >= 0)
224
4280732
        put_bits(s, (num >> n) & 1, 1);
225
691538
}
226
227
/** flush the bitstream */
228
27300
static void j2k_flush(Jpeg2000EncoderContext *s)
229
{
230
27300
    if (s->bit_index){
231
27300
        s->bit_index = 0;
232
27300
        s->buf++;
233
    }
234
27300
}
235
236
/* tag tree routines */
237
238
/** code the value stored in node */
239
759169
static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
240
{
241
    Jpeg2000TgtNode *stack[30];
242
759169
    int sp = 1, curval = 0;
243
759169
    stack[0] = node;
244
245
759169
    node = node->parent;
246
1058065
    while(node){
247
917643
        if (node->vis){
248
618747
            curval = node->val;
249
618747
            break;
250
        }
251
298896
        node->vis++;
252
298896
        stack[sp++] = node;
253
298896
        node = node->parent;
254
    }
255
1749603
    while(--sp >= 0){
256
1058065
        if (stack[sp]->val >= threshold){
257
67631
            put_bits(s, 0, threshold - curval);
258
67631
            break;
259
        }
260
990434
        put_bits(s, 0, stack[sp]->val - curval);
261
990434
        put_bits(s, 1, 1);
262
990434
        curval = stack[sp]->val;
263
    }
264
759169
}
265
266
/** update the value in node */
267
826800
static void tag_tree_update(Jpeg2000TgtNode *node)
268
{
269
826800
    int lev = 0;
270
826800
    while (node->parent){
271
747000
        if (node->parent->val <= node->val)
272
747000
            break;
273
        node->parent->val = node->val;
274
        node = node->parent;
275
        lev++;
276
    }
277
826800
}
278
279
400
static int put_siz(Jpeg2000EncoderContext *s)
280
{
281
    int i;
282
283
400
    if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
284
        return -1;
285
286
400
    bytestream_put_be16(&s->buf, JPEG2000_SIZ);
287
400
    bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
288
400
    bytestream_put_be16(&s->buf, 0); // Rsiz
289
400
    bytestream_put_be32(&s->buf, s->width); // width
290
400
    bytestream_put_be32(&s->buf, s->height); // height
291
400
    bytestream_put_be32(&s->buf, 0); // X0Siz
292
400
    bytestream_put_be32(&s->buf, 0); // Y0Siz
293
294
400
    bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
295
400
    bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
296
400
    bytestream_put_be32(&s->buf, 0); // XT0Siz
297
400
    bytestream_put_be32(&s->buf, 0); // YT0Siz
298
400
    bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
299
300
1600
    for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
301
1200
        bytestream_put_byte(&s->buf, 7);
302
1200
        bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
303
1200
        bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
304
    }
305
400
    return 0;
306
}
307
308
400
static int put_cod(Jpeg2000EncoderContext *s)
309
{
310
400
    Jpeg2000CodingStyle *codsty = &s->codsty;
311
312
400
    if (s->buf_end - s->buf < 14)
313
        return -1;
314
315
400
    bytestream_put_be16(&s->buf, JPEG2000_COD);
316
400
    bytestream_put_be16(&s->buf, 12); // Lcod
317
400
    bytestream_put_byte(&s->buf, 0);  // Scod
318
    // SGcod
319
400
    bytestream_put_byte(&s->buf, 0); // progression level
320
400
    bytestream_put_be16(&s->buf, 1); // num of layers
321
400
    if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
322
        bytestream_put_byte(&s->buf, 0); // unspecified
323
    }else{
324
400
        bytestream_put_byte(&s->buf, 0); // unspecified
325
    }
326
    // SPcod
327
400
    bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
328
400
    bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
329
400
    bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
330
400
    bytestream_put_byte(&s->buf, 0); // cblk style
331
400
    bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
332
400
    return 0;
333
}
334
335
400
static int put_qcd(Jpeg2000EncoderContext *s, int compno)
336
{
337
    int i, size;
338
400
    Jpeg2000CodingStyle *codsty = &s->codsty;
339
400
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
340
341
400
    if (qntsty->quantsty == JPEG2000_QSTY_NONE)
342
200
        size = 4 + 3 * (codsty->nreslevels-1);
343
    else // QSTY_SE
344
200
        size = 5 + 6 * (codsty->nreslevels-1);
345
346
400
    if (s->buf_end - s->buf < size + 2)
347
        return -1;
348
349
400
    bytestream_put_be16(&s->buf, JPEG2000_QCD);
350
400
    bytestream_put_be16(&s->buf, size);  // LQcd
351
400
    bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty);  // Sqcd
352
400
    if (qntsty->quantsty == JPEG2000_QSTY_NONE)
353
4000
        for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
354
3800
            bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
355
    else // QSTY_SE
356
4000
        for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
357
3800
            bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
358
400
    return 0;
359
}
360
361
400
static int put_com(Jpeg2000EncoderContext *s, int compno)
362
{
363
400
    int size = 4 + strlen(LIBAVCODEC_IDENT);
364
365
400
    if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
366
400
        return 0;
367
368
    if (s->buf_end - s->buf < size + 2)
369
        return -1;
370
371
    bytestream_put_be16(&s->buf, JPEG2000_COM);
372
    bytestream_put_be16(&s->buf, size);
373
    bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
374
375
    bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
376
377
    return 0;
378
}
379
380
1300
static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
381
{
382
    uint8_t *psotptr;
383
384
1300
    if (s->buf_end - s->buf < 12)
385
        return NULL;
386
387
1300
    bytestream_put_be16(&s->buf, JPEG2000_SOT);
388
1300
    bytestream_put_be16(&s->buf, 10); // Lsot
389
1300
    bytestream_put_be16(&s->buf, tileno); // Isot
390
391
1300
    psotptr = s->buf;
392
1300
    bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
393
394
1300
    bytestream_put_byte(&s->buf, 0); // TPsot
395
1300
    bytestream_put_byte(&s->buf, 1); // TNsot
396
1300
    return psotptr;
397
}
398
399
/**
400
 * compute the sizes of tiles, resolution levels, bands, etc.
401
 * allocate memory for them
402
 * divide the input image into tile-components
403
 */
404
8
static int init_tiles(Jpeg2000EncoderContext *s)
405
{
406
    int tileno, tilex, tiley, compno;
407
8
    Jpeg2000CodingStyle *codsty = &s->codsty;
408
8
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
409
410
8
    s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
411
8
    s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
412
413
8
    s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
414
8
    if (!s->tile)
415
        return AVERROR(ENOMEM);
416
22
    for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
417
40
        for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
418
26
            Jpeg2000Tile *tile = s->tile + tileno;
419
420
26
            tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
421
26
            if (!tile->comp)
422
                return AVERROR(ENOMEM);
423
104
            for (compno = 0; compno < s->ncomponents; compno++){
424
78
                Jpeg2000Component *comp = tile->comp + compno;
425
                int ret, i, j;
426
427
78
                comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
428
78
                comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
429
78
                comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
430
78
                comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
431
78
                if (compno > 0)
432
156
                    for (i = 0; i < 2; i++)
433
312
                        for (j = 0; j < 2; j++)
434
208
                            comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
435
436

208
                if ((ret = ff_jpeg2000_init_component(comp,
437
                                                codsty,
438
                                                qntsty,
439
78
                                                s->cbps[compno],
440
52
                                                compno?1<<s->chroma_shift[0]:1,
441
52
                                                compno?1<<s->chroma_shift[1]:1,
442
                                                s->avctx
443
                                               )) < 0)
444
                    return ret;
445
            }
446
        }
447
8
    return 0;
448
}
449
450
400
static void copy_frame(Jpeg2000EncoderContext *s)
451
{
452
    int tileno, compno, i, y, x;
453
    uint8_t *line;
454
1700
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
455
1300
        Jpeg2000Tile *tile = s->tile + tileno;
456
1300
        if (s->planar){
457
            for (compno = 0; compno < s->ncomponents; compno++){
458
                Jpeg2000Component *comp = tile->comp + compno;
459
                int *dst = comp->i_data;
460
                line = s->picture->data[compno]
461
                       + comp->coord[1][0] * s->picture->linesize[compno]
462
                       + comp->coord[0][0];
463
                for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){
464
                    uint8_t *ptr = line;
465
                    for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)
466
                        *dst++ = *ptr++ - (1 << 7);
467
                    line += s->picture->linesize[compno];
468
                }
469
            }
470
        } else{
471
1300
            line = s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0]
472
1300
                   + tile->comp[0].coord[0][0] * s->ncomponents;
473
474
1300
            i = 0;
475
177500
            for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){
476
176200
                uint8_t *ptr = line;
477
30704600
                for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){
478
122113600
                    for (compno = 0; compno < s->ncomponents; compno++){
479
91585200
                        tile->comp[compno].i_data[i] = *ptr++  - (1 << 7);
480
                    }
481
                }
482
176200
                line += s->picture->linesize[0];
483
            }
484
        }
485
    }
486
400
}
487
488
8
static void init_quantization(Jpeg2000EncoderContext *s)
489
{
490
    int compno, reslevelno, bandno;
491
8
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
492
8
    Jpeg2000CodingStyle *codsty = &s->codsty;
493
494
32
    for (compno = 0; compno < s->ncomponents; compno++){
495
24
        int gbandno = 0;
496
192
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
497
168
            int nbands, lev = codsty->nreslevels - reslevelno - 1;
498
168
            nbands = reslevelno ? 3 : 1;
499
624
            for (bandno = 0; bandno < nbands; bandno++, gbandno++){
500
456
                int expn, mant = 0;
501
502
456
                if (codsty->transform == FF_DWT97_INT){
503
228
                    int bandpos = bandno + (reslevelno>0),
504
228
                        ss = 81920000 / dwt_norms[0][bandpos][lev],
505
228
                        log = av_log2(ss);
506
228
                    mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
507
228
                    expn = s->cbps[compno] - log + 13;
508
                } else
509
228
                    expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
510
511
456
                qntsty->expn[gbandno] = expn;
512
456
                qntsty->mant[gbandno] = mant;
513
            }
514
        }
515
    }
516
8
}
517
518
8
static void init_luts(void)
519
{
520
    int i, a,
521
8
        mask = ~((1<<NMSEDEC_FRACBITS)-1);
522
523
1032
    for (i = 0; i < (1 << NMSEDEC_BITS); i++){
524
1024
        lut_nmsedec_sig[i]  = FFMAX(6*i - (9<<NMSEDEC_FRACBITS-1) << 12-NMSEDEC_FRACBITS, 0);
525
1024
        lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
526
527
1024
        a = (i >> (NMSEDEC_BITS-2)&2) + 1;
528
1024
        lut_nmsedec_ref[i]  = FFMAX((-2*i + (1<<NMSEDEC_FRACBITS) + a*i - (a*a<<NMSEDEC_FRACBITS-2))
529
                                    << 13-NMSEDEC_FRACBITS, 0);
530
1024
        lut_nmsedec_ref0[i] = FFMAX(((i*i + (1-4*i << NMSEDEC_FRACBITS-1) + (1<<2*NMSEDEC_FRACBITS)) & mask)
531
                                    << 1, 0);
532
    }
533
8
}
534
535
/* tier-1 routines */
536
73779107
static int getnmsedec_sig(int x, int bpno)
537
{
538
73779107
    if (bpno > NMSEDEC_FRACBITS)
539
57508511
        return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
540
16270596
    return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
541
}
542
543
155371831
static int getnmsedec_ref(int x, int bpno)
544
{
545
155371831
    if (bpno > NMSEDEC_FRACBITS)
546
97863320
        return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
547
57508511
    return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
548
}
549
550
2341659
static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
551
{
552
2341659
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
553
10642563
    for (y0 = 0; y0 < height; y0 += 4)
554
133682311
        for (x = 0; x < width; x++)
555

624667412
            for (y = y0; y < height && y < y0+4; y++){
556

499286005
                if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
557
163633824
                    int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
558
163633824
                        bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
559
163633824
                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
560
163633824
                    if (bit){
561
                        int xorbit;
562
59386202
                        int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
563
59386202
                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
564
59386202
                        *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
565
59386202
                        ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
566
                    }
567
163633824
                    t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
568
                }
569
            }
570
2341659
}
571
572
2341659
static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
573
{
574
2341659
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
575
10642563
    for (y0 = 0; y0 < height; y0 += 4)
576
133682311
        for (x = 0; x < width; x++)
577

624667412
            for (y = y0; y < height && y < y0+4; y++)
578
499286005
                if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
579
155371831
                    int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
580
155371831
                    *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
581
155371831
                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
582
155371831
                    t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
583
                }
584
2341659
}
585
586
2755058
static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
587
{
588
2755058
    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
589
12558961
    for (y0 = 0; y0 < height; y0 += 4)
590
158157809
        for (x = 0; x < width; x++){
591
148353906
            if (y0 + 3 < height && !(
592
147328814
            (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
593
57872409
            (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
594
52649523
            (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
595
48304510
            (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
596
3619464
            {
597
                // aggregation mode
598
                int rlen;
599
221843104
                for (rlen = 0; rlen < 4; rlen++)
600
179323436
                    if (t1->data[(y0+rlen) * t1->stride + x] & mask)
601
3619464
                        break;
602
46139132
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
603
46139132
                if (rlen == 4)
604
42519668
                    continue;
605
3619464
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
606
3619464
                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
607
12472020
                for (y = y0 + rlen; y < y0 + 4; y++){
608
8852556
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
609
8852556
                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
610
8852556
                        if (y > y0 + rlen)
611
5233092
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
612
8852556
                        if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
613
                            int xorbit;
614
4325058
                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
615
4325058
                            *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
616
4325058
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
617
4325058
                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
618
                        }
619
                    }
620
8852556
                    t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
621
                }
622
            } else{
623

508529450
                for (y = y0; y < y0 + 4 && y < height; y++){
624
406314676
                    if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
625
87309021
                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
626
87309021
                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
627
87309021
                        if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
628
                            int xorbit;
629
10067847
                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
630
10067847
                            *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
631
10067847
                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
632
10067847
                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
633
                        }
634
                    }
635
406314676
                    t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
636
                }
637
            }
638
        }
639
2755058
}
640
641
413400
static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
642
                        int width, int height, int bandpos, int lev)
643
{
644
413400
    int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
645
413400
    int64_t wmsedec = 0;
646
647
413400
    memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
648
649
6372900
    for (y = 0; y < height; y++){
650
97544700
        for (x = 0; x < width; x++){
651
91585200
            if (t1->data[(y) * t1->stride + x] < 0){
652
35748311
                t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
653
35748311
                t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
654
            }
655
91585200
            max = FFMAX(max, t1->data[(y) * t1->stride + x]);
656
        }
657
    }
658
659
413400
    if (max == 0){
660
51
        cblk->nonzerobits = 0;
661
51
        bpno = 0;
662
    } else{
663
413349
        cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
664
413349
        bpno = cblk->nonzerobits - 1;
665
    }
666
667
413400
    cblk->data[0] = 0;
668
413400
    ff_mqc_initenc(&t1->mqc, cblk->data + 1);
669
670
7851776
    for (passno = 0; bpno >= 0; passno++){
671
7438376
        nmsedec=0;
672
673

7438376
        switch(pass_t){
674
2341659
            case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
675
2341659
                    break;
676
2341659
            case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
677
2341659
                    break;
678
2755058
            case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
679
2755058
                    break;
680
        }
681
682
7438376
        cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
683
7438376
        wmsedec += (int64_t)nmsedec << (2*bpno);
684
7438376
        cblk->passes[passno].disto = wmsedec;
685
686
7438376
        if (++pass_t == 3){
687
2755058
            pass_t = 0;
688
2755058
            bpno--;
689
        }
690
    }
691
413400
    cblk->npasses = passno;
692
413400
    cblk->ninclpasses = passno;
693
694
413400
    if (passno)
695
413399
        cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
696
413400
}
697
698
/* tier-2 routines: */
699
700
345769
static void putnumpasses(Jpeg2000EncoderContext *s, int n)
701
{
702
345769
    if (n == 1)
703
19966
        put_num(s, 0, 1);
704
325803
    else if (n == 2)
705
12191
        put_num(s, 2, 2);
706
313612
    else if (n <= 5)
707
103883
        put_num(s, 0xc | (n-3), 4);
708
209729
    else if (n <= 36)
709
209726
        put_num(s, 0x1e0 | (n-6), 9);
710
    else
711
3
        put_num(s, 0xff80 | (n-37), 16);
712
345769
}
713
714
715
27300
static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int precno,
716
                          uint8_t *expn, int numgbits)
717
{
718
27300
    int bandno, empty = 1;
719
720
    // init bitstream
721
27300
    *s->buf = 0;
722
27300
    s->bit_index = 0;
723
724
    // header
725
726
    // is the packet empty?
727
27300
    for (bandno = 0; bandno < rlevel->nbands; bandno++){
728
27300
        if (rlevel->band[bandno].coord[0][0] < rlevel->band[bandno].coord[0][1]
729
27300
        &&  rlevel->band[bandno].coord[1][0] < rlevel->band[bandno].coord[1][1]){
730
27300
            empty = 0;
731
27300
            break;
732
        }
733
    }
734
735
27300
    put_bits(s, !empty, 1);
736
27300
    if (empty){
737
        j2k_flush(s);
738
        return 0;
739
    }
740
741
101400
    for (bandno = 0; bandno < rlevel->nbands; bandno++){
742
74100
        Jpeg2000Band *band = rlevel->band + bandno;
743
74100
        Jpeg2000Prec *prec = band->prec + precno;
744
        int yi, xi, pos;
745
74100
        int cblknw = prec->nb_codeblocks_width;
746
747
74100
        if (band->coord[0][0] == band->coord[0][1]
748
74100
        ||  band->coord[1][0] == band->coord[1][1])
749
3600
            continue;
750
751
201300
        for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
752
544200
            for (xi = 0; xi < cblknw; xi++, pos++){
753
413400
                prec->cblkincl[pos].val = prec->cblk[yi * cblknw + xi].ninclpasses == 0;
754
413400
                tag_tree_update(prec->cblkincl + pos);
755
413400
                prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - prec->cblk[yi * cblknw + xi].nonzerobits;
756
413400
                tag_tree_update(prec->zerobits + pos);
757
            }
758
        }
759
760
201300
        for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++){
761
544200
            for (xi = 0; xi < cblknw; xi++, pos++){
762
413400
                int pad = 0, llen, length;
763
413400
                Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
764
765
413400
                if (s->buf_end - s->buf < 20) // approximately
766
                    return -1;
767
768
                // inclusion information
769
413400
                tag_tree_code(s, prec->cblkincl + pos, 1);
770
413400
                if (!cblk->ninclpasses)
771
67631
                    continue;
772
                // zerobits information
773
345769
                tag_tree_code(s, prec->zerobits + pos, 100);
774
                // number of passes
775
345769
                putnumpasses(s, cblk->ninclpasses);
776
777
345769
                length = cblk->passes[cblk->ninclpasses-1].rate;
778
345769
                llen = av_log2(length) - av_log2(cblk->ninclpasses) - 2;
779
345769
                if (llen < 0){
780
98010
                    pad = -llen;
781
98010
                    llen = 0;
782
                }
783
                // length of code block
784
345769
                put_bits(s, 1, llen);
785
345769
                put_bits(s, 0, 1);
786
345769
                put_num(s, length, av_log2(length)+1+pad);
787
            }
788
        }
789
    }
790
27300
    j2k_flush(s);
791
101400
    for (bandno = 0; bandno < rlevel->nbands; bandno++){
792
74100
        Jpeg2000Band *band = rlevel->band + bandno;
793
74100
        Jpeg2000Prec *prec = band->prec + precno;
794
74100
        int yi, cblknw = prec->nb_codeblocks_width;
795
208500
        for (yi =0; yi < prec->nb_codeblocks_height; yi++){
796
            int xi;
797
551400
            for (xi = 0; xi < cblknw; xi++){
798
417000
                Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
799
417000
                if (cblk->ninclpasses){
800
345769
                    if (s->buf_end - s->buf < cblk->passes[cblk->ninclpasses-1].rate)
801
                        return -1;
802
345769
                    bytestream_put_buffer(&s->buf, cblk->data + 1,   cblk->passes[cblk->ninclpasses-1].rate
803
345769
                                                               - cblk->passes[cblk->ninclpasses-1].flushed_len);
804
345769
                    bytestream_put_buffer(&s->buf, cblk->passes[cblk->ninclpasses-1].flushed,
805
345769
                                                   cblk->passes[cblk->ninclpasses-1].flushed_len);
806
                }
807
            }
808
        }
809
    }
810
27300
    return 0;
811
}
812
813
1300
static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
814
{
815
    int compno, reslevelno, ret;
816
1300
    Jpeg2000CodingStyle *codsty = &s->codsty;
817
1300
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
818
819
1300
    av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
820
    // lay-rlevel-comp-pos progression
821
10400
    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
822
36400
        for (compno = 0; compno < s->ncomponents; compno++){
823
            int precno;
824
27300
            Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
825
54600
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
826
27300
                if ((ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
827
27300
                              qntsty->nguardbits)) < 0)
828
                    return ret;
829
            }
830
        }
831
    }
832
1300
    av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
833
1300
    return 0;
834
}
835
836
417000
static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
837
{
838
417000
    int passno, res = 0;
839
7855376
    for (passno = 0; passno < cblk->npasses; passno++){
840
        int dr;
841
        int64_t dd;
842
843
14876752
        dr = cblk->passes[passno].rate
844
7438376
           - (res ? cblk->passes[res-1].rate:0);
845
14876752
        dd = cblk->passes[passno].disto
846
7438376
           - (res ? cblk->passes[res-1].disto:0);
847
848
7438376
        if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
849
2504255
            res = passno+1;
850
    }
851
417000
    return res;
852
}
853
854
1300
static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
855
{
856
    int precno, compno, reslevelno, bandno, cblkno, lev;
857
1300
    Jpeg2000CodingStyle *codsty = &s->codsty;
858
859
5200
    for (compno = 0; compno < s->ncomponents; compno++){
860
3900
        Jpeg2000Component *comp = tile->comp + compno;
861
862
31200
        for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
863
27300
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
864
865
54600
            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
866
101400
                for (bandno = 0; bandno < reslevel->nbands ; bandno++){
867
74100
                    int bandpos = bandno + (reslevelno > 0);
868
74100
                    Jpeg2000Band *band = reslevel->band + bandno;
869
74100
                    Jpeg2000Prec *prec = band->prec + precno;
870
871
491100
                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
872
417000
                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;
873
874
417000
                        cblk->ninclpasses = getcut(cblk, s->lambda,
875
417000
                                (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
876
                    }
877
                }
878
            }
879
        }
880
    }
881
1300
}
882
883
1300
static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
884
{
885
    int compno, reslevelno, bandno, ret;
886
    Jpeg2000T1Context t1;
887
1300
    Jpeg2000CodingStyle *codsty = &s->codsty;
888
5200
    for (compno = 0; compno < s->ncomponents; compno++){
889
3900
        Jpeg2000Component *comp = s->tile[tileno].comp + compno;
890
891
3900
        t1.stride = (1<<codsty->log2_cblk_width) + 2;
892
893
3900
        av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
894
3900
        if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
895
            return ret;
896
3900
        av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
897
898
31200
        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
899
27300
            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
900
901
101400
            for (bandno = 0; bandno < reslevel->nbands ; bandno++){
902
74100
                Jpeg2000Band *band = reslevel->band + bandno;
903
74100
                Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
904
74100
                int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
905
74100
                yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
906
74100
                y0 = yy0;
907
74100
                yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
908
74100
                            band->coord[1][1]) - band->coord[1][0] + yy0;
909
910

74100
                if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
911
3600
                    continue;
912
913
70500
                bandpos = bandno + (reslevelno > 0);
914
915
201300
                for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
916

130800
                    if (reslevelno == 0 || bandno == 1)
917
45600
                        xx0 = 0;
918
                    else
919
85200
                        xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
920
130800
                    x0 = xx0;
921
130800
                    xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
922
130800
                                band->coord[0][1]) - band->coord[0][0] + xx0;
923
924
544200
                    for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
925
                        int y, x;
926
413400
                        if (codsty->transform == FF_DWT53){
927
3186450
                            for (y = yy0; y < yy1; y++){
928
2979750
                                int *ptr = t1.data + (y-yy0)*t1.stride;
929
48772350
                                for (x = xx0; x < xx1; x++){
930
45792600
                                    *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] << NMSEDEC_FRACBITS;
931
                                }
932
                            }
933
                        } else{
934
3186450
                            for (y = yy0; y < yy1; y++){
935
2979750
                                int *ptr = t1.data + (y-yy0)*t1.stride;
936
48772350
                                for (x = xx0; x < xx1; x++){
937
45792600
                                    *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
938
45792600
                                    *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
939
45792600
                                    ptr++;
940
                                }
941
                            }
942
                        }
943
413400
                        if (!prec->cblk[cblkno].data)
944
8268
                            prec->cblk[cblkno].data = av_malloc(1 + 8192);
945
413400
                        if (!prec->cblk[cblkno].passes)
946
8268
                            prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
947

413400
                        if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
948
                            return AVERROR(ENOMEM);
949
413400
                        encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
950
413400
                                    bandpos, codsty->nreslevels - reslevelno - 1);
951
413400
                        xx0 = xx1;
952
413400
                        xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
953
                    }
954
130800
                    yy0 = yy1;
955
130800
                    yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
956
                }
957
            }
958
        }
959
3900
        av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
960
    }
961
962
1300
    av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
963
1300
    truncpasses(s, tile);
964
1300
    if ((ret = encode_packets(s, tile, tileno)) < 0)
965
        return ret;
966
1300
    av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
967
1300
    return 0;
968
}
969
970
8
static void cleanup(Jpeg2000EncoderContext *s)
971
{
972
    int tileno, compno;
973
8
    Jpeg2000CodingStyle *codsty = &s->codsty;
974
975
34
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
976
104
        for (compno = 0; compno < s->ncomponents; compno++){
977
78
            Jpeg2000Component *comp = s->tile[tileno].comp + compno;
978
78
            ff_jpeg2000_cleanup(comp, codsty);
979
        }
980
26
        av_freep(&s->tile[tileno].comp);
981
    }
982
8
    av_freep(&s->tile);
983
8
}
984
985
400
static void reinit(Jpeg2000EncoderContext *s)
986
{
987
    int tileno, compno;
988
1700
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
989
1300
        Jpeg2000Tile *tile = s->tile + tileno;
990
5200
        for (compno = 0; compno < s->ncomponents; compno++)
991
3900
            ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
992
    }
993
400
}
994
995
2000
static void update_size(uint8_t *size, const uint8_t *end)
996
{
997
2000
    AV_WB32(size, end-size);
998
2000
}
999
1000
400
static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1001
                        const AVFrame *pict, int *got_packet)
1002
{
1003
    int tileno, ret;
1004
400
    Jpeg2000EncoderContext *s = avctx->priv_data;
1005
    uint8_t *chunkstart, *jp2cstart, *jp2hstart;
1006
1007
400
    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
1008
        return ret;
1009
1010
    // init:
1011
400
    s->buf = s->buf_start = pkt->data;
1012
400
    s->buf_end = pkt->data + pkt->size;
1013
1014
400
    s->picture = pict;
1015
1016
400
    s->lambda = s->picture->quality * LAMBDA_SCALE;
1017
1018
400
    copy_frame(s);
1019
400
    reinit(s);
1020
1021
400
    if (s->format == CODEC_JP2) {
1022
400
        av_assert0(s->buf == pkt->data);
1023
1024
400
        bytestream_put_be32(&s->buf, 0x0000000C);
1025
400
        bytestream_put_be32(&s->buf, 0x6A502020);
1026
400
        bytestream_put_be32(&s->buf, 0x0D0A870A);
1027
1028
400
        chunkstart = s->buf;
1029
400
        bytestream_put_be32(&s->buf, 0);
1030
400
        bytestream_put_buffer(&s->buf, "ftyp", 4);
1031
400
        bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
1032
400
        bytestream_put_be32(&s->buf, 0);
1033
400
        bytestream_put_buffer(&s->buf, "jp2\040", 4);
1034
400
        update_size(chunkstart, s->buf);
1035
1036
400
        jp2hstart = s->buf;
1037
400
        bytestream_put_be32(&s->buf, 0);
1038
400
        bytestream_put_buffer(&s->buf, "jp2h", 4);
1039
1040
400
        chunkstart = s->buf;
1041
400
        bytestream_put_be32(&s->buf, 0);
1042
400
        bytestream_put_buffer(&s->buf, "ihdr", 4);
1043
400
        bytestream_put_be32(&s->buf, avctx->height);
1044
400
        bytestream_put_be32(&s->buf, avctx->width);
1045
400
        bytestream_put_be16(&s->buf, s->ncomponents);
1046
400
        bytestream_put_byte(&s->buf, s->cbps[0]);
1047
400
        bytestream_put_byte(&s->buf, 7);
1048
400
        bytestream_put_byte(&s->buf, 0);
1049
400
        bytestream_put_byte(&s->buf, 0);
1050
400
        update_size(chunkstart, s->buf);
1051
1052
400
        chunkstart = s->buf;
1053
400
        bytestream_put_be32(&s->buf, 0);
1054
400
        bytestream_put_buffer(&s->buf, "colr", 4);
1055
400
        bytestream_put_byte(&s->buf, 1);
1056
400
        bytestream_put_byte(&s->buf, 0);
1057
400
        bytestream_put_byte(&s->buf, 0);
1058

400
        if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1059
400
            bytestream_put_be32(&s->buf, 16);
1060
        } else if (s->ncomponents == 1) {
1061
            bytestream_put_be32(&s->buf, 17);
1062
        } else {
1063
            bytestream_put_be32(&s->buf, 18);
1064
        }
1065
400
        update_size(chunkstart, s->buf);
1066
400
        if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1067
            int i;
1068
            uint8_t *palette = pict->data[1];
1069
            chunkstart = s->buf;
1070
            bytestream_put_be32(&s->buf, 0);
1071
            bytestream_put_buffer(&s->buf, "pclr", 4);
1072
            bytestream_put_be16(&s->buf, AVPALETTE_COUNT);
1073
            bytestream_put_byte(&s->buf, 3); // colour channels
1074
            bytestream_put_be24(&s->buf, 0x070707); //colour depths
1075
            for (i = 0; i < AVPALETTE_COUNT; i++) {
1076
                bytestream_put_be24(&s->buf, HAVE_BIGENDIAN ? AV_RB24(palette + 1) : AV_RL24(palette));
1077
                palette += 4;
1078
            }
1079
            update_size(chunkstart, s->buf);
1080
            chunkstart = s->buf;
1081
            bytestream_put_be32(&s->buf, 0);
1082
            bytestream_put_buffer(&s->buf, "cmap", 4);
1083
            for (i = 0; i < 3; i++) {
1084
                bytestream_put_be16(&s->buf, 0); // component
1085
                bytestream_put_byte(&s->buf, 1); // palette mapping
1086
                bytestream_put_byte(&s->buf, i); // index
1087
            }
1088
            update_size(chunkstart, s->buf);
1089
        }
1090
400
        update_size(jp2hstart, s->buf);
1091
1092
400
        jp2cstart = s->buf;
1093
400
        bytestream_put_be32(&s->buf, 0);
1094
400
        bytestream_put_buffer(&s->buf, "jp2c", 4);
1095
    }
1096
1097
400
    if (s->buf_end - s->buf < 2)
1098
        return -1;
1099
400
    bytestream_put_be16(&s->buf, JPEG2000_SOC);
1100
400
    if ((ret = put_siz(s)) < 0)
1101
        return ret;
1102
400
    if ((ret = put_cod(s)) < 0)
1103
        return ret;
1104
400
    if ((ret = put_qcd(s, 0)) < 0)
1105
        return ret;
1106
400
    if ((ret = put_com(s, 0)) < 0)
1107
        return ret;
1108
1109
1700
    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
1110
        uint8_t *psotptr;
1111
1300
        if (!(psotptr = put_sot(s, tileno)))
1112
            return -1;
1113
1300
        if (s->buf_end - s->buf < 2)
1114
            return -1;
1115
1300
        bytestream_put_be16(&s->buf, JPEG2000_SOD);
1116
1300
        if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
1117
            return ret;
1118
1300
        bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
1119
    }
1120
400
    if (s->buf_end - s->buf < 2)
1121
        return -1;
1122
400
    bytestream_put_be16(&s->buf, JPEG2000_EOC);
1123
1124
400
    if (s->format == CODEC_JP2)
1125
400
        update_size(jp2cstart, s->buf);
1126
1127
400
    av_log(s->avctx, AV_LOG_DEBUG, "end\n");
1128
400
    pkt->size = s->buf - s->buf_start;
1129
400
    pkt->flags |= AV_PKT_FLAG_KEY;
1130
400
    *got_packet = 1;
1131
1132
400
    return 0;
1133
}
1134
1135
8
static av_cold int j2kenc_init(AVCodecContext *avctx)
1136
{
1137
    int i, ret;
1138
8
    Jpeg2000EncoderContext *s = avctx->priv_data;
1139
8
    Jpeg2000CodingStyle *codsty = &s->codsty;
1140
8
    Jpeg2000QuantStyle  *qntsty = &s->qntsty;
1141
1142
8
    s->avctx = avctx;
1143
8
    av_log(s->avctx, AV_LOG_DEBUG, "init\n");
1144
1145
#if FF_API_PRIVATE_OPT
1146
FF_DISABLE_DEPRECATION_WARNINGS
1147
8
    if (avctx->prediction_method)
1148
        s->pred = avctx->prediction_method;
1149
FF_ENABLE_DEPRECATION_WARNINGS
1150
#endif
1151
1152

8
    if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (s->pred != FF_DWT97_INT || s->format != CODEC_JP2)) {
1153
        av_log(s->avctx, AV_LOG_WARNING, "Forcing lossless jp2 for pal8\n");
1154
        s->pred = FF_DWT97_INT;
1155
        s->format = CODEC_JP2;
1156
    }
1157
1158
    // defaults:
1159
    // TODO: implement setting non-standard precinct size
1160
8
    memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
1161
8
    memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
1162
8
    codsty->nreslevels2decode=
1163
8
    codsty->nreslevels       = 7;
1164
8
    codsty->log2_cblk_width  = 4;
1165
8
    codsty->log2_cblk_height = 4;
1166
8
    codsty->transform        = s->pred ? FF_DWT53 : FF_DWT97_INT;
1167
1168
8
    qntsty->nguardbits       = 1;
1169
1170
8
    if ((s->tile_width  & (s->tile_width -1)) ||
1171
8
        (s->tile_height & (s->tile_height-1))) {
1172
        av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
1173
    }
1174
1175
8
    if (codsty->transform == FF_DWT53)
1176
4
        qntsty->quantsty = JPEG2000_QSTY_NONE;
1177
    else
1178
4
        qntsty->quantsty = JPEG2000_QSTY_SE;
1179
1180
8
    s->width = avctx->width;
1181
8
    s->height = avctx->height;
1182
1183
32
    for (i = 0; i < 3; i++)
1184
24
        s->cbps[i] = 8;
1185
1186
8
    if (avctx->pix_fmt == AV_PIX_FMT_RGB24){
1187
8
        s->ncomponents = 3;
1188
    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_PAL8){
1189
        s->ncomponents = 1;
1190
    } else{ // planar YUV
1191
        s->planar = 1;
1192
        s->ncomponents = 3;
1193
        ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
1194
                                               s->chroma_shift, s->chroma_shift + 1);
1195
        if (ret)
1196
            return ret;
1197
    }
1198
1199
8
    ff_jpeg2000_init_tier1_luts();
1200
8
    ff_mqc_init_context_tables();
1201
8
    init_luts();
1202
1203
8
    init_quantization(s);
1204
8
    if ((ret=init_tiles(s)) < 0)
1205
        return ret;
1206
1207
8
    av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
1208
1209
8
    return 0;
1210
}
1211
1212
8
static int j2kenc_destroy(AVCodecContext *avctx)
1213
{
1214
8
    Jpeg2000EncoderContext *s = avctx->priv_data;
1215
1216
8
    cleanup(s);
1217
8
    return 0;
1218
}
1219
1220
// taken from the libopenjpeg wraper so it matches
1221
1222
#define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
1223
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1224
static const AVOption options[] = {
1225
    { "format",        "Codec Format",      OFFSET(format),        AV_OPT_TYPE_INT,   { .i64 = CODEC_JP2   }, CODEC_J2K, CODEC_JP2,   VE, "format"      },
1226
    { "j2k",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K   }, 0,         0,           VE, "format"      },
1227
    { "jp2",           NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2   }, 0,         0,           VE, "format"      },
1228
    { "tile_width",    "Tile Width",        OFFSET(tile_width),    AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1229
    { "tile_height",   "Tile Height",       OFFSET(tile_height),   AV_OPT_TYPE_INT,   { .i64 = 256         }, 1,     1<<30,           VE, },
1230
    { "pred",          "DWT Type",          OFFSET(pred),          AV_OPT_TYPE_INT,   { .i64 = 0           }, 0,         1,           VE, "pred"        },
1231
    { "dwt97int",      NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
1232
    { "dwt53",         NULL,                0,                     AV_OPT_TYPE_CONST, { .i64 = 0           }, INT_MIN, INT_MAX,       VE, "pred"        },
1233
1234
    { NULL }
1235
};
1236
1237
static const AVClass j2k_class = {
1238
    .class_name = "jpeg 2000 encoder",
1239
    .item_name  = av_default_item_name,
1240
    .option     = options,
1241
    .version    = LIBAVUTIL_VERSION_INT,
1242
};
1243
1244
AVCodec ff_jpeg2000_encoder = {
1245
    .name           = "jpeg2000",
1246
    .long_name      = NULL_IF_CONFIG_SMALL("JPEG 2000"),
1247
    .type           = AVMEDIA_TYPE_VIDEO,
1248
    .id             = AV_CODEC_ID_JPEG2000,
1249
    .priv_data_size = sizeof(Jpeg2000EncoderContext),
1250
    .init           = j2kenc_init,
1251
    .encode2        = encode_frame,
1252
    .close          = j2kenc_destroy,
1253
    .pix_fmts       = (const enum AVPixelFormat[]) {
1254
        AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
1255
        AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
1256
        AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
1257
        AV_PIX_FMT_PAL8,
1258
        AV_PIX_FMT_NONE
1259
    },
1260
    .priv_class     = &j2k_class,
1261
};