Libav
jpeglsenc.c
Go to the documentation of this 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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
28 #include "avcodec.h"
29 #include "get_bits.h"
30 #include "golomb.h"
31 #include "internal.h"
32 #include "mathops.h"
33 #include "mjpeg.h"
34 #include "jpegls.h"
35 
39 static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q,
40  int err)
41 {
42  int k;
43  int val;
44  int map;
45 
46  for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
47  ;
48 
49  map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
50 
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  } else
57  val = 2 * err + map;
58 
59  set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
60 
61  ff_jpegls_update_state_regular(state, Q, err);
62 }
63 
67 static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb,
68  int RItype, int err, int limit_add)
69 {
70  int k;
71  int val, map;
72  int Q = 365 + RItype;
73  int temp;
74 
75  temp = state->A[Q];
76  if (RItype)
77  temp += state->N[Q] >> 1;
78  for (k = 0; (state->N[Q] << k) < temp; k++)
79  ;
80  map = 0;
81  if (!k && err && (2 * state->B[Q] < state->N[Q]))
82  map = 1;
83 
84  if (err < 0)
85  val = -(2 * err) - 1 - RItype + map;
86  else
87  val = 2 * err - RItype - map;
88  set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
89 
90  if (err < 0)
91  state->B[Q]++;
92  state->A[Q] += (val + 1 - RItype) >> 1;
93 
94  ff_jpegls_downscale_state(state, Q);
95 }
96 
100 static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run,
101  int comp, int trail)
102 {
103  while (run >= (1 << ff_log2_run[state->run_index[comp]])) {
104  put_bits(pb, 1, 1);
105  run -= 1 << ff_log2_run[state->run_index[comp]];
106  if (state->run_index[comp] < 31)
107  state->run_index[comp]++;
108  }
109  /* 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  put_bits(pb, ff_log2_run[state->run_index[comp]], run);
116  }
117 }
118 
122 static inline void ls_encode_line(JLSState *state, PutBitContext *pb,
123  void *last, void *cur, int last2, int w,
124  int stride, int comp, int bits)
125 {
126  int x = 0;
127  int Ra, Rb, Rc, Rd;
128  int D0, D1, D2;
129 
130  while (x < w) {
131  int err, pred, sign;
132 
133  /* compute gradients */
134  Ra = x ? R(cur, x - stride) : R(last, x);
135  Rb = R(last, x);
136  Rc = x ? R(last, x - stride) : last2;
137  Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
138  D0 = Rd - Rb;
139  D1 = Rb - Rc;
140  D2 = Rc - Ra;
141 
142  /* run mode */
143  if ((FFABS(D0) <= state->near) &&
144  (FFABS(D1) <= state->near) &&
145  (FFABS(D2) <= state->near)) {
146  int RUNval, RItype, run;
147 
148  run = 0;
149  RUNval = Ra;
150  while (x < w && (FFABS(R(cur, x) - RUNval) <= state->near)) {
151  run++;
152  W(cur, x, Ra);
153  x += stride;
154  }
155  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  pred = RItype ? Ra : Rb;
161  err = R(cur, x) - pred;
162 
163  if (!RItype && Ra > Rb)
164  err = -err;
165 
166  if (state->near) {
167  if (err > 0)
168  err = (state->near + err) / state->twonear;
169  else
170  err = -(state->near - err) / state->twonear;
171 
172  if (RItype || (Rb >= Ra))
173  Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
174  else
175  Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
176  W(cur, x, Ra);
177  }
178  if (err < 0)
179  err += state->range;
180  if (err >= state->range + 1 >> 1)
181  err -= state->range;
182 
183  ls_encode_runterm(state, pb, RItype, err,
184  ff_log2_run[state->run_index[comp]]);
185 
186  if (state->run_index[comp] > 0)
187  state->run_index[comp]--;
188  } else { /* regular mode */
189  int context;
190 
191  context = ff_jpegls_quantize(state, D0) * 81 +
192  ff_jpegls_quantize(state, D1) * 9 +
193  ff_jpegls_quantize(state, D2);
194  pred = mid_pred(Ra, Ra + Rb - Rc, Rb);
195 
196  if (context < 0) {
197  context = -context;
198  sign = 1;
199  pred = av_clip(pred - state->C[context], 0, state->maxval);
200  err = pred - R(cur, x);
201  } else {
202  sign = 0;
203  pred = av_clip(pred + state->C[context], 0, state->maxval);
204  err = R(cur, x) - pred;
205  }
206 
207  if (state->near) {
208  if (err > 0)
209  err = (state->near + err) / state->twonear;
210  else
211  err = -(state->near - err) / state->twonear;
212  if (!sign)
213  Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
214  else
215  Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
216  W(cur, x, Ra);
217  }
218 
219  ls_encode_regular(state, pb, context, err);
220  }
221  x += stride;
222  }
223 }
224 
226 {
227  /* Test if we have default params and don't need to store LSE */
228  JLSState state2 = { 0 };
229  state2.bpp = state->bpp;
230  state2.near = state->near;
232  if (state->T1 == state2.T1 &&
233  state->T2 == state2.T2 &&
234  state->T3 == state2.T3 &&
235  state->reset == state2.reset)
236  return;
237  /* store LSE type 1 */
238  put_marker(pb, LSE);
239  put_bits(pb, 16, 13);
240  put_bits(pb, 8, 1);
241  put_bits(pb, 16, state->maxval);
242  put_bits(pb, 16, state->T1);
243  put_bits(pb, 16, state->T2);
244  put_bits(pb, 16, state->T3);
245  put_bits(pb, 16, state->reset);
246 }
247 
248 static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,
249  const AVFrame *pict, int *got_packet)
250 {
251  const AVFrame *const p = pict;
252  const int near = avctx->prediction_method;
253  PutBitContext pb, pb2;
254  GetBitContext gb;
255  uint8_t *buf2, *zero, *cur, *last;
256  JLSState *state;
257  int i, size, ret;
258  int comps;
259 
260  if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||
261  avctx->pix_fmt == AV_PIX_FMT_GRAY16)
262  comps = 1;
263  else
264  comps = 3;
265 
266  if ((ret = ff_alloc_packet(pkt, avctx->width * avctx->height * comps * 4 +
267  FF_MIN_BUFFER_SIZE)) < 0) {
268  av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
269  return ret;
270  }
271 
272  buf2 = av_malloc(pkt->size);
273 
274  init_put_bits(&pb, pkt->data, pkt->size);
275  init_put_bits(&pb2, buf2, pkt->size);
276 
277  /* write our own JPEG header, can't use mjpeg_picture_header */
278  put_marker(&pb, SOI);
279  put_marker(&pb, SOF48);
280  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  put_bits(&pb, 16, avctx->height);
283  put_bits(&pb, 16, avctx->width);
284  put_bits(&pb, 8, comps); // components
285  for (i = 1; i <= comps; i++) {
286  put_bits(&pb, 8, i); // component ID
287  put_bits(&pb, 8, 0x11); // subsampling: none
288  put_bits(&pb, 8, 0); // Tiq, used by JPEG-LS ext
289  }
290 
291  put_marker(&pb, SOS);
292  put_bits(&pb, 16, 6 + comps * 2);
293  put_bits(&pb, 8, comps);
294  for (i = 1; i <= comps; i++) {
295  put_bits(&pb, 8, i); // component ID
296  put_bits(&pb, 8, 0); // mapping index: none
297  }
298  put_bits(&pb, 8, near);
299  put_bits(&pb, 8, (comps > 1) ? 1 : 0); // interleaving: 0 - plane, 1 - line
300  put_bits(&pb, 8, 0); // point transform: none
301 
302  state = av_mallocz(sizeof(JLSState));
303  /* initialize JPEG-LS state from JPEG parameters */
304  state->near = near;
305  state->bpp = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
307  ff_jpegls_init_state(state);
308 
309  ls_store_lse(state, &pb);
310 
311  zero = av_mallocz(p->linesize[0]);
312  last = zero;
313  cur = p->data[0];
314  if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
315  int t = 0;
316 
317  for (i = 0; i < avctx->height; i++) {
318  ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);
319  t = last[0];
320  last = cur;
321  cur += p->linesize[0];
322  }
323  } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {
324  int t = 0;
325 
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  last = cur;
330  cur += p->linesize[0];
331  }
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  for (i = 0; i < avctx->height; i++) {
338  for (j = 0; j < 3; j++) {
339  ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],
340  width, 3, j, 8);
341  Rc[j] = last[j];
342  }
343  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  for (i = 0; i < avctx->height; i++) {
352  for (j = 2; j >= 0; j--) {
353  ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],
354  width, 3, j, 8);
355  Rc[j] = last[j];
356  }
357  last = cur;
358  cur += p->linesize[0];
359  }
360  }
361 
362  av_free(zero);
363  av_free(state);
364 
365  /* the specification says that after doing 0xff escaping unused bits in
366  * the last byte must be set to 0, so just append 7 "optional" zero-bits
367  * to avoid special-casing. */
368  put_bits(&pb2, 7, 0);
369  size = put_bits_count(&pb2);
370  flush_put_bits(&pb2);
371  /* do escape coding */
372  init_get_bits(&gb, buf2, size);
373  size -= 7;
374  while (get_bits_count(&gb) < size) {
375  int v;
376  v = get_bits(&gb, 8);
377  put_bits(&pb, 8, v);
378  if (v == 0xFF) {
379  v = get_bits(&gb, 7);
380  put_bits(&pb, 8, v);
381  }
382  }
384  av_free(buf2);
385 
386  /* End of image */
387  put_marker(&pb, EOI);
388  flush_put_bits(&pb);
389 
390  emms_c();
391 
392  pkt->size = put_bits_count(&pb) >> 3;
393  pkt->flags |= AV_PKT_FLAG_KEY;
394  *got_packet = 1;
395  return 0;
396 }
397 
399 {
400  av_frame_free(&avctx->coded_frame);
401  return 0;
402 }
403 
405 {
406  ctx->coded_frame = av_frame_alloc();
407  if (!ctx->coded_frame)
408  return AVERROR(ENOMEM);
409 
411  ctx->coded_frame->key_frame = 1;
412 
413  if (ctx->pix_fmt != AV_PIX_FMT_GRAY8 &&
414  ctx->pix_fmt != AV_PIX_FMT_GRAY16 &&
415  ctx->pix_fmt != AV_PIX_FMT_RGB24 &&
416  ctx->pix_fmt != AV_PIX_FMT_BGR24) {
417  av_log(ctx, AV_LOG_ERROR,
418  "Only grayscale and RGB24/BGR24 images are supported\n");
419  return -1;
420  }
421  return 0;
422 }
423 
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  .pix_fmts = (const enum AVPixelFormat[]) {
436  },
437 };
int reset
Definition: jpegls.h:41
const uint8_t ff_log2_run[41]
Definition: bitstream.c:36
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
int T2
Definition: jpegls.h:39
int size
This structure describes decoded (raw) audio or video data.
Definition: frame.h:135
AVCodec ff_jpegls_encoder
Definition: jpeglsenc.c:424
JPEG-LS.
Definition: mjpeg.h:108
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition: get_bits.h:240
packed RGB 8:8:8, 24bpp, RGBRGB...
Definition: pixfmt.h:67
static void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q, int err)
Encode error from regular symbol.
Definition: jpeglsenc.c:39
AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:2548
#define R
Definition: huffyuv.h:51
static av_cold int encode_close(AVCodecContext *avctx)
Definition: jpeglsenc.c:398
int size
Definition: avcodec.h:974
int C[365]
Definition: jpegls.h:40
void avpriv_align_put_bits(PutBitContext *s)
Pad the bitstream with zeros up to the next byte boundary.
Definition: bitstream.c:45
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1270
Definition: mjpeg.h:75
int twonear
Definition: jpegls.h:42
uint8_t run
Definition: svq3.c:146
int limit
Definition: jpegls.h:41
int stride
Definition: mace.c:144
AVCodec.
Definition: avcodec.h:2812
MJPEG encoder and decoder.
int bpp
Definition: jpegls.h:41
int maxval
Definition: jpegls.h:41
uint8_t bits
Definition: crc.c:251
uint8_t
#define av_cold
Definition: attributes.h:66
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:57
#define emms_c()
Definition: internal.h:47
uint8_t * data
Definition: avcodec.h:973
static int get_bits_count(const GetBitContext *s)
Definition: get_bits.h:194
static void ls_encode_line(JLSState *state, PutBitContext *pb, void *last, void *cur, int last2, int w, int stride, int comp, int bits)
Encode one line of image.
Definition: jpeglsenc.c:122
bitstream reader API header.
static void ls_encode_run(JLSState *state, PutBitContext *pb, int run, int comp, int trail)
Encode run value as specified by JPEG-LS standard.
Definition: jpeglsenc.c:100
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1019
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:123
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:186
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:69
static void ls_store_lse(JLSState *state, PutBitContext *pb)
Definition: jpeglsenc.c:225
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:145
int run_index[3]
Definition: jpegls.h:43
void ff_jpegls_reset_coding_parameters(JLSState *s, int reset_all)
Calculate JPEG-LS codec values.
Definition: jpegls.c:63
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:169
const char * name
Name of the codec implementation.
Definition: avcodec.h:2819
static int ff_jpegls_update_state_regular(JLSState *state, int Q, int err)
Definition: jpegls.h:98
int B[367]
Definition: jpegls.h:40
static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet)
Definition: jpeglsenc.c:248
static void put_bits(PutBitContext *s, int n, unsigned int value)
Write up to 31 bits into a bitstream.
Definition: put_bits.h:134
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:979
int near
Definition: jpegls.h:42
static int put_bits_count(PutBitContext *s)
Definition: put_bits.h:67
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:196
#define AV_PIX_FMT_GRAY16
Definition: pixfmt.h:227
Definition: mjpeg.h:77
#define FF_MIN_BUFFER_SIZE
minimum encoding buffer size Used to avoid some checks during header writing.
Definition: avcodec.h:538
int width
picture width / height.
Definition: avcodec.h:1229
#define FFABS(a)
Definition: common.h:52
int ff_alloc_packet(AVPacket *avpkt, int size)
Check AVPacket size and/or allocate data.
Definition: utils.c:1245
static void ls_encode_runterm(JLSState *state, PutBitContext *pb, int RItype, int err, int limit_add)
Encode error from run termination.
Definition: jpeglsenc.c:67
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition: pixfmt.h:68
static void set_ur_golomb_jpegls(PutBitContext *pb, int i, int k, int limit, int esc_len)
write unsigned golomb rice code (jpegls).
Definition: golomb.h:541
Definition: mjpeg.h:76
static const float pred[4]
Definition: siprdata.h:259
int qbpp
Definition: jpegls.h:41
static int width
Definition: utils.c:156
Libavcodec external API header.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:153
main external API structure.
Definition: avcodec.h:1050
int A[367]
Definition: jpegls.h:40
#define W(a, i, v)
Definition: jpegls.h:121
JPEG-LS common code.
int T1
Definition: jpegls.h:39
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition: get_bits.h:375
int range
Definition: jpegls.h:41
int N[367]
Definition: jpegls.h:40
#define mid_pred
Definition: mathops.h:98
static av_cold int encode_init_ls(AVCodecContext *ctx)
Definition: jpeglsenc.c:404
static uint32_t state
Definition: trasher.c:27
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:141
Y , 8bpp.
Definition: pixfmt.h:73
common internal api header.
static void flush_put_bits(PutBitContext *s)
Pad the end of the output stream with zeros.
Definition: put_bits.h:83
int prediction_method
prediction method (needed for huffyuv)
Definition: avcodec.h:1426
static void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
Initialize the PutBitContext s.
Definition: put_bits.h:48
static void put_marker(PutBitContext *p, int code)
Definition: mjpeg.h:123
static int ff_jpegls_quantize(JLSState *s, int v)
Calculate quantized gradient value, used for context determination.
Definition: jpegls.h:56
JPEG-LS extension parameters.
Definition: mjpeg.h:109
int key_frame
1 -> keyframe, 0-> not
Definition: frame.h:191
static void comp(unsigned char *dst, int dst_stride, unsigned char *src, int src_stride, int add)
Definition: eamad.c:83
int T3
Definition: jpegls.h:39
void ff_jpegls_init_state(JLSState *state)
Calculate initial JPEG-LS parameters.
Definition: jpegls.c:30
exp golomb vlc stuff
AVPixelFormat
Pixel format.
Definition: pixfmt.h:63
This structure stores compressed data.
Definition: avcodec.h:950
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:205
static void ff_jpegls_downscale_state(JLSState *state, int Q)
Definition: jpegls.h:88