libavcodec/jpeglsenc.c
6ba04c2b
 /*
  * 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
  */
 
 /**
ba87f080
  * @file
6ba04c2b
  * JPEG-LS encoder.
  */
 
 #include "avcodec.h"
9106a698
 #include "get_bits.h"
a2dd988b
 #include "put_bits.h"
6ba04c2b
 #include "golomb.h"
6d9c27dc
 #include "internal.h"
199436b9
 #include "mathops.h"
6ba04c2b
 #include "mjpeg.h"
e6e3dcba
 #include "mjpegenc.h"
6ba04c2b
 #include "jpegls.h"
 
2862b637
 typedef struct JPEGLSContext {
     AVClass *class;
 
     int pred;
 } JPEGLSContext;
 
6ba04c2b
 /**
  * Encode error from regular symbol
  */
ff4fc5ef
 static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
                                      int err)
 {
6ba04c2b
     int k;
     int val;
     int map;
 
ff4fc5ef
     for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
         ;
6ba04c2b
 
     map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
 
ff4fc5ef
     if (err < 0)
6ba04c2b
         err += state->range;
9cacdabd
     if (err >= (state->range + 1 >> 1)) {
6ba04c2b
         err -= state->range;
ff4fc5ef
         val  = 2 * FFABS(err) - 1 - map;
6ba04c2b
     } 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
  */
ff4fc5ef
 static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
                                      int RItype, int err, int limit_add)
 {
6ba04c2b
     int k;
     int val, map;
     int Q = 365 + RItype;
     int temp;
 
     temp = state->A[Q];
ff4fc5ef
     if (RItype)
6ba04c2b
         temp += state->N[Q] >> 1;
ff4fc5ef
     for (k = 0; (state->N[Q] << k) < temp; k++)
         ;
6ba04c2b
     map = 0;
ff4fc5ef
     if (!k && err && (2 * state->B[Q] < state->N[Q]))
6ba04c2b
         map = 1;
 
ff4fc5ef
     if (err < 0)
         val = -(2 * err) - 1 - RItype + map;
6ba04c2b
     else
         val = 2 * err - RItype - map;
     set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
 
ff4fc5ef
     if (err < 0)
6ba04c2b
         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
  */
ff4fc5ef
 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]])) {
6ba04c2b
         put_bits(pb, 1, 1);
         run -= 1 << ff_log2_run[state->run_index[comp]];
ff4fc5ef
         if (state->run_index[comp] < 31)
6ba04c2b
             state->run_index[comp]++;
     }
     /* if hit EOL, encode another full run, else encode aborted run */
ff4fc5ef
     if (!trail && run) {
6ba04c2b
         put_bits(pb, 1, 1);
ff4fc5ef
     } else if (trail) {
6ba04c2b
         put_bits(pb, 1, 0);
ff4fc5ef
         if (ff_log2_run[state->run_index[comp]])
6ba04c2b
             put_bits(pb, ff_log2_run[state->run_index[comp]], run);
     }
 }
 
 /**
  * Encode one line of image
  */
ff4fc5ef
 static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
                                   void *last, void *cur, int last2, int w,
                                   int stride, int comp, int bits)
 {
6ba04c2b
     int x = 0;
     int Ra, Rb, Rc, Rd;
     int D0, D1, D2;
 
ff4fc5ef
     while (x < w) {
6ba04c2b
         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 */
ff4fc5ef
         if ((FFABS(D0) <= state->near) &&
             (FFABS(D1) <= state->near) &&
             (FFABS(D2) <= state->near)) {
6ba04c2b
             int RUNval, RItype, run;
 
ff4fc5ef
             run    = 0;
6ba04c2b
             RUNval = Ra;
ff4fc5ef
             while (x < w && (FFABS(R(cur, x) - RUNval) <= state->near)) {
6ba04c2b
                 run++;
                 W(cur, x, Ra);
                 x += stride;
             }
             ls_encode_run(state, pb, run, comp, x < w);
ff4fc5ef
             if (x >= w)
6ba04c2b
                 return;
ff4fc5ef
             Rb     = R(last, x);
9cacdabd
             RItype = FFABS(Ra - Rb) <= state->near;
ff4fc5ef
             pred   = RItype ? Ra : Rb;
             err    = R(cur, x) - pred;
6ba04c2b
 
ff4fc5ef
             if (!RItype && Ra > Rb)
6ba04c2b
                 err = -err;
 
ff4fc5ef
             if (state->near) {
                 if (err > 0)
                     err =  (state->near + err) / state->twonear;
6ba04c2b
                 else
                     err = -(state->near - err) / state->twonear;
 
ff4fc5ef
                 if (RItype || (Rb >= Ra))
6ba04c2b
                     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);
             }
ff4fc5ef
             if (err < 0)
6ba04c2b
                 err += state->range;
9cacdabd
             if (err >= state->range + 1 >> 1)
6ba04c2b
                 err -= state->range;
 
ff4fc5ef
             ls_encode_runterm(state, pb, RItype, err,
                               ff_log2_run[state->run_index[comp]]);
6ba04c2b
 
ff4fc5ef
             if (state->run_index[comp] > 0)
6ba04c2b
                 state->run_index[comp]--;
         } else { /* regular mode */
             int context;
 
ff4fc5ef
             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);
6ba04c2b
 
ff4fc5ef
             if (context < 0) {
6ba04c2b
                 context = -context;
ff4fc5ef
                 sign    = 1;
                 pred    = av_clip(pred - state->C[context], 0, state->maxval);
                 err     = pred - R(cur, x);
             } else {
6ba04c2b
                 sign = 0;
                 pred = av_clip(pred + state->C[context], 0, state->maxval);
ff4fc5ef
                 err  = R(cur, x) - pred;
6ba04c2b
             }
 
ff4fc5ef
             if (state->near) {
                 if (err > 0)
                     err =  (state->near + err) / state->twonear;
6ba04c2b
                 else
                     err = -(state->near - err) / state->twonear;
ff4fc5ef
                 if (!sign)
6ba04c2b
                     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;
     }
 }
 
