GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/jpeglsenc.c Lines: 191 236 80.9 %
Date: 2021-04-20 15:25:36 Branches: 109 162 67.3 %

Line Branch Exec Source
1
/*
2
 * JPEG-LS encoder
3
 * Copyright (c) 2003 Michael Niedermayer
4
 * Copyright (c) 2006 Konstantin Shishkov
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
/**
24
 * @file
25
 * JPEG-LS encoder.
26
 */
27
28
#include "avcodec.h"
29
#include "bytestream.h"
30
#include "get_bits.h"
31
#include "put_bits.h"
32
#include "golomb.h"
33
#include "internal.h"
34
#include "mathops.h"
35
#include "mjpeg.h"
36
#include "mjpegenc.h"
37
#include "jpegls.h"
38
39
typedef struct JPEGLSContext {
40
    AVClass *class;
41
42
    int pred;
43
} JPEGLSContext;
44
45
600
static inline void put_marker_byteu(PutByteContext *pb, enum JpegMarker code)
46
{
47
600
    bytestream2_put_byteu(pb, 0xff);
48
600
    bytestream2_put_byteu(pb, code);
49
600
}
50
51
200
static inline void put_marker_byte(PutByteContext *pb, enum JpegMarker code)
52
{
53
200
    bytestream2_put_byte(pb, 0xff);
54
200
    bytestream2_put_byte(pb, code);
55
200
}
56
57
/**
58
 * Encode error from regular symbol
59
 */
60
43082291
static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
61
                                     int err)
62
{
63
    int k;
64
    int val;
65
    int map;
66
67
157370825
    for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
68
        ;
69
70

43082291
    map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
71
72
43082291
    if (err < 0)
73
22103040
        err += state->range;
74
43082291
    if (err >= (state->range + 1 >> 1)) {
75
22391239
        err -= state->range;
76
22391239
        val  = 2 * FFABS(err) - 1 - map;
77
    } else
78
20691052
        val = 2 * err + map;
79
80
43082291
    set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
81
82
43082291
    ff_jpegls_update_state_regular(state, Q, err);
83
43082291
}
84
85
/**
86
 * Encode error from run termination
87
 */
88
511058
static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
89
                                     int RItype, int err, int limit_add)
90
{
91
    int k;
92
    int val, map;
93
511058
    int Q = 365 + RItype;
94
    int temp;
95
96
511058
    temp = state->A[Q];
97
511058
    if (RItype)
98
285855
        temp += state->N[Q] >> 1;
99
2112443
    for (k = 0; (state->N[Q] << k) < temp; k++)
100
        ;
101
511058
    map = 0;
102

511058
    if (!k && err && (2 * state->B[Q] < state->N[Q]))
103
3887
        map = 1;
104
105
511058
    if (err < 0)
106
224602
        val = -(2 * err) - 1 - RItype + map;
107
    else
108
286456
        val = 2 * err - RItype - map;
109
511058
    set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
110
111
511058
    if (err < 0)
112
224602
        state->B[Q]++;
113
511058
    state->A[Q] += (val + 1 - RItype) >> 1;
114
115
511058
    ff_jpegls_downscale_state(state, Q);
116
511058
}
117
118
/**
119
 * Encode run value as specified by JPEG-LS standard
120
 */
121
516421
static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run,
122
                                 int comp, int trail)
123
{
124
983239
    while (run >= (1 << ff_log2_run[state->run_index[comp]])) {
125
466818
        put_bits(pb, 1, 1);
126
466818
        run -= 1 << ff_log2_run[state->run_index[comp]];
127
466818
        if (state->run_index[comp] < 31)
128
466818
            state->run_index[comp]++;
129
    }
130
    /* if hit EOL, encode another full run, else encode aborted run */
131

516421
    if (!trail && run) {
132
4162
        put_bits(pb, 1, 1);
133
512259
    } else if (trail) {
134
511058
        put_bits(pb, 1, 0);
135
511058
        if (ff_log2_run[state->run_index[comp]])
136
414758
            put_bits(pb, ff_log2_run[state->run_index[comp]], run);
137
    }
138
516421
}
139
140
/**
141
 * Encode one line of image
142
 */
143
134700
static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
144
                                  void *tmp, const void *in, int last2, int w,
145
                                  int stride, int comp, int bits)
