utvideo: handle empty Huffman trees
[libav.git] / libavcodec / utvideo.c
1 /*
2 * Ut Video decoder
3 * Copyright (c) 2011 Konstantin Shishkov
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /**
23 * @file
24 * Ut Video decoder
25 */
26
27 #include <stdlib.h>
28
29 #include "libavutil/intreadwrite.h"
30 #include "avcodec.h"
31 #include "bytestream.h"
32 #include "get_bits.h"
33 #include "dsputil.h"
34
35 enum {
36 PRED_NONE = 0,
37 PRED_LEFT,
38 PRED_GRADIENT,
39 PRED_MEDIAN,
40 };
41
42 typedef struct UtvideoContext {
43 AVCodecContext *avctx;
44 AVFrame pic;
45 DSPContext dsp;
46
47 uint32_t frame_info_size, flags, frame_info;
48 int planes;
49 int slices;
50 int compression;
51 int interlaced;
52 int frame_pred;
53
54 uint8_t *slice_bits;
55 int slice_bits_size;
56 } UtvideoContext;
57
58 typedef struct HuffEntry {
59 uint8_t sym;
60 uint8_t len;
61 } HuffEntry;
62
63 static int huff_cmp(const void *a, const void *b)
64 {
65 const HuffEntry *aa = a, *bb = b;
66 return (aa->len - bb->len)*256 + aa->sym - bb->sym;
67 }
68
69 static int build_huff(const uint8_t *src, VLC *vlc, int *fsym)
70 {
71 int i;
72 HuffEntry he[256];
73 int last;
74 uint32_t codes[256];
75 uint8_t bits[256];
76 uint8_t syms[256];
77 uint32_t code;
78
79 *fsym = -1;
80 for (i = 0; i < 256; i++) {
81 he[i].sym = i;
82 he[i].len = *src++;
83 }
84 qsort(he, 256, sizeof(*he), huff_cmp);
85
86 if (!he[0].len) {
87 *fsym = he[0].sym;
88 return 0;
89 }
90 if (he[0].len > 32)
91 return -1;
92
93 last = 255;
94 while (he[last].len == 255 && last)
95 last--;
96
97 code = 1;
98 for (i = last; i >= 0; i--) {
99 codes[i] = code >> (32 - he[i].len);
100 bits[i] = he[i].len;
101 syms[i] = he[i].sym;
102 code += 0x80000000u >> (he[i].len - 1);
103 }
104
105 return init_vlc_sparse(vlc, FFMIN(he[last].len, 9), last + 1,
106 bits, sizeof(*bits), sizeof(*bits),
107 codes, sizeof(*codes), sizeof(*codes),
108 syms, sizeof(*syms), sizeof(*syms), 0);
109 }
110
111 static int decode_plane(UtvideoContext *c, int plane_no,
112 uint8_t *dst, int step, int stride,
113 int width, int height,
114 const uint8_t *src, int src_size, int use_pred)
115 {
116 int i, j, slice, pix;
117 int sstart, send;
118 VLC vlc;
119 GetBitContext gb;
120 int prev, fsym;
121 const int cmask = ~(!plane_no && c->avctx->pix_fmt == PIX_FMT_YUV420P);
122
123 if (build_huff(src, &vlc, &fsym)) {
124 av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");
125 return AVERROR_INVALIDDATA;
126 }
127 if (fsym >= 0) { // build_huff reported a symbol to fill slices with
128 send = 0;
129 for (slice = 0; slice < c->slices; slice++) {
130 uint8_t *dest;
131
132 sstart = send;
133 send = (height * (slice + 1) / c->slices) & cmask;
134 dest = dst + sstart * stride;
135
136 prev = 0x80;
137 for (j = sstart; j < send; j++) {
138 for (i = 0; i < width * step; i += step) {
139 pix = fsym;
140 if (use_pred) {
141 prev += pix;
142 pix = prev;
143 }
144 dest[i] = pix;
145 }
146 dest += stride;
147 }
148 }
149 return 0;
150 }
151
152 src += 256;
153 src_size -= 256;
154
155 send = 0;
156 for (slice = 0; slice < c->slices; slice++) {
157 uint8_t *dest;
158 int slice_data_start, slice_data_end, slice_size;
159
160 sstart = send;
161 send = (height * (slice + 1) / c->slices) & cmask;
162 dest = dst + sstart * stride;
163
164 // slice offset and size validation was done earlier
165 slice_data_start = slice ? AV_RL32(src + slice * 4 - 4) : 0;
166 slice_data_end = AV_RL32(src + slice * 4);
167 slice_size = slice_data_end - slice_data_start;
168
169 if (!slice_size) {
170 for (j = sstart; j < send; j++) {
171 for (i = 0; i < width * step; i += step)
172 dest[i] = 0x80;
173 dest += stride;
174 }
175 continue;
176 }
177
178 memcpy(c->slice_bits, src + slice_data_start + c->slices * 4, slice_size);
179 memset(c->slice_bits + slice_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
180 c->dsp.bswap_buf((uint32_t*)c->slice_bits, (uint32_t*)c->slice_bits,
181 (slice_data_end - slice_data_start + 3) >> 2);
182 init_get_bits(&gb, c->slice_bits, slice_size * 8);
183
184 prev = 0x80;
185 for (j = sstart; j < send; j++) {
186 for (i = 0; i < width * step; i += step) {
187 if (get_bits_left(&gb) <= 0) {
188 av_log(c->avctx, AV_LOG_ERROR, "Slice decoding ran out of bits\n");
189 goto fail;
190 }
191 pix = get_vlc2(&gb, vlc.table, vlc.bits, 4);
192 if (pix < 0) {
193 av_log(c->avctx, AV_LOG_ERROR, "Decoding error\n");
194 goto fail;
195 }
196 if (use_pred) {
197 prev += pix;
198 pix = prev;
199 }
200 dest[i] = pix;
201 }
202 dest += stride;
203 }
204 if (get_bits_left(&gb) > 32)
205 av_log(c->avctx, AV_LOG_WARNING, "%d bits left after decoding slice\n",
206 get_bits_left(&gb));
207 }
208
209 free_vlc(&vlc);
210
211 return 0;
212 fail:
213 free_vlc(&vlc);
214 return AVERROR_INVALIDDATA;
215 }
216
217 static const int rgb_order[4] = { 1, 2, 0, 3 };
218
219 static void restore_rgb_planes(uint8_t *src, int step, int stride, int width, int height)
220 {
221 int i, j;
222 uint8_t r, g, b;
223
224 for (j = 0; j < height; j++) {
225 for (i = 0; i < width * step; i += step) {
226 r = src[i];
227 g = src[i + 1];
228 b = src[i + 2];
229 src[i] = r + g - 0x80;
230 src[i + 2] = b + g - 0x80;
231 }
232 src += stride;
233 }
234 }
235
236 static void restore_median(uint8_t *src, int step, int stride,
237 int width, int height, int slices, int rmode)
238 {
239 int i, j, slice;
240 int A, B, C;
241 uint8_t *bsrc;
242 int slice_start, slice_height;
243 const int cmask = ~rmode;
244
245 for (slice = 0; slice < slices; slice++) {
246 slice_start = ((slice * height) / slices) & cmask;
247 slice_height = ((((slice + 1) * height) / slices) & cmask) - slice_start;
248
249 bsrc = src + slice_start * stride;
250
251 // first line - left neighbour prediction
252 bsrc[0] += 0x80;
253 A = bsrc[0];
254 for (i = step; i < width * step; i += step) {
255 bsrc[i] += A;
256 A = bsrc[i];
257 }
258 bsrc += stride;
259 if (slice_height == 1)
260 continue;
261 // second line - first element has top predition, the rest uses median
262 C = bsrc[-stride];
263 bsrc[0] += C;
264 A = bsrc[0];
265 for (i = step; i < width * step; i += step) {
266 B = bsrc[i - stride];
267 bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
268 C = B;
269 A = bsrc[i];
270 }
271 bsrc += stride;
272 // the rest of lines use continuous median prediction
273 for (j = 2; j < slice_height; j++) {
274 for (i = 0; i < width * step; i += step) {
275 B = bsrc[i - stride];
276 bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
277 C = B;
278 A = bsrc[i];
279 }
280 bsrc += stride;
281 }
282 }
283 }
284
285 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
286 {
287 const uint8_t *buf = avpkt->data;
288 int buf_size = avpkt->size;
289 const uint8_t *buf_end = buf + buf_size;
290 UtvideoContext *c = avctx->priv_data;
291 const uint8_t *ptr;
292 int i, j;
293 const uint8_t *plane_start[5];
294 int plane_size, max_slice_size = 0, slice_start, slice_end, slice_size;
295 int ret;
296
297 if (c->pic.data[0])
298 avctx->release_buffer(avctx, &c->pic);
299
300 c->pic.reference = 1;
301 c->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
302 if ((ret = avctx->get_buffer(avctx, &c->pic)) < 0) {
303 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
304 return ret;
305 }
306
307 /* parse plane structure to retrieve frame flags and validate slice offsets */
308 ptr = buf;
309 for (i = 0; i < c->planes; i++) {
310 plane_start[i] = ptr;
311 if (buf_end - ptr < 256 + 4 * c->slices) {
312 av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");
313 return AVERROR_INVALIDDATA;
314 }
315 ptr += 256;
316 slice_start = 0;
317 slice_end = 0;
318 for (j = 0; j < c->slices; j++) {
319 slice_end = bytestream_get_le32(&ptr);
320 slice_size = slice_end - slice_start;
321 if (slice_size < 0) {
322 av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");
323 return AVERROR_INVALIDDATA;
324 }
325 slice_start = slice_end;
326 max_slice_size = FFMAX(max_slice_size, slice_size);
327 }
328 plane_size = slice_end;
329 if (buf_end - ptr < plane_size) {
330 av_log(avctx, AV_LOG_ERROR, "Plane size is bigger than available data\n");
331 return AVERROR_INVALIDDATA;
332 }
333 ptr += plane_size;
334 }
335 plane_start[c->planes] = ptr;
336 if (buf_end - ptr < c->frame_info_size) {
337 av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");
338 return AVERROR_INVALIDDATA;
339 }
340 c->frame_info = AV_RL32(ptr);
341 av_log(avctx, AV_LOG_DEBUG, "frame information flags %X\n", c->frame_info);
342
343 c->frame_pred = (c->frame_info >> 8) & 3;
344
345 if (c->frame_pred == PRED_GRADIENT) {
346 av_log_ask_for_sample(avctx, "Frame uses gradient prediction\n");
347 return AVERROR_PATCHWELCOME;
348 }
349
350 av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
351 max_slice_size + FF_INPUT_BUFFER_PADDING_SIZE);
352
353 if (!c->slice_bits) {
354 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
355 return AVERROR(ENOMEM);
356 }
357
358 switch (c->avctx->pix_fmt) {
359 case PIX_FMT_RGB24:
360 case PIX_FMT_RGBA:
361 for (i = 0; i < c->planes; i++) {
362 ret = decode_plane(c, i, c->pic.data[0] + rgb_order[i], c->planes,
363 c->pic.linesize[0], avctx->width, avctx->height,
364 plane_start[i], plane_start[i + 1] - plane_start[i],
365 c->frame_pred == PRED_LEFT);
366 if (ret)
367 return ret;
368 if (c->frame_pred == PRED_MEDIAN)
369 restore_median(c->pic.data[0] + rgb_order[i], c->planes,
370 c->pic.linesize[0], avctx->width, avctx->height,
371 c->slices, 0);
372 }
373 restore_rgb_planes(c->pic.data[0], c->planes, c->pic.linesize[0],
374 avctx->width, avctx->height);
375 break;
376 case PIX_FMT_YUV420P:
377 for (i = 0; i < 3; i++) {
378 ret = decode_plane(c, i, c->pic.data[i], 1,
379 c->pic.linesize[i], avctx->width >> !!i, avctx->height >> !!i,
380 plane_start[i], plane_start[i + 1] - plane_start[i],
381 c->frame_pred == PRED_LEFT);
382 if (ret)
383 return ret;
384 if (c->frame_pred == PRED_MEDIAN)
385 restore_median(c->pic.data[i], 1, c->pic.linesize[i],
386 avctx->width >> !!i, avctx->height >> !!i,
387 c->slices, !i);
388 }
389 break;
390 case PIX_FMT_YUV422P:
391 for (i = 0; i < 3; i++) {
392 ret = decode_plane(c, i, c->pic.data[i], 1,
393 c->pic.linesize[i], avctx->width >> !!i, avctx->height,
394 plane_start[i], plane_start[i + 1] - plane_start[i],
395 c->frame_pred == PRED_LEFT);
396 if (ret)
397 return ret;
398 if (c->frame_pred == PRED_MEDIAN)
399 restore_median(c->pic.data[i], 1, c->pic.linesize[i],
400 avctx->width >> !!i, avctx->height, c->slices, 0);
401 }
402 break;
403 }
404
405 *data_size = sizeof(AVFrame);
406 *(AVFrame*)data = c->pic;
407
408 /* always report that the buffer was completely consumed */
409 return buf_size;
410 }
411
412 static av_cold int decode_init(AVCodecContext *avctx)
413 {
414 UtvideoContext * const c = avctx->priv_data;
415
416 c->avctx = avctx;
417
418 dsputil_init(&c->dsp, avctx);
419
420 if (avctx->extradata_size < 16) {
421 av_log(avctx, AV_LOG_ERROR, "Insufficient extradata size %d, should be at least 16\n",
422 avctx->extradata_size);
423 return AVERROR_INVALIDDATA;
424 }
425
426 av_log(avctx, AV_LOG_DEBUG, "Encoder version %d.%d.%d.%d\n",
427 avctx->extradata[3], avctx->extradata[2],
428 avctx->extradata[1], avctx->extradata[0]);
429 av_log(avctx, AV_LOG_DEBUG, "Original format %X\n", AV_RB32(avctx->extradata + 4));
430 c->frame_info_size = AV_RL32(avctx->extradata + 8);
431 c->flags = AV_RL32(avctx->extradata + 12);
432
433 if (c->frame_info_size != 4)
434 av_log_ask_for_sample(avctx, "Frame info is not 4 bytes\n");
435 av_log(avctx, AV_LOG_DEBUG, "Encoding parameters %08X\n", c->flags);
436 c->slices = (c->flags >> 24) + 1;
437 c->compression = c->flags & 1;
438 c->interlaced = c->flags & 0x800;
439
440 c->slice_bits_size = 0;
441
442 switch (avctx->codec_tag) {
443 case MKTAG('U', 'L', 'R', 'G'):
444 c->planes = 3;
445 avctx->pix_fmt = PIX_FMT_RGB24;
446 break;
447 case MKTAG('U', 'L', 'R', 'A'):
448 c->planes = 4;
449 avctx->pix_fmt = PIX_FMT_RGBA;
450 break;
451 case MKTAG('U', 'L', 'Y', '0'):
452 c->planes = 3;
453 avctx->pix_fmt = PIX_FMT_YUV420P;
454 break;
455 case MKTAG('U', 'L', 'Y', '2'):
456 c->planes = 3;
457 avctx->pix_fmt = PIX_FMT_YUV422P;
458 break;
459 default:
460 av_log(avctx, AV_LOG_ERROR, "Unknown Ut Video FOURCC provided (%08X)\n",
461 avctx->codec_tag);
462 return AVERROR_INVALIDDATA;
463 }
464
465 return 0;
466 }
467
468 static av_cold int decode_end(AVCodecContext *avctx)
469 {
470 UtvideoContext * const c = avctx->priv_data;
471
472 if (c->pic.data[0])
473 avctx->release_buffer(avctx, &c->pic);
474
475 av_freep(&c->slice_bits);
476
477 return 0;
478 }
479
480 AVCodec ff_utvideo_decoder = {
481 .name = "utvideo",
482 .type = AVMEDIA_TYPE_VIDEO,
483 .id = CODEC_ID_UTVIDEO,
484 .priv_data_size = sizeof(UtvideoContext),
485 .init = decode_init,
486 .close = decode_end,
487 .decode = decode_frame,
488 .capabilities = CODEC_CAP_DR1,
489 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
490 };
491