]> git.sesse.net Git - ffmpeg/blob - libavcodec/jpeglsdec.c
Merge commit 'b42f49e42f8cde25a788b2d13d03e99ca2956647'
[ffmpeg] / libavcodec / jpeglsdec.c
1 /*
2  * JPEG-LS decoder
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 decoder.
26  */
27
28 #include "avcodec.h"
29 #include "get_bits.h"
30 #include "golomb.h"
31 #include "mathops.h"
32 #include "mjpeg.h"
33 #include "mjpegdec.h"
34 #include "jpegls.h"
35 #include "jpeglsdec.h"
36
37 /*
38  * Uncomment this to significantly speed up decoding of broken JPEG-LS
39  * (or test broken JPEG-LS decoder) and slow down ordinary decoding a bit.
40  *
41  * There is no Golomb code with length >= 32 bits possible, so check and
42  * avoid situation of 32 zeros, FFmpeg Golomb decoder is painfully slow
43  * on this errors.
44  */
45 //#define JLS_BROKEN
46
47 /**
48  * Decode LSE block with initialization parameters
49  */
50 int ff_jpegls_decode_lse(MJpegDecodeContext *s)
51 {
52     int id;
53     int tid, wt, maxtab, i, j;
54
55     int len = get_bits(&s->gb, 16);  /* length: FIXME: verify field validity */
56     id = get_bits(&s->gb, 8);
57
58     switch (id) {
59     case 1:
60         s->maxval = get_bits(&s->gb, 16);
61         s->t1     = get_bits(&s->gb, 16);
62         s->t2     = get_bits(&s->gb, 16);
63         s->t3     = get_bits(&s->gb, 16);
64         s->reset  = get_bits(&s->gb, 16);
65
66 //        ff_jpegls_reset_coding_parameters(s, 0);
67         //FIXME quant table?
68         break;
69     case 2:
70         s->palette_index = 0;
71     case 3:
72         tid= get_bits(&s->gb, 8);
73         wt = get_bits(&s->gb, 8);
74
75         if (len < 5)
76             return AVERROR_INVALIDDATA;
77
78         if (wt < 1 || wt > MAX_COMPONENTS) {
79             avpriv_request_sample(s->avctx, "wt %d", wt);
80             return AVERROR_PATCHWELCOME;
81         }
82
83         if (!s->maxval)
84             maxtab = 255;
85         else if ((5 + wt*(s->maxval+1)) < 65535)
86             maxtab = s->maxval;
87         else
88             maxtab = 65530/wt - 1;
89
90         if(s->avctx->debug & FF_DEBUG_PICT_INFO) {
91             av_log(s->avctx, AV_LOG_DEBUG, "LSE palette %d tid:%d wt:%d maxtab:%d\n", id, tid, wt, maxtab);
92         }
93         if (maxtab >= 256) {
94             avpriv_request_sample(s->avctx, ">8bit palette");
95             return AVERROR_PATCHWELCOME;
96         }
97         maxtab = FFMIN(maxtab, (len - 5) / wt + s->palette_index);
98
99         if (s->palette_index > maxtab)
100             return AVERROR_INVALIDDATA;
101
102         if ((s->avctx->pix_fmt == AV_PIX_FMT_GRAY8 || s->avctx->pix_fmt == AV_PIX_FMT_PAL8) &&
103             (s->picture_ptr->format == AV_PIX_FMT_GRAY8 || s->picture_ptr->format == AV_PIX_FMT_PAL8)) {
104             uint32_t *pal = s->picture_ptr->data[1];
105             s->picture_ptr->format =
106             s->avctx->pix_fmt = AV_PIX_FMT_PAL8;
107             for (i=s->palette_index; i<=maxtab; i++) {
108                 pal[i] = 0;
109                 for (j=0; j<wt; j++) {
110                     pal[i] |= get_bits(&s->gb, 8) << (8*(wt-j-1));
111                 }
112             }
113             s->palette_index = i;
114         }
115         break;
116     case 4:
117         av_log(s->avctx, AV_LOG_ERROR, "oversize image not supported\n");
118         return AVERROR(ENOSYS);
119     default:
120         av_log(s->avctx, AV_LOG_ERROR, "invalid id %d\n", id);
121         return AVERROR_INVALIDDATA;
122     }
123     av_dlog(s->avctx, "ID=%i, T=%i,%i,%i\n", id, s->t1, s->t2, s->t3);
124
125     return 0;
126 }
127
128 /**
129  * Get context-dependent Golomb code, decode it and update context
130  */
131 static inline int ls_get_code_regular(GetBitContext *gb, JLSState *state, int Q)
132 {
133     int k, ret;
134
135     for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
136         ;
137
138 #ifdef JLS_BROKEN
139     if (!show_bits_long(gb, 32))
140         return -1;
141 #endif
142     ret = get_ur_golomb_jpegls(gb, k, state->limit, state->qbpp);
143
144     /* decode mapped error */
145     if (ret & 1)
146         ret = -(ret + 1 >> 1);
147     else
148         ret >>= 1;
149
150     /* for NEAR=0, k=0 and 2*B[Q] <= - N[Q] mapping is reversed */
151     if (!state->near && !k && (2 * state->B[Q] <= -state->N[Q]))
152         ret = -(ret + 1);
153
154     ret = ff_jpegls_update_state_regular(state, Q, ret);
155
156     return ret;
157 }
158
159 /**
160  * Get Golomb code, decode it and update state for run termination
161  */
162 static inline int ls_get_code_runterm(GetBitContext *gb, JLSState *state,
163                                       int RItype, int limit_add)
164 {
165     int k, ret, temp, map;
166     int Q = 365 + RItype;
167
168     temp = state->A[Q];
169     if (RItype)
170         temp += state->N[Q] >> 1;
171
172     for (k = 0; (state->N[Q] << k) < temp; k++)
173         ;
174
175 #ifdef JLS_BROKEN
176     if (!show_bits_long(gb, 32))
177         return -1;
178 #endif
179     ret = get_ur_golomb_jpegls(gb, k, state->limit - limit_add - 1,
180                                state->qbpp);
181
182     /* decode mapped error */
183     map = 0;
184     if (!k && (RItype || ret) && (2 * state->B[Q] < state->N[Q]))
185         map = 1;
186     ret += RItype + map;
187
188     if (ret & 1) {
189         ret = map - (ret + 1 >> 1);
190         state->B[Q]++;
191     } else {
192         ret = ret >> 1;
193     }
194
195     if(FFABS(ret) > 0xFFFF)
196         return -0x10000;
197     /* update state */
198     state->A[Q] += FFABS(ret) - RItype;
199     ret         *= state->twonear;
200     ff_jpegls_downscale_state(state, Q);
201
202     return ret;
203 }
204
205 /**
206  * Decode one line of image
207  */
208 static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s,
209                                   void *last, void *dst, int last2, int w,
210                                   int stride, int comp, int bits)
211 {
212     int i, x = 0;
213     int Ra, Rb, Rc, Rd;
214     int D0, D1, D2;
215
216     while (x < w) {
217         int err, pred;
218
219         /* compute gradients */
220         Ra = x ? R(dst, x - stride) : R(last, x);
221         Rb = R(last, x);
222         Rc = x ? R(last, x - stride) : last2;
223         Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
224         D0 = Rd - Rb;
225         D1 = Rb - Rc;
226         D2 = Rc - Ra;
227         /* run mode */
228         if ((FFABS(D0) <= state->near) &&
229             (FFABS(D1) <= state->near) &&
230             (FFABS(D2) <= state->near)) {
231             int r;
232             int RItype;
233
234             /* decode full runs while available */
235             while (get_bits1(&s->gb)) {
236                 int r;
237                 r = 1 << ff_log2_run[state->run_index[comp]];
238                 if (x + r * stride > w)
239                     r = (w - x) / stride;
240                 for (i = 0; i < r; i++) {
241                     W(dst, x, Ra);
242                     x += stride;
243                 }
244                 /* if EOL reached, we stop decoding */
245                 if (r != 1 << ff_log2_run[state->run_index[comp]])
246                     return;
247                 if (state->run_index[comp] < 31)
248                     state->run_index[comp]++;
249                 if (x + stride > w)
250                     return;
251             }
252             /* decode aborted run */
253             r = ff_log2_run[state->run_index[comp]];
254             if (r)
255                 r = get_bits_long(&s->gb, r);
256             if (x + r * stride > w) {
257                 r = (w - x) / stride;
258             }
259             for (i = 0; i < r; i++) {
260                 W(dst, x, Ra);
261                 x += stride;
262             }
263
264             /* decode run termination value */
265             Rb     = R(last, x);
266             RItype = (FFABS(Ra - Rb) <= state->near) ? 1 : 0;
267             err    = ls_get_code_runterm(&s->gb, state, RItype,
268                                          ff_log2_run[state->run_index[comp]]);
269             if (state->run_index[comp])
270                 state->run_index[comp]--;
271
272             if (state->near && RItype) {
273                 pred = Ra + err;
274             } else {
275                 if (Rb < Ra)
276                     pred = Rb - err;
277                 else
278                     pred = Rb + err;
279             }
280         } else { /* regular mode */
281             int context, sign;
282
283             context = ff_jpegls_quantize(state, D0) * 81 +
284                       ff_jpegls_quantize(state, D1) *  9 +
285                       ff_jpegls_quantize(state, D2);
286             pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
287
288             if (context < 0) {
289                 context = -context;
290                 sign    = 1;
291             } else {
292                 sign = 0;
293             }
294
295             if (sign) {
296                 pred = av_clip(pred - state->C[context], 0, state->maxval);
297                 err  = -ls_get_code_regular(&s->gb, state, context);
298             } else {
299                 pred = av_clip(pred + state->C[context], 0, state->maxval);
300                 err  = ls_get_code_regular(&s->gb, state, context);
301             }
302
303             /* we have to do something more for near-lossless coding */
304             pred += err;
305         }
306         if (state->near) {
307             if (pred < -state->near)
308                 pred += state->range * state->twonear;
309             else if (pred > state->maxval + state->near)
310                 pred -= state->range * state->twonear;
311             pred = av_clip(pred, 0, state->maxval);
312         }
313
314         pred &= state->maxval;
315         W(dst, x, pred);
316         x += stride;
317     }
318 }
319
320 int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near,
321                              int point_transform, int ilv)
322 {
323     int i, t = 0;
324     uint8_t *zero, *last, *cur;
325     JLSState *state;
326     int off = 0, stride = 1, width, shift, ret = 0;
327
328     zero = av_mallocz(s->picture_ptr->linesize[0]);
329     last = zero;
330     cur  = s->picture_ptr->data[0];
331
332     state = av_mallocz(sizeof(JLSState));
333     /* initialize JPEG-LS state from JPEG parameters */
334     state->near   = near;
335     state->bpp    = (s->bits < 2) ? 2 : s->bits;
336     state->maxval = s->maxval;
337     state->T1     = s->t1;
338     state->T2     = s->t2;
339     state->T3     = s->t3;
340     state->reset  = s->reset;
341     ff_jpegls_reset_coding_parameters(state, 0);
342     ff_jpegls_init_state(state);
343
344     if (s->bits <= 8)
345         shift = point_transform + (8 - s->bits);
346     else
347         shift = point_transform + (16 - s->bits);
348
349     if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
350         av_log(s->avctx, AV_LOG_DEBUG,
351                "JPEG-LS params: %ix%i NEAR=%i MV=%i T(%i,%i,%i) "
352                "RESET=%i, LIMIT=%i, qbpp=%i, RANGE=%i\n",
353                 s->width, s->height, state->near, state->maxval,
354                 state->T1, state->T2, state->T3,
355                 state->reset, state->limit, state->qbpp, state->range);
356         av_log(s->avctx, AV_LOG_DEBUG, "JPEG params: ILV=%i Pt=%i BPP=%i, scan = %i\n",
357                 ilv, point_transform, s->bits, s->cur_scan);
358     }
359     if (ilv == 0) { /* separate planes */
360         if (s->cur_scan > s->nb_components) {
361             ret = AVERROR_INVALIDDATA;
362             goto end;
363         }
364         stride = (s->nb_components > 1) ? 3 : 1;
365         off    = av_clip(s->cur_scan - 1, 0, stride - 1);
366         width  = s->width * stride;
367         cur   += off;
368         for (i = 0; i < s->height; i++) {
369             if (s->bits <= 8) {
370                 ls_decode_line(state, s, last, cur, t, width, stride, off, 8);
371                 t = last[0];
372             } else {
373                 ls_decode_line(state, s, last, cur, t, width, stride, off, 16);
374                 t = *((uint16_t *)last);
375             }
376             last = cur;
377             cur += s->picture_ptr->linesize[0];
378
379             if (s->restart_interval && !--s->restart_count) {
380                 align_get_bits(&s->gb);
381                 skip_bits(&s->gb, 16); /* skip RSTn */
382             }
383         }
384     } else if (ilv == 1) { /* line interleaving */
385         int j;
386         int Rc[3] = { 0, 0, 0 };
387         stride = (s->nb_components > 1) ? 3 : 1;
388         memset(cur, 0, s->picture_ptr->linesize[0]);
389         width = s->width * stride;
390         for (i = 0; i < s->height; i++) {
391             for (j = 0; j < stride; j++) {
392                 ls_decode_line(state, s, last + j, cur + j,
393                                Rc[j], width, stride, j, 8);
394                 Rc[j] = last[j];
395
396                 if (s->restart_interval && !--s->restart_count) {
397                     align_get_bits(&s->gb);
398                     skip_bits(&s->gb, 16); /* skip RSTn */
399                 }
400             }
401             last = cur;
402             cur += s->picture_ptr->linesize[0];
403         }
404     } else if (ilv == 2) { /* sample interleaving */
405         avpriv_report_missing_feature(s->avctx, "Sample interleaved images");
406         ret = AVERROR_PATCHWELCOME;
407         goto end;
408     }
409
410     if (s->xfrm && s->nb_components == 3) {
411         int x, w;
412
413         w = s->width * s->nb_components;
414
415         if (s->bits <= 8) {
416             uint8_t *src = s->picture_ptr->data[0];
417
418             for (i = 0; i < s->height; i++) {
419                 switch(s->xfrm) {
420                 case 1:
421                     for (x = off; x < w; x += 3) {
422                         src[x  ] += src[x+1] + 128;
423                         src[x+2] += src[x+1] + 128;
424                     }
425                     break;
426                 case 2:
427                     for (x = off; x < w; x += 3) {
428                         src[x  ] += src[x+1] + 128;
429                         src[x+2] += ((src[x  ] + src[x+1])>>1) + 128;
430                     }
431                     break;
432                 case 3:
433                     for (x = off; x < w; x += 3) {
434                         int g = src[x+0] - ((src[x+2]+src[x+1])>>2) + 64;
435                         src[x+0] = src[x+2] + g + 128;
436                         src[x+2] = src[x+1] + g + 128;
437                         src[x+1] = g;
438                     }
439                     break;
440                 case 4:
441                     for (x = off; x < w; x += 3) {
442                         int r    = src[x+0] - ((                       359 * (src[x+2]-128) + 490) >> 8);
443                         int g    = src[x+0] - (( 88 * (src[x+1]-128) - 183 * (src[x+2]-128) +  30) >> 8);
444                         int b    = src[x+0] + ((454 * (src[x+1]-128)                        + 574) >> 8);
445                         src[x+0] = av_clip_uint8(r);
446                         src[x+1] = av_clip_uint8(g);
447                         src[x+2] = av_clip_uint8(b);
448                     }
449                     break;
450                 }
451                 src += s->picture_ptr->linesize[0];
452             }
453         }else
454             avpriv_report_missing_feature(s->avctx, "16bit xfrm");
455     }
456
457     if (shift) { /* we need to do point transform or normalize samples */
458         int x, w;
459
460         w = s->width * s->nb_components;
461
462         if (s->bits <= 8) {
463             uint8_t *src = s->picture_ptr->data[0];
464
465             for (i = 0; i < s->height; i++) {
466                 for (x = off; x < w; x += stride)
467                     src[x] <<= shift;
468                 src += s->picture_ptr->linesize[0];
469             }
470         } else {
471             uint16_t *src = (uint16_t *)s->picture_ptr->data[0];
472
473             for (i = 0; i < s->height; i++) {
474                 for (x = 0; x < w; x++)
475                     src[x] <<= shift;
476                 src += s->picture_ptr->linesize[0] / 2;
477             }
478         }
479     }
480
481 end:
482     av_free(state);
483     av_free(zero);
484
485     return ret;
486 }
487
488 AVCodec ff_jpegls_decoder = {
489     .name           = "jpegls",
490     .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
491     .type           = AVMEDIA_TYPE_VIDEO,
492     .id             = AV_CODEC_ID_JPEGLS,
493     .priv_data_size = sizeof(MJpegDecodeContext),
494     .init           = ff_mjpeg_decode_init,
495     .close          = ff_mjpeg_decode_end,
496     .decode         = ff_mjpeg_decode_frame,
497     .capabilities   = CODEC_CAP_DR1,
498 };