146
{
147
134700
    int x = 0;
148
134700
    int Ra = R(tmp, 0), Rb, Rc = last2, Rd;
149
    int D0, D1, D2;
150
151
43728049
    while (x < w) {
152
        int err, pred, sign;
153
154
        /* compute gradients */
155
43598712
        Rb = R(tmp, x);
156

43598712
        Rd = (x >= w - stride) ? R(tmp, x) : R(tmp, x + stride);
157
43598712
        D0 = Rd - Rb;
158
43598712
        D1 = Rb - Rc;
159
43598712
        D2 = Rc - Ra;
160
161
        /* run mode */
162
43598712
        if ((FFABS(D0) <= state->near) &&
163
4643505
            (FFABS(D1) <= state->near) &&
164
2133452
            (FFABS(D2) <= state->near)) {
165
            int RUNval, RItype, run;
166
167
516421
            run    = 0;
168
516421
            RUNval = Ra;
169

2715672
            while (x < w && (FFABS(R(in, x) - RUNval) <= state->near)) {
170
2199251
                run++;
171
2199251
                W(tmp, x, Ra);
172
2199251
                x += stride;
173
            }
174
516421
            ls_encode_run(state, pb, run, comp, x < w);
175
516421
            if (x >= w)
176
5363
                return;
177
511058
            Rb     = R(tmp, x);
178
511058
            RItype = FFABS(Ra - Rb) <= state->near;
179
511058
            pred   = RItype ? Ra : Rb;
180
511058
            err    = R(in, x) - pred;
181
182

511058
            if (!RItype && Ra > Rb)
183
145241
                err = -err;
184
185
511058
            if (state->near) {
186
                if (err > 0)
187
                    err =  (state->near + err) / state->twonear;
188
                else
189
                    err = -(state->near - err) / state->twonear;
190
191
                if (RItype || (Rb >= Ra))
192
                    Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
193
                else
194
                    Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
195
            } else
196
511058
                Ra = R(in, x);
197
511058
            W(tmp, x, Ra);
198
199
511058
            if (err < 0)
200
228701
                err += state->range;
201
511058
            if (err >= state->range + 1 >> 1)
202
224602
                err -= state->range;
203
204
511058
            ls_encode_runterm(state, pb, RItype, err,
205
511058
                              ff_log2_run[state->run_index[comp]]);
206
207
511058
            if (state->run_index[comp] > 0)
208
464801
                state->run_index[comp]--;
209
        } else { /* regular mode */
210
            int context;
211
212
43082291
            context = ff_jpegls_quantize(state, D0) * 81 +
213
43082291
                      ff_jpegls_quantize(state, D1) *  9 +
214
43082291
                      ff_jpegls_quantize(state, D2);
215
43082291
            pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
216
217
43082291
            if (context < 0) {
218
17406898
                context = -context;
219
17406898
                sign    = 1;
220
17406898
                pred    = av_clip(pred - state->C[context], 0, state->maxval);
221
17406898
                err     = pred - R(in, x);
222
            } else {
223
25675393
                sign = 0;
224
25675393
                pred = av_clip(pred + state->C[context], 0, state->maxval);
225
25675393
                err  = R(in, x) - pred;
226
            }
227
228
43082291
            if (state->near) {
229
                if (err > 0)
230
                    err =  (state->near + err) / state->twonear;
231
                else
232
                    err = -(state->near - err) / state->twonear;
233
                if (!sign)
234
                    Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
235
                else
236
                    Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
237
            } else
238
43082291
                Ra = R(in, x);
239
43082291
            W(tmp, x, Ra);
240
241
43082291
            ls_encode_regular(state, pb, context, err);
242
        }
243
43593349
        Rc = Rb;
244
43593349
        x += stride;
245
    }
246
}
247
248
200
static void ls_store_lse(JLSState *state, PutByteContext *pb)
249
{
250
    /* Test if we have default params and don't need to store LSE */
251
200
    JLSState state2 = { 0 };
252
200
    state2.bpp  = state->bpp;
253
200
    state2.near = state->near;
254
200
    ff_jpegls_reset_coding_parameters(&state2, 1);
255
200
    if (state->T1 == state2.T1 &&
256
200
        state->T2 == state2.T2 &&
257
200
        state->T3 == state2.T3 &&
258
200
        state->reset == state2.reset)
259
200
        return;
260
    /* store LSE type 1 */
261
    put_marker_byteu(pb, LSE);
262
    bytestream2_put_be16u(pb, 13);
263
    bytestream2_put_byteu(pb, 1);
264
    bytestream2_put_be16u(pb, state->maxval);
265
    bytestream2_put_be16u(pb, state->T1);
266
    bytestream2_put_be16u(pb, state->T2);
267
    bytestream2_put_be16u(pb, state->T3);
268
    bytestream2_put_be16u(pb, state->reset);
269
}
270
271
200
static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
272
                             const AVFrame *pict, int *got_packet)
