]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1dec.c
atrac3plus: Convert to the new bitstream reader
[ffmpeg] / libavcodec / ffv1dec.c
1 /*
2  * FFV1 decoder
3  *
4  * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * FF Video Codec 1 (a lossless codec) decoder
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/timer.h"
34 #include "avcodec.h"
35 #include "internal.h"
36 #include "get_bits.h"
37 #include "put_bits.h"
38 #include "rangecoder.h"
39 #include "golomb.h"
40 #include "mathops.h"
41 #include "ffv1.h"
42
43 static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,
44                                                int is_signed)
45 {
46     if (get_rac(c, state + 0))
47         return 0;
48     else {
49         int i, e, a;
50         e = 0;
51         while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10
52             e++;
53
54         a = 1;
55         for (i = e - 1; i >= 0; i--)
56             a += a + get_rac(c, state + 22 + FFMIN(i, 9));  // 22..31
57
58         e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21
59         return (a ^ e) - e;
60     }
61 }
62
63 static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed)
64 {
65     return get_symbol_inline(c, state, is_signed);
66 }
67
68 static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state,
69                                  int bits)
70 {
71     int k, i, v, ret;
72
73     i = state->count;
74     k = 0;
75     while (i < state->error_sum) { // FIXME: optimize
76         k++;
77         i += i;
78     }
79
80     assert(k <= 8);
81
82     v = get_sr_golomb(gb, k, 12, bits);
83     ff_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
84             v, state->bias, state->error_sum, state->drift, state->count, k);
85
86     v ^= ((2 * state->drift + state->count) >> 31);
87
88     ret = fold(v + state->bias, bits);
89
90     update_vlc_state(state, v);
91
92     return ret;
93 }
94
95 static av_always_inline void decode_line(FFV1Context *s, int w,
96                                          int16_t *sample[2],
97                                          int plane_index, int bits)
98 {
99     PlaneContext *const p = &s->plane[plane_index];
100     RangeCoder *const c   = &s->c;
101     int x;
102     int run_count = 0;
103     int run_mode  = 0;
104     int run_index = s->run_index;
105
106     for (x = 0; x < w; x++) {
107         int diff, context, sign;
108
109         context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
110         if (context < 0) {
111             context = -context;
112             sign    = 1;
113         } else
114             sign = 0;
115
116         av_assert2(context < p->context_count);
117
118         if (s->ac != AC_GOLOMB_RICE) {
119             diff = get_symbol_inline(c, p->state[context], 1);
120         } else {
121             if (context == 0 && run_mode == 0)
122                 run_mode = 1;
123
124             if (run_mode) {
125                 if (run_count == 0 && run_mode == 1) {
126                     if (get_bits1(&s->gb)) {
127                         run_count = 1 << ff_log2_run[run_index];
128                         if (x + run_count <= w)
129                             run_index++;
130                     } else {
131                         if (ff_log2_run[run_index])
132                             run_count = get_bits(&s->gb, ff_log2_run[run_index]);
133                         else
134                             run_count = 0;
135                         if (run_index)
136                             run_index--;
137                         run_mode = 2;
138                     }
139                 }
140                 run_count--;
141                 if (run_count < 0) {
142                     run_mode  = 0;
143                     run_count = 0;
144                     diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],
145                                                bits);
146                     if (diff >= 0)
147                         diff++;
148                 } else
149                     diff = 0;
150             } else
151                 diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
152
153             ff_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
154                     run_count, run_index, run_mode, x, get_bits_count(&s->gb));
155         }
156
157         if (sign)
158             diff = -diff;
159
160         sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
161                        ((1 << bits) - 1);
162     }
163     s->run_index = run_index;
164 }
165
166 static void decode_plane(FFV1Context *s, uint8_t *src,
167                          int w, int h, int stride, int plane_index)
168 {
169     int x, y;
170     int16_t *sample[2];
171     sample[0] = s->sample_buffer + 3;
172     sample[1] = s->sample_buffer + w + 6 + 3;
173
174     s->run_index = 0;
175
176     memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
177
178     for (y = 0; y < h; y++) {
179         int16_t *temp = sample[0]; // FIXME: try a normal buffer
180
181         sample[0] = sample[1];
182         sample[1] = temp;
183
184         sample[1][-1] = sample[0][0];
185         sample[0][w]  = sample[0][w - 1];
186
187 // { START_TIMER
188         if (s->avctx->bits_per_raw_sample <= 8) {
189             decode_line(s, w, sample, plane_index, 8);
190             for (x = 0; x < w; x++)
191                 src[x + stride * y] = sample[1][x];
192         } else {
193             decode_line(s, w, sample, plane_index,
194                         s->avctx->bits_per_raw_sample);
195             if (s->packed_at_lsb) {
196                 for (x = 0; x < w; x++)
197                     ((uint16_t *)(src + stride * y))[x] = sample[1][x];
198             } else {
199                 for (x = 0; x < w; x++)
200                     ((uint16_t *)(src + stride * y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
201             }
202         }
203 // STOP_TIMER("decode-line") }
204     }
205 }
206
207 static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h,
208                              int stride[3])
209 {
210     int x, y, p;
211     int16_t *sample[4][2];
212     int lbd  = s->avctx->bits_per_raw_sample <= 8;
213     int bits = s->avctx->bits_per_raw_sample > 0
214                ? s->avctx->bits_per_raw_sample
215                : 8;
216     int offset = 1 << bits;
217
218     for (x = 0; x < 4; x++) {
219         sample[x][0] = s->sample_buffer +  x * 2      * (w + 6) + 3;
220         sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
221     }
222
223     s->run_index = 0;
224
225     memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
226
227     for (y = 0; y < h; y++) {
228         for (p = 0; p < 3 + s->transparency; p++) {
229             int16_t *temp = sample[p][0]; //FIXME try a normal buffer
230
231             sample[p][0] = sample[p][1];
232             sample[p][1] = temp;
233
234             sample[p][1][-1] = sample[p][0][0];
235             sample[p][0][w]  = sample[p][0][w - 1];
236             if (lbd)
237                 decode_line(s, w, sample[p], (p + 1) / 2, 9);
238             else
239                 decode_line(s, w, sample[p], (p + 1) / 2, bits + 1);
240         }
241         for (x = 0; x < w; x++) {
242             int g = sample[0][1][x];
243             int b = sample[1][1][x];
244             int r = sample[2][1][x];
245             int a = sample[3][1][x];
246
247             b -= offset;
248             r -= offset;
249             g -= (b + r) >> 2;
250             b += g;
251             r += g;
252
253             if (lbd)
254                 *((uint32_t *)(src[0] + x * 4 + stride[0] * y)) = b +
255                     (g << 8) + (r << 16) + (a << 24);
256             else {
257                 *((uint16_t *)(src[0] + x * 2 + stride[0] * y)) = b;
258                 *((uint16_t *)(src[1] + x * 2 + stride[1] * y)) = g;
259                 *((uint16_t *)(src[2] + x * 2 + stride[2] * y)) = r;
260             }
261         }
262     }
263 }
264
265 static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
266 {
267     RangeCoder *c = &fs->c;
268     uint8_t state[CONTEXT_SIZE];
269     unsigned ps, i, context_count;
270     memset(state, 128, sizeof(state));
271
272     if (fs->ac == AC_RANGE_CUSTOM_TAB) {
273         for (i = 1; i < 256; i++) {
274             fs->c.one_state[i]        = f->state_transition[i];
275             fs->c.zero_state[256 - i] = 256 - fs->c.one_state[i];
276         }
277     }
278
279     fs->slice_x      = get_symbol(c, state, 0) * f->width;
280     fs->slice_y      = get_symbol(c, state, 0) * f->height;
281     fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;
282     fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
283
284     fs->slice_x     /= f->num_h_slices;
285     fs->slice_y     /= f->num_v_slices;
286     fs->slice_width  = fs->slice_width / f->num_h_slices - fs->slice_x;
287     fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
288     if ((unsigned)fs->slice_width  > f->width ||
289         (unsigned)fs->slice_height > f->height)
290         return AVERROR_INVALIDDATA;
291     if ((unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width ||
292         (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
293         return AVERROR_INVALIDDATA;
294
295     for (i = 0; i < f->plane_count; i++) {
296         PlaneContext *const p = &fs->plane[i];
297         int idx               = get_symbol(c, state, 0);
298         if (idx > (unsigned)f->quant_table_count) {
299             av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
300             return AVERROR_INVALIDDATA;
301         }
302         p->quant_table_index = idx;
303         memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
304         context_count = f->context_count[idx];
305
306         if (p->context_count < context_count) {
307             av_freep(&p->state);
308             av_freep(&p->vlc_state);
309         }
310         p->context_count = context_count;
311     }
312
313     ps = get_symbol(c, state, 0);
314     if (ps == 1) {
315         f->cur->interlaced_frame = 1;
316         f->cur->top_field_first  = 1;
317     } else if (ps == 2) {
318         f->cur->interlaced_frame = 1;
319         f->cur->top_field_first  = 0;
320     } else if (ps == 3) {
321         f->cur->interlaced_frame = 0;
322     }
323     f->cur->sample_aspect_ratio.num = get_symbol(c, state, 0);
324     f->cur->sample_aspect_ratio.den = get_symbol(c, state, 0);
325
326     if (av_image_check_sar(f->width, f->height,
327                            f->cur->sample_aspect_ratio) < 0) {
328         av_log(f->avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
329                f->cur->sample_aspect_ratio.num,
330                f->cur->sample_aspect_ratio.den);
331         f->cur->sample_aspect_ratio = (AVRational){ 0, 1 };
332     }
333
334     return 0;
335 }
336
337 static int decode_slice(AVCodecContext *c, void *arg)
338 {
339     FFV1Context *fs = *(void **)arg;
340     FFV1Context *f  = fs->avctx->priv_data;
341     int width, height, x, y, ret;
342     const int ps = (av_pix_fmt_desc_get(c->pix_fmt)->flags & AV_PIX_FMT_FLAG_PLANAR)
343                    ? (c->bits_per_raw_sample > 8) + 1
344                    : 4;
345     AVFrame *const p = f->cur;
346
347     if (f->version > 2) {
348         if (decode_slice_header(f, fs) < 0) {
349             fs->slice_damaged = 1;
350             return AVERROR_INVALIDDATA;
351         }
352     }
353     if ((ret = ffv1_init_slice_state(f, fs)) < 0)
354         return ret;
355     if (f->cur->key_frame)
356         ffv1_clear_slice_state(f, fs);
357     width  = fs->slice_width;
358     height = fs->slice_height;
359     x      = fs->slice_x;
360     y      = fs->slice_y;
361
362     if (fs->ac == AC_GOLOMB_RICE) {
363         if (f->version == 3 && f->minor_version > 1 || f->version > 3)
364             get_rac(&fs->c, (uint8_t[]) { 129 });
365         fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
366         init_get_bits(&fs->gb, fs->c.bytestream_start + fs->ac_byte_count,
367                       (fs->c.bytestream_end - fs->c.bytestream_start -
368                        fs->ac_byte_count) * 8);
369     }
370
371     av_assert1(width && height);
372     if (f->colorspace == 0) {
373         const int chroma_width  = AV_CEIL_RSHIFT(width,  f->chroma_h_shift);
374         const int chroma_height = AV_CEIL_RSHIFT(height, f->chroma_v_shift);
375         const int cx            = x >> f->chroma_h_shift;
376         const int cy            = y >> f->chroma_v_shift;
377         decode_plane(fs, p->data[0] + ps * x + y * p->linesize[0], width,
378                      height, p->linesize[0],
379                      0);
380
381         if (f->chroma_planes) {
382             decode_plane(fs, p->data[1] + ps * cx + cy * p->linesize[1],
383                          chroma_width, chroma_height, p->linesize[1],
384                          1);
385             decode_plane(fs, p->data[2] + ps * cx + cy * p->linesize[2],
386                          chroma_width, chroma_height, p->linesize[2],
387                          1);
388         }
389         if (fs->transparency)
390             decode_plane(fs, p->data[3] + ps * x + y * p->linesize[3], width,
391                          height, p->linesize[3],
392                          2);
393     } else {
394         uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
395                                p->data[1] + ps * x + y * p->linesize[1],
396                                p->data[2] + ps * x + y * p->linesize[2] };
397         decode_rgb_frame(fs, planes, width, height, p->linesize);
398     }
399     if (fs->ac != AC_GOLOMB_RICE && f->version > 2) {
400         int v;
401         get_rac(&fs->c, (uint8_t[]) { 129 });
402         v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5 * f->ec;
403         if (v) {
404             av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n",
405                    v);
406             fs->slice_damaged = 1;
407         }
408     }
409
410     emms_c();
411
412     return 0;
413 }
414
415 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
416 {
417     int v;
418     int i = 0;
419     uint8_t state[CONTEXT_SIZE];
420
421     memset(state, 128, sizeof(state));
422
423     for (v = 0; i < 128; v++) {
424         unsigned len = get_symbol(c, state, 0) + 1;
425
426         if (len > 128 - i)
427             return -1;
428
429         while (len--) {
430             quant_table[i] = scale * v;
431             i++;
432         }
433     }
434
435     for (i = 1; i < 128; i++)
436         quant_table[256 - i] = -quant_table[i];
437     quant_table[128] = -quant_table[127];
438
439     return 2 * v - 1;
440 }
441
442 static int read_quant_tables(RangeCoder *c,
443                              int16_t quant_table[MAX_CONTEXT_INPUTS][256])
444 {
445     int i;
446     int context_count = 1;
447
448     for (i = 0; i < 5; i++) {
449         context_count *= read_quant_table(c, quant_table[i], context_count);
450         if (context_count > 32768U) {
451             return -1;
452         }
453     }
454     return (context_count + 1) / 2;
455 }
456
457 static int read_extra_header(FFV1Context *f)
458 {
459     RangeCoder *const c = &f->c;
460     uint8_t state[CONTEXT_SIZE];
461     int i, j, k, ret;
462     uint8_t state2[32][CONTEXT_SIZE];
463
464     memset(state2, 128, sizeof(state2));
465     memset(state, 128, sizeof(state));
466
467     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
468     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
469
470     f->version = get_symbol(c, state, 0);
471     if (f->version > 2) {
472         c->bytestream_end -= 4;
473         f->minor_version   = get_symbol(c, state, 0);
474     }
475     f->ac = get_symbol(c, state, 0);
476
477     if (f->ac == AC_RANGE_CUSTOM_TAB) {
478         for (i = 1; i < 256; i++)
479             f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
480     }
481
482     f->colorspace                 = get_symbol(c, state, 0); //YUV cs type
483     f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
484     f->chroma_planes              = get_rac(c, state);
485     f->chroma_h_shift             = get_symbol(c, state, 0);
486     f->chroma_v_shift             = get_symbol(c, state, 0);
487     f->transparency               = get_rac(c, state);
488     f->plane_count                = 2 + f->transparency;
489     f->num_h_slices               = 1 + get_symbol(c, state, 0);
490     f->num_v_slices               = 1 + get_symbol(c, state, 0);
491
492     if (f->num_h_slices > (unsigned)f->width ||
493         f->num_v_slices > (unsigned)f->height) {
494         av_log(f->avctx, AV_LOG_ERROR, "too many slices\n");
495         return AVERROR_INVALIDDATA;
496     }
497
498     f->quant_table_count = get_symbol(c, state, 0);
499     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
500         return AVERROR_INVALIDDATA;
501     for (i = 0; i < f->quant_table_count; i++) {
502         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
503         if (f->context_count[i] < 0) {
504             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
505             return AVERROR_INVALIDDATA;
506         }
507     }
508     if ((ret = ffv1_allocate_initial_states(f)) < 0)
509         return ret;
510
511     for (i = 0; i < f->quant_table_count; i++)
512         if (get_rac(c, state)) {
513             for (j = 0; j < f->context_count[i]; j++)
514                 for (k = 0; k < CONTEXT_SIZE; k++) {
515                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
516                     f->initial_states[i][j][k] =
517                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
518                 }
519         }
520
521     if (f->version > 2) {
522         f->ec = get_symbol(c, state, 0);
523     }
524
525     if (f->version > 2) {
526         unsigned v;
527         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
528                    f->avctx->extradata, f->avctx->extradata_size);
529         if (v) {
530             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
531             return AVERROR_INVALIDDATA;
532         }
533     }
534
535     av_log(f->avctx, AV_LOG_VERBOSE,
536            "FFV1 version %d.%d colorspace %d - %d bits - %d/%d planes, %s transparent - tile geometry %dx%d - %s\n",
537            f->version, f->minor_version, f->colorspace, f->avctx->bits_per_raw_sample,
538            f->plane_count, f->chroma_planes, f->transparency ? "" : "not",
539            f->num_h_slices, f->num_v_slices,
540            f->ec ? "per-slice crc" : "no crc");
541
542     return 0;
543 }
544
545
546 static int read_header(FFV1Context *f)
547 {
548     uint8_t state[CONTEXT_SIZE];
549     int i, j, context_count = -1;
550     RangeCoder *const c = &f->slice_context[0]->c;
551
552     memset(state, 128, sizeof(state));
553
554     if (f->version < 2) {
555         int chroma_planes, chroma_h_shift, chroma_v_shift, transparency, colorspace, bits_per_raw_sample;
556         unsigned v = get_symbol(c, state, 0);
557         if (v > 1) {
558             av_log(f->avctx, AV_LOG_ERROR,
559                    "invalid version %d in version 1 header\n", v);
560             return AVERROR_INVALIDDATA;
561         }
562         f->version = v;
563
564         f->ac = get_symbol(c, state, 0);
565
566         if (f->ac == AC_RANGE_CUSTOM_TAB) {
567             for (i = 1; i < 256; i++)
568                 f->state_transition[i] =
569                     get_symbol(c, state, 1) + c->one_state[i];
570         }
571
572         colorspace          = get_symbol(c, state, 0); //YUV cs type
573         bits_per_raw_sample = f->version > 0 ? get_symbol(c, state, 0) : f->avctx->bits_per_raw_sample;
574         chroma_planes       = get_rac(c, state);
575         chroma_h_shift      = get_symbol(c, state, 0);
576         chroma_v_shift      = get_symbol(c, state, 0);
577         transparency        = get_rac(c, state);
578
579         if (f->plane_count) {
580             if (colorspace          != f->colorspace                 ||
581                 bits_per_raw_sample != f->avctx->bits_per_raw_sample ||
582                 chroma_planes       != f->chroma_planes              ||
583                 chroma_h_shift      != f->chroma_h_shift             ||
584                 chroma_v_shift      != f->chroma_v_shift             ||
585                 transparency        != f->transparency) {
586                 av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n");
587                 return AVERROR_INVALIDDATA;
588             }
589         }
590
591         f->colorspace                 = colorspace;
592         f->avctx->bits_per_raw_sample = bits_per_raw_sample;
593         f->chroma_planes              = chroma_planes;
594         f->chroma_h_shift             = chroma_h_shift;
595         f->chroma_v_shift             = chroma_v_shift;
596         f->transparency               = transparency;
597
598         f->plane_count    = 2 + f->transparency;
599     }
600
601     if (f->colorspace == 0) {
602         if (f->transparency && f->avctx->bits_per_raw_sample > 8) {
603             av_log(f->avctx, AV_LOG_ERROR,
604                    "Transparency not supported for bit depth %d\n",
605                    f->avctx->bits_per_raw_sample);
606             return AVERROR(ENOSYS);
607         }
608         if (!f->transparency && !f->chroma_planes) {
609             if (f->avctx->bits_per_raw_sample <= 8)
610                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
611             else
612                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
613         } else if (f->avctx->bits_per_raw_sample <= 8 && !f->transparency) {
614             switch (16 * f->chroma_h_shift + f->chroma_v_shift) {
615             case 0x00:
616                 f->avctx->pix_fmt = AV_PIX_FMT_YUV444P;
617                 break;
618             case 0x01:
619                 f->avctx->pix_fmt = AV_PIX_FMT_YUV440P;
620                 break;
621             case 0x10:
622                 f->avctx->pix_fmt = AV_PIX_FMT_YUV422P;
623                 break;
624             case 0x11:
625                 f->avctx->pix_fmt = AV_PIX_FMT_YUV420P;
626                 break;
627             case 0x20:
628                 f->avctx->pix_fmt = AV_PIX_FMT_YUV411P;
629                 break;
630             case 0x22:
631                 f->avctx->pix_fmt = AV_PIX_FMT_YUV410P;
632                 break;
633             default:
634                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
635                 return AVERROR(ENOSYS);
636             }
637         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
638             switch (16 * f->chroma_h_shift + f->chroma_v_shift) {
639             case 0x00:
640                 f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P;
641                 break;
642             case 0x10:
643                 f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P;
644                 break;
645             case 0x11:
646                 f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
647                 break;
648             default:
649                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
650                 return AVERROR(ENOSYS);
651             }
652         } else if (f->avctx->bits_per_raw_sample == 9) {
653             f->packed_at_lsb = 1;
654             switch (16 * f->chroma_h_shift + f->chroma_v_shift) {
655             case 0x00:
656                 f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9;
657                 break;
658             case 0x10:
659                 f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9;
660                 break;
661             case 0x11:
662                 f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9;
663                 break;
664             default:
665                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
666                 return AVERROR(ENOSYS);
667             }
668         } else if (f->avctx->bits_per_raw_sample == 10) {
669             f->packed_at_lsb = 1;
670             switch (16 * f->chroma_h_shift + f->chroma_v_shift) {
671             case 0x00:
672                 f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
673                 break;
674             case 0x10:
675                 f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
676                 break;
677             case 0x11:
678                 f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
679                 break;
680             default:
681                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
682                 return AVERROR(ENOSYS);
683             }
684         } else {
685             switch (16 * f->chroma_h_shift + f->chroma_v_shift) {
686             case 0x00:
687                 f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16;
688                 break;
689             case 0x10:
690                 f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16;
691                 break;
692             case 0x11:
693                 f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16;
694                 break;
695             default:
696                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
697                 return AVERROR(ENOSYS);
698             }
699         }
700     } else if (f->colorspace == 1) {
701         if (f->chroma_h_shift || f->chroma_v_shift) {
702             av_log(f->avctx, AV_LOG_ERROR,
703                    "chroma subsampling not supported in this colorspace\n");
704             return AVERROR(ENOSYS);
705         }
706         if (f->transparency) {
707             av_log(f->avctx, AV_LOG_ERROR,
708                    "Transparency not supported in this colorspace\n");
709                    return AVERROR(ENOSYS);
710         }
711         switch (f->avctx->bits_per_raw_sample) {
712         case 0:
713         case 8:
714             f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
715             break;
716         case 9:
717             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
718             break;
719         case 10:
720             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
721             break;
722         default:
723             av_log(f->avctx, AV_LOG_ERROR,
724                    "bit depth %d not supported\n",
725                    f->avctx->bits_per_raw_sample);
726             return AVERROR(ENOSYS);
727         }
728     } else {
729         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
730         return AVERROR(ENOSYS);
731     }
732
733     ff_dlog(f->avctx, "%d %d %d\n",
734             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
735     if (f->version < 2) {
736         context_count = read_quant_tables(c, f->quant_table);
737         if (context_count < 0) {
738             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
739             return AVERROR_INVALIDDATA;
740         }
741     } else if (f->version < 3) {
742         f->slice_count = get_symbol(c, state, 0);
743     } else {
744         const uint8_t *p = c->bytestream_end;
745         for (f->slice_count = 0;
746              f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
747              f->slice_count++) {
748             int trailer = 3 + 5 * !!f->ec;
749             int size    = AV_RB24(p - trailer);
750             if (size + trailer > p - c->bytestream_start)
751                 break;
752             p -= size + trailer;
753         }
754     }
755     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
756         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n",
757                f->slice_count);
758         return AVERROR_INVALIDDATA;
759     }
760
761     for (j = 0; j < f->slice_count; j++) {
762         FFV1Context *fs = f->slice_context[j];
763         fs->ac            = f->ac;
764         fs->packed_at_lsb = f->packed_at_lsb;
765
766         fs->slice_damaged = 0;
767
768         if (f->version == 2) {
769             fs->slice_x     = get_symbol(c, state, 0) * f->width;
770             fs->slice_y     = get_symbol(c, state, 0) * f->height;
771             fs->slice_width =
772                 (get_symbol(c, state, 0) + 1) * f->width + fs->slice_x;
773             fs->slice_height =
774                 (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
775
776             fs->slice_x      /= f->num_h_slices;
777             fs->slice_y      /= f->num_v_slices;
778             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
779             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
780             if ((unsigned)fs->slice_width > f->width ||
781                 (unsigned)fs->slice_height > f->height)
782                 return AVERROR_INVALIDDATA;
783             if ((unsigned)fs->slice_x + (uint64_t)fs->slice_width > f->width
784                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height >
785                 f->height)
786                 return AVERROR_INVALIDDATA;
787         }
788
789         for (i = 0; i < f->plane_count; i++) {
790             PlaneContext *const p = &fs->plane[i];
791
792             if (f->version == 2) {
793                 int idx = get_symbol(c, state, 0);
794                 if (idx > (unsigned)f->quant_table_count) {
795                     av_log(f->avctx, AV_LOG_ERROR,
796                            "quant_table_index out of range\n");
797                     return AVERROR_INVALIDDATA;
798                 }
799                 p->quant_table_index = idx;
800                 memcpy(p->quant_table, f->quant_tables[idx],
801                        sizeof(p->quant_table));
802                 context_count = f->context_count[idx];
803             } else {
804                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
805             }
806
807             if (f->version <= 2) {
808                 av_assert0(context_count >= 0);
809                 if (p->context_count < context_count) {
810                     av_freep(&p->state);
811                     av_freep(&p->vlc_state);
812                 }
813                 p->context_count = context_count;
814             }
815         }
816     }
817     return 0;
818 }
819
820 static av_cold int ffv1_decode_init(AVCodecContext *avctx)
821 {
822     FFV1Context *f = avctx->priv_data;
823     int ret;
824
825     ffv1_common_init(avctx);
826
827     f->last_picture = av_frame_alloc();
828     if (!f->last_picture)
829         return AVERROR(ENOMEM);
830
831     if (avctx->extradata && (ret = read_extra_header(f)) < 0)
832         return ret;
833
834     if ((ret = ffv1_init_slice_contexts(f)) < 0)
835         return ret;
836
837     return 0;
838 }
839
840 static int ffv1_decode_frame(AVCodecContext *avctx, void *data,
841                              int *got_frame, AVPacket *avpkt)
842 {
843     uint8_t *buf        = avpkt->data;
844     int buf_size        = avpkt->size;
845     FFV1Context *f      = avctx->priv_data;
846     RangeCoder *const c = &f->slice_context[0]->c;
847     int i, ret;
848     uint8_t keystate = 128;
849     uint8_t *buf_p;
850     AVFrame *const p    = data;
851
852     f->cur = p;
853
854     ff_init_range_decoder(c, buf, buf_size);
855     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
856
857     p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
858     if (get_rac(c, &keystate)) {
859         p->key_frame    = 1;
860         f->key_frame_ok = 0;
861         if ((ret = read_header(f)) < 0)
862             return ret;
863         f->key_frame_ok = 1;
864     } else {
865         if (!f->key_frame_ok) {
866             av_log(avctx, AV_LOG_ERROR,
867                    "Cannot decode non-keyframe without valid keyframe\n");
868             return AVERROR_INVALIDDATA;
869         }
870         p->key_frame = 0;
871     }
872
873     if ((ret = ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF)) < 0) {
874         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
875         return ret;
876     }
877
878     if (avctx->debug & FF_DEBUG_PICT_INFO)
879         av_log(avctx, AV_LOG_DEBUG,
880                "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
881                f->version, p->key_frame, f->ac, f->ec, f->slice_count,
882                f->avctx->bits_per_raw_sample);
883
884     buf_p = buf + buf_size;
885     for (i = f->slice_count - 1; i >= 0; i--) {
886         FFV1Context *fs = f->slice_context[i];
887         int trailer     = 3 + 5 * !!f->ec;
888         int v;
889
890         if (i || f->version > 2)
891             v = AV_RB24(buf_p - trailer) + trailer;
892         else
893             v = buf_p - c->bytestream_start;
894         if (buf_p - c->bytestream_start < v) {
895             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
896             return AVERROR_INVALIDDATA;
897         }
898         buf_p -= v;
899
900         if (f->ec) {
901             unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
902             if (crc) {
903                 av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", crc);
904                 fs->slice_damaged = 1;
905             }
906         }
907
908         if (i) {
909             ff_init_range_decoder(&fs->c, buf_p, v);
910         } else
911             fs->c.bytestream_end = buf_p + v;
912
913         fs->cur = p;
914     }
915
916     avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL,
917                    f->slice_count,
918                    sizeof(void *));
919
920     for (i = f->slice_count - 1; i >= 0; i--) {
921         FFV1Context *fs = f->slice_context[i];
922         int j;
923         if (fs->slice_damaged && f->last_picture->data[0]) {
924             const uint8_t *src[4];
925             uint8_t *dst[4];
926             for (j = 0; j < 4; j++) {
927                 int sh = (j == 1 || j == 2) ? f->chroma_h_shift : 0;
928                 int sv = (j == 1 || j == 2) ? f->chroma_v_shift : 0;
929                 dst[j] = p->data[j] + p->linesize[j] *
930                          (fs->slice_y >> sv) + (fs->slice_x >> sh);
931                 src[j] = f->last_picture->data[j] +
932                          f->last_picture->linesize[j] *
933                          (fs->slice_y >> sv) + (fs->slice_x >> sh);
934             }
935             av_image_copy(dst, p->linesize, src,
936                           f->last_picture->linesize,
937                           avctx->pix_fmt, fs->slice_width,
938                           fs->slice_height);
939         }
940     }
941
942     f->picture_number++;
943
944     av_frame_unref(f->last_picture);
945     if ((ret = av_frame_ref(f->last_picture, p)) < 0)
946         return ret;
947     f->cur = NULL;
948
949     *got_frame = 1;
950
951     return buf_size;
952 }
953
954 static av_cold int ffv1_decode_close(AVCodecContext *avctx)
955 {
956     FFV1Context *s = avctx->priv_data;;
957
958     av_frame_free(&s->last_picture);
959
960     ffv1_close(avctx);
961
962     return 0;
963 }
964
965 AVCodec ff_ffv1_decoder = {
966     .name           = "ffv1",
967     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
968     .type           = AVMEDIA_TYPE_VIDEO,
969     .id             = AV_CODEC_ID_FFV1,
970     .priv_data_size = sizeof(FFV1Context),
971     .init           = ffv1_decode_init,
972     .close          = ffv1_decode_close,
973     .decode         = ffv1_decode_frame,
974     .capabilities   = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/ |
975                       AV_CODEC_CAP_SLICE_THREADS,
976 };