]> git.sesse.net Git - ffmpeg/blob - libavcodec/utvideo.c
Merge remote-tracking branch 'mans/dnxhd'
[ffmpeg] / 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)
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     for (i = 0; i < 256; i++) {
80         he[i].sym = i;
81         he[i].len = *src++;
82     }
83     qsort(he, 256, sizeof(*he), huff_cmp);
84
85     if (!he[0].len || he[0].len > 32)
86         return -1;
87
88     last = 255;
89     while (he[last].len == 255 && last)
90         last--;
91
92     code = 1;
93     for (i = last; i >= 0; i--) {
94         codes[i] = code >> (32 - he[i].len);
95         bits[i]  = he[i].len;
96         syms[i]  = he[i].sym;
97         code += 0x80000000u >> (he[i].len - 1);
98     }
99
100     return init_vlc_sparse(vlc, FFMIN(he[last].len, 9), last + 1,
101                            bits,  sizeof(*bits),  sizeof(*bits),
102                            codes, sizeof(*codes), sizeof(*codes),
103                            syms,  sizeof(*syms),  sizeof(*syms), 0);
104 }
105
106 static int decode_plane(UtvideoContext *c, int plane_no,
107                         uint8_t *dst, int step, int stride,
108                         int width, int height,
109                         const uint8_t *src, int src_size, int use_pred)
110 {
111     int i, j, slice, pix;
112     int sstart, send;
113     VLC vlc;
114     GetBitContext gb;
115     int prev;
116
117     if (build_huff(src, &vlc)) {
118         av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");
119         return AVERROR_INVALIDDATA;
120     }
121
122     src      += 256;
123     src_size -= 256;
124
125     send = 0;
126     for (slice = 0; slice < c->slices; slice++) {
127         uint8_t *dest;
128         int slice_data_start, slice_data_end, slice_size;
129
130         sstart = send;
131         send   = height * (slice + 1) / c->slices;
132         dest   = dst + sstart * stride;
133
134         // slice offset and size validation was done earlier
135         slice_data_start = slice ? AV_RL32(src + slice * 4 - 4) : 0;
136         slice_data_end   = AV_RL32(src + slice * 4);
137         slice_size       = slice_data_end - slice_data_start;
138
139         if (!slice_size) {
140             for (j = sstart; j < send; j++) {
141                 for (i = 0; i < width * step; i += step)
142                     dest[i] = 0x80;
143                 dest += stride;
144             }
145             continue;
146         }
147
148         memcpy(c->slice_bits, src + slice_data_start + c->slices * 4, slice_size);
149         memset(c->slice_bits + slice_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
150         c->dsp.bswap_buf((uint32_t*)c->slice_bits, (uint32_t*)c->slice_bits,
151                          (slice_data_end - slice_data_start + 3) >> 2);
152         init_get_bits(&gb, c->slice_bits, slice_size * 8);
153
154         prev = 0x80;
155         for (j = sstart; j < send; j++) {
156             for (i = 0; i < width * step; i += step) {
157                 if (get_bits_left(&gb) <= 0) {
158                     av_log(c->avctx, AV_LOG_ERROR, "Slice decoding ran out of bits\n");
159                     goto fail;
160                 }
161                 pix = get_vlc2(&gb, vlc.table, vlc.bits, 4);
162                 if (pix < 0) {
163                     av_log(c->avctx, AV_LOG_ERROR, "Decoding error\n");
164                     goto fail;
165                 }
166                 if (use_pred) {
167                     prev += pix;
168                     pix   = prev;
169                 }
170                 dest[i] = pix;
171             }
172             dest += stride;
173         }
174         if (get_bits_left(&gb) > 32)
175             av_log(c->avctx, AV_LOG_WARNING, "%d bits left after decoding slice\n",
176                    get_bits_left(&gb));
177     }
178
179     free_vlc(&vlc);
180
181     return 0;
182 fail:
183     free_vlc(&vlc);
184     return AVERROR_INVALIDDATA;
185 }
186
187 static const int rgb_order[4] = { 1, 2, 0, 3 };
188
189 static void restore_rgb_planes(uint8_t *src, int step, int stride, int width, int height)
190 {
191     int i, j;
192     uint8_t r, g, b;
193
194     for (j = 0; j < height; j++) {
195         for (i = 0; i < width * step; i += step) {
196             r = src[i];
197             g = src[i + 1];
198             b = src[i + 2];
199             src[i]     = r + g - 0x80;
200             src[i + 2] = b + g - 0x80;
201         }
202         src += stride;
203     }
204 }
205
206 static void restore_median(uint8_t *src, int step, int stride,
207                            int width, int height, int slices)
208 {
209     int i, j, slice;
210     int A, B, C;
211     uint8_t *bsrc;
212     int slice_start, slice_height;
213
214     for (slice = 0; slice < slices; slice++) {
215         slice_start = (slice * height) / slices;
216         slice_height = ((slice + 1) * height) / slices - slice_start;
217
218         bsrc = src + slice_start * stride;
219
220         // first line - left neighbour prediction
221         bsrc[0] += 0x80;
222         A = bsrc[0];
223         for (i = step; i < width * step; i += step) {
224             bsrc[i] += A;
225             A = bsrc[i];
226         }
227         bsrc += stride;
228         if (slice_height == 1)
229             continue;
230         // second line - first element has top predition, the rest uses median
231         C = bsrc[-stride];
232         bsrc[0] += C;
233         A = bsrc[0];
234         for (i = step; i < width * step; i += step) {
235             B = bsrc[i - stride];
236             bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
237             C = B;
238             A = bsrc[i];
239         }
240         bsrc += stride;
241         // the rest of lines use continuous median prediction
242         for (j = 2; j < slice_height; j++) {
243             for (i = 0; i < width * step; i += step) {
244                 B = bsrc[i - stride];
245                 bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
246                 C = B;
247                 A = bsrc[i];
248             }
249             bsrc += stride;
250         }
251     }
252 }
253
254 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
255 {
256     const uint8_t *buf = avpkt->data;
257     int buf_size = avpkt->size;
258     const uint8_t *buf_end = buf + buf_size;
259     UtvideoContext *c = avctx->priv_data;
260     const uint8_t *ptr;
261     int i, j;
262     const uint8_t *plane_start[5];
263     int plane_size, max_slice_size = 0, slice_start, slice_end, slice_size;
264     int ret;
265
266     if (c->pic.data[0])
267         avctx->release_buffer(avctx, &c->pic);
268
269     c->pic.reference = 1;
270     c->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
271     if ((ret = avctx->get_buffer(avctx, &c->pic)) < 0) {
272         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
273         return ret;
274     }
275
276     /* parse plane structure to retrieve frame flags and validate slice offsets */
277     ptr = buf;
278     for (i = 0; i < c->planes; i++) {
279         plane_start[i] = ptr;
280         if (buf_end - ptr < 256 + 4 * c->slices) {
281             av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");
282             return AVERROR_INVALIDDATA;
283         }
284         ptr += 256;
285         slice_start = 0;
286         slice_end   = 0;
287         for (j = 0; j < c->slices; j++) {
288             slice_end   = bytestream_get_le32(&ptr);
289             slice_size  = slice_end - slice_start;
290             if (slice_size < 0) {
291                 av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");
292                 return AVERROR_INVALIDDATA;
293             }
294             slice_start = slice_end;
295             max_slice_size = FFMAX(max_slice_size, slice_size);
296         }
297         plane_size = slice_end;
298         if (buf_end - ptr < plane_size) {
299             av_log(avctx, AV_LOG_ERROR, "Plane size is bigger than available data\n");
300             return AVERROR_INVALIDDATA;
301         }
302         ptr += plane_size;
303     }
304     plane_start[c->planes] = ptr;
305     if (buf_end - ptr < c->frame_info_size) {
306         av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");
307         return AVERROR_INVALIDDATA;
308     }
309     c->frame_info = AV_RL32(ptr);
310     av_log(avctx, AV_LOG_DEBUG, "frame information flags %X\n", c->frame_info);
311
312     c->frame_pred = (c->frame_info >> 8) & 3;
313
314     if (c->frame_pred == PRED_GRADIENT) {
315         av_log_ask_for_sample(avctx, "Frame uses gradient prediction\n");
316         return AVERROR_PATCHWELCOME;
317     }
318
319     av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
320                    max_slice_size + FF_INPUT_BUFFER_PADDING_SIZE);
321
322     if (!c->slice_bits) {
323         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
324         return AVERROR(ENOMEM);
325     }
326
327     switch (c->avctx->pix_fmt) {
328     case PIX_FMT_RGB24:
329     case PIX_FMT_RGBA:
330         for (i = 0; i < c->planes; i++) {
331             ret = decode_plane(c, i, c->pic.data[0] + rgb_order[i], c->planes,
332                                c->pic.linesize[0], avctx->width, avctx->height,
333                                plane_start[i], plane_start[i + 1] - plane_start[i],
334                                c->frame_pred == PRED_LEFT);
335             if (ret)
336                 return ret;
337             if (c->frame_pred == PRED_MEDIAN)
338                 restore_median(c->pic.data[0] + rgb_order[i], c->planes,
339                                c->pic.linesize[0], avctx->width, avctx->height,
340                                c->slices);
341         }
342         restore_rgb_planes(c->pic.data[0], c->planes, c->pic.linesize[0],
343                            avctx->width, avctx->height);
344         break;
345     case PIX_FMT_YUV420P:
346         for (i = 0; i < 3; i++) {
347             ret = decode_plane(c, i, c->pic.data[i], 1,
348                                c->pic.linesize[i], avctx->width >> !!i, avctx->height >> !!i,
349                                plane_start[i], plane_start[i + 1] - plane_start[i],
350                                c->frame_pred == PRED_LEFT);
351             if (ret)
352                 return ret;
353             if (c->frame_pred == PRED_MEDIAN)
354                 restore_median(c->pic.data[i], 1, c->pic.linesize[i],
355                                avctx->width >> !!i, avctx->height >> !!i,
356                                c->slices);
357         }
358         break;
359     case PIX_FMT_YUV422P:
360         for (i = 0; i < 3; i++) {
361             ret = decode_plane(c, i, c->pic.data[i], 1,
362                                c->pic.linesize[i], avctx->width >> !!i, avctx->height,
363                                plane_start[i], plane_start[i + 1] - plane_start[i],
364                                c->frame_pred == PRED_LEFT);
365             if (ret)
366                 return ret;
367             if (c->frame_pred == PRED_MEDIAN)
368                 restore_median(c->pic.data[i], 1, c->pic.linesize[i],
369                                avctx->width >> !!i, avctx->height, c->slices);
370         }
371         break;
372     }
373
374     *data_size = sizeof(AVFrame);
375     *(AVFrame*)data = c->pic;
376
377     /* always report that the buffer was completely consumed */
378     return buf_size;
379 }
380
381 static av_cold int decode_init(AVCodecContext *avctx)
382 {
383     UtvideoContext * const c = avctx->priv_data;
384
385     c->avctx = avctx;
386
387     dsputil_init(&c->dsp, avctx);
388
389     if (avctx->extradata_size < 16) {
390         av_log(avctx, AV_LOG_ERROR, "Insufficient extradata size %d, should be at least 16\n",
391                avctx->extradata_size);
392         return AVERROR_INVALIDDATA;
393     }
394
395     av_log(avctx, AV_LOG_DEBUG, "Encoder version %d.%d.%d.%d\n",
396            avctx->extradata[3], avctx->extradata[2],
397            avctx->extradata[1], avctx->extradata[0]);
398     av_log(avctx, AV_LOG_DEBUG, "Original format %X\n", AV_RB32(avctx->extradata + 4));
399     c->frame_info_size = AV_RL32(avctx->extradata + 8);
400     c->flags           = AV_RL32(avctx->extradata + 12);
401
402     if (c->frame_info_size != 4)
403         av_log_ask_for_sample(avctx, "Frame info is not 4 bytes\n");
404     av_log(avctx, AV_LOG_DEBUG, "Encoding parameters %08X\n", c->flags);
405     c->slices      = (c->flags >> 24) + 1;
406     c->compression = c->flags & 1;
407     c->interlaced  = c->flags & 0x800;
408
409     c->slice_bits_size = 0;
410
411     switch (avctx->codec_tag) {
412     case MKTAG('U', 'L', 'R', 'G'):
413         c->planes      = 3;
414         avctx->pix_fmt = PIX_FMT_RGB24;
415         break;
416     case MKTAG('U', 'L', 'R', 'A'):
417         c->planes      = 4;
418         avctx->pix_fmt = PIX_FMT_RGBA;
419         break;
420     case MKTAG('U', 'L', 'Y', '0'):
421         c->planes      = 3;
422         avctx->pix_fmt = PIX_FMT_YUV420P;
423         break;
424     case MKTAG('U', 'L', 'Y', '2'):
425         c->planes      = 3;
426         avctx->pix_fmt = PIX_FMT_YUV422P;
427         break;
428     default:
429         av_log(avctx, AV_LOG_ERROR, "Unknown Ut Video FOURCC provided (%08X)\n",
430                avctx->codec_tag);
431         return AVERROR_INVALIDDATA;
432     }
433
434     return 0;
435 }
436
437 static av_cold int decode_end(AVCodecContext *avctx)
438 {
439     UtvideoContext * const c = avctx->priv_data;
440
441     if (c->pic.data[0])
442         avctx->release_buffer(avctx, &c->pic);
443
444     av_freep(&c->slice_bits);
445
446     return 0;
447 }
448
449 AVCodec ff_utvideo_decoder = {
450     .name           = "utvideo",
451     .type           = AVMEDIA_TYPE_VIDEO,
452     .id             = CODEC_ID_UTVIDEO,
453     .priv_data_size = sizeof(UtvideoContext),
454     .init           = decode_init,
455     .close          = decode_end,
456     .decode         = decode_frame,
457     .capabilities   = CODEC_CAP_DR1,
458     .long_name      = NULL_IF_CONFIG_SMALL("Ut Video"),
459 };
460