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