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