]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1dec.c
Merge commit '97bf7c03b1338a867da52c159a2afecbdedcfa88'
[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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/crc.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/pixdesc.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 "dsputil.h"
39 #include "rangecoder.h"
40 #include "golomb.h"
41 #include "mathops.h"
42 #include "ffv1.h"
43
44 static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,
45                                                int is_signed)
46 {
47     if (get_rac(c, state + 0))
48         return 0;
49     else {
50         int i, e, a;
51         e = 0;
52         while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10
53             e++;
54
55         a = 1;
56         for (i = e - 1; i >= 0; i--)
57             a += a + get_rac(c, state + 22 + FFMIN(i, 9));  // 22..31
58
59         e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21
60         return (a ^ e) - e;
61     }
62 }
63
64 static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed)
65 {
66     return get_symbol_inline(c, state, is_signed);
67 }
68
69 static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state,
70                                  int bits)
71 {
72     int k, i, v, ret;
73
74     i = state->count;
75     k = 0;
76     while (i < state->error_sum) { // FIXME: optimize
77         k++;
78         i += i;
79     }
80
81     assert(k <= 8);
82
83     v = get_sr_golomb(gb, k, 12, bits);
84     av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
85             v, state->bias, state->error_sum, state->drift, state->count, k);
86
87 #if 0 // JPEG LS
88     if (k == 0 && 2 * state->drift <= -state->count)
89         v ^= (-1);
90 #else
91     v ^= ((2 * state->drift + state->count) >> 31);
92 #endif
93
94     ret = fold(v + state->bias, bits);
95
96     update_vlc_state(state, v);
97
98     return ret;
99 }
100
101 static av_always_inline void decode_line(FFV1Context *s, int w,
102                                          int16_t *sample[2],
103                                          int plane_index, int bits)
104 {
105     PlaneContext *const p = &s->plane[plane_index];
106     RangeCoder *const c   = &s->c;
107     int x;
108     int run_count = 0;
109     int run_mode  = 0;
110     int run_index = s->run_index;
111
112     for (x = 0; x < w; x++) {
113         int diff, context, sign;
114
115         context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
116         if (context < 0) {
117             context = -context;
118             sign    = 1;
119         } else
120             sign = 0;
121
122         av_assert2(context < p->context_count);
123
124         if (s->ac) {
125             diff = get_symbol_inline(c, p->state[context], 1);
126         } else {
127             if (context == 0 && run_mode == 0)
128                 run_mode = 1;
129
130             if (run_mode) {
131                 if (run_count == 0 && run_mode == 1) {
132                     if (get_bits1(&s->gb)) {
133                         run_count = 1 << ff_log2_run[run_index];
134                         if (x + run_count <= w)
135                             run_index++;
136                     } else {
137                         if (ff_log2_run[run_index])
138                             run_count = get_bits(&s->gb, ff_log2_run[run_index]);
139                         else
140                             run_count = 0;
141                         if (run_index)
142                             run_index--;
143                         run_mode = 2;
144                     }
145                 }
146                 run_count--;
147                 if (run_count < 0) {
148                     run_mode  = 0;
149                     run_count = 0;
150                     diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],
151                                                bits);
152                     if (diff >= 0)
153                         diff++;
154                 } else
155                     diff = 0;
156             } else
157                 diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
158
159             av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
160                     run_count, run_index, run_mode, x, get_bits_count(&s->gb));
161         }
162
163         if (sign)
164             diff = -diff;
165
166         sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
167                        ((1 << bits) - 1);
168     }
169     s->run_index = run_index;
170 }
171
172 static void decode_plane(FFV1Context *s, uint8_t *src,
173                          int w, int h, int stride, int plane_index)
174 {
175     int x, y;
176     int16_t *sample[2];
177     sample[0] = s->sample_buffer + 3;
178     sample[1] = s->sample_buffer + w + 6 + 3;
179
180     s->run_index = 0;
181
182     memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
183
184     for (y = 0; y < h; y++) {
185         int16_t *temp = sample[0]; // FIXME: try a normal buffer
186
187         sample[0] = sample[1];
188         sample[1] = temp;
189
190         sample[1][-1] = sample[0][0];
191         sample[0][w]  = sample[0][w - 1];
192
193 // { START_TIMER
194         if (s->avctx->bits_per_raw_sample <= 8) {
195             decode_line(s, w, sample, plane_index, 8);
196             for (x = 0; x < w; x++)
197                 src[x + stride * y] = sample[1][x];
198         } else {
199             decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
200             if (s->packed_at_lsb) {
201                 for (x = 0; x < w; x++) {
202                     ((uint16_t*)(src + stride*y))[x] = sample[1][x];
203                 }
204             } else {
205                 for (x = 0; x < w; x++) {
206                     ((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
207                 }
208             }
209         }
210 // STOP_TIMER("decode-line") }
211     }
212 }
213
214 static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
215 {
216     int x, y, p;
217     int16_t *sample[4][2];
218     int lbd    = s->avctx->bits_per_raw_sample <= 8;
219     int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
220     int offset = 1 << bits;
221
222     for (x = 0; x < 4; x++) {
223         sample[x][0] = s->sample_buffer +  x * 2      * (w + 6) + 3;
224         sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
225     }
226
227     s->run_index = 0;
228
229     memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
230
231     for (y = 0; y < h; y++) {
232         for (p = 0; p < 3 + s->transparency; p++) {
233             int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
234
235             sample[p][0] = sample[p][1];
236             sample[p][1] = temp;
237
238             sample[p][1][-1]= sample[p][0][0  ];
239             sample[p][0][ w]= sample[p][0][w-1];
240             if (lbd)
241                 decode_line(s, w, sample[p], (p + 1)/2, 9);
242             else
243                 decode_line(s, w, sample[p], (p + 1)/2, bits + 1);
244         }
245         for (x = 0; x < w; x++) {
246             int g = sample[0][1][x];
247             int b = sample[1][1][x];
248             int r = sample[2][1][x];
249             int a = sample[3][1][x];
250
251             b -= offset;
252             r -= offset;
253             g -= (b + r) >> 2;
254             b += g;
255             r += g;
256
257             if (lbd)
258                 *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
259             else {
260                 *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
261                 *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
262                 *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
263             }
264         }
265     }
266 }
267
268 static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
269 {
270     RangeCoder *c = &fs->c;
271     uint8_t state[CONTEXT_SIZE];
272     unsigned ps, i, context_count;
273     memset(state, 128, sizeof(state));
274
275     av_assert0(f->version > 2);
276
277     fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
278     fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
279     fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
280     fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
281
282     fs->slice_x /= f->num_h_slices;
283     fs->slice_y /= f->num_v_slices;
284     fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;
285     fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
286     if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
287         return -1;
288     if (    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
289          || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
290         return -1;
291
292     for (i = 0; i < f->plane_count; i++) {
293         PlaneContext * const p = &fs->plane[i];
294         int idx = get_symbol(c, state, 0);
295         if (idx > (unsigned)f->quant_table_count) {
296             av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
297             return -1;
298         }
299         p->quant_table_index = idx;
300         memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
301         context_count = f->context_count[idx];
302
303         if (p->context_count < context_count) {
304             av_freep(&p->state);
305             av_freep(&p->vlc_state);
306         }
307         p->context_count = context_count;
308     }
309
310     ps = get_symbol(c, state, 0);
311     if (ps == 1) {
312         f->picture.interlaced_frame = 1;
313         f->picture.top_field_first  = 1;
314     } else if (ps == 2) {
315         f->picture.interlaced_frame = 1;
316         f->picture.top_field_first  = 0;
317     } else if (ps == 3) {
318         f->picture.interlaced_frame = 0;
319     }
320     f->picture.sample_aspect_ratio.num = get_symbol(c, state, 0);
321     f->picture.sample_aspect_ratio.den = get_symbol(c, state, 0);
322
323     return 0;
324 }
325
326 static int decode_slice(AVCodecContext *c, void *arg)
327 {
328     FFV1Context *fs   = *(void **)arg;
329     FFV1Context *f    = fs->avctx->priv_data;
330     int width, height, x, y, ret;
331     const int ps      = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;
332     AVFrame * const p = &f->picture;
333
334     if (f->version > 2) {
335         if (ffv1_init_slice_state(f, fs) < 0)
336             return AVERROR(ENOMEM);
337         if (decode_slice_header(f, fs) < 0) {
338             fs->slice_damaged = 1;
339             return AVERROR_INVALIDDATA;
340         }
341     }
342     if ((ret = ffv1_init_slice_state(f, fs)) < 0)
343         return ret;
344     if (f->picture.key_frame)
345         ffv1_clear_slice_state(f, fs);
346
347     width  = fs->slice_width;
348     height = fs->slice_height;
349     x      = fs->slice_x;
350     y      = fs->slice_y;
351
352     if (!fs->ac) {
353         if (f->version == 3 && f->minor_version > 1 || f->version > 3)
354             get_rac(&fs->c, (uint8_t[]) { 129 });
355         fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
356         init_get_bits(&fs->gb,
357                       fs->c.bytestream_start + fs->ac_byte_count,
358                       (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
359     }
360
361     av_assert1(width && height);
362     if (f->colorspace == 0) {
363         const int chroma_width  = -((-width) >> f->chroma_h_shift);
364         const int chroma_height = -((-height) >> f->chroma_v_shift);
365         const int cx            = x >> f->chroma_h_shift;
366         const int cy            = y >> f->chroma_v_shift;
367         decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
368
369         if (f->chroma_planes) {
370             decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
371             decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
372         }
373         if (fs->transparency)
374             decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
375     } else {
376         uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
377                                p->data[1] + ps * x + y * p->linesize[1],
378                                p->data[2] + ps * x + y * p->linesize[2] };
379         decode_rgb_frame(fs, planes, width, height, p->linesize);
380     }
381     if (fs->ac && f->version > 2) {
382         int v;
383         get_rac(&fs->c, (uint8_t[]) { 129 });
384         v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
385         if (v) {
386             av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
387             fs->slice_damaged = 1;
388         }
389     }
390
391     emms_c();
392
393     return 0;
394 }
395
396 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
397 {
398     int v;
399     int i = 0;
400     uint8_t state[CONTEXT_SIZE];
401
402     memset(state, 128, sizeof(state));
403
404     for (v = 0; i < 128; v++) {
405         unsigned len = get_symbol(c, state, 0) + 1;
406
407         if (len > 128 - i)
408             return AVERROR_INVALIDDATA;
409
410         while (len--) {
411             quant_table[i] = scale * v;
412             i++;
413         }
414     }
415
416     for (i = 1; i < 128; i++)
417         quant_table[256 - i] = -quant_table[i];
418     quant_table[128] = -quant_table[127];
419
420     return 2 * v - 1;
421 }
422
423 static int read_quant_tables(RangeCoder *c,
424                              int16_t quant_table[MAX_CONTEXT_INPUTS][256])
425 {
426     int i;
427     int context_count = 1;
428
429     for (i = 0; i < 5; i++) {
430         context_count *= read_quant_table(c, quant_table[i], context_count);
431         if (context_count > 32768U) {
432             return AVERROR_INVALIDDATA;
433         }
434     }
435     return (context_count + 1) / 2;
436 }
437
438 static int read_extra_header(FFV1Context *f)
439 {
440     RangeCoder *const c = &f->c;
441     uint8_t state[CONTEXT_SIZE];
442     int i, j, k, ret;
443     uint8_t state2[32][CONTEXT_SIZE];
444
445     memset(state2, 128, sizeof(state2));
446     memset(state, 128, sizeof(state));
447
448     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
449     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
450
451     f->version = get_symbol(c, state, 0);
452     if (f->version > 2) {
453         c->bytestream_end -= 4;
454         f->minor_version = get_symbol(c, state, 0);
455     }
456     f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
457     if (f->ac > 1) {
458         for (i = 1; i < 256; i++)
459             f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
460     }
461
462     f->colorspace                 = get_symbol(c, state, 0); //YUV cs type
463     f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
464     f->chroma_planes              = get_rac(c, state);
465     f->chroma_h_shift             = get_symbol(c, state, 0);
466     f->chroma_v_shift             = get_symbol(c, state, 0);
467     f->transparency               = get_rac(c, state);
468     f->plane_count                = 2 + f->transparency;
469     f->num_h_slices               = 1 + get_symbol(c, state, 0);
470     f->num_v_slices               = 1 + get_symbol(c, state, 0);
471
472     if (f->num_h_slices > (unsigned)f->width  || !f->num_h_slices ||
473         f->num_v_slices > (unsigned)f->height || !f->num_v_slices
474        ) {
475         av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
476         return AVERROR_INVALIDDATA;
477     }
478
479     f->quant_table_count = get_symbol(c, state, 0);
480     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
481         return AVERROR_INVALIDDATA;
482
483     for (i = 0; i < f->quant_table_count; i++) {
484         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
485         if (f->context_count[i] < 0) {
486             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
487             return AVERROR_INVALIDDATA;
488         }
489     }
490     if ((ret = ffv1_allocate_initial_states(f)) < 0)
491         return ret;
492
493     for (i = 0; i < f->quant_table_count; i++)
494         if (get_rac(c, state)) {
495             for (j = 0; j < f->context_count[i]; j++)
496                 for (k = 0; k < CONTEXT_SIZE; k++) {
497                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
498                     f->initial_states[i][j][k] =
499                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
500                 }
501         }
502
503     if (f->version > 2) {
504         f->ec = get_symbol(c, state, 0);
505     }
506
507     if (f->version > 2) {
508         unsigned v;
509         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
510                    f->avctx->extradata, f->avctx->extradata_size);
511         if (v) {
512             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
513             return AVERROR_INVALIDDATA;
514         }
515     }
516
517     return 0;
518 }
519
520 static int read_header(FFV1Context *f)
521 {
522     uint8_t state[CONTEXT_SIZE];
523     int i, j, context_count = -1; //-1 to avoid warning
524     RangeCoder *const c = &f->slice_context[0]->c;
525
526     memset(state, 128, sizeof(state));
527
528     if (f->version < 2) {
529         unsigned v= get_symbol(c, state, 0);
530         if (v >= 2) {
531             av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
532             return AVERROR_INVALIDDATA;
533         }
534         f->version = v;
535         f->ac      = f->avctx->coder_type = get_symbol(c, state, 0);
536         if (f->ac > 1) {
537             for (i = 1; i < 256; i++)
538                 f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
539         }
540
541         f->colorspace = get_symbol(c, state, 0); //YUV cs type
542
543         if (f->version > 0)
544             f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
545
546         f->chroma_planes  = get_rac(c, state);
547         f->chroma_h_shift = get_symbol(c, state, 0);
548         f->chroma_v_shift = get_symbol(c, state, 0);
549         f->transparency   = get_rac(c, state);
550         f->plane_count    = 2 + f->transparency;
551     }
552
553     if (f->colorspace == 0) {
554         if (!f->transparency && !f->chroma_planes) {
555             if (f->avctx->bits_per_raw_sample <= 8)
556                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
557             else
558                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
559         } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
560             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
561             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
562             case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
563             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
564             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
565             case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
566             case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
567             default:
568                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
569                 return AVERROR(ENOSYS);
570             }
571         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
572             switch(16*f->chroma_h_shift + f->chroma_v_shift) {
573             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
574             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
575             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
576             default:
577                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
578                 return AVERROR(ENOSYS);
579             }
580         } else if (f->avctx->bits_per_raw_sample == 9) {
581             f->packed_at_lsb = 1;
582             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
583             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
584             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
585             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
586             default:
587                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
588                 return AVERROR(ENOSYS);
589             }
590         } else if (f->avctx->bits_per_raw_sample == 10) {
591             f->packed_at_lsb = 1;
592             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
593             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
594             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
595             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
596             default:
597                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
598                 return AVERROR(ENOSYS);
599             }
600         } else {
601             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
602             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
603             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
604             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
605             default:
606                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
607                 return AVERROR(ENOSYS);
608             }
609         }
610     } else if (f->colorspace == 1) {
611         if (f->chroma_h_shift || f->chroma_v_shift) {
612             av_log(f->avctx, AV_LOG_ERROR,
613                    "chroma subsampling not supported in this colorspace\n");
614             return AVERROR(ENOSYS);
615         }
616         if (     f->avctx->bits_per_raw_sample ==  9)
617             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
618         else if (f->avctx->bits_per_raw_sample == 10)
619             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
620         else if (f->avctx->bits_per_raw_sample == 12)
621             f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
622         else if (f->avctx->bits_per_raw_sample == 14)
623             f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
624         else
625         if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
626         else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
627     } else {
628         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
629         return AVERROR(ENOSYS);
630     }
631
632     av_dlog(f->avctx, "%d %d %d\n",
633             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
634     if (f->version < 2) {
635         context_count = read_quant_tables(c, f->quant_table);
636         if (context_count < 0) {
637             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
638             return AVERROR_INVALIDDATA;
639         }
640     } else if (f->version < 3) {
641         f->slice_count = get_symbol(c, state, 0);
642     } else {
643         const uint8_t *p = c->bytestream_end;
644         for (f->slice_count = 0;
645              f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
646              f->slice_count++) {
647             int trailer = 3 + 5*!!f->ec;
648             int size = AV_RB24(p-trailer);
649             if (size + trailer > p - c->bytestream_start)
650                 break;
651             p -= size + trailer;
652         }
653     }
654     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
655         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
656         return AVERROR_INVALIDDATA;
657     }
658
659     for (j = 0; j < f->slice_count; j++) {
660         FFV1Context *fs = f->slice_context[j];
661         fs->ac            = f->ac;
662         fs->packed_at_lsb = f->packed_at_lsb;
663
664         fs->slice_damaged = 0;
665
666         if (f->version == 2) {
667             fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
668             fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
669             fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
670             fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
671
672             fs->slice_x     /= f->num_h_slices;
673             fs->slice_y     /= f->num_v_slices;
674             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
675             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
676             if ((unsigned)fs->slice_width  > f->width ||
677                 (unsigned)fs->slice_height > f->height)
678                 return AVERROR_INVALIDDATA;
679             if (   (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
680                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
681                 return AVERROR_INVALIDDATA;
682         }
683
684         for (i = 0; i < f->plane_count; i++) {
685             PlaneContext *const p = &fs->plane[i];
686
687             if (f->version == 2) {
688                 int idx = get_symbol(c, state, 0);
689                 if (idx > (unsigned)f->quant_table_count) {
690                     av_log(f->avctx, AV_LOG_ERROR,
691                            "quant_table_index out of range\n");
692                     return AVERROR_INVALIDDATA;
693                 }
694                 p->quant_table_index = idx;
695                 memcpy(p->quant_table, f->quant_tables[idx],
696                        sizeof(p->quant_table));
697                 context_count = f->context_count[idx];
698             } else {
699                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
700             }
701
702             if (f->version <= 2) {
703                 av_assert0(context_count >= 0);
704                 if (p->context_count < context_count) {
705                     av_freep(&p->state);
706                     av_freep(&p->vlc_state);
707                 }
708                 p->context_count = context_count;
709             }
710         }
711     }
712     return 0;
713 }
714
715 static av_cold int decode_init(AVCodecContext *avctx)
716 {
717     FFV1Context *f = avctx->priv_data;
718     int ret;
719
720     if ((ret = ffv1_common_init(avctx)) < 0)
721         return ret;
722
723     if (avctx->extradata && (ret = read_extra_header(f)) < 0)
724         return ret;
725
726     if ((ret = ffv1_init_slice_contexts(f)) < 0)
727         return ret;
728
729     return 0;
730 }
731
732 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
733 {
734     const uint8_t *buf  = avpkt->data;
735     int buf_size        = avpkt->size;
736     FFV1Context *f      = avctx->priv_data;
737     RangeCoder *const c = &f->slice_context[0]->c;
738     AVFrame *const p    = &f->picture;
739     int i, ret;
740     uint8_t keystate = 128;
741     const uint8_t *buf_p;
742
743     AVFrame *picture = data;
744
745     /* release previously stored data */
746     if (p->data[0])
747         avctx->release_buffer(avctx, p);
748
749     ff_init_range_decoder(c, buf, buf_size);
750     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
751
752     p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
753     if (get_rac(c, &keystate)) {
754         p->key_frame    = 1;
755         f->key_frame_ok = 0;
756         if ((ret = read_header(f)) < 0)
757             return ret;
758         f->key_frame_ok = 1;
759     } else {
760         if (!f->key_frame_ok) {
761             av_log(avctx, AV_LOG_ERROR,
762                    "Cant decode non keyframe without valid keyframe\n");
763             return AVERROR_INVALIDDATA;
764         }
765         p->key_frame = 0;
766     }
767
768     p->reference = 3; //for error concealment
769     if ((ret = avctx->get_buffer(avctx, p)) < 0) {
770         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
771         return ret;
772     }
773
774     if (avctx->debug & FF_DEBUG_PICT_INFO)
775         av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
776                f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
777
778     buf_p = buf + buf_size;
779     for (i = f->slice_count - 1; i >= 0; i--) {
780         FFV1Context *fs = f->slice_context[i];
781         int trailer = 3 + 5*!!f->ec;
782         int v;
783
784         if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
785         else                     v = buf_p - c->bytestream_start;
786         if (buf_p - c->bytestream_start < v) {
787             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
788             return AVERROR_INVALIDDATA;
789         }
790         buf_p -= v;
791
792         if (f->ec) {
793             unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
794             if (crc) {
795                 int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
796                 av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
797                 if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
798                     av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
799                 } else if (ts != AV_NOPTS_VALUE) {
800                     av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
801                 } else {
802                     av_log(f->avctx, AV_LOG_ERROR, "\n");
803                 }
804                 fs->slice_damaged = 1;
805             }
806         }
807
808         if (i) {
809             ff_init_range_decoder(&fs->c, buf_p, v);
810         } else
811             fs->c.bytestream_end = (uint8_t *)(buf_p + v);
812     }
813
814     avctx->execute(avctx,
815                    decode_slice,
816                    &f->slice_context[0],
817                    NULL,
818                    f->slice_count,
819                    sizeof(void*));
820
821     for (i = f->slice_count - 1; i >= 0; i--) {
822         FFV1Context *fs = f->slice_context[i];
823         int j;
824         if (fs->slice_damaged && f->last_picture.data[0]) {
825             const uint8_t *src[4];
826             uint8_t *dst[4];
827             for (j = 0; j < 4; j++) {
828                 int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
829                 int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
830                 dst[j] = f->picture     .data[j] + f->picture     .linesize[j]*
831                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
832                 src[j] = f->last_picture.data[j] + f->last_picture.linesize[j]*
833                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
834             }
835             av_image_copy(dst,
836                           f->picture.linesize,
837                           (const uint8_t **)src,
838                           f->last_picture.linesize,
839                           avctx->pix_fmt,
840                           fs->slice_width,
841                           fs->slice_height);
842         }
843     }
844
845     f->picture_number++;
846
847     *picture   = *p;
848     *data_size = sizeof(AVFrame);
849
850     FFSWAP(AVFrame, f->picture, f->last_picture);
851
852     return buf_size;
853 }
854
855 AVCodec ff_ffv1_decoder = {
856     .name           = "ffv1",
857     .type           = AVMEDIA_TYPE_VIDEO,
858     .id             = AV_CODEC_ID_FFV1,
859     .priv_data_size = sizeof(FFV1Context),
860     .init           = decode_init,
861     .close          = ffv1_close,
862     .decode         = decode_frame,
863     .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
864                       CODEC_CAP_SLICE_THREADS,
865     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
866 };