]> git.sesse.net Git - ffmpeg/blob - libavcodec/utvideodec.c
Merge commit '78fa0b9033c0834c049e2aedf71a8c613fed87ab'
[ffmpeg] / libavcodec / utvideodec.c
1 /*
2  * Ut Video decoder
3  * Copyright (c) 2011 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 <inttypes.h>
28 #include <stdlib.h>
29
30 #define UNCHECKED_BITSTREAM_READER 1
31
32 #include "libavutil/intreadwrite.h"
33 #include "avcodec.h"
34 #include "bswapdsp.h"
35 #include "bytestream.h"
36 #include "get_bits.h"
37 #include "internal.h"
38 #include "thread.h"
39 #include "utvideo.h"
40
41 static int build_huff10(const uint8_t *src, VLC *vlc, int *fsym)
42 {
43     int i;
44     HuffEntry he[1024];
45     int last;
46     uint32_t codes[1024];
47     uint8_t bits[1024];
48     uint16_t syms[1024];
49     uint32_t code;
50
51     *fsym = -1;
52     for (i = 0; i < 1024; i++) {
53         he[i].sym = i;
54         he[i].len = *src++;
55     }
56     qsort(he, 1024, sizeof(*he), ff_ut10_huff_cmp_len);
57
58     if (!he[0].len) {
59         *fsym = he[0].sym;
60         return 0;
61     }
62
63     last = 1023;
64     while (he[last].len == 255 && last)
65         last--;
66
67     if (he[last].len > 32) {
68         return -1;
69     }
70
71     code = 1;
72     for (i = last; i >= 0; i--) {
73         codes[i] = code >> (32 - he[i].len);
74         bits[i]  = he[i].len;
75         syms[i]  = he[i].sym;
76         code += 0x80000000u >> (he[i].len - 1);
77     }
78 #define VLC_BITS 11
79     return ff_init_vlc_sparse(vlc, VLC_BITS, last + 1,
80                               bits,  sizeof(*bits),  sizeof(*bits),
81                               codes, sizeof(*codes), sizeof(*codes),
82                               syms,  sizeof(*syms),  sizeof(*syms), 0);
83 }
84
85 static int build_huff(const uint8_t *src, VLC *vlc, int *fsym)
86 {
87     int i;
88     HuffEntry he[256];
89     int last;
90     uint32_t codes[256];
91     uint8_t bits[256];
92     uint8_t syms[256];
93     uint32_t code;
94
95     *fsym = -1;
96     for (i = 0; i < 256; i++) {
97         he[i].sym = i;
98         he[i].len = *src++;
99     }
100     qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
101
102     if (!he[0].len) {
103         *fsym = he[0].sym;
104         return 0;
105     }
106
107     last = 255;
108     while (he[last].len == 255 && last)
109         last--;
110
111     if (he[last].len > 32)
112         return -1;
113
114     code = 1;
115     for (i = last; i >= 0; i--) {
116         codes[i] = code >> (32 - he[i].len);
117         bits[i]  = he[i].len;
118         syms[i]  = he[i].sym;
119         code += 0x80000000u >> (he[i].len - 1);
120     }
121
122     return ff_init_vlc_sparse(vlc, VLC_BITS, last + 1,
123                               bits,  sizeof(*bits),  sizeof(*bits),
124                               codes, sizeof(*codes), sizeof(*codes),
125                               syms,  sizeof(*syms),  sizeof(*syms), 0);
126 }
127
128 static int decode_plane10(UtvideoContext *c, int plane_no,
129                           uint16_t *dst, ptrdiff_t stride,
130                           int width, int height,
131                           const uint8_t *src, const uint8_t *huff,
132                           int use_pred)
133 {
134     int i, j, slice, pix, ret;
135     int sstart, send;
136     VLC vlc;
137     GetBitContext gb;
138     int prev, fsym;
139
140     if ((ret = build_huff10(huff, &vlc, &fsym)) < 0) {
141         av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");
142         return ret;
143     }
144     if (fsym >= 0) { // build_huff reported a symbol to fill slices with
145         send = 0;
146         for (slice = 0; slice < c->slices; slice++) {
147             uint16_t *dest;
148
149             sstart = send;
150             send   = (height * (slice + 1) / c->slices);
151             dest   = dst + sstart * stride;
152
153             prev = 0x200;
154             for (j = sstart; j < send; j++) {
155                 for (i = 0; i < width; i++) {
156                     pix = fsym;
157                     if (use_pred) {
158                         prev += pix;
159                         prev &= 0x3FF;
160                         pix   = prev;
161                     }
162                     dest[i] = pix;
163                 }
164                 dest += stride;
165             }
166         }
167         return 0;
168     }
169
170     send = 0;
171     for (slice = 0; slice < c->slices; slice++) {
172         uint16_t *dest;
173         int slice_data_start, slice_data_end, slice_size;
174
175         sstart = send;
176         send   = (height * (slice + 1) / c->slices);
177         dest   = dst + sstart * stride;
178
179         // slice offset and size validation was done earlier
180         slice_data_start = slice ? AV_RL32(src + slice * 4 - 4) : 0;
181         slice_data_end   = AV_RL32(src + slice * 4);
182         slice_size       = slice_data_end - slice_data_start;
183
184         if (!slice_size) {
185             av_log(c->avctx, AV_LOG_ERROR, "Plane has more than one symbol "
186                    "yet a slice has a length of zero.\n");
187             goto fail;
188         }
189
190         memset(c->slice_bits + slice_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
191         c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
192                           (uint32_t *)(src + slice_data_start + c->slices * 4),
193                           (slice_data_end - slice_data_start + 3) >> 2);
194         init_get_bits(&gb, c->slice_bits, slice_size * 8);
195
196         prev = 0x200;
197         for (j = sstart; j < send; j++) {
198             for (i = 0; i < width; i++) {
199                 pix = get_vlc2(&gb, vlc.table, VLC_BITS, 3);
200                 if (pix < 0) {
201                     av_log(c->avctx, AV_LOG_ERROR, "Decoding error\n");
202                     goto fail;
203                 }
204                 if (use_pred) {
205                     prev += pix;
206                     prev &= 0x3FF;
207                     pix   = prev;
208                 }
209                 dest[i] = pix;
210             }
211             dest += stride;
212             if (get_bits_left(&gb) < 0) {
213                 av_log(c->avctx, AV_LOG_ERROR,
214                         "Slice decoding ran out of bits\n");
215                 goto fail;
216             }
217         }
218         if (get_bits_left(&gb) > 32)
219             av_log(c->avctx, AV_LOG_WARNING,
220                    "%d bits left after decoding slice\n", get_bits_left(&gb));
221     }
222
223     ff_free_vlc(&vlc);
224
225     return 0;
226 fail:
227     ff_free_vlc(&vlc);
228     return AVERROR_INVALIDDATA;
229 }
230
231 static int compute_cmask(int plane_no, int interlaced, enum AVPixelFormat pix_fmt)
232 {
233     const int is_luma = (pix_fmt == AV_PIX_FMT_YUV420P) && !plane_no;
234
235     if (interlaced)
236         return ~(1 + 2 * is_luma);
237
238     return ~is_luma;
239 }
240
241 static int decode_plane(UtvideoContext *c, int plane_no,
242                         uint8_t *dst, ptrdiff_t stride,
243                         int width, int height,
244                         const uint8_t *src, int use_pred)
245 {
246     int i, j, slice, pix;
247     int sstart, send;
248     VLC vlc;
249     GetBitContext gb;
250     int ret, prev, fsym;
251     const int cmask = compute_cmask(plane_no, c->interlaced, c->avctx->pix_fmt);
252
253     if (c->pack) {
254         send = 0;
255         for (slice = 0; slice < c->slices; slice++) {
256             GetBitContext cbit, pbit;
257             uint8_t *dest, *p;
258
259             ret = init_get_bits8(&cbit, c->control_stream[plane_no][slice], c->control_stream_size[plane_no][slice]);
260             if (ret < 0)
261                 return ret;
262
263             ret = init_get_bits8(&pbit, c->packed_stream[plane_no][slice], c->packed_stream_size[plane_no][slice]);
264             if (ret < 0)
265                 return ret;
266
267             sstart = send;
268             send   = (height * (slice + 1) / c->slices) & cmask;
269             dest   = dst + sstart * stride;
270
271             if (3 * ((dst + send * stride - dest + 7)/8) > get_bits_left(&cbit))
272                 return AVERROR_INVALIDDATA;
273
274             for (p = dest; p < dst + send * stride; p += 8) {
275                 int bits = get_bits_le(&cbit, 3);
276
277                 if (bits == 0) {
278                     *(uint64_t *) p = 0;
279                 } else {
280                     uint32_t sub = 0x80 >> (8 - (bits + 1)), add;
281                     int k;
282
283                     if ((bits + 1) * 8 > get_bits_left(&pbit))
284                         return AVERROR_INVALIDDATA;
285
286                     for (k = 0; k < 8; k++) {
287
288                         p[k] = get_bits_le(&pbit, bits + 1);
289                         add = (~p[k] & sub) << (8 - bits);
290                         p[k] -= sub;
291                         p[k] += add;
292                     }
293                 }
294             }
295         }
296
297         return 0;
298     }
299
300     if (build_huff(src, &vlc, &fsym)) {
301         av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");
302         return AVERROR_INVALIDDATA;
303     }
304     if (fsym >= 0) { // build_huff reported a symbol to fill slices with
305         send = 0;
306         for (slice = 0; slice < c->slices; slice++) {
307             uint8_t *dest;
308
309             sstart = send;
310             send   = (height * (slice + 1) / c->slices) & cmask;
311             dest   = dst + sstart * stride;
312
313             prev = 0x80;
314             for (j = sstart; j < send; j++) {
315                 for (i = 0; i < width; i++) {
316                     pix = fsym;
317                     if (use_pred) {
318                         prev += pix;
319                         pix   = prev;
320                     }
321                     dest[i] = pix;
322                 }
323                 dest += stride;
324             }
325         }
326         return 0;
327     }
328
329     src      += 256;
330
331     send = 0;
332     for (slice = 0; slice < c->slices; slice++) {
333         uint8_t *dest;
334         int slice_data_start, slice_data_end, slice_size;
335
336         sstart = send;
337         send   = (height * (slice + 1) / c->slices) & cmask;
338         dest   = dst + sstart * stride;
339
340         // slice offset and size validation was done earlier
341         slice_data_start = slice ? AV_RL32(src + slice * 4 - 4) : 0;
342         slice_data_end   = AV_RL32(src + slice * 4);
343         slice_size       = slice_data_end - slice_data_start;
344
345         if (!slice_size) {
346             av_log(c->avctx, AV_LOG_ERROR, "Plane has more than one symbol "
347                    "yet a slice has a length of zero.\n");
348             goto fail;
349         }
350
351         memset(c->slice_bits + slice_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
352         c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
353                           (uint32_t *)(src + slice_data_start + c->slices * 4),
354                           (slice_data_end - slice_data_start + 3) >> 2);
355         init_get_bits(&gb, c->slice_bits, slice_size * 8);
356
357         prev = 0x80;
358         for (j = sstart; j < send; j++) {
359             for (i = 0; i < width; i++) {
360                 pix = get_vlc2(&gb, vlc.table, VLC_BITS, 3);
361                 if (pix < 0) {
362                     av_log(c->avctx, AV_LOG_ERROR, "Decoding error\n");
363                     goto fail;
364                 }
365                 if (use_pred) {
366                     prev += pix;
367                     pix   = prev;
368                 }
369                 dest[i] = pix;
370             }
371             if (get_bits_left(&gb) < 0) {
372                 av_log(c->avctx, AV_LOG_ERROR,
373                         "Slice decoding ran out of bits\n");
374                 goto fail;
375             }
376             dest += stride;
377         }
378         if (get_bits_left(&gb) > 32)
379             av_log(c->avctx, AV_LOG_WARNING,
380                    "%d bits left after decoding slice\n", get_bits_left(&gb));
381     }
382
383     ff_free_vlc(&vlc);
384
385     return 0;
386 fail:
387     ff_free_vlc(&vlc);
388     return AVERROR_INVALIDDATA;
389 }
390
391 #undef A
392 #undef B
393 #undef C
394
395 static void restore_median_planar(UtvideoContext *c, uint8_t *src, ptrdiff_t stride,
396                                   int width, int height, int slices, int rmode)
397 {
398     int i, j, slice;
399     int A, B, C;
400     uint8_t *bsrc;
401     int slice_start, slice_height;
402     const int cmask = ~rmode;
403
404     for (slice = 0; slice < slices; slice++) {
405         slice_start  = ((slice * height) / slices) & cmask;
406         slice_height = ((((slice + 1) * height) / slices) & cmask) -
407                        slice_start;
408
409         if (!slice_height)
410             continue;
411         bsrc = src + slice_start * stride;
412
413         // first line - left neighbour prediction
414         bsrc[0] += 0x80;
415         c->llviddsp.add_left_pred(bsrc, bsrc, width, 0);
416         bsrc += stride;
417         if (slice_height <= 1)
418             continue;
419         // second line - first element has top prediction, the rest uses median
420         C        = bsrc[-stride];
421         bsrc[0] += C;
422         A        = bsrc[0];
423         for (i = 1; i < FFMIN(width, 16); i++) { /* scalar loop (DSP need align 16) */
424             B        = bsrc[i - stride];
425             bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
426             C        = B;
427             A        = bsrc[i];
428         }
429         if (width > 16)
430             c->llviddsp.add_median_pred(bsrc + 16, bsrc - stride + 16,
431                                         bsrc + 16, width - 16, &A, &B);
432
433         bsrc += stride;
434         // the rest of lines use continuous median prediction
435         for (j = 2; j < slice_height; j++) {
436             c->llviddsp.add_median_pred(bsrc, bsrc - stride,
437                                             bsrc, width, &A, &B);
438             bsrc += stride;
439         }
440     }
441 }
442
443 /* UtVideo interlaced mode treats every two lines as a single one,
444  * so restoring function should take care of possible padding between
445  * two parts of the same "line".
446  */
447 static void restore_median_planar_il(UtvideoContext *c, uint8_t *src, ptrdiff_t stride,
448                                      int width, int height, int slices, int rmode)
449 {
450     int i, j, slice;
451     int A, B, C;
452     uint8_t *bsrc;
453     int slice_start, slice_height;
454     const int cmask   = ~(rmode ? 3 : 1);
455     const ptrdiff_t stride2 = stride << 1;
456
457     for (slice = 0; slice < slices; slice++) {
458         slice_start    = ((slice * height) / slices) & cmask;
459         slice_height   = ((((slice + 1) * height) / slices) & cmask) -
460                          slice_start;
461         slice_height >>= 1;
462         if (!slice_height)
463             continue;
464
465         bsrc = src + slice_start * stride;
466
467         // first line - left neighbour prediction
468         bsrc[0] += 0x80;
469         A = c->llviddsp.add_left_pred(bsrc, bsrc, width, 0);
470         c->llviddsp.add_left_pred(bsrc + stride, bsrc + stride, width, A);
471         bsrc += stride2;
472         if (slice_height <= 1)
473             continue;
474         // second line - first element has top prediction, the rest uses median
475         C        = bsrc[-stride2];
476         bsrc[0] += C;
477         A        = bsrc[0];
478         for (i = 1; i < FFMIN(width, 16); i++) { /* scalar loop (DSP need align 16) */
479             B        = bsrc[i - stride2];
480             bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
481             C        = B;
482             A        = bsrc[i];
483         }
484         if (width > 16)
485             c->llviddsp.add_median_pred(bsrc + 16, bsrc - stride2 + 16,
486                                         bsrc + 16, width - 16, &A, &B);
487
488         c->llviddsp.add_median_pred(bsrc + stride, bsrc - stride,
489                                         bsrc + stride, width, &A, &B);
490         bsrc += stride2;
491         // the rest of lines use continuous median prediction
492         for (j = 2; j < slice_height; j++) {
493             c->llviddsp.add_median_pred(bsrc, bsrc - stride2,
494                                             bsrc, width, &A, &B);
495             c->llviddsp.add_median_pred(bsrc + stride, bsrc - stride,
496                                             bsrc + stride, width, &A, &B);
497             bsrc += stride2;
498         }
499     }
500 }
501
502 static void restore_gradient_planar(UtvideoContext *c, uint8_t *src, ptrdiff_t stride,
503                                     int width, int height, int slices, int rmode)
504 {
505     int i, j, slice;
506     int A, B, C;
507     uint8_t *bsrc;
508     int slice_start, slice_height;
509     const int cmask = ~rmode;
510     int min_width = FFMIN(width, 32);
511
512     for (slice = 0; slice < slices; slice++) {
513         slice_start  = ((slice * height) / slices) & cmask;
514         slice_height = ((((slice + 1) * height) / slices) & cmask) -
515                        slice_start;
516
517         if (!slice_height)
518             continue;
519         bsrc = src + slice_start * stride;
520
521         // first line - left neighbour prediction
522         bsrc[0] += 0x80;
523         c->llviddsp.add_left_pred(bsrc, bsrc, width, 0);
524         bsrc += stride;
525         if (slice_height <= 1)
526             continue;
527         for (j = 1; j < slice_height; j++) {
528             // second line - first element has top prediction, the rest uses gradient
529             bsrc[0] = (bsrc[0] + bsrc[-stride]) & 0xFF;
530             for (i = 1; i < min_width; i++) { /* dsp need align 32 */
531                 A = bsrc[i - stride];
532                 B = bsrc[i - (stride + 1)];
533                 C = bsrc[i - 1];
534                 bsrc[i] = (A - B + C + bsrc[i]) & 0xFF;
535             }
536             if (width > 32)
537                 c->llviddsp.add_gradient_pred(bsrc + 32, stride, width - 32);
538             bsrc += stride;
539         }
540     }
541 }
542
543 static void restore_gradient_planar_il(UtvideoContext *c, uint8_t *src, ptrdiff_t stride,
544                                       int width, int height, int slices, int rmode)
545 {
546     int i, j, slice;
547     int A, B, C;
548     uint8_t *bsrc;
549     int slice_start, slice_height;
550     const int cmask   = ~(rmode ? 3 : 1);
551     const ptrdiff_t stride2 = stride << 1;
552     int min_width = FFMIN(width, 32);
553
554     for (slice = 0; slice < slices; slice++) {
555         slice_start    = ((slice * height) / slices) & cmask;
556         slice_height   = ((((slice + 1) * height) / slices) & cmask) -
557                          slice_start;
558         slice_height >>= 1;
559         if (!slice_height)
560             continue;
561
562         bsrc = src + slice_start * stride;
563
564         // first line - left neighbour prediction
565         bsrc[0] += 0x80;
566         A = c->llviddsp.add_left_pred(bsrc, bsrc, width, 0);
567         c->llviddsp.add_left_pred(bsrc + stride, bsrc + stride, width, A);
568         bsrc += stride2;
569         if (slice_height <= 1)
570             continue;
571         for (j = 1; j < slice_height; j++) {
572             // second line - first element has top prediction, the rest uses gradient
573             bsrc[0] = (bsrc[0] + bsrc[-stride2]) & 0xFF;
574             for (i = 1; i < min_width; i++) { /* dsp need align 32 */
575                 A = bsrc[i - stride2];
576                 B = bsrc[i - (stride2 + 1)];
577                 C = bsrc[i - 1];
578                 bsrc[i] = (A - B + C + bsrc[i]) & 0xFF;
579             }
580             if (width > 32)
581                 c->llviddsp.add_gradient_pred(bsrc + 32, stride2, width - 32);
582
583             A = bsrc[-stride];
584             B = bsrc[-(1 + stride + stride - width)];
585             C = bsrc[width - 1];
586             bsrc[stride] = (A - B + C + bsrc[stride]) & 0xFF;
587             for (i = 1; i < width; i++) {
588                 A = bsrc[i - stride];
589                 B = bsrc[i - (1 + stride)];
590                 C = bsrc[i - 1 + stride];
591                 bsrc[i + stride] = (A - B + C + bsrc[i + stride]) & 0xFF;
592             }
593             bsrc += stride2;
594         }
595     }
596 }
597
598 static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
599                         AVPacket *avpkt)
600 {
601     const uint8_t *buf = avpkt->data;
602     int buf_size = avpkt->size;
603     UtvideoContext *c = avctx->priv_data;
604     int i, j;
605     const uint8_t *plane_start[5];
606     int plane_size, max_slice_size = 0, slice_start, slice_end, slice_size;
607     int ret;
608     GetByteContext gb;
609     ThreadFrame frame = { .f = data };
610
611     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
612         return ret;
613
614     /* parse plane structure to get frame flags and validate slice offsets */
615     bytestream2_init(&gb, buf, buf_size);
616
617     if (c->pack) {
618         const uint8_t *packed_stream;
619         const uint8_t *control_stream;
620         GetByteContext pb;
621         uint32_t nb_cbs;
622         int left;
623
624         c->frame_info = PRED_GRADIENT << 8;
625
626         if (bytestream2_get_byte(&gb) != 1)
627             return AVERROR_INVALIDDATA;
628         bytestream2_skip(&gb, 3);
629         c->offset = bytestream2_get_le32(&gb);
630
631         if (buf_size <= c->offset + 8LL)
632             return AVERROR_INVALIDDATA;
633
634         bytestream2_init(&pb, buf + 8 + c->offset, buf_size - 8 - c->offset);
635
636         nb_cbs = bytestream2_get_le32(&pb);
637         if (nb_cbs > c->offset)
638             return AVERROR_INVALIDDATA;
639
640         packed_stream = buf + 8;
641         control_stream = packed_stream + (c->offset - nb_cbs);
642         left = control_stream - packed_stream;
643
644         for (i = 0; i < c->planes; i++) {
645             for (j = 0; j < c->slices; j++) {
646                 c->packed_stream[i][j] = packed_stream;
647                 c->packed_stream_size[i][j] = bytestream2_get_le32(&pb);
648                 if (c->packed_stream_size[i][j] > left)
649                     return AVERROR_INVALIDDATA;
650                 left -= c->packed_stream_size[i][j];
651                 packed_stream += c->packed_stream_size[i][j];
652             }
653         }
654
655         left = buf + buf_size - control_stream;
656
657         for (i = 0; i < c->planes; i++) {
658             for (j = 0; j < c->slices; j++) {
659                 c->control_stream[i][j] = control_stream;
660                 c->control_stream_size[i][j] = bytestream2_get_le32(&pb);
661                 if (c->control_stream_size[i][j] > left)
662                     return AVERROR_INVALIDDATA;
663                 left -= c->control_stream_size[i][j];
664                 control_stream += c->control_stream_size[i][j];
665             }
666         }
667     } else if (c->pro) {
668         if (bytestream2_get_bytes_left(&gb) < c->frame_info_size) {
669             av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");
670             return AVERROR_INVALIDDATA;
671         }
672         c->frame_info = bytestream2_get_le32u(&gb);
673         c->slices = ((c->frame_info >> 16) & 0xff) + 1;
674         for (i = 0; i < c->planes; i++) {
675             plane_start[i] = gb.buffer;
676             if (bytestream2_get_bytes_left(&gb) < 1024 + 4 * c->slices) {
677                 av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");
678                 return AVERROR_INVALIDDATA;
679             }
680             slice_start = 0;
681             slice_end   = 0;
682             for (j = 0; j < c->slices; j++) {
683                 slice_end   = bytestream2_get_le32u(&gb);
684                 if (slice_end < 0 || slice_end < slice_start ||
685                     bytestream2_get_bytes_left(&gb) < slice_end + 1024LL) {
686                     av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");
687                     return AVERROR_INVALIDDATA;
688                 }
689                 slice_size  = slice_end - slice_start;
690                 slice_start = slice_end;
691                 max_slice_size = FFMAX(max_slice_size, slice_size);
692             }
693             plane_size = slice_end;
694             bytestream2_skipu(&gb, plane_size);
695             bytestream2_skipu(&gb, 1024);
696         }
697         plane_start[c->planes] = gb.buffer;
698     } else {
699         for (i = 0; i < c->planes; i++) {
700             plane_start[i] = gb.buffer;
701             if (bytestream2_get_bytes_left(&gb) < 256 + 4 * c->slices) {
702                 av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");
703                 return AVERROR_INVALIDDATA;
704             }
705             bytestream2_skipu(&gb, 256);
706             slice_start = 0;
707             slice_end   = 0;
708             for (j = 0; j < c->slices; j++) {
709                 slice_end   = bytestream2_get_le32u(&gb);
710                 if (slice_end < 0 || slice_end < slice_start ||
711                     bytestream2_get_bytes_left(&gb) < slice_end) {
712                     av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");
713                     return AVERROR_INVALIDDATA;
714                 }
715                 slice_size  = slice_end - slice_start;
716                 slice_start = slice_end;
717                 max_slice_size = FFMAX(max_slice_size, slice_size);
718             }
719             plane_size = slice_end;
720             bytestream2_skipu(&gb, plane_size);
721         }
722         plane_start[c->planes] = gb.buffer;
723         if (bytestream2_get_bytes_left(&gb) < c->frame_info_size) {
724             av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");
725             return AVERROR_INVALIDDATA;
726         }
727         c->frame_info = bytestream2_get_le32u(&gb);
728     }
729     av_log(avctx, AV_LOG_DEBUG, "frame information flags %"PRIX32"\n",
730            c->frame_info);
731
732     c->frame_pred = (c->frame_info >> 8) & 3;
733
734     max_slice_size += 4*avctx->width;
735
736     if (!c->pack) {
737         av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
738                        max_slice_size + AV_INPUT_BUFFER_PADDING_SIZE);
739
740         if (!c->slice_bits) {
741             av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
742             return AVERROR(ENOMEM);
743         }
744     }
745
746     switch (c->avctx->pix_fmt) {
747     case AV_PIX_FMT_GBRP:
748     case AV_PIX_FMT_GBRAP:
749         for (i = 0; i < c->planes; i++) {
750             ret = decode_plane(c, i, frame.f->data[i],
751                                frame.f->linesize[i], avctx->width,
752                                avctx->height, plane_start[i],
753                                c->frame_pred == PRED_LEFT);
754             if (ret)
755                 return ret;
756             if (c->frame_pred == PRED_MEDIAN) {
757                 if (!c->interlaced) {
758                     restore_median_planar(c, frame.f->data[i],
759                                           frame.f->linesize[i], avctx->width,
760                                           avctx->height, c->slices, 0);
761                 } else {
762                     restore_median_planar_il(c, frame.f->data[i],
763                                              frame.f->linesize[i],
764                                              avctx->width, avctx->height, c->slices,
765                                              0);
766                 }
767             } else if (c->frame_pred == PRED_GRADIENT) {
768                 if (!c->interlaced) {
769                     restore_gradient_planar(c, frame.f->data[i],
770                                             frame.f->linesize[i], avctx->width,
771                                             avctx->height, c->slices, 0);
772                 } else {
773                     restore_gradient_planar_il(c, frame.f->data[i],
774                                                frame.f->linesize[i],
775                                                avctx->width, avctx->height, c->slices,
776                                                0);
777                 }
778             }
779         }
780         c->utdsp.restore_rgb_planes(frame.f->data[2], frame.f->data[0], frame.f->data[1],
781                                     frame.f->linesize[2], frame.f->linesize[0], frame.f->linesize[1],
782                                     avctx->width, avctx->height);
783         break;
784     case AV_PIX_FMT_GBRAP10:
785     case AV_PIX_FMT_GBRP10:
786         for (i = 0; i < c->planes; i++) {
787             ret = decode_plane10(c, i, (uint16_t *)frame.f->data[i],
788                                  frame.f->linesize[i] / 2, avctx->width,
789                                  avctx->height, plane_start[i],
790                                  plane_start[i + 1] - 1024,
791                                  c->frame_pred == PRED_LEFT);
792             if (ret)
793                 return ret;
794         }
795         c->utdsp.restore_rgb_planes10((uint16_t *)frame.f->data[2], (uint16_t *)frame.f->data[0], (uint16_t *)frame.f->data[1],
796                                       frame.f->linesize[2] / 2, frame.f->linesize[0] / 2, frame.f->linesize[1] / 2,
797                                       avctx->width, avctx->height);
798         break;
799     case AV_PIX_FMT_YUV420P:
800         for (i = 0; i < 3; i++) {
801             ret = decode_plane(c, i, frame.f->data[i], frame.f->linesize[i],
802                                avctx->width >> !!i, avctx->height >> !!i,
803                                plane_start[i], c->frame_pred == PRED_LEFT);
804             if (ret)
805                 return ret;
806             if (c->frame_pred == PRED_MEDIAN) {
807                 if (!c->interlaced) {
808                     restore_median_planar(c, frame.f->data[i], frame.f->linesize[i],
809                                           avctx->width >> !!i, avctx->height >> !!i,
810                                           c->slices, !i);
811                 } else {
812                     restore_median_planar_il(c, frame.f->data[i], frame.f->linesize[i],
813                                              avctx->width  >> !!i,
814                                              avctx->height >> !!i,
815                                              c->slices, !i);
816                 }
817             } else if (c->frame_pred == PRED_GRADIENT) {
818                 if (!c->interlaced) {
819                     restore_gradient_planar(c, frame.f->data[i], frame.f->linesize[i],
820                                             avctx->width >> !!i, avctx->height >> !!i,
821                                             c->slices, !i);
822                 } else {
823                     restore_gradient_planar_il(c, frame.f->data[i], frame.f->linesize[i],
824                                                avctx->width  >> !!i,
825                                                avctx->height >> !!i,
826                                                c->slices, !i);
827                 }
828             }
829         }
830         break;
831     case AV_PIX_FMT_YUV422P:
832         for (i = 0; i < 3; i++) {
833             ret = decode_plane(c, i, frame.f->data[i], frame.f->linesize[i],
834                                avctx->width >> !!i, avctx->height,
835                                plane_start[i], c->frame_pred == PRED_LEFT);
836             if (ret)
837                 return ret;
838             if (c->frame_pred == PRED_MEDIAN) {
839                 if (!c->interlaced) {
840                     restore_median_planar(c, frame.f->data[i], frame.f->linesize[i],
841                                           avctx->width >> !!i, avctx->height,
842                                           c->slices, 0);
843                 } else {
844                     restore_median_planar_il(c, frame.f->data[i], frame.f->linesize[i],
845                                              avctx->width >> !!i, avctx->height,
846                                              c->slices, 0);
847                 }
848             } else if (c->frame_pred == PRED_GRADIENT) {
849                 if (!c->interlaced) {
850                     restore_gradient_planar(c, frame.f->data[i], frame.f->linesize[i],
851                                             avctx->width >> !!i, avctx->height,
852                                             c->slices, 0);
853                 } else {
854                     restore_gradient_planar_il(c, frame.f->data[i], frame.f->linesize[i],
855                                                avctx->width  >> !!i, avctx->height,
856                                                c->slices, 0);
857                 }
858             }
859         }
860         break;
861     case AV_PIX_FMT_YUV444P:
862         for (i = 0; i < 3; i++) {
863             ret = decode_plane(c, i, frame.f->data[i], frame.f->linesize[i],
864                                avctx->width, avctx->height,
865                                plane_start[i], c->frame_pred == PRED_LEFT);
866             if (ret)
867                 return ret;
868             if (c->frame_pred == PRED_MEDIAN) {
869                 if (!c->interlaced) {
870                     restore_median_planar(c, frame.f->data[i], frame.f->linesize[i],
871                                           avctx->width, avctx->height,
872                                           c->slices, 0);
873                 } else {
874                     restore_median_planar_il(c, frame.f->data[i], frame.f->linesize[i],
875                                              avctx->width, avctx->height,
876                                              c->slices, 0);
877                 }
878             } else if (c->frame_pred == PRED_GRADIENT) {
879                 if (!c->interlaced) {
880                     restore_gradient_planar(c, frame.f->data[i], frame.f->linesize[i],
881                                             avctx->width, avctx->height,
882                                             c->slices, 0);
883                 } else {
884                     restore_gradient_planar_il(c, frame.f->data[i], frame.f->linesize[i],
885                                                avctx->width, avctx->height,
886                                                c->slices, 0);
887                 }
888             }
889         }
890         break;
891     case AV_PIX_FMT_YUV422P10:
892         for (i = 0; i < 3; i++) {
893             ret = decode_plane10(c, i, (uint16_t *)frame.f->data[i], frame.f->linesize[i] / 2,
894                                  avctx->width >> !!i, avctx->height,
895                                  plane_start[i], plane_start[i + 1] - 1024, c->frame_pred == PRED_LEFT);
896             if (ret)
897                 return ret;
898         }
899         break;
900     }
901
902     frame.f->key_frame = 1;
903     frame.f->pict_type = AV_PICTURE_TYPE_I;
904     frame.f->interlaced_frame = !!c->interlaced;
905
906     *got_frame = 1;
907
908     /* always report that the buffer was completely consumed */
909     return buf_size;
910 }
911
912 static av_cold int decode_init(AVCodecContext *avctx)
913 {
914     UtvideoContext * const c = avctx->priv_data;
915
916     c->avctx = avctx;
917
918     ff_utvideodsp_init(&c->utdsp);
919     ff_bswapdsp_init(&c->bdsp);
920     ff_llviddsp_init(&c->llviddsp);
921
922     c->slice_bits_size = 0;
923
924     switch (avctx->codec_tag) {
925     case MKTAG('U', 'L', 'R', 'G'):
926         c->planes      = 3;
927         avctx->pix_fmt = AV_PIX_FMT_GBRP;
928         break;
929     case MKTAG('U', 'L', 'R', 'A'):
930         c->planes      = 4;
931         avctx->pix_fmt = AV_PIX_FMT_GBRAP;
932         break;
933     case MKTAG('U', 'L', 'Y', '0'):
934         c->planes      = 3;
935         avctx->pix_fmt = AV_PIX_FMT_YUV420P;
936         avctx->colorspace = AVCOL_SPC_BT470BG;
937         break;
938     case MKTAG('U', 'L', 'Y', '2'):
939         c->planes      = 3;
940         avctx->pix_fmt = AV_PIX_FMT_YUV422P;
941         avctx->colorspace = AVCOL_SPC_BT470BG;
942         break;
943     case MKTAG('U', 'L', 'Y', '4'):
944         c->planes      = 3;
945         avctx->pix_fmt = AV_PIX_FMT_YUV444P;
946         avctx->colorspace = AVCOL_SPC_BT470BG;
947         break;
948     case MKTAG('U', 'Q', 'Y', '2'):
949         c->planes      = 3;
950         avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
951         break;
952     case MKTAG('U', 'Q', 'R', 'G'):
953         c->planes      = 3;
954         avctx->pix_fmt = AV_PIX_FMT_GBRP10;
955         break;
956     case MKTAG('U', 'Q', 'R', 'A'):
957         c->planes      = 4;
958         avctx->pix_fmt = AV_PIX_FMT_GBRAP10;
959         break;
960     case MKTAG('U', 'L', 'H', '0'):
961         c->planes      = 3;
962         avctx->pix_fmt = AV_PIX_FMT_YUV420P;
963         avctx->colorspace = AVCOL_SPC_BT709;
964         break;
965     case MKTAG('U', 'L', 'H', '2'):
966         c->planes      = 3;
967         avctx->pix_fmt = AV_PIX_FMT_YUV422P;
968         avctx->colorspace = AVCOL_SPC_BT709;
969         break;
970     case MKTAG('U', 'L', 'H', '4'):
971         c->planes      = 3;
972         avctx->pix_fmt = AV_PIX_FMT_YUV444P;
973         avctx->colorspace = AVCOL_SPC_BT709;
974         break;
975     case MKTAG('U', 'M', 'Y', '2'):
976         c->planes      = 3;
977         c->pack        = 1;
978         avctx->pix_fmt = AV_PIX_FMT_YUV422P;
979         avctx->colorspace = AVCOL_SPC_BT470BG;
980         break;
981     case MKTAG('U', 'M', 'H', '2'):
982         c->planes      = 3;
983         c->pack        = 1;
984         avctx->pix_fmt = AV_PIX_FMT_YUV422P;
985         avctx->colorspace = AVCOL_SPC_BT709;
986         break;
987     case MKTAG('U', 'M', 'Y', '4'):
988         c->planes      = 3;
989         c->pack        = 1;
990         avctx->pix_fmt = AV_PIX_FMT_YUV444P;
991         avctx->colorspace = AVCOL_SPC_BT470BG;
992         break;
993     case MKTAG('U', 'M', 'H', '4'):
994         c->planes      = 3;
995         c->pack        = 1;
996         avctx->pix_fmt = AV_PIX_FMT_YUV444P;
997         avctx->colorspace = AVCOL_SPC_BT709;
998         break;
999     case MKTAG('U', 'M', 'R', 'G'):
1000         c->planes      = 3;
1001         c->pack        = 1;
1002         avctx->pix_fmt = AV_PIX_FMT_GBRP;
1003         break;
1004     case MKTAG('U', 'M', 'R', 'A'):
1005         c->planes      = 4;
1006         c->pack        = 1;
1007         avctx->pix_fmt = AV_PIX_FMT_GBRAP;
1008         break;
1009     default:
1010         av_log(avctx, AV_LOG_ERROR, "Unknown Ut Video FOURCC provided (%08X)\n",
1011                avctx->codec_tag);
1012         return AVERROR_INVALIDDATA;
1013     }
1014
1015     if (c->pack && avctx->extradata_size >= 16) {
1016         av_log(avctx, AV_LOG_DEBUG, "Encoder version %d.%d.%d.%d\n",
1017                avctx->extradata[3], avctx->extradata[2],
1018                avctx->extradata[1], avctx->extradata[0]);
1019         av_log(avctx, AV_LOG_DEBUG, "Original format %"PRIX32"\n",
1020                AV_RB32(avctx->extradata + 4));
1021         c->compression = avctx->extradata[8];
1022         if (c->compression != 2)
1023             avpriv_request_sample(avctx, "Unknown compression type");
1024         c->slices      = avctx->extradata[9] + 1;
1025     } else if (avctx->extradata_size >= 16) {
1026         av_log(avctx, AV_LOG_DEBUG, "Encoder version %d.%d.%d.%d\n",
1027                avctx->extradata[3], avctx->extradata[2],
1028                avctx->extradata[1], avctx->extradata[0]);
1029         av_log(avctx, AV_LOG_DEBUG, "Original format %"PRIX32"\n",
1030                AV_RB32(avctx->extradata + 4));
1031         c->frame_info_size = AV_RL32(avctx->extradata + 8);
1032         c->flags           = AV_RL32(avctx->extradata + 12);
1033
1034         if (c->frame_info_size != 4)
1035             avpriv_request_sample(avctx, "Frame info not 4 bytes");
1036         av_log(avctx, AV_LOG_DEBUG, "Encoding parameters %08"PRIX32"\n", c->flags);
1037         c->slices      = (c->flags >> 24) + 1;
1038         c->compression = c->flags & 1;
1039         c->interlaced  = c->flags & 0x800;
1040     } else if (avctx->extradata_size == 8) {
1041         av_log(avctx, AV_LOG_DEBUG, "Encoder version %d.%d.%d.%d\n",
1042                avctx->extradata[3], avctx->extradata[2],
1043                avctx->extradata[1], avctx->extradata[0]);
1044         av_log(avctx, AV_LOG_DEBUG, "Original format %"PRIX32"\n",
1045                AV_RB32(avctx->extradata + 4));
1046         c->interlaced  = 0;
1047         c->pro         = 1;
1048         c->frame_info_size = 4;
1049     } else {
1050         av_log(avctx, AV_LOG_ERROR,
1051                "Insufficient extradata size %d, should be at least 16\n",
1052                avctx->extradata_size);
1053         return AVERROR_INVALIDDATA;
1054     }
1055
1056     return 0;
1057 }
1058
1059 static av_cold int decode_end(AVCodecContext *avctx)
1060 {
1061     UtvideoContext * const c = avctx->priv_data;
1062
1063     av_freep(&c->slice_bits);
1064
1065     return 0;
1066 }
1067
1068 AVCodec ff_utvideo_decoder = {
1069     .name           = "utvideo",
1070     .long_name      = NULL_IF_CONFIG_SMALL("Ut Video"),
1071     .type           = AVMEDIA_TYPE_VIDEO,
1072     .id             = AV_CODEC_ID_UTVIDEO,
1073     .priv_data_size = sizeof(UtvideoContext),
1074     .init           = decode_init,
1075     .close          = decode_end,
1076     .decode         = decode_frame,
1077     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
1078     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
1079 };