273
{
274
200
    JPEGLSContext *ctx = avctx->priv_data;
275
200
    const AVFrame *const p = pict;
276
    PutByteContext pb;
277
    PutBitContext pb2;
278
    GetBitContext gb;
279
    const uint8_t *in;
280
200
    uint8_t *last = NULL;
281
200
    JLSState state = { 0 };
282
    int i, size, ret;
283
    int comps;
284
285
#if FF_API_PRIVATE_OPT
286
FF_DISABLE_DEPRECATION_WARNINGS
287
200
    if (avctx->prediction_method)
288
        ctx->pred = avctx->prediction_method;
289
FF_ENABLE_DEPRECATION_WARNINGS
290
#endif
291
292
200
    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
293
200
        avctx->pix_fmt == AV_PIX_FMT_GRAY16)
294
        comps = 1;
295
    else
296
200
        comps = 3;
297
298
200
    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width  *avctx->height * comps * 4 +
299
                                AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
300
        return ret;
301
302
200
    last = av_malloc((unsigned)pkt->size + FFABS(p->linesize[0]));
303
200
    if (!last)
304
        return AVERROR(ENOMEM);
305
200
    memset(last, 0, FFABS(p->linesize[0]));
306
307
200
    bytestream2_init_writer(&pb, pkt->data, pkt->size);
308
200
    init_put_bits(&pb2, last + FFABS(p->linesize[0]), pkt->size);
309
310
    /* write our own JPEG header, can't use mjpeg_picture_header */
311
200
    put_marker_byteu(&pb, SOI);
312
200
    put_marker_byteu(&pb, SOF48);
313
200
    bytestream2_put_be16u(&pb, 8 + comps * 3); // header size depends on components
314
200
    bytestream2_put_byteu(&pb, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8);  // bpp
315
200
    bytestream2_put_be16u(&pb, avctx->height);
316
200
    bytestream2_put_be16u(&pb, avctx->width);
317
200
    bytestream2_put_byteu(&pb, comps);          // components
318
800
    for (i = 1; i <= comps; i++) {
319
600
        bytestream2_put_byteu(&pb, i);     // component ID
320
600
        bytestream2_put_byteu(&pb, 0x11);  // subsampling: none
321
600
        bytestream2_put_byteu(&pb, 0);     // Tiq, used by JPEG-LS ext
322
    }
323
324
200
    put_marker_byteu(&pb, SOS);
325
200
    bytestream2_put_be16u(&pb, 6 + comps * 2);
326
200
    bytestream2_put_byteu(&pb, comps);
327
800
    for (i = 1; i <= comps; i++) {
328
600
        bytestream2_put_byteu(&pb, i);   // component ID
329
600
        bytestream2_put_byteu(&pb, 0);   // mapping index: none
330
    }
331
200
    bytestream2_put_byteu(&pb, ctx->pred);
332
200
    bytestream2_put_byteu(&pb, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line
333
200
    bytestream2_put_byteu(&pb, 0);  // point transform: none
334
335
    /* initialize JPEG-LS state from JPEG parameters */
336
200
    state.near = ctx->pred;
337
200
    state.bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
338
200
    ff_jpegls_reset_coding_parameters(&state, 0);
339
200
    ff_jpegls_init_state(&state);
340
341
200
    ls_store_lse(&state, &pb);
342
343
200
    in = p->data[0];
344
200
    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
345
        int t = 0;
346
347
        for (i = 0; i < avctx->height; i++) {
348
            int last0 = last[0];
349
            ls_encode_line(&state, &pb2, last, in, t, avctx->width, 1, 0, 8);
350
            t   = last0;
351
            in += p->linesize[0];
352
        }
353
200
    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
354
        int t = 0;
355
356
        for (i = 0; i < avctx->height; i++) {
357
            int last0 = *((uint16_t *)last);
358
            ls_encode_line(&state, &pb2, last, in, t, avctx->width, 1, 0, 16);
359
            t   = last0;
360
            in += p->linesize[0];
361
        }
362
200
    } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
