]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1dec.c
Merge remote-tracking branch 'qatar/master'
[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 ||
473         f->num_v_slices > (unsigned)f->height) {
474         av_log(f->avctx, AV_LOG_ERROR, "too many slices\n");
475         return AVERROR_INVALIDDATA;
476     }
477
478     f->quant_table_count = get_symbol(c, state, 0);
479     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
480         return AVERROR_INVALIDDATA;
481
482     for (i = 0; i < f->quant_table_count; i++) {
483         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
484         if (f->context_count[i] < 0) {
485             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
486             return AVERROR_INVALIDDATA;
487         }
488     }
489     if ((ret = ffv1_allocate_initial_states(f)) < 0)
490         return ret;
491
492     for (i = 0; i < f->quant_table_count; i++)
493         if (get_rac(c, state)) {
494             for (j = 0; j < f->context_count[i]; j++)
495                 for (k = 0; k < CONTEXT_SIZE; k++) {
496                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
497                     f->initial_states[i][j][k] =
498                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
499                 }
500         }
501
502     if (f->version > 2) {
503         f->ec = get_symbol(c, state, 0);
504     }
505
506     if (f->version > 2) {
507         unsigned v;
508         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
509                    f->avctx->extradata, f->avctx->extradata_size);
510         if (v) {
511             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
512             return AVERROR_INVALIDDATA;
513         }
514     }
515
516     return 0;
517 }
518
519 static int read_header(FFV1Context *f)
520 {
521     uint8_t state[CONTEXT_SIZE];
522     int i, j, context_count = -1; //-1 to avoid warning
523     RangeCoder *const c = &f->slice_context[0]->c;
524
525     memset(state, 128, sizeof(state));
526
527     if (f->version < 2) {
528         unsigned v= get_symbol(c, state, 0);
529         if (v >= 2) {
530             av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
531             return AVERROR_INVALIDDATA;
532         }
533         f->version = v;
534         f->ac      = f->avctx->coder_type = get_symbol(c, state, 0);
535         if (f->ac > 1) {
536             for (i = 1; i < 256; i++)
537                 f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
538         }
539
540         f->colorspace = get_symbol(c, state, 0); //YUV cs type
541
542         if (f->version > 0)
543             f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
544
545         f->chroma_planes  = get_rac(c, state);
546         f->chroma_h_shift = get_symbol(c, state, 0);
547         f->chroma_v_shift = get_symbol(c, state, 0);
548         f->transparency   = get_rac(c, state);
549         f->plane_count    = 2 + f->transparency;
550     }
551
552     if (f->colorspace == 0) {
553         if (!f->transparency && !f->chroma_planes) {
554             if (f->avctx->bits_per_raw_sample <= 8)
555                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
556             else
557                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
558         } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
559             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
560             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
561             case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
562             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
563             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
564             case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
565             case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
566             default:
567                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
568                 return AVERROR(ENOSYS);
569             }
570         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
571             switch(16*f->chroma_h_shift + f->chroma_v_shift) {
572             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
573             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
574             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
575             default:
576                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
577                 return AVERROR(ENOSYS);
578             }
579         } else if (f->avctx->bits_per_raw_sample == 9) {
580             f->packed_at_lsb = 1;
581             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
582             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
583             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
584             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
585             default:
586                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
587                 return AVERROR(ENOSYS);
588             }
589         } else if (f->avctx->bits_per_raw_sample == 10) {
590             f->packed_at_lsb = 1;
591             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
592             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
593             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
594             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
595             default:
596                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
597                 return AVERROR(ENOSYS);
598             }
599         } else {
600             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
601             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
602             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
603             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
604             default:
605                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
606                 return AVERROR(ENOSYS);
607             }
608         }
609     } else if (f->colorspace == 1) {
610         if (f->chroma_h_shift || f->chroma_v_shift) {
611             av_log(f->avctx, AV_LOG_ERROR,
612                    "chroma subsampling not supported in this colorspace\n");
613             return AVERROR(ENOSYS);
614         }
615         if (     f->avctx->bits_per_raw_sample ==  9)
616             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
617         else if (f->avctx->bits_per_raw_sample == 10)
618             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
619         else if (f->avctx->bits_per_raw_sample == 12)
620             f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
621         else if (f->avctx->bits_per_raw_sample == 14)
622             f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
623         else
624         if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
625         else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
626     } else {
627         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
628         return AVERROR(ENOSYS);
629     }
630
631     av_dlog(f->avctx, "%d %d %d\n",
632             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
633     if (f->version < 2) {
634         context_count = read_quant_tables(c, f->quant_table);
635         if (context_count < 0) {
636             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
637             return AVERROR_INVALIDDATA;
638         }
639     } else if (f->version < 3) {
640         f->slice_count = get_symbol(c, state, 0);
641     } else {
642         const uint8_t *p = c->bytestream_end;
643         for (f->slice_count = 0;
644              f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
645              f->slice_count++) {
646             int trailer = 3 + 5*!!f->ec;
647             int size = AV_RB24(p-trailer);
648             if (size + trailer > p - c->bytestream_start)
649                 break;
650             p -= size + trailer;
651         }
652     }
653     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
654         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
655         return AVERROR_INVALIDDATA;
656     }
657
658     for (j = 0; j < f->slice_count; j++) {
659         FFV1Context *fs = f->slice_context[j];
660         fs->ac            = f->ac;
661         fs->packed_at_lsb = f->packed_at_lsb;
662
663         fs->slice_damaged = 0;
664
665         if (f->version == 2) {
666             fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
667             fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
668             fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
669             fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
670
671             fs->slice_x     /= f->num_h_slices;
672             fs->slice_y     /= f->num_v_slices;
673             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
674             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
675             if ((unsigned)fs->slice_width  > f->width ||
676                 (unsigned)fs->slice_height > f->height)
677                 return AVERROR_INVALIDDATA;
678             if (   (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
679                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
680                 return AVERROR_INVALIDDATA;
681         }
682
683         for (i = 0; i < f->plane_count; i++) {
684             PlaneContext *const p = &fs->plane[i];
685
686             if (f->version == 2) {
687                 int idx = get_symbol(c, state, 0);
688                 if (idx > (unsigned)f->quant_table_count) {
689                     av_log(f->avctx, AV_LOG_ERROR,
690                            "quant_table_index out of range\n");
691                     return AVERROR_INVALIDDATA;
692                 }
693                 p->quant_table_index = idx;
694                 memcpy(p->quant_table, f->quant_tables[idx],
695                        sizeof(p->quant_table));
696                 context_count = f->context_count[idx];
697             } else {
698                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
699             }
700
701             if (f->version <= 2) {
702                 av_assert0(context_count >= 0);
703                 if (p->context_count < context_count) {
704                     av_freep(&p->state);
705                     av_freep(&p->vlc_state);
706                 }
707                 p->context_count = context_count;
708             }
709         }
710     }
711     return 0;
712 }
713
714 static av_cold int decode_init(AVCodecContext *avctx)
715 {
716     FFV1Context *f = avctx->priv_data;
717     int ret;
718
719     ffv1_common_init(avctx);
720
721     if (avctx->extradata && (ret = read_extra_header(f)) < 0)
722         return ret;
723
724     if ((ret = ffv1_init_slice_contexts(f)) < 0)
725         return ret;
726
727     return 0;
728 }
729
730 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
731 {
732     const uint8_t *buf  = avpkt->data;
733     int buf_size        = avpkt->size;
734     FFV1Context *f      = avctx->priv_data;
735     RangeCoder *const c = &f->slice_context[0]->c;
736     AVFrame *const p    = &f->picture;
737     int i, ret;
738     uint8_t keystate = 128;
739     const uint8_t *buf_p;
740
741     AVFrame *picture = data;
742
743     /* release previously stored data */
744     if (p->data[0])
745         avctx->release_buffer(avctx, p);
746
747     ff_init_range_decoder(c, buf, buf_size);
748     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
749
750     p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
751     if (get_rac(c, &keystate)) {
752         p->key_frame    = 1;
753         f->key_frame_ok = 0;
754         if ((ret = read_header(f)) < 0)
755             return ret;
756         f->key_frame_ok = 1;
757     } else {
758         if (!f->key_frame_ok) {
759             av_log(avctx, AV_LOG_ERROR,
760                    "Cant decode non keyframe without valid keyframe\n");
761             return AVERROR_INVALIDDATA;
762         }
763         p->key_frame = 0;
764     }
765
766     p->reference = 3; //for error concealment
767     if ((ret = avctx->get_buffer(avctx, p)) < 0) {
768         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
769         return ret;
770     }
771
772     if (avctx->debug & FF_DEBUG_PICT_INFO)
773         av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
774                f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
775
776     buf_p = buf + buf_size;
777     for (i = f->slice_count - 1; i >= 0; i--) {
778         FFV1Context *fs = f->slice_context[i];
779         int trailer = 3 + 5*!!f->ec;
780         int v;
781
782         if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
783         else                     v = buf_p - c->bytestream_start;
784         if (buf_p - c->bytestream_start < v) {
785             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
786             return AVERROR_INVALIDDATA;
787         }
788         buf_p -= v;
789
790         if (f->ec) {
791             unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
792             if (crc) {
793                 int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
794                 av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
795                 if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
796                     av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
797                 } else if (ts != AV_NOPTS_VALUE) {
798                     av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
799                 } else {
800                     av_log(f->avctx, AV_LOG_ERROR, "\n");
801                 }
802                 fs->slice_damaged = 1;
803             }
804         }
805
806         if (i) {
807             ff_init_range_decoder(&fs->c, buf_p, v);
808         } else
809             fs->c.bytestream_end = (uint8_t *)(buf_p + v);
810     }
811
812     avctx->execute(avctx,
813                    decode_slice,
814                    &f->slice_context[0],
815                    NULL,
816                    f->slice_count,
817                    sizeof(void*));
818
819     for (i = f->slice_count - 1; i >= 0; i--) {
820         FFV1Context *fs = f->slice_context[i];
821         int j;
822         if (fs->slice_damaged && f->last_picture.data[0]) {
823             const uint8_t *src[4];
824             uint8_t *dst[4];
825             for (j = 0; j < 4; j++) {
826                 int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
827                 int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
828                 dst[j] = f->picture     .data[j] + f->picture     .linesize[j]*
829                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
830                 src[j] = f->last_picture.data[j] + f->last_picture.linesize[j]*
831                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
832             }
833             av_image_copy(dst,
834                           f->picture.linesize,
835                           (const uint8_t **)src,
836                           f->last_picture.linesize,
837                           avctx->pix_fmt,
838                           fs->slice_width,
839                           fs->slice_height);
840         }
841     }
842
843     f->picture_number++;
844
845     *picture   = *p;
846     *data_size = sizeof(AVFrame);
847
848     FFSWAP(AVFrame, f->picture, f->last_picture);
849
850     return buf_size;
851 }
852
853 AVCodec ff_ffv1_decoder = {
854     .name           = "ffv1",
855     .type           = AVMEDIA_TYPE_VIDEO,
856     .id             = AV_CODEC_ID_FFV1,
857     .priv_data_size = sizeof(FFV1Context),
858     .init           = decode_init,
859     .close          = ffv1_close,
860     .decode         = decode_frame,
861     .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
862                       CODEC_CAP_SLICE_THREADS,
863     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
864 };