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