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