]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1dec.c
ffv1dec: Check bits_per_raw_sample and colorspace for equality in ver 0/1 headers
[ffmpeg] / libavcodec / ffv1dec.c
1 /*
2  * FFV1 decoder
3  *
4  * Copyright (c) 2003-2013 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     int i, si;
330
331     for( si=0; fs != f->slice_context[si]; si ++)
332         ;
333
334     if(f->fsrc && !p->key_frame)
335         ff_thread_await_progress(&f->last_picture, si, 0);
336
337     if(f->fsrc && !p->key_frame) {
338         FFV1Context *fssrc = f->fsrc->slice_context[si];
339         FFV1Context *fsdst = f->slice_context[si];
340         av_assert1(fsdst->plane_count == fssrc->plane_count);
341         av_assert1(fsdst == fs);
342
343         if (!p->key_frame)
344             fsdst->slice_damaged |= fssrc->slice_damaged;
345
346         for (i = 0; i < f->plane_count; i++) {
347             PlaneContext *psrc = &fssrc->plane[i];
348             PlaneContext *pdst = &fsdst->plane[i];
349
350             av_free(pdst->state);
351             av_free(pdst->vlc_state);
352             memcpy(pdst, psrc, sizeof(*pdst));
353             pdst->state = NULL;
354             pdst->vlc_state = NULL;
355
356             if (fssrc->ac) {
357                 pdst->state = av_malloc(CONTEXT_SIZE * psrc->context_count);
358                 memcpy(pdst->state, psrc->state, CONTEXT_SIZE * psrc->context_count);
359             } else {
360                 pdst->vlc_state = av_malloc(sizeof(*pdst->vlc_state) * psrc->context_count);
361                 memcpy(pdst->vlc_state, psrc->vlc_state, sizeof(*pdst->vlc_state) * psrc->context_count);
362             }
363         }
364     }
365
366     if (f->version > 2) {
367         if (ffv1_init_slice_state(f, fs) < 0)
368             return AVERROR(ENOMEM);
369         if (decode_slice_header(f, fs) < 0) {
370             fs->slice_damaged = 1;
371             return AVERROR_INVALIDDATA;
372         }
373     }
374     if ((ret = ffv1_init_slice_state(f, fs)) < 0)
375         return ret;
376     if (f->cur->key_frame)
377         ffv1_clear_slice_state(f, fs);
378
379     width  = fs->slice_width;
380     height = fs->slice_height;
381     x      = fs->slice_x;
382     y      = fs->slice_y;
383
384     if (!fs->ac) {
385         if (f->version == 3 && f->micro_version > 1 || f->version > 3)
386             get_rac(&fs->c, (uint8_t[]) { 129 });
387         fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
388         init_get_bits(&fs->gb,
389                       fs->c.bytestream_start + fs->ac_byte_count,
390                       (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
391     }
392
393     av_assert1(width && height);
394     if (f->colorspace == 0) {
395         const int chroma_width  = FF_CEIL_RSHIFT(width,  f->chroma_h_shift);
396         const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift);
397         const int cx            = x >> f->chroma_h_shift;
398         const int cy            = y >> f->chroma_v_shift;
399         decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
400
401         if (f->chroma_planes) {
402             decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
403             decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
404         }
405         if (fs->transparency)
406             decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
407     } else {
408         uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
409                                p->data[1] + ps * x + y * p->linesize[1],
410                                p->data[2] + ps * x + y * p->linesize[2] };
411         decode_rgb_frame(fs, planes, width, height, p->linesize);
412     }
413     if (fs->ac && f->version > 2) {
414         int v;
415         get_rac(&fs->c, (uint8_t[]) { 129 });
416         v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
417         if (v) {
418             av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
419             fs->slice_damaged = 1;
420         }
421     }
422
423     emms_c();
424
425     ff_thread_report_progress(&f->picture, si, 0);
426
427     return 0;
428 }
429
430 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
431 {
432     int v;
433     int i = 0;
434     uint8_t state[CONTEXT_SIZE];
435
436     memset(state, 128, sizeof(state));
437
438     for (v = 0; i < 128; v++) {
439         unsigned len = get_symbol(c, state, 0) + 1;
440
441         if (len > 128 - i)
442             return AVERROR_INVALIDDATA;
443
444         while (len--) {
445             quant_table[i] = scale * v;
446             i++;
447         }
448     }
449
450     for (i = 1; i < 128; i++)
451         quant_table[256 - i] = -quant_table[i];
452     quant_table[128] = -quant_table[127];
453
454     return 2 * v - 1;
455 }
456
457 static int read_quant_tables(RangeCoder *c,
458                              int16_t quant_table[MAX_CONTEXT_INPUTS][256])
459 {
460     int i;
461     int context_count = 1;
462
463     for (i = 0; i < 5; i++) {
464         context_count *= read_quant_table(c, quant_table[i], context_count);
465         if (context_count > 32768U) {
466             return AVERROR_INVALIDDATA;
467         }
468     }
469     return (context_count + 1) / 2;
470 }
471
472 static int read_extra_header(FFV1Context *f)
473 {
474     RangeCoder *const c = &f->c;
475     uint8_t state[CONTEXT_SIZE];
476     int i, j, k, ret;
477     uint8_t state2[32][CONTEXT_SIZE];
478
479     memset(state2, 128, sizeof(state2));
480     memset(state, 128, sizeof(state));
481
482     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
483     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
484
485     f->version = get_symbol(c, state, 0);
486     if (f->version < 2) {
487         av_log(f->avctx, AV_LOG_ERROR, "Invalid version in global header\n");
488         return AVERROR_INVALIDDATA;
489     }
490     if (f->version > 2) {
491         c->bytestream_end -= 4;
492         f->micro_version = get_symbol(c, state, 0);
493     }
494     f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
495     if (f->ac > 1) {
496         for (i = 1; i < 256; i++)
497             f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
498     }
499
500     f->colorspace                 = get_symbol(c, state, 0); //YUV cs type
501     f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
502     f->chroma_planes              = get_rac(c, state);
503     f->chroma_h_shift             = get_symbol(c, state, 0);
504     f->chroma_v_shift             = get_symbol(c, state, 0);
505     f->transparency               = get_rac(c, state);
506     f->plane_count                = 1 + (f->chroma_planes || f->version<4) + f->transparency;
507     f->num_h_slices               = 1 + get_symbol(c, state, 0);
508     f->num_v_slices               = 1 + get_symbol(c, state, 0);
509
510     if (f->num_h_slices > (unsigned)f->width  || !f->num_h_slices ||
511         f->num_v_slices > (unsigned)f->height || !f->num_v_slices
512        ) {
513         av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
514         return AVERROR_INVALIDDATA;
515     }
516
517     f->quant_table_count = get_symbol(c, state, 0);
518     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
519         return AVERROR_INVALIDDATA;
520
521     for (i = 0; i < f->quant_table_count; i++) {
522         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
523         if (f->context_count[i] < 0) {
524             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
525             return AVERROR_INVALIDDATA;
526         }
527     }
528     if ((ret = ffv1_allocate_initial_states(f)) < 0)
529         return ret;
530
531     for (i = 0; i < f->quant_table_count; i++)
532         if (get_rac(c, state)) {
533             for (j = 0; j < f->context_count[i]; j++)
534                 for (k = 0; k < CONTEXT_SIZE; k++) {
535                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
536                     f->initial_states[i][j][k] =
537                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
538                 }
539         }
540
541     if (f->version > 2) {
542         f->ec = get_symbol(c, state, 0);
543         if (f->micro_version > 2)
544             f->intra = get_symbol(c, state, 0);
545     }
546
547     if (f->version > 2) {
548         unsigned v;
549         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
550                    f->avctx->extradata, f->avctx->extradata_size);
551         if (v) {
552             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
553             return AVERROR_INVALIDDATA;
554         }
555     }
556
557     if (f->avctx->debug & FF_DEBUG_PICT_INFO)
558         av_log(f->avctx, AV_LOG_DEBUG,
559                "global: ver:%d.%d, coder:%d, colorspace: %d bpr:%d chroma:%d(%d:%d), alpha:%d slices:%dx%d qtabs:%d ec:%d intra:%d\n",
560                f->version, f->micro_version,
561                f->ac,
562                f->colorspace,
563                f->avctx->bits_per_raw_sample,
564                f->chroma_planes, f->chroma_h_shift, f->chroma_v_shift,
565                f->transparency,
566                f->num_h_slices, f->num_v_slices,
567                f->quant_table_count,
568                f->ec,
569                f->intra
570               );
571     return 0;
572 }
573
574 static int read_header(FFV1Context *f)
575 {
576     uint8_t state[CONTEXT_SIZE];
577     int i, j, context_count = -1; //-1 to avoid warning
578     RangeCoder *const c = &f->slice_context[0]->c;
579
580     memset(state, 128, sizeof(state));
581
582     if (f->version < 2) {
583         int chroma_planes, chroma_h_shift, chroma_v_shift, transparency, colorspace, bits_per_raw_sample;
584         unsigned v= get_symbol(c, state, 0);
585         if (v >= 2) {
586             av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
587             return AVERROR_INVALIDDATA;
588         }
589         f->version = v;
590         f->ac      = f->avctx->coder_type = get_symbol(c, state, 0);
591         if (f->ac > 1) {
592             for (i = 1; i < 256; i++)
593                 f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
594         }
595
596         colorspace     = get_symbol(c, state, 0); //YUV cs type
597         bits_per_raw_sample = f->version > 0 ? get_symbol(c, state, 0) : f->avctx->bits_per_raw_sample;
598         chroma_planes  = get_rac(c, state);
599         chroma_h_shift = get_symbol(c, state, 0);
600         chroma_v_shift = get_symbol(c, state, 0);
601         transparency   = get_rac(c, state);
602
603         if (f->plane_count) {
604             if (   colorspace    != f->colorspace
605                 || bits_per_raw_sample != f->avctx->bits_per_raw_sample
606                 || chroma_planes != f->chroma_planes
607                 || chroma_h_shift!= f->chroma_h_shift
608                 || chroma_v_shift!= f->chroma_v_shift
609                 || transparency  != f->transparency) {
610                 av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n");
611                 return AVERROR_INVALIDDATA;
612             }
613         }
614
615         f->colorspace     = colorspace;
616         f->avctx->bits_per_raw_sample = bits_per_raw_sample;
617         f->chroma_planes  = chroma_planes;
618         f->chroma_h_shift = chroma_h_shift;
619         f->chroma_v_shift = chroma_v_shift;
620         f->transparency   = transparency;
621
622         f->plane_count    = 2 + f->transparency;
623     }
624
625     if (f->colorspace == 0) {
626         if (!f->transparency && !f->chroma_planes) {
627             if (f->avctx->bits_per_raw_sample <= 8)
628                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
629             else
630                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
631         } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
632             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
633             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
634             case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
635             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
636             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
637             case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
638             case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
639             default:
640                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
641                 return AVERROR(ENOSYS);
642             }
643         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
644             switch(16*f->chroma_h_shift + f->chroma_v_shift) {
645             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
646             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
647             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
648             default:
649                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
650                 return AVERROR(ENOSYS);
651             }
652         } else if (f->avctx->bits_per_raw_sample == 9) {
653             f->packed_at_lsb = 1;
654             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
655             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
656             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
657             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
658             default:
659                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
660                 return AVERROR(ENOSYS);
661             }
662         } else if (f->avctx->bits_per_raw_sample == 10) {
663             f->packed_at_lsb = 1;
664             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
665             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
666             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
667             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
668             default:
669                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
670                 return AVERROR(ENOSYS);
671             }
672         } else {
673             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
674             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
675             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
676             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
677             default:
678                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
679                 return AVERROR(ENOSYS);
680             }
681         }
682     } else if (f->colorspace == 1) {
683         if (f->chroma_h_shift || f->chroma_v_shift) {
684             av_log(f->avctx, AV_LOG_ERROR,
685                    "chroma subsampling not supported in this colorspace\n");
686             return AVERROR(ENOSYS);
687         }
688         if (     f->avctx->bits_per_raw_sample ==  9)
689             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
690         else if (f->avctx->bits_per_raw_sample == 10)
691             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
692         else if (f->avctx->bits_per_raw_sample == 12)
693             f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
694         else if (f->avctx->bits_per_raw_sample == 14)
695             f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
696         else
697         if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
698         else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
699     } else {
700         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
701         return AVERROR(ENOSYS);
702     }
703
704     av_dlog(f->avctx, "%d %d %d\n",
705             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
706     if (f->version < 2) {
707         context_count = read_quant_tables(c, f->quant_table);
708         if (context_count < 0) {
709             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
710             return AVERROR_INVALIDDATA;
711         }
712     } else if (f->version < 3) {
713         f->slice_count = get_symbol(c, state, 0);
714     } else {
715         const uint8_t *p = c->bytestream_end;
716         for (f->slice_count = 0;
717              f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
718              f->slice_count++) {
719             int trailer = 3 + 5*!!f->ec;
720             int size = AV_RB24(p-trailer);
721             if (size + trailer > p - c->bytestream_start)
722                 break;
723             p -= size + trailer;
724         }
725     }
726     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
727         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
728         return AVERROR_INVALIDDATA;
729     }
730
731     for (j = 0; j < f->slice_count; j++) {
732         FFV1Context *fs = f->slice_context[j];
733         fs->ac            = f->ac;
734         fs->packed_at_lsb = f->packed_at_lsb;
735
736         fs->slice_damaged = 0;
737
738         if (f->version == 2) {
739             fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
740             fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
741             fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
742             fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
743
744             fs->slice_x     /= f->num_h_slices;
745             fs->slice_y     /= f->num_v_slices;
746             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
747             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
748             if ((unsigned)fs->slice_width  > f->width ||
749                 (unsigned)fs->slice_height > f->height)
750                 return AVERROR_INVALIDDATA;
751             if (   (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
752                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
753                 return AVERROR_INVALIDDATA;
754         }
755
756         for (i = 0; i < f->plane_count; i++) {
757             PlaneContext *const p = &fs->plane[i];
758
759             if (f->version == 2) {
760                 int idx = get_symbol(c, state, 0);
761                 if (idx > (unsigned)f->quant_table_count) {
762                     av_log(f->avctx, AV_LOG_ERROR,
763                            "quant_table_index out of range\n");
764                     return AVERROR_INVALIDDATA;
765                 }
766                 p->quant_table_index = idx;
767                 memcpy(p->quant_table, f->quant_tables[idx],
768                        sizeof(p->quant_table));
769                 context_count = f->context_count[idx];
770             } else {
771                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
772             }
773
774             if (f->version <= 2) {
775                 av_assert0(context_count >= 0);
776                 if (p->context_count < context_count) {
777                     av_freep(&p->state);
778                     av_freep(&p->vlc_state);
779                 }
780                 p->context_count = context_count;
781             }
782         }
783     }
784     return 0;
785 }
786
787 static av_cold int decode_init(AVCodecContext *avctx)
788 {
789     FFV1Context *f = avctx->priv_data;
790     int ret;
791
792     if ((ret = ffv1_common_init(avctx)) < 0)
793         return ret;
794
795     if (avctx->extradata && (ret = read_extra_header(f)) < 0)
796         return ret;
797
798     if ((ret = ffv1_init_slice_contexts(f)) < 0)
799         return ret;
800
801     avctx->internal->allocate_progress = 1;
802
803     return 0;
804 }
805
806 static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
807 {
808     const uint8_t *buf  = avpkt->data;
809     int buf_size        = avpkt->size;
810     FFV1Context *f      = avctx->priv_data;
811     RangeCoder *const c = &f->slice_context[0]->c;
812     int i, ret;
813     uint8_t keystate = 128;
814     const uint8_t *buf_p;
815     AVFrame *p;
816
817     if (f->last_picture.f)
818         ff_thread_release_buffer(avctx, &f->last_picture);
819     FFSWAP(ThreadFrame, f->picture, f->last_picture);
820
821     f->cur = p = f->picture.f;
822
823     if (f->version < 3 && avctx->field_order > AV_FIELD_PROGRESSIVE) {
824         /* we have interlaced material flagged in container */
825         p->interlaced_frame = 1;
826         if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB)
827             p->top_field_first = 1;
828     }
829
830     f->avctx = avctx;
831     ff_init_range_decoder(c, buf, buf_size);
832     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
833
834     p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
835     if (get_rac(c, &keystate)) {
836         p->key_frame    = 1;
837         f->key_frame_ok = 0;
838         if ((ret = read_header(f)) < 0)
839             return ret;
840         f->key_frame_ok = 1;
841     } else {
842         if (!f->key_frame_ok) {
843             av_log(avctx, AV_LOG_ERROR,
844                    "Cannot decode non-keyframe without valid keyframe\n");
845             return AVERROR_INVALIDDATA;
846         }
847         p->key_frame = 0;
848     }
849
850     if ((ret = ff_thread_get_buffer(avctx, &f->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
851         return ret;
852
853     if (avctx->debug & FF_DEBUG_PICT_INFO)
854         av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
855                f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
856
857     ff_thread_finish_setup(avctx);
858
859     buf_p = buf + buf_size;
860     for (i = f->slice_count - 1; i >= 0; i--) {
861         FFV1Context *fs = f->slice_context[i];
862         int trailer = 3 + 5*!!f->ec;
863         int v;
864
865         if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
866         else                     v = buf_p - c->bytestream_start;
867         if (buf_p - c->bytestream_start < v) {
868             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
869             return AVERROR_INVALIDDATA;
870         }
871         buf_p -= v;
872
873         if (f->ec) {
874             unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
875             if (crc) {
876                 int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
877                 av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
878                 if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
879                     av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
880                 } else if (ts != AV_NOPTS_VALUE) {
881                     av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
882                 } else {
883                     av_log(f->avctx, AV_LOG_ERROR, "\n");
884                 }
885                 fs->slice_damaged = 1;
886             }
887         }
888
889         if (i) {
890             ff_init_range_decoder(&fs->c, buf_p, v);
891         } else
892             fs->c.bytestream_end = (uint8_t *)(buf_p + v);
893
894         fs->avctx = avctx;
895         fs->cur = p;
896     }
897
898     avctx->execute(avctx,
899                    decode_slice,
900                    &f->slice_context[0],
901                    NULL,
902                    f->slice_count,
903                    sizeof(void*));
904
905     for (i = f->slice_count - 1; i >= 0; i--) {
906         FFV1Context *fs = f->slice_context[i];
907         int j;
908         if (fs->slice_damaged && f->last_picture.f->data[0]) {
909             const uint8_t *src[4];
910             uint8_t *dst[4];
911             ff_thread_await_progress(&f->last_picture, INT_MAX, 0);
912             for (j = 0; j < 4; j++) {
913                 int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
914                 int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
915                 dst[j] = p->data[j] + p->linesize[j]*
916                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
917                 src[j] = f->last_picture.f->data[j] + f->last_picture.f->linesize[j]*
918                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
919             }
920             av_image_copy(dst, p->linesize, (const uint8_t **)src,
921                           f->last_picture.f->linesize,
922                           avctx->pix_fmt,
923                           fs->slice_width,
924                           fs->slice_height);
925         }
926     }
927     ff_thread_report_progress(&f->picture, INT_MAX, 0);
928
929     f->picture_number++;
930
931     if (f->last_picture.f)
932         ff_thread_release_buffer(avctx, &f->last_picture);
933     f->cur = NULL;
934     if ((ret = av_frame_ref(data, f->picture.f)) < 0)
935         return ret;
936
937     *got_frame = 1;
938
939     return buf_size;
940 }
941
942 static int init_thread_copy(AVCodecContext *avctx)
943 {
944     FFV1Context *f = avctx->priv_data;
945
946     f->picture.f      = NULL;
947     f->last_picture.f = NULL;
948     f->sample_buffer  = NULL;
949     f->quant_table_count = 0;
950     f->slice_count = 0;
951
952     return 0;
953 }
954
955 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
956 {
957     FFV1Context *fsrc = src->priv_data;
958     FFV1Context *fdst = dst->priv_data;
959     int i, ret;
960
961     if (dst == src)
962         return 0;
963
964     if (!fdst->picture.f) {
965         memcpy(fdst, fsrc, sizeof(*fdst));
966
967         for (i = 0; i < fdst->quant_table_count; i++) {
968             fdst->initial_states[i] = av_malloc(fdst->context_count[i] * sizeof(*fdst->initial_states[i]));
969             memcpy(fdst->initial_states[i], fsrc->initial_states[i], fdst->context_count[i] * sizeof(*fdst->initial_states[i]));
970         }
971
972         fdst->picture.f      = av_frame_alloc();
973         fdst->last_picture.f = av_frame_alloc();
974
975         if ((ret = ffv1_init_slice_contexts(fdst)) < 0)
976             return ret;
977     }
978
979     av_assert1(fdst->slice_count == fsrc->slice_count);
980
981     fdst->key_frame_ok = fsrc->key_frame_ok;
982
983     ff_thread_release_buffer(dst, &fdst->picture);
984     if (fsrc->picture.f->data[0]) {
985         if ((ret = ff_thread_ref_frame(&fdst->picture, &fsrc->picture)) < 0)
986             return ret;
987     }
988     for (i = 0; i < fdst->slice_count; i++) {
989         FFV1Context *fsdst = fdst->slice_context[i];
990         FFV1Context *fssrc = fsrc->slice_context[i];
991
992         fsdst->slice_damaged = fssrc->slice_damaged;
993     }
994
995     fdst->fsrc = fsrc;
996
997     return 0;
998 }
999
1000 AVCodec ff_ffv1_decoder = {
1001     .name           = "ffv1",
1002     .type           = AVMEDIA_TYPE_VIDEO,
1003     .id             = AV_CODEC_ID_FFV1,
1004     .priv_data_size = sizeof(FFV1Context),
1005     .init           = decode_init,
1006     .close          = ffv1_close,
1007     .decode         = decode_frame,
1008     .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
1009     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1010     .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
1011                       CODEC_CAP_FRAME_THREADS | CODEC_CAP_SLICE_THREADS,
1012     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
1013 };