PageRenderTime 45ms CodeModel.GetById 8ms app.highlight 31ms RepoModel.GetById 1ms app.codeStats 0ms

/libavcodec/jpeglsenc.c

http://github.com/FFmpeg/FFmpeg
C | 483 lines | 374 code | 60 blank | 49 comment | 81 complexity | 5645e64c5d85e06a360c04de9ffa896e MD5 | raw file
  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 "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#include "jpegls.h"
 37
 38typedef struct JPEGLSContext {
 39    AVClass *class;
 40
 41    int pred;
 42} JPEGLSContext;
 43
 44/**
 45 * Encode error from regular symbol
 46 */
 47static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
 48                                     int err)
 49{
 50    int k;
 51    int val;
 52    int map;
 53
 54    for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
 55        ;
 56
 57    map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
 58
 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    } else
 65        val = 2 * err + map;
 66
 67    set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
 68
 69    ff_jpegls_update_state_regular(state, Q, err);
 70}
 71
 72/**
 73 * Encode error from run termination
 74 */
 75static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
 76                                     int RItype, int err, int limit_add)
 77{
 78    int k;
 79    int val, map;
 80    int Q = 365 + RItype;
 81    int temp;
 82
 83    temp = state->A[Q];
 84    if (RItype)
 85        temp += state->N[Q] >> 1;
 86    for (k = 0; (state->N[Q] << k) < temp; k++)
 87        ;
 88    map = 0;
 89    if (!k && err && (2 * state->B[Q] < state->N[Q]))
 90        map = 1;
 91
 92    if (err < 0)
 93        val = -(2 * err) - 1 - RItype + map;
 94    else
 95        val = 2 * err - RItype - map;
 96    set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
 97
 98    if (err < 0)
 99        state->B[Q]++;
100    state->A[Q] += (val + 1 - RItype) >> 1;
101
102    ff_jpegls_downscale_state(state, Q);
103}
104
105/**
106 * Encode run value as specified by JPEG-LS standard
107 */
108static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run,
109                                 int comp, int trail)
110{
111    while (run >= (1 << ff_log2_run[state->run_index[comp]])) {
112        put_bits(pb, 1, 1);
113        run -= 1 << ff_log2_run[state->run_index[comp]];
114        if (state->run_index[comp] < 31)
115            state->run_index[comp]++;
116    }
117    /* 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            put_bits(pb, ff_log2_run[state->run_index[comp]], run);
124    }
125}
126
127/**
128 * Encode one line of image
129 */
130static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
131                                  void *last, void *cur, int last2, int w,
132                                  int stride, int comp, int bits)
133{
134    int x = 0;
135    int Ra, Rb, Rc, Rd;
136    int D0, D1, D2;
137
138    while (x < w) {
139        int err, pred, sign;
140
141        /* compute gradients */
142        Ra = x ? R(cur, x - stride) : R(last, x);
143        Rb = R(last, x);
144        Rc = x ? R(last, x - stride) : last2;
145        Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
146        D0 = Rd - Rb;
147        D1 = Rb - Rc;
148        D2 = Rc - Ra;
149
150        /* run mode */
151        if ((FFABS(D0) <= state->near) &&
152            (FFABS(D1) <= state->near) &&
153            (FFABS(D2) <= state->near)) {
154            int RUNval, RItype, run;
155
156            run    = 0;
157            RUNval = Ra;
158            while (x < w && (FFABS(R(cur, x) - RUNval) <= state->near)) {
159                run++;
160                W(cur, x, Ra);
161                x += stride;
162            }
163            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            pred   = RItype ? Ra : Rb;
169            err    = R(cur, x) - pred;
170
171            if (!RItype && Ra > Rb)
172                err = -err;
173
174            if (state->near) {
175                if (err > 0)
176                    err =  (state->near + err) / state->twonear;
177                else
178                    err = -(state->near - err) / state->twonear;
179
180                if (RItype || (Rb >= Ra))
181                    Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
182                else
183                    Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
184                W(cur, x, Ra);
185            }
186            if (err < 0)
187                err += state->range;
188            if (err >= state->range + 1 >> 1)
189                err -= state->range;
190
191            ls_encode_runterm(state, pb, RItype, err,
192                              ff_log2_run[state->run_index[comp]]);
193
194            if (state->run_index[comp] > 0)
195                state->run_index[comp]--;
196        } else { /* regular mode */
197            int context;
198
199            context = ff_jpegls_quantize(state, D0) * 81 +
200                      ff_jpegls_quantize(state, D1) *  9 +
201                      ff_jpegls_quantize(state, D2);
202            pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
203
204            if (context < 0) {
205                context = -context;
206                sign    = 1;
207                pred    = av_clip(pred - state->C[context], 0, state->maxval);
208                err     = pred - R(cur, x);
209            } else {
210                sign = 0;
211                pred = av_clip(pred + state->C[context], 0, state->maxval);
212                err  = R(cur, x) - pred;
213            }
214
215            if (state->near) {
216                if (err > 0)
217                    err =  (state->near + err) / state->twonear;
218                else
219                    err = -(state->near - err) / state->twonear;
220                if (!sign)
221                    Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
222                else
223                    Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
224                W(cur, x, Ra);
225            }
226
227            ls_encode_regular(state, pb, context, err);
228        }
229        x += stride;
230    }
231}
232
233static void ls_store_lse(JLSState *state, PutBitContext *pb)
234{
235    /* Test if we have default params and don't need to store LSE */
236    JLSState state2 = { 0 };
237    state2.bpp  = state->bpp;
238    state2.near = state->near;
239    ff_jpegls_reset_coding_parameters(&state2, 1);
240    if (state->T1 == state2.T1 &&
241        state->T2 == state2.T2 &&
242        state->T3 == state2.T3 &&
243        state->reset == state2.reset)
244        return;
245    /* store LSE type 1 */
246    put_marker(pb, LSE);
247    put_bits(pb, 16, 13);
248    put_bits(pb, 8, 1);
249    put_bits(pb, 16, state->maxval);
250    put_bits(pb, 16, state->T1);
251    put_bits(pb, 16, state->T2);
252    put_bits(pb, 16, state->T3);
253    put_bits(pb, 16, state->reset);
254}
255
256static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
257                             const AVFrame *pict, int *got_packet)
258{
259    JPEGLSContext *ctx = avctx->priv_data;
260    const AVFrame *const p = pict;
261    PutBitContext pb, pb2;
262    GetBitContext gb;
263    uint8_t *buf2 = NULL;
264    uint8_t *zero = NULL;
265    uint8_t *cur  = NULL;
266    uint8_t *last = NULL;
267    JLSState *state = NULL;
268    int i, size, ret;
269    int comps;
270
271#if FF_API_PRIVATE_OPT
272FF_DISABLE_DEPRECATION_WARNINGS
273    if (avctx->prediction_method)
274        ctx->pred = avctx->prediction_method;
275FF_ENABLE_DEPRECATION_WARNINGS
276#endif
277
278    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
279        avctx->pix_fmt == AV_PIX_FMT_GRAY16)
280        comps = 1;
281    else
282        comps = 3;
283
284    if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width  *avctx->height * comps * 4 +
285                                AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
286        return ret;
287
288    buf2 = av_malloc(pkt->size);
289    if (!buf2)
290        goto memfail;
291
292    init_put_bits(&pb, pkt->data, pkt->size);
293    init_put_bits(&pb2, buf2, pkt->size);
294
295    /* write our own JPEG header, can't use mjpeg_picture_header */
296    put_marker(&pb, SOI);
297    put_marker(&pb, SOF48);
298    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    put_bits(&pb, 16, avctx->height);
301    put_bits(&pb, 16, avctx->width);
302    put_bits(&pb, 8, comps);          // components
303    for (i = 1; i <= comps; i++) {
304        put_bits(&pb, 8, i);     // component ID
305        put_bits(&pb, 8, 0x11);  // subsampling: none
306        put_bits(&pb, 8, 0);     // Tiq, used by JPEG-LS ext
307    }
308
309    put_marker(&pb, SOS);
310    put_bits(&pb, 16, 6 + comps * 2);
311    put_bits(&pb, 8, comps);
312    for (i = 1; i <= comps; i++) {
313        put_bits(&pb, 8, i);   // component ID
314        put_bits(&pb, 8, 0);   // mapping index: none
315    }
316    put_bits(&pb, 8, ctx->pred);
317    put_bits(&pb, 8, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line
318    put_bits(&pb, 8, 0);  // point transform: none
319
320    state = av_mallocz(sizeof(JLSState));
321    if (!state)
322        goto memfail;
323
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    ff_jpegls_reset_coding_parameters(state, 0);
328    ff_jpegls_init_state(state);
329
330    ls_store_lse(state, &pb);
331
332    zero = last = av_mallocz(FFABS(p->linesize[0]));
333    if (!zero)
334        goto memfail;
335
336    cur  = p->data[0];
337    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
338        int t = 0;
339
340        for (i = 0; i < avctx->height; i++) {
341            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);
342            t    = last[0];
343            last = cur;
344            cur += p->linesize[0];
345        }
346    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
347        int t = 0;
348
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            last = cur;
353            cur += p->linesize[0];
354        }
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        for (i = 0; i < avctx->height; i++) {
361            for (j = 0; j < 3; j++) {
362                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],
363                               width, 3, j, 8);
364                Rc[j] = last[j];
365            }
366            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        for (i = 0; i < avctx->height; i++) {
375            for (j = 2; j >= 0; j--) {
376                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],
377                               width, 3, j, 8);
378                Rc[j] = last[j];
379            }
380            last = cur;
381            cur += p->linesize[0];
382        }
383    }
384
385    av_freep(&zero);
386    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    put_bits(&pb2, 7, 0);
392    size = put_bits_count(&pb2);
393    flush_put_bits(&pb2);
394    /* do escape coding */
395    init_get_bits(&gb, buf2, size);
396    size -= 7;
397    while (get_bits_count(&gb) < size) {
398        int v;
399        v = get_bits(&gb, 8);
400        put_bits(&pb, 8, v);
401        if (v == 0xFF) {
402            v = get_bits(&gb, 7);
403            put_bits(&pb, 8, v);
404        }
405    }
406    avpriv_align_put_bits(&pb);
407    av_freep(&buf2);
408
409    /* End of image */
410    put_marker(&pb, EOI);
411    flush_put_bits(&pb);
412
413    emms_c();
414
415    pkt->size   = put_bits_count(&pb) >> 3;
416    pkt->flags |= AV_PKT_FLAG_KEY;
417    *got_packet = 1;
418    return 0;
419
420memfail:
421    av_packet_unref(pkt);
422    av_freep(&buf2);
423    av_freep(&state);
424    av_freep(&zero);
425    return AVERROR(ENOMEM);
426}
427
428static av_cold int encode_init_ls(AVCodecContext *ctx)
429{
430#if FF_API_CODED_FRAME
431FF_DISABLE_DEPRECATION_WARNINGS
432    ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
433    ctx->coded_frame->key_frame = 1;
434FF_ENABLE_DEPRECATION_WARNINGS
435#endif
436
437    if (ctx->pix_fmt != AV_PIX_FMT_GRAY8  &&
438        ctx->pix_fmt != AV_PIX_FMT_GRAY16 &&
439        ctx->pix_fmt != AV_PIX_FMT_RGB24  &&
440        ctx->pix_fmt != AV_PIX_FMT_BGR24) {
441        av_log(ctx, AV_LOG_ERROR,
442               "Only grayscale and RGB24/BGR24 images are supported\n");
443        return -1;
444    }
445    return 0;
446}
447
448#define OFFSET(x) offsetof(JPEGLSContext, x)
449#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
450static const AVOption options[] = {
451{ "pred", "Prediction method", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "pred" },
452    { "left",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
453    { "plane",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "pred" },
454    { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "pred" },
455
456    { NULL},
457};
458
459static const AVClass jpegls_class = {
460    .class_name = "jpegls",
461    .item_name  = av_default_item_name,
462    .option     = options,
463    .version    = LIBAVUTIL_VERSION_INT,
464};
465
466AVCodec 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    .priv_data_size = sizeof(JPEGLSContext),
472    .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    .pix_fmts       = (const enum AVPixelFormat[]) {
477        AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
478        AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
479        AV_PIX_FMT_NONE
480    },
481    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
482                      FF_CODEC_CAP_INIT_CLEANUP,
483};