ff4fc5ef
 static void ls_store_lse(JLSState *state, PutBitContext *pb)
 {
6ba04c2b
     /* Test if we have default params and don't need to store LSE */
a92be9b8
     JLSState state2 = { 0 };
ff4fc5ef
     state2.bpp  = state->bpp;
6ba04c2b
     state2.near = state->near;
     ff_jpegls_reset_coding_parameters(&state2, 1);
ff4fc5ef
     if (state->T1 == state2.T1 &&
         state->T2 == state2.T2 &&
         state->T3 == state2.T3 &&
         state->reset == state2.reset)
6ba04c2b
         return;
     /* store LSE type 1 */
     put_marker(pb, LSE);
     put_bits(pb, 16, 13);
ff4fc5ef
     put_bits(pb, 8, 1);
6ba04c2b
     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);
 }
 
6d9c27dc
 static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
                              const AVFrame *pict, int *got_packet)
 {
2862b637
     JPEGLSContext *ctx = avctx->priv_data;
706a9292
     const AVFrame *const p = pict;
6ba04c2b
     PutBitContext pb, pb2;
     GetBitContext gb;
48214956
     uint8_t *buf2 = NULL;
3919a457
     uint8_t *zero = NULL;
     uint8_t *cur  = NULL;
     uint8_t *last = NULL;
48214956
     JLSState *state = NULL;
6d9c27dc
     int i, size, ret;
6ba04c2b
     int comps;
 
2862b637
 #if FF_API_PRIVATE_OPT
 FF_DISABLE_DEPRECATION_WARNINGS
     if (avctx->prediction_method)
         ctx->pred = avctx->prediction_method;
 FF_ENABLE_DEPRECATION_WARNINGS
 #endif
 
ff4fc5ef
     if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
         avctx->pix_fmt == AV_PIX_FMT_GRAY16)
6ba04c2b
         comps = 1;
     else
         comps = 3;
 
39354d60
     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width  *avctx->height * comps * 4 +
29d147c9
                                 AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
6d9c27dc
         return ret;
 
     buf2 = av_malloc(pkt->size);
48214956
     if (!buf2)
3919a457
         goto memfail;
6d9c27dc
 
     init_put_bits(&pb, pkt->data, pkt->size);
     init_put_bits(&pb2, buf2, pkt->size);
 
6ba04c2b
     /* 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
ff4fc5ef
     put_bits(&pb, 8, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8);  // bpp
6ba04c2b
     put_bits(&pb, 16, avctx->height);
     put_bits(&pb, 16, avctx->width);
ff4fc5ef
     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
6ba04c2b
     }
 
     put_marker(&pb, SOS);
     put_bits(&pb, 16, 6 + comps * 2);
ff4fc5ef
     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
6ba04c2b
     }
2862b637
     put_bits(&pb, 8, ctx->pred);
ff4fc5ef
     put_bits(&pb, 8, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line
     put_bits(&pb, 8, 0);  // point transform: none
6ba04c2b
 
     state = av_mallocz(sizeof(JLSState));
48214956
     if (!state)
3919a457
         goto memfail;
 
6ba04c2b
     /* initialize JPEG-LS state from JPEG parameters */
2862b637
     state->near = ctx->pred;
ff4fc5ef
     state->bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
