jpeglsenc.c 12.9 KB
Newer Older
1 2 3 4 5
/*
 * JPEG-LS encoder
 * Copyright (c) 2003 Michael Niedermayer
 * Copyright (c) 2006 Konstantin Shishkov
 *
6
 * This file is part of Libav.
7
 *
8
 * Libav is free software; you can redistribute it and/or
9 10 11 12
 * 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.
 *
13
 * Libav is distributed in the hope that it will be useful,
14 15 16 17 18
 * 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
19
 * License along with Libav; if not, write to the Free Software
20 21 22 23
 * 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 "golomb.h"
31
#include "internal.h"
32
#include "mathops.h"
33 34 35 36 37 38
#include "mjpeg.h"
#include "jpegls.h"

/**
 * Encode error from regular symbol
 */
39 40 41
static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
                                     int err)
{
42 43 44 45
    int k;
    int val;
    int map;

46 47
    for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
        ;
48 49 50

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

51
    if (err < 0)
52
        err += state->range;
53
    if (err >= (state->range + 1 >> 1)) {
54
        err -= state->range;
55
        val  = 2 * FFABS(err) - 1 - map;
56 57 58 59 60 61 62 63 64 65 66
    } 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
 */
67 68 69
static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
                                     int RItype, int err, int limit_add)
{
70 71 72 73 74 75
    int k;
    int val, map;
    int Q = 365 + RItype;
    int temp;

    temp = state->A[Q];
76
    if (RItype)
77
        temp += state->N[Q] >> 1;
78 79
    for (k = 0; (state->N[Q] << k) < temp; k++)
        ;
80
    map = 0;
81
    if (!k && err && (2 * state->B[Q] < state->N[Q]))
82 83
        map = 1;

84 85
    if (err < 0)
        val = -(2 * err) - 1 - RItype + map;
86 87 88 89
    else
        val = 2 * err - RItype - map;
    set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);

90
    if (err < 0)
91 92 93 94 95 96 97 98 99
        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
 */
100 101 102 103
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]])) {
104 105
        put_bits(pb, 1, 1);
        run -= 1 << ff_log2_run[state->run_index[comp]];
106
        if (state->run_index[comp] < 31)
107 108 109
            state->run_index[comp]++;
    }
    /* if hit EOL, encode another full run, else encode aborted run */
110
    if (!trail && run) {
111
        put_bits(pb, 1, 1);
112
    } else if (trail) {
113
        put_bits(pb, 1, 0);
114
        if (ff_log2_run[state->run_index[comp]])
115 116 117 118 119 120 121
            put_bits(pb, ff_log2_run[state->run_index[comp]], run);
    }
}

/**
 * Encode one line of image
 */
122 123 124 125
static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
                                  void *last, void *cur, int last2, int w,
                                  int stride, int comp, int bits)
{
126 127 128 129
    int x = 0;
    int Ra, Rb, Rc, Rd;
    int D0, D1, D2;

130
    while (x < w) {
131 132 133 134 135 136 137 138 139 140 141 142
        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 */
143 144 145
        if ((FFABS(D0) <= state->near) &&
            (FFABS(D1) <= state->near) &&
            (FFABS(D2) <= state->near)) {
146 147
            int RUNval, RItype, run;

148
            run    = 0;
149
            RUNval = Ra;
150
            while (x < w && (FFABS(R(cur, x) - RUNval) <= state->near)) {
151 152 153 154 155
                run++;
                W(cur, x, Ra);
                x += stride;
            }
            ls_encode_run(state, pb, run, comp, x < w);
156
            if (x >= w)
157
                return;
158
            Rb     = R(last, x);
159
            RItype = FFABS(Ra - Rb) <= state->near;
160 161
            pred   = RItype ? Ra : Rb;
            err    = R(cur, x) - pred;
162

163
            if (!RItype && Ra > Rb)
164 165
                err = -err;

166 167 168
            if (state->near) {
                if (err > 0)
                    err =  (state->near + err) / state->twonear;
169 170 171
                else
                    err = -(state->near - err) / state->twonear;

172
                if (RItype || (Rb >= Ra))
173 174 175 176 177
                    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);
            }
178
            if (err < 0)
179
                err += state->range;
180
            if (err >= state->range + 1 >> 1)
181 182
                err -= state->range;

183 184
            ls_encode_runterm(state, pb, RItype, err,
                              ff_log2_run[state->run_index[comp]]);
185

186
            if (state->run_index[comp] > 0)
187 188 189 190
                state->run_index[comp]--;
        } else { /* regular mode */
            int context;

191 192 193 194
            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);
195

196
            if (context < 0) {
197
                context = -context;
198 199 200 201
                sign    = 1;
                pred    = av_clip(pred - state->C[context], 0, state->maxval);
                err     = pred - R(cur, x);
            } else {
202 203
                sign = 0;
                pred = av_clip(pred + state->C[context], 0, state->maxval);
204
                err  = R(cur, x) - pred;
205 206
            }

207 208 209
            if (state->near) {
                if (err > 0)
                    err =  (state->near + err) / state->twonear;
210 211
                else
                    err = -(state->near - err) / state->twonear;
212
                if (!sign)
213 214 215 216 217 218 219 220 221 222 223 224
                    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;
    }
}

