]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1dec.c
Merge commit '594d4d5df3c70404168701dd5c90b7e6e5587793'
[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     v = get_sr_golomb(gb, k, 12, bits);
82     av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
83             v, state->bias, state->error_sum, state->drift, state->count, k);
84
85 #if 0 // JPEG LS
86     if (k == 0 && 2 * state->drift <= -state->count)
87         v ^= (-1);
88 #else
89     v ^= ((2 * state->drift + state->count) >> 31);
90 #endif
91
92     ret = fold(v + state->bias, bits);
93
94     update_vlc_state(state, v);
95
96     return ret;
97 }
98
99 static av_always_inline void decode_line(FFV1Context *s, int w,
100                                          int16_t *sample[2],
101                                          int plane_index, int bits)
102 {
103     PlaneContext *const p = &s->plane[plane_index];
104     RangeCoder *const c   = &s->c;
105     int x;
106     int run_count = 0;
107     int run_mode  = 0;
108     int run_index = s->run_index;
109
110     for (x = 0; x < w; x++) {
111         int diff, context, sign;
112
113         context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
114         if (context < 0) {
115             context = -context;
116             sign    = 1;
117         } else
118             sign = 0;
119
120         av_assert2(context < p->context_count);
121
122         if (s->ac) {
123             diff = get_symbol_inline(c, p->state[context], 1);
124         } else {
125             if (context == 0 && run_mode == 0)
126                 run_mode = 1;
127
128             if (run_mode) {
129                 if (run_count == 0 && run_mode == 1) {
130                     if (get_bits1(&s->gb)) {
131                         run_count = 1 << ff_log2_run[run_index];
132                         if (x + run_count <= w)
133                             run_index++;
134                     } else {
135                         if (ff_log2_run[run_index])
136                             run_count = get_bits(&s->gb, ff_log2_run[run_index]);
137                         else
138                             run_count = 0;
139                         if (run_index)
140                             run_index--;
141                         run_mode = 2;
142                     }
143                 }
144                 run_count--;
145                 if (run_count < 0) {
146                     run_mode  = 0;
147                     run_count = 0;
148                     diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],
149                                                bits);
150                     if (diff >= 0)
151                         diff++;
152                 } else
153                     diff = 0;
154             } else
155                 diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
156
157             av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
158                     run_count, run_index, run_mode, x, get_bits_count(&s->gb));
159         }
160
161         if (sign)
162             diff = -diff;
163
164         sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
165                        ((1 << bits) - 1);
166     }
167     s->run_index = run_index;
168 }
169
170 static void decode_plane(FFV1Context *s, uint8_t *src,
171                          int w, int h, int stride, int plane_index)
172 {
173     int x, y;
174     int16_t *sample[2];
175     sample[0] = s->sample_buffer + 3;
176     sample[1] = s->sample_buffer + w + 6 + 3;
177
178     s->run_index = 0;
179
180     memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
181
182     for (y = 0; y < h; y++) {
183         int16_t *temp = sample[0]; // FIXME: try a normal buffer
184
185         sample[0] = sample[1];
186         sample[1] = temp;
187
188         sample[1][-1] = sample[0][0];
189         sample[0][w]  = sample[0][w - 1];
190
191 // { START_TIMER
192         if (s->avctx->bits_per_raw_sample <= 8) {
193             decode_line(s, w, sample, plane_index, 8);
194             for (x = 0; x < w; x++)
195                 src[x + stride * y] = sample[1][x];
196         } else {
197             decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
198             if (s->packed_at_lsb) {
199                 for (x = 0; x < w; x++) {
200                     ((uint16_t*)(src + stride*y))[x] = sample[1][x];
201                 }
202             } else {
203                 for (x = 0; x < w; x++) {
204                     ((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
205                 }
206             }
207         }
208 // STOP_TIMER("decode-line") }
209     }
210 }
211
212 static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
213 {
214     int x, y, p;
215     int16_t *sample[4][2];
216     int lbd    = s->avctx->bits_per_raw_sample <= 8;
217     int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
218     int offset = 1 << bits;
219
220     for (x = 0; x < 4; x++) {
221         sample[x][0] = s->sample_buffer +  x * 2      * (w + 6) + 3;
222         sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
223     }
224
225     s->run_index = 0;
226
227     memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
228
229     for (y = 0; y < h; y++) {
230         for (p = 0; p < 3 + s->transparency; p++) {
231             int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
232
233             sample[p][0] = sample[p][1];
234             sample[p][1] = temp;
235
236             sample[p][1][-1]= sample[p][0][0  ];
237             sample[p][0][ w]= sample[p][0][w-1];
238             if (lbd)
239                 decode_line(s, w, sample[p], (p + 1)/2, 9);
240             else
241                 decode_line(s, w, sample[p], (p + 1)/2, bits + 1);
242         }
243         for (x = 0; x < w; x++) {
244             int g = sample[0][1][x];
245             int b = sample[1][1][x];
246             int r = sample[2][1][x];
247             int a = sample[3][1][x];
248
249             b -= offset;
250             r -= offset;
251             g -= (b + r) >> 2;
252             b += g;
253             r += g;
254
255             if (lbd)
256                 *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
257             else {
258                 *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
259                 *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
260                 *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
261             }
262         }
263     }
264 }
265
266 static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
267 {
268     RangeCoder *c = &fs->c;
269     uint8_t state[CONTEXT_SIZE];
270     unsigned ps, i, context_count;
271     memset(state, 128, sizeof(state));
272
273     av_assert0(f->version > 2);
274
275     fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
276     fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
277     fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
278     fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
279
280     fs->slice_x /= f->num_h_slices;
281     fs->slice_y /= f->num_v_slices;
282     fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;
283     fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
284     if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
285         return -1;
286     if (    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
287          || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
288         return -1;
289
290     for (i = 0; i < f->plane_count; i++) {
291         PlaneContext * const p = &fs->plane[i];
292         int idx = get_symbol(c, state, 0);
293         if (idx > (unsigned)f->quant_table_count) {
294             av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
295             return -1;
296         }
297         p->quant_table_index = idx;
298         memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
299         context_count = f->context_count[idx];
300
301         if (p->context_count < context_count) {
302             av_freep(&p->state);
303             av_freep(&p->vlc_state);
304         }
305         p->context_count = context_count;
306     }
307
308     ps = get_symbol(c, state, 0);
309     if (ps == 1) {
310         f->picture.interlaced_frame = 1;
311         f->picture.top_field_first  = 1;
312     } else if (ps == 2) {
313         f->picture.interlaced_frame = 1;
314         f->picture.top_field_first  = 0;
315     } else if (ps == 3) {
316         f->picture.interlaced_frame = 0;
317     }
318     f->picture.sample_aspect_ratio.num = get_symbol(c, state, 0);
319     f->picture.sample_aspect_ratio.den = get_symbol(c, state, 0);
320
321     return 0;
322 }
323
324 static int decode_slice(AVCodecContext *c, void *arg)
325 {
326     FFV1Context *fs   = *(void **)arg;
327     FFV1Context *f    = fs->avctx->priv_data;
328     int width, height, x, y, ret;
329     const int ps      = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;
330     AVFrame * const p = &f->picture;
331
332     if (f->version > 2) {
333         if (ffv1_init_slice_state(f, fs) < 0)
334             return AVERROR(ENOMEM);
335         if (decode_slice_header(f, fs) < 0) {
336             fs->slice_damaged = 1;
337             return AVERROR_INVALIDDATA;
338         }
339     }
340     if ((ret = ffv1_init_slice_state(f, fs)) < 0)
341         return ret;
342     if (f->picture.key_frame)
343         ffv1_clear_slice_state(f, fs);
344
345     width  = fs->slice_width;
346     height = fs->slice_height;
347     x      = fs->slice_x;
348     y      = fs->slice_y;
349
350     if (!fs->ac) {
351         if (f->version == 3 && f->minor_version > 1 || f->version > 3)
352             get_rac(&fs->c, (uint8_t[]) { 129 });
353         fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
354         init_get_bits(&fs->gb,
355                       fs->c.bytestream_start + fs->ac_byte_count,
356                       (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
357     }
358
359     av_assert1(width && height);
360     if (f->colorspace == 0) {
361         const int chroma_width  = -((-width) >> f->chroma_h_shift);
362         const int chroma_height = -((-height) >> f->chroma_v_shift);
363         const int cx            = x >> f->chroma_h_shift;
364         const int cy            = y >> f->chroma_v_shift;
365         decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
366
367         if (f->chroma_planes) {
368             decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
369             decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
370         }
371         if (fs->transparency)
372             decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
373     } else {
374         uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
375                                p->data[1] + ps * x + y * p->linesize[1],
376                                p->data[2] + ps * x + y * p->linesize[2] };
377         decode_rgb_frame(fs, planes, width, height, p->linesize);
378     }
379     if (fs->ac && f->version > 2) {
380         int v;
381         get_rac(&fs->c, (uint8_t[]) { 129 });
382         v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
383         if (v) {
384             av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
385             fs->slice_damaged = 1;
386         }
387     }
388
389     emms_c();
390
391     return 0;
392 }
393
394 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
395 {
396     int v;
397     int i = 0;
398     uint8_t state[CONTEXT_SIZE];
399
400     memset(state, 128, sizeof(state));
401
402     for (v = 0; i < 128; v++) {
403         unsigned len = get_symbol(c, state, 0) + 1;
404
405         if (len > 128 - i)
406             return AVERROR_INVALIDDATA;
407
408         while (len--) {
409             quant_table[i] = scale * v;
410             i++;
411         }
412     }
413
414     for (i = 1; i < 128; i++)
415         quant_table[256 - i] = -quant_table[i];
416     quant_table[128] = -quant_table[127];
417
418     return 2 * v - 1;
419 }
420
421 static int read_quant_tables(RangeCoder *c,
422                              int16_t quant_table[MAX_CONTEXT_INPUTS][256])
423 {
424     int i;
425     int context_count = 1;
426
427     for (i = 0; i < 5; i++) {
428         context_count *= read_quant_table(c, quant_table[i], context_count);
429         if (context_count > 32768U) {
430             return AVERROR_INVALIDDATA;
431         }
432     }
433     return (context_count + 1) / 2;
434 }
435
436 static int read_extra_header(FFV1Context *f)
437 {
438     RangeCoder *const c = &f->c;
439     uint8_t state[CONTEXT_SIZE];
440     int i, j, k, ret;
441     uint8_t state2[32][CONTEXT_SIZE];
442
443     memset(state2, 128, sizeof(state2));
444     memset(state, 128, sizeof(state));
445
446     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
447     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
448
449     f->version = get_symbol(c, state, 0);
450     if (f->version > 2) {
451         c->bytestream_end -= 4;
452         f->minor_version = get_symbol(c, state, 0);
453     }
454     f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
455     if (f->ac > 1) {
456         for (i = 1; i < 256; i++)
457             f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
458     }
459
460     f->colorspace                 = get_symbol(c, state, 0); //YUV cs type
461     f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
462     f->chroma_planes              = get_rac(c, state);
463     f->chroma_h_shift             = get_symbol(c, state, 0);
464     f->chroma_v_shift             = get_symbol(c, state, 0);
465     f->transparency               = get_rac(c, state);
466     f->plane_count                = 2 + f->transparency;
467     f->num_h_slices               = 1 + get_symbol(c, state, 0);
468     f->num_v_slices               = 1 + get_symbol(c, state, 0);
469
470     if (f->num_h_slices > (unsigned)f->width  || !f->num_h_slices ||
471         f->num_v_slices > (unsigned)f->height || !f->num_v_slices
472        ) {
473         av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
474         return AVERROR_INVALIDDATA;
475     }
476
477     f->quant_table_count = get_symbol(c, state, 0);
478     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
479         return AVERROR_INVALIDDATA;
480
481     for (i = 0; i < f->quant_table_count; i++) {
482         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
483         if (f->context_count[i] < 0) {
484             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
485             return AVERROR_INVALIDDATA;
486         }
487     }
488     if ((ret = ffv1_allocate_initial_states(f)) < 0)
489         return ret;
490
491     for (i = 0; i < f->quant_table_count; i++)
492         if (get_rac(c, state)) {
493             for (j = 0; j < f->context_count[i]; j++)
494                 for (k = 0; k < CONTEXT_SIZE; k++) {
495                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
496                     f->initial_states[i][j][k] =
497                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
498                 }
499         }
500
501     if (f->version > 2) {
502         f->ec = get_symbol(c, state, 0);
503     }
504
505     if (f->version > 2) {
506         unsigned v;
507         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
508                    f->avctx->extradata, f->avctx->extradata_size);
509         if (v) {
510             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
511             return AVERROR_INVALIDDATA;
512         }
513     }
514
515     return 0;
516 }
517
518 static int read_header(FFV1Context *f)
519 {
520     uint8_t state[CONTEXT_SIZE];
521     int i, j, context_count = -1; //-1 to avoid warning
522     RangeCoder *const c = &f->slice_context[0]->c;
523
524     memset(state, 128, sizeof(state));
525
526     if (f->version < 2) {
527         unsigned v= get_symbol(c, state, 0);
528         if (v >= 2) {
529             av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
530             return AVERROR_INVALIDDATA;
531         }
532         f->version = v;
533         f->ac      = f->avctx->coder_type = get_symbol(c, state, 0);
534         if (f->ac > 1) {
535             for (i = 1; i < 256; i++)
536                 f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
537         }
538
539         f->colorspace = get_symbol(c, state, 0); //YUV cs type
540
541         if (f->version > 0)
542             f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
543
544         f->chroma_planes  = get_rac(c, state);
545         f->chroma_h_shift = get_symbol(c, state, 0);
546         f->chroma_v_shift = get_symbol(c, state, 0);
547         f->transparency   = get_rac(c, state);
548         f->plane_count    = 2 + f->transparency;
549     }
550
551     if (f->colorspace == 0) {
552         if (!f->transparency && !f->chroma_planes) {
553             if (f->avctx->bits_per_raw_sample <= 8)
554                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
555             else
556                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
557         } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
558             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
559             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
560             case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
561             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
562             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
563             case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
564             case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
565             default:
566                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
567                 return AVERROR(ENOSYS);
568             }
569         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
570             switch(16*f->chroma_h_shift + f->chroma_v_shift) {
571             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
572             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
573             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
574             default:
575                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
576                 return AVERROR(ENOSYS);
577             }
578         } else if (f->avctx->bits_per_raw_sample == 9) {
579             f->packed_at_lsb = 1;
580             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
581             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
582             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
583             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
584             default:
585                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
586                 return AVERROR(ENOSYS);
587             }
588         } else if (f->avctx->bits_per_raw_sample == 10) {
589             f->packed_at_lsb = 1;
590             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
591             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
592             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
593             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
594             default:
595                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
596                 return AVERROR(ENOSYS);
597             }
598         } else {
599             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
600             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
601             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
602             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
603             default:
604                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
605                 return AVERROR(ENOSYS);
606             }
607         }
608     } else if (f->colorspace == 1) {
609         if (f->chroma_h_shift || f->chroma_v_shift) {
610             av_log(f->avctx, AV_LOG_ERROR,
611                    "chroma subsampling not supported in this colorspace\n");
612             return AVERROR(ENOSYS);
613         }
614         if (     f->avctx->bits_per_raw_sample ==  9)
615             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
616         else if (f->avctx->bits_per_raw_sample == 10)
617             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
618         else if (f->avctx->bits_per_raw_sample == 12)
619             f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
620         else if (f->avctx->bits_per_raw_sample == 14)
621             f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
622         else
623         if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
624         else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
625     } else {
626         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
627         return AVERROR(ENOSYS);
628     }
629
630     av_dlog(f->avctx, "%d %d %d\n",
631             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
632     if (f->version < 2) {
633         context_count = read_quant_tables(c, f->quant_table);
634         if (context_count < 0) {
635             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
636             return AVERROR_INVALIDDATA;
637         }
638     } else if (f->version < 3) {
639         f->slice_count = get_symbol(c, state, 0);
640     } else {
641         const uint8_t *p = c->bytestream_end;
642         for (f->slice_count = 0;
643              f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
644              f->slice_count++) {
645             int trailer = 3 + 5*!!f->ec;
646             int size = AV_RB24(p-trailer);
647             if (size + trailer > p - c->bytestream_start)
648                 break;
649             p -= size + trailer;
650         }
651     }
652     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
653         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
654         return AVERROR_INVALIDDATA;
655     }
656
657     for (j = 0; j < f->slice_count; j++) {
658         FFV1Context *fs = f->slice_context[j];
659         fs->ac            = f->ac;
660         fs->packed_at_lsb = f->packed_at_lsb;
661
662         fs->slice_damaged = 0;
663
664         if (f->version == 2) {
665             fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
666             fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
667             fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
668             fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
669
670             fs->slice_x     /= f->num_h_slices;
671             fs->slice_y     /= f->num_v_slices;
672             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
673             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
674             if ((unsigned)fs->slice_width  > f->width ||
675                 (unsigned)fs->slice_height > f->height)
676                 return AVERROR_INVALIDDATA;
677             if (   (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
678                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
679                 return AVERROR_INVALIDDATA;
680         }
681
682         for (i = 0; i < f->plane_count; i++) {
683             PlaneContext *const p = &fs->plane[i];
684
685             if (f->version == 2) {
686                 int idx = get_symbol(c, state, 0);
687                 if (idx > (unsigned)f->quant_table_count) {
688                     av_log(f->avctx, AV_LOG_ERROR,
689                            "quant_table_index out of range\n");
690                     return AVERROR_INVALIDDATA;
691                 }
692                 p->quant_table_index = idx;
693                 memcpy(p->quant_table, f->quant_tables[idx],
694                        sizeof(p->quant_table));
695                 context_count = f->context_count[idx];
696             } else {
697                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
698             }
699
700             if (f->version <= 2) {
701                 av_assert0(context_count >= 0);
702                 if (p->context_count < context_count) {
703                     av_freep(&p->state);
704                     av_freep(&p->vlc_state);
705                 }
706                 p->context_count = context_count;
707             }
708         }
709     }
710     return 0;
711 }
712
713 static av_cold int decode_init(AVCodecContext *avctx)
714 {
715     FFV1Context *f = avctx->priv_data;
716     int ret;
717
718     if ((ret = ffv1_common_init(avctx)) < 0)
719         return ret;
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 = ff_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 };