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