225 226
static void ls_store_lse(JLSState *state, PutBitContext *pb)
{
227
    /* Test if we have default params and don't need to store LSE */
228
    JLSState state2 = { 0 };
229
    state2.bpp  = state->bpp;
230 231
    state2.near = state->near;
    ff_jpegls_reset_coding_parameters(&state2, 1);
232 233 234 235
    if (state->T1 == state2.T1 &&
        state->T2 == state2.T2 &&
        state->T3 == state2.T3 &&
        state->reset == state2.reset)
236 237 238 239
        return;
    /* store LSE type 1 */
    put_marker(pb, LSE);
    put_bits(pb, 16, 13);
240
    put_bits(pb, 8, 1);
241 242 243 244 245 246 247
    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);
}

248 249 250
static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
                             const AVFrame *pict, int *got_packet)
{
251
    const AVFrame *const p = pict;
252
    const int near         = avctx->prediction_method;
253 254 255 256
    PutBitContext pb, pb2;
    GetBitContext gb;
    uint8_t *buf2, *zero, *cur, *last;
    JLSState *state;
257
    int i, size, ret;
258 259
    int comps;

260 261
    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
        avctx->pix_fmt == AV_PIX_FMT_GRAY16)
262 263 264 265
        comps = 1;
    else
        comps = 3;

266 267
    if ((ret = ff_alloc_packet(pkt, avctx->width * avctx->height * comps * 4 +
                               FF_MIN_BUFFER_SIZE)) < 0) {
268 269 270 271 272 273 274 275 276
        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
        return ret;
    }

    buf2 = av_malloc(pkt->size);

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

277 278 279 280
    /* 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
281
    put_bits(&pb, 8, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8);  // bpp
282 283
    put_bits(&pb, 16, avctx->height);
    put_bits(&pb, 16, avctx->width);
284 285 286 287 288
    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
289 290 291 292
    }

    put_marker(&pb, SOS);
    put_bits(&pb, 16, 6 + comps * 2);
293 294 295 296
    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
297
    }
298 299 300
    put_bits(&pb, 8, near);
    put_bits(&pb, 8, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line
    put_bits(&pb, 8, 0);  // point transform: none
301 302 303 304

    state = av_mallocz(sizeof(JLSState));
    /* initialize JPEG-LS state from JPEG parameters */
    state->near = near;
305
    state->bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
306 307 308 309 310 311 312
    ff_jpegls_reset_coding_parameters(state, 0);
    ff_jpegls_init_state(state);

    ls_store_lse(state, &pb);

    zero = av_mallocz(p->linesize[0]);
    last = zero;
313 314
    cur  = p->data[0];
    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
315 316
        int t = 0;

317 318 319
        for (i = 0; i < avctx->height; i++) {
            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);
            t    = last[0];
320 321 322
            last = cur;
            cur += p->linesize[0];
        }
323
    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
324 325
        int t = 0;

326
        for (i = 0; i < avctx->height; i++) {
327
            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);
328
            t    = *((uint16_t *)last);
329 330 331
            last = cur;
            cur += p->linesize[0];
        }
332
    } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
333
        int j, width;
334
        int Rc[3] = { 0, 0, 0 };
335 336

        width = avctx->width * 3;
337 338 339 340
        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);
341 342 343
                Rc[j] = last[j];
            }
            last = cur;
344
            cur += p->linesize[0];
345
        }
346
    } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {
347
        int j, width;
348
        int Rc[3] = { 0, 0, 0 };
349 350

        width = avctx->width * 3;
351 352 353 354
        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);
355 356 357
                Rc[j] = last[j];
            }
            last = cur;
358
            cur += p->linesize[0];
359 360 361 362 363 364
        }
    }

    av_free(zero);
    av_free(state);

365 366 367
    /* the specification says that after doing 0xff escaping unused bits in
     * the last byte must be set to 0, so just append 7 "optional" zero-bits
     * to avoid special-casing. */
368 369 370 371 372 373
    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;
374
    while (get_bits_count(&gb) < size) {
375 376 377
        int v;
        v = get_bits(&gb, 8);
        put_bits(&pb, 8, v);
378
        if (v == 0xFF) {
379 380 381 382
            v = get_bits(&gb, 7);
            put_bits(&pb, 8, v);
        }
    }
383
    avpriv_align_put_bits(&pb);
384 385 386 387 388 389 390 391
    av_free(buf2);

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

    emms_c();

392 393 394 395
    pkt->size   = put_bits_count(&pb) >> 3;
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
    return 0;
396 397
}

398 399 400 401 402 403
static av_cold int encode_close(AVCodecContext *avctx)
{
    av_frame_free(&avctx->coded_frame);
    return 0;
}

404 405
static av_cold int encode_init_ls(AVCodecContext *ctx)
{
406 407 408
    ctx->coded_frame = av_frame_alloc();
    if (!ctx->coded_frame)
        return AVERROR(ENOMEM);
409

410 411
    ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
    ctx->coded_frame->key_frame = 1;
412

413 414 415 416 417 418
    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");
419 420 421 422 423
        return -1;
    }
    return 0;
}

424
AVCodec ff_jpegls_encoder = {
425
    .name           = "jpegls",
426
    .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
427
    .type           = AVMEDIA_TYPE_VIDEO,
428
    .id             = AV_CODEC_ID_JPEGLS,
429
    .init           = encode_init_ls,
430
    .close          = encode_close,
431
    .encode2        = encode_picture_ls,
432 433 434
    .pix_fmts       = (const enum AVPixelFormat[]) {
        AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
435
        AV_PIX_FMT_NONE
436
    },
437
};