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