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