]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1.c
Merge commit '0bca0283ccded5e32da143a462168ad1988a58fd'
[ffmpeg] / libavcodec / ffv1.c
1 /*
2  * FFV1 codec for libavcodec
3  *
4  * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * FF Video Codec 1 (a lossless codec)
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/crc.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/timer.h"
34 #include "avcodec.h"
35 #include "internal.h"
36 #include "get_bits.h"
37 #include "put_bits.h"
38 #include "dsputil.h"
39 #include "rangecoder.h"
40 #include "golomb.h"
41 #include "mathops.h"
42
43 #ifdef __INTEL_COMPILER
44 #undef av_flatten
45 #define av_flatten
46 #endif
47
48 #define MAX_PLANES 4
49 #define CONTEXT_SIZE 32
50
51 #define MAX_QUANT_TABLES 8
52 #define MAX_CONTEXT_INPUTS 5
53
54 extern const uint8_t ff_log2_run[41];
55
56 static const int8_t quant5_10bit[256] = {
57      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,
58      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
59      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
60      1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
61      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
62      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
63      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
64      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
65     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
66     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
67     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
68     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
69     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1,
70     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
71     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
72     -1, -1, -1, -1, -1, -1, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0,
73 };
74
75 static const int8_t quant5[256] = {
76      0,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
77      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
78      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
79      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
80      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
81      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
82      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
83      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
84     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
85     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
86     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
87     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
88     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
89     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
90     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
91     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -1,
92 };
93
94 static const int8_t quant9_10bit[256] = {
95      0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,
96      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
97      3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
98      3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,  4,  4,
99      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
100      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
101      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
102      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
103     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
104     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
105     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
106     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
107     -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -3, -3, -3, -3, -3, -3,
108     -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3,
109     -3, -3, -3, -3, -3, -3, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
110     -2, -2, -2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -0, -0, -0, -0,
111 };
112
113 static const int8_t quant11[256] = {
114      0,  1,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,
115      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
116      4,  4,  4,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
117      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
118      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
119      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
120      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
121      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
122     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
123     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
124     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
125     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
126     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
127     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -4, -4,
128     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
129     -4, -4, -4, -4, -4, -3, -3, -3, -3, -3, -3, -3, -2, -2, -2, -1,
130 };
131
132 static const uint8_t ver2_state[256] = {
133       0,  10,  10,  10,  10,  16,  16,  16, 28,   16,  16,  29,  42,  49,  20,  49,
134      59,  25,  26,  26,  27,  31,  33,  33, 33,   34,  34,  37,  67,  38,  39,  39,
135      40,  40,  41,  79,  43,  44,  45,  45, 48,   48,  64,  50,  51,  52,  88,  52,
136      53,  74,  55,  57,  58,  58,  74,  60, 101,  61,  62,  84,  66,  66,  68,  69,
137      87,  82,  71,  97,  73,  73,  82,  75, 111,  77,  94,  78,  87,  81,  83,  97,
138      85,  83,  94,  86,  99,  89,  90,  99, 111,  92,  93,  134, 95,  98,  105, 98,
139     105, 110, 102, 108, 102, 118, 103, 106, 106, 113, 109, 112, 114, 112, 116, 125,
140     115, 116, 117, 117, 126, 119, 125, 121, 121, 123, 145, 124, 126, 131, 127, 129,
141     165, 130, 132, 138, 133, 135, 145, 136, 137, 139, 146, 141, 143, 142, 144, 148,
142     147, 155, 151, 149, 151, 150, 152, 157, 153, 154, 156, 168, 158, 162, 161, 160,
143     172, 163, 169, 164, 166, 184, 167, 170, 177, 174, 171, 173, 182, 176, 180, 178,
144     175, 189, 179, 181, 186, 183, 192, 185, 200, 187, 191, 188, 190, 197, 193, 196,
145     197, 194, 195, 196, 198, 202, 199, 201, 210, 203, 207, 204, 205, 206, 208, 214,
146     209, 211, 221, 212, 213, 215, 224, 216, 217, 218, 219, 220, 222, 228, 223, 225,
147     226, 224, 227, 229, 240, 230, 231, 232, 233, 234, 235, 236, 238, 239, 237, 242,
148     241, 243, 242, 244, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255,
149 };
150
151 typedef struct VlcState {
152     int16_t drift;
153     uint16_t error_sum;
154     int8_t bias;
155     uint8_t count;
156 } VlcState;
157
158 typedef struct PlaneContext {
159     int16_t quant_table[MAX_CONTEXT_INPUTS][256];
160     int quant_table_index;
161     int context_count;
162     uint8_t (*state)[CONTEXT_SIZE];
163     VlcState *vlc_state;
164     uint8_t interlace_bit_state[2];
165 } PlaneContext;
166
167 #define MAX_SLICES 256
168
169 typedef struct FFV1Context {
170     AVClass *class;
171     AVCodecContext *avctx;
172     RangeCoder c;
173     GetBitContext gb;
174     PutBitContext pb;
175     uint64_t rc_stat[256][2];
176     uint64_t (*rc_stat2[MAX_QUANT_TABLES])[32][2];
177     int version;
178     int minor_version;
179     int width, height;
180     int chroma_h_shift, chroma_v_shift;
181     int chroma_planes;
182     int transparency;
183     int flags;
184     int picture_number;
185     AVFrame picture;
186     AVFrame last_picture;
187     int plane_count;
188     int ac;                              ///< 1=range coder <-> 0=golomb rice
189     int ac_byte_count;                   ///< number of bytes used for AC coding
190     PlaneContext plane[MAX_PLANES];
191     int16_t quant_table[MAX_CONTEXT_INPUTS][256];
192     int16_t quant_tables[MAX_QUANT_TABLES][MAX_CONTEXT_INPUTS][256];
193     int context_count[MAX_QUANT_TABLES];
194     uint8_t state_transition[256];
195     uint8_t (*initial_states[MAX_QUANT_TABLES])[32];
196     int run_index;
197     int colorspace;
198     int16_t *sample_buffer;
199     int gob_count;
200     int packed_at_lsb;
201     int ec;
202     int slice_damaged;
203     int key_frame_ok;
204
205     int quant_table_count;
206
207     DSPContext dsp;
208
209     struct FFV1Context *slice_context[MAX_SLICES];
210     int slice_count;
211     int num_v_slices;
212     int num_h_slices;
213     int slice_width;
214     int slice_height;
215     int slice_x;
216     int slice_y;
217     int bits_per_raw_sample;
218 } FFV1Context;
219
220 static av_always_inline int fold(int diff, int bits)
221 {
222     if (bits == 8)
223         diff = (int8_t)diff;
224     else {
225         diff +=  1 << (bits  - 1);
226         diff &= (1 <<  bits) - 1;
227         diff -=  1 << (bits  - 1);
228     }
229
230     return diff;
231 }
232
233 static inline int predict(int16_t *src, int16_t *last)
234 {
235     const int LT = last[-1];
236     const int T  = last[0];
237     const int L  = src[-1];
238
239     return mid_pred(L, L + T - LT, T);
240 }
241
242 static inline int get_context(PlaneContext *p, int16_t *src,
243                               int16_t *last, int16_t *last2)
244 {
245     const int LT = last[-1];
246     const int T  = last[0];
247     const int RT = last[1];
248     const int L  = src[-1];
249
250     if (p->quant_table[3][127]) {
251         const int TT = last2[0];
252         const int LL = src[-2];
253         return p->quant_table[0][(L - LT) & 0xFF] +
254                p->quant_table[1][(LT - T) & 0xFF] +
255                p->quant_table[2][(T - RT) & 0xFF] +
256                p->quant_table[3][(LL - L) & 0xFF] +
257                p->quant_table[4][(TT - T) & 0xFF];
258     } else
259         return p->quant_table[0][(L - LT) & 0xFF] +
260                p->quant_table[1][(LT - T) & 0xFF] +
261                p->quant_table[2][(T - RT) & 0xFF];
262 }
263
264 static void find_best_state(uint8_t best_state[256][256],
265                             const uint8_t one_state[256])
266 {
267     int i, j, k, m;
268     double l2tab[256];
269
270     for (i = 1; i < 256; i++)
271         l2tab[i] = log2(i / 256.0);
272
273     for (i = 0; i < 256; i++) {
274         double best_len[256];
275         double p = i / 256.0;
276
277         for (j = 0; j < 256; j++)
278             best_len[j] = 1 << 30;
279
280         for (j = FFMAX(i - 10, 1); j < FFMIN(i + 11, 256); j++) {
281             double occ[256] = { 0 };
282             double len      = 0;
283             occ[j] = 1.0;
284             for (k = 0; k < 256; k++) {
285                 double newocc[256] = { 0 };
286                 for (m = 1; m < 256; m++)
287                     if (occ[m]) {
288                         len -=occ[m]*(     p *l2tab[    m]
289                                       + (1-p)*l2tab[256-m]);
290                     }
291                 if (len < best_len[k]) {
292                     best_len[k]      = len;
293                     best_state[i][k] = j;
294                 }
295                 for (m = 0; m < 256; m++)
296                     if (occ[m]) {
297                         newocc[      one_state[      m]] += occ[m] * p;
298                         newocc[256 - one_state[256 - m]] += occ[m] * (1 - p);
299                     }
300                 memcpy(occ, newocc, sizeof(occ));
301             }
302         }
303     }
304 }
305
306 static av_always_inline av_flatten void put_symbol_inline(RangeCoder *c,
307                                                           uint8_t *state, int v,
308                                                           int is_signed,
309                                                           uint64_t rc_stat[256][2],
310                                                           uint64_t rc_stat2[32][2])
311 {
312     int i;
313
314 #define put_rac(C, S, B)                        \
315     do {                                        \
316         if (rc_stat) {                          \
317             rc_stat[*(S)][B]++;                 \
318             rc_stat2[(S) - state][B]++;         \
319         }                                       \
320         put_rac(C, S, B);                       \
321     } while (0)
322
323     if (v) {
324         const int a = FFABS(v);
325         const int e = av_log2(a);
326         put_rac(c, state + 0, 0);
327         if (e <= 9) {
328             for (i = 0; i < e; i++)
329                 put_rac(c, state + 1 + i, 1);  // 1..10
330             put_rac(c, state + 1 + i, 0);
331
332             for (i = e - 1; i >= 0; i--)
333                 put_rac(c, state + 22 + i, (a >> i) & 1);  // 22..31
334
335             if (is_signed)
336                 put_rac(c, state + 11 + e, v < 0);  // 11..21
337         } else {
338             for (i = 0; i < e; i++)
339                 put_rac(c, state + 1 + FFMIN(i, 9), 1);  // 1..10
340             put_rac(c, state + 1 + 9, 0);
341
342             for (i = e - 1; i >= 0; i--)
343                 put_rac(c, state + 22 + FFMIN(i, 9), (a >> i) & 1);  // 22..31
344
345             if (is_signed)
346                 put_rac(c, state + 11 + 10, v < 0);  // 11..21
347         }
348     } else {
349         put_rac(c, state + 0, 1);
350     }
351 #undef put_rac
352 }
353
354 static av_noinline void put_symbol(RangeCoder *c, uint8_t *state,
355                                    int v, int is_signed)
356 {
357     put_symbol_inline(c, state, v, is_signed, NULL, NULL);
358 }
359
360 static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,
361                                                int is_signed)
362 {
363     if (get_rac(c, state + 0))
364         return 0;
365     else {
366         int i, e, a;
367         e = 0;
368         while (get_rac(c, state + 1 + FFMIN(e, 9))) // 1..10
369             e++;
370
371         a = 1;
372         for (i = e - 1; i >= 0; i--)
373             a += a + get_rac(c, state + 22 + FFMIN(i, 9));  // 22..31
374
375         e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21
376         return (a ^ e) - e;
377     }
378 }
379
380 static av_noinline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed)
381 {
382     return get_symbol_inline(c, state, is_signed);
383 }
384
385 static inline void update_vlc_state(VlcState *const state, const int v)
386 {
387     int drift = state->drift;
388     int count = state->count;
389     state->error_sum += FFABS(v);
390     drift            += v;
391
392     if (count == 128) { // FIXME: variable
393         count            >>= 1;
394         drift            >>= 1;
395         state->error_sum >>= 1;
396     }
397     count++;
398
399     if (drift <= -count) {
400         if (state->bias > -128)
401             state->bias--;
402
403         drift += count;
404         if (drift <= -count)
405             drift = -count + 1;
406     } else if (drift > 0) {
407         if (state->bias < 127)
408             state->bias++;
409
410         drift -= count;
411         if (drift > 0)
412             drift = 0;
413     }
414
415     state->drift = drift;
416     state->count = count;
417 }
418
419 static inline void put_vlc_symbol(PutBitContext *pb, VlcState *const state,
420                                   int v, int bits)
421 {
422     int i, k, code;
423     v = fold(v - state->bias, bits);
424
425     i = state->count;
426     k = 0;
427     while (i < state->error_sum) { // FIXME: optimize
428         k++;
429         i += i;
430     }
431
432     av_assert2(k<=13);
433
434 #if 0 // JPEG LS
435     if (k == 0 && 2 * state->drift <= -state->count)
436         code = v ^ (-1);
437     else
438         code = v;
439 #else
440     code = v ^ ((2 * state->drift + state->count) >> 31);
441 #endif
442
443     av_dlog(NULL, "v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code,
444             state->bias, state->error_sum, state->drift, state->count, k);
445     set_sr_golomb(pb, code, k, 12, bits);
446
447     update_vlc_state(state, v);
448 }
449
450 static inline int get_vlc_symbol(GetBitContext *gb, VlcState *const state,
451                                  int bits)
452 {
453     int k, i, v, ret;
454
455     i = state->count;
456     k = 0;
457     while (i < state->error_sum) { // FIXME: optimize
458         k++;
459         i += i;
460     }
461
462     assert(k <= 8);
463
464     v = get_sr_golomb(gb, k, 12, bits);
465     av_dlog(NULL, "v:%d bias:%d error:%d drift:%d count:%d k:%d",
466             v, state->bias, state->error_sum, state->drift, state->count, k);
467
468 #if 0 // JPEG LS
469     if (k == 0 && 2 * state->drift <= -state->count)
470         v ^= (-1);
471 #else
472     v ^= ((2 * state->drift + state->count) >> 31);
473 #endif
474
475     ret = fold(v + state->bias, bits);
476
477     update_vlc_state(state, v);
478
479     return ret;
480 }
481
482 #if CONFIG_FFV1_ENCODER
483 static av_always_inline int encode_line(FFV1Context *s, int w,
484                                         int16_t *sample[3],
485                                         int plane_index, int bits)
486 {
487     PlaneContext *const p = &s->plane[plane_index];
488     RangeCoder *const c   = &s->c;
489     int x;
490     int run_index = s->run_index;
491     int run_count = 0;
492     int run_mode  = 0;
493
494     if (s->ac) {
495         if (c->bytestream_end - c->bytestream < w * 20) {
496             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
497             return -1;
498         }
499     } else {
500         if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) < w * 4) {
501             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
502             return -1;
503         }
504     }
505
506     for (x = 0; x < w; x++) {
507         int diff, context;
508
509         context = get_context(p, sample[0] + x, sample[1] + x, sample[2] + x);
510         diff    = sample[0][x] - predict(sample[0] + x, sample[1] + x);
511
512         if (context < 0) {
513             context = -context;
514             diff    = -diff;
515         }
516
517         diff = fold(diff, bits);
518
519         if (s->ac) {
520             if (s->flags & CODEC_FLAG_PASS1) {
521                 put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat,
522                                   s->rc_stat2[p->quant_table_index][context]);
523             } else {
524                 put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);
525             }
526         } else {
527             if (context == 0)
528                 run_mode = 1;
529
530             if (run_mode) {
531                 if (diff) {
532                     while (run_count >= 1 << ff_log2_run[run_index]) {
533                         run_count -= 1 << ff_log2_run[run_index];
534                         run_index++;
535                         put_bits(&s->pb, 1, 1);
536                     }
537
538                     put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
539                     if (run_index)
540                         run_index--;
541                     run_count = 0;
542                     run_mode  = 0;
543                     if (diff > 0)
544                         diff--;
545                 } else {
546                     run_count++;
547                 }
548             }
549
550             av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
551                     run_count, run_index, run_mode, x,
552                     (int)put_bits_count(&s->pb));
553
554             if (run_mode == 0)
555                 put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
556         }
557     }
558     if (run_mode) {
559         while (run_count >= 1 << ff_log2_run[run_index]) {
560             run_count -= 1 << ff_log2_run[run_index];
561             run_index++;
562             put_bits(&s->pb, 1, 1);
563         }
564
565         if (run_count)
566             put_bits(&s->pb, 1, 1);
567     }
568     s->run_index = run_index;
569
570     return 0;
571 }
572
573 static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h,
574                          int stride, int plane_index)
575 {
576     int x, y, i;
577     const int ring_size = s->avctx->context_model ? 3 : 2;
578     int16_t *sample[3];
579     s->run_index = 0;
580
581     memset(s->sample_buffer, 0, ring_size * (w + 6) * sizeof(*s->sample_buffer));
582
583     for (y = 0; y < h; y++) {
584         for (i = 0; i < ring_size; i++)
585             sample[i] = s->sample_buffer + (w + 6) * ((h + i - y) % ring_size) + 3;
586
587         sample[0][-1]= sample[1][0  ];
588         sample[1][ w]= sample[1][w-1];
589 // { START_TIMER
590         if (s->bits_per_raw_sample <= 8) {
591             for (x = 0; x < w; x++)
592                 sample[0][x] = src[x + stride * y];
593             encode_line(s, w, sample, plane_index, 8);
594         } else {
595             if (s->packed_at_lsb) {
596                 for (x = 0; x < w; x++) {
597                     sample[0][x] = ((uint16_t*)(src + stride*y))[x];
598                 }
599             } else {
600                 for (x = 0; x < w; x++) {
601                     sample[0][x] = ((uint16_t*)(src + stride*y))[x] >> (16 - s->bits_per_raw_sample);
602                 }
603             }
604             encode_line(s, w, sample, plane_index, s->bits_per_raw_sample);
605         }
606 // STOP_TIMER("encode line") }
607     }
608 }
609
610 static void encode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
611 {
612     int x, y, p, i;
613     const int ring_size = s->avctx->context_model ? 3 : 2;
614     int16_t *sample[4][3];
615     int lbd    = s->avctx->bits_per_raw_sample <= 8;
616     int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
617     int offset = 1 << bits;
618     s->run_index = 0;
619
620     memset(s->sample_buffer, 0, ring_size * 4 * (w + 6) * sizeof(*s->sample_buffer));
621
622     for (y = 0; y < h; y++) {
623         for (i = 0; i < ring_size; i++)
624             for (p = 0; p < 4; p++)
625                 sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;
626
627         for (x = 0; x < w; x++) {
628             int b, g, r, av_uninit(a);
629             if (lbd) {
630                 unsigned v = *((uint32_t*)(src[0] + x*4 + stride[0]*y));
631                 b =  v        & 0xFF;
632                 g = (v >>  8) & 0xFF;
633                 r = (v >> 16) & 0xFF;
634                 a =  v >> 24;
635             } else {
636                 b = *((uint16_t*)(src[0] + x*2 + stride[0]*y));
637                 g = *((uint16_t*)(src[1] + x*2 + stride[1]*y));
638                 r = *((uint16_t*)(src[2] + x*2 + stride[2]*y));
639             }
640
641             b -= g;
642             r -= g;
643             g += (b + r) >> 2;
644             b += offset;
645             r += offset;
646
647             sample[0][0][x] = g;
648             sample[1][0][x] = b;
649             sample[2][0][x] = r;
650             sample[3][0][x] = a;
651         }
652         for (p = 0; p < 3 + s->transparency; p++) {
653             sample[p][0][-1] = sample[p][1][0  ];
654             sample[p][1][ w] = sample[p][1][w-1];
655             if (lbd)
656                 encode_line(s, w, sample[p], (p+1)/2, 9);
657             else
658                 encode_line(s, w, sample[p], (p+1)/2, bits+1);
659         }
660     }
661 }
662
663 static void write_quant_table(RangeCoder *c, int16_t *quant_table)
664 {
665     int last = 0;
666     int i;
667     uint8_t state[CONTEXT_SIZE];
668     memset(state, 128, sizeof(state));
669
670     for (i = 1; i < 128; i++)
671         if (quant_table[i] != quant_table[i - 1]) {
672             put_symbol(c, state, i - last - 1, 0);
673             last = i;
674         }
675     put_symbol(c, state, i - last - 1, 0);
676 }
677
678 static void write_quant_tables(RangeCoder *c,
679                                int16_t quant_table[MAX_CONTEXT_INPUTS][256])
680 {
681     int i;
682     for (i = 0; i < 5; i++)
683         write_quant_table(c, quant_table[i]);
684 }
685
686 static void write_header(FFV1Context *f)
687 {
688     uint8_t state[CONTEXT_SIZE];
689     int i, j;
690     RangeCoder *const c = &f->slice_context[0]->c;
691
692     memset(state, 128, sizeof(state));
693
694     if (f->version < 2) {
695         put_symbol(c, state, f->version, 0);
696         put_symbol(c, state, f->ac, 0);
697         if (f->ac > 1) {
698             for (i = 1; i < 256; i++)
699                 put_symbol(c, state,
700                            f->state_transition[i] - c->one_state[i], 1);
701         }
702         put_symbol(c, state, f->colorspace, 0); //YUV cs type
703         if (f->version > 0)
704             put_symbol(c, state, f->bits_per_raw_sample, 0);
705         put_rac(c, state, f->chroma_planes);
706         put_symbol(c, state, f->chroma_h_shift, 0);
707         put_symbol(c, state, f->chroma_v_shift, 0);
708         put_rac(c, state, f->transparency);
709
710         write_quant_tables(c, f->quant_table);
711     } else if (f->version < 3) {
712         put_symbol(c, state, f->slice_count, 0);
713         for (i = 0; i < f->slice_count; i++) {
714             FFV1Context *fs = f->slice_context[i];
715             put_symbol(c, state,
716                        (fs->slice_x      + 1) * f->num_h_slices / f->width, 0);
717             put_symbol(c, state,
718                        (fs->slice_y      + 1) * f->num_v_slices / f->height, 0);
719             put_symbol(c, state,
720                        (fs->slice_width  + 1) * f->num_h_slices / f->width - 1,
721                        0);
722             put_symbol(c, state,
723                        (fs->slice_height + 1) * f->num_v_slices / f->height - 1,
724                        0);
725             for (j = 0; j < f->plane_count; j++) {
726                 put_symbol(c, state, f->plane[j].quant_table_index, 0);
727                 av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
728             }
729         }
730     }
731 }
732
733 #endif /* CONFIG_FFV1_ENCODER */
734
735 static av_cold int common_init(AVCodecContext *avctx)
736 {
737     FFV1Context *s = avctx->priv_data;
738
739     if (!avctx->width || !avctx->height)
740         return AVERROR_INVALIDDATA;
741
742     s->avctx = avctx;
743     s->flags = avctx->flags;
744
745     avcodec_get_frame_defaults(&s->picture);
746
747     ff_dsputil_init(&s->dsp, avctx);
748
749     s->width  = avctx->width;
750     s->height = avctx->height;
751
752     // defaults
753     s->num_h_slices = 1;
754     s->num_v_slices = 1;
755
756     return 0;
757 }
758
759 static int init_slice_state(FFV1Context *f, FFV1Context *fs)
760 {
761     int j;
762
763         fs->plane_count  = f->plane_count;
764         fs->transparency = f->transparency;
765         for (j = 0; j < f->plane_count; j++) {
766             PlaneContext *const p = &fs->plane[j];
767
768             if (fs->ac) {
769                 if (!p->state)
770                     p->state = av_malloc(CONTEXT_SIZE * p->context_count *
771                                          sizeof(uint8_t));
772                 if (!p->state)
773                     return AVERROR(ENOMEM);
774             } else {
775                 if (!p->vlc_state)
776                     p->vlc_state = av_malloc(p->context_count * sizeof(VlcState));
777                 if (!p->vlc_state)
778                     return AVERROR(ENOMEM);
779             }
780         }
781
782         if (fs->ac > 1) {
783             // FIXME: only redo if state_transition changed
784             for (j = 1; j < 256; j++) {
785                 fs->c. one_state[      j] = f->state_transition[j];
786                 fs->c.zero_state[256 - j] = 256 - fs->c.one_state[j];
787             }
788         }
789
790     return 0;
791 }
792
793 static int init_slices_state(FFV1Context *f) {
794     int i;
795     for (i = 0; i < f->slice_count; i++) {
796         FFV1Context *fs = f->slice_context[i];
797         if (init_slice_state(f, fs) < 0)
798             return -1;
799     }
800     return 0;
801 }
802
803 static av_cold int init_slice_contexts(FFV1Context *f)
804 {
805     int i;
806
807     f->slice_count = f->num_h_slices * f->num_v_slices;
808
809     for (i = 0; i < f->slice_count; i++) {
810         FFV1Context *fs = av_mallocz(sizeof(*fs));
811         int sx          = i % f->num_h_slices;
812         int sy          = i / f->num_h_slices;
813         int sxs         = f->avctx->width  *  sx      / f->num_h_slices;
814         int sxe         = f->avctx->width  * (sx + 1) / f->num_h_slices;
815         int sys         = f->avctx->height *  sy      / f->num_v_slices;
816         int sye         = f->avctx->height * (sy + 1) / f->num_v_slices;
817         f->slice_context[i] = fs;
818         memcpy(fs, f, sizeof(*fs));
819         memset(fs->rc_stat2, 0, sizeof(fs->rc_stat2));
820
821         fs->slice_width  = sxe - sxs;
822         fs->slice_height = sye - sys;
823         fs->slice_x      = sxs;
824         fs->slice_y      = sys;
825
826         fs->sample_buffer = av_malloc(3*4 * (fs->width+6) * sizeof(*fs->sample_buffer));
827         if (!fs->sample_buffer)
828             return AVERROR(ENOMEM);
829     }
830     return 0;
831 }
832
833 static int allocate_initial_states(FFV1Context *f)
834 {
835     int i;
836
837     for (i = 0; i < f->quant_table_count; i++) {
838         f->initial_states[i] = av_malloc(f->context_count[i] *
839                                          sizeof(*f->initial_states[i]));
840         if (!f->initial_states[i])
841             return AVERROR(ENOMEM);
842         memset(f->initial_states[i], 128,
843                f->context_count[i] * sizeof(*f->initial_states[i]));
844     }
845     return 0;
846 }
847
848 #if CONFIG_FFV1_ENCODER
849 static int write_extra_header(FFV1Context *f)
850 {
851     RangeCoder *const c = &f->c;
852     uint8_t state[CONTEXT_SIZE];
853     int i, j, k;
854     uint8_t state2[32][CONTEXT_SIZE];
855     unsigned v;
856
857     memset(state2, 128, sizeof(state2));
858     memset(state, 128, sizeof(state));
859
860     f->avctx->extradata = av_malloc(f->avctx->extradata_size = 10000 +
861                                     (11 * 11 * 5 * 5 * 5 + 11 * 11 * 11) * 32);
862     ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);
863     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
864
865     put_symbol(c, state, f->version, 0);
866     if (f->version > 2) {
867         if (f->version == 3)
868             f->minor_version = 2;
869         put_symbol(c, state, f->minor_version, 0);
870     }
871     put_symbol(c, state, f->ac, 0);
872     if (f->ac > 1)
873         for (i = 1; i < 256; i++)
874             put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
875     put_symbol(c, state, f->colorspace, 0); // YUV cs type
876     put_symbol(c, state, f->bits_per_raw_sample, 0);
877     put_rac(c, state, f->chroma_planes);
878     put_symbol(c, state, f->chroma_h_shift, 0);
879     put_symbol(c, state, f->chroma_v_shift, 0);
880     put_rac(c, state, f->transparency);
881     put_symbol(c, state, f->num_h_slices - 1, 0);
882     put_symbol(c, state, f->num_v_slices - 1, 0);
883
884     put_symbol(c, state, f->quant_table_count, 0);
885     for (i = 0; i < f->quant_table_count; i++)
886         write_quant_tables(c, f->quant_tables[i]);
887
888     for (i = 0; i < f->quant_table_count; i++) {
889         for (j = 0; j < f->context_count[i] * CONTEXT_SIZE; j++)
890             if (f->initial_states[i] && f->initial_states[i][0][j] != 128)
891                 break;
892         if (j < f->context_count[i] * CONTEXT_SIZE) {
893             put_rac(c, state, 1);
894             for (j = 0; j < f->context_count[i]; j++)
895                 for (k = 0; k < CONTEXT_SIZE; k++) {
896                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
897                     put_symbol(c, state2[k],
898                                (int8_t)(f->initial_states[i][j][k] - pred), 1);
899                 }
900         } else {
901             put_rac(c, state, 0);
902         }
903     }
904
905     if (f->version > 2) {
906         put_symbol(c, state, f->ec, 0);
907     }
908
909     f->avctx->extradata_size = ff_rac_terminate(c);
910     v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
911     AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);
912     f->avctx->extradata_size += 4;
913
914     return 0;
915 }
916
917 static int sort_stt(FFV1Context *s, uint8_t stt[256])
918 {
919     int i, i2, changed, print = 0;
920
921     do {
922         changed = 0;
923         for (i = 12; i < 244; i++) {
924             for (i2 = i + 1; i2 < 245 && i2 < i + 4; i2++) {
925
926 #define COST(old, new)                                      \
927     s->rc_stat[old][0] * -log2((256 - (new)) / 256.0) +     \
928     s->rc_stat[old][1] * -log2((new)         / 256.0)
929
930 #define COST2(old, new)                         \
931     COST(old, new) + COST(256 - (old), 256 - (new))
932
933                 double size0 = COST2(i,  i) + COST2(i2, i2);
934                 double sizeX = COST2(i, i2) + COST2(i2, i);
935                 if (sizeX < size0 && i != 128 && i2 != 128) {
936                     int j;
937                     FFSWAP(int, stt[i], stt[i2]);
938                     FFSWAP(int, s->rc_stat[i][0], s->rc_stat[i2][0]);
939                     FFSWAP(int, s->rc_stat[i][1], s->rc_stat[i2][1]);
940                     if (i != 256 - i2) {
941                         FFSWAP(int, stt[256 - i], stt[256 - i2]);
942                         FFSWAP(int, s->rc_stat[256 - i][0], s->rc_stat[256 - i2][0]);
943                         FFSWAP(int, s->rc_stat[256 - i][1], s->rc_stat[256 - i2][1]);
944                     }
945                     for (j = 1; j < 256; j++) {
946                         if (stt[j] == i)
947                             stt[j] = i2;
948                         else if (stt[j] == i2)
949                             stt[j] = i;
950                         if (i != 256 - i2) {
951                             if (stt[256 - j] == 256 - i)
952                                 stt[256 - j] = 256 - i2;
953                             else if (stt[256 - j] == 256 - i2)
954                                 stt[256 - j] = 256 - i;
955                         }
956                     }
957                     print = changed = 1;
958                 }
959             }
960         }
961     } while (changed);
962     return print;
963 }
964
965 static av_cold int encode_init(AVCodecContext *avctx)
966 {
967     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
968     FFV1Context *s = avctx->priv_data;
969     int i, j, k, m;
970
971     common_init(avctx);
972
973     s->version = 0;
974
975     if ((avctx->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)) || avctx->slices>1)
976         s->version = FFMAX(s->version, 2);
977
978     if (avctx->level == 3) {
979         s->version = 3;
980     }
981
982     if (s->ec < 0) {
983         s->ec = (s->version >= 3);
984     }
985
986     if (s->version >= 2 && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
987         av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n");
988         return AVERROR_INVALIDDATA;
989     }
990
991     s->ac = avctx->coder_type > 0 ? 2 : 0;
992
993     s->plane_count = 3;
994     switch(avctx->pix_fmt) {
995     case AV_PIX_FMT_YUV444P9:
996     case AV_PIX_FMT_YUV422P9:
997     case AV_PIX_FMT_YUV420P9:
998         if (!avctx->bits_per_raw_sample)
999             s->bits_per_raw_sample = 9;
1000     case AV_PIX_FMT_YUV444P10:
1001     case AV_PIX_FMT_YUV420P10:
1002     case AV_PIX_FMT_YUV422P10:
1003         s->packed_at_lsb = 1;
1004         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
1005             s->bits_per_raw_sample = 10;
1006     case AV_PIX_FMT_GRAY16:
1007     case AV_PIX_FMT_YUV444P16:
1008     case AV_PIX_FMT_YUV422P16:
1009     case AV_PIX_FMT_YUV420P16:
1010         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {
1011             s->bits_per_raw_sample = 16;
1012         } else if (!s->bits_per_raw_sample) {
1013             s->bits_per_raw_sample = avctx->bits_per_raw_sample;
1014         }
1015         if (s->bits_per_raw_sample <= 8) {
1016             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
1017             return AVERROR_INVALIDDATA;
1018         }
1019         if (!s->ac && avctx->coder_type == -1) {
1020             av_log(avctx, AV_LOG_INFO, "bits_per_raw_sample > 8, forcing coder 1\n");
1021             s->ac = 2;
1022         }
1023         if (!s->ac) {
1024             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
1025             return AVERROR_INVALIDDATA;
1026         }
1027         s->version = FFMAX(s->version, 1);
1028     case AV_PIX_FMT_GRAY8:
1029     case AV_PIX_FMT_YUV444P:
1030     case AV_PIX_FMT_YUV440P:
1031     case AV_PIX_FMT_YUV422P:
1032     case AV_PIX_FMT_YUV420P:
1033     case AV_PIX_FMT_YUV411P:
1034     case AV_PIX_FMT_YUV410P:
1035         s->chroma_planes = desc->nb_components < 3 ? 0 : 1;
1036         s->colorspace = 0;
1037         break;
1038     case AV_PIX_FMT_YUVA444P:
1039     case AV_PIX_FMT_YUVA422P:
1040     case AV_PIX_FMT_YUVA420P:
1041         s->chroma_planes = 1;
1042         s->colorspace = 0;
1043         s->transparency = 1;
1044         break;
1045     case AV_PIX_FMT_RGB32:
1046         s->colorspace = 1;
1047         s->transparency = 1;
1048         break;
1049     case AV_PIX_FMT_0RGB32:
1050         s->colorspace = 1;
1051         break;
1052     case AV_PIX_FMT_GBRP9:
1053         if (!avctx->bits_per_raw_sample)
1054             s->bits_per_raw_sample = 9;
1055     case AV_PIX_FMT_GBRP10:
1056         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
1057             s->bits_per_raw_sample = 10;
1058     case AV_PIX_FMT_GBRP12:
1059         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
1060             s->bits_per_raw_sample = 12;
1061     case AV_PIX_FMT_GBRP14:
1062         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
1063             s->bits_per_raw_sample = 14;
1064         else if (!s->bits_per_raw_sample)
1065             s->bits_per_raw_sample = avctx->bits_per_raw_sample;
1066         s->colorspace = 1;
1067         s->chroma_planes = 1;
1068         s->version = FFMAX(s->version, 1);
1069         break;
1070     default:
1071         av_log(avctx, AV_LOG_ERROR, "format not supported\n");
1072         return AVERROR_INVALIDDATA;
1073     }
1074     if (s->transparency) {
1075         av_log(avctx, AV_LOG_WARNING, "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");
1076     }
1077     if (avctx->context_model > 1U) {
1078         av_log(avctx, AV_LOG_ERROR, "Invalid context model %d, valid values are 0 and 1\n", avctx->context_model);
1079         return AVERROR(EINVAL);
1080     }
1081
1082     if (s->ac > 1)
1083         for (i = 1; i < 256; i++)
1084             s->state_transition[i] = ver2_state[i];
1085
1086     for (i = 0; i < 256; i++) {
1087         s->quant_table_count = 2;
1088         if (s->bits_per_raw_sample <= 8) {
1089             s->quant_tables[0][0][i]=           quant11[i];
1090             s->quant_tables[0][1][i]=        11*quant11[i];
1091             s->quant_tables[0][2][i]=     11*11*quant11[i];
1092             s->quant_tables[1][0][i]=           quant11[i];
1093             s->quant_tables[1][1][i]=        11*quant11[i];
1094             s->quant_tables[1][2][i]=     11*11*quant5 [i];
1095             s->quant_tables[1][3][i]=   5*11*11*quant5 [i];
1096             s->quant_tables[1][4][i]= 5*5*11*11*quant5 [i];
1097         } else {
1098             s->quant_tables[0][0][i]=           quant9_10bit[i];
1099             s->quant_tables[0][1][i]=        11*quant9_10bit[i];
1100             s->quant_tables[0][2][i]=     11*11*quant9_10bit[i];
1101             s->quant_tables[1][0][i]=           quant9_10bit[i];
1102             s->quant_tables[1][1][i]=        11*quant9_10bit[i];
1103             s->quant_tables[1][2][i]=     11*11*quant5_10bit[i];
1104             s->quant_tables[1][3][i]=   5*11*11*quant5_10bit[i];
1105             s->quant_tables[1][4][i]= 5*5*11*11*quant5_10bit[i];
1106         }
1107     }
1108     s->context_count[0] = (11 * 11 * 11        + 1) / 2;
1109     s->context_count[1] = (11 * 11 * 5 * 5 * 5 + 1) / 2;
1110     memcpy(s->quant_table, s->quant_tables[avctx->context_model],
1111            sizeof(s->quant_table));
1112
1113     for (i = 0; i < s->plane_count; i++) {
1114         PlaneContext *const p = &s->plane[i];
1115
1116         memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));
1117         p->quant_table_index = avctx->context_model;
1118         p->context_count     = s->context_count[p->quant_table_index];
1119     }
1120
1121     if (allocate_initial_states(s) < 0)
1122         return AVERROR(ENOMEM);
1123
1124     avctx->coded_frame = &s->picture;
1125     if (!s->transparency)
1126         s->plane_count = 2;
1127     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
1128     s->picture_number = 0;
1129
1130     if (avctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
1131         for (i = 0; i < s->quant_table_count; i++) {
1132             s->rc_stat2[i] = av_mallocz(s->context_count[i] *
1133                                         sizeof(*s->rc_stat2[i]));
1134             if (!s->rc_stat2[i])
1135                 return AVERROR(ENOMEM);
1136         }
1137     }
1138     if (avctx->stats_in) {
1139         char *p = avctx->stats_in;
1140         uint8_t best_state[256][256];
1141         int gob_count = 0;
1142         char *next;
1143
1144         av_assert0(s->version >= 2);
1145
1146         for (;;) {
1147             for (j = 0; j < 256; j++)
1148                 for (i = 0; i < 2; i++) {
1149                     s->rc_stat[j][i] = strtol(p, &next, 0);
1150                     if (next == p) {
1151                         av_log(avctx, AV_LOG_ERROR,
1152                                "2Pass file invalid at %d %d [%s]\n", j, i, p);
1153                         return -1;
1154                     }
1155                     p = next;
1156                 }
1157             for (i = 0; i < s->quant_table_count; i++)
1158                 for (j = 0; j < s->context_count[i]; j++) {
1159                     for (k = 0; k < 32; k++)
1160                         for (m = 0; m < 2; m++) {
1161                             s->rc_stat2[i][j][k][m] = strtol(p, &next, 0);
1162                             if (next == p) {
1163                                 av_log(avctx, AV_LOG_ERROR,
1164                                        "2Pass file invalid at %d %d %d %d [%s]\n",
1165                                        i, j, k, m, p);
1166                                 return AVERROR_INVALIDDATA;
1167                             }
1168                             p = next;
1169                         }
1170                 }
1171             gob_count = strtol(p, &next, 0);
1172             if (next == p || gob_count <= 0) {
1173                 av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");
1174                 return AVERROR_INVALIDDATA;
1175             }
1176             p = next;
1177             while (*p == '\n' || *p == ' ')
1178                 p++;
1179             if (p[0] == 0)
1180                 break;
1181         }
1182         sort_stt(s, s->state_transition);
1183
1184         find_best_state(best_state, s->state_transition);
1185
1186         for (i = 0; i < s->quant_table_count; i++) {
1187             for (j = 0; j < s->context_count[i]; j++)
1188                 for (k = 0; k < 32; k++) {
1189                     double p = 128;
1190                     if (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1]) {
1191                         p = 256.0 * s->rc_stat2[i][j][k][1] /
1192                             (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1]);
1193                     }
1194                     s->initial_states[i][j][k] =
1195                         best_state[av_clip(round(p), 1, 255)][av_clip((s->rc_stat2[i][j][k][0] +
1196                                                                        s->rc_stat2[i][j][k][1]) /
1197                                                                       gob_count, 0, 255)];
1198                 }
1199         }
1200     }
1201
1202     if (s->version > 1) {
1203         for (s->num_v_slices = 2; s->num_v_slices < 9; s->num_v_slices++) {
1204             for (s->num_h_slices = s->num_v_slices; s->num_h_slices < 2*s->num_v_slices; s->num_h_slices++) {
1205                 if (avctx->slices == s->num_h_slices * s->num_v_slices && avctx->slices <= 64 || !avctx->slices)
1206                     goto slices_ok;
1207             }
1208         }
1209         av_log(avctx, AV_LOG_ERROR, "Unsupported number %d of slices requested, please specify a supported number with -slices (ex:4,6,9,12,16, ...)\n", avctx->slices);
1210         return -1;
1211         slices_ok:
1212         write_extra_header(s);
1213     }
1214
1215     if (init_slice_contexts(s) < 0)
1216         return -1;
1217     if (init_slices_state(s) < 0)
1218         return -1;
1219
1220 #define STATS_OUT_SIZE 1024 * 1024 * 6
1221     if (avctx->flags & CODEC_FLAG_PASS1) {
1222         avctx->stats_out = av_mallocz(STATS_OUT_SIZE);
1223         for (i = 0; i < s->quant_table_count; i++)
1224             for (j = 0; j < s->slice_count; j++) {
1225                 FFV1Context *sf = s->slice_context[j];
1226                 av_assert0(!sf->rc_stat2[i]);
1227                 sf->rc_stat2[i] = av_mallocz(s->context_count[i] *
1228                                              sizeof(*sf->rc_stat2[i]));
1229                 if (!sf->rc_stat2[i])
1230                     return AVERROR(ENOMEM);
1231             }
1232     }
1233
1234     return 0;
1235 }
1236
1237 #endif /* CONFIG_FFV1_ENCODER */
1238
1239
1240 static void clear_slice_state(FFV1Context *f, FFV1Context *fs)
1241 {
1242     int i, j;
1243
1244         for (i = 0; i < f->plane_count; i++) {
1245             PlaneContext *p = &fs->plane[i];
1246
1247             p->interlace_bit_state[0] = 128;
1248             p->interlace_bit_state[1] = 128;
1249
1250             if (fs->ac) {
1251                 if (f->initial_states[p->quant_table_index]) {
1252                     memcpy(p->state, f->initial_states[p->quant_table_index],
1253                            CONTEXT_SIZE * p->context_count);
1254                 } else
1255                     memset(p->state, 128, CONTEXT_SIZE * p->context_count);
1256             } else {
1257                 for (j = 0; j < p->context_count; j++) {
1258                     p->vlc_state[j].drift     = 0;
1259                     p->vlc_state[j].error_sum = 4; // FFMAX((RANGE + 32)/64, 2);
1260                     p->vlc_state[j].bias      = 0;
1261                     p->vlc_state[j].count     = 1;
1262                 }
1263             }
1264         }
1265 }
1266
1267 #if CONFIG_FFV1_ENCODER
1268
1269 static void encode_slice_header(FFV1Context *f, FFV1Context *fs)
1270 {
1271     RangeCoder *c = &fs->c;
1272     uint8_t state[CONTEXT_SIZE];
1273     int j;
1274     memset(state, 128, sizeof(state));
1275
1276     put_symbol(c, state, (fs->slice_x     +1)*f->num_h_slices / f->width   , 0);
1277     put_symbol(c, state, (fs->slice_y     +1)*f->num_v_slices / f->height  , 0);
1278     put_symbol(c, state, (fs->slice_width +1)*f->num_h_slices / f->width -1, 0);
1279     put_symbol(c, state, (fs->slice_height+1)*f->num_v_slices / f->height-1, 0);
1280     for (j=0; j<f->plane_count; j++) {
1281         put_symbol(c, state, f->plane[j].quant_table_index, 0);
1282         av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
1283     }
1284     if (!f->picture.interlaced_frame) put_symbol(c, state, 3, 0);
1285     else                             put_symbol(c, state, 1 + !f->picture.top_field_first, 0);
1286     put_symbol(c, state, f->picture.sample_aspect_ratio.num, 0);
1287     put_symbol(c, state, f->picture.sample_aspect_ratio.den, 0);
1288 }
1289
1290 static int encode_slice(AVCodecContext *c, void *arg)
1291 {
1292     FFV1Context *fs  = *(void **)arg;
1293     FFV1Context *f   = fs->avctx->priv_data;
1294     int width        = fs->slice_width;
1295     int height       = fs->slice_height;
1296     int x            = fs->slice_x;
1297     int y            = fs->slice_y;
1298     AVFrame *const p = &f->picture;
1299     const int ps     = (av_pix_fmt_desc_get(c->pix_fmt)->flags & PIX_FMT_PLANAR)
1300                             ?
1301                        (f->bits_per_raw_sample>8)+1
1302                             :
1303                        4;
1304
1305     if (p->key_frame)
1306         clear_slice_state(f, fs);
1307     if (f->version > 2) {
1308         encode_slice_header(f, fs);
1309     }
1310     if (!fs->ac) {
1311         if (f->version > 2)
1312             put_rac(&fs->c, (uint8_t[]) {129}, 0);
1313         fs->ac_byte_count = f->version > 2 || (!x&&!y) ? ff_rac_terminate(&fs->c) : 0;
1314         init_put_bits(&fs->pb, fs->c.bytestream_start + fs->ac_byte_count, fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count);
1315     }
1316
1317     if (f->colorspace == 0) {
1318         const int chroma_width  = -((-width) >> f->chroma_h_shift);
1319         const int chroma_height = -((-height) >> f->chroma_v_shift);
1320         const int cx            = x >> f->chroma_h_shift;
1321         const int cy            = y >> f->chroma_v_shift;
1322
1323         encode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
1324
1325         if (f->chroma_planes) {
1326             encode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
1327             encode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
1328         }
1329         if (fs->transparency)
1330             encode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
1331     } else {
1332         uint8_t *planes[3] = {p->data[0] + ps*x + y*p->linesize[0],
1333                               p->data[1] + ps*x + y*p->linesize[1],
1334                               p->data[2] + ps*x + y*p->linesize[2]};
1335         encode_rgb_frame(fs, planes, width, height, p->linesize);
1336     }
1337     emms_c();
1338
1339     return 0;
1340 }
1341
1342 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1343                         const AVFrame *pict, int *got_packet)
1344 {
1345     FFV1Context *f      = avctx->priv_data;
1346     RangeCoder *const c = &f->slice_context[0]->c;
1347     AVFrame *const p    = &f->picture;
1348     int used_count      = 0;
1349     uint8_t keystate    = 128;
1350     uint8_t *buf_p;
1351     int i, ret;
1352
1353     if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*((8*2+1+1)*4)/8
1354                                             + FF_MIN_BUFFER_SIZE)) < 0)
1355         return ret;
1356
1357     ff_init_range_encoder(c, pkt->data, pkt->size);
1358     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
1359
1360     *p           = *pict;
1361     p->pict_type = AV_PICTURE_TYPE_I;
1362
1363     if (avctx->gop_size == 0 || f->picture_number % avctx->gop_size == 0) {
1364         put_rac(c, &keystate, 1);
1365         p->key_frame = 1;
1366         f->gob_count++;
1367         write_header(f);
1368     } else {
1369         put_rac(c, &keystate, 0);
1370         p->key_frame = 0;
1371     }
1372
1373     if (f->ac > 1) {
1374         int i;
1375         for (i = 1; i < 256; i++) {
1376             c->one_state[i]        = f->state_transition[i];
1377             c->zero_state[256 - i] = 256 - c->one_state[i];
1378         }
1379     }
1380
1381     for (i = 1; i < f->slice_count; i++) {
1382         FFV1Context *fs = f->slice_context[i];
1383         uint8_t *start  = pkt->data + (pkt->size - used_count) * (int64_t)i / f->slice_count;
1384         int len         = pkt->size / f->slice_count;
1385         ff_init_range_encoder(&fs->c, start, len);
1386     }
1387     avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL,
1388                    f->slice_count, sizeof(void *));
1389
1390     buf_p = pkt->data;
1391     for (i = 0; i < f->slice_count; i++) {
1392         FFV1Context *fs = f->slice_context[i];
1393         int bytes;
1394
1395         if (fs->ac) {
1396             uint8_t state=129;
1397             put_rac(&fs->c, &state, 0);
1398             bytes = ff_rac_terminate(&fs->c);
1399         } else {
1400             flush_put_bits(&fs->pb); // FIXME: nicer padding
1401             bytes = fs->ac_byte_count + (put_bits_count(&fs->pb) + 7)/8;
1402         }
1403         if (i > 0 || f->version > 2) {
1404             av_assert0(bytes < pkt->size / f->slice_count);
1405             memmove(buf_p, fs->c.bytestream_start, bytes);
1406             av_assert0(bytes < (1 << 24));
1407             AV_WB24(buf_p + bytes, bytes);
1408             bytes += 3;
1409         }
1410         if (f->ec) {
1411             unsigned v;
1412             buf_p[bytes++] = 0;
1413             v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);
1414             AV_WL32(buf_p + bytes, v); bytes += 4;
1415         }
1416         buf_p += bytes;
1417     }
1418
1419     if ((avctx->flags & CODEC_FLAG_PASS1) && (f->picture_number & 31) == 0) {
1420         int j, k, m;
1421         char *p   = avctx->stats_out;
1422         char *end = p + STATS_OUT_SIZE;
1423
1424         memset(f->rc_stat, 0, sizeof(f->rc_stat));
1425         for (i = 0; i < f->quant_table_count; i++)
1426             memset(f->rc_stat2[i], 0, f->context_count[i] * sizeof(*f->rc_stat2[i]));
1427
1428         for (j = 0; j < f->slice_count; j++) {
1429             FFV1Context *fs = f->slice_context[j];
1430             for (i = 0; i < 256; i++) {
1431                 f->rc_stat[i][0] += fs->rc_stat[i][0];
1432                 f->rc_stat[i][1] += fs->rc_stat[i][1];
1433             }
1434             for (i = 0; i < f->quant_table_count; i++) {
1435                 for (k = 0; k < f->context_count[i]; k++)
1436                     for (m = 0; m < 32; m++) {
1437                         f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];
1438                         f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];
1439                     }
1440             }
1441         }
1442
1443         for (j = 0; j < 256; j++) {
1444             snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",
1445                      f->rc_stat[j][0], f->rc_stat[j][1]);
1446             p += strlen(p);
1447         }
1448         snprintf(p, end - p, "\n");
1449
1450         for (i = 0; i < f->quant_table_count; i++) {
1451             for (j = 0; j < f->context_count[i]; j++)
1452                 for (m = 0; m < 32; m++) {
1453                     snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",
1454                              f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);
1455                     p += strlen(p);
1456                 }
1457         }
1458         snprintf(p, end - p, "%d\n", f->gob_count);
1459     } else if (avctx->flags & CODEC_FLAG_PASS1)
1460         avctx->stats_out[0] = '\0';
1461
1462     f->picture_number++;
1463     pkt->size   = buf_p - pkt->data;
1464     pkt->flags |= AV_PKT_FLAG_KEY * p->key_frame;
1465     *got_packet = 1;
1466
1467     return 0;
1468 }
1469
1470 #endif /* CONFIG_FFV1_ENCODER */
1471
1472 static av_cold int common_end(AVCodecContext *avctx)
1473 {
1474     FFV1Context *s = avctx->priv_data;
1475     int i, j;
1476
1477     if (avctx->codec->decode && s->picture.data[0])
1478         avctx->release_buffer(avctx, &s->picture);
1479     if (avctx->codec->decode && s->last_picture.data[0])
1480         avctx->release_buffer(avctx, &s->last_picture);
1481
1482     for (j = 0; j < s->slice_count; j++) {
1483         FFV1Context *fs = s->slice_context[j];
1484         for (i = 0; i < s->plane_count; i++) {
1485             PlaneContext *p = &fs->plane[i];
1486
1487             av_freep(&p->state);
1488             av_freep(&p->vlc_state);
1489         }
1490         av_freep(&fs->sample_buffer);
1491     }
1492
1493     av_freep(&avctx->stats_out);
1494     for (j = 0; j < s->quant_table_count; j++) {
1495         av_freep(&s->initial_states[j]);
1496         for (i = 0; i < s->slice_count; i++) {
1497             FFV1Context *sf = s->slice_context[i];
1498             av_freep(&sf->rc_stat2[j]);
1499         }
1500         av_freep(&s->rc_stat2[j]);
1501     }
1502
1503     for (i = 0; i < s->slice_count; i++)
1504         av_freep(&s->slice_context[i]);
1505
1506     return 0;
1507 }
1508
1509 static av_always_inline void decode_line(FFV1Context *s, int w,
1510                                          int16_t *sample[2],
1511                                          int plane_index, int bits)
1512 {
1513     PlaneContext *const p = &s->plane[plane_index];
1514     RangeCoder *const c   = &s->c;
1515     int x;
1516     int run_count = 0;
1517     int run_mode  = 0;
1518     int run_index = s->run_index;
1519
1520     for (x = 0; x < w; x++) {
1521         int diff, context, sign;
1522
1523         context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);
1524         if (context < 0) {
1525             context = -context;
1526             sign    = 1;
1527         } else
1528             sign = 0;
1529
1530         av_assert2(context < p->context_count);
1531
1532         if (s->ac) {
1533             diff = get_symbol_inline(c, p->state[context], 1);
1534         } else {
1535             if (context == 0 && run_mode == 0)
1536                 run_mode = 1;
1537
1538             if (run_mode) {
1539                 if (run_count == 0 && run_mode == 1) {
1540                     if (get_bits1(&s->gb)) {
1541                         run_count = 1 << ff_log2_run[run_index];
1542                         if (x + run_count <= w)
1543                             run_index++;
1544                     } else {
1545                         if (ff_log2_run[run_index])
1546                             run_count = get_bits(&s->gb, ff_log2_run[run_index]);
1547                         else
1548                             run_count = 0;
1549                         if (run_index)
1550                             run_index--;
1551                         run_mode = 2;
1552                     }
1553                 }
1554                 run_count--;
1555                 if (run_count < 0) {
1556                     run_mode  = 0;
1557                     run_count = 0;
1558                     diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],
1559                                                bits);
1560                     if (diff >= 0)
1561                         diff++;
1562                 } else
1563                     diff = 0;
1564             } else
1565                 diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);
1566
1567             av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
1568                     run_count, run_index, run_mode, x, get_bits_count(&s->gb));
1569         }
1570
1571         if (sign)
1572             diff = -diff;
1573
1574         sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &
1575                        ((1 << bits) - 1);
1576     }
1577     s->run_index = run_index;
1578 }
1579
1580 static void decode_plane(FFV1Context *s, uint8_t *src,
1581                          int w, int h, int stride, int plane_index)
1582 {
1583     int x, y;
1584     int16_t *sample[2];
1585     sample[0] = s->sample_buffer + 3;
1586     sample[1] = s->sample_buffer + w + 6 + 3;
1587
1588     s->run_index = 0;
1589
1590     memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));
1591
1592     for (y = 0; y < h; y++) {
1593         int16_t *temp = sample[0]; // FIXME: try a normal buffer
1594
1595         sample[0] = sample[1];
1596         sample[1] = temp;
1597
1598         sample[1][-1] = sample[0][0];
1599         sample[0][w]  = sample[0][w - 1];
1600
1601 // { START_TIMER
1602         if (s->avctx->bits_per_raw_sample <= 8) {
1603             decode_line(s, w, sample, plane_index, 8);
1604             for (x = 0; x < w; x++)
1605                 src[x + stride * y] = sample[1][x];
1606         } else {
1607             decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
1608             if (s->packed_at_lsb) {
1609                 for (x = 0; x < w; x++) {
1610                     ((uint16_t*)(src + stride*y))[x] = sample[1][x];
1611                 }
1612             } else {
1613                 for (x = 0; x < w; x++) {
1614                     ((uint16_t*)(src + stride*y))[x] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
1615                 }
1616             }
1617         }
1618 // STOP_TIMER("decode-line") }
1619     }
1620 }
1621
1622 static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
1623 {
1624     int x, y, p;
1625     int16_t *sample[4][2];
1626     int lbd  = s->avctx->bits_per_raw_sample <= 8;
1627     int bits = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
1628     int offset = 1 << bits;
1629     for (x = 0; x < 4; x++) {
1630         sample[x][0] = s->sample_buffer +  x * 2      * (w + 6) + 3;
1631         sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
1632     }
1633
1634     s->run_index = 0;
1635
1636     memset(s->sample_buffer, 0, 8*(w+6)*sizeof(*s->sample_buffer));
1637
1638     for (y = 0; y < h; y++) {
1639         for (p = 0; p < 3 + s->transparency; p++) {
1640             int16_t *temp = sample[p][0]; // FIXME: try a normal buffer
1641
1642             sample[p][0] = sample[p][1];
1643             sample[p][1] = temp;
1644
1645             sample[p][1][-1]= sample[p][0][0  ];
1646             sample[p][0][ w]= sample[p][0][w-1];
1647             if (lbd)
1648                 decode_line(s, w, sample[p], (p+1)/2, 9);
1649             else
1650                 decode_line(s, w, sample[p], (p+1)/2, bits+1);
1651         }
1652         for (x = 0; x < w; x++) {
1653             int g = sample[0][1][x];
1654             int b = sample[1][1][x];
1655             int r = sample[2][1][x];
1656             int a = sample[3][1][x];
1657
1658             b -= offset;
1659             r -= offset;
1660             g -= (b + r) >> 2;
1661             b += g;
1662             r += g;
1663
1664             if (lbd)
1665                 *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
1666             else {
1667                 *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
1668                 *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
1669                 *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
1670             }
1671         }
1672     }
1673 }
1674
1675 static int decode_slice_header(FFV1Context *f, FFV1Context *fs)
1676 {
1677     RangeCoder *c = &fs->c;
1678     uint8_t state[CONTEXT_SIZE];
1679     unsigned ps, i, context_count;
1680     memset(state, 128, sizeof(state));
1681
1682     av_assert0(f->version > 2);
1683
1684     fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
1685     fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
1686     fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
1687     fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
1688
1689     fs->slice_x /= f->num_h_slices;
1690     fs->slice_y /= f->num_v_slices;
1691     fs->slice_width  = fs->slice_width /f->num_h_slices - fs->slice_x;
1692     fs->slice_height = fs->slice_height/f->num_v_slices - fs->slice_y;
1693     if ((unsigned)fs->slice_width > f->width || (unsigned)fs->slice_height > f->height)
1694         return -1;
1695     if (    (unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width
1696          || (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
1697         return -1;
1698
1699     for (i = 0; i < f->plane_count; i++) {
1700         PlaneContext * const p = &fs->plane[i];
1701         int idx = get_symbol(c, state, 0);
1702         if (idx > (unsigned)f->quant_table_count) {
1703             av_log(f->avctx, AV_LOG_ERROR, "quant_table_index out of range\n");
1704             return -1;
1705         }
1706         p->quant_table_index = idx;
1707         memcpy(p->quant_table, f->quant_tables[idx], sizeof(p->quant_table));
1708         context_count = f->context_count[idx];
1709
1710         if (p->context_count < context_count) {
1711             av_freep(&p->state);
1712             av_freep(&p->vlc_state);
1713         }
1714         p->context_count = context_count;
1715     }
1716
1717     ps = get_symbol(c, state, 0);
1718     if (ps == 1) {
1719         f->picture.interlaced_frame = 1;
1720         f->picture.top_field_first  = 1;
1721     } else if (ps == 2) {
1722         f->picture.interlaced_frame = 1;
1723         f->picture.top_field_first  = 0;
1724     } else if (ps == 3) {
1725         f->picture.interlaced_frame = 0;
1726     }
1727     f->picture.sample_aspect_ratio.num = get_symbol(c, state, 0);
1728     f->picture.sample_aspect_ratio.den = get_symbol(c, state, 0);
1729
1730     return 0;
1731 }
1732
1733 static int decode_slice(AVCodecContext *c, void *arg)
1734 {
1735     FFV1Context *fs  = *(void **)arg;
1736     FFV1Context *f   = fs->avctx->priv_data;
1737     int width, height, x, y;
1738     const int ps = (av_pix_fmt_desc_get(c->pix_fmt)->flags & PIX_FMT_PLANAR)
1739                         ?
1740                    (c->bits_per_raw_sample>8)+1
1741                         :
1742                     4;
1743     AVFrame * const p = &f->picture;
1744
1745     if (f->version > 2) {
1746         if (init_slice_state(f, fs) < 0)
1747             return AVERROR(ENOMEM);
1748         if (decode_slice_header(f, fs) < 0) {
1749             fs->slice_damaged = 1;
1750             return AVERROR_INVALIDDATA;
1751         }
1752     }
1753     if (init_slice_state(f, fs) < 0)
1754         return AVERROR(ENOMEM);
1755     if (f->picture.key_frame)
1756         clear_slice_state(f, fs);
1757     width = fs->slice_width;
1758     height= fs->slice_height;
1759     x= fs->slice_x;
1760     y= fs->slice_y;
1761
1762     if (!fs->ac) {
1763         if (f->version == 3 && f->minor_version > 1 || f->version > 3)
1764             get_rac(&fs->c, (uint8_t[]) {129});
1765         fs->ac_byte_count = f->version > 2 || (!x&&!y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;
1766         init_get_bits(&fs->gb,
1767                       fs->c.bytestream_start + fs->ac_byte_count,
1768                       (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);
1769     }
1770
1771     av_assert1(width && height);
1772     if (f->colorspace == 0) {
1773         const int chroma_width  = -((-width)  >> f->chroma_h_shift);
1774         const int chroma_height = -((-height) >> f->chroma_v_shift);
1775         const int cx            = x >> f->chroma_h_shift;
1776         const int cy            = y >> f->chroma_v_shift;
1777         decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
1778
1779         if (f->chroma_planes) {
1780             decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
1781             decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
1782         }
1783         if (fs->transparency)
1784             decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
1785     } else {
1786         uint8_t *planes[3] = {p->data[0] + ps*x + y*p->linesize[0],
1787                               p->data[1] + ps*x + y*p->linesize[1],
1788                               p->data[2] + ps*x + y*p->linesize[2]};
1789         decode_rgb_frame(fs, planes, width, height, p->linesize);
1790     }
1791     if (fs->ac && f->version > 2) {
1792         int v;
1793         get_rac(&fs->c, (uint8_t[]) {129});
1794         v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;
1795         if (v) {
1796             av_log(f->avctx, AV_LOG_ERROR, "bytestream end mismatching by %d\n", v);
1797             fs->slice_damaged = 1;
1798         }
1799     }
1800
1801     emms_c();
1802
1803     return 0;
1804 }
1805
1806 static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale)
1807 {
1808     int v;
1809     int i = 0;
1810     uint8_t state[CONTEXT_SIZE];
1811
1812     memset(state, 128, sizeof(state));
1813
1814     for (v = 0; i < 128; v++) {
1815         unsigned len = get_symbol(c, state, 0) + 1;
1816
1817         if (len > 128 - i)
1818             return -1;
1819
1820         while (len--) {
1821             quant_table[i] = scale * v;
1822             i++;
1823         }
1824     }
1825
1826     for (i = 1; i < 128; i++)
1827         quant_table[256 - i] = -quant_table[i];
1828     quant_table[128] = -quant_table[127];
1829
1830     return 2 * v - 1;
1831 }
1832
1833 static int read_quant_tables(RangeCoder *c,
1834                              int16_t quant_table[MAX_CONTEXT_INPUTS][256])
1835 {
1836     int i;
1837     int context_count = 1;
1838
1839     for (i = 0; i < 5; i++) {
1840         context_count *= read_quant_table(c, quant_table[i], context_count);
1841         if (context_count > 32768U) {
1842             return -1;
1843         }
1844     }
1845     return (context_count + 1) / 2;
1846 }
1847
1848 static int read_extra_header(FFV1Context *f)
1849 {
1850     RangeCoder *const c = &f->c;
1851     uint8_t state[CONTEXT_SIZE];
1852     int i, j, k;
1853     uint8_t state2[32][CONTEXT_SIZE];
1854
1855     memset(state2, 128, sizeof(state2));
1856     memset(state, 128, sizeof(state));
1857
1858     ff_init_range_decoder(c, f->avctx->extradata, f->avctx->extradata_size);
1859     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
1860
1861     f->version = get_symbol(c, state, 0);
1862     if (f->version > 2) {
1863         c->bytestream_end -= 4;
1864         f->minor_version = get_symbol(c, state, 0);
1865     }
1866     f->ac = f->avctx->coder_type = get_symbol(c, state, 0);
1867     if (f->ac > 1)
1868         for (i = 1; i < 256; i++)
1869             f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
1870
1871     f->colorspace                 = get_symbol(c, state, 0); // YUV cs type
1872     f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
1873     f->chroma_planes  = get_rac(c, state);
1874     f->chroma_h_shift = get_symbol(c, state, 0);
1875     f->chroma_v_shift = get_symbol(c, state, 0);
1876     f->transparency = get_rac(c, state);
1877     f->plane_count  = 2 + f->transparency;
1878     f->num_h_slices = 1 + get_symbol(c, state, 0);
1879     f->num_v_slices = 1 + get_symbol(c, state, 0);
1880
1881     if (f->num_h_slices > (unsigned)f->width ||
1882         f->num_v_slices > (unsigned)f->height) {
1883         av_log(f->avctx, AV_LOG_ERROR, "too many slices\n");
1884         return -1;
1885     }
1886
1887     f->quant_table_count = get_symbol(c, state, 0);
1888
1889     if (f->quant_table_count > (unsigned)MAX_QUANT_TABLES)
1890         return -1;
1891
1892     for (i = 0; i < f->quant_table_count; i++) {
1893         f->context_count[i] = read_quant_tables(c, f->quant_tables[i]);
1894         if (f->context_count[i] < 0) {
1895             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
1896             return -1;
1897         }
1898     }
1899
1900     if (allocate_initial_states(f) < 0)
1901         return AVERROR(ENOMEM);
1902
1903     for (i = 0; i < f->quant_table_count; i++)
1904         if (get_rac(c, state))
1905             for (j = 0; j < f->context_count[i]; j++)
1906                 for (k = 0; k < CONTEXT_SIZE; k++) {
1907                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
1908                     f->initial_states[i][j][k] =
1909                         (pred + get_symbol(c, state2[k], 1)) & 0xFF;
1910                 }
1911
1912     if (f->version > 2) {
1913         f->ec = get_symbol(c, state, 0);
1914     }
1915
1916     if (f->version > 2) {
1917         unsigned v;
1918         v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
1919         if (v) {
1920             av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!\n", v);
1921             return AVERROR_INVALIDDATA;
1922         }
1923     }
1924
1925     return 0;
1926 }
1927
1928 static int read_header(FFV1Context *f)
1929 {
1930     uint8_t state[CONTEXT_SIZE];
1931     int i, j, context_count = -1; //-1 to avoid warning
1932     RangeCoder *const c = &f->slice_context[0]->c;
1933
1934     memset(state, 128, sizeof(state));
1935
1936     if (f->version < 2) {
1937         unsigned v= get_symbol(c, state, 0);
1938         if (v >= 2) {
1939             av_log(f->avctx, AV_LOG_ERROR, "invalid version %d in ver01 header\n", v);
1940             return AVERROR_INVALIDDATA;
1941         }
1942         f->version = v;
1943         f->ac      = f->avctx->coder_type = get_symbol(c, state, 0);
1944         if (f->ac > 1)
1945             for (i = 1; i < 256; i++)
1946                 f->state_transition[i] = get_symbol(c, state, 1) + c->one_state[i];
1947         f->colorspace = get_symbol(c, state, 0); // YUV cs type
1948         if (f->version > 0)
1949             f->avctx->bits_per_raw_sample = get_symbol(c, state, 0);
1950         f->chroma_planes  = get_rac(c, state);
1951         f->chroma_h_shift = get_symbol(c, state, 0);
1952         f->chroma_v_shift = get_symbol(c, state, 0);
1953         f->transparency   = get_rac(c, state);
1954         f->plane_count    = 2 + f->transparency;
1955     }
1956
1957     if (f->colorspace == 0) {
1958         if (!f->transparency && !f->chroma_planes) {
1959             if (f->avctx->bits_per_raw_sample <= 8)
1960                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
1961             else
1962                 f->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
1963         } else if (f->avctx->bits_per_raw_sample<=8 && !f->transparency) {
1964             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
1965             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P; break;
1966             case 0x01: f->avctx->pix_fmt = AV_PIX_FMT_YUV440P; break;
1967             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P; break;
1968             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P; break;
1969             case 0x20: f->avctx->pix_fmt = AV_PIX_FMT_YUV411P; break;
1970             case 0x22: f->avctx->pix_fmt = AV_PIX_FMT_YUV410P; break;
1971             default:
1972                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
1973                 return -1;
1974             }
1975         } else if (f->avctx->bits_per_raw_sample <= 8 && f->transparency) {
1976             switch(16*f->chroma_h_shift + f->chroma_v_shift) {
1977             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUVA444P; break;
1978             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUVA422P; break;
1979             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUVA420P; break;
1980             default:
1981                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
1982                 return -1;
1983             }
1984         } else if (f->avctx->bits_per_raw_sample == 9) {
1985             f->packed_at_lsb = 1;
1986             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
1987             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P9; break;
1988             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P9; break;
1989             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P9; break;
1990             default:
1991                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
1992                 return -1;
1993             }
1994         } else if (f->avctx->bits_per_raw_sample == 10) {
1995             f->packed_at_lsb = 1;
1996             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
1997             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P10; break;
1998             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P10; break;
1999             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P10; break;
2000             default:
2001                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
2002                 return -1;
2003             }
2004         } else {
2005             switch(16 * f->chroma_h_shift + f->chroma_v_shift) {
2006             case 0x00: f->avctx->pix_fmt = AV_PIX_FMT_YUV444P16; break;
2007             case 0x10: f->avctx->pix_fmt = AV_PIX_FMT_YUV422P16; break;
2008             case 0x11: f->avctx->pix_fmt = AV_PIX_FMT_YUV420P16; break;
2009             default:
2010                 av_log(f->avctx, AV_LOG_ERROR, "format not supported\n");
2011                 return -1;
2012             }
2013         }
2014     } else if (f->colorspace == 1) {
2015         if (f->chroma_h_shift || f->chroma_v_shift) {
2016             av_log(f->avctx, AV_LOG_ERROR,
2017                    "chroma subsampling not supported in this colorspace\n");
2018             return -1;
2019         }
2020         if (     f->avctx->bits_per_raw_sample ==  9)
2021             f->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
2022         else if (f->avctx->bits_per_raw_sample == 10)
2023             f->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
2024         else if (f->avctx->bits_per_raw_sample == 12)
2025             f->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
2026         else if (f->avctx->bits_per_raw_sample == 14)
2027             f->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
2028         else
2029         if (f->transparency) f->avctx->pix_fmt = AV_PIX_FMT_RGB32;
2030         else                 f->avctx->pix_fmt = AV_PIX_FMT_0RGB32;
2031     } else {
2032         av_log(f->avctx, AV_LOG_ERROR, "colorspace not supported\n");
2033         return -1;
2034     }
2035
2036     av_dlog(f->avctx, "%d %d %d\n",
2037             f->chroma_h_shift, f->chroma_v_shift, f->avctx->pix_fmt);
2038
2039     if (f->version < 2) {
2040         context_count = read_quant_tables(c, f->quant_table);
2041         if (context_count < 0) {
2042             av_log(f->avctx, AV_LOG_ERROR, "read_quant_table error\n");
2043             return -1;
2044         }
2045     } else if (f->version < 3) {
2046         f->slice_count = get_symbol(c, state, 0);
2047     } else {
2048         const uint8_t *p = c->bytestream_end;
2049         for (f->slice_count = 0; f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start; f->slice_count++) {
2050             int trailer = 3 + 5*!!f->ec;
2051             int size = AV_RB24(p-trailer);
2052             if (size + trailer > p - c->bytestream_start)
2053                 break;
2054             p -= size + trailer;
2055         }
2056     }
2057     if (f->slice_count > (unsigned)MAX_SLICES || f->slice_count <= 0) {
2058         av_log(f->avctx, AV_LOG_ERROR, "slice count %d is invalid\n", f->slice_count);
2059         return -1;
2060     }
2061
2062     for (j = 0; j < f->slice_count; j++) {
2063         FFV1Context *fs = f->slice_context[j];
2064         fs->ac = f->ac;
2065         fs->packed_at_lsb = f->packed_at_lsb;
2066
2067         fs->slice_damaged = 0;
2068
2069         if (f->version == 2) {
2070             fs->slice_x      =  get_symbol(c, state, 0)      * f->width ;
2071             fs->slice_y      =  get_symbol(c, state, 0)      * f->height;
2072             fs->slice_width  = (get_symbol(c, state, 0) + 1) * f->width  + fs->slice_x;
2073             fs->slice_height = (get_symbol(c, state, 0) + 1) * f->height + fs->slice_y;
2074
2075             fs->slice_x     /= f->num_h_slices;
2076             fs->slice_y     /= f->num_v_slices;
2077             fs->slice_width  = fs->slice_width  / f->num_h_slices - fs->slice_x;
2078             fs->slice_height = fs->slice_height / f->num_v_slices - fs->slice_y;
2079             if ((unsigned)fs->slice_width  > f->width ||
2080                 (unsigned)fs->slice_height > f->height)
2081                 return -1;
2082             if ((unsigned)fs->slice_x + (uint64_t)fs->slice_width  > f->width ||
2083                 (unsigned)fs->slice_y + (uint64_t)fs->slice_height > f->height)
2084                 return -1;
2085         }
2086
2087         for (i = 0; i < f->plane_count; i++) {
2088             PlaneContext *const p = &fs->plane[i];
2089
2090             if (f->version == 2) {
2091                 int idx = get_symbol(c, state, 0);
2092                 if (idx > (unsigned)f->quant_table_count) {
2093                     av_log(f->avctx, AV_LOG_ERROR,
2094                            "quant_table_index out of range\n");
2095                     return -1;
2096                 }
2097                 p->quant_table_index = idx;
2098                 memcpy(p->quant_table, f->quant_tables[idx],
2099                        sizeof(p->quant_table));
2100                 context_count = f->context_count[idx];
2101             } else {
2102                 memcpy(p->quant_table, f->quant_table, sizeof(p->quant_table));
2103             }
2104
2105             if (f->version <= 2) {
2106                 av_assert0(context_count >= 0);
2107                 if (p->context_count < context_count) {
2108                     av_freep(&p->state);
2109                     av_freep(&p->vlc_state);
2110                 }
2111                 p->context_count = context_count;
2112             }
2113         }
2114     }
2115     return 0;
2116 }
2117
2118 static av_cold int decode_init(AVCodecContext *avctx)
2119 {
2120     FFV1Context *f = avctx->priv_data;
2121
2122     common_init(avctx);
2123
2124     if (avctx->extradata && read_extra_header(f) < 0)
2125         return -1;
2126
2127     if (init_slice_contexts(f) < 0)
2128         return -1;
2129
2130     return 0;
2131 }
2132
2133 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
2134 {
2135     const uint8_t *buf  = avpkt->data;
2136     int buf_size        = avpkt->size;
2137     FFV1Context *f      = avctx->priv_data;
2138     RangeCoder *const c = &f->slice_context[0]->c;
2139     AVFrame *const p    = &f->picture;
2140     int i;
2141     uint8_t keystate = 128;
2142     const uint8_t *buf_p;
2143
2144     AVFrame *picture = data;
2145
2146     /* release previously stored data */
2147     if (p->data[0])
2148         avctx->release_buffer(avctx, p);
2149
2150     ff_init_range_decoder(c, buf, buf_size);
2151     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
2152
2153     p->pict_type = AV_PICTURE_TYPE_I; // FIXME: I vs. P
2154     if (get_rac(c, &keystate)) {
2155         p->key_frame = 1;
2156         f->key_frame_ok = 0;
2157         if (read_header(f) < 0)
2158             return -1;
2159         f->key_frame_ok = 1;
2160     } else {
2161         if (!f->key_frame_ok) {
2162             av_log(avctx, AV_LOG_ERROR, "Cant decode non keyframe without valid keyframe\n");
2163             return AVERROR_INVALIDDATA;
2164         }
2165         p->key_frame= 0;
2166     }
2167
2168     p->reference = 3; //for error concealment
2169     if (avctx->get_buffer(avctx, p) < 0) {
2170         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2171         return -1;
2172     }
2173
2174     if (avctx->debug&FF_DEBUG_PICT_INFO)
2175         av_log(avctx, AV_LOG_DEBUG, "ver:%d keyframe:%d coder:%d ec:%d slices:%d bps:%d\n",
2176                f->version, p->key_frame, f->ac, f->ec, f->slice_count, f->avctx->bits_per_raw_sample);
2177
2178     buf_p = buf + buf_size;
2179     for (i = f->slice_count - 1; i >= 0; i--) {
2180         FFV1Context *fs = f->slice_context[i];
2181         int trailer = 3 + 5*!!f->ec;
2182         int v;
2183
2184         if (i || f->version>2) v = AV_RB24(buf_p-trailer)+trailer;
2185         else                   v = buf_p - c->bytestream_start;
2186         if (buf_p - c->bytestream_start < v) {
2187             av_log(avctx, AV_LOG_ERROR, "Slice pointer chain broken\n");
2188             return -1;
2189         }
2190         buf_p -= v;
2191
2192         if (f->ec) {
2193             unsigned crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, v);
2194             if (crc) {
2195                 int64_t ts = avpkt->pts != AV_NOPTS_VALUE ? avpkt->pts : avpkt->dts;
2196                 av_log(f->avctx, AV_LOG_ERROR, "CRC mismatch %X!", crc);
2197                 if (ts != AV_NOPTS_VALUE && avctx->pkt_timebase.num) {
2198                     av_log(f->avctx, AV_LOG_ERROR, "at %f seconds\n", ts*av_q2d(avctx->pkt_timebase));
2199                 } else if (ts != AV_NOPTS_VALUE) {
2200                     av_log(f->avctx, AV_LOG_ERROR, "at %"PRId64"\n", ts);
2201                 } else {
2202                     av_log(f->avctx, AV_LOG_ERROR, "\n");
2203                 }
2204                 fs->slice_damaged = 1;
2205             }
2206         }
2207
2208         if (i) {
2209             ff_init_range_decoder(&fs->c, buf_p, v);
2210         } else
2211             fs->c.bytestream_end = (uint8_t *)(buf_p + v);
2212     }
2213
2214     avctx->execute(avctx, decode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void*));
2215
2216     for (i=f->slice_count-1; i>=0; i--) {
2217         FFV1Context *fs= f->slice_context[i];
2218         int j;
2219         if (fs->slice_damaged && f->last_picture.data[0]) {
2220             uint8_t *dst[4], *src[4];
2221             for (j=0; j<4; j++) {
2222                 int sh = (j==1 || j==2) ? f->chroma_h_shift : 0;
2223                 int sv = (j==1 || j==2) ? f->chroma_v_shift : 0;
2224                 dst[j] = f->picture     .data[j] + f->picture     .linesize[j]*
2225                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
2226                 src[j] = f->last_picture.data[j] + f->last_picture.linesize[j]*
2227                          (fs->slice_y>>sv) + (fs->slice_x>>sh);
2228             }
2229             av_image_copy(dst, f->picture.linesize, (const uint8_t **)src, f->last_picture.linesize,
2230                           avctx->pix_fmt, fs->slice_width, fs->slice_height);
2231         }
2232     }
2233
2234     f->picture_number++;
2235
2236     *picture   = *p;
2237     *data_size = sizeof(AVFrame);
2238
2239     FFSWAP(AVFrame, f->picture, f->last_picture);
2240
2241     return buf_size;
2242 }
2243
2244 AVCodec ff_ffv1_decoder = {
2245     .name           = "ffv1",
2246     .type           = AVMEDIA_TYPE_VIDEO,
2247     .id             = AV_CODEC_ID_FFV1,
2248     .priv_data_size = sizeof(FFV1Context),
2249     .init           = decode_init,
2250     .close          = common_end,
2251     .decode         = decode_frame,
2252     .capabilities   = CODEC_CAP_DR1 /*| CODEC_CAP_DRAW_HORIZ_BAND*/ |
2253                       CODEC_CAP_SLICE_THREADS,
2254     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
2255 };
2256
2257 #if CONFIG_FFV1_ENCODER
2258
2259 #define OFFSET(x) offsetof(FFV1Context, x)
2260 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2261 static const AVOption options[] = {
2262     { "slicecrc",        "Protect slices with CRCs",               OFFSET(ec),              AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
2263 {NULL}
2264 };
2265
2266 static const AVClass class = {
2267     .class_name = "ffv1 encoder",
2268     .item_name  = av_default_item_name,
2269     .option     = options,
2270     .version    = LIBAVUTIL_VERSION_INT,
2271 };
2272
2273 static const AVCodecDefault ffv1_defaults[] = {
2274     { "coder",                "-1" },
2275     { NULL },
2276 };
2277
2278 AVCodec ff_ffv1_encoder = {
2279     .name           = "ffv1",
2280     .type           = AVMEDIA_TYPE_VIDEO,
2281     .id             = AV_CODEC_ID_FFV1,
2282     .priv_data_size = sizeof(FFV1Context),
2283     .init           = encode_init,
2284     .encode2        = encode_frame,
2285     .close          = common_end,
2286     .capabilities   = CODEC_CAP_SLICE_THREADS,
2287     .defaults       = ffv1_defaults,
2288     .pix_fmts       = (const enum AVPixelFormat[]) {
2289         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUV444P,
2290         AV_PIX_FMT_YUVA444P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P,
2291         AV_PIX_FMT_YUV410P, AV_PIX_FMT_0RGB32, AV_PIX_FMT_RGB32, AV_PIX_FMT_YUV420P16,
2292         AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16, AV_PIX_FMT_YUV444P9, AV_PIX_FMT_YUV422P9,
2293         AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
2294         AV_PIX_FMT_GRAY16, AV_PIX_FMT_GRAY8, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
2295         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14,
2296         AV_PIX_FMT_NONE
2297     },
2298     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
2299     .priv_class     = &class,
2300 };
2301 #endif