363
        int j, width;
364
200
        int Rc[3] = { 0, 0, 0 };
365
366
200
        width = avctx->width * 3;
367
45100
        for (i = 0; i < avctx->height; i++) {
368
179600
            for (j = 0; j < 3; j++) {
369
134700
                int last0 = last[j];
370
134700
                ls_encode_line(&state, &pb2, last + j, in + j, Rc[j],
371
                               width, 3, j, 8);
372
134700
                Rc[j] = last0;
373
            }
374
44900
            in += p->linesize[0];
375
        }
376
    } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {
377
        int j, width;
378
        int Rc[3] = { 0, 0, 0 };
379
380
        width = avctx->width * 3;
381
        for (i = 0; i < avctx->height; i++) {
382
            for (j = 2; j >= 0; j--) {
383
                int last0 = last[j];
384
                ls_encode_line(&state, &pb2, last + j, in + j, Rc[j],
385
                               width, 3, j, 8);
386
                Rc[j] = last0;
387
            }
388
            in += p->linesize[0];
389
        }
390
    }
391
392
    /* the specification says that after doing 0xff escaping unused bits in
393
     * the last byte must be set to 0, so just append 7 "optional" zero bits
394
     * to avoid special-casing. */
395
200
    put_bits(&pb2, 7, 0);
396
200
    size = put_bits_count(&pb2);
397
200
    flush_put_bits(&pb2);
398
    /* do escape coding */
399
200
    init_get_bits(&gb, pb2.buf, size);
400
200
    size -= 7;
401
25690223
    while (get_bits_count(&gb) < size) {
402
        int v;
403
25690023
        v = get_bits(&gb, 8);
404
25690023
        bytestream2_put_byte(&pb, v);
405
25690023
        if (v == 0xFF) {
406
144308
            v = get_bits(&gb, 7);
407
144308
            bytestream2_put_byte(&pb, v);
408
        }
409
    }
410
200
    av_freep(&last);
411
412
    /* End of image */
413
200
    put_marker_byte(&pb, EOI);
414
415
200
    emms_c();
416
417
200
    pkt->size   = bytestream2_tell_p(&pb);
418
200
    pkt->flags |= AV_PKT_FLAG_KEY;
419
200
    *got_packet = 1;
420
200
    return 0;
421
}
422
423
4
static av_cold int encode_init_ls(AVCodecContext *ctx)
424
{
425
#if FF_API_CODED_FRAME
426
FF_DISABLE_DEPRECATION_WARNINGS
427
4
    ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
428
4
    ctx->coded_frame->key_frame = 1;
429
FF_ENABLE_DEPRECATION_WARNINGS
430
#endif
431
432
4
    return 0;
433
}
434
435
#define OFFSET(x) offsetof(JPEGLSContext, x)
436
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
437
static const AVOption options[] = {
438
{ "pred", "Prediction method", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "pred" },
439
    { "left",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
440
    { "plane",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "pred" },
441
    { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "pred" },
442
443
    { NULL},
444
};
445
446
static const AVClass jpegls_class = {
447
    .class_name = "jpegls",
448
    .item_name  = av_default_item_name,
449
    .option     = options,
450
    .version    = LIBAVUTIL_VERSION_INT,
451
};
452
453
AVCodec ff_jpegls_encoder = {
454
    .name           = "jpegls",
455
    .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
456
    .type           = AVMEDIA_TYPE_VIDEO,
457
    .id             = AV_CODEC_ID_JPEGLS,
458
    .priv_data_size = sizeof(JPEGLSContext),
459
    .priv_class     = &jpegls_class,
460
    .init           = encode_init_ls,
461
    .capabilities   = AV_CODEC_CAP_FRAME_THREADS,
462
    .encode2        = encode_picture_ls,
463
    .pix_fmts       = (const enum AVPixelFormat[]) {
464
        AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
465
        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
466
        AV_PIX_FMT_NONE
467
    },
468
    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
469
                      FF_CODEC_CAP_INIT_CLEANUP,
470
};