]> git.sesse.net Git - ffmpeg/blob - libavcodec/jpeglsdec.c
libopusdec: fix out-of-bounds read
[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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; 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, Libav 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
55     skip_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     case 3:
71         av_log(s->avctx, AV_LOG_ERROR, "palette not supported\n");
72         return AVERROR(ENOSYS);
73     case 4:
74         av_log(s->avctx, AV_LOG_ERROR, "oversize image not supported\n");
75         return AVERROR(ENOSYS);
76     default:
77         av_log(s->avctx, AV_LOG_ERROR, "invalid id %d\n", id);
78         return AVERROR_INVALIDDATA;
79     }
80     ff_dlog(s->avctx, "ID=%i, T=%i,%i,%i\n", id, s->t1, s->t2, s->t3);
81
82     return 0;
83 }
84
85 /**
86  * Get context-dependent Golomb code, decode it and update context
87  */
88 static inline int ls_get_code_regular(GetBitContext *gb, JLSState *state, int Q)
89 {
90     int k, ret;
91
92     for (k = 0; (state->N[Q] << k) < state->A[Q]; k++)
93         ;
94
95 #ifdef JLS_BROKEN
96     if (!show_bits_long(gb, 32))
97         return -1;
98 #endif
99     ret = get_ur_golomb_jpegls(gb, k, state->limit, state->qbpp);
100
101     /* decode mapped error */
102     if (ret & 1)
103         ret = -(ret + 1 >> 1);
104     else
105         ret >>= 1;
106
107     /* for NEAR=0, k=0 and 2*B[Q] <= - N[Q] mapping is reversed */
108     if (!state->near && !k && (2 * state->B[Q] <= -state->N[Q]))
109         ret = -(ret + 1);
110
111     ret = ff_jpegls_update_state_regular(state, Q, ret);
112
113     return ret;
114 }
115
116 /**
117  * Get Golomb code, decode it and update state for run termination
118  */
119 static inline int ls_get_code_runterm(GetBitContext *gb, JLSState *state,
120                                       int RItype, int limit_add)
121 {
122     int k, ret, temp, map;
123     int Q = 365 + RItype;
124
125     temp = state->A[Q];
126     if (RItype)
127         temp += state->N[Q] >> 1;
128
129     for (k = 0; (state->N[Q] << k) < temp; k++)
130         ;
131
132 #ifdef JLS_BROKEN
133     if (!show_bits_long(gb, 32))
134         return -1;
135 #endif
136     ret = get_ur_golomb_jpegls(gb, k, state->limit - limit_add - 1,
137                                state->qbpp);
138
139     /* decode mapped error */
140     map = 0;
141     if (!k && (RItype || ret) && (2 * state->B[Q] < state->N[Q]))
142         map = 1;
143     ret += RItype + map;
144
145     if (ret & 1) {
146         ret = map - (ret + 1 >> 1);
147         state->B[Q]++;
148     } else {
149         ret = ret >> 1;
150     }
151
152     /* update state */
153     state->A[Q] += FFABS(ret) - RItype;
154     ret         *= state->twonear;
155     ff_jpegls_downscale_state(state, Q);
156
157     return ret;
158 }
159
160 /**
161  * Decode one line of image
162  */
163 static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s,
164                                   void *last, void *dst, int last2, int w,
165                                   int stride, int comp, int bits)
166 {
167     int i, x = 0;
168     int Ra, Rb, Rc, Rd;
169     int D0, D1, D2;
170
171     while (x < w) {
172         int err, pred;
173
174         /* compute gradients */
175         Ra = x ? R(dst, x - stride) : R(last, x);
176         Rb = R(last, x);
177         Rc = x ? R(last, x - stride) : last2;
178         Rd = (x >= w - stride) ? R(last, x) : R(last, x + stride);
179         D0 = Rd - Rb;
180         D1 = Rb - Rc;
181         D2 = Rc - Ra;
182         /* run mode */
183         if ((FFABS(D0) <= state->near) &&
184             (FFABS(D1) <= state->near) &&
185             (FFABS(D2) <= state->near)) {
186             int r;
187             int RItype;
188
189             /* decode full runs while available */
190             while (get_bits1(&s->gb)) {
191                 int r;
192                 r = 1 << ff_log2_run[state->run_index[comp]];
193                 if (x + r * stride > w)
194                     r = (w - x) / stride;
195                 for (i = 0; i < r; i++) {
196                     W(dst, x, Ra);
197                     x += stride;
198                 }
199                 /* if EOL reached, we stop decoding */
200                 if (r != 1 << ff_log2_run[state->run_index[comp]])
201                     return;
202                 if (state->run_index[comp] < 31)
203                     state->run_index[comp]++;
204                 if (x + stride > w)
205                     return;
206             }
207             /* decode aborted run */
208             r = ff_log2_run[state->run_index[comp]];
209             if (r)
210                 r = get_bits_long(&s->gb, r);
211             for (i = 0; i < r; i++) {
212                 W(dst, x, Ra);
213                 x += stride;
214             }
215
216             /* decode run termination value */
217             Rb     = R(last, x);
218             RItype = (FFABS(Ra - Rb) <= state->near) ? 1 : 0;
219             err    = ls_get_code_runterm(&s->gb, state, RItype,
220                                          ff_log2_run[state->run_index[comp]]);
221             if (state->run_index[comp])
222                 state->run_index[comp]--;
223
224             if (state->near && RItype) {
225                 pred = Ra + err;
226             } else {
227                 if (Rb < Ra)
228                     pred = Rb - err;
229                 else
230                     pred = Rb + err;
231             }
232         } else { /* regular mode */
233             int context, sign;
234
235             context = ff_jpegls_quantize(state, D0) * 81 +
236                       ff_jpegls_quantize(state, D1) *  9 +
237                       ff_jpegls_quantize(state, D2);
238             pred    = mid_pred(Ra, Ra + Rb - Rc, Rb);
239
240             if (context < 0) {
241                 context = -context;
242                 sign    = 1;
243             } else {
244                 sign = 0;
245             }
246
247             if (sign) {
248                 pred = av_clip(pred - state->C[context], 0, state->maxval);
249                 err  = -ls_get_code_regular(&s->gb, state, context);
250             } else {
251                 pred = av_clip(pred + state->C[context], 0, state->maxval);
252                 err  = ls_get_code_regular(&s->gb, state, context);
253             }
254
255             /* we have to do something more for near-lossless coding */
256             pred += err;
257         }
258         if (state->near) {
259             if (pred < -state->near)
260                 pred += state->range * state->twonear;
261             else if (pred > state->maxval + state->near)
262                 pred -= state->range * state->twonear;
263             pred = av_clip(pred, 0, state->maxval);
264         }
265
266         pred &= state->maxval;
267         W(dst, x, pred);
268         x += stride;
269     }
270 }
271
272 int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near,
273                              int point_transform, int ilv)
274 {
275     int i, t = 0;
276     uint8_t *zero, *last, *cur;
277     JLSState *state;
278     int off = 0, stride = 1, width, shift, ret = 0;
279
280     zero = av_mallocz(s->picture_ptr->linesize[0]);
281     if (!zero)
282         return AVERROR(ENOMEM);
283     last = zero;
284     cur  = s->picture_ptr->data[0];
285
286     state = av_mallocz(sizeof(JLSState));
287     if (!state) {
288         av_free(zero);
289         return AVERROR(ENOMEM);
290     }
291     /* initialize JPEG-LS state from JPEG parameters */
292     state->near   = near;
293     state->bpp    = (s->bits < 2) ? 2 : s->bits;
294     state->maxval = s->maxval;
295     state->T1     = s->t1;
296     state->T2     = s->t2;
297     state->T3     = s->t3;
298     state->reset  = s->reset;
299     ff_jpegls_reset_coding_parameters(state, 0);
300     ff_jpegls_init_state(state);
301
302     if (s->bits <= 8)
303         shift = point_transform + (8 - s->bits);
304     else
305         shift = point_transform + (16 - s->bits);
306
307     ff_dlog(s->avctx,
308             "JPEG-LS params: %ix%i NEAR=%i MV=%i T(%i,%i,%i) "
309             "RESET=%i, LIMIT=%i, qbpp=%i, RANGE=%i\n",
310             s->width, s->height, state->near, state->maxval,
311             state->T1, state->T2, state->T3,
312             state->reset, state->limit, state->qbpp, state->range);
313     ff_dlog(s->avctx, "JPEG params: ILV=%i Pt=%i BPP=%i, scan = %i\n",
314             ilv, point_transform, s->bits, s->cur_scan);
315     if (ilv == 0) { /* separate planes */
316         if (s->cur_scan > s->nb_components) {
317             ret = AVERROR_INVALIDDATA;
318             goto end;
319         }
320         off    = s->cur_scan - 1;
321         stride = (s->nb_components > 1) ? 3 : 1;
322         width  = s->width * stride;
323         cur   += off;
324         for (i = 0; i < s->height; i++) {
325             if (s->bits <= 8) {
326                 ls_decode_line(state, s, last, cur, t, width, stride, off, 8);
327                 t = last[0];
328             } else {
329                 ls_decode_line(state, s, last, cur, t, width, stride, off, 16);
330                 t = *((uint16_t *)last);
331             }
332             last = cur;
333             cur += s->picture_ptr->linesize[0];
334
335             if (s->restart_interval && !--s->restart_count) {
336                 align_get_bits(&s->gb);
337                 skip_bits(&s->gb, 16); /* skip RSTn */
338             }
339         }
340     } else if (ilv == 1) { /* line interleaving */
341         int j;
342         int Rc[3] = { 0, 0, 0 };
343         memset(cur, 0, s->picture_ptr->linesize[0]);
344         width = s->width * 3;
345         for (i = 0; i < s->height; i++) {
346             for (j = 0; j < 3; j++) {
347                 ls_decode_line(state, s, last + j, cur + j,
348                                Rc[j], width, 3, j, 8);
349                 Rc[j] = last[j];
350
351                 if (s->restart_interval && !--s->restart_count) {
352                     align_get_bits(&s->gb);
353                     skip_bits(&s->gb, 16); /* skip RSTn */
354                 }
355             }
356             last = cur;
357             cur += s->picture_ptr->linesize[0];
358         }
359     } else if (ilv == 2) { /* sample interleaving */
360         avpriv_report_missing_feature(s->avctx, "Sample interleaved images");
361         ret = AVERROR_PATCHWELCOME;
362         goto end;
363     }
364
365     if (shift) { /* we need to do point transform or normalize samples */
366         int x, w;
367
368         w = s->width * s->nb_components;
369
370         if (s->bits <= 8) {
371             uint8_t *src = s->picture_ptr->data[0];
372
373             for (i = 0; i < s->height; i++) {
374                 for (x = off; x < w; x += stride)
375                     src[x] <<= shift;
376                 src += s->picture_ptr->linesize[0];
377             }
378         } else {
379             uint16_t *src = (uint16_t *)s->picture_ptr->data[0];
380
381             for (i = 0; i < s->height; i++) {
382                 for (x = 0; x < w; x++)
383                     src[x] <<= shift;
384                 src += s->picture_ptr->linesize[0] / 2;
385             }
386         }
387     }
388
389 end:
390     av_free(state);
391     av_free(zero);
392
393     return ret;
394 }
395
396 AVCodec ff_jpegls_decoder = {
397     .name           = "jpegls",
398     .long_name      = NULL_IF_CONFIG_SMALL("JPEG-LS"),
399     .type           = AVMEDIA_TYPE_VIDEO,
400     .id             = AV_CODEC_ID_JPEGLS,
401     .priv_data_size = sizeof(MJpegDecodeContext),
402     .init           = ff_mjpeg_decode_init,
403     .close          = ff_mjpeg_decode_end,
404     .decode         = ff_mjpeg_decode_frame,
405     .capabilities   = AV_CODEC_CAP_DR1,
406     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
407 };