]> git.sesse.net Git - ffmpeg/blob - libavcodec/ffv1enc.c
mimic: Convert to the new bitstream reader
[ffmpeg] / libavcodec / ffv1enc.c
1 /*
2  * FFV1 encoder for libavcodec
3  *
4  * Copyright (c) 2003-2012 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav 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  * Libav 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 Libav; 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/pixdesc.h"
31 #include "libavutil/crc.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/imgutils.h"
34
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 void find_best_state(uint8_t best_state[256][256],
44                             const uint8_t one_state[256])
45 {
46     int i, j, k, m;
47     double l2tab[256];
48
49     for (i = 1; i < 256; i++)
50         l2tab[i] = log2(i / 256.0);
51
52     for (i = 0; i < 256; i++) {
53         double best_len[256];
54         double p = i / 256.0;
55
56         for (j = 0; j < 256; j++)
57             best_len[j] = 1 << 30;
58
59         for (j = FFMAX(i - 10, 1); j < FFMIN(i + 11, 256); j++) {
60             double occ[256] = { 0 };
61             double len      = 0;
62             occ[j] = 1.0;
63             for (k = 0; k < 256; k++) {
64                 double newocc[256] = { 0 };
65                 for (m = 1; m < 256; m++)
66                     if (occ[m]) {
67                         len -= occ[m] *     (p  * l2tab[m] +
68                                         (1 - p) * l2tab[256 - m]);
69                     }
70                 if (len < best_len[k]) {
71                     best_len[k]      = len;
72                     best_state[i][k] = j;
73                 }
74                 for (m = 1; m < 256; m++)
75                     if (occ[m]) {
76                         newocc[one_state[m]]             += occ[m] * p;
77                         newocc[256 - one_state[256 - m]] += occ[m] * (1 - p);
78                     }
79                 memcpy(occ, newocc, sizeof(occ));
80             }
81         }
82     }
83 }
84
85 static av_always_inline av_flatten void put_symbol_inline(RangeCoder *c,
86                                                           uint8_t *state, int v,
87                                                           int is_signed,
88                                                           uint64_t rc_stat[256][2],
89                                                           uint64_t rc_stat2[32][2])
90 {
91     int i;
92
93 #define put_rac(C, S, B)                        \
94     do {                                        \
95         if (rc_stat) {                          \
96             rc_stat[*(S)][B]++;                 \
97             rc_stat2[(S) - state][B]++;         \
98         }                                       \
99         put_rac(C, S, B);                       \
100     } while (0)
101
102     if (v) {
103         const int a = FFABS(v);
104         const int e = av_log2(a);
105         put_rac(c, state + 0, 0);
106         if (e <= 9) {
107             for (i = 0; i < e; i++)
108                 put_rac(c, state + 1 + i, 1);  // 1..10
109             put_rac(c, state + 1 + i, 0);
110
111             for (i = e - 1; i >= 0; i--)
112                 put_rac(c, state + 22 + i, (a >> i) & 1);  // 22..31
113
114             if (is_signed)
115                 put_rac(c, state + 11 + e, v < 0);  // 11..21
116         } else {
117             for (i = 0; i < e; i++)
118                 put_rac(c, state + 1 + FFMIN(i, 9), 1);  // 1..10
119             put_rac(c, state + 1 + 9, 0);
120
121             for (i = e - 1; i >= 0; i--)
122                 put_rac(c, state + 22 + FFMIN(i, 9), (a >> i) & 1);  // 22..31
123
124             if (is_signed)
125                 put_rac(c, state + 11 + 10, v < 0);  // 11..21
126         }
127     } else {
128         put_rac(c, state + 0, 1);
129     }
130 #undef put_rac
131 }
132
133 static av_noinline void put_symbol(RangeCoder *c, uint8_t *state,
134                                    int v, int is_signed)
135 {
136     put_symbol_inline(c, state, v, is_signed, NULL, NULL);
137 }
138
139 static inline void put_vlc_symbol(PutBitContext *pb, VlcState *const state,
140                                   int v, int bits)
141 {
142     int i, k, code;
143     v = fold(v - state->bias, bits);
144
145     i = state->count;
146     k = 0;
147     while (i < state->error_sum) { // FIXME: optimize
148         k++;
149         i += i;
150     }
151
152     assert(k <= 13);
153
154     code = v ^ ((2 * state->drift + state->count) >> 31);
155
156     ff_dlog(NULL, "v:%d/%d bias:%d error:%d drift:%d count:%d k:%d\n", v, code,
157             state->bias, state->error_sum, state->drift, state->count, k);
158     set_sr_golomb(pb, code, k, 12, bits);
159
160     update_vlc_state(state, v);
161 }
162
163 static av_always_inline int encode_line(FFV1Context *s, int w,
164                                         int16_t *sample[3],
165                                         int plane_index, int bits)
166 {
167     PlaneContext *const p = &s->plane[plane_index];
168     RangeCoder *const c   = &s->c;
169     int x;
170     int run_index = s->run_index;
171     int run_count = 0;
172     int run_mode  = 0;
173
174     if (s->ac != AC_GOLOMB_RICE) {
175         if (c->bytestream_end - c->bytestream < w * 20) {
176             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
177             return AVERROR_INVALIDDATA;
178         }
179     } else {
180         if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) < w * 4) {
181             av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
182             return AVERROR_INVALIDDATA;
183         }
184     }
185
186     for (x = 0; x < w; x++) {
187         int diff, context;
188
189         context = get_context(p, sample[0] + x, sample[1] + x, sample[2] + x);
190         diff    = sample[0][x] - predict(sample[0] + x, sample[1] + x);
191
192         if (context < 0) {
193             context = -context;
194             diff    = -diff;
195         }
196
197         diff = fold(diff, bits);
198
199         if (s->ac != AC_GOLOMB_RICE) {
200             if (s->flags & AV_CODEC_FLAG_PASS1) {
201                 put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat,
202                                   s->rc_stat2[p->quant_table_index][context]);
203             } else {
204                 put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);
205             }
206         } else {
207             if (context == 0)
208                 run_mode = 1;
209
210             if (run_mode) {
211                 if (diff) {
212                     while (run_count >= 1 << ff_log2_run[run_index]) {
213                         run_count -= 1 << ff_log2_run[run_index];
214                         run_index++;
215                         put_bits(&s->pb, 1, 1);
216                     }
217
218                     put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);
219                     if (run_index)
220                         run_index--;
221                     run_count = 0;
222                     run_mode  = 0;
223                     if (diff > 0)
224                         diff--;
225                 } else {
226                     run_count++;
227                 }
228             }
229
230             ff_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",
231                     run_count, run_index, run_mode, x,
232                     (int)put_bits_count(&s->pb));
233
234             if (run_mode == 0)
235                 put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);
236         }
237     }
238     if (run_mode) {
239         while (run_count >= 1 << ff_log2_run[run_index]) {
240             run_count -= 1 << ff_log2_run[run_index];
241             run_index++;
242             put_bits(&s->pb, 1, 1);
243         }
244
245         if (run_count)
246             put_bits(&s->pb, 1, 1);
247     }
248     s->run_index = run_index;
249
250     return 0;
251 }
252
253 static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h,
254                          int stride, int plane_index)
255 {
256     int x, y, i;
257     const int ring_size = s->context_model ? 3 : 2;
258     int16_t *sample[3];
259     s->run_index = 0;
260
261     memset(s->sample_buffer, 0, ring_size * (w + 6) * sizeof(*s->sample_buffer));
262
263     for (y = 0; y < h; y++) {
264         for (i = 0; i < ring_size; i++)
265             sample[i] = s->sample_buffer + (w + 6) * ((h + i - y) % ring_size) + 3;
266
267         sample[0][-1] = sample[1][0];
268         sample[1][w]  = sample[1][w - 1];
269 // { START_TIMER
270         if (s->bits_per_raw_sample <= 8) {
271             for (x = 0; x < w; x++)
272                 sample[0][x] = src[x + stride * y];
273             encode_line(s, w, sample, plane_index, 8);
274         } else {
275             if (s->packed_at_lsb) {
276                 for (x = 0; x < w; x++)
277                     sample[0][x] = ((uint16_t *)(src + stride * y))[x];
278             } else {
279                 for (x = 0; x < w; x++)
280                     sample[0][x] =
281                         ((uint16_t *)(src + stride * y))[x] >> (16 - s->bits_per_raw_sample);
282             }
283             encode_line(s, w, sample, plane_index, s->bits_per_raw_sample);
284         }
285 // STOP_TIMER("encode line") }
286     }
287 }
288
289 static void encode_rgb_frame(FFV1Context *s, const uint8_t *src[3],
290                              int w, int h, const int stride[3])
291 {
292     int x, y, p, i;
293     const int ring_size = s->context_model ? 3 : 2;
294     int16_t *sample[MAX_PLANES][3];
295     int lbd  = s->avctx->bits_per_raw_sample <= 8;
296     int bits = s->avctx->bits_per_raw_sample > 0
297                ? s->avctx->bits_per_raw_sample
298                : 8;
299     int offset = 1 << bits;
300
301     s->run_index = 0;
302
303     memset(s->sample_buffer, 0, ring_size * MAX_PLANES *
304                                 (w + 6) * sizeof(*s->sample_buffer));
305
306     for (y = 0; y < h; y++) {
307         for (i = 0; i < ring_size; i++)
308             for (p = 0; p < MAX_PLANES; p++)
309                 sample[p][i] = s->sample_buffer + p * ring_size *
310                                (w + 6) +
311                                ((h + i - y) % ring_size) * (w + 6) + 3;
312
313         for (x = 0; x < w; x++) {
314             int b, g, r, av_uninit(a);
315             if (lbd) {
316                 unsigned v = *((const uint32_t *)(src[0] + x * 4 + stride[0] * y));
317                 b = v & 0xFF;
318                 g = (v >> 8) & 0xFF;
319                 r = (v >> 16) & 0xFF;
320                 a = v >> 24;
321             } else {
322                 b = *((const uint16_t *)(src[0] + x * 2 + stride[0] * y));
323                 g = *((const uint16_t *)(src[1] + x * 2 + stride[1] * y));
324                 r = *((const uint16_t *)(src[2] + x * 2 + stride[2] * y));
325             }
326
327             b -= g;
328             r -= g;
329             g += (b + r) >> 2;
330             b += offset;
331             r += offset;
332
333             sample[0][0][x] = g;
334             sample[1][0][x] = b;
335             sample[2][0][x] = r;
336             sample[3][0][x] = a;
337         }
338         for (p = 0; p < 3 + s->transparency; p++) {
339             sample[p][0][-1] = sample[p][1][0];
340             sample[p][1][w]  = sample[p][1][w - 1];
341             if (lbd)
342                 encode_line(s, w, sample[p], (p + 1) / 2, 9);
343             else
344                 encode_line(s, w, sample[p], (p + 1) / 2, bits + 1);
345         }
346     }
347 }
348
349
350 static void write_quant_table(RangeCoder *c, int16_t *quant_table)
351 {
352     int last = 0;
353     int i;
354     uint8_t state[CONTEXT_SIZE];
355     memset(state, 128, sizeof(state));
356
357     for (i = 1; i < 128; i++)
358         if (quant_table[i] != quant_table[i - 1]) {
359             put_symbol(c, state, i - last - 1, 0);
360             last = i;
361         }
362     put_symbol(c, state, i - last - 1, 0);
363 }
364
365 static void write_quant_tables(RangeCoder *c,
366                                int16_t quant_table[MAX_CONTEXT_INPUTS][256])
367 {
368     int i;
369     for (i = 0; i < 5; i++)
370         write_quant_table(c, quant_table[i]);
371 }
372
373 static void write_header(FFV1Context *f)
374 {
375     uint8_t state[CONTEXT_SIZE];
376     int i;
377     RangeCoder *const c = &f->slice_context[0]->c;
378
379     memset(state, 128, sizeof(state));
380
381     if (f->version < 2) {
382         put_symbol(c, state, f->version, 0);
383         put_symbol(c, state, f->ac, 0);
384         if (f->ac == AC_RANGE_CUSTOM_TAB) {
385             for (i = 1; i < 256; i++)
386                 put_symbol(c, state,
387                            f->state_transition[i] - c->one_state[i], 1);
388         }
389         put_symbol(c, state, f->colorspace, 0); // YUV cs type
390         if (f->version > 0)
391             put_symbol(c, state, f->bits_per_raw_sample, 0);
392         put_rac(c, state, f->chroma_planes);
393         put_symbol(c, state, f->chroma_h_shift, 0);
394         put_symbol(c, state, f->chroma_v_shift, 0);
395         put_rac(c, state, f->transparency);
396
397         write_quant_tables(c, f->quant_table);
398     }
399 }
400
401 static int write_extradata(FFV1Context *f)
402 {
403     RangeCoder *const c = &f->c;
404     uint8_t state[CONTEXT_SIZE];
405     int i, j, k;
406     uint8_t state2[32][CONTEXT_SIZE];
407     unsigned v;
408
409     memset(state2, 128, sizeof(state2));
410     memset(state, 128, sizeof(state));
411
412     f->avctx->extradata_size = 10000 + 4 +
413                                     (11 * 11 * 5 * 5 * 5 + 11 * 11 * 11) * 32;
414     f->avctx->extradata = av_malloc(f->avctx->extradata_size);
415     ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);
416     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
417
418     put_symbol(c, state, f->version, 0);
419     if (f->version > 1) {
420         if (f->version == 3)
421             f->minor_version = 2;
422         put_symbol(c, state, f->minor_version, 0);
423     }
424
425     put_symbol(c, state, f->ac, 0);
426     if (f->ac == AC_RANGE_CUSTOM_TAB)
427         for (i = 1; i < 256; i++)
428             put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);
429
430     put_symbol(c, state, f->colorspace, 0); // YUV cs type
431     put_symbol(c, state, f->bits_per_raw_sample, 0);
432     put_rac(c, state, f->chroma_planes);
433     put_symbol(c, state, f->chroma_h_shift, 0);
434     put_symbol(c, state, f->chroma_v_shift, 0);
435     put_rac(c, state, f->transparency);
436     put_symbol(c, state, f->num_h_slices - 1, 0);
437     put_symbol(c, state, f->num_v_slices - 1, 0);
438
439     put_symbol(c, state, f->quant_table_count, 0);
440     for (i = 0; i < f->quant_table_count; i++)
441         write_quant_tables(c, f->quant_tables[i]);
442
443     for (i = 0; i < f->quant_table_count; i++) {
444         for (j = 0; j < f->context_count[i] * CONTEXT_SIZE; j++)
445             if (f->initial_states[i] && f->initial_states[i][0][j] != 128)
446                 break;
447         if (j < f->context_count[i] * CONTEXT_SIZE) {
448             put_rac(c, state, 1);
449             for (j = 0; j < f->context_count[i]; j++)
450                 for (k = 0; k < CONTEXT_SIZE; k++) {
451                     int pred = j ? f->initial_states[i][j - 1][k] : 128;
452                     put_symbol(c, state2[k],
453                                (int8_t)(f->initial_states[i][j][k] - pred), 1);
454                 }
455         } else {
456             put_rac(c, state, 0);
457         }
458     }
459
460     if (f->version > 2) {
461         put_symbol(c, state, f->ec, 0);
462     }
463
464     f->avctx->extradata_size = ff_rac_terminate(c);
465
466     v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0,
467                f->avctx->extradata, f->avctx->extradata_size);
468     AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);
469     f->avctx->extradata_size += 4;
470
471     return 0;
472 }
473
474 static int sort_stt(FFV1Context *s, uint8_t stt[256])
475 {
476     int i, i2, changed, print = 0;
477
478     do {
479         changed = 0;
480         for (i = 12; i < 244; i++) {
481             for (i2 = i + 1; i2 < 245 && i2 < i + 4; i2++) {
482
483 #define COST(old, new)                                      \
484     s->rc_stat[old][0] * -log2((256 - (new)) / 256.0) +     \
485     s->rc_stat[old][1] * -log2((new)         / 256.0)
486
487 #define COST2(old, new)                         \
488     COST(old, new) + COST(256 - (old), 256 - (new))
489
490                 double size0 = COST2(i,  i) + COST2(i2, i2);
491                 double sizeX = COST2(i, i2) + COST2(i2, i);
492                 if (sizeX < size0 && i != 128 && i2 != 128) {
493                     int j;
494                     FFSWAP(int, stt[i], stt[i2]);
495                     FFSWAP(int, s->rc_stat[i][0], s->rc_stat[i2][0]);
496                     FFSWAP(int, s->rc_stat[i][1], s->rc_stat[i2][1]);
497                     if (i != 256 - i2) {
498                         FFSWAP(int, stt[256 - i], stt[256 - i2]);
499                         FFSWAP(int, s->rc_stat[256 - i][0], s->rc_stat[256 - i2][0]);
500                         FFSWAP(int, s->rc_stat[256 - i][1], s->rc_stat[256 - i2][1]);
501                     }
502                     for (j = 1; j < 256; j++) {
503                         if (stt[j] == i)
504                             stt[j] = i2;
505                         else if (stt[j] == i2)
506                             stt[j] = i;
507                         if (i != 256 - i2) {
508                             if (stt[256 - j] == 256 - i)
509                                 stt[256 - j] = 256 - i2;
510                             else if (stt[256 - j] == 256 - i2)
511                                 stt[256 - j] = 256 - i;
512                         }
513                     }
514                     print = changed = 1;
515                 }
516             }
517         }
518     } while (changed);
519     return print;
520 }
521
522 static av_cold int init_slices_state(FFV1Context *f)
523 {
524     int i, ret;
525     for (i = 0; i < f->slice_count; i++) {
526         FFV1Context *fs = f->slice_context[i];
527         if ((ret = ffv1_init_slice_state(f, fs)) < 0)
528             return AVERROR(ENOMEM);
529     }
530     return 0;
531 }
532
533 static av_cold int ffv1_encode_init(AVCodecContext *avctx)
534 {
535     FFV1Context *s = avctx->priv_data;
536     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
537     int i, j, k, m, ret;
538
539     ffv1_common_init(avctx);
540
541     s->version = 0;
542
543     switch (avctx->level) {
544     case 3:
545         break;
546     case 2:
547         av_log(avctx, AV_LOG_ERROR,
548                "Version 2 had been deemed non-standard and deprecated "
549                "the support for it had been removed\n");
550         return AVERROR(ENOSYS);
551     case 1:
552     case 0:
553         if (avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) {
554             av_log(avctx, AV_LOG_ERROR,
555                    "Multiple pass encoding requires version 3.\n");
556             return AVERROR(ENOSYS);
557         }
558         if (avctx->slices > 1) {
559             av_log(avctx, AV_LOG_ERROR,
560                    "Multiple slices support requires version 3.\n");
561             return AVERROR(ENOSYS);
562         }
563         break;
564     case FF_LEVEL_UNKNOWN:
565         if ((avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) ||
566             avctx->slices > 1)
567             s->version = 3;
568         else
569             s->version = 0;
570         break;
571     default:
572         av_log(avctx, AV_LOG_ERROR, "Version %d not supported\n",
573                avctx->level);
574         return AVERROR(ENOSYS);
575     }
576
577     if (s->ec < 0) {
578         s->ec = (s->version >= 3);
579     }
580
581 #if FF_API_CODER_TYPE
582 FF_DISABLE_DEPRECATION_WARNINGS
583     if (avctx->coder_type != -1)
584         s->ac = avctx->coder_type > 0 ? AC_RANGE_CUSTOM_TAB : AC_GOLOMB_RICE;
585 FF_ENABLE_DEPRECATION_WARNINGS
586 #endif
587
588     s->plane_count = 3;
589     switch (avctx->pix_fmt) {
590     case AV_PIX_FMT_YUV444P9:
591     case AV_PIX_FMT_YUV422P9:
592     case AV_PIX_FMT_YUV420P9:
593         if (!avctx->bits_per_raw_sample)
594             s->bits_per_raw_sample = 9;
595     case AV_PIX_FMT_YUV444P10:
596     case AV_PIX_FMT_YUV420P10:
597     case AV_PIX_FMT_YUV422P10:
598         s->packed_at_lsb = 1;
599         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
600             s->bits_per_raw_sample = 10;
601     case AV_PIX_FMT_GRAY16:
602     case AV_PIX_FMT_YUV444P16:
603     case AV_PIX_FMT_YUV422P16:
604     case AV_PIX_FMT_YUV420P16:
605         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {
606             s->bits_per_raw_sample = 16;
607         } else if (!s->bits_per_raw_sample) {
608             s->bits_per_raw_sample = avctx->bits_per_raw_sample;
609         }
610         if (s->bits_per_raw_sample <= 8) {
611             av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");
612             return AVERROR_INVALIDDATA;
613         }
614         if (s->ac == AC_GOLOMB_RICE) {
615             av_log(avctx, AV_LOG_INFO,
616                    "bits_per_raw_sample > 8, forcing range coder\n");
617             s->ac = AC_RANGE_CUSTOM_TAB;
618         }
619         s->version = FFMAX(s->version, 1);
620     case AV_PIX_FMT_GRAY8:
621     case AV_PIX_FMT_YUV444P:
622     case AV_PIX_FMT_YUV440P:
623     case AV_PIX_FMT_YUV422P:
624     case AV_PIX_FMT_YUV420P:
625     case AV_PIX_FMT_YUV411P:
626     case AV_PIX_FMT_YUV410P:
627         s->chroma_planes = desc->nb_components < 3 ? 0 : 1;
628         s->colorspace    = 0;
629         break;
630     case AV_PIX_FMT_YUVA444P:
631     case AV_PIX_FMT_YUVA422P:
632     case AV_PIX_FMT_YUVA420P:
633         s->chroma_planes = 1;
634         s->colorspace    = 0;
635         s->transparency  = 1;
636         break;
637     case AV_PIX_FMT_RGB32:
638         s->colorspace   = 1;
639         s->transparency = 1;
640         break;
641     case AV_PIX_FMT_GBRP9:
642         if (!avctx->bits_per_raw_sample)
643             s->bits_per_raw_sample = 9;
644     case AV_PIX_FMT_GBRP10:
645         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
646             s->bits_per_raw_sample = 10;
647     case AV_PIX_FMT_GBRP16:
648         if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)
649             s->bits_per_raw_sample = 16;
650         else if (!s->bits_per_raw_sample)
651             s->bits_per_raw_sample = avctx->bits_per_raw_sample;
652         s->colorspace    = 1;
653         s->chroma_planes = 1;
654         s->version       = FFMAX(s->version, 1);
655         break;
656     default:
657         av_log(avctx, AV_LOG_ERROR, "format not supported\n");
658         return AVERROR_INVALIDDATA;
659     }
660     if (s->transparency) {
661         av_log(
662             avctx, AV_LOG_WARNING,
663             "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");
664     }
665 #if FF_API_PRIVATE_OPT
666 FF_DISABLE_DEPRECATION_WARNINGS
667     if (avctx->context_model)
668         s->context_model = avctx->context_model;
669     if (avctx->context_model > 1U) {
670         av_log(avctx, AV_LOG_ERROR,
671                "Invalid context model %d, valid values are 0 and 1\n",
672                avctx->context_model);
673         return AVERROR(EINVAL);
674     }
675 FF_ENABLE_DEPRECATION_WARNINGS
676 #endif
677
678     if (s->ac == AC_RANGE_CUSTOM_TAB)
679         for (i = 1; i < 256; i++)
680             s->state_transition[i] = ffv1_ver2_state[i];
681
682     for (i = 0; i < 256; i++) {
683         s->quant_table_count = 2;
684         if (s->bits_per_raw_sample <= 8) {
685             s->quant_tables[0][0][i] = ffv1_quant11[i];
686             s->quant_tables[0][1][i] = ffv1_quant11[i] * 11;
687             s->quant_tables[0][2][i] = ffv1_quant11[i] * 11 * 11;
688             s->quant_tables[1][0][i] = ffv1_quant11[i];
689             s->quant_tables[1][1][i] = ffv1_quant11[i] * 11;
690             s->quant_tables[1][2][i] = ffv1_quant5[i]  * 11 * 11;
691             s->quant_tables[1][3][i] = ffv1_quant5[i]  *  5 * 11 * 11;
692             s->quant_tables[1][4][i] = ffv1_quant5[i]  *  5 *  5 * 11 * 11;
693         } else {
694             s->quant_tables[0][0][i] = ffv1_quant9_10bit[i];
695             s->quant_tables[0][1][i] = ffv1_quant9_10bit[i] * 11;
696             s->quant_tables[0][2][i] = ffv1_quant9_10bit[i] * 11 * 11;
697             s->quant_tables[1][0][i] = ffv1_quant9_10bit[i];
698             s->quant_tables[1][1][i] = ffv1_quant9_10bit[i] * 11;
699             s->quant_tables[1][2][i] = ffv1_quant5_10bit[i] * 11 * 11;
700             s->quant_tables[1][3][i] = ffv1_quant5_10bit[i] *  5 * 11 * 11;
701             s->quant_tables[1][4][i] = ffv1_quant5_10bit[i] *  5 *  5 * 11 * 11;
702         }
703     }
704     s->context_count[0] = (11 * 11 * 11        + 1) / 2;
705     s->context_count[1] = (11 * 11 * 5 * 5 * 5 + 1) / 2;
706     memcpy(s->quant_table, s->quant_tables[s->context_model],
707            sizeof(s->quant_table));
708
709     for (i = 0; i < s->plane_count; i++) {
710         PlaneContext *const p = &s->plane[i];
711
712         memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));
713         p->quant_table_index = s->context_model;
714         p->context_count     = s->context_count[p->quant_table_index];
715     }
716
717     if ((ret = ffv1_allocate_initial_states(s)) < 0)
718         return ret;
719
720 #if FF_API_CODED_FRAME
721 FF_DISABLE_DEPRECATION_WARNINGS
722     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
723 FF_ENABLE_DEPRECATION_WARNINGS
724 #endif
725
726     if (!s->transparency)
727         s->plane_count = 2;
728
729     av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift,
730                                      &s->chroma_v_shift);
731
732     s->picture_number = 0;
733
734     if (avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) {
735         for (i = 0; i < s->quant_table_count; i++) {
736             s->rc_stat2[i] = av_mallocz(s->context_count[i] *
737                                         sizeof(*s->rc_stat2[i]));
738             if (!s->rc_stat2[i])
739                 return AVERROR(ENOMEM);
740         }
741     }
742     if (avctx->stats_in) {
743         char *p = avctx->stats_in;
744         uint8_t best_state[256][256];
745         int gob_count = 0;
746         char *next;
747
748         av_assert0(s->version > 2);
749
750         for (;; ) {
751             for (j = 0; j < 256; j++)
752                 for (i = 0; i < 2; i++) {
753                     s->rc_stat[j][i] = strtol(p, &next, 0);
754                     if (next == p) {
755                         av_log(avctx, AV_LOG_ERROR,
756                                "2Pass file invalid at %d %d [%s]\n", j, i, p);
757                         return AVERROR_INVALIDDATA;
758                     }
759                     p = next;
760                 }
761             for (i = 0; i < s->quant_table_count; i++)
762                 for (j = 0; j < s->context_count[i]; j++) {
763                     for (k = 0; k < 32; k++)
764                         for (m = 0; m < 2; m++) {
765                             s->rc_stat2[i][j][k][m] = strtol(p, &next, 0);
766                             if (next == p) {
767                                 av_log(avctx, AV_LOG_ERROR,
768                                        "2Pass file invalid at %d %d %d %d [%s]\n",
769                                        i, j, k, m, p);
770                                 return AVERROR_INVALIDDATA;
771                             }
772                             p = next;
773                         }
774                 }
775             gob_count = strtol(p, &next, 0);
776             if (next == p || gob_count <= 0) {
777                 av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");
778                 return AVERROR_INVALIDDATA;
779             }
780             p = next;
781             while (*p == '\n' || *p == ' ')
782                 p++;
783             if (p[0] == 0)
784                 break;
785         }
786         sort_stt(s, s->state_transition);
787
788         find_best_state(best_state, s->state_transition);
789
790         for (i = 0; i < s->quant_table_count; i++) {
791             for (j = 0; j < s->context_count[i]; j++)
792                 for (k = 0; k < 32; k++) {
793                     double p = 128;
794                     if (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1]) {
795                         p = 256.0 * s->rc_stat2[i][j][k][1] /
796                             (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1]);
797                     }
798                     s->initial_states[i][j][k] =
799                         best_state[av_clip(round(p), 1, 255)][av_clip((s->rc_stat2[i][j][k][0] +
800                                                                        s->rc_stat2[i][j][k][1]) /
801                                                                       gob_count, 0, 255)];
802                 }
803         }
804     }
805
806     if (s->version > 1) {
807         for (s->num_v_slices = 2; s->num_v_slices < 9; s->num_v_slices++)
808             for (s->num_h_slices = s->num_v_slices;
809                  s->num_h_slices < 2 * s->num_v_slices; s->num_h_slices++)
810                 if (avctx->slices == s->num_h_slices * s->num_v_slices &&
811                     avctx->slices <= 64 || !avctx->slices)
812                     goto slices_ok;
813         av_log(avctx, AV_LOG_ERROR,
814                "Unsupported number %d of slices requested, please specify a "
815                "supported number with -slices (ex:4,6,9,12,16, ...)\n",
816                avctx->slices);
817         return AVERROR(ENOSYS);
818 slices_ok:
819         write_extradata(s);
820     }
821
822     if ((ret = ffv1_init_slice_contexts(s)) < 0)
823         return ret;
824     if ((ret = init_slices_state(s)) < 0)
825         return ret;
826
827 #define STATS_OUT_SIZE 1024 * 1024 * 6
828     if (avctx->flags & AV_CODEC_FLAG_PASS1) {
829         avctx->stats_out = av_mallocz(STATS_OUT_SIZE);
830         for (i = 0; i < s->quant_table_count; i++)
831             for (j = 0; j < s->slice_count; j++) {
832                 FFV1Context *sf = s->slice_context[j];
833                 av_assert0(!sf->rc_stat2[i]);
834                 sf->rc_stat2[i] = av_mallocz(s->context_count[i] *
835                                              sizeof(*sf->rc_stat2[i]));
836                 if (!sf->rc_stat2[i])
837                     return AVERROR(ENOMEM);
838             }
839     }
840
841     return 0;
842 }
843
844 static void encode_slice_header(FFV1Context *f, FFV1Context *fs)
845 {
846     RangeCoder *c = &fs->c;
847     uint8_t state[CONTEXT_SIZE];
848     int j;
849     memset(state, 128, sizeof(state));
850
851     put_symbol(c, state, (fs->slice_x + 1) * f->num_h_slices / f->width, 0);
852     put_symbol(c, state, (fs->slice_y + 1) * f->num_v_slices / f->height, 0);
853     put_symbol(c, state, (fs->slice_width + 1) * f->num_h_slices / f->width - 1,
854                0);
855     put_symbol(c, state,
856                (fs->slice_height + 1) * f->num_v_slices / f->height - 1,
857                0);
858     for (j = 0; j < f->plane_count; j++) {
859         put_symbol(c, state, f->plane[j].quant_table_index, 0);
860         av_assert0(f->plane[j].quant_table_index == f->context_model);
861     }
862     if (!f->frame->interlaced_frame)
863         put_symbol(c, state, 3, 0);
864     else
865         put_symbol(c, state, 1 + !f->frame->top_field_first, 0);
866     put_symbol(c, state, f->frame->sample_aspect_ratio.num, 0);
867     put_symbol(c, state, f->frame->sample_aspect_ratio.den, 0);
868 }
869
870 static int encode_slice(AVCodecContext *c, void *arg)
871 {
872     FFV1Context *fs  = *(void **)arg;
873     FFV1Context *f   = fs->avctx->priv_data;
874     int width        = fs->slice_width;
875     int height       = fs->slice_height;
876     int x            = fs->slice_x;
877     int y            = fs->slice_y;
878     const AVFrame *const p = f->frame;
879     const int ps     = (av_pix_fmt_desc_get(c->pix_fmt)->flags & AV_PIX_FMT_FLAG_PLANAR)
880                        ? (f->bits_per_raw_sample > 8) + 1
881                        : 4;
882
883     if (f->key_frame)
884         ffv1_clear_slice_state(f, fs);
885     if (f->version > 2) {
886         encode_slice_header(f, fs);
887     }
888     if (fs->ac == AC_GOLOMB_RICE) {
889         if (f->version > 2)
890             put_rac(&fs->c, (uint8_t[]) { 129 }, 0);
891         fs->ac_byte_count = f->version > 2 || (!x && !y) ? ff_rac_terminate( &fs->c) : 0;
892         init_put_bits(&fs->pb, fs->c.bytestream_start + fs->ac_byte_count,
893                       fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count);
894     }
895
896     if (f->colorspace == 0) {
897         const int chroma_width  = AV_CEIL_RSHIFT(width,  f->chroma_h_shift);
898         const int chroma_height = AV_CEIL_RSHIFT(height, f->chroma_v_shift);
899         const int cx            = x >> f->chroma_h_shift;
900         const int cy            = y >> f->chroma_v_shift;
901
902         encode_plane(fs, p->data[0] + ps * x + y * p->linesize[0],
903                      width, height, p->linesize[0], 0);
904
905         if (f->chroma_planes) {
906             encode_plane(fs, p->data[1] + ps * cx + cy * p->linesize[1],
907                          chroma_width, chroma_height, p->linesize[1], 1);
908             encode_plane(fs, p->data[2] + ps * cx + cy * p->linesize[2],
909                          chroma_width, chroma_height, p->linesize[2], 1);
910         }
911         if (fs->transparency)
912             encode_plane(fs, p->data[3] + ps * x + y * p->linesize[3], width,
913                          height, p->linesize[3], 2);
914     } else {
915         const uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],
916                                      p->data[1] + ps * x + y * p->linesize[1],
917                                      p->data[2] + ps * x + y * p->linesize[2] };
918         encode_rgb_frame(fs, planes, width, height, p->linesize);
919     }
920     emms_c();
921
922     return 0;
923 }
924
925 static int ffv1_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
926                         const AVFrame *pict, int *got_packet)
927 {
928     FFV1Context *f      = avctx->priv_data;
929     RangeCoder *const c = &f->slice_context[0]->c;
930     int used_count      = 0;
931     uint8_t keystate    = 128;
932     uint8_t *buf_p;
933     int i, ret;
934
935     f->frame = pict;
936
937     if ((ret = ff_alloc_packet(pkt, avctx->width * avctx->height *
938                              ((8 * 2 + 1 + 1) * 4) / 8 +
939                              AV_INPUT_BUFFER_MIN_SIZE)) < 0) {
940         av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
941         return ret;
942     }
943
944     ff_init_range_encoder(c, pkt->data, pkt->size);
945     ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);
946
947     if (avctx->gop_size == 0 || f->picture_number % avctx->gop_size == 0) {
948         put_rac(c, &keystate, 1);
949         f->key_frame = 1;
950         f->gob_count++;
951         write_header(f);
952     } else {
953         put_rac(c, &keystate, 0);
954         f->key_frame = 0;
955     }
956
957     if (f->ac == AC_RANGE_CUSTOM_TAB) {
958         int i;
959         for (i = 1; i < 256; i++) {
960             c->one_state[i]        = f->state_transition[i];
961             c->zero_state[256 - i] = 256 - c->one_state[i];
962         }
963     }
964
965     for (i = 1; i < f->slice_count; i++) {
966         FFV1Context *fs = f->slice_context[i];
967         uint8_t *start  = pkt->data +
968                           (pkt->size - used_count) * (int64_t)i / f->slice_count;
969         int len = pkt->size / f->slice_count;
970         ff_init_range_encoder(&fs->c, start, len);
971     }
972     avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL,
973                    f->slice_count, sizeof(void *));
974
975     buf_p = pkt->data;
976     for (i = 0; i < f->slice_count; i++) {
977         FFV1Context *fs = f->slice_context[i];
978         int bytes;
979
980         if (fs->ac != AC_GOLOMB_RICE) {
981             uint8_t state = 129;
982             put_rac(&fs->c, &state, 0);
983             bytes = ff_rac_terminate(&fs->c);
984         } else {
985             flush_put_bits(&fs->pb); // FIXME: nicer padding
986             bytes = fs->ac_byte_count + (put_bits_count(&fs->pb) + 7) / 8;
987         }
988         if (i > 0 || f->version > 2) {
989             av_assert0(bytes < pkt->size / f->slice_count);
990             memmove(buf_p, fs->c.bytestream_start, bytes);
991             av_assert0(bytes < (1 << 24));
992             AV_WB24(buf_p + bytes, bytes);
993             bytes += 3;
994         }
995         if (f->ec) {
996             unsigned v;
997             buf_p[bytes++] = 0;
998             v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);
999             AV_WL32(buf_p + bytes, v);
1000             bytes += 4;
1001         }
1002         buf_p += bytes;
1003     }
1004
1005     if ((avctx->flags & AV_CODEC_FLAG_PASS1) && (f->picture_number & 31) == 0) {
1006         int j, k, m;
1007         char *p   = avctx->stats_out;
1008         char *end = p + STATS_OUT_SIZE;
1009
1010         memset(f->rc_stat, 0, sizeof(f->rc_stat));
1011         for (i = 0; i < f->quant_table_count; i++)
1012             memset(f->rc_stat2[i], 0, f->context_count[i] * sizeof(*f->rc_stat2[i]));
1013
1014         for (j = 0; j < f->slice_count; j++) {
1015             FFV1Context *fs = f->slice_context[j];
1016             for (i = 0; i < 256; i++) {
1017                 f->rc_stat[i][0] += fs->rc_stat[i][0];
1018                 f->rc_stat[i][1] += fs->rc_stat[i][1];
1019             }
1020             for (i = 0; i < f->quant_table_count; i++) {
1021                 for (k = 0; k < f->context_count[i]; k++)
1022                     for (m = 0; m < 32; m++) {
1023                         f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];
1024                         f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];
1025                     }
1026             }
1027         }
1028
1029         for (j = 0; j < 256; j++) {
1030             snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",
1031                      f->rc_stat[j][0], f->rc_stat[j][1]);
1032             p += strlen(p);
1033         }
1034         snprintf(p, end - p, "\n");
1035
1036         for (i = 0; i < f->quant_table_count; i++) {
1037             for (j = 0; j < f->context_count[i]; j++)
1038                 for (m = 0; m < 32; m++) {
1039                     snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",
1040                              f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);
1041                     p += strlen(p);
1042                 }
1043         }
1044         snprintf(p, end - p, "%d\n", f->gob_count);
1045     } else if (avctx->flags & AV_CODEC_FLAG_PASS1)
1046         avctx->stats_out[0] = '\0';
1047
1048 #if FF_API_CODED_FRAME
1049 FF_DISABLE_DEPRECATION_WARNINGS
1050     avctx->coded_frame->key_frame = f->key_frame;
1051 FF_ENABLE_DEPRECATION_WARNINGS
1052 #endif
1053
1054     f->picture_number++;
1055     pkt->size   = buf_p - pkt->data;
1056     pkt->flags |= AV_PKT_FLAG_KEY * f->key_frame;
1057     *got_packet = 1;
1058
1059     return 0;
1060 }
1061
1062 static av_cold int ffv1_encode_close(AVCodecContext *avctx)
1063 {
1064     ffv1_close(avctx);
1065     return 0;
1066 }
1067
1068 #define OFFSET(x) offsetof(FFV1Context, x)
1069 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1070 static const AVOption options[] = {
1071     { "slicecrc", "Protect slices with CRCs", OFFSET(ec), AV_OPT_TYPE_INT,
1072              { .i64 = -1 }, -1, 1, VE },
1073     { "coder", "Coder type", OFFSET(ac), AV_OPT_TYPE_INT,
1074             { .i64 = AC_GOLOMB_RICE }, 0, 2, VE, "coder" },
1075         { "rice", "Golomb rice", 0, AV_OPT_TYPE_CONST,
1076             { .i64 = AC_GOLOMB_RICE }, INT_MIN, INT_MAX, VE, "coder" },
1077         { "range_def", "Range with default table", 0, AV_OPT_TYPE_CONST,
1078             { .i64 = AC_RANGE_DEFAULT_TAB }, INT_MIN, INT_MAX, VE, "coder" },
1079         { "range_tab", "Range with custom table", 0, AV_OPT_TYPE_CONST,
1080             { .i64 = AC_RANGE_CUSTOM_TAB }, INT_MIN, INT_MAX, VE, "coder" },
1081     { "context", "Context model", OFFSET(context_model), AV_OPT_TYPE_INT,
1082             { .i64 = 0 }, 0, 1, VE },
1083
1084     { NULL }
1085 };
1086
1087 static const AVClass class = {
1088     .class_name = "ffv1 encoder",
1089     .item_name  = av_default_item_name,
1090     .option     = options,
1091     .version    = LIBAVUTIL_VERSION_INT,
1092 };
1093
1094 #if FF_API_CODER_TYPE
1095 static const AVCodecDefault ffv1_defaults[] = {
1096     { "coder", "-1" },
1097     { NULL },
1098 };
1099 #endif
1100
1101 AVCodec ff_ffv1_encoder = {
1102     .name           = "ffv1",
1103     .long_name      = NULL_IF_CONFIG_SMALL("FFmpeg video codec #1"),
1104     .type           = AVMEDIA_TYPE_VIDEO,
1105     .id             = AV_CODEC_ID_FFV1,
1106     .priv_data_size = sizeof(FFV1Context),
1107     .init           = ffv1_encode_init,
1108     .encode2        = ffv1_encode_frame,
1109     .close          = ffv1_encode_close,
1110     .capabilities   = AV_CODEC_CAP_SLICE_THREADS,
1111     .pix_fmts       = (const enum AVPixelFormat[]) {
1112         AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV444P,
1113         AV_PIX_FMT_YUV411P,   AV_PIX_FMT_YUV410P,
1114         AV_PIX_FMT_YUV444P9,  AV_PIX_FMT_YUV422P9,  AV_PIX_FMT_YUV420P9,
1115         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
1116         AV_PIX_FMT_YUV420P16, AV_PIX_FMT_YUV422P16, AV_PIX_FMT_YUV444P16,
1117         AV_PIX_FMT_RGB32,
1118         AV_PIX_FMT_GBRP9,     AV_PIX_FMT_GBRP10,
1119         AV_PIX_FMT_YUVA420P,  AV_PIX_FMT_YUVA422P,  AV_PIX_FMT_YUVA444P,
1120         AV_PIX_FMT_GRAY16,    AV_PIX_FMT_GRAY8,
1121         AV_PIX_FMT_NONE
1122
1123     },
1124 #if FF_API_CODER_TYPE
1125     .defaults       = ffv1_defaults,
1126 #endif
1127     .priv_class     = &class,
1128 };