]> git.sesse.net Git - ffmpeg/blob - libavcodec/utvideo.c
378a1f7c1635cd59137c6e7df6097232cfc9951d
[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 #include "thread.h"
35
36 enum {
37     PRED_NONE = 0,
38     PRED_LEFT,
39     PRED_GRADIENT,
40     PRED_MEDIAN,
41 };
42
43 typedef struct UtvideoContext {
44     AVCodecContext *avctx;
45     AVFrame pic;
46     DSPContext dsp;
47
48     uint32_t frame_info_size, flags, frame_info;
49     int planes;
50     int slices;
51     int compression;
52     int interlaced;
53     int frame_pred;
54
55     uint8_t *slice_bits;
56     int slice_bits_size;
57 } UtvideoContext;
58
59 typedef struct HuffEntry {
60     uint8_t sym;
61     uint8_t len;
62 } HuffEntry;
63
64 static int huff_cmp(const void *a, const void *b)
65 {
66     const HuffEntry *aa = a, *bb = b;
67     return (aa->len - bb->len)*256 + aa->sym - bb->sym;
68 }
69
70 static int build_huff(const uint8_t *src, VLC *vlc, int *fsym)
71 {
72     int i;
73     HuffEntry he[256];
74     int last;
75     uint32_t codes[256];
76     uint8_t bits[256];
77     uint8_t syms[256];
78     uint32_t code;
79
80     *fsym = -1;
81     for (i = 0; i < 256; i++) {
82         he[i].sym = i;
83         he[i].len = *src++;
84     }
85     qsort(he, 256, sizeof(*he), huff_cmp);
86
87     if (!he[0].len) {
88         *fsym = he[0].sym;
89         return 0;
90     }
91     if (he[0].len > 32)
92         return -1;
93
94     last = 255;
95     while (he[last].len == 255 && last)
96         last--;
97
98     code = 1;
99     for (i = last; i >= 0; i--) {
100         codes[i] = code >> (32 - he[i].len);
101         bits[i]  = he[i].len;
102         syms[i]  = he[i].sym;
103         code += 0x80000000u >> (he[i].len - 1);
104     }
105
106     return ff_init_vlc_sparse(vlc, FFMIN(he[last].len, 9), last + 1,
107                               bits,  sizeof(*bits),  sizeof(*bits),
108                               codes, sizeof(*codes), sizeof(*codes),
109                               syms,  sizeof(*syms),  sizeof(*syms), 0);
110 }
111
112 static int decode_plane(UtvideoContext *c, int plane_no,
113                         uint8_t *dst, int step, int stride,
114                         int width, int height,
115                         const uint8_t *src, int use_pred)
116 {
117     int i, j, slice, pix;
118     int sstart, send;
119     VLC vlc;
120     GetBitContext gb;
121     int prev, fsym;
122     const int cmask = ~(!plane_no && c->avctx->pix_fmt == PIX_FMT_YUV420P);
123
124     if (build_huff(src, &vlc, &fsym)) {
125         av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");
126         return AVERROR_INVALIDDATA;
127     }
128     if (fsym >= 0) { // build_huff reported a symbol to fill slices with
129         send = 0;
130         for (slice = 0; slice < c->slices; slice++) {
131             uint8_t *dest;
132
133             sstart = send;
134             send   = (height * (slice + 1) / c->slices) & cmask;
135             dest   = dst + sstart * stride;
136
137             prev = 0x80;
138             for (j = sstart; j < send; j++) {
139                 for (i = 0; i < width * step; i += step) {
140                     pix = fsym;
141                     if (use_pred) {
142                         prev += pix;
143                         pix   = prev;
144                     }
145                     dest[i] = pix;
146                 }
147                 dest += stride;
148             }
149         }
150         return 0;
151     }
152
153     src      += 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     ff_free_vlc(&vlc);
210
211     return 0;
212 fail:
213     ff_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 /* UtVideo interlaced mode treats every two lines as a single one,
286  * so restoring function should take care of possible padding between
287  * two parts of the same "line".
288  */
289 static void restore_median_il(uint8_t *src, int step, int stride,
290                               int width, int height, int slices, int rmode)
291 {
292     int i, j, slice;
293     int A, B, C;
294     uint8_t *bsrc;
295     int slice_start, slice_height;
296     const int cmask = ~(rmode ? 3 : 1);
297     const int stride2 = stride << 1;
298
299     for (slice = 0; slice < slices; slice++) {
300         slice_start    = ((slice * height) / slices) & cmask;
301         slice_height   = ((((slice + 1) * height) / slices) & cmask) - slice_start;
302         slice_height >>= 1;
303
304         bsrc = src + slice_start * stride;
305
306         // first line - left neighbour prediction
307         bsrc[0] += 0x80;
308         A = bsrc[0];
309         for (i = step; i < width * step; i += step) {
310             bsrc[i] += A;
311             A = bsrc[i];
312         }
313         for (i = 0; i < width * step; i += step) {
314             bsrc[stride + i] += A;
315             A = bsrc[stride + i];
316         }
317         bsrc += stride2;
318         if (slice_height == 1)
319             continue;
320         // second line - first element has top predition, the rest uses median
321         C = bsrc[-stride2];
322         bsrc[0] += C;
323         A = bsrc[0];
324         for (i = step; i < width * step; i += step) {
325             B = bsrc[i - stride2];
326             bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
327             C = B;
328             A = bsrc[i];
329         }
330         for (i = 0; i < width * step; i += step) {
331             B = bsrc[i - stride];
332             bsrc[stride + i] += mid_pred(A, B, (uint8_t)(A + B - C));
333             C = B;
334             A = bsrc[stride + i];
335         }
336         bsrc += stride2;
337         // the rest of lines use continuous median prediction
338         for (j = 2; j < slice_height; j++) {
339             for (i = 0; i < width * step; i += step) {
340                 B = bsrc[i - stride2];
341                 bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
342                 C = B;
343                 A = bsrc[i];
344             }
345             for (i = 0; i < width * step; i += step) {
346                 B = bsrc[i - stride];
347                 bsrc[i + stride] += mid_pred(A, B, (uint8_t)(A + B - C));
348                 C = B;
349                 A = bsrc[i + stride];
350             }
351             bsrc += stride2;
352         }
353     }
354 }
355
356 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
357 {
358     const uint8_t *buf = avpkt->data;
359     int buf_size = avpkt->size;
360     UtvideoContext *c = avctx->priv_data;
361     int i, j;
362     const uint8_t *plane_start[5];
363     int plane_size, max_slice_size = 0, slice_start, slice_end, slice_size;
364     int ret;
365     GetByteContext gb;
366
367     if (c->pic.data[0])
368         ff_thread_release_buffer(avctx, &c->pic);
369
370     c->pic.reference = 1;
371     c->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
372     if ((ret = ff_thread_get_buffer(avctx, &c->pic)) < 0) {
373         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
374         return ret;
375     }
376
377     ff_thread_finish_setup(avctx);
378
379     /* parse plane structure to retrieve frame flags and validate slice offsets */
380     bytestream2_init(&gb, buf, buf_size);
381     for (i = 0; i < c->planes; i++) {
382         plane_start[i] = gb.buffer;
383         if (bytestream2_get_bytes_left(&gb) < 256 + 4 * c->slices) {
384             av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");
385             return AVERROR_INVALIDDATA;
386         }
387         bytestream2_skipu(&gb, 256);
388         slice_start = 0;
389         slice_end   = 0;
390         for (j = 0; j < c->slices; j++) {
391             slice_end   = bytestream2_get_le32u(&gb);
392             slice_size  = slice_end - slice_start;
393             if (slice_end <= 0 || slice_size <= 0 ||
394                 bytestream2_get_bytes_left(&gb) < slice_end) {
395                 av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");
396                 return AVERROR_INVALIDDATA;
397             }
398             slice_start = slice_end;
399             max_slice_size = FFMAX(max_slice_size, slice_size);
400         }
401         plane_size = slice_end;
402         bytestream2_skipu(&gb, plane_size);
403     }
404     plane_start[c->planes] = gb.buffer;
405     if (bytestream2_get_bytes_left(&gb) < c->frame_info_size) {
406         av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");
407         return AVERROR_INVALIDDATA;
408     }
409     c->frame_info = bytestream2_get_le32u(&gb);
410     av_log(avctx, AV_LOG_DEBUG, "frame information flags %X\n", c->frame_info);
411
412     c->frame_pred = (c->frame_info >> 8) & 3;
413
414     if (c->frame_pred == PRED_GRADIENT) {
415         av_log_ask_for_sample(avctx, "Frame uses gradient prediction\n");
416         return AVERROR_PATCHWELCOME;
417     }
418
419     av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
420                    max_slice_size + FF_INPUT_BUFFER_PADDING_SIZE);
421
422     if (!c->slice_bits) {
423         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
424         return AVERROR(ENOMEM);
425     }
426
427     switch (c->avctx->pix_fmt) {
428     case PIX_FMT_RGB24:
429     case PIX_FMT_RGBA:
430         for (i = 0; i < c->planes; i++) {
431             ret = decode_plane(c, i, c->pic.data[0] + rgb_order[i], c->planes,
432                                c->pic.linesize[0], avctx->width, avctx->height,
433                                plane_start[i], c->frame_pred == PRED_LEFT);
434             if (ret)
435                 return ret;
436             if (c->frame_pred == PRED_MEDIAN)
437                 restore_median(c->pic.data[0] + rgb_order[i], c->planes,
438                                c->pic.linesize[0], avctx->width, avctx->height,
439                                c->slices, 0);
440         }
441         restore_rgb_planes(c->pic.data[0], c->planes, c->pic.linesize[0],
442                            avctx->width, avctx->height);
443         break;
444     case PIX_FMT_YUV420P:
445         for (i = 0; i < 3; i++) {
446             ret = decode_plane(c, i, c->pic.data[i], 1,
447                                c->pic.linesize[i], avctx->width >> !!i, avctx->height >> !!i,
448                                plane_start[i], c->frame_pred == PRED_LEFT);
449             if (ret)
450                 return ret;
451             if (c->frame_pred == PRED_MEDIAN) {
452                 if (!c->interlaced) {
453                     restore_median(c->pic.data[i], 1, c->pic.linesize[i],
454                                    avctx->width >> !!i, avctx->height >> !!i,
455                                    c->slices, !i);
456                 } else {
457                     restore_median_il(c->pic.data[i], 1, c->pic.linesize[i],
458                                       avctx->width  >> !!i,
459                                       avctx->height >> !!i,
460                                       c->slices, !i);
461                 }
462             }
463         }
464         break;
465     case PIX_FMT_YUV422P:
466         for (i = 0; i < 3; i++) {
467             ret = decode_plane(c, i, c->pic.data[i], 1,
468                                c->pic.linesize[i], avctx->width >> !!i, avctx->height,
469                                plane_start[i], c->frame_pred == PRED_LEFT);
470             if (ret)
471                 return ret;
472             if (c->frame_pred == PRED_MEDIAN) {
473                 if (!c->interlaced) {
474                     restore_median(c->pic.data[i], 1, c->pic.linesize[i],
475                                    avctx->width >> !!i, avctx->height,
476                                    c->slices, 0);
477                 } else {
478                     restore_median_il(c->pic.data[i], 1, c->pic.linesize[i],
479                                       avctx->width >> !!i, avctx->height,
480                                       c->slices, 0);
481                 }
482             }
483         }
484         break;
485     }
486
487     c->pic.key_frame = 1;
488     c->pic.pict_type = AV_PICTURE_TYPE_I;
489     *data_size = sizeof(AVFrame);
490     *(AVFrame*)data = c->pic;
491
492     /* always report that the buffer was completely consumed */
493     return buf_size;
494 }
495
496 static av_cold int decode_init(AVCodecContext *avctx)
497 {
498     UtvideoContext * const c = avctx->priv_data;
499
500     c->avctx = avctx;
501
502     ff_dsputil_init(&c->dsp, avctx);
503
504     if (avctx->extradata_size < 16) {
505         av_log(avctx, AV_LOG_ERROR, "Insufficient extradata size %d, should be at least 16\n",
506                avctx->extradata_size);
507         return AVERROR_INVALIDDATA;
508     }
509
510     av_log(avctx, AV_LOG_DEBUG, "Encoder version %d.%d.%d.%d\n",
511            avctx->extradata[3], avctx->extradata[2],
512            avctx->extradata[1], avctx->extradata[0]);
513     av_log(avctx, AV_LOG_DEBUG, "Original format %X\n", AV_RB32(avctx->extradata + 4));
514     c->frame_info_size = AV_RL32(avctx->extradata + 8);
515     c->flags           = AV_RL32(avctx->extradata + 12);
516
517     if (c->frame_info_size != 4)
518         av_log_ask_for_sample(avctx, "Frame info is not 4 bytes\n");
519     av_log(avctx, AV_LOG_DEBUG, "Encoding parameters %08X\n", c->flags);
520     c->slices      = (c->flags >> 24) + 1;
521     c->compression = c->flags & 1;
522     c->interlaced  = c->flags & 0x800;
523
524     c->slice_bits_size = 0;
525
526     switch (avctx->codec_tag) {
527     case MKTAG('U', 'L', 'R', 'G'):
528         c->planes      = 3;
529         avctx->pix_fmt = PIX_FMT_RGB24;
530         break;
531     case MKTAG('U', 'L', 'R', 'A'):
532         c->planes      = 4;
533         avctx->pix_fmt = PIX_FMT_RGBA;
534         break;
535     case MKTAG('U', 'L', 'Y', '0'):
536         c->planes      = 3;
537         avctx->pix_fmt = PIX_FMT_YUV420P;
538         break;
539     case MKTAG('U', 'L', 'Y', '2'):
540         c->planes      = 3;
541         avctx->pix_fmt = PIX_FMT_YUV422P;
542         break;
543     default:
544         av_log(avctx, AV_LOG_ERROR, "Unknown Ut Video FOURCC provided (%08X)\n",
545                avctx->codec_tag);
546         return AVERROR_INVALIDDATA;
547     }
548
549     return 0;
550 }
551
552 static av_cold int decode_end(AVCodecContext *avctx)
553 {
554     UtvideoContext * const c = avctx->priv_data;
555
556     if (c->pic.data[0])
557         ff_thread_release_buffer(avctx, &c->pic);
558
559     av_freep(&c->slice_bits);
560
561     return 0;
562 }
563
564 AVCodec ff_utvideo_decoder = {
565     .name           = "utvideo",
566     .type           = AVMEDIA_TYPE_VIDEO,
567     .id             = CODEC_ID_UTVIDEO,
568     .priv_data_size = sizeof(UtvideoContext),
569     .init           = decode_init,
570     .close          = decode_end,
571     .decode         = decode_frame,
572     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
573     .long_name      = NULL_IF_CONFIG_SMALL("Ut Video"),
574 };