2
* JPEG-LS encoder and decoder
3
* Copyright (c) 2003 Michael Niedermayer
4
* Copyright (c) 2006 Konstantin Shishkov
6
* This library is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU Lesser General Public
8
* License as published by the Free Software Foundation; either
9
* version 2 of the License, or (at your option) any later version.
11
* This library is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
* Lesser General Public License for more details.
16
* You should have received a copy of the GNU Lesser General Public
17
* License along with this library; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25
* JPEG-LS encoder and decoder.
28
typedef struct JpeglsContext{
29
AVCodecContext *avctx;
33
typedef struct JLSState{
35
int A[367], B[367], C[365], N[367];
36
int limit, reset, bpp, qbpp, maxval, range;
41
static const uint8_t log2_run[32]={
42
0, 0, 0, 0, 1, 1, 1, 1,
43
2, 2, 2, 2, 3, 3, 3, 3,
44
4, 4, 5, 5, 6, 6, 7, 7,
45
8, 9,10,11,12,13,14,15
49
* Uncomment this to significantly speed up decoding of broken JPEG-LS
50
* (or test broken JPEG-LS decoder) and slow down ordinary decoding a bit.
52
* There is no Golomb code with length >= 32 bits possible, so check and
53
* avoid situation of 32 zeros, FFmpeg Golomb decoder is painfully slow
58
/********** Functions for both encoder and decoder **********/
61
* Calculate initial JPEG-LS parameters
63
static void ls_init_state(JLSState *state){
66
state->twonear = state->near * 2 + 1;
67
state->range = ((state->maxval + state->twonear - 1) / state->twonear) + 1;
69
// QBPP = ceil(log2(RANGE))
70
for(state->qbpp = 0; (1 << state->qbpp) < state->range; state->qbpp++);
73
state->limit = 16 + 2 * state->bpp - state->qbpp;
75
state->limit = (4 * state->bpp) - state->qbpp;
77
for(i = 0; i < 367; i++) {
78
state->A[i] = (state->range + 32) >> 6;
87
* Calculate quantized gradient value, used for context determination
89
static inline int quantize(JLSState *s, int v){ //FIXME optimize
92
if(v <= -s->T3) return -4;
93
if(v <= -s->T2) return -3;
94
if(v <= -s->T1) return -2;
95
if(v < -s->near) return -1;
98
if(v <= s->near) return 0;
99
if(v < s->T1) return 1;
100
if(v < s->T2) return 2;
101
if(v < s->T3) return 3;
107
* Custom value clipping function used in T1, T2, T3 calculation
109
static inline int iso_clip(int v, int vmin, int vmax){
110
if(v > vmax || v < vmin) return vmin;
115
* Calculate JPEG-LS codec values
117
static void reset_ls_coding_parameters(JLSState *s, int reset_all){
118
const int basic_t1= 3;
119
const int basic_t2= 7;
120
const int basic_t3= 21;
123
if(s->maxval==0 || reset_all) s->maxval= (1 << s->bpp) - 1;
126
factor= (FFMIN(s->maxval, 4095) + 128)>>8;
128
if(s->T1==0 || reset_all)
129
s->T1= iso_clip(factor*(basic_t1-2) + 2 + 3*s->near, s->near+1, s->maxval);
130
if(s->T2==0 || reset_all)
131
s->T2= iso_clip(factor*(basic_t2-3) + 3 + 5*s->near, s->T1, s->maxval);
132
if(s->T3==0 || reset_all)
133
s->T3= iso_clip(factor*(basic_t3-4) + 4 + 7*s->near, s->T2, s->maxval);
135
factor= 256 / (s->maxval + 1);
137
if(s->T1==0 || reset_all)
138
s->T1= iso_clip(FFMAX(2, basic_t1/factor + 3*s->near), s->near+1, s->maxval);
139
if(s->T2==0 || reset_all)
140
s->T2= iso_clip(FFMAX(3, basic_t2/factor + 5*s->near), s->T1, s->maxval);
141
if(s->T3==0 || reset_all)
142
s->T3= iso_clip(FFMAX(4, basic_t3/factor + 6*s->near), s->T2, s->maxval);
145
if(s->reset==0 || reset_all) s->reset= 64;
146
// av_log(NULL, AV_LOG_DEBUG, "[JPEG-LS RESET] T=%i,%i,%i\n", s->T1, s->T2, s->T3);
150
/********** Decoder-specific functions **********/
153
* Decode LSE block with initialization parameters
155
static int decode_lse(MJpegDecodeContext *s)
159
/* XXX: verify len field validity */
160
len = get_bits(&s->gb, 16);
161
id = get_bits(&s->gb, 8);
165
s->maxval= get_bits(&s->gb, 16);
166
s->t1= get_bits(&s->gb, 16);
167
s->t2= get_bits(&s->gb, 16);
168
s->t3= get_bits(&s->gb, 16);
169
s->reset= get_bits(&s->gb, 16);
171
// reset_ls_coding_parameters(s, 0);
176
av_log(s->avctx, AV_LOG_ERROR, "palette not supported\n");
179
av_log(s->avctx, AV_LOG_ERROR, "oversize image not supported\n");
182
av_log(s->avctx, AV_LOG_ERROR, "invalid id %d\n", id);
185
// av_log(s->avctx, AV_LOG_DEBUG, "ID=%i, T=%i,%i,%i\n", id, s->t1, s->t2, s->t3);
192
* Get context-dependent Golomb code, decode it and update context
194
static inline int ls_get_code_regular(GetBitContext *gb, JLSState *state, int Q){
197
for(k = 0; (state->N[Q] << k) < state->A[Q]; k++);
200
if(!show_bits_long(gb, 32))return -1;
202
ret = get_ur_golomb_jpegls(gb, k, state->limit, state->qbpp);
204
/* decode mapped error */
206
ret = -((ret + 1) >> 1);
210
/* for NEAR=0, k=0 and 2*B[Q] <= - N[Q] mapping is reversed */
211
if(!state->near && !k && (2 * state->B[Q] <= -state->N[Q]))
214
state->A[Q] += ABS(ret);
215
ret *= state->twonear;
218
if(state->N[Q] == state->reset) {
225
if(state->B[Q] <= -state->N[Q]) {
226
state->B[Q] += state->N[Q];
227
if(state->C[Q] > -128)
229
if(state->B[Q] <= -state->N[Q])
230
state->B[Q] = -state->N[Q] + 1;
231
}else if(state->B[Q] > 0){
232
state->B[Q] -= state->N[Q];
233
if(state->C[Q] < 127)
243
* Get Golomb code, decode it and update state for run termination
245
static inline int ls_get_code_runterm(GetBitContext *gb, JLSState *state, int RItype, int limit_add){
246
int k, ret, temp, map;
247
int Q = 365 + RItype;
252
temp = state->A[Q] + (state->N[Q] >> 1);
254
for(k = 0; (state->N[Q] << k) < temp; k++);
257
if(!show_bits_long(gb, 32))return -1;
259
ret = get_ur_golomb_jpegls(gb, k, state->limit - limit_add - 1, state->qbpp);
261
/* decode mapped error */
263
if(!k && (RItype || ret) && (2 * state->B[Q] < state->N[Q]))
268
ret = map - ((ret + 1) >> 1);
275
state->A[Q] += ABS(ret) - RItype;
276
ret *= state->twonear;
277
if(state->N[Q] == state->reset){
288
* Decode one line of image
290
static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s, uint8_t *last, uint8_t *dst, int last2, int w, int stride, int comp){
298
/* compute gradients */
299
Ra = x ? dst[x - stride] : last[x];
301
Rc = x ? last[x - stride] : last2;
302
Rd = (x >= w - stride) ? last[x] : last[x + stride];
307
if((ABS(D0) <= state->near) && (ABS(D1) <= state->near) && (ABS(D2) <= state->near)) {
311
/* decode full runs while available */
312
while(get_bits1(&s->gb)) {
314
r = 1 << log2_run[state->run_index[comp]];
315
if(x + r * stride > w) {
316
r = (w - x) / stride;
318
for(i = 0; i < r; i++) {
322
/* if EOL reached, we stop decoding */
323
if(r != (1 << log2_run[state->run_index[comp]]))
325
if(state->run_index[comp] < 31)
326
state->run_index[comp]++;
330
/* decode aborted run */
331
r = log2_run[state->run_index[comp]];
333
r = get_bits_long(&s->gb, r);
334
for(i = 0; i < r; i++) {
339
/* decode run termination value */
341
RItype = (ABS(Ra - Rb) <= state->near) ? 1 : 0;
342
err = ls_get_code_runterm(&s->gb, state, RItype, log2_run[state->run_index[comp]]);
343
if(state->run_index[comp])
344
state->run_index[comp]--;
346
if(state->near && RItype){
356
if(pred < -state->near)
357
pred += state->range * state->twonear;
358
else if(pred > state->maxval + state->near)
359
pred -= state->range * state->twonear;
360
pred = clip(pred, 0, state->maxval);
365
} else { /* regular mode */
368
context = quantize(state, D0) * 81 + quantize(state, D1) * 9 + quantize(state, D2);
369
pred = mid_pred(Ra, Ra + Rb - Rc, Rb);
379
pred = clip(pred - state->C[context], 0, state->maxval);
380
err = -ls_get_code_regular(&s->gb, state, context);
382
pred = clip(pred + state->C[context], 0, state->maxval);
383
err = ls_get_code_regular(&s->gb, state, context);
386
/* we have to do something more for near-lossless coding */
389
if(pred < -state->near)
390
pred += state->range * state->twonear;
391
else if(pred > state->maxval + state->near)
392
pred -= state->range * state->twonear;
393
pred = clip(pred, 0, state->maxval);
402
static int ls_decode_picture(MJpegDecodeContext *s, int near, int point_transform, int ilv){
404
uint8_t *zero, *last, *cur;
406
int off, stride, width;
408
zero = av_mallocz(s->picture.linesize[0]);
410
cur = s->picture.data[0];
412
state = av_mallocz(sizeof(JLSState));
413
/* initialize JPEG-LS state from JPEG parameters */
415
state->bpp = (s->bits < 2) ? 2 : s->bits;
416
state->maxval = s->maxval;
420
state->reset = s->reset;
421
reset_ls_coding_parameters(state, 0);
422
ls_init_state(state);
424
// av_log(s->avctx, AV_LOG_DEBUG, "JPEG-LS params: %ix%i NEAR=%i MV=%i T(%i,%i,%i) RESET=%i, LIMIT=%i, qbpp=%i, RANGE=%i\n",s->width,s->height,state->near,state->maxval,state->T1,state->T2,state->T3,state->reset,state->limit,state->qbpp, state->range);
425
// av_log(s->avctx, AV_LOG_DEBUG, "JPEG params: ILV=%i Pt=%i BPP=%i, scan = %i\n", ilv, point_transform, s->bits, s->cur_scan);
426
if(ilv == 0) { /* separate planes */
427
off = s->cur_scan - 1;
428
stride = (s->nb_components > 1) ? 3 : 1;
429
width = s->width * stride;
431
for(i = 0; i < s->height; i++) {
432
ls_decode_line(state, s, last, cur, t, width, stride, off);
435
cur += s->picture.linesize[0];
437
if (s->restart_interval && !--s->restart_count) {
438
align_get_bits(&s->gb);
439
skip_bits(&s->gb, 16); /* skip RSTn */
442
} else if(ilv == 1) { /* line interleaving */
444
int Rc[3] = {0, 0, 0};
445
memset(cur, 0, s->picture.linesize[0]);
446
width = s->width * 3;
447
for(i = 0; i < s->height; i++) {
448
for(j = 0; j < 3; j++) {
449
ls_decode_line(state, s, last + j, cur + j, Rc[j], width, 3, j);
452
if (s->restart_interval && !--s->restart_count) {
453
align_get_bits(&s->gb);
454
skip_bits(&s->gb, 16); /* skip RSTn */
458
cur += s->picture.linesize[0];
460
} else if(ilv == 2) { /* sample interleaving */
461
av_log(s->avctx, AV_LOG_ERROR, "Sample interleaved images are not supported.\n");
471
#if defined(CONFIG_ENCODERS) && defined(CONFIG_JPEGLS_ENCODER)
472
/********** Encoder-specific functions **********/
475
* Encode error from regular symbol
477
static inline void ls_encode_regular(JLSState *state, PutBitContext *pb, int Q, int err){
482
for(k = 0; (state->N[Q] << k) < state->A[Q]; k++);
484
map = !state->near && !k && (2 * state->B[Q] <= -state->N[Q]);
488
if(err >= ((state->range + 1) >> 1)) {
490
val = 2 * ABS(err) - 1 - map;
494
set_ur_golomb_jpegls(pb, val, k, state->limit, state->qbpp);
496
state->A[Q] += ABS(err);
497
state->B[Q] += err * state->twonear;
499
if(state->N[Q] == state->reset) {
506
if(state->B[Q] <= -state->N[Q]) {
507
state->B[Q] += state->N[Q];
508
if(state->C[Q] > -128)
510
if(state->B[Q] <= -state->N[Q])
511
state->B[Q] = -state->N[Q] + 1;
512
}else if(state->B[Q] > 0){
513
state->B[Q] -= state->N[Q];
514
if(state->C[Q] < 127)
522
* Encode error from run termination
524
static inline void ls_encode_runterm(JLSState *state, PutBitContext *pb, int RItype, int err, int limit_add){
527
int Q = 365 + RItype;
532
temp += state->N[Q] >> 1;
533
for(k = 0; (state->N[Q] << k) < temp; k++);
535
if(!k && err && (2 * state->B[Q] < state->N[Q]))
539
val = - (2 * err) - 1 - RItype + map;
541
val = 2 * err - RItype - map;
542
set_ur_golomb_jpegls(pb, val, k, state->limit - limit_add - 1, state->qbpp);
546
state->A[Q] += (val + 1 - RItype) >> 1;
548
if(state->N[Q] == state->reset) {
557
* Encode run value as specified by JPEG-LS standard
559
static inline void ls_encode_run(JLSState *state, PutBitContext *pb, int run, int comp, int trail){
560
while(run >= (1 << log2_run[state->run_index[comp]])){
562
run -= 1 << log2_run[state->run_index[comp]];
563
if(state->run_index[comp] < 31)
564
state->run_index[comp]++;
566
/* if hit EOL, encode another full run, else encode aborted run */
571
if(log2_run[state->run_index[comp]])
572
put_bits(pb, log2_run[state->run_index[comp]], run);
577
* Encode one line of image
579
static inline void ls_encode_line(JLSState *state, PutBitContext *pb, uint8_t *last, uint8_t *cur, int last2, int w, int stride, int comp){
587
/* compute gradients */
588
Ra = x ? cur[x - stride] : last[x];
590
Rc = x ? last[x - stride] : last2;
591
Rd = (x >= w - stride) ? last[x] : last[x + stride];
597
if((ABS(D0) <= state->near) && (ABS(D1) <= state->near) && (ABS(D2) <= state->near)) {
598
int RUNval, RItype, run;
602
while(x < w && (ABS(cur[x] - RUNval) <= state->near)){
607
ls_encode_run(state, pb, run, comp, x < w);
611
RItype = (ABS(Ra - Rb) <= state->near);
612
pred = RItype ? Ra : Rb;
615
if(!RItype && Ra > Rb)
620
err = (state->near + err) / state->twonear;
622
err = -(state->near - err) / state->twonear;
624
if(RItype || (Rb >= Ra))
625
Ra = clip(pred + err * state->twonear, 0, state->maxval);
627
Ra = clip(pred - err * state->twonear, 0, state->maxval);
632
if(err >= ((state->range + 1) >> 1))
635
ls_encode_runterm(state, pb, RItype, err, log2_run[state->run_index[comp]]);
637
if(state->run_index[comp] > 0)
638
state->run_index[comp]--;
640
} else { /* regular mode */
643
context = quantize(state, D0) * 81 + quantize(state, D1) * 9 + quantize(state, D2);
644
pred = mid_pred(Ra, Ra + Rb - Rc, Rb);
649
pred = clip(pred - state->C[context], 0, state->maxval);
653
pred = clip(pred + state->C[context], 0, state->maxval);
659
err = (state->near + err) / state->twonear;
661
err = -(state->near - err) / state->twonear;
663
Ra = clip(pred + err * state->twonear, 0, state->maxval);
665
Ra = clip(pred - err * state->twonear, 0, state->maxval);
669
ls_encode_regular(state, pb, context, err);
675
static void ls_store_lse(JLSState *state, PutBitContext *pb){
676
/* Test if we have default params and don't need to store LSE */
678
memset(&state2, 0, sizeof(JLSState));
680
state2.near = state->near;
681
reset_ls_coding_parameters(&state2, 1);
682
if(state->T1 == state2.T1 && state->T2 == state2.T2 && state->T3 == state2.T3 && state->reset == state2.reset)
684
/* store LSE type 1 */
686
put_bits(pb, 16, 13);
688
put_bits(pb, 16, state->maxval);
689
put_bits(pb, 16, state->T1);
690
put_bits(pb, 16, state->T2);
691
put_bits(pb, 16, state->T3);
692
put_bits(pb, 16, state->reset);
695
static int encode_picture_ls(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){
696
JpeglsContext * const s = avctx->priv_data;
697
AVFrame *pict = data;
698
AVFrame * const p= (AVFrame*)&s->picture;
699
const int near = avctx->prediction_method;
700
PutBitContext pb, pb2;
702
uint8_t *buf2, *zero, *cur, *last;
707
buf2 = av_malloc(buf_size);
709
init_put_bits(&pb, buf, buf_size);
710
init_put_bits(&pb2, buf2, buf_size);
713
p->pict_type= FF_I_TYPE;
716
comps = (avctx->pix_fmt == PIX_FMT_GRAY8) ? 1 : 3;
718
/* write our own JPEG header, can't use mjpeg_picture_header */
719
put_marker(&pb, SOI);
720
put_marker(&pb, SOF48);
721
put_bits(&pb, 16, 8 + comps * 3); // header size depends on components
722
put_bits(&pb, 8, 8); // bpp
723
put_bits(&pb, 16, avctx->height);
724
put_bits(&pb, 16, avctx->width);
725
put_bits(&pb, 8, comps); // components
726
for(i = 1; i <= comps; i++) {
727
put_bits(&pb, 8, i); // component ID
728
put_bits(&pb, 8, 0x11); // subsampling: none
729
put_bits(&pb, 8, 0); // Tiq, used by JPEG-LS ext
732
put_marker(&pb, SOS);
733
put_bits(&pb, 16, 6 + comps * 2);
734
put_bits(&pb, 8, comps);
735
for(i = 1; i <= comps; i++) {
736
put_bits(&pb, 8, i); // component ID
737
put_bits(&pb, 8, 0); // mapping index: none
739
put_bits(&pb, 8, near);
740
put_bits(&pb, 8, (comps > 1) ? 1 : 0); // interleaving: 0 - plane, 1 - line
741
put_bits(&pb, 8, 0); // point transform: none
743
state = av_mallocz(sizeof(JLSState));
744
/* initialize JPEG-LS state from JPEG parameters */
747
reset_ls_coding_parameters(state, 0);
748
ls_init_state(state);
750
ls_store_lse(state, &pb);
752
zero = av_mallocz(p->linesize[0]);
755
if(avctx->pix_fmt == PIX_FMT_GRAY8){
758
for(i = 0; i < avctx->height; i++) {
759
ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0);
762
cur += p->linesize[0];
764
}else if(avctx->pix_fmt == PIX_FMT_RGB24){
766
int Rc[3] = {0, 0, 0};
768
width = avctx->width * 3;
769
for(i = 0; i < avctx->height; i++) {
770
for(j = 0; j < 3; j++) {
771
ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j);
775
cur += s->picture.linesize[0];
777
}else if(avctx->pix_fmt == PIX_FMT_BGR24){
779
int Rc[3] = {0, 0, 0};
781
width = avctx->width * 3;
782
for(i = 0; i < avctx->height; i++) {
783
for(j = 2; j >= 0; j--) {
784
ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j);
788
cur += s->picture.linesize[0];
795
flush_put_bits(&pb2);
796
/* do escape coding */
797
size = put_bits_count(&pb2) >> 3;
798
init_get_bits(&gb, buf2, size);
799
while(get_bits_count(&gb) < size * 8){
801
v = get_bits(&gb, 8);
804
v = get_bits(&gb, 7);
812
put_marker(&pb, EOI);
817
return put_bits_count(&pb) >> 3;
820
static int encode_init_ls(AVCodecContext *ctx) {
821
JpeglsContext *c = (JpeglsContext*)ctx->priv_data;
824
ctx->coded_frame = &c->picture;
826
if(ctx->pix_fmt != PIX_FMT_GRAY8 && ctx->pix_fmt != PIX_FMT_RGB24 && ctx->pix_fmt != PIX_FMT_BGR24){
827
av_log(ctx, AV_LOG_ERROR, "Only grayscale and RGB24/BGR24 images are supported\n");
833
AVCodec jpegls_encoder = { //FIXME avoid MPV_* lossless jpeg shouldnt need them
837
sizeof(JpeglsContext),
841
.pix_fmts= (enum PixelFormat[]){PIX_FMT_BGR24, PIX_FMT_RGB24, PIX_FMT_GRAY8, -1},