]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1enc.c
Merge commit '3973f0f773e0bd212734eccda78aa798f8b20692'
[ffmpeg] / libavcodec / ffv1enc.c
1 /*
2  * FFV1 encoder
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) encoder
26  */
27
28 #include "libavutil/attributes.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/pixdesc.h"
34 #include "libavutil/timer.h"
35 #include "avcodec.h"
36 #include "internal.h"
37 #include "put_bits.h"
38 #include "rangecoder.h"
39 #include "golomb.h"
40 #include "mathops.h"
41 #include "ffv1.h"
42
43 static const int8_t quant5_10bit[256] = {
44      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,
45      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
46      1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
47      1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
48      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
49      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
50      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
51      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
52     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
53     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
54     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
55     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
56     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1,
57     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -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, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0,
60 };
61
62 static const int8_t quant5[256] = {
63      0,  1,  1,  1,  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,  2,
70      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
71     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
72     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
73     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
74     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
75     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
76     -2, -2, -2, -2, -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, -1, -1, -1,
79 };
80
81 static const int8_t quant9_10bit[256] = {
82      0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,
83      2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
84      3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,
85      3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,  4,  4,
86      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
87      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
88      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
89      4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
90     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
91     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
92     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
93     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
94     -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -3, -3, -3, -3, -3, -3,
95     -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3,
96     -3, -3, -3, -3, -3, -3, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
97     -2, -2, -2, -2, -1, -1, -1, -1, -1, -1, -1, -1, -0, -0, -0, -0,
98 };
99
100 static const int8_t quant11[256] = {
101      0,  1,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  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,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
104      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
105      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
106      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
107      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
108      5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5,
109     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
110     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
111     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
112     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
113     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5,
114     -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -4, -4,
115     -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4,
116     -4, -4, -4, -4, -4, -3, -3, -3, -3, -3, -3, -3, -2, -2, -2, -1,
117 };
118
119 static const uint8_t ver2_state[256] = {
120       0,  10,  10,  10,  10,  16,  16,  16, 28,   16,  16,  29,  42,  49,  20,  49,
121      59,  25,  26,  26,  27,  31,  33,  33, 33,   34,  34,  37,  67,  38,  39,  39,
122      40,  40,  41,  79,  43,  44,  45,  45, 48,   48,  64,  50,  51,  52,  88,  52,
123      53,  74,  55,  57,  58,  58,  74,  60, 101,  61,  62,  84,  66,  66,  68,  69,
124      87,  82,  71,  97,  73,  73,  82,  75, 111,  77,  94,  78,  87,  81,  83,  97,
125      85,  83,  94,  86,  99,  89,  90,  99, 111,  92,  93,  134, 95,  98,  105, 98,
126     105, 110, 102, 108, 102, 118, 103, 106, 106, 113, 109, 112, 114, 112, 116, 125,
127     115, 116, 117, 117, 126, 119, 125, 121, 121, 123, 145, 124, 126, 131, 127, 129,
128     165, 130, 132, 138, 133, 135, 145, 136, 137, 139, 146, 141, 143, 142, 144, 148,
129     147, 155, 151, 149, 151, 150, 152, 157, 153, 154, 156, 168, 158, 162, 161, 160,
130     172, 163, 169, 164, 166, 184, 167, 170, 177, 174, 171, 173, 182, 176, 180, 178,
131     175, 189, 179, 181, 186, 183, 192, 185, 200, 187, 191, 188, 190, 197, 193, 196,
132     197, 194, 195, 196, 198, 202, 199, 201, 210, 203, 207, 204, 205, 206, 208, 214,
133     209, 211, 221, 212, 213, 215, 224, 216, 217, 218, 219, 220, 222, 228, 223, 225,
134     226, 224, 227, 229, 240, 230, 231, 232, 233, 234, 235, 236, 238, 239, 237, 242,
135     241, 243, 242, 244, 245, 246, 247, 248, 249, 250, 251, 252, 252, 253, 254, 255,
136 };
137
138 static void find_best_state(uint8_t best_state[256][256],
139                             const uint8_t one_state[256])
140 {
141     int i, j, k, m;
142     double l2tab[256];
143
144     for (i = 1; i < 256; i++)
145         l2tab[i] = log2(i / 256.0);
146
147     for (i = 0; i < 256; i++) {
148         double best_len[256];
149         double p = i / 256.0;
150
151         for (j = 0; j < 256; j++)
152             best_len[j] = 1 << 30;
153
154         for (j = FFMAX(i - 10, 1); j < FFMIN(i + 11, 256); j++) {
155             double occ[256] = { 0 };
156             double len      = 0;
157             occ[j] = 1.0;
158             for (k = 0; k < 256; k++) {
159                 double newocc[256] = { 0 };
160                 for (m = 1; m < 256; m++)
161                     if (occ[m]) {
162                         len -=occ[m]*(     p *l2tab[    m]
163                                       + (1-p)*l2tab[256-m]);
164                     }
165                 if (len < best_len[k]) {
166                     best_len[k]      = len;
167                     best_state[i][k] = j;
168                 }
169                 for (m = 1; m < 256; m++)
170                     if (occ[m]) {
171                         newocc[      one_state[      m]] += occ[m] * p;
172                         newocc[256 - one_state[256 - m]] += occ[m] * (1 - p);
173                     }
174                 memcpy(occ, newocc, sizeof(occ));
175             }
176         }
177     }
178 }
179
180 static av_always_inline av_flatten void put_symbol_inline(RangeCoder *c,
181                                                           uint8_t *state, int v,
182                                                           int is_signed,
183                                                           uint64_t rc_stat[256][2],
184                                                           uint64_t rc_stat2[32][2])
185 {
186     int i;
187
188 #define put_rac(C, S, B)                        \
189     do {                                        \
190         if (rc_stat) {                          \
191             rc_stat[*(S)][B]++;                 \
192             rc_stat2[(S) - state][B]++;         \
193         }                                       \
194         put_rac(C, S, B);                       \
195     } while (0)
196
197     if (v) {
198         const int a = FFABS(v);
199         const int e = av_log2(a);
200         put_rac(c, state + 0, 0);
201         if (e <= 9) {
202             for (i = 0; i < e; i++)
203                 put_rac(c, state + 1 + i, 1);  // 1..10
204             put_rac(c, state + 1 + i, 0);
205
206             for (i = e - 1; i >= 0; i--)
207                 put_rac(c, state + 22 + i, (a >> i) & 1);  // 22..31
208
209             if (is_signed)
210                 put_rac(c, state + 11 + e, v < 0);  // 11..21
211         } else {
212             for (i = 0; i < e; i++)
213                 put_rac(c, state + 1 + FFMIN(i, 9), 1);  // 1..10
214             put_rac(c, state + 1 + 9, 0);
215
216             for (i = e - 1; i >= 0; i--)
217                 put_rac(c, state + 22 + FFMIN(i, 9), (a >> i) & 1);  // 22..31
218
219             if (is_signed)
220                 put_rac(c, state + 11 + 10, v < 0);  // 11..21
221         }
222     } else {
223         put_rac(c, state + 0, 1);
224     }
225 #undef put_rac
226 }
227
228 static av_noinline void put_symbol(RangeCoder *c, uint8_t *state,
229                                    int v, int is_signed)
230 {
231     put_symbol_inline(c, state, v, is_signed, NULL, NULL);
232 }
233
234
235 static inline void put_vlc_symbol(PutBitContext *pb, VlcState *const state,
236                                   int v, int bits)
237 {
238     int i, k, code;
239     v = fold(v - state->bias, bits);
240
241     i = state->count;
242     k = 0;
243     while (i < state->error_sum) { // FIXME: optimize
244         k++;
245         i += i;
246     }
247
248     av_assert2(k <= 13);
249
250 #if 0 // JPEG LS
251     if (k == 0 && 2 * state->drift <= -state->count)
252         code = v ^ (-1);
253     else
254         code = v;
255 #else
256     code = v ^ ((2 * state->drift + state->count) >> 31);
257 #endif
258
259     ff_dlog(NULL, "v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code,
260             state->bias, state->error_sum, state->drift, state->count, k);
261     set_sr_golomb(pb, code, k, 12, bits);
262
263     update_vlc_state(state, v);
264 }
265
266 static av_always_inline int encode_line(FFV1Context *s, int w,
267                                         int16_t *sample[3],
268                                         int plane_index, int bits)
269 {
270     PlaneContext *const p = &s->plane[plane_index];
271     RangeCoder *const c   = &s->c;
272     int x;
273     int run_index = s->run_index;
274     int run_count = 0;
275     int run_mode  = 0;
276
277     if (s->ac) {
278         if (c->bytestream_end - c->bytestream < w * 35) {
279             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
280             return AVERROR_INVALIDDATA;
281         }
282     } else {
283         if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) < w * 4) {
284             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
285             return AVERROR_INVALIDDATA;
286         }
287     }
288
289     if (s->slice_coding_mode == 1) {
290         for (x = 0; x < w; x++) {
291             int i;
292             int v = sample[0][x];
293             for (i = bits-1; i>=0; i--) {
294                 uint8_t state = 128;
295                 put_rac(c, &state, (v>>i) & 1);
296             }
297         }
298         return 0;
299     }
300
301     for (x = 0; x < w; x++) {
302         int diff, context;
303
304         context = get_context(p, sample[0] + x, sample[1] + x, sample[2] + x);
305         diff    = sample[0][x] - predict(sample[0] + x, sample[1] + x);
306
307         if (context < 0) {
308             context = -context;
309             diff    = -diff;
310         }
311
312         diff = fold(diff, bits);
313
314         if (s->ac) {
315             if (s->flags & AV_CODEC_FLAG_PASS1) {
316                 put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat,
317                                   s->rc_stat2[p->quant_table_index][context]);
318             } else {
319                 put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);
320             }
321         } else {
322             if (context == 0)
323                 run_mode = 1;
324
325             if (run_mode) {
326                 if (diff) {
327                     while (run_count >= 1 << ff_log2_run[run_index]) {
328                         run_count -= 1 << ff_log2_run[run_index];
329                         run_index++;
330                         put_bits(&s->pb, 1, 1);
331                     }
332
333                     put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
334                     if (run_index)
335                         run_index--;
336                     run_count = 0;
337                     run_mode  = 0;
338                     if (diff > 0)
339                         diff--;
340                 } else {
341                     run_count++;
342                 }
343             }
344
345             ff_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
346                     run_count, run_index, run_mode, x,
347                     (int)put_bits_count(&s->pb));
348
349             if (run_mode == 0)
350                 put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
351         }
352     }
353     if (run_mode) {
354         while (run_count >= 1 << ff_log2_run[run_index]) {
355             run_count -= 1 << ff_log2_run[run_index];
356             run_index++;
357             put_bits(&s->pb, 1, 1);
358         }
359
360         if (run_count)
361             put_bits(&s->pb, 1, 1);
362     }
363     s->run_index = run_index;
364
365     return 0;
366 }
367
368 static int encode_plane(FFV1Context *s, uint8_t *src, int w, int h,
369                          int stride, int plane_index)
370 {
371     int x, y, i, ret;
372     const int ring_size = s->avctx->context_model ? 3 : 2;
373     int16_t *sample[3];
374     s->run_index = 0;
375
376     memset(s->sample_buffer, 0, ring_size * (w + 6) * sizeof(*s->sample_buffer));
377
378     for (y = 0; y < h; y++) {
379         for (i = 0; i < ring_size; i++)
380             sample[i] = s->sample_buffer + (w + 6) * ((h + i - y) % ring_size) + 3;
381
382         sample[0][-1]= sample[1][0  ];
383         sample[1][ w]= sample[1][w-1];
384 // { START_TIMER
385         if (s->bits_per_raw_sample <= 8) {
386             for (x = 0; x < w; x++)
387                 sample[0][x] = src[x + stride * y];
388             if((ret = encode_line(s, w, sample, plane_index, 8)) < 0)
389                 return ret;
390         } else {
391             if (s->packed_at_lsb) {
392                 for (x = 0; x < w; x++) {
393                     sample[0][x] = ((uint16_t*)(src + stride*y))[x];
394                 }
395             } else {
396                 for (x = 0; x < w; x++) {
397                     sample[0][x] = ((uint16_t*)(src + stride*y))[x] >> (16 - s->bits_per_raw_sample);
398                 }
399             }
400             if((ret = encode_line(s, w, sample, plane_index, s->bits_per_raw_sample)) < 0)
401                 return ret;
402         }
403 // STOP_TIMER("encode line") }
404     }
405     return 0;
406 }
407
408 static int encode_rgb_frame(FFV1Context *s, const uint8_t *src[3],
409                              int w, int h, const int stride[3])
410 {
411     int x, y, p, i;
412     const int ring_size = s->avctx->context_model ? 3 : 2;
413     int16_t *sample[4][3];
414     int lbd    = s->bits_per_raw_sample <= 8;
415     int bits   = s->bits_per_raw_sample > 0 ? s->bits_per_raw_sample : 8;
416     int offset = 1 << bits;
417
418     s->run_index = 0;
419
420     memset(s->sample_buffer, 0, ring_size * MAX_PLANES *
421                                 (w + 6) * sizeof(*s->sample_buffer));
422
423     for (y = 0; y < h; y++) {
424         for (i = 0; i < ring_size; i++)
425             for (p = 0; p < MAX_PLANES; p++)
426                 sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;
427
428         for (x = 0; x < w; x++) {
429             int b, g, r, av_uninit(a);
430             if (lbd) {
431                 unsigned v = *((const uint32_t*)(src[0] + x*4 + stride[0]*y));
432                 b =  v        & 0xFF;
433                 g = (v >>  8) & 0xFF;
434                 r = (v >> 16) & 0xFF;
435                 a =  v >> 24;
436             } else {
437                 b = *((const uint16_t *)(src[0] + x*2 + stride[0]*y));
438                 g = *((const uint16_t *)(src[1] + x*2 + stride[1]*y));
439                 r = *((const uint16_t *)(src[2] + x*2 + stride[2]*y));
440             }
441
442             if (s->slice_coding_mode != 1) {
443                 b -= g;
444                 r -= g;
445                 g += (b * s->slice_rct_by_coef + r * s->slice_rct_ry_coef) >> 2;
446                 b += offset;
447                 r += offset;
448             }
449
450             sample[0][0][x] = g;
451             sample[1][0][x] = b;
452             sample[2][0][x] = r;
453             sample[3][0][x] = a;
454         }
455         for (p = 0; p < 3 + s->transparency; p++) {
456             int ret;
457             sample[p][0][-1] = sample[p][1][0  ];
458             sample[p][1][ w] = sample[p][1][w-1];
459             if (lbd && s->slice_coding_mode == 0)
460                 ret = encode_line(s, w, sample[p], (p + 1) / 2, 9);
461             else
462                 ret = encode_line(s, w, sample[p], (p + 1) / 2, bits + (s->slice_coding_mode != 1));
463             if (ret < 0)
464                 return ret;
465         }
466     }
467     return 0;
468 }
469
470 static void write_quant_table(RangeCoder *c, int16_t *quant_table)
471 {
472     int last = 0;
473     int i;
474     uint8_t state[CONTEXT_SIZE];
475     memset(state, 128, sizeof(state));
476
477     for (i = 1; i < 128; i++)
478         if (quant_table[i] != quant_table[i - 1]) {
479             put_symbol(c, state, i - last - 1, 0);
480             last = i;
481         }
482     put_symbol(c, state, i - last - 1, 0);
483 }
484
485 static void write_quant_tables(RangeCoder *c,
486                                int16_t quant_table[MAX_CONTEXT_INPUTS][256])
487 {
488     int i;
489     for (i = 0; i < 5; i++)
490         write_quant_table(c, quant_table[i]);
491 }
492
493 static void write_header(FFV1Context *f)
494 {
495     uint8_t state[CONTEXT_SIZE];
496     int i, j;
497     RangeCoder *const c = &f->slice_context[0]->c;
498
499     memset(state, 128, sizeof(state));
500
501     if (f->version < 2) {
502         put_symbol(c, state, f->version, 0);
503         put_symbol(c, state, f->ac, 0);
504         if (f->ac > 1) {
505             for (i = 1; i < 256; i++)
506                 put_symbol(c, state,
507                            f->state_transition[i] - c->one_state[i], 1);
508         }
509         put_symbol(c, state, f->colorspace, 0); //YUV cs type
510         if (f->version > 0)
511             put_symbol(c, state, f->bits_per_raw_sample, 0);
512         put_rac(c, state, f->chroma_planes);
513         put_symbol(c, state, f->chroma_h_shift, 0);
514         put_symbol(c, state, f->chroma_v_shift, 0);
515         put_rac(c, state, f->transparency);
516
517         write_quant_tables(c, f->quant_table);
518     } else if (f->version < 3) {
519         put_symbol(c, state, f->slice_count, 0);
520         for (i = 0; i < f->slice_count; i++) {
521             FFV1Context *fs = f->slice_context[i];
522             put_symbol(c, state,
523                        (fs->slice_x      + 1) * f->num_h_slices / f->width, 0);
524             put_symbol(c, state,
525                        (fs->slice_y      + 1) * f->num_v_slices / f->height, 0);
526             put_symbol(c, state,
527                        (fs->slice_width  + 1) * f->num_h_slices / f->width - 1,
528                        0);
529             put_symbol(c, state,
530                        (fs->slice_height + 1) * f->num_v_slices / f->height - 1,
531                        0);
532             for (j = 0; j < f->plane_count; j++) {
533                 put_symbol(c, state, f->plane[j].quant_table_index, 0);
534                 av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
535             }
536         }
537     }
538 }
539
540 static int write_extradata(FFV1Context *f)
541 {
542     RangeCoder *const c = &f->c;
543     uint8_t state[CONTEXT_SIZE];
544     int i, j, k;
545     uint8_t state2[32][CONTEXT_SIZE];
546     unsigned v;
547
548     memset(state2, 128, sizeof(state2));
549     memset(state, 128, sizeof(state));
550
551     f->avctx->extradata_size = 10000 + 4 +
552                                     (11 * 11 * 5 * 5 * 5 + 11 * 11 * 11) * 32;
553     f->avctx->extradata = av_malloc(f->avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
554     if (!f->avctx->extradata)
555         return AVERROR(ENOMEM);
556     ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);
557     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
558
559     put_symbol(c, state, f->version, 0);
560     if (f->version > 2) {
561         if (f->version == 3) {
562             f->micro_version = 4;
563         } else if (f->version == 4)
564             f->micro_version = 2;
565         put_symbol(c, state, f->micro_version, 0);
566     }
567
568     put_symbol(c, state, f->ac, 0);
569     if (f->ac > 1)
570         for (i = 1; i < 256; i++)
571             put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
572
573     put_symbol(c, state, f->colorspace, 0); // YUV cs type
574     put_symbol(c, state, f->bits_per_raw_sample, 0);
575     put_rac(c, state, f->chroma_planes);
576     put_symbol(c, state, f->chroma_h_shift, 0);
577     put_symbol(c, state, f->chroma_v_shift, 0);
578     put_rac(c, state, f->transparency);
579     put_symbol(c, state, f->num_h_slices - 1, 0);
580     put_symbol(c, state, f->num_v_slices - 1, 0);
581
582     put_symbol(c, state, f->quant_table_count, 0);
583     for (i = 0; i < f->quant_table_count; i++)
584         write_quant_tables(c, f->quant_tables[i]);
585
586     for (i = 0; i < f->quant_table_count; i++) {
587         for (j = 0; j < f->context_count[i] * CONTEXT_SIZE; j++)
588             if (f->initial_states[i] && f->initial_states[i][0][j] != 128)
589                 break;
590         if (j < f->context_count[i] * CONTEXT_SIZE) {
591             put_rac(c, state, 1);
592             for (j = 0; j < f->context_count[i]; j++)
593                 for (k = 0; k < CONTEXT_SIZE; k++) {
594                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
595                     put_symbol(c, state2[k],
596                                (int8_t)(f->initial_states[i][j][k] - pred), 1);
597                 }
598         } else {
599             put_rac(c, state, 0);
600         }
601     }
602
603     if (f->version > 2) {
604         put_symbol(c, state, f->ec, 0);
605         put_symbol(c, state, f->intra = (f->avctx->gop_size < 2), 0);
606     }
607
608     f->avctx->extradata_size = ff_rac_terminate(c);
609     v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);
610     AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);
611     f->avctx->extradata_size += 4;
612
613     return 0;
614 }
615
616 static int sort_stt(FFV1Context *s, uint8_t stt[256])
617 {
618     int i, i2, changed, print = 0;
619
620     do {
621         changed = 0;
622         for (i = 12; i < 244; i++) {
623             for (i2 = i + 1; i2 < 245 && i2 < i + 4; i2++) {
624
625 #define COST(old, new)                                      \
626     s->rc_stat[old][0] * -log2((256 - (new)) / 256.0) +     \
627     s->rc_stat[old][1] * -log2((new)         / 256.0)
628
629 #define COST2(old, new)                         \
630     COST(old, new) + COST(256 - (old), 256 - (new))
631
632                 double size0 = COST2(i,  i) + COST2(i2, i2);
633                 double sizeX = COST2(i, i2) + COST2(i2, i);
634                 if (size0 - sizeX > size0*(1e-14) && i != 128 && i2 != 128) {
635                     int j;
636                     FFSWAP(int, stt[i], stt[i2]);
637                     FFSWAP(int, s->rc_stat[i][0], s->rc_stat[i2][0]);
638                     FFSWAP(int, s->rc_stat[i][1], s->rc_stat[i2][1]);
639                     if (i != 256 - i2) {
640                         FFSWAP(int, stt[256 - i], stt[256 - i2]);
641                         FFSWAP(int, s->rc_stat[256 - i][0], s->rc_stat[256 - i2][0]);
642                         FFSWAP(int, s->rc_stat[256 - i][1], s->rc_stat[256 - i2][1]);
643                     }
644                     for (j = 1; j < 256; j++) {
645                         if (stt[j] == i)
646                             stt[j] = i2;
647                         else if (stt[j] == i2)
648                             stt[j] = i;
649                         if (i != 256 - i2) {
650                             if (stt[256 - j] == 256 - i)
651                                 stt[256 - j] = 256 - i2;
652                             else if (stt[256 - j] == 256 - i2)
653                                 stt[256 - j] = 256 - i;
654                         }
655                     }
656                     print = changed = 1;
657                 }
658             }
659         }
660     } while (changed);
661     return print;
662 }
663
664 static av_cold int encode_init(AVCodecContext *avctx)
665 {
666     FFV1Context *s = avctx->priv_data;
667     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
668     int i, j, k, m, ret;
669
670     if ((ret = ff_ffv1_common_init(avctx)) < 0)
671         return ret;
672
673     s->version = 0;
674
675     if ((avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) ||
676         avctx->slices > 1)
677         s->version = FFMAX(s->version, 2);
678
679     // Unspecified level & slices, we choose version 1.2+ to ensure multithreaded decodability
680     if (avctx->slices == 0 && avctx->level < 0 && avctx->width * avctx->height > 720*576)
681         s->version = FFMAX(s->version, 2);
682
683     if (avctx->level <= 0 && s->version == 2) {
684         s->version = 3;
685     }
686     if (avctx->level >= 0 && avctx->level <= 4) {
687         if (avctx->level < s->version) {
688             av_log(avctx, AV_LOG_ERROR, "Version %d needed for requested features but %d requested\n", s->version, avctx->level);
689             return AVERROR(EINVAL);
690         }
691         s->version = avctx->level;
692     }
693
694     if (s->ec < 0) {
695         s->ec = (s->version >= 3);
696     }
697
698     if ((s->version == 2 || s->version>3) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
699         av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n");
700         return AVERROR_INVALIDDATA;
701     }
702
703     s->ac = avctx->coder_type > 0 ? 2 : 0;
704
705     s->plane_count = 3;
706     switch(avctx->pix_fmt) {
707     case AV_PIX_FMT_YUV444P9:
708     case AV_PIX_FMT_YUV422P9:
709     case AV_PIX_FMT_YUV420P9:
710     case AV_PIX_FMT_YUVA444P9:
711     case AV_PIX_FMT_YUVA422P9:
712     case AV_PIX_FMT_YUVA420P9:
713         if (!avctx->bits_per_raw_sample)
714             s->bits_per_raw_sample = 9;
715     case AV_PIX_FMT_YUV444P10:
716     case AV_PIX_FMT_YUV420P10:
717     case AV_PIX_FMT_YUV422P10:
718     case AV_PIX_FMT_YUVA444P10:
719     case AV_PIX_FMT_YUVA422P10:
720     case AV_PIX_FMT_YUVA420P10:
721         s->packed_at_lsb = 1;
722         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
723             s->bits_per_raw_sample = 10;
724     case AV_PIX_FMT_GRAY16:
725     case AV_PIX_FMT_YUV444P16:
726     case AV_PIX_FMT_YUV422P16:
727     case AV_PIX_FMT_YUV420P16:
728     case AV_PIX_FMT_YUVA444P16:
729     case AV_PIX_FMT_YUVA422P16:
730     case AV_PIX_FMT_YUVA420P16:
731         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {
732             s->bits_per_raw_sample = 16;
733         } else if (!s->bits_per_raw_sample) {
734             s->bits_per_raw_sample = avctx->bits_per_raw_sample;
735         }
736         if (s->bits_per_raw_sample <= 8) {
737             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
738             return AVERROR_INVALIDDATA;
739         }
740         if (!s->ac && avctx->coder_type == -1) {
741             av_log(avctx, AV_LOG_INFO, "bits_per_raw_sample > 8, forcing coder 1\n");
742             s->ac = 2;
743         }
744         if (!s->ac) {
745             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
746             return AVERROR(ENOSYS);
747         }
748         s->version = FFMAX(s->version, 1);
749     case AV_PIX_FMT_GRAY8:
750     case AV_PIX_FMT_YUV444P:
751     case AV_PIX_FMT_YUV440P:
752     case AV_PIX_FMT_YUV422P:
753     case AV_PIX_FMT_YUV420P:
754     case AV_PIX_FMT_YUV411P:
755     case AV_PIX_FMT_YUV410P:
756     case AV_PIX_FMT_YUVA444P:
757     case AV_PIX_FMT_YUVA422P:
758     case AV_PIX_FMT_YUVA420P:
759         s->chroma_planes = desc->nb_components < 3 ? 0 : 1;
760         s->colorspace = 0;
761         s->transparency = desc->nb_components == 4;
762         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
763             s->bits_per_raw_sample = 8;
764         else if (!s->bits_per_raw_sample)
765             s->bits_per_raw_sample = 8;
766         break;
767     case AV_PIX_FMT_RGB32:
768         s->colorspace = 1;
769         s->transparency = 1;
770         s->chroma_planes = 1;
771         if (!avctx->bits_per_raw_sample)
772             s->bits_per_raw_sample = 8;
773         break;
774     case AV_PIX_FMT_0RGB32:
775         s->colorspace = 1;
776         s->chroma_planes = 1;
777         if (!avctx->bits_per_raw_sample)
778             s->bits_per_raw_sample = 8;
779         break;
780     case AV_PIX_FMT_GBRP9:
781         if (!avctx->bits_per_raw_sample)
782             s->bits_per_raw_sample = 9;
783     case AV_PIX_FMT_GBRP10:
784         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
785             s->bits_per_raw_sample = 10;
786     case AV_PIX_FMT_GBRP12:
787         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
788             s->bits_per_raw_sample = 12;
789     case AV_PIX_FMT_GBRP14:
790         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
791             s->bits_per_raw_sample = 14;
792         else if (!s->bits_per_raw_sample)
793             s->bits_per_raw_sample = avctx->bits_per_raw_sample;
794         s->colorspace = 1;
795         s->chroma_planes = 1;
796         s->version = FFMAX(s->version, 1);
797         if (!s->ac && avctx->coder_type == -1) {
798             av_log(avctx, AV_LOG_INFO, "bits_per_raw_sample > 8, forcing coder 1\n");
799             s->ac = 2;
800         }
801         if (!s->ac) {
802             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");
803             return AVERROR(ENOSYS);
804         }
805         break;
806     default:
807         av_log(avctx, AV_LOG_ERROR, "format not supported\n");
808         return AVERROR(ENOSYS);
809     }
810     av_assert0(s->bits_per_raw_sample >= 8);
811
812     if (s->transparency) {
813         av_log(avctx, AV_LOG_WARNING, "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");
814     }
815     if (avctx->context_model > 1U) {
816         av_log(avctx, AV_LOG_ERROR, "Invalid context model %d, valid values are 0 and 1\n", avctx->context_model);
817         return AVERROR(EINVAL);
818     }
819
820     if (s->ac > 1)
821         for (i = 1; i < 256; i++)
822             s->state_transition[i] = ver2_state[i];
823
824     for (i = 0; i < 256; i++) {
825         s->quant_table_count = 2;
826         if (s->bits_per_raw_sample <= 8) {
827             s->quant_tables[0][0][i]=           quant11[i];
828             s->quant_tables[0][1][i]=        11*quant11[i];
829             s->quant_tables[0][2][i]=     11*11*quant11[i];
830             s->quant_tables[1][0][i]=           quant11[i];
831             s->quant_tables[1][1][i]=        11*quant11[i];
832             s->quant_tables[1][2][i]=     11*11*quant5 [i];
833             s->quant_tables[1][3][i]=   5*11*11*quant5 [i];
834             s->quant_tables[1][4][i]= 5*5*11*11*quant5 [i];
835         } else {
836             s->quant_tables[0][0][i]=           quant9_10bit[i];
837             s->quant_tables[0][1][i]=        11*quant9_10bit[i];
838             s->quant_tables[0][2][i]=     11*11*quant9_10bit[i];
839             s->quant_tables[1][0][i]=           quant9_10bit[i];
840             s->quant_tables[1][1][i]=        11*quant9_10bit[i];
841             s->quant_tables[1][2][i]=     11*11*quant5_10bit[i];
842             s->quant_tables[1][3][i]=   5*11*11*quant5_10bit[i];
843             s->quant_tables[1][4][i]= 5*5*11*11*quant5_10bit[i];
844         }
845     }
846     s->context_count[0] = (11 * 11 * 11        + 1) / 2;
847     s->context_count[1] = (11 * 11 * 5 * 5 * 5 + 1) / 2;
848     memcpy(s->quant_table, s->quant_tables[avctx->context_model],
849            sizeof(s->quant_table));
850
851     for (i = 0; i < s->plane_count; i++) {
852         PlaneContext *const p = &s->plane[i];
853
854         memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));
855         p->quant_table_index = avctx->context_model;
856         p->context_count     = s->context_count[p->quant_table_index];
857     }
858
859     if ((ret = ff_ffv1_allocate_initial_states(s)) < 0)
860         return ret;
861
862 #if FF_API_CODED_FRAME
863 FF_DISABLE_DEPRECATION_WARNINGS
864     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
865 FF_ENABLE_DEPRECATION_WARNINGS
866 #endif
867
868     if (!s->transparency)
869         s->plane_count = 2;
870     if (!s->chroma_planes && s->version > 3)
871         s->plane_count--;
872
873     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift, &s->chroma_v_shift);
874     s->picture_number = 0;
875
876     if (avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) {
877         for (i = 0; i < s->quant_table_count; i++) {
878             s->rc_stat2[i] = av_mallocz(s->context_count[i] *
879                                         sizeof(*s->rc_stat2[i]));
880             if (!s->rc_stat2[i])
881                 return AVERROR(ENOMEM);
882         }
883     }
884     if (avctx->stats_in) {
885         char *p = avctx->stats_in;
886         uint8_t (*best_state)[256] = av_malloc_array(256, 256);
887         int gob_count = 0;
888         char *next;
889         if (!best_state)
890             return AVERROR(ENOMEM);
891
892         av_assert0(s->version >= 2);
893
894         for (;;) {
895             for (j = 0; j < 256; j++)
896                 for (i = 0; i < 2; i++) {
897                     s->rc_stat[j][i] = strtol(p, &next, 0);
898                     if (next == p) {
899                         av_log(avctx, AV_LOG_ERROR,
900                                "2Pass file invalid at %d %d [%s]\n", j, i, p);
901                         av_freep(&best_state);
902                         return AVERROR_INVALIDDATA;
903                     }
904                     p = next;
905                 }
906             for (i = 0; i < s->quant_table_count; i++)
907                 for (j = 0; j < s->context_count[i]; j++) {
908                     for (k = 0; k < 32; k++)
909                         for (m = 0; m < 2; m++) {
910                             s->rc_stat2[i][j][k][m] = strtol(p, &next, 0);
911                             if (next == p) {
912                                 av_log(avctx, AV_LOG_ERROR,
913                                        "2Pass file invalid at %d %d %d %d [%s]\n",
914                                        i, j, k, m, p);
915                                 av_freep(&best_state);
916                                 return AVERROR_INVALIDDATA;
917                             }
918                             p = next;
919                         }
920                 }
921             gob_count = strtol(p, &next, 0);
922             if (next == p || gob_count <= 0) {
923                 av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");
924                 av_freep(&best_state);
925                 return AVERROR_INVALIDDATA;
926             }
927             p = next;
928             while (*p == '\n' || *p == ' ')
929                 p++;
930             if (p[0] == 0)
931                 break;
932         }
933         sort_stt(s, s->state_transition);
934
935         find_best_state(best_state, s->state_transition);
936
937         for (i = 0; i < s->quant_table_count; i++) {
938             for (k = 0; k < 32; k++) {
939                 double a=0, b=0;
940                 int jp = 0;
941                 for (j = 0; j < s->context_count[i]; j++) {
942                     double p = 128;
943                     if (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1] > 200 && j || a+b > 200) {
944                         if (a+b)
945                             p = 256.0 * b / (a + b);
946                         s->initial_states[i][jp][k] =
947                             best_state[av_clip(round(p), 1, 255)][av_clip_uint8((a + b) / gob_count)];
948                         for(jp++; jp<j; jp++)
949                             s->initial_states[i][jp][k] = s->initial_states[i][jp-1][k];
950                         a=b=0;
951                     }
952                     a += s->rc_stat2[i][j][k][0];
953                     b += s->rc_stat2[i][j][k][1];
954                     if (a+b) {
955                         p = 256.0 * b / (a + b);
956                     }
957                     s->initial_states[i][j][k] =
958                         best_state[av_clip(round(p), 1, 255)][av_clip_uint8((a + b) / gob_count)];
959                 }
960             }
961         }
962         av_freep(&best_state);
963     }
964
965     if (s->version > 1) {
966         s->num_v_slices = (avctx->width > 352 || avctx->height > 288 || !avctx->slices) ? 2 : 1;
967         for (; s->num_v_slices < 9; s->num_v_slices++) {
968             for (s->num_h_slices = s->num_v_slices; s->num_h_slices < 2*s->num_v_slices; s->num_h_slices++) {
969                 if (avctx->slices == s->num_h_slices * s->num_v_slices && avctx->slices <= 64 || !avctx->slices)
970                     goto slices_ok;
971             }
972         }
973         av_log(avctx, AV_LOG_ERROR,
974                "Unsupported number %d of slices requested, please specify a "
975                "supported number with -slices (ex:4,6,9,12,16, ...)\n",
976                avctx->slices);
977         return AVERROR(ENOSYS);
978 slices_ok:
979         if ((ret = write_extradata(s)) < 0)
980             return ret;
981     }
982
983     if ((ret = ff_ffv1_init_slice_contexts(s)) < 0)
984         return ret;
985     s->slice_count = s->max_slice_count;
986     if ((ret = ff_ffv1_init_slices_state(s)) < 0)
987         return ret;
988
989 #define STATS_OUT_SIZE 1024 * 1024 * 6
990     if (avctx->flags & AV_CODEC_FLAG_PASS1) {
991         avctx->stats_out = av_mallocz(STATS_OUT_SIZE);
992         if (!avctx->stats_out)
993             return AVERROR(ENOMEM);
994         for (i = 0; i < s->quant_table_count; i++)
995             for (j = 0; j < s->max_slice_count; j++) {
996                 FFV1Context *sf = s->slice_context[j];
997                 av_assert0(!sf->rc_stat2[i]);
998                 sf->rc_stat2[i] = av_mallocz(s->context_count[i] *
999                                              sizeof(*sf->rc_stat2[i]));
1000                 if (!sf->rc_stat2[i])
1001                     return AVERROR(ENOMEM);
1002             }
1003     }
1004
1005     return 0;
1006 }
1007
1008 static void encode_slice_header(FFV1Context *f, FFV1Context *fs)
1009 {
1010     RangeCoder *c = &fs->c;
1011     uint8_t state[CONTEXT_SIZE];
1012     int j;
1013     memset(state, 128, sizeof(state));
1014
1015     put_symbol(c, state, (fs->slice_x     +1)*f->num_h_slices / f->width   , 0);
1016     put_symbol(c, state, (fs->slice_y     +1)*f->num_v_slices / f->height  , 0);
1017     put_symbol(c, state, (fs->slice_width +1)*f->num_h_slices / f->width -1, 0);
1018     put_symbol(c, state, (fs->slice_height+1)*f->num_v_slices / f->height-1, 0);
1019     for (j=0; j<f->plane_count; j++) {
1020         put_symbol(c, state, f->plane[j].quant_table_index, 0);
1021         av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);
1022     }
1023     if (!f->picture.f->interlaced_frame)
1024         put_symbol(c, state, 3, 0);
1025     else
1026         put_symbol(c, state, 1 + !f->picture.f->top_field_first, 0);
1027     put_symbol(c, state, f->picture.f->sample_aspect_ratio.num, 0);
1028     put_symbol(c, state, f->picture.f->sample_aspect_ratio.den, 0);
1029     if (f->version > 3) {
1030         put_rac(c, state, fs->slice_coding_mode == 1);
1031         if (fs->slice_coding_mode == 1)
1032             ff_ffv1_clear_slice_state(f, fs);
1033         put_symbol(c, state, fs->slice_coding_mode, 0);
1034         if (fs->slice_coding_mode != 1) {
1035             put_symbol(c, state, fs->slice_rct_by_coef, 0);
1036             put_symbol(c, state, fs->slice_rct_ry_coef, 0);
1037         }
1038     }
1039 }
1040
1041 static void choose_rct_params(FFV1Context *fs, const uint8_t *src[3], const int stride[3], int w, int h)
1042 {
1043 #define NB_Y_COEFF 15
1044     static const int rct_y_coeff[15][2] = {
1045         {0, 0}, //      4G
1046         {1, 1}, //  R + 2G + B
1047         {2, 2}, // 2R      + 2B
1048         {0, 2}, //      2G + 2B
1049         {2, 0}, // 2R + 2G
1050         {4, 0}, // 4R
1051         {0, 4}, //           4B
1052
1053         {0, 3}, //      1G + 3B
1054         {3, 0}, // 3R + 1G
1055         {3, 1}, // 3R      +  B
1056         {1, 3}, //  R      + 3B
1057         {1, 2}, //  R +  G + 2B
1058         {2, 1}, // 2R +  G +  B
1059         {0, 1}, //      3G +  B
1060         {1, 0}, //  R + 3G
1061     };
1062
1063     int stat[NB_Y_COEFF] = {0};
1064     int x, y, i, p, best;
1065     int16_t *sample[3];
1066     int lbd = fs->bits_per_raw_sample <= 8;
1067
1068     for (y = 0; y < h; y++) {
1069         int lastr=0, lastg=0, lastb=0;
1070         for (p = 0; p < 3; p++)
1071             sample[p] = fs->sample_buffer + p*w;
1072
1073         for (x = 0; x < w; x++) {
1074             int b, g, r;
1075             int ab, ag, ar;
1076             if (lbd) {
1077                 unsigned v = *((const uint32_t*)(src[0] + x*4 + stride[0]*y));
1078                 b =  v        & 0xFF;
1079                 g = (v >>  8) & 0xFF;
1080                 r = (v >> 16) & 0xFF;
1081             } else {
1082                 b = *((const uint16_t*)(src[0] + x*2 + stride[0]*y));
1083                 g = *((const uint16_t*)(src[1] + x*2 + stride[1]*y));
1084                 r = *((const uint16_t*)(src[2] + x*2 + stride[2]*y));
1085             }
1086
1087             ar = r - lastr;
1088             ag = g - lastg;
1089             ab = b - lastb;
1090             if (x && y) {
1091                 int bg = ag - sample[0][x];
1092                 int bb = ab - sample[1][x];
1093                 int br = ar - sample[2][x];
1094
1095                 br -= bg;
1096                 bb -= bg;
1097
1098                 for (i = 0; i<NB_Y_COEFF; i++) {
1099                     stat[i] += FFABS(bg + ((br*rct_y_coeff[i][0] + bb*rct_y_coeff[i][1])>>2));
1100                 }
1101
1102             }
1103             sample[0][x] = ag;
1104             sample[1][x] = ab;
1105             sample[2][x] = ar;
1106
1107             lastr = r;
1108             lastg = g;
1109             lastb = b;
1110         }
1111     }
1112
1113     best = 0;
1114     for (i=1; i<NB_Y_COEFF; i++) {
1115         if (stat[i] < stat[best])
1116             best = i;
1117     }
1118
1119     fs->slice_rct_by_coef = rct_y_coeff[best][1];
1120     fs->slice_rct_ry_coef = rct_y_coeff[best][0];
1121 }
1122
1123 static int encode_slice(AVCodecContext *c, void *arg)
1124 {
1125     FFV1Context *fs  = *(void **)arg;
1126     FFV1Context *f   = fs->avctx->priv_data;
1127     int width        = fs->slice_width;
1128     int height       = fs->slice_height;
1129     int x            = fs->slice_x;
1130     int y            = fs->slice_y;
1131     const AVFrame *const p = f->picture.f;
1132     const int ps     = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step;
1133     int ret;
1134     RangeCoder c_bak = fs->c;
1135     const uint8_t *planes[3] = {p->data[0] + ps*x + y*p->linesize[0],
1136                                 p->data[1] + ps*x + y*p->linesize[1],
1137                                 p->data[2] + ps*x + y*p->linesize[2]};
1138
1139     fs->slice_coding_mode = 0;
1140     if (f->version > 3) {
1141         choose_rct_params(fs, planes, p->linesize, width, height);
1142     } else {
1143         fs->slice_rct_by_coef = 1;
1144         fs->slice_rct_ry_coef = 1;
1145     }
1146
1147 retry:
1148     if (f->key_frame)
1149         ff_ffv1_clear_slice_state(f, fs);
1150     if (f->version > 2) {
1151         encode_slice_header(f, fs);
1152     }
1153     if (!fs->ac) {
1154         if (f->version > 2)
1155             put_rac(&fs->c, (uint8_t[]) { 129 }, 0);
1156         fs->ac_byte_count = f->version > 2 || (!x && !y) ? ff_rac_terminate(&fs->c) : 0;
1157         init_put_bits(&fs->pb,
1158                       fs->c.bytestream_start + fs->ac_byte_count,
1159                       fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count);
1160     }
1161
1162     if (f->colorspace == 0) {
1163         const int chroma_width  = FF_CEIL_RSHIFT(width,  f->chroma_h_shift);
1164         const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift);
1165         const int cx            = x >> f->chroma_h_shift;
1166         const int cy            = y >> f->chroma_v_shift;
1167
1168         ret = encode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);
1169
1170         if (f->chroma_planes) {
1171             ret |= encode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);
1172             ret |= encode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);
1173         }
1174         if (fs->transparency)
1175             ret |= encode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);
1176     } else {
1177         ret = encode_rgb_frame(fs, planes, width, height, p->linesize);
1178     }
1179     emms_c();
1180
1181     if (ret < 0) {
1182         av_assert0(fs->slice_coding_mode == 0);
1183         if (fs->version < 4 || !fs->ac) {
1184             av_log(c, AV_LOG_ERROR, "Buffer too small\n");
1185             return ret;
1186         }
1187         av_log(c, AV_LOG_DEBUG, "Coding slice as PCM\n");
1188         fs->slice_coding_mode = 1;
1189         fs->c = c_bak;
1190         goto retry;
1191     }
1192
1193     return 0;
1194 }
1195
1196 static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1197                         const AVFrame *pict, int *got_packet)
1198 {
1199     FFV1Context *f      = avctx->priv_data;
1200     RangeCoder *const c = &f->slice_context[0]->c;
1201     AVFrame *const p    = f->picture.f;
1202     int used_count      = 0;
1203     uint8_t keystate    = 128;
1204     uint8_t *buf_p;
1205     int i, ret;
1206     int64_t maxsize =   AV_INPUT_BUFFER_MIN_SIZE
1207                       + avctx->width*avctx->height*35LL*4;
1208
1209     if(!pict) {
1210         if (avctx->flags & AV_CODEC_FLAG_PASS1) {
1211             int j, k, m;
1212             char *p   = avctx->stats_out;
1213             char *end = p + STATS_OUT_SIZE;
1214
1215             memset(f->rc_stat, 0, sizeof(f->rc_stat));
1216             for (i = 0; i < f->quant_table_count; i++)
1217                 memset(f->rc_stat2[i], 0, f->context_count[i] * sizeof(*f->rc_stat2[i]));
1218
1219             av_assert0(f->slice_count == f->max_slice_count);
1220             for (j = 0; j < f->slice_count; j++) {
1221                 FFV1Context *fs = f->slice_context[j];
1222                 for (i = 0; i < 256; i++) {
1223                     f->rc_stat[i][0] += fs->rc_stat[i][0];
1224                     f->rc_stat[i][1] += fs->rc_stat[i][1];
1225                 }
1226                 for (i = 0; i < f->quant_table_count; i++) {
1227                     for (k = 0; k < f->context_count[i]; k++)
1228                         for (m = 0; m < 32; m++) {
1229                             f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];
1230                             f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];
1231                         }
1232                 }
1233             }
1234
1235             for (j = 0; j < 256; j++) {
1236                 snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",
1237                         f->rc_stat[j][0], f->rc_stat[j][1]);
1238                 p += strlen(p);
1239             }
1240             snprintf(p, end - p, "\n");
1241
1242             for (i = 0; i < f->quant_table_count; i++) {
1243                 for (j = 0; j < f->context_count[i]; j++)
1244                     for (m = 0; m < 32; m++) {
1245                         snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",
1246                                 f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);
1247                         p += strlen(p);
1248                     }
1249             }
1250             snprintf(p, end - p, "%d\n", f->gob_count);
1251         }
1252         return 0;
1253     }
1254
1255     if (f->version > 3)
1256         maxsize = AV_INPUT_BUFFER_MIN_SIZE + avctx->width*avctx->height*3LL*4;
1257
1258     if ((ret = ff_alloc_packet2(avctx, pkt, maxsize, 0)) < 0)
1259         return ret;
1260
1261     ff_init_range_encoder(c, pkt->data, pkt->size);
1262     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
1263
1264     av_frame_unref(p);
1265     if ((ret = av_frame_ref(p, pict)) < 0)
1266         return ret;
1267     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1268
1269     if (avctx->gop_size == 0 || f->picture_number % avctx->gop_size == 0) {
1270         put_rac(c, &keystate, 1);
1271         f->key_frame = 1;
1272         f->gob_count++;
1273         write_header(f);
1274     } else {
1275         put_rac(c, &keystate, 0);
1276         f->key_frame = 0;
1277     }
1278
1279     if (f->ac > 1) {
1280         int i;
1281         for (i = 1; i < 256; i++) {
1282             c->one_state[i]        = f->state_transition[i];
1283             c->zero_state[256 - i] = 256 - c->one_state[i];
1284         }
1285     }
1286
1287     for (i = 1; i < f->slice_count; i++) {
1288         FFV1Context *fs = f->slice_context[i];
1289         uint8_t *start  = pkt->data + (pkt->size - used_count) * (int64_t)i / f->slice_count;
1290         int len         = pkt->size / f->slice_count;
1291         ff_init_range_encoder(&fs->c, start, len);
1292     }
1293     avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL,
1294                    f->slice_count, sizeof(void *));
1295
1296     buf_p = pkt->data;
1297     for (i = 0; i < f->slice_count; i++) {
1298         FFV1Context *fs = f->slice_context[i];
1299         int bytes;
1300
1301         if (fs->ac) {
1302             uint8_t state = 129;
1303             put_rac(&fs->c, &state, 0);
1304             bytes = ff_rac_terminate(&fs->c);
1305         } else {
1306             flush_put_bits(&fs->pb); // FIXME: nicer padding
1307             bytes = fs->ac_byte_count + (put_bits_count(&fs->pb) + 7) / 8;
1308         }
1309         if (i > 0 || f->version > 2) {
1310             av_assert0(bytes < pkt->size / f->slice_count);
1311             memmove(buf_p, fs->c.bytestream_start, bytes);
1312             av_assert0(bytes < (1 << 24));
1313             AV_WB24(buf_p + bytes, bytes);
1314             bytes += 3;
1315         }
1316         if (f->ec) {
1317             unsigned v;
1318             buf_p[bytes++] = 0;
1319             v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);
1320             AV_WL32(buf_p + bytes, v);
1321             bytes += 4;
1322         }
1323         buf_p += bytes;
1324     }
1325
1326     if (avctx->flags & AV_CODEC_FLAG_PASS1)
1327         avctx->stats_out[0] = '\0';
1328
1329 #if FF_API_CODED_FRAME
1330 FF_DISABLE_DEPRECATION_WARNINGS
1331     avctx->coded_frame->key_frame = f->key_frame;
1332 FF_ENABLE_DEPRECATION_WARNINGS
1333 #endif
1334
1335     f->picture_number++;
1336     pkt->size   = buf_p - pkt->data;
1337     pkt->pts    =
1338     pkt->dts    = pict->pts;
1339     pkt->flags |= AV_PKT_FLAG_KEY * f->key_frame;
1340     *got_packet = 1;
1341
1342     return 0;
1343 }
1344
1345 static av_cold int encode_close(AVCodecContext *avctx)
1346 {
1347     ff_ffv1_close(avctx);
1348     return 0;
1349 }
1350
1351 #define OFFSET(x) offsetof(FFV1Context, x)
1352 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1353 static const AVOption options[] = {
1354     { "slicecrc", "Protect slices with CRCs", OFFSET(ec), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE },
1355     { NULL }
1356 };
1357
1358 static const AVClass ffv1_class = {
1359     .class_name = "ffv1 encoder",
1360     .item_name  = av_default_item_name,
1361     .option     = options,
1362     .version    = LIBAVUTIL_VERSION_INT,
1363 };
1364
1365 static const AVCodecDefault ffv1_defaults[] = {
1366     { "coder", "-1" },
1367     { NULL },
1368 };
1369
1370 AVCodec ff_ffv1_encoder = {
1371     .name           = "ffv1",
1372     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
1373     .type           = AVMEDIA_TYPE_VIDEO,
1374     .id             = AV_CODEC_ID_FFV1,
1375     .priv_data_size = sizeof(FFV1Context),
1376     .init           = encode_init,
1377     .encode2        = encode_frame,
1378     .close          = encode_close,
1379     .capabilities   = AV_CODEC_CAP_SLICE_THREADS | AV_CODEC_CAP_DELAY,
1380     .pix_fmts       = (const enum AVPixelFormat[]) {
1381         AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUVA420P,  AV_PIX_FMT_YUVA422P,  AV_PIX_FMT_YUV444P,
1382         AV_PIX_FMT_YUVA444P,  AV_PIX_FMT_YUV440P,   AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV411P,
1383         AV_PIX_FMT_YUV410P,   AV_PIX_FMT_0RGB32,    AV_PIX_FMT_RGB32,     AV_PIX_FMT_YUV420P16,
1384         AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16, AV_PIX_FMT_YUV444P9,  AV_PIX_FMT_YUV422P9,
1385         AV_PIX_FMT_YUV420P9,  AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
1386         AV_PIX_FMT_YUVA444P16, AV_PIX_FMT_YUVA422P16, AV_PIX_FMT_YUVA420P16,
1387         AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA420P10,
1388         AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA420P9,
1389         AV_PIX_FMT_GRAY16,    AV_PIX_FMT_GRAY8,     AV_PIX_FMT_GBRP9,     AV_PIX_FMT_GBRP10,
1390         AV_PIX_FMT_GBRP12,    AV_PIX_FMT_GBRP14,
1391         AV_PIX_FMT_NONE
1392
1393     },
1394     .defaults       = ffv1_defaults,
1395     .priv_class     = &ffv1_class,
1396 };