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 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 "jpegls.h"
36 
37 
38 /**
39  * Encode error from regular symbol
40  */
41 static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q, int err){
42  int k;
43  int val;
44  int map;
45 
46  for(k = 0; (state->N[Q] << k) < state->A[Q]; k++);
47 
48  map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
49 
50  if(err < 0)
51  err += state->range;
52  if(err >= ((state->range + 1) >> 1)) {
53  err -= state->range;
54  val = 2 * FFABS(err) - 1 - map;
55  } else
56  val = 2 * err + map;
57 
58  set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
59 
60  ff_jpegls_update_state_regular(state, Q, err);
61 }
62 
63 /**
64  * Encode error from run termination
65  */
66 static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb, int RItype, int err, int limit_add){
67  int k;
68  int val, map;
69  int Q = 365 + RItype;
70  int temp;
71 
72  temp = state->A[Q];
73  if(RItype)
74  temp += state->N[Q] >> 1;
75  for(k = 0; (state->N[Q] << k) < temp; k++);
76  map = 0;
77  if(!k && err && (2 * state->B[Q] < state->N[Q]))
78  map = 1;
79 
80  if(err < 0)
81  val = - (2 * err) - 1 - RItype + map;
82  else
83  val = 2 * err - RItype - map;
84  set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
85 
86  if(err < 0)
87  state->B[Q]++;
88  state->A[Q] += (val + 1 - RItype) >> 1;
89 
90  ff_jpegls_downscale_state(state, Q);
91 }
92 
93 /**
94  * Encode run value as specified by JPEG-LS standard
95  */
96 static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run, int comp, int trail){
97  while(run >= (1 << ff_log2_run[state->run_index[comp]])){
98  put_bits(pb, 1, 1);
99  run -= 1 << ff_log2_run[state->run_index[comp]];
100  if(state->run_index[comp] < 31)
101  state->run_index[comp]++;
102  }
103  /* if hit EOL, encode another full run, else encode aborted run */
104  if(!trail && run) {
105  put_bits(pb, 1, 1);
106  }else if(trail){
107  put_bits(pb, 1, 0);
108  if(ff_log2_run[state->run_index[comp]])
109  put_bits(pb, ff_log2_run[state->run_index[comp]], run);
110  }
111 }
112 
113 /**
114  * Encode one line of image
115  */
116 static inline void ls_encode_line(JLSState *state, PutBitContext *pb, void *last, void *cur, int last2, int w, int stride, int comp, int bits){
117  int x = 0;
118  int Ra, Rb, Rc, Rd;
119  int D0, D1, D2;
120 
121  while(x < w) {
122  int err, pred, sign;
123 
124  /* compute gradients */
125  Ra = x ? R(cur, x - stride) : R(last, x);
126  Rb = R(last, x);
127  Rc = x ? R(last, x - stride) : last2;
128  Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
129  D0 = Rd - Rb;
130  D1 = Rb - Rc;
131  D2 = Rc - Ra;
132 
133  /* run mode */
134  if((FFABS(D0) <= state->near) && (FFABS(D1) <= state->near) && (FFABS(D2) <= state->near)) {
135  int RUNval, RItype, run;
136 
137  run = 0;
138  RUNval = Ra;
139  while(x < w && (FFABS(R(cur, x) - RUNval) <= state->near)){
140  run++;
141  W(cur, x, Ra);
142  x += stride;
143  }
144  ls_encode_run(state, pb, run, comp, x < w);
145  if(x >= w)
146  return;
147  Rb = R(last, x);
148  RItype = (FFABS(Ra - Rb) <= state->near);
149  pred = RItype ? Ra : Rb;
150  err = R(cur, x) - pred;
151 
152  if(!RItype && Ra > Rb)
153  err = -err;
154 
155  if(state->near){
156  if(err > 0)
157  err = (state->near + err) / state->twonear;
158  else
159  err = -(state->near - err) / state->twonear;
160 
161  if(RItype || (Rb >= Ra))
162  Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
163  else
164  Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
165  W(cur, x, Ra);
166  }
167  if(err < 0)
168  err += state->range;
169  if(err >= ((state->range + 1) >> 1))
170  err -= state->range;
171 
172  ls_encode_runterm(state, pb, RItype, err, ff_log2_run[state->run_index[comp]]);
173 
174  if(state->run_index[comp] > 0)
175  state->run_index[comp]--;
176  } else { /* regular mode */
177  int context;
178 
179  context = ff_jpegls_quantize(state, D0) * 81 + ff_jpegls_quantize(state, D1) * 9 + ff_jpegls_quantize(state, D2);
180  pred = mid_pred(Ra, Ra + Rb - Rc, Rb);
181 
182  if(context < 0){
183  context = -context;
184  sign = 1;
185  pred = av_clip(pred - state->C[context], 0, state->maxval);
186  err = pred - R(cur, x);
187  }else{
188  sign = 0;
189  pred = av_clip(pred + state->C[context], 0, state->maxval);
190  err = R(cur, x) - pred;
191  }
192 
193  if(state->near){
194  if(err > 0)
195  err = (state->near + err) / state->twonear;
196  else
197  err = -(state->near - err) / state->twonear;
198  if(!sign)
199  Ra = av_clip(pred + err * state->twonear, 0, state->maxval);
200  else
201  Ra = av_clip(pred - err * state->twonear, 0, state->maxval);
202  W(cur, x, Ra);
203  }
204 
205  ls_encode_regular(state, pb, context, err);
206  }
207  x += stride;
208  }
209 }
210 
212  /* Test if we have default params and don't need to store LSE */
213  JLSState state2 = { 0 };
214  state2.bpp = state->bpp;
215  state2.near = state->near;
217  if(state->T1 == state2.T1 && state->T2 == state2.T2 && state->T3 == state2.T3 && state->reset == state2.reset)
218  return;
219  /* store LSE type 1 */
220  put_marker(pb, LSE);
221  put_bits(pb, 16, 13);
222  put_bits(pb, 8, 1);
223  put_bits(pb, 16, state->maxval);
224  put_bits(pb, 16, state->T1);
225  put_bits(pb, 16, state->T2);
226  put_bits(pb, 16, state->T3);
227  put_bits(pb, 16, state->reset);
228 }
229 
231  const AVFrame *pict, int *got_packet)
232 {
233  JpeglsContext * const s = avctx->priv_data;
234  AVFrame * const p = &s->picture;
235  const int near = avctx->prediction_method;
236  PutBitContext pb, pb2;
237  GetBitContext gb;
238  uint8_t *buf2, *zero, *cur, *last;
239  JLSState *state;
240  int i, size, ret;
241  int comps;
242 
243  *p = *pict;
245  p->key_frame= 1;
246 
247  if(avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16)
248  comps = 1;
249  else
250  comps = 3;
251 
252  if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*comps*4 +
253  FF_MIN_BUFFER_SIZE)) < 0)
254  return ret;
255 
256  buf2 = av_malloc(pkt->size);
257 
258  init_put_bits(&pb, pkt->data, pkt->size);
259  init_put_bits(&pb2, buf2, pkt->size);
260 
261  /* write our own JPEG header, can't use mjpeg_picture_header */
262  put_marker(&pb, SOI);
263  put_marker(&pb, SOF48);
264  put_bits(&pb, 16, 8 + comps * 3); // header size depends on components
265  put_bits(&pb, 8, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8); // bpp
266  put_bits(&pb, 16, avctx->height);
267  put_bits(&pb, 16, avctx->width);
268  put_bits(&pb, 8, comps); // components
269  for(i = 1; i <= comps; i++) {
270  put_bits(&pb, 8, i); // component ID
271  put_bits(&pb, 8, 0x11); // subsampling: none
272  put_bits(&pb, 8, 0); // Tiq, used by JPEG-LS ext
273  }
274 
275  put_marker(&pb, SOS);
276  put_bits(&pb, 16, 6 + comps * 2);
277  put_bits(&pb, 8, comps);
278  for(i = 1; i <= comps; i++) {
279  put_bits(&pb, 8, i); // component ID
280  put_bits(&pb, 8, 0); // mapping index: none
281  }
282  put_bits(&pb, 8, near);
283  put_bits(&pb, 8, (comps > 1) ? 1 : 0); // interleaving: 0 - plane, 1 - line
284  put_bits(&pb, 8, 0); // point transform: none
285 
286  state = av_mallocz(sizeof(JLSState));
287  /* initialize JPEG-LS state from JPEG parameters */
288  state->near = near;
289  state->bpp = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;
291  ff_jpegls_init_state(state);
292 
293  ls_store_lse(state, &pb);
294 
295  zero = av_mallocz(FFABS(p->linesize[0]));
296  if (!zero) {
297  av_free(state);
298  return AVERROR(ENOMEM);
299  }
300  last = zero;
301  cur = p->data[0];
302  if(avctx->pix_fmt == AV_PIX_FMT_GRAY8){
303  int t = 0;
304 
305  for(i = 0; i < avctx->height; i++) {
306  ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);
307  t = last[0];
308  last = cur;
309  cur += p->linesize[0];
310  }
311  }else if(avctx->pix_fmt == AV_PIX_FMT_GRAY16){
312  int t = 0;
313 
314  for(i = 0; i < avctx->height; i++) {
315  ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);
316  t = *((uint16_t*)last);
317  last = cur;
318  cur += p->linesize[0];
319  }
320  }else if(avctx->pix_fmt == AV_PIX_FMT_RGB24){
321  int j, width;
322  int Rc[3] = {0, 0, 0};
323 
324  width = avctx->width * 3;
325  for(i = 0; i < avctx->height; i++) {
326  for(j = 0; j < 3; j++) {
327  ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j, 8);
328  Rc[j] = last[j];
329  }
330  last = cur;
331  cur += s->picture.linesize[0];
332  }
333  }else if(avctx->pix_fmt == AV_PIX_FMT_BGR24){
334  int j, width;
335  int Rc[3] = {0, 0, 0};
336 
337  width = avctx->width * 3;
338  for(i = 0; i < avctx->height; i++) {
339  for(j = 2; j >= 0; j--) {
340  ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j, 8);
341  Rc[j] = last[j];
342  }
343  last = cur;
344  cur += s->picture.linesize[0];
345  }
346  }
347 
348  av_freep(&zero);
349  av_freep(&state);
350 
351  // the specification says that after doing 0xff escaping unused bits in the
352  // last byte must be set to 0, so just append 7 "optional" zero-bits to
353  // avoid special-casing.
354  put_bits(&pb2, 7, 0);
355  size = put_bits_count(&pb2);
356  flush_put_bits(&pb2);
357  /* do escape coding */
358  init_get_bits(&gb, buf2, size);
359  size -= 7;
360  while(get_bits_count(&gb) < size){
361  int v;
362  v = get_bits(&gb, 8);
363  put_bits(&pb, 8, v);
364  if(v == 0xFF){
365  v = get_bits(&gb, 7);
366  put_bits(&pb, 8, v);
367  }
368  }
370  av_free(buf2);
371 
372  /* End of image */
373  put_marker(&pb, EOI);
374  flush_put_bits(&pb);
375 
376  emms_c();
377 
378  pkt->size = put_bits_count(&pb) >> 3;
379  pkt->flags |= AV_PKT_FLAG_KEY;
380  *got_packet = 1;
381  return 0;
382 }
383 
386 
387  c->avctx = ctx;
388  ctx->coded_frame = &c->picture;
389 
391  av_log(ctx, AV_LOG_ERROR, "Only grayscale and RGB24/BGR24 images are supported\n");
392  return -1;
393  }
394  return 0;
395 }
396 
398  .name = "jpegls",
399  .type = AVMEDIA_TYPE_VIDEO,
400  .id = AV_CODEC_ID_JPEGLS,
401  .priv_data_size = sizeof(JpeglsContext),
402  .init = encode_init_ls,
403  .encode2 = encode_picture_ls,
404  .pix_fmts = (const enum AVPixelFormat[]){
407  },
408  .long_name = NULL_IF_CONFIG_SMALL("JPEG-LS"),
409 };
int reset
Definition: jpegls.h:42
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
const uint8_t ff_log2_run[41]
Definition: bitstream.c:37
float v
const char * s
Definition: avisynth_c.h:668
int T2
Definition: jpegls.h:40
This structure describes decoded (raw) audio or video data.
Definition: frame.h:76
AVCodec ff_jpegls_encoder
Definition: jpeglsenc.c:397
JPEG-LS.
Definition: mjpeg.h:107
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:70
static void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q, int err)
Encode error from regular symbol.
Definition: jpeglsenc.c:41
else temp
Definition: vf_mcdeint.c:148
AVFrame * coded_frame
the picture in the bitstream
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
int C[365]
Definition: jpegls.h:41
void avpriv_align_put_bits(PutBitContext *s)
Pad the bitstream with zeros up to the next byte boundary.
Definition: bitstream.c:46
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: mjpeg.h:74
int twonear
Definition: jpegls.h:43
uint8_t run
Definition: svq3.c:136
AVFrame picture
Definition: jpegls.h:36
int limit
Definition: jpegls.h:42
int stride
Definition: mace.c:144
MJPEG encoder and decoder.
output residual component w
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:198
int bpp
Definition: jpegls.h:42
int maxval
Definition: jpegls.h:42
uint8_t bits
Definition: crc.c:216
uint8_t
#define av_cold
Definition: attributes.h:78
static AVPacket pkt
Definition: demuxing.c:56
#define emms_c()
#define R
Definition: dsputil.c:2027
uint8_t * data
static int get_bits_count(const GetBitContext *s)
Definition: get_bits.h:193
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:116
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:96
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Discrete Time axis x
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:183
static void ls_store_lse(JLSState *state, PutBitContext *pb)
Definition: jpeglsenc.c:211
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
#define zero
Definition: regdef.h:64
void ff_jpegls_reset_coding_parameters(JLSState *s, int reset_all)
Calculate JPEG-LS codec values.
Definition: jpegls.c:57
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:246
const char * name
Name of the codec implementation.
static int ff_jpegls_update_state_regular(JLSState *state, int Q, int err)
Definition: jpegls.h:89
int B[367]
Definition: jpegls.h:41
static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pict, int *got_packet)
Definition: jpeglsenc.c:230
static void put_bits(J2kEncoderContext *s, int val, int n)
put n times val bit
Definition: j2kenc.c:160
external API header
int size
int flags
A combination of AV_PKT_FLAG values.
int near
Definition: jpegls.h:43
static int put_bits_count(PutBitContext *s)
Definition: put_bits.h:73
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:144
#define AV_PIX_FMT_GRAY16
Definition: pixfmt.h:266
Definition: mjpeg.h:76
#define FF_MIN_BUFFER_SIZE
minimum encoding buffer size Used to avoid some checks during header writing.
ret
Definition: avfilter.c:821
int width
picture width / height.
t
Definition: genspecsines3.m:6
#define FFABS(a)
Definition: common.h:53
static void ls_encode_runterm(JLSState *state, PutBitContext *pb, int RItype, int err, int limit_add)
Encode error from run termination.
Definition: jpeglsenc.c:66
packed RGB 8:8:8, 24bpp, BGRBGR...
Definition: pixfmt.h:71
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:509
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int size)
Check AVPacket size and/or allocate data.
Definition: mjpeg.h:75
static const float pred[4]
Definition: siprdata.h:259
int qbpp
Definition: jpegls.h:42
for k
static int width
Definition: tests/utils.c:158
AVCodecContext * avctx
Definition: jpegls.h:35
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:101
main external API structure.
int A[367]
Definition: jpegls.h:41
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:148
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:73
JPEG-LS common code.
synthesis window for stochastic i
int T1
Definition: jpegls.h:40
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition: get_bits.h:379
int range
Definition: jpegls.h:42
int N[367]
Definition: jpegls.h:41
#define mid_pred
Definition: mathops.h:94
static av_cold int encode_init_ls(AVCodecContext *ctx)
Definition: jpeglsenc.c:384
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFilterBuffer structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later.That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another.Buffer references ownership and permissions
static uint32_t state
Definition: trasher.c:27
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:87
Y , 8bpp.
Definition: pixfmt.h:76
common internal api header.
static void flush_put_bits(PutBitContext *s)
Pad the end of the output stream with zeros.
Definition: put_bits.h:81
static double c[64]
int prediction_method
prediction method (needed for huffyuv)
static void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
Initialize the PutBitContext s.
Definition: put_bits.h:54
static void put_marker(PutBitContext *p, int code)
Definition: mjpeg.h:122
static int ff_jpegls_quantize(JLSState *s, int v)
Calculate quantized gradient value, used for context determination.
Definition: jpegls.h:57
JPEG-LS extension parameters.
Definition: mjpeg.h:108
int key_frame
1 -> keyframe, 0-> not
Definition: frame.h:139
static void comp(unsigned char *dst, int dst_stride, unsigned char *src, int src_stride, int add)
Definition: eamad.c:71
int T3
Definition: jpegls.h:40
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:66
This structure stores compressed data.
int run_index[4]
Definition: jpegls.h:44
static void ff_jpegls_downscale_state(JLSState *state, int Q)
Definition: jpegls.h:80
normalize window W
Definition: stft_peak.m:10
struct JpeglsContext JpeglsContext
bitstream writer API