jpeglsenc.c 14.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * JPEG-LS encoder
 * Copyright (c) 2003 Michael Niedermayer
 * Copyright (c) 2006 Konstantin Shishkov
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
24
 * @file
25 26 27 28
 * JPEG-LS encoder.
 */

#include "avcodec.h"
29
#include "get_bits.h"
30
#include "put_bits.h"
31
#include "golomb.h"
32
#include "internal.h"
33
#include "mathops.h"
34
#include "mjpeg.h"
35
#include "mjpegenc.h"
36 37
#include "jpegls.h"

38 39 40 41 42 43
typedef struct JPEGLSContext {
    AVClass *class;

    int pred;
} JPEGLSContext;

44 45 46
/**
 * Encode error from regular symbol
 */
47 48 49
static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
                                     int err)
{
50 51 52 53
    int k;
    int val;
    int map;

54 55
    for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
        ;
56 57 58

    map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);

59
    if (err < 0)
60
        err += state->range;
61
    if (err >= (state->range + 1 >> 1)) {
62
        err -= state->range;
63
        val  = 2 * FFABS(err) - 1 - map;
64 65 66 67 68 69 70 71 72 73 74
    } else
        val = 2 * err + map;

    set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);

    ff_jpegls_update_state_regular(state, Q, err);
}

/**
 * Encode error from run termination
 */
75 76 77
static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
                                     int RItype, int err, int limit_add)
{
78 79 80 81 82 83
    int k;
    int val, map;
    int Q = 365 + RItype;
    int temp;

    temp = state->A[Q];
84
    if (RItype)
85
        temp += state->N[Q] >> 1;
86 87
    for (k = 0; (state->N[Q] << k) < temp; k++)
        ;
88
    map = 0;
89
    if (!k && err && (2 * state->B[Q] < state->N[Q]))
90 91
        map = 1;

92 93
    if (err < 0)
        val = -(2 * err) - 1 - RItype + map;
94 95 96 97
    else
        val = 2 * err - RItype - map;
    set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);

98
    if (err < 0)
99 100 101 102 103 104 105 106 107
        state->B[Q]++;
    state->A[Q] += (val + 1 - RItype) >> 1;

    ff_jpegls_downscale_state(state, Q);
}

/**
 * Encode run value as specified by JPEG-LS standard
 */
108 109 110 111
static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run,
                                 int comp, int trail)
{
    while (run >= (1 << ff_log2_run[state->run_index[comp]])) {
112 113
        put_bits(pb, 1, 1);
        run -= 1 << ff_log2_run[state->run_index[comp]];
114
        if (state->run_index[comp] < 31)
115 116 117
            state->run_index[comp]++;
    }
    /* if hit EOL, encode another full run, else encode aborted run */
118
    if (!trail && run) {
119
        put_bits(pb, 1, 1);
120
    } else if (trail) {
121
        put_bits(pb, 1, 0);
122
        if (ff_log2_run[state->run_index[comp]])
123 124 125 126 127 128 129
            put_bits(pb, ff_log2_run[state->run_index[comp]], run);
    }
}

/**
 * Encode one line of image
 */
130 131 132 133
static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
                                  void *last, void *cur, int last2, int w,
                                  int stride, int comp, int bits)
{
134 135 136 137
    int x = 0;
    int Ra, Rb, Rc, Rd;
    int D0, D1, D2;

138
    while (x < w) {
139 140 141 142 143 144 145 146 147 148 149 150
        int err, pred, sign;

        /* compute gradients */
        Ra = x ? R(cur, x - stride) : R(last, x);
        Rb = R(last, x);
        Rc = x ? R(last, x - stride) : last2;
        Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
        D0 = Rd - Rb;
        D1 = Rb - Rc;
        D2 = Rc - Ra;

        /* run mode */
151 152 153
        if ((FFABS(D0) <= state->near) &&
            (FFABS(D1) <= state->near) &&
            (FFABS(D2) <= state->near)) {
154 155
            int RUNval, RItype, run;

156
            run    = 0;
157
            RUNval = Ra;
158
            while (x < w && (FFABS(R(cur, x) - RUNval) <= state->near)) {
159 160 161 162 163
                run++;
                W(cur, x, Ra);
                x += stride;
            }
            ls_encode_run(state, pb, run, comp, x < w);
164
            if (x >= w)
165
                return;
166
            Rb     = R(last, x);
167
            RItype = FFABS(Ra - Rb) <= state->near;
168 169
            pred   = RItype ? Ra : Rb;
            err    = R(cur, x) - pred;
170

171
            if (!RItype && Ra > Rb)
172 173
                err = -err;

174 175 176
            if (state->near) {
                if (err > 0)
                    err =  (state->near + err) / state->twonear;
177 178 179
                else
                    err = -(state->near - err) / state->twonear;

180
                if (RItype || (Rb >= Ra))
181 182 183 184 185
                    Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
                else
                    Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
                W(cur, x, Ra);
            }
186
            if (err < 0)
187
                err += state->range;
188
            if (err >= state->range + 1 >> 1)
189 190
                err -= state->range;

191 192
            ls_encode_runterm(state, pb, RItype, err,
                              ff_log2_run[state->run_index[comp]]);
193

194
            if (state->run_index[comp] > 0)
195 196 197 198
                state->run_index[comp]--;
        } else { /* regular mode */
            int context;

199 200 201 202
            context = ff_jpegls_quantize(state, D0) * 81 +
                      ff_jpegls_quantize(state, D1) *  9 +
                      ff_jpegls_quantize(state, D2);
            pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
203

204
            if (context < 0) {
205
                context = -context;
206 207 208 209
                sign    = 1;
                pred    = av_clip(pred - state->C[context], 0, state->maxval);
                err     = pred - R(cur, x);
            } else {
210 211
                sign = 0;
                pred = av_clip(pred + state->C[context], 0, state->maxval);
212
                err  = R(cur, x) - pred;
213 214
            }

215 216 217
            if (state->near) {
                if (err > 0)
                    err =  (state->near + err) / state->twonear;
218 219
                else
                    err = -(state->near - err) / state->twonear;
220
                if (!sign)
221 222 223 224 225 226 227 228 229 230 231 232
                    Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
                else
                    Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
                W(cur, x, Ra);
            }

            ls_encode_regular(state, pb, context, err);
        }
        x += stride;
    }
}