6ba04c2b
     ff_jpegls_reset_coding_parameters(state, 0);
     ff_jpegls_init_state(state);
 
     ls_store_lse(state, &pb);
 
27801500
     zero = last = av_mallocz(FFABS(p->linesize[0]));
48214956
     if (!zero)
3919a457
         goto memfail;
48214956
 
ff4fc5ef
     cur  = p->data[0];
     if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
6ba04c2b
         int t = 0;
 
ff4fc5ef
         for (i = 0; i < avctx->height; i++) {
             ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);
             t    = last[0];
6ba04c2b
             last = cur;
             cur += p->linesize[0];
         }
ff4fc5ef
     } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
6ba04c2b
         int t = 0;
 
ff4fc5ef
         for (i = 0; i < avctx->height; i++) {
6ba04c2b
             ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);
ff4fc5ef
             t    = *((uint16_t *)last);
6ba04c2b
             last = cur;
             cur += p->linesize[0];
         }
ff4fc5ef
     } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {
6ba04c2b
         int j, width;
ff4fc5ef
         int Rc[3] = { 0, 0, 0 };
6ba04c2b
 
         width = avctx->width * 3;
ff4fc5ef
         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);
6ba04c2b
                 Rc[j] = last[j];
             }
             last = cur;
706a9292
             cur += p->linesize[0];
6ba04c2b
         }
ff4fc5ef
     } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {
6ba04c2b
         int j, width;
ff4fc5ef
         int Rc[3] = { 0, 0, 0 };
6ba04c2b
 
         width = avctx->width * 3;
ff4fc5ef
         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);
6ba04c2b
                 Rc[j] = last[j];
             }
             last = cur;
706a9292
             cur += p->linesize[0];
6ba04c2b
         }
     }
 
b96d1859
     av_freep(&zero);
     av_freep(&state);
6ba04c2b
 
ff4fc5ef
     /* the specification says that after doing 0xff escaping unused bits in
41ed7ab4
      * the last byte must be set to 0, so just append 7 "optional" zero bits
ff4fc5ef
      * to avoid special-casing. */
6ba04c2b
     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;
ff4fc5ef
     while (get_bits_count(&gb) < size) {
6ba04c2b
         int v;
         v = get_bits(&gb, 8);
         put_bits(&pb, 8, v);
ff4fc5ef
         if (v == 0xFF) {
6ba04c2b
             v = get_bits(&gb, 7);
             put_bits(&pb, 8, v);
         }
     }
9f51c682
     avpriv_align_put_bits(&pb);
48214956
     av_freep(&buf2);
6ba04c2b
 
     /* End of image */
     put_marker(&pb, EOI);
     flush_put_bits(&pb);
 
     emms_c();
 
6d9c27dc
     pkt->size   = put_bits_count(&pb) >> 3;
     pkt->flags |= AV_PKT_FLAG_KEY;
     *got_packet = 1;
     return 0;
3919a457
 
 memfail:
ce70f28a
     av_packet_unref(pkt);
48214956
     av_freep(&buf2);
     av_freep(&state);
3919a457
     av_freep(&zero);
48214956
     return AVERROR(ENOMEM);
6ba04c2b
 }
 
ff4fc5ef
 static av_cold int encode_init_ls(AVCodecContext *ctx)
 {
40cf1bba
 #if FF_API_CODED_FRAME
 FF_DISABLE_DEPRECATION_WARNINGS
706a9292
     ctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
     ctx->coded_frame->key_frame = 1;
40cf1bba
 FF_ENABLE_DEPRECATION_WARNINGS
 #endif
6ba04c2b
 
ff4fc5ef
     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");
6ba04c2b
         return -1;
     }
     return 0;
 }
 
2862b637
 #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,
 };
 
02c2a54b
 AVCodec ff_jpegls_encoder = {
86714887
     .name           = "jpegls",
ff4fc5ef
     .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
86714887
     .type           = AVMEDIA_TYPE_VIDEO,
36ef5369
     .id             = AV_CODEC_ID_JPEGLS,
2862b637
     .priv_data_size = sizeof(JPEGLSContext),
     .priv_class     = &jpegls_class,
86714887
     .init           = encode_init_ls,
444e9874
     .capabilities   = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
6d9c27dc
     .encode2        = encode_picture_ls,
ff4fc5ef
     .pix_fmts       = (const enum AVPixelFormat[]) {
         AV_PIX_FMT_BGR24, AV_PIX_FMT_RGB24,
         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
716d413c
         AV_PIX_FMT_NONE
00c3b67b
     },
c3418201
     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE |
                       FF_CODEC_CAP_INIT_CLEANUP,
6ba04c2b
 };