]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1dec.c
Merge commit '29b00f880faa404aa1d0d6820310c510c5996479'
[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     ff_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     if (s->slice_coding_mode == 1) {
109         int i;
110         for (x = 0; x < w; x++) {
111             int v = 0;
112             for (i=0; i<bits; i++) {
113                 uint8_t state = 128;
114                 v += v + get_rac(c, &state);
115             }
116             sample[1][x] = v;
117         }
118         return;
119     }
120
121     for (x = 0; x < w; x++) {
122         int diff, context, sign;
123
124         context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
125         if (context < 0) {
126             context = -context;
127             sign    = 1;
128         } else
129             sign = 0;
130
131         av_assert2(context < p->context_count);
132
133         if (s->ac) {
134             diff = get_symbol_inline(c, p->state[context], 1);
135         } else {
136             if (context == 0 && run_mode == 0)
137                 run_mode = 1;
138
139             if (run_mode) {
140                 if (run_count == 0 && run_mode == 1) {
141                     if (get_bits1(&s->gb)) {
142                         run_count = 1 << ff_log2_run[run_index];
143                         if (x + run_count <= w)
144                             run_index++;
145                     } else {
146                         if (ff_log2_run[run_index])
147                             run_count = get_bits(&s->gb, ff_log2_run[run_index]);
148                         else
149                             run_count = 0;
150                         if (run_index)
151                             run_index--;
152                         run_mode = 2;
153                     }
154                 }
155                 run_count--;
156                 if (run_count < 0) {
157                     run_mode  = 0;
158                     run_count = 0;
159                     diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],
160                                                bits);
161                     if (diff >= 0)
162                         diff++;
163                 } else
164                     diff = 0;
165             } else
166                 diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
167
168             ff_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
169                     run_count, run_index, run_mode, x, get_bits_count(&s->gb));
170         }
171
172         if (sign)
173             diff = -diff;
174
175         sample[1][x] = av_mod_uintp2(predict(sample[1] + x, sample[0] + x) + diff, bits);
176     }
177     s->run_index = run_index;
178 }
179
180 static void decode_plane(FFV1Context *s, uint8_t *src,
181                          int w, int h, int stride, int plane_index)
182 {
183     int x, y;
184     int16_t *sample[2];
185     sample[0] = s->sample_buffer + 3;
186     sample[1] = s->sample_buffer + w + 6 + 3;
187
188     s->run_index = 0;
189
190     memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
191
192     for (y = 0; y < h; y++) {
193         int16_t *temp = sample[0]; // FIXME: try a normal buffer
194
195         sample[0] = sample[1];
196         sample[1] = temp;
197
198         sample[1][-1] = sample[0][0];
199         sample[0][w]  = sample[0][w - 1];
200
201 // { START_TIMER
202         if (s->avctx->bits_per_raw_sample <= 8) {
203             decode_line(s, w, sample, plane_index, 8);
204             for (x = 0; x < w; x++)
205                 src[x + stride * y] = sample[1][x];
206         } else {
207             decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
208             if (s->packed_at_lsb) {
209                 for (x = 0; x < w; x++) {
210                     ((uint16_t*)(src + stride*y))[x] = sample[1][x];
211                 }
212             } else {
213                 for (x = 0; x < w; x++) {
214                     ((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
215                 }
216             }
217         }
218 // STOP_TIMER("decode-line") }
219     }
220 }
221
222 static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
223 {
224     int x, y, p;
225     int16_t *sample[4][2];
226     int lbd    = s->avctx->bits_per_raw_sample <= 8;
227     int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
228     int offset = 1 << bits;
229
230     for (x = 0; x < 4; x++) {
231         sample[x][0] = s->sample_buffer +  x * 2      * (w + 6) + 3;
232         sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
233     }
234
235     s->run_index = 0;
236
237     memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));
238
239     for (y = 0; y < h; y++) {
240         for (p = 0; p < 3 + s->transparency; p++) {
241             int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
242
243             sample[p][0] = sample[p][1];
244             sample[p][1] = temp;
245
246             sample[p][1][-1]= sample[p][0][0  ];
247             sample[p][0][ w]= sample[p][0][w-1];
248             if (lbd && s->slice_coding_mode == 0)
249                 decode_line(s, w, sample[p], (p + 1)/2, 9);
250             else
251                 decode_line(s, w, sample[p], (p + 1)/2, bits + (s->slice_coding_mode != 1));
252         }
253         for (x = 0; x < w; x++) {
254             int g = sample[0][1][x];
255             int b = sample[1][1][x];
256             int r = sample[2][1][x];
257             int a = sample[3][1][x];
258
259             if (s->slice_coding_mode != 1) {
260                 b -= offset;
261                 r -= offset;
262                 g -= (b * s->slice_rct_by_coef + r * s->slice_rct_ry_coef) >> 2;
263                 b += g;
264                 r += g;
265             }
266
267             if (lbd)
268                 *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
269             else {
270                 *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
271                 *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
272                 *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
273             }
274         }
275     }
276 }
277
278 static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
279 {
280     RangeCoder *c = &fs->c;
281     uint8_t state[CONTEXT_SIZE];
282     unsigned ps, i, context_count;
283     memset(state, 128, sizeof(state));
284
285     av_assert0(f->version > 2);
286
287     fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
288     fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
289     fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
290     fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
291
292     fs->slice_x /= f->num_h_slices;
293     fs->slice_y /= f->num_v_slices;
294     fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;
295     fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
296     if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
297         return -1;
298     if (    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
299          || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
300         return -1;
301
302     for (i = 0; i < f->plane_count; i++) {
303         PlaneContext * const p = &fs->plane[i];
304         int idx = get_symbol(c, state, 0);
305         if (idx > (unsigned)f->quant_table_count) {
306             av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
307             return -1;
308         }
309         p->quant_table_index = idx;
310         memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
311         context_count = f->context_count[idx];
312
313         if (p->context_count < context_count) {
314             av_freep(&p->state);
315             av_freep(&p->vlc_state);
316         }
317         p->context_count = context_count;
318     }
319
320     ps = get_symbol(c, state, 0);
321     if (ps == 1) {
322         f->cur->interlaced_frame = 1;
323         f->cur->top_field_first  = 1;
324     } else if (ps == 2) {
325         f->cur->interlaced_frame = 1;
326         f->cur->top_field_first  = 0;
327     } else if (ps == 3) {
328         f->cur->interlaced_frame = 0;
329     }
330     f->cur->sample_aspect_ratio.num = get_symbol(c, state, 0);
331     f->cur->sample_aspect_ratio.den = get_symbol(c, state, 0);
332
333     if (av_image_check_sar(f->width, f->height,
334                            f->cur->sample_aspect_ratio) < 0) {
335         av_log(f->avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
336                f->cur->sample_aspect_ratio.num,
337                f->cur->sample_aspect_ratio.den);
338         f->cur->sample_aspect_ratio = (AVRational){ 0, 1 };
339     }
340
341     if (fs->version > 3) {
342         fs->slice_reset_contexts = get_rac(c, state);
343         fs->slice_coding_mode = get_symbol(c, state, 0);
344         if (fs->slice_coding_mode != 1) {
345             fs->slice_rct_by_coef = get_symbol(c, state, 0);
346             fs->slice_rct_ry_coef = get_symbol(c, state, 0);
347             if ((uint64_t)fs->slice_rct_by_coef + (uint64_t)fs->slice_rct_ry_coef > 4) {
348                 av_log(f->avctx, AV_LOG_ERROR, "slice_rct_y_coef out of range\n");
349                 return AVERROR_INVALIDDATA;
350             }
351         }
352     }
353
354     return 0;
355 }
356
357 static int decode_slice(AVCodecContext *c, void *arg)
358 {
359     FFV1Context *fs   = *(void **)arg;
360     FFV1Context *f    = fs->avctx->priv_data;
361     int width, height, x, y, ret;
362     const int ps      = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step;
363     AVFrame * const p = f->cur;
364     int i, si;
365
366     for( si=0; fs != f->slice_context[si]; si ++)
367         ;
368
369     if(f->fsrc && !p->key_frame)
370         ff_thread_await_progress(&f->last_picture, si, 0);
371
372     if(f->fsrc && !p->key_frame) {
373         FFV1Context *fssrc = f->fsrc->slice_context[si];
374         FFV1Context *fsdst = f->slice_context[si];
375         av_assert1(fsdst->plane_count == fssrc->plane_count);
376         av_assert1(fsdst == fs);
377
378         if (!p->key_frame)
379             fsdst->slice_damaged |= fssrc->slice_damaged;
380
381         for (i = 0; i < f->plane_count; i++) {
382             PlaneContext *psrc = &fssrc->plane[i];
383             PlaneContext *pdst = &fsdst->plane[i];
384
385             av_free(pdst->state);
386             av_free(pdst->vlc_state);
387             memcpy(pdst, psrc, sizeof(*pdst));
388             pdst->state = NULL;
389             pdst->vlc_state = NULL;
390
391             if (fssrc->ac) {
392                 pdst->state = av_malloc_array(CONTEXT_SIZE,  psrc->context_count);
393                 memcpy(pdst->state, psrc->state, CONTEXT_SIZE * psrc->context_count);
394             } else {
395                 pdst->vlc_state = av_malloc_array(sizeof(*pdst->vlc_state), psrc->context_count);
396                 memcpy(pdst->vlc_state, psrc->vlc_state, sizeof(*pdst->vlc_state) * psrc->context_count);
397             }
398         }
399     }
400
401     fs->slice_rct_by_coef = 1;
402     fs->slice_rct_ry_coef = 1;
403
404     if (f->version > 2) {
405         if (ff_ffv1_init_slice_state(f, fs) < 0)
406             return AVERROR(ENOMEM);
407         if (decode_slice_header(f, fs) < 0) {
408             fs->slice_damaged = 1;
409             return AVERROR_INVALIDDATA;
410         }
411     }
412     if ((ret = ff_ffv1_init_slice_state(f, fs)) < 0)
413         return ret;
414     if (f->cur->key_frame || fs->slice_reset_contexts)
415         ff_ffv1_clear_slice_state(f, fs);
416
417     width  = fs->slice_width;
418     height = fs->slice_height;
419     x      = fs->slice_x;
420     y      = fs->slice_y;
421
422     if (!fs->ac) {
423         if (f->version == 3 && f->micro_version > 1 || f->version > 3)
424             get_rac(&fs->c, (uint8_t[]) { 129 });
425         fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
426         init_get_bits(&fs->gb,
427                       fs->c.bytestream_start + fs->ac_byte_count,
428                       (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
429     }
430
431     av_assert1(width && height);
432     if (f->colorspace == 0) {
433         const int chroma_width  = FF_CEIL_RSHIFT(width,  f->chroma_h_shift);
434         const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift);
435         const int cx            = x >> f->chroma_h_shift;
436         const int cy            = y >> f->chroma_v_shift;
437         decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
438
439         if (f->chroma_planes) {
440             decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
441             decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
442         }
443         if (fs->transparency)
444             decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], (f->version >= 4 && !f->chroma_planes) ? 1 : 2);
445     } else {
446         uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
447                                p->data[1] + ps * x + y * p->linesize[1],
448                                p->data[2] + ps * x + y * p->linesize[2] };
449         decode_rgb_frame(fs, planes, width, height, p->linesize);
450     }
451     if (fs->ac && f->version > 2) {
452         int v;
453         get_rac(&fs->c, (uint8_t[]) { 129 });
454         v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
455         if (v) {
456             av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
457             fs->slice_damaged = 1;
458         }
459     }
460
461     emms_c();
462
463     ff_thread_report_progress(&f->picture, si, 0);
464
465     return 0;
466 }
467
468 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
469 {
470     int v;
471     int i = 0;
472     uint8_t state[CONTEXT_SIZE];
473
474     memset(state, 128, sizeof(state));
475
476     for (v = 0; i < 128; v++) {
477         unsigned len = get_symbol(c, state, 0) + 1;
478
479         if (len > 128 - i || !len)
480             return AVERROR_INVALIDDATA;
481
482         while (len--) {
483             quant_table[i] = scale * v;
484             i++;
485         }
486     }
487
488     for (i = 1; i < 128; i++)
489         quant_table[256 - i] = -quant_table[i];
490     quant_table[128] = -quant_table[127];
491
492     return 2 * v - 1;
493 }
494
495 static int read_quant_tables(RangeCoder *c,
496                              int16_t quant_table[MAX_CONTEXT_INPUTS][256])
497 {
498     int i;
499     int context_count = 1;
500
501     for (i = 0; i < 5; i++) {
502         context_count *= read_quant_table(c, quant_table[i], context_count);
503         if (context_count > 32768U) {
504             return AVERROR_INVALIDDATA;
505         }
506     }
507     return (context_count + 1) / 2;
508 }
509
510 static int read_extra_header(FFV1Context *f)
511 {
512     RangeCoder *const c = &f->c;
513     uint8_t state[CONTEXT_SIZE];
514     int i, j, k, ret;
515     uint8_t state2[32][CONTEXT_SIZE];
516     unsigned crc = 0;
517
518     memset(state2, 128, sizeof(state2));
519     memset(state, 128, sizeof(state));
520
521     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
522     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
523
524     f->version = get_symbol(c, state, 0);
525     if (f->version < 2) {
526         av_log(f->avctx, AV_LOG_ERROR, "Invalid version in global header\n");
527         return AVERROR_INVALIDDATA;
528     }
529     if (f->version > 2) {
530         c->bytestream_end -= 4;
531         f->micro_version = get_symbol(c, state, 0);
532         if (f->micro_version < 0)
533             return AVERROR_INVALIDDATA;
534     }
535     f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
536     if (f->ac > 1) {
537         for (i = 1; i < 256; i++)
538             f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
539     }
540
541     f->colorspace                 = get_symbol(c, state, 0); //YUV cs type
542     f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
543     f->chroma_planes              = get_rac(c, state);
544     f->chroma_h_shift             = get_symbol(c, state, 0);
545     f->chroma_v_shift             = get_symbol(c, state, 0);
546     f->transparency               = get_rac(c, state);
547     f->plane_count                = 1 + (f->chroma_planes || f->version<4) + f->transparency;
548     f->num_h_slices               = 1 + get_symbol(c, state, 0);
549     f->num_v_slices               = 1 + get_symbol(c, state, 0);
550
551     if (f->chroma_h_shift > 4U || f->chroma_v_shift > 4U) {
552         av_log(f->avctx, AV_LOG_ERROR, "chroma shift parameters %d %d are invalid\n",
553                f->chroma_h_shift, f->chroma_v_shift);
554         return AVERROR_INVALIDDATA;
555     }
556
557     if (f->num_h_slices > (unsigned)f->width  || !f->num_h_slices ||
558         f->num_v_slices > (unsigned)f->height || !f->num_v_slices
559        ) {
560         av_log(f->avctx, AV_LOG_ERROR, "slice count invalid\n");
561         return AVERROR_INVALIDDATA;
562     }
563
564     f->quant_table_count = get_symbol(c, state, 0);
565     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
566         return AVERROR_INVALIDDATA;
567
568     for (i = 0; i < f->quant_table_count; i++) {
569         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
570         if (f->context_count[i] < 0) {
571             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
572             return AVERROR_INVALIDDATA;
573         }
574     }
575     if ((ret = ff_ffv1_allocate_initial_states(f)) < 0)
576         return ret;
577
578     for (i = 0; i < f->quant_table_count; i++)
579         if (get_rac(c, state)) {
580             for (j = 0; j < f->context_count[i]; j++)
581                 for (k = 0; k < CONTEXT_SIZE; k++) {
582                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
583                     f->initial_states[i][j][k] =
584                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
585                 }
586         }
587
588     if (f->version > 2) {
589         f->ec = get_symbol(c, state, 0);
590         if (f->micro_version > 2)
591             f->intra = get_symbol(c, state, 0);
592     }
593
594     if (f->version > 2) {
595         unsigned v;
596         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
597                    f->avctx->extradata, f->avctx->extradata_size);
598         if (v || f->avctx->extradata_size < 4) {
599             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
600             return AVERROR_INVALIDDATA;
601         }
602         crc = AV_RB32(f->avctx->extradata + f->avctx->extradata_size - 4);
603     }
604
605     if (f->avctx->debug & FF_DEBUG_PICT_INFO)
606         av_log(f->avctx, AV_LOG_DEBUG,
607                "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 CRC:0x%08X\n",
608                f->version, f->micro_version,
609                f->ac,
610                f->colorspace,
611                f->avctx->bits_per_raw_sample,
612                f->chroma_planes, f->chroma_h_shift, f->chroma_v_shift,
613                f->transparency,
614                f->num_h_slices, f->num_v_slices,
615                f->quant_table_count,
616                f->ec,
617                f->intra,
618                crc
619               );
620     return 0;
621 }
622
623 static int read_header(FFV1Context *f)
624 {
625     uint8_t state[CONTEXT_SIZE];
626     int i, j, context_count = -1; //-1 to avoid warning
627     RangeCoder *const c = &f->slice_context[0]->c;
628
629     memset(state, 128, sizeof(state));
630
631     if (f->version < 2) {
632         int chroma_planes, chroma_h_shift, chroma_v_shift, transparency, colorspace, bits_per_raw_sample;
633         unsigned v= get_symbol(c, state, 0);
634         if (v >= 2) {
635             av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
636             return AVERROR_INVALIDDATA;
637         }
638         f->version = v;
639         f->ac      = f->avctx->coder_type = get_symbol(c, state, 0);
640         if (f->ac > 1) {
641             for (i = 1; i < 256; i++)
642                 f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
643         }
644
645         colorspace          = get_symbol(c, state, 0); //YUV cs type
646         bits_per_raw_sample = f->version > 0 ? get_symbol(c, state, 0) : f->avctx->bits_per_raw_sample;
647         chroma_planes       = get_rac(c, state);
648         chroma_h_shift      = get_symbol(c, state, 0);
649         chroma_v_shift      = get_symbol(c, state, 0);
650         transparency        = get_rac(c, state);
651         if (colorspace == 0 && f->avctx->skip_alpha)
652             transparency = 0;
653
654         if (f->plane_count) {
655             if (colorspace          != f->colorspace                 ||
656                 bits_per_raw_sample != f->avctx->bits_per_raw_sample ||
657                 chroma_planes       != f->chroma_planes              ||
658                 chroma_h_shift      != f->chroma_h_shift             ||
659                 chroma_v_shift      != f->chroma_v_shift             ||
660                 transparency        != f->transparency) {
661                 av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n");
662                 return AVERROR_INVALIDDATA;
663             }
664         }
665
666         if (chroma_h_shift > 4U || chroma_v_shift > 4U) {
667             av_log(f->avctx, AV_LOG_ERROR, "chroma shift parameters %d %d are invalid\n",
668                    chroma_h_shift, chroma_v_shift);
669             return AVERROR_INVALIDDATA;
670         }
671
672         f->colorspace                 = colorspace;
673         f->avctx->bits_per_raw_sample = bits_per_raw_sample;
674         f->chroma_planes              = chroma_planes;
675         f->chroma_h_shift             = chroma_h_shift;
676         f->chroma_v_shift             = chroma_v_shift;
677         f->transparency               = transparency;
678
679         f->plane_count    = 2 + f->transparency;
680     }
681
682     if (f->colorspace == 0) {
683         if (!f->transparency && !f->chroma_planes) {
684             if (f->avctx->bits_per_raw_sample <= 8)
685                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
686             else
687                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
688         } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
689             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
690             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
691             case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
692             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
693             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
694             case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
695             case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
696             }
697         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
698             switch(16*f->chroma_h_shift + f->chroma_v_shift) {
699             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
700             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
701             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
702             }
703         } else if (f->avctx->bits_per_raw_sample == 9 && !f->transparency) {
704             f->packed_at_lsb = 1;
705             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
706             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
707             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
708             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
709             }
710         } else if (f->avctx->bits_per_raw_sample == 9 && f->transparency) {
711             f->packed_at_lsb = 1;
712             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
713             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P9; break;
714             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P9; break;
715             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P9; break;
716             }
717         } else if (f->avctx->bits_per_raw_sample == 10 && !f->transparency) {
718             f->packed_at_lsb = 1;
719             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
720             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
721             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
722             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
723             }
724         } else if (f->avctx->bits_per_raw_sample == 10 && f->transparency) {
725             f->packed_at_lsb = 1;
726             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
727             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P10; break;
728             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P10; break;
729             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P10; break;
730             }
731         } else if (f->avctx->bits_per_raw_sample == 16 && !f->transparency){
732             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
733             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
734             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
735             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
736             }
737         } else if (f->avctx->bits_per_raw_sample == 16 && f->transparency){
738             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
739             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P16; break;
740             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P16; break;
741             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P16; break;
742             }
743         }
744     } else if (f->colorspace == 1) {
745         if (f->chroma_h_shift || f->chroma_v_shift) {
746             av_log(f->avctx, AV_LOG_ERROR,
747                    "chroma subsampling not supported in this colorspace\n");
748             return AVERROR(ENOSYS);
749         }
750         if (     f->avctx->bits_per_raw_sample ==  9)
751             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
752         else if (f->avctx->bits_per_raw_sample == 10)
753             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
754         else if (f->avctx->bits_per_raw_sample == 12)
755             f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
756         else if (f->avctx->bits_per_raw_sample == 14)
757             f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
758         else
759         if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
760         else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
761     } else {
762         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
763         return AVERROR(ENOSYS);
764     }
765     if (f->avctx->pix_fmt == AV_PIX_FMT_NONE) {
766         av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
767         return AVERROR(ENOSYS);
768     }
769
770     ff_dlog(f->avctx, "%d %d %d\n",
771             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
772     if (f->version < 2) {
773         context_count = read_quant_tables(c, f->quant_table);
774         if (context_count < 0) {
775             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
776             return AVERROR_INVALIDDATA;
777         }
778     } else if (f->version < 3) {
779         f->slice_count = get_symbol(c, state, 0);
780     } else {
781         const uint8_t *p = c->bytestream_end;
782         for (f->slice_count = 0;
783              f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start;
784              f->slice_count++) {
785             int trailer = 3 + 5*!!f->ec;
786             int size = AV_RB24(p-trailer);
787             if (size + trailer > p - c->bytestream_start)
788                 break;
789             p -= size + trailer;
790         }
791     }
792     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
793         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
794         return AVERROR_INVALIDDATA;
795     }
796
797     for (j = 0; j < f->slice_count; j++) {
798         FFV1Context *fs = f->slice_context[j];
799         fs->ac            = f->ac;
800         fs->packed_at_lsb = f->packed_at_lsb;
801
802         fs->slice_damaged = 0;
803
804         if (f->version == 2) {
805             fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
806             fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
807             fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
808             fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
809
810             fs->slice_x     /= f->num_h_slices;
811             fs->slice_y     /= f->num_v_slices;
812             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
813             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
814             if ((unsigned)fs->slice_width  > f->width ||
815                 (unsigned)fs->slice_height > f->height)
816                 return AVERROR_INVALIDDATA;
817             if (   (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
818                 || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
819                 return AVERROR_INVALIDDATA;
820         }
821
822         for (i = 0; i < f->plane_count; i++) {
823             PlaneContext *const p = &fs->plane[i];
824
825             if (f->version == 2) {
826                 int idx = get_symbol(c, state, 0);
827                 if (idx > (unsigned)f->quant_table_count) {
828                     av_log(f->avctx, AV_LOG_ERROR,
829                            "quant_table_index out of range\n");
830                     return AVERROR_INVALIDDATA;
831                 }
832                 p->quant_table_index = idx;
833                 memcpy(p->quant_table, f->quant_tables[idx],
834                        sizeof(p->quant_table));
835                 context_count = f->context_count[idx];
836             } else {
837                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
838             }
839
840             if (f->version <= 2) {
841                 av_assert0(context_count >= 0);
842                 if (p->context_count < context_count) {
843                     av_freep(&p->state);
844                     av_freep(&p->vlc_state);
845                 }
846                 p->context_count = context_count;
847             }
848         }
849     }
850     return 0;
851 }
852
853 static av_cold int decode_init(AVCodecContext *avctx)
854 {
855     FFV1Context *f = avctx->priv_data;
856     int ret;
857
858     if ((ret = ff_ffv1_common_init(avctx)) < 0)
859         return ret;
860
861     if (avctx->extradata && (ret = read_extra_header(f)) < 0)
862         return ret;
863
864     if ((ret = ff_ffv1_init_slice_contexts(f)) < 0)
865         return ret;
866
867     avctx->internal->allocate_progress = 1;
868
869     return 0;
870 }
871
872 static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
873 {
874     uint8_t *buf        = avpkt->data;
875     int buf_size        = avpkt->size;
876     FFV1Context *f      = avctx->priv_data;
877     RangeCoder *const c = &f->slice_context[0]->c;
878     int i, ret;
879     uint8_t keystate = 128;
880     uint8_t *buf_p;
881     AVFrame *p;
882
883     if (f->last_picture.f)
884         ff_thread_release_buffer(avctx, &f->last_picture);
885     FFSWAP(ThreadFrame, f->picture, f->last_picture);
886
887     f->cur = p = f->picture.f;
888
889     if (f->version < 3 && avctx->field_order > AV_FIELD_PROGRESSIVE) {
890         /* we have interlaced material flagged in container */
891         p->interlaced_frame = 1;
892         if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB)
893             p->top_field_first = 1;
894     }
895
896     f->avctx = avctx;
897     ff_init_range_decoder(c, buf, buf_size);
898     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
899
900     p->pict_type = AV_PICTURE_TYPE_I; //FIXME I vs. P
901     if (get_rac(c, &keystate)) {
902         p->key_frame    = 1;
903         f->key_frame_ok = 0;
904         if ((ret = read_header(f)) < 0)
905             return ret;
906         f->key_frame_ok = 1;
907     } else {
908         if (!f->key_frame_ok) {
909             av_log(avctx, AV_LOG_ERROR,
910                    "Cannot decode non-keyframe without valid keyframe\n");
911             return AVERROR_INVALIDDATA;
912         }
913         p->key_frame = 0;
914     }
915
916     if ((ret = ff_thread_get_buffer(avctx, &f->picture, AV_GET_BUFFER_FLAG_REF)) < 0)
917         return ret;
918
919     if (avctx->debug & FF_DEBUG_PICT_INFO)
920         av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
921                f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
922
923     ff_thread_finish_setup(avctx);
924
925     buf_p = buf + buf_size;
926     for (i = f->slice_count - 1; i >= 0; i--) {
927         FFV1Context *fs = f->slice_context[i];
928         int trailer = 3 + 5*!!f->ec;
929         int v;
930
931         if (i || f->version > 2) v = AV_RB24(buf_p-trailer) + trailer;
932         else                     v = buf_p - c->bytestream_start;
933         if (buf_p - c->bytestream_start < v) {
934             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
935             return AVERROR_INVALIDDATA;
936         }
937         buf_p -= v;
938
939         if (f->ec) {
940             unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
941             if (crc) {
942                 int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
943                 av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
944                 if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
945                     av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
946                 } else if (ts != AV_NOPTS_VALUE) {
947                     av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
948                 } else {
949                     av_log(f->avctx, AV_LOG_ERROR, "\n");
950                 }
951                 fs->slice_damaged = 1;
952             }
953             if (avctx->debug & FF_DEBUG_PICT_INFO) {
954                 av_log(avctx, AV_LOG_DEBUG, "slice %d, CRC: 0x%08X\n", i, AV_RB32(buf_p + v - 4));
955             }
956         }
957
958         if (i) {
959             ff_init_range_decoder(&fs->c, buf_p, v);
960         } else
961             fs->c.bytestream_end = buf_p + v;
962
963         fs->avctx = avctx;
964         fs->cur = p;
965     }
966
967     avctx->execute(avctx,
968                    decode_slice,
969                    &f->slice_context[0],
970                    NULL,
971                    f->slice_count,
972                    sizeof(void*));
973
974     for (i = f->slice_count - 1; i >= 0; i--) {
975         FFV1Context *fs = f->slice_context[i];
976         int j;
977         if (fs->slice_damaged && f->last_picture.f->data[0]) {
978             const uint8_t *src[4];
979             uint8_t *dst[4];
980             ff_thread_await_progress(&f->last_picture, INT_MAX, 0);
981             for (j = 0; j < 4; j++) {
982                 int sh = (j == 1 || j == 2) ? f->chroma_h_shift : 0;
983                 int sv = (j == 1 || j == 2) ? f->chroma_v_shift : 0;
984                 dst[j] = p->data[j] + p->linesize[j] *
985                          (fs->slice_y >> sv) + (fs->slice_x >> sh);
986                 src[j] = f->last_picture.f->data[j] + f->last_picture.f->linesize[j] *
987                          (fs->slice_y >> sv) + (fs->slice_x >> sh);
988             }
989             av_image_copy(dst, p->linesize, src,
990                           f->last_picture.f->linesize,
991                           avctx->pix_fmt,
992                           fs->slice_width,
993                           fs->slice_height);
994         }
995     }
996     ff_thread_report_progress(&f->picture, INT_MAX, 0);
997
998     f->picture_number++;
999
1000     if (f->last_picture.f)
1001         ff_thread_release_buffer(avctx, &f->last_picture);
1002     f->cur = NULL;
1003     if ((ret = av_frame_ref(data, f->picture.f)) < 0)
1004         return ret;
1005
1006     *got_frame = 1;
1007
1008     return buf_size;
1009 }
1010
1011 static int init_thread_copy(AVCodecContext *avctx)
1012 {
1013     FFV1Context *f = avctx->priv_data;
1014     int i, ret;
1015
1016     f->picture.f      = NULL;
1017     f->last_picture.f = NULL;
1018     f->sample_buffer  = NULL;
1019     f->slice_count = 0;
1020
1021     for (i = 0; i < f->quant_table_count; i++) {
1022         av_assert0(f->version > 1);
1023         f->initial_states[i] = av_memdup(f->initial_states[i],
1024                                          f->context_count[i] * sizeof(*f->initial_states[i]));
1025     }
1026
1027     f->picture.f      = av_frame_alloc();
1028     f->last_picture.f = av_frame_alloc();
1029
1030     if ((ret = ff_ffv1_init_slice_contexts(f)) < 0)
1031         return ret;
1032
1033     return 0;
1034 }
1035
1036 static void copy_fields(FFV1Context *fsdst, FFV1Context *fssrc, FFV1Context *fsrc)
1037 {
1038     fsdst->version             = fsrc->version;
1039     fsdst->micro_version       = fsrc->micro_version;
1040     fsdst->chroma_planes       = fsrc->chroma_planes;
1041     fsdst->chroma_h_shift      = fsrc->chroma_h_shift;
1042     fsdst->chroma_v_shift      = fsrc->chroma_v_shift;
1043     fsdst->transparency        = fsrc->transparency;
1044     fsdst->plane_count         = fsrc->plane_count;
1045     fsdst->ac                  = fsrc->ac;
1046     fsdst->colorspace          = fsrc->colorspace;
1047
1048     fsdst->ec                  = fsrc->ec;
1049     fsdst->intra               = fsrc->intra;
1050     fsdst->slice_damaged       = fssrc->slice_damaged;
1051     fsdst->key_frame_ok        = fsrc->key_frame_ok;
1052
1053     fsdst->bits_per_raw_sample = fsrc->bits_per_raw_sample;
1054     fsdst->packed_at_lsb       = fsrc->packed_at_lsb;
1055     fsdst->slice_count         = fsrc->slice_count;
1056     if (fsrc->version<3){
1057         fsdst->slice_x             = fssrc->slice_x;
1058         fsdst->slice_y             = fssrc->slice_y;
1059         fsdst->slice_width         = fssrc->slice_width;
1060         fsdst->slice_height        = fssrc->slice_height;
1061     }
1062 }
1063
1064 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1065 {
1066     FFV1Context *fsrc = src->priv_data;
1067     FFV1Context *fdst = dst->priv_data;
1068     int i, ret;
1069
1070     if (dst == src)
1071         return 0;
1072
1073     {
1074         ThreadFrame picture = fdst->picture, last_picture = fdst->last_picture;
1075         uint8_t (*initial_states[MAX_QUANT_TABLES])[32];
1076         struct FFV1Context *slice_context[MAX_SLICES];
1077         memcpy(initial_states, fdst->initial_states, sizeof(fdst->initial_states));
1078         memcpy(slice_context,  fdst->slice_context , sizeof(fdst->slice_context));
1079
1080         memcpy(fdst, fsrc, sizeof(*fdst));
1081         memcpy(fdst->initial_states, initial_states, sizeof(fdst->initial_states));
1082         memcpy(fdst->slice_context,  slice_context , sizeof(fdst->slice_context));
1083         fdst->picture      = picture;
1084         fdst->last_picture = last_picture;
1085         for (i = 0; i<fdst->num_h_slices * fdst->num_v_slices; i++) {
1086             FFV1Context *fssrc = fsrc->slice_context[i];
1087             FFV1Context *fsdst = fdst->slice_context[i];
1088             copy_fields(fsdst, fssrc, fsrc);
1089         }
1090         av_assert0(!fdst->plane[0].state);
1091         av_assert0(!fdst->sample_buffer);
1092     }
1093
1094     av_assert1(fdst->slice_count == fsrc->slice_count);
1095
1096
1097     ff_thread_release_buffer(dst, &fdst->picture);
1098     if (fsrc->picture.f->data[0]) {
1099         if ((ret = ff_thread_ref_frame(&fdst->picture, &fsrc->picture)) < 0)
1100             return ret;
1101     }
1102
1103     fdst->fsrc = fsrc;
1104
1105     return 0;
1106 }
1107
1108 AVCodec ff_ffv1_decoder = {
1109     .name           = "ffv1",
1110     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
1111     .type           = AVMEDIA_TYPE_VIDEO,
1112     .id             = AV_CODEC_ID_FFV1,
1113     .priv_data_size = sizeof(FFV1Context),
1114     .init           = decode_init,
1115     .close          = ff_ffv1_close,
1116     .decode         = decode_frame,
1117     .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
1118     .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1119     .capabilities   = AV_CODEC_CAP_DR1 /*| AV_CODEC_CAP_DRAW_HORIZ_BAND*/ |
1120                       AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_SLICE_THREADS,
1121 };