233 234
static void ls_store_lse(JLSState *state, PutBitContext *pb)
{
235
    /* Test if we have default params and don't need to store LSE */
236
    JLSState state2 = { 0 };
237
    state2.bpp  = state->bpp;
238 239
    state2.near = state->near;
    ff_jpegls_reset_coding_parameters(&state2, 1);
240 241 242 243
    if (state->T1 == state2.T1 &&
        state->T2 == state2.T2 &&
        state->T3 == state2.T3 &&
        state->reset == state2.reset)
244 245 246 247
        return;
    /* store LSE type 1 */
    put_marker(pb, LSE);
    put_bits(pb, 16, 13);
248
    put_bits(pb, 8, 1);
249 250 251 252 253 254 255
    put_bits(pb, 16, state->maxval);
    put_bits(pb, 16, state->T1);
    put_bits(pb, 16, state->T2);
    put_bits(pb, 16, state->T3);
    put_bits(pb, 16, state->reset);
}

256 257 258
static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
                             const AVFrame *pict, int *got_packet)
{
259
    JPEGLSContext *ctx = avctx->priv_data;
260
    const AVFrame *const p = pict;
261 262
    PutBitContext pb, pb2;
    GetBitContext gb;
263
    uint8_t *buf2 = NULL;
264 265 266
    uint8_t *zero = NULL;
    uint8_t *cur  = NULL;
    uint8_t *last = NULL;
267
    JLSState *state = NULL;
268
    int i, size, ret;
269 270
    int comps;

271 272 273 274 275 276 277
#if FF_API_PRIVATE_OPT
FF_DISABLE_DEPRECATION_WARNINGS
    if (avctx->prediction_method)
        ctx->pred = avctx->prediction_method;
FF_ENABLE_DEPRECATION_WARNINGS
#endif

278 279
    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
        avctx->pix_fmt == AV_PIX_FMT_GRAY16)
280 281 282 283
        comps = 1;
    else
        comps = 3;

284
    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width  *avctx->height * comps * 4 +
285
                                AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
286 287 288
        return ret;

    buf2 = av_malloc(pkt->size);
289
    if (!buf2)
290
        goto memfail;
291 292 293 294

    init_put_bits(&pb, pkt->data, pkt->size);
    init_put_bits(&pb2, buf2, pkt->size);

295 296 297 298
    /* write our own JPEG header, can't use mjpeg_picture_header */
    put_marker(&pb, SOI);
    put_marker(&pb, SOF48);
    put_bits(&pb, 16, 8 + comps * 3); // header size depends on components
299
    put_bits(&pb, 8, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8);  // bpp
300 301
    put_bits(&pb, 16, avctx->height);
    put_bits(&pb, 16, avctx->width);
302 303 304 305 306
    put_bits(&pb, 8, comps);          // components
    for (i = 1; i <= comps; i++) {
        put_bits(&pb, 8, i);     // component ID
        put_bits(&pb, 8, 0x11);  // subsampling: none
        put_bits(&pb, 8, 0);     // Tiq, used by JPEG-LS ext
307 308 309 310
    }

    put_marker(&pb, SOS);
    put_bits(&pb, 16, 6 + comps * 2);
311 312 313 314
    put_bits(&pb, 8, comps);
    for (i = 1; i <= comps; i++) {
        put_bits(&pb, 8, i);   // component ID
        put_bits(&pb, 8, 0);   // mapping index: none
315
    }
316
    put_bits(&pb, 8, ctx->pred);
317 318
    put_bits(&pb, 8, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line
    put_bits(&pb, 8, 0);  // point transform: none
319 320

    state = av_mallocz(sizeof(JLSState));
321
    if (!state)
322 323
        goto memfail;

324
    /* initialize JPEG-LS state from JPEG parameters */
325
    state->near = ctx->pred;
326
    state->bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
327 328 329 330 331
    ff_jpegls_reset_coding_parameters(state, 0);
    ff_jpegls_init_state(state);

    ls_store_lse(state, &pb);

332
    zero = last = av_mallocz(FFABS(p->linesize[0]));
333
    if (!zero)
334
        goto memfail;
335

336 337
    cur  = p->data[0];
    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
338 339
        int t = 0;

340 341 342
        for (i = 0; i < avctx->height; i++) {
            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);
            t    = last[0];
343 344 345
            last = cur;
            cur += p->linesize[0];
        }
346
    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
347 348
        int t = 0;

349
        for (i = 0; i < avctx->height; i++) {
350
            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);
351
            t    = *((uint16_t *)last);
352 353 354
            last = cur;
            cur += p->linesize[0];
        }
355
    } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
356
        int j, width;
357
        int Rc[3] = { 0, 0, 0 };
358 359

        width = avctx->width * 3;
360 361 362 363
        for (i = 0; i < avctx->height; i++) {
            for (j = 0; j < 3; j++) {
                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],
                               width, 3, j, 8);
364 365 366
                Rc[j] = last[j];
            }
            last = cur;
367
            cur += p->linesize[0];
368
        }
369
    } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {
370
        int j, width;
371
        int Rc[3] = { 0, 0, 0 };
372 373

        width = avctx->width * 3;
374 375 376 377
        for (i = 0; i < avctx->height; i++) {
            for (j = 2; j >= 0; j--) {
                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],
                               width, 3, j, 8);
378 379 380
                Rc[j] = last[j];
            }
            last = cur;
381
            cur += p->linesize[0];
382 383 384
        }
    }

385 386
    av_freep(&zero);
    av_freep(&state);
387

388
    /* the specification says that after doing 0xff escaping unused bits in
389
     * the last byte must be set to 0, so just append 7 "optional" zero bits
390
     * to avoid special-casing. */
391 392 393 394 395 396
    put_bits(&pb2, 7, 0);
    size = put_bits_count(&pb2);
    flush_put_bits(&pb2);
    /* do escape coding */
    init_get_bits(&gb, buf2, size);
    size -= 7;
397
    while (get_bits_count(&gb) < size) {
398 399 400
        int v;
        v = get_bits(&gb, 8);
        put_bits(&pb, 8, v);
401
        if (v == 0xFF) {
402 403 404 405
            v = get_bits(&gb, 7);
            put_bits(&pb, 8, v);
        }
    }
406
    avpriv_align_put_bits(&pb);
407
    av_freep(&buf2);
408 409 410 411 412 413 414

    /* End of image */
    put_marker(&pb, EOI);
    flush_put_bits(&pb);

    emms_c();

415 416 417 418
    pkt->size   = put_bits_count(&pb) >> 3;
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
    return 0;
419 420

memfail:
421
    av_packet_unref(pkt);
422 423
    av_freep(&buf2);
    av_freep(&state);
424
    av_freep(&zero);
425
    return AVERROR(ENOMEM);
426 427
}

428 429
static av_cold int encode_init_ls(AVCodecContext *ctx)
{
430 431
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
432 433
    ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
    ctx->coded_frame->key_frame = 1;
434 435
FF_ENABLE_DEPRECATION_WARNINGS
#endif
436

437 438 439 440 441 442
    if (ctx->pix_fmt != AV_PIX_FMT_GRAY8  &&
        ctx->pix_fmt != AV_PIX_FMT_GRAY16 &&
        ctx->pix_fmt != AV_PIX_FMT_RGB24  &&
        ctx->pix_fmt != AV_PIX_FMT_BGR24) {
        av_log(ctx, AV_LOG_ERROR,
               "Only grayscale and RGB24/BGR24 images are supported\n");
443 444 445 446 447
        return -1;
    }
    return 0;
}

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
#define OFFSET(x) offsetof(JPEGLSContext, x)
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
{ "pred", "Prediction method", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "pred" },
    { "left",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
    { "plane",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "pred" },
    { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "pred" },

    { NULL},
};

static const AVClass jpegls_class = {
    .class_name = "jpegls",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

466
AVCodec ff_jpegls_encoder = {
467
    .name           = "jpegls",
468
    .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
469
    .type           = AVMEDIA_TYPE_VIDEO,
470
    .id             = AV_CODEC_ID_JPEGLS,
471 472
    .priv_data_size = sizeof(JPEGLSContext),
    .priv_class     = &jpegls_class,
473
    .init           = encode_init_ls,
474
    .capabilities   = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
475
    .encode2        = encode_picture_ls,
476 477 478
    .pix_fmts       = (const enum AVPixelFormat[]) {
        AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
479
        AV_PIX_FMT_NONE
480
    },
481 482
    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
                      FF_CODEC_CAP_INIT_CLEANUP,
483
};