]> git.sesse.net Git - ffmpeg/blob - libavcodec/vc2enc.c
avcodec/fft: Add revtab32 for FFTs with more than 65536 samples
[ffmpeg] / libavcodec / vc2enc.c
1 /*
2  * Copyright (C) 2016 Open Broadcast Systems Ltd.
3  * Author        2016 Rostislav Pehlivanov <atomnuker@gmail.com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/pixdesc.h"
23 #include "libavutil/opt.h"
24 #include "dirac.h"
25 #include "put_bits.h"
26 #include "internal.h"
27 #include "version.h"
28
29 #include "vc2enc_dwt.h"
30 #include "diractab.h"
31
32 /* Quantizations above this usually zero coefficients and lower the quality */
33 #define MAX_QUANT_INDEX 50
34
35 /* Total range is -COEF_LUT_TAB to +COEFF_LUT_TAB, but total tab size is half
36  * (COEF_LUT_TAB*MAX_QUANT_INDEX) since the sign is appended during encoding */
37 #define COEF_LUT_TAB 2048
38
39 /* Decides the cutoff point in # of slices to distribute the leftover bytes */
40 #define SLICE_REDIST_TOTAL 150
41
42 enum VC2_QM {
43     VC2_QM_DEF = 0,
44     VC2_QM_COL,
45     VC2_QM_FLAT,
46
47     VC2_QM_NB
48 };
49
50 typedef struct SubBand {
51     dwtcoef *buf;
52     ptrdiff_t stride;
53     int width;
54     int height;
55 } SubBand;
56
57 typedef struct Plane {
58     SubBand band[MAX_DWT_LEVELS][4];
59     dwtcoef *coef_buf;
60     int width;
61     int height;
62     int dwt_width;
63     int dwt_height;
64     ptrdiff_t coef_stride;
65 } Plane;
66
67 typedef struct SliceArgs {
68     PutBitContext pb;
69     int cache[MAX_QUANT_INDEX];
70     void *ctx;
71     int x;
72     int y;
73     int quant_idx;
74     int bits_ceil;
75     int bits_floor;
76     int bytes_left;
77     int bytes;
78 } SliceArgs;
79
80 typedef struct TransformArgs {
81     void *ctx;
82     Plane *plane;
83     void *idata;
84     ptrdiff_t istride;
85     int field;
86     VC2TransformContext t;
87 } TransformArgs;
88
89 typedef struct VC2EncContext {
90     AVClass *av_class;
91     PutBitContext pb;
92     Plane plane[3];
93     AVCodecContext *avctx;
94     DiracVersionInfo ver;
95
96     SliceArgs *slice_args;
97     TransformArgs transform_args[3];
98
99     /* For conversion from unsigned pixel values to signed */
100     int diff_offset;
101     int bpp;
102
103     /* Picture number */
104     uint32_t picture_number;
105
106     /* Base video format */
107     int base_vf;
108     int level;
109     int profile;
110
111     /* Quantization matrix */
112     uint8_t quant[MAX_DWT_LEVELS][4];
113
114     /* Coefficient LUT */
115     uint32_t *coef_lut_val;
116     uint8_t  *coef_lut_len;
117
118     int num_x; /* #slices horizontally */
119     int num_y; /* #slices vertically */
120     int prefix_bytes;
121     int size_scaler;
122     int chroma_x_shift;
123     int chroma_y_shift;
124
125     /* Rate control stuff */
126     int slice_max_bytes;
127     int slice_min_bytes;
128     int q_ceil;
129     int q_avg;
130
131     /* Options */
132     double tolerance;
133     int wavelet_idx;
134     int wavelet_depth;
135     int strict_compliance;
136     int slice_height;
137     int slice_width;
138     int interlaced;
139     enum VC2_QM quant_matrix;
140
141     /* Parse code state */
142     uint32_t next_parse_offset;
143     enum DiracParseCodes last_parse_code;
144 } VC2EncContext;
145
146 static av_always_inline void put_vc2_ue_uint(PutBitContext *pb, uint32_t val)
147 {
148     int i;
149     int pbits = 0, bits = 0, topbit = 1, maxval = 1;
150
151     if (!val++) {
152         put_bits(pb, 1, 1);
153         return;
154     }
155
156     while (val > maxval) {
157         topbit <<= 1;
158         maxval <<= 1;
159         maxval |=  1;
160     }
161
162     bits = ff_log2(topbit);
163
164     for (i = 0; i < bits; i++) {
165         topbit >>= 1;
166         pbits <<= 2;
167         if (val & topbit)
168             pbits |= 0x1;
169     }
170
171     put_bits(pb, bits*2 + 1, (pbits << 1) | 1);
172 }
173
174 static av_always_inline int count_vc2_ue_uint(uint32_t val)
175 {
176     int topbit = 1, maxval = 1;
177
178     if (!val++)
179         return 1;
180
181     while (val > maxval) {
182         topbit <<= 1;
183         maxval <<= 1;
184         maxval |=  1;
185     }
186
187     return ff_log2(topbit)*2 + 1;
188 }
189
190 static av_always_inline void get_vc2_ue_uint(int val, uint8_t *nbits,
191                                              uint32_t *eval)
192 {
193     int i;
194     int pbits = 0, bits = 0, topbit = 1, maxval = 1;
195
196     if (!val++) {
197         *nbits = 1;
198         *eval = 1;
199         return;
200     }
201
202     while (val > maxval) {
203         topbit <<= 1;
204         maxval <<= 1;
205         maxval |=  1;
206     }
207
208     bits = ff_log2(topbit);
209
210     for (i = 0; i < bits; i++) {
211         topbit >>= 1;
212         pbits <<= 2;
213         if (val & topbit)
214             pbits |= 0x1;
215     }
216
217     *nbits = bits*2 + 1;
218     *eval = (pbits << 1) | 1;
219 }
220
221 /* VC-2 10.4 - parse_info() */
222 static void encode_parse_info(VC2EncContext *s, enum DiracParseCodes pcode)
223 {
224     uint32_t cur_pos, dist;
225
226     avpriv_align_put_bits(&s->pb);
227
228     cur_pos = put_bits_count(&s->pb) >> 3;
229
230     /* Magic string */
231     avpriv_put_string(&s->pb, "BBCD", 0);
232
233     /* Parse code */
234     put_bits(&s->pb, 8, pcode);
235
236     /* Next parse offset */
237     dist = cur_pos - s->next_parse_offset;
238     AV_WB32(s->pb.buf + s->next_parse_offset + 5, dist);
239     s->next_parse_offset = cur_pos;
240     put_bits32(&s->pb, pcode == DIRAC_PCODE_END_SEQ ? 13 : 0);
241
242     /* Last parse offset */
243     put_bits32(&s->pb, s->last_parse_code == DIRAC_PCODE_END_SEQ ? 13 : dist);
244
245     s->last_parse_code = pcode;
246 }
247
248 /* VC-2 11.1 - parse_parameters()
249  * The level dictates what the decoder should expect in terms of resolution
250  * and allows it to quickly reject whatever it can't support. Remember,
251  * this codec kinda targets cheapo FPGAs without much memory. Unfortunately
252  * it also limits us greatly in our choice of formats, hence the flag to disable
253  * strict_compliance */
254 static void encode_parse_params(VC2EncContext *s)
255 {
256     put_vc2_ue_uint(&s->pb, s->ver.major); /* VC-2 demands this to be 2 */
257     put_vc2_ue_uint(&s->pb, s->ver.minor); /* ^^ and this to be 0       */
258     put_vc2_ue_uint(&s->pb, s->profile);   /* 3 to signal HQ profile    */
259     put_vc2_ue_uint(&s->pb, s->level);     /* 3 - 1080/720, 6 - 4K      */
260 }
261
262 /* VC-2 11.3 - frame_size() */
263 static void encode_frame_size(VC2EncContext *s)
264 {
265     put_bits(&s->pb, 1, !s->strict_compliance);
266     if (!s->strict_compliance) {
267         AVCodecContext *avctx = s->avctx;
268         put_vc2_ue_uint(&s->pb, avctx->width);
269         put_vc2_ue_uint(&s->pb, avctx->height);
270     }
271 }
272
273 /* VC-2 11.3.3 - color_diff_sampling_format() */
274 static void encode_sample_fmt(VC2EncContext *s)
275 {
276     put_bits(&s->pb, 1, !s->strict_compliance);
277     if (!s->strict_compliance) {
278         int idx;
279         if (s->chroma_x_shift == 1 && s->chroma_y_shift == 0)
280             idx = 1; /* 422 */
281         else if (s->chroma_x_shift == 1 && s->chroma_y_shift == 1)
282             idx = 2; /* 420 */
283         else
284             idx = 0; /* 444 */
285         put_vc2_ue_uint(&s->pb, idx);
286     }
287 }
288
289 /* VC-2 11.3.4 - scan_format() */
290 static void encode_scan_format(VC2EncContext *s)
291 {
292     put_bits(&s->pb, 1, !s->strict_compliance);
293     if (!s->strict_compliance)
294         put_vc2_ue_uint(&s->pb, s->interlaced);
295 }
296
297 /* VC-2 11.3.5 - frame_rate() */
298 static void encode_frame_rate(VC2EncContext *s)
299 {
300     put_bits(&s->pb, 1, !s->strict_compliance);
301     if (!s->strict_compliance) {
302         AVCodecContext *avctx = s->avctx;
303         put_vc2_ue_uint(&s->pb, 0);
304         put_vc2_ue_uint(&s->pb, avctx->time_base.den);
305         put_vc2_ue_uint(&s->pb, avctx->time_base.num);
306     }
307 }
308
309 /* VC-2 11.3.6 - aspect_ratio() */
310 static void encode_aspect_ratio(VC2EncContext *s)
311 {
312     put_bits(&s->pb, 1, !s->strict_compliance);
313     if (!s->strict_compliance) {
314         AVCodecContext *avctx = s->avctx;
315         put_vc2_ue_uint(&s->pb, 0);
316         put_vc2_ue_uint(&s->pb, avctx->sample_aspect_ratio.num);
317         put_vc2_ue_uint(&s->pb, avctx->sample_aspect_ratio.den);
318     }
319 }
320
321 /* VC-2 11.3.7 - clean_area() */
322 static void encode_clean_area(VC2EncContext *s)
323 {
324     put_bits(&s->pb, 1, 0);
325 }
326
327 /* VC-2 11.3.8 - signal_range() */
328 static void encode_signal_range(VC2EncContext *s)
329 {
330     int idx;
331     AVCodecContext *avctx = s->avctx;
332     const AVPixFmtDescriptor *fmt = av_pix_fmt_desc_get(avctx->pix_fmt);
333     const int depth = fmt->comp[0].depth;
334     if (depth == 8 && avctx->color_range == AVCOL_RANGE_JPEG) {
335         idx = 1;
336         s->bpp = 1;
337         s->diff_offset = 128;
338     } else if (depth == 8 && (avctx->color_range == AVCOL_RANGE_MPEG ||
339                avctx->color_range == AVCOL_RANGE_UNSPECIFIED)) {
340         idx = 2;
341         s->bpp = 1;
342         s->diff_offset = 128;
343     } else if (depth == 10) {
344         idx = 3;
345         s->bpp = 2;
346         s->diff_offset = 512;
347     } else {
348         idx = 4;
349         s->bpp = 2;
350         s->diff_offset = 2048;
351     }
352     put_bits(&s->pb, 1, !s->strict_compliance);
353     if (!s->strict_compliance)
354         put_vc2_ue_uint(&s->pb, idx);
355 }
356
357 /* VC-2 11.3.9 - color_spec() */
358 static void encode_color_spec(VC2EncContext *s)
359 {
360     AVCodecContext *avctx = s->avctx;
361     put_bits(&s->pb, 1, !s->strict_compliance);
362     if (!s->strict_compliance) {
363         int val;
364         put_vc2_ue_uint(&s->pb, 0);
365
366         /* primaries */
367         put_bits(&s->pb, 1, 1);
368         if (avctx->color_primaries == AVCOL_PRI_BT470BG)
369             val = 2;
370         else if (avctx->color_primaries == AVCOL_PRI_SMPTE170M)
371             val = 1;
372         else if (avctx->color_primaries == AVCOL_PRI_SMPTE240M)
373             val = 1;
374         else
375             val = 0;
376         put_vc2_ue_uint(&s->pb, val);
377
378         /* color matrix */
379         put_bits(&s->pb, 1, 1);
380         if (avctx->colorspace == AVCOL_SPC_RGB)
381             val = 3;
382         else if (avctx->colorspace == AVCOL_SPC_YCOCG)
383             val = 2;
384         else if (avctx->colorspace == AVCOL_SPC_BT470BG)
385             val = 1;
386         else
387             val = 0;
388         put_vc2_ue_uint(&s->pb, val);
389
390         /* transfer function */
391         put_bits(&s->pb, 1, 1);
392         if (avctx->color_trc == AVCOL_TRC_LINEAR)
393             val = 2;
394         else if (avctx->color_trc == AVCOL_TRC_BT1361_ECG)
395             val = 1;
396         else
397             val = 0;
398         put_vc2_ue_uint(&s->pb, val);
399     }
400 }
401
402 /* VC-2 11.3 - source_parameters() */
403 static void encode_source_params(VC2EncContext *s)
404 {
405     encode_frame_size(s);
406     encode_sample_fmt(s);
407     encode_scan_format(s);
408     encode_frame_rate(s);
409     encode_aspect_ratio(s);
410     encode_clean_area(s);
411     encode_signal_range(s);
412     encode_color_spec(s);
413 }
414
415 /* VC-2 11 - sequence_header() */
416 static void encode_seq_header(VC2EncContext *s)
417 {
418     avpriv_align_put_bits(&s->pb);
419     encode_parse_params(s);
420     put_vc2_ue_uint(&s->pb, s->base_vf);
421     encode_source_params(s);
422     put_vc2_ue_uint(&s->pb, s->interlaced); /* Frames or fields coding */
423 }
424
425 /* VC-2 12.1 - picture_header() */
426 static void encode_picture_header(VC2EncContext *s)
427 {
428     avpriv_align_put_bits(&s->pb);
429     put_bits32(&s->pb, s->picture_number++);
430 }
431
432 /* VC-2 12.3.4.1 - slice_parameters() */
433 static void encode_slice_params(VC2EncContext *s)
434 {
435     put_vc2_ue_uint(&s->pb, s->num_x);
436     put_vc2_ue_uint(&s->pb, s->num_y);
437     put_vc2_ue_uint(&s->pb, s->prefix_bytes);
438     put_vc2_ue_uint(&s->pb, s->size_scaler);
439 }
440
441 /* 1st idx = LL, second - vertical, third - horizontal, fourth - total */
442 const uint8_t vc2_qm_col_tab[][4] = {
443     {20,  9, 15,  4},
444     { 0,  6,  6,  4},
445     { 0,  3,  3,  5},
446     { 0,  3,  5,  1},
447     { 0, 11, 10, 11}
448 };
449
450 const uint8_t vc2_qm_flat_tab[][4] = {
451     { 0,  0,  0,  0},
452     { 0,  0,  0,  0},
453     { 0,  0,  0,  0},
454     { 0,  0,  0,  0},
455     { 0,  0,  0,  0}
456 };
457
458 static void init_custom_qm(VC2EncContext *s)
459 {
460     int level, orientation;
461
462     if (s->quant_matrix == VC2_QM_DEF) {
463         for (level = 0; level < s->wavelet_depth; level++) {
464             for (orientation = 0; orientation < 4; orientation++) {
465                 if (level <= 3)
466                     s->quant[level][orientation] = ff_dirac_default_qmat[s->wavelet_idx][level][orientation];
467                 else
468                     s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];
469             }
470         }
471     } else if (s->quant_matrix == VC2_QM_COL) {
472         for (level = 0; level < s->wavelet_depth; level++) {
473             for (orientation = 0; orientation < 4; orientation++) {
474                 s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];
475             }
476         }
477     } else {
478         for (level = 0; level < s->wavelet_depth; level++) {
479             for (orientation = 0; orientation < 4; orientation++) {
480                 s->quant[level][orientation] = vc2_qm_flat_tab[level][orientation];
481             }
482         }
483     }
484 }
485
486 /* VC-2 12.3.4.2 - quant_matrix() */
487 static void encode_quant_matrix(VC2EncContext *s)
488 {
489     int level, custom_quant_matrix = 0;
490     if (s->wavelet_depth > 4 || s->quant_matrix != VC2_QM_DEF)
491         custom_quant_matrix = 1;
492     put_bits(&s->pb, 1, custom_quant_matrix);
493     if (custom_quant_matrix) {
494         init_custom_qm(s);
495         put_vc2_ue_uint(&s->pb, s->quant[0][0]);
496         for (level = 0; level < s->wavelet_depth; level++) {
497             put_vc2_ue_uint(&s->pb, s->quant[level][1]);
498             put_vc2_ue_uint(&s->pb, s->quant[level][2]);
499             put_vc2_ue_uint(&s->pb, s->quant[level][3]);
500         }
501     } else {
502         for (level = 0; level < s->wavelet_depth; level++) {
503             s->quant[level][0] = ff_dirac_default_qmat[s->wavelet_idx][level][0];
504             s->quant[level][1] = ff_dirac_default_qmat[s->wavelet_idx][level][1];
505             s->quant[level][2] = ff_dirac_default_qmat[s->wavelet_idx][level][2];
506             s->quant[level][3] = ff_dirac_default_qmat[s->wavelet_idx][level][3];
507         }
508     }
509 }
510
511 /* VC-2 12.3 - transform_parameters() */
512 static void encode_transform_params(VC2EncContext *s)
513 {
514     put_vc2_ue_uint(&s->pb, s->wavelet_idx);
515     put_vc2_ue_uint(&s->pb, s->wavelet_depth);
516
517     encode_slice_params(s);
518     encode_quant_matrix(s);
519 }
520
521 /* VC-2 12.2 - wavelet_transform() */
522 static void encode_wavelet_transform(VC2EncContext *s)
523 {
524     encode_transform_params(s);
525     avpriv_align_put_bits(&s->pb);
526     /* Continued after DWT in encode_transform_data() */
527 }
528
529 /* VC-2 12 - picture_parse() */
530 static void encode_picture_start(VC2EncContext *s)
531 {
532     avpriv_align_put_bits(&s->pb);
533     encode_picture_header(s);
534     avpriv_align_put_bits(&s->pb);
535     encode_wavelet_transform(s);
536 }
537
538 #define QUANT(c, qf) (((c) << 2)/(qf))
539
540 /* VC-2 13.5.5.2 - slice_band() */
541 static void encode_subband(VC2EncContext *s, PutBitContext *pb, int sx, int sy,
542                            SubBand *b, int quant)
543 {
544     int x, y;
545
546     const int left   = b->width  * (sx+0) / s->num_x;
547     const int right  = b->width  * (sx+1) / s->num_x;
548     const int top    = b->height * (sy+0) / s->num_y;
549     const int bottom = b->height * (sy+1) / s->num_y;
550
551     const int qfactor = ff_dirac_qscale_tab[quant];
552     const uint8_t  *len_lut = &s->coef_lut_len[quant*COEF_LUT_TAB];
553     const uint32_t *val_lut = &s->coef_lut_val[quant*COEF_LUT_TAB];
554
555     dwtcoef *coeff = b->buf + top * b->stride;
556
557     for (y = top; y < bottom; y++) {
558         for (x = left; x < right; x++) {
559             const int neg = coeff[x] < 0;
560             uint32_t c_abs = FFABS(coeff[x]);
561             if (c_abs < COEF_LUT_TAB) {
562                 const uint8_t len  = len_lut[c_abs];
563                 if (len == 1)
564                     put_bits(pb, 1, 1);
565                 else
566                     put_bits(pb, len + 1, (val_lut[c_abs] << 1) | neg);
567             } else {
568                 c_abs = QUANT(c_abs, qfactor);
569                 put_vc2_ue_uint(pb, c_abs);
570                 if (c_abs)
571                     put_bits(pb, 1, neg);
572             }
573         }
574         coeff += b->stride;
575     }
576 }
577
578 static int count_hq_slice(VC2EncContext *s, int *cache,
579                           int slice_x, int slice_y, int quant_idx)
580 {
581     int x, y;
582     uint8_t quants[MAX_DWT_LEVELS][4];
583     int bits = 0, p, level, orientation;
584
585     if (cache && cache[quant_idx])
586         return cache[quant_idx];
587
588     bits += 8*s->prefix_bytes;
589     bits += 8; /* quant_idx */
590
591     for (level = 0; level < s->wavelet_depth; level++)
592         for (orientation = !!level; orientation < 4; orientation++)
593             quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);
594
595     for (p = 0; p < 3; p++) {
596         int bytes_start, bytes_len, pad_s, pad_c;
597         bytes_start = bits >> 3;
598         bits += 8;
599         for (level = 0; level < s->wavelet_depth; level++) {
600             for (orientation = !!level; orientation < 4; orientation++) {
601                 SubBand *b = &s->plane[p].band[level][orientation];
602
603                 const int q_idx = quants[level][orientation];
604                 const uint8_t *len_lut = &s->coef_lut_len[q_idx*COEF_LUT_TAB];
605                 const int qfactor = ff_dirac_qscale_tab[q_idx];
606
607                 const int left   = b->width  * slice_x    / s->num_x;
608                 const int right  = b->width  *(slice_x+1) / s->num_x;
609                 const int top    = b->height * slice_y    / s->num_y;
610                 const int bottom = b->height *(slice_y+1) / s->num_y;
611
612                 dwtcoef *buf = b->buf + top * b->stride;
613
614                 for (y = top; y < bottom; y++) {
615                     for (x = left; x < right; x++) {
616                         uint32_t c_abs = FFABS(buf[x]);
617                         if (c_abs < COEF_LUT_TAB) {
618                             const int len = len_lut[c_abs];
619                             bits += len + (len != 1);
620                         } else {
621                             c_abs = QUANT(c_abs, qfactor);
622                             bits += count_vc2_ue_uint(c_abs);
623                             bits += !!c_abs;
624                         }
625                     }
626                     buf += b->stride;
627                 }
628             }
629         }
630         bits += FFALIGN(bits, 8) - bits;
631         bytes_len = (bits >> 3) - bytes_start - 1;
632         pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;
633         pad_c = (pad_s*s->size_scaler) - bytes_len;
634         bits += pad_c*8;
635     }
636
637     if (cache)
638         cache[quant_idx] = bits;
639
640     return bits;
641 }
642
643 /* Approaches the best possible quantizer asymptotically, its kinda exaustive
644  * but we have a LUT to get the coefficient size in bits. Guaranteed to never
645  * overshoot, which is apparently very important when streaming */
646 static int rate_control(AVCodecContext *avctx, void *arg)
647 {
648     SliceArgs *slice_dat = arg;
649     VC2EncContext *s = slice_dat->ctx;
650     const int sx = slice_dat->x;
651     const int sy = slice_dat->y;
652     int bits_last = INT_MAX, quant_buf[2] = {-1, -1};
653     int quant = slice_dat->quant_idx, range = quant/5;
654     const int top = slice_dat->bits_ceil;
655     const int bottom = slice_dat->bits_floor;
656     int bits = count_hq_slice(s, slice_dat->cache, sx, sy, quant);
657     range -= range & 1; /* Make it an even number */
658     while ((bits > top) || (bits < bottom)) {
659         range *= bits > top ? +1 : -1;
660         quant = av_clip(quant + range, 0, s->q_ceil);
661         bits = count_hq_slice(s, slice_dat->cache, sx, sy, quant);
662         range = av_clip(range/2, 1, s->q_ceil);
663         if (quant_buf[1] == quant) {
664             quant = bits_last < bits ? quant_buf[0] : quant;
665             bits  = bits_last < bits ? bits_last : bits;
666             break;
667         }
668         quant_buf[1] = quant_buf[0];
669         quant_buf[0] = quant;
670         bits_last = bits;
671     }
672     slice_dat->quant_idx = av_clip(quant, 0, s->q_ceil);
673     slice_dat->bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;
674     slice_dat->bytes_left = s->slice_max_bytes - slice_dat->bytes;
675
676     return 0;
677 }
678
679 static void calc_slice_sizes(VC2EncContext *s)
680 {
681     int slice_x, slice_y;
682     SliceArgs *enc_args = s->slice_args;
683
684     for (slice_y = 0; slice_y < s->num_y; slice_y++) {
685         for (slice_x = 0; slice_x < s->num_x; slice_x++) {
686             SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
687             args->ctx = s;
688             args->x = slice_x;
689             args->y = slice_y;
690             args->bits_ceil = s->slice_max_bytes << 3;
691             args->bits_floor = s->slice_min_bytes << 3;
692             memset(args->cache, 0, MAX_QUANT_INDEX*sizeof(*args->cache));
693         }
694     }
695
696     /* Determine quantization indices and bytes per slice */
697     s->avctx->execute(s->avctx, rate_control, enc_args, NULL, s->num_x*s->num_y,
698                       sizeof(SliceArgs));
699 }
700
701 /* VC-2 13.5.3 - hq_slice */
702 static int encode_hq_slice(AVCodecContext *avctx, void *arg)
703 {
704     SliceArgs *slice_dat = arg;
705     VC2EncContext *s = slice_dat->ctx;
706     PutBitContext *pb = &slice_dat->pb;
707     const int slice_x = slice_dat->x;
708     const int slice_y = slice_dat->y;
709     const int quant_idx = slice_dat->quant_idx;
710     const int slice_bytes_max = slice_dat->bytes;
711     uint8_t quants[MAX_DWT_LEVELS][4];
712     int p, level, orientation;
713
714     avpriv_align_put_bits(pb);
715     skip_put_bytes(pb, s->prefix_bytes);
716     put_bits(pb, 8, quant_idx);
717
718     /* Slice quantization (slice_quantizers() in the specs) */
719     for (level = 0; level < s->wavelet_depth; level++)
720         for (orientation = !!level; orientation < 4; orientation++)
721             quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);
722
723     /* Luma + 2 Chroma planes */
724     for (p = 0; p < 3; p++) {
725         int bytes_start, bytes_len, pad_s, pad_c;
726         bytes_start = put_bits_count(pb) >> 3;
727         put_bits(pb, 8, 0);
728         for (level = 0; level < s->wavelet_depth; level++) {
729             for (orientation = !!level; orientation < 4; orientation++) {
730                 encode_subband(s, pb, slice_x, slice_y,
731                                &s->plane[p].band[level][orientation],
732                                quants[level][orientation]);
733             }
734         }
735         avpriv_align_put_bits(pb);
736         bytes_len = (put_bits_count(pb) >> 3) - bytes_start - 1;
737         if (p == 2) {
738             int len_diff = slice_bytes_max - (put_bits_count(pb) >> 3);
739             pad_s = FFALIGN((bytes_len + len_diff), s->size_scaler)/s->size_scaler;
740             pad_c = (pad_s*s->size_scaler) - bytes_len;
741         } else {
742             pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;
743             pad_c = (pad_s*s->size_scaler) - bytes_len;
744         }
745         pb->buf[bytes_start] = pad_s;
746         flush_put_bits(pb);
747         skip_put_bytes(pb, pad_c);
748     }
749
750     return 0;
751 }
752
753 /* VC-2 13.5.1 - low_delay_transform_data() */
754 static int encode_slices(VC2EncContext *s)
755 {
756     uint8_t *buf;
757     int i, slice_x, slice_y, skip = 0;
758     int bytes_left = 0;
759     SliceArgs *enc_args = s->slice_args;
760
761     int bytes_top[SLICE_REDIST_TOTAL] = {0};
762     SliceArgs *top_loc[SLICE_REDIST_TOTAL] = {NULL};
763
764     avpriv_align_put_bits(&s->pb);
765     flush_put_bits(&s->pb);
766     buf = put_bits_ptr(&s->pb);
767
768     for (slice_y = 0; slice_y < s->num_y; slice_y++) {
769         for (slice_x = 0; slice_x < s->num_x; slice_x++) {
770             SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
771             bytes_left += args->bytes_left;
772             for (i = 0; i < FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y); i++) {
773                 if (args->bytes > bytes_top[i]) {
774                     bytes_top[i] = args->bytes;
775                     top_loc[i] = args;
776                     break;
777                 }
778             }
779         }
780     }
781
782     while (1) {
783         int distributed = 0;
784         for (i = 0; i < FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y); i++) {
785             SliceArgs *args;
786             int bits, bytes, diff, prev_bytes, new_idx;
787             if (bytes_left <= 0)
788                 break;
789             if (!top_loc[i] || !top_loc[i]->quant_idx)
790                 break;
791             args = top_loc[i];
792             prev_bytes = args->bytes;
793             new_idx = av_clip(args->quant_idx - 1, 0, s->q_ceil);
794             bits = count_hq_slice(s, args->cache, args->x, args->y, new_idx);
795             bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;
796             diff = bytes - prev_bytes;
797             if ((bytes_left - diff) >= 0) {
798                 args->quant_idx = new_idx;
799                 args->bytes = bytes;
800                 bytes_left -= diff;
801                 distributed++;
802             }
803         }
804         if (!distributed)
805             break;
806     }
807
808     for (slice_y = 0; slice_y < s->num_y; slice_y++) {
809         for (slice_x = 0; slice_x < s->num_x; slice_x++) {
810             SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
811             init_put_bits(&args->pb, buf + skip, args->bytes);
812             s->q_avg = (s->q_avg + args->quant_idx)/2;
813             skip += args->bytes;
814         }
815     }
816
817     s->avctx->execute(s->avctx, encode_hq_slice, enc_args, NULL, s->num_x*s->num_y,
818                       sizeof(SliceArgs));
819
820     skip_put_bytes(&s->pb, skip);
821
822     return 0;
823 }
824
825 /*
826  * Transform basics for a 3 level transform
827  * |---------------------------------------------------------------------|
828  * |  LL-0  | HL-0  |                 |                                  |
829  * |--------|-------|      HL-1       |                                  |
830  * |  LH-0  | HH-0  |                 |                                  |
831  * |----------------|-----------------|              HL-2                |
832  * |                |                 |                                  |
833  * |     LH-1       |      HH-1       |                                  |
834  * |                |                 |                                  |
835  * |----------------------------------|----------------------------------|
836  * |                                  |                                  |
837  * |                                  |                                  |
838  * |                                  |                                  |
839  * |              LH-2                |              HH-2                |
840  * |                                  |                                  |
841  * |                                  |                                  |
842  * |                                  |                                  |
843  * |---------------------------------------------------------------------|
844  *
845  * DWT transforms are generally applied by splitting the image in two vertically
846  * and applying a low pass transform on the left part and a corresponding high
847  * pass transform on the right hand side. This is known as the horizontal filter
848  * stage.
849  * After that, the same operation is performed except the image is divided
850  * horizontally, with the high pass on the lower and the low pass on the higher
851  * side.
852  * Therefore, you're left with 4 subdivisions - known as  low-low, low-high,
853  * high-low and high-high. They're referred to as orientations in the decoder
854  * and encoder.
855  *
856  * The LL (low-low) area contains the original image downsampled by the amount
857  * of levels. The rest of the areas can be thought as the details needed
858  * to restore the image perfectly to its original size.
859  */
860 static int dwt_plane(AVCodecContext *avctx, void *arg)
861 {
862     TransformArgs *transform_dat = arg;
863     VC2EncContext *s = transform_dat->ctx;
864     const void *frame_data = transform_dat->idata;
865     const ptrdiff_t linesize = transform_dat->istride;
866     const int field = transform_dat->field;
867     const Plane *p = transform_dat->plane;
868     VC2TransformContext *t = &transform_dat->t;
869     dwtcoef *buf = p->coef_buf;
870     const int idx = s->wavelet_idx;
871     const int skip = 1 + s->interlaced;
872
873     int x, y, level, offset;
874     ptrdiff_t pix_stride = linesize >> (s->bpp - 1);
875
876     if (field == 1) {
877         offset = 0;
878         pix_stride <<= 1;
879     } else if (field == 2) {
880         offset = pix_stride;
881         pix_stride <<= 1;
882     } else {
883         offset = 0;
884     }
885
886     if (s->bpp == 1) {
887         const uint8_t *pix = (const uint8_t *)frame_data + offset;
888         for (y = 0; y < p->height*skip; y+=skip) {
889             for (x = 0; x < p->width; x++) {
890                 buf[x] = pix[x] - s->diff_offset;
891             }
892             buf += p->coef_stride;
893             pix += pix_stride;
894         }
895     } else {
896         const uint16_t *pix = (const uint16_t *)frame_data + offset;
897         for (y = 0; y < p->height*skip; y+=skip) {
898             for (x = 0; x < p->width; x++) {
899                 buf[x] = pix[x] - s->diff_offset;
900             }
901             buf += p->coef_stride;
902             pix += pix_stride;
903         }
904     }
905
906     memset(buf, 0, p->coef_stride * (p->dwt_height - p->height) * sizeof(dwtcoef));
907
908     for (level = s->wavelet_depth-1; level >= 0; level--) {
909         const SubBand *b = &p->band[level][0];
910         t->vc2_subband_dwt[idx](t, p->coef_buf, p->coef_stride,
911                                 b->width, b->height);
912     }
913
914     return 0;
915 }
916
917 static void encode_frame(VC2EncContext *s, const AVFrame *frame,
918                          const char *aux_data, int field)
919 {
920     int i;
921
922     /* Sequence header */
923     encode_parse_info(s, DIRAC_PCODE_SEQ_HEADER);
924     encode_seq_header(s);
925
926     /* Encoder version */
927     if (aux_data) {
928         encode_parse_info(s, DIRAC_PCODE_AUX);
929         avpriv_put_string(&s->pb, aux_data, 1);
930     }
931
932     /* Picture header */
933     encode_parse_info(s, DIRAC_PCODE_PICTURE_HQ);
934     encode_picture_start(s);
935
936     for (i = 0; i < 3; i++) {
937         s->transform_args[i].ctx   = s;
938         s->transform_args[i].field = field;
939         s->transform_args[i].plane = &s->plane[i];
940         s->transform_args[i].idata = frame->data[i];
941         s->transform_args[i].istride = frame->linesize[i];
942     }
943
944     /* Do a DWT transform */
945     s->avctx->execute(s->avctx, dwt_plane, s->transform_args, NULL, 3,
946                       sizeof(TransformArgs));
947
948     /* Calculate per-slice quantizers and sizes */
949     calc_slice_sizes(s);
950
951     /* Init planes and encode slices */
952     encode_slices(s);
953
954     /* End sequence */
955     encode_parse_info(s, DIRAC_PCODE_END_SEQ);
956 }
957
958 static av_cold int vc2_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
959                                       const AVFrame *frame, int *got_packet_ptr)
960 {
961     int ret;
962     int max_frame_bytes, sig_size = 256;
963     VC2EncContext *s = avctx->priv_data;
964     const char aux_data[] = LIBAVCODEC_IDENT;
965     const int aux_data_size = sizeof(aux_data);
966     const int header_size = 100 + aux_data_size;
967     int64_t r_bitrate = avctx->bit_rate >> (s->interlaced);
968
969     s->avctx = avctx;
970     s->size_scaler = 1;
971     s->prefix_bytes = 0;
972     s->last_parse_code = 0;
973     s->next_parse_offset = 0;
974
975     /* Rate control */
976     max_frame_bytes = (av_rescale(r_bitrate, s->avctx->time_base.num,
977                                   s->avctx->time_base.den) >> 3) - header_size;
978
979     /* Find an appropriate size scaler */
980     while (sig_size > 255) {
981         s->slice_max_bytes = FFALIGN(av_rescale(max_frame_bytes, 1,
982                                      s->num_x*s->num_y), s->size_scaler);
983         s->slice_max_bytes += 4 + s->prefix_bytes;
984         sig_size = s->slice_max_bytes/s->size_scaler; /* Signalled slize size */
985         s->size_scaler <<= 1;
986     }
987
988     s->slice_min_bytes = s->slice_max_bytes - s->slice_max_bytes*(s->tolerance/100.0f);
989
990     ret = ff_alloc_packet2(avctx, avpkt, max_frame_bytes*3, 0);
991     if (ret < 0) {
992         av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
993         return ret;
994     } else {
995         init_put_bits(&s->pb, avpkt->data, avpkt->size);
996     }
997
998     encode_frame(s, frame, aux_data, s->interlaced);
999     if (s->interlaced)
1000         encode_frame(s, frame, NULL, 2);
1001
1002     flush_put_bits(&s->pb);
1003     avpkt->size = put_bits_count(&s->pb) >> 3;
1004
1005     *got_packet_ptr = 1;
1006
1007     return 0;
1008 }
1009
1010 static av_cold int vc2_encode_end(AVCodecContext *avctx)
1011 {
1012     int i;
1013     VC2EncContext *s = avctx->priv_data;
1014
1015     av_log(avctx, AV_LOG_INFO, "Qavg: %i\n", s->q_avg);
1016
1017     for (i = 0; i < 3; i++) {
1018         ff_vc2enc_free_transforms(&s->transform_args[i].t);
1019         av_freep(&s->plane[i].coef_buf);
1020     }
1021
1022     av_freep(&s->slice_args);
1023     av_freep(&s->coef_lut_len);
1024     av_freep(&s->coef_lut_val);
1025
1026     return 0;
1027 }
1028
1029 static int minimum_frame_bits(VC2EncContext *s)
1030 {
1031     int slice_x, slice_y, bits = 0;
1032     s->size_scaler = 64;
1033     for (slice_y = 0; slice_y < s->num_y; slice_y++) {
1034         for (slice_x = 0; slice_x < s->num_x; slice_x++) {
1035             bits += count_hq_slice(s, NULL, slice_x, slice_y, s->q_ceil);
1036         }
1037     }
1038     return bits;
1039 }
1040
1041 static av_cold int vc2_encode_init(AVCodecContext *avctx)
1042 {
1043     Plane *p;
1044     SubBand *b;
1045     int i, j, level, o, shift;
1046     int64_t bits_per_frame, min_bits_per_frame;
1047     VC2EncContext *s = avctx->priv_data;
1048
1049     s->picture_number = 0;
1050
1051     /* Total allowed quantization range */
1052     s->q_ceil    = MAX_QUANT_INDEX;
1053
1054     s->ver.major = 2;
1055     s->ver.minor = 0;
1056     s->profile   = 3;
1057     s->level     = 3;
1058
1059     s->base_vf   = -1;
1060     s->strict_compliance = 1;
1061
1062     s->q_avg = 0;
1063     s->slice_max_bytes = 0;
1064     s->slice_min_bytes = 0;
1065
1066     /* Mark unknown as progressive */
1067     s->interlaced = !((avctx->field_order == AV_FIELD_UNKNOWN) ||
1068                       (avctx->field_order == AV_FIELD_PROGRESSIVE));
1069
1070     if (avctx->pix_fmt == AV_PIX_FMT_YUV422P10) {
1071         if (avctx->width == 1280 && avctx->height == 720) {
1072             s->level = 3;
1073             if (avctx->time_base.num == 1001 && avctx->time_base.den == 60000)
1074                 s->base_vf = 9;
1075             if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1076                 s->base_vf = 10;
1077         } else if (avctx->width == 1920 && avctx->height == 1080) {
1078             s->level = 3;
1079             if (s->interlaced) {
1080                 if (avctx->time_base.num == 1001 && avctx->time_base.den == 30000)
1081                     s->base_vf = 11;
1082                 if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1083                     s->base_vf = 12;
1084             } else {
1085                 if (avctx->time_base.num == 1001 && avctx->time_base.den == 60000)
1086                     s->base_vf = 13;
1087                 if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1088                     s->base_vf = 14;
1089                 if (avctx->time_base.num == 1001 && avctx->time_base.den == 24000)
1090                     s->base_vf = 21;
1091             }
1092         } else if (avctx->width == 3840 && avctx->height == 2160) {
1093             s->level = 6;
1094             if (avctx->time_base.num == 1001 && avctx->time_base.den == 60000)
1095                 s->base_vf = 17;
1096             if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1097                 s->base_vf = 18;
1098         }
1099     }
1100
1101     if (s->interlaced && s->base_vf <= 0) {
1102         av_log(avctx, AV_LOG_ERROR, "Interlacing not supported with non standard formats!\n");
1103         return AVERROR_UNKNOWN;
1104     }
1105
1106     if (s->interlaced)
1107         av_log(avctx, AV_LOG_WARNING, "Interlacing enabled!\n");
1108
1109     if ((s->slice_width  & (s->slice_width  - 1)) ||
1110         (s->slice_height & (s->slice_height - 1))) {
1111         av_log(avctx, AV_LOG_ERROR, "Slice size is not a power of two!\n");
1112         return AVERROR_UNKNOWN;
1113     }
1114
1115     if ((s->slice_width > avctx->width) ||
1116         (s->slice_height > avctx->height)) {
1117         av_log(avctx, AV_LOG_ERROR, "Slice size is bigger than the image!\n");
1118         return AVERROR_UNKNOWN;
1119     }
1120
1121     if (s->base_vf <= 0) {
1122         if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1123             s->strict_compliance = s->base_vf = 0;
1124             av_log(avctx, AV_LOG_WARNING, "Disabling strict compliance\n");
1125         } else {
1126             av_log(avctx, AV_LOG_WARNING, "Given format does not strictly comply with "
1127                    "the specifications, please add a -strict -1 flag to use it\n");
1128             return AVERROR_UNKNOWN;
1129         }
1130     } else {
1131         av_log(avctx, AV_LOG_INFO, "Selected base video format = %i\n", s->base_vf);
1132     }
1133
1134     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1135
1136     /* Planes initialization */
1137     for (i = 0; i < 3; i++) {
1138         int w, h;
1139         p = &s->plane[i];
1140         p->width      = avctx->width  >> (i ? s->chroma_x_shift : 0);
1141         p->height     = avctx->height >> (i ? s->chroma_y_shift : 0);
1142         if (s->interlaced)
1143             p->height >>= 1;
1144         p->dwt_width  = w = FFALIGN(p->width,  (1 << s->wavelet_depth));
1145         p->dwt_height = h = FFALIGN(p->height, (1 << s->wavelet_depth));
1146         p->coef_stride = FFALIGN(p->dwt_width, 32);
1147         p->coef_buf = av_malloc(p->coef_stride*p->dwt_height*sizeof(dwtcoef));
1148         if (!p->coef_buf)
1149             goto alloc_fail;
1150         for (level = s->wavelet_depth-1; level >= 0; level--) {
1151             w = w >> 1;
1152             h = h >> 1;
1153             for (o = 0; o < 4; o++) {
1154                 b = &p->band[level][o];
1155                 b->width  = w;
1156                 b->height = h;
1157                 b->stride = p->coef_stride;
1158                 shift = (o > 1)*b->height*b->stride + (o & 1)*b->width;
1159                 b->buf = p->coef_buf + shift;
1160             }
1161         }
1162
1163         /* DWT init */
1164         if (ff_vc2enc_init_transforms(&s->transform_args[i].t,
1165                                       s->plane[i].coef_stride,
1166                                       s->plane[i].dwt_height))
1167             goto alloc_fail;
1168     }
1169
1170     /* Slices */
1171     s->num_x = s->plane[0].dwt_width/s->slice_width;
1172     s->num_y = s->plane[0].dwt_height/s->slice_height;
1173
1174     s->slice_args = av_malloc(s->num_x*s->num_y*sizeof(SliceArgs));
1175     if (!s->slice_args)
1176         goto alloc_fail;
1177
1178     /* Lookup tables */
1179     s->coef_lut_len = av_malloc(COEF_LUT_TAB*s->q_ceil*sizeof(*s->coef_lut_len));
1180     if (!s->coef_lut_len)
1181         goto alloc_fail;
1182
1183     s->coef_lut_val = av_malloc(COEF_LUT_TAB*s->q_ceil*sizeof(*s->coef_lut_val));
1184     if (!s->coef_lut_val)
1185         goto alloc_fail;
1186
1187     for (i = 0; i < s->q_ceil; i++) {
1188         for (j = 0; j < COEF_LUT_TAB; j++) {
1189             uint8_t  *len_lut = &s->coef_lut_len[i*COEF_LUT_TAB];
1190             uint32_t *val_lut = &s->coef_lut_val[i*COEF_LUT_TAB];
1191             get_vc2_ue_uint(QUANT(j, ff_dirac_qscale_tab[i]),
1192                             &len_lut[j], &val_lut[j]);
1193         }
1194     }
1195
1196     bits_per_frame = av_rescale(avctx->bit_rate, avctx->time_base.num,
1197                                  avctx->time_base.den);
1198     min_bits_per_frame = minimum_frame_bits(s) + 8*sizeof(LIBAVCODEC_IDENT) + 8*40 + 8*20000;
1199     if (bits_per_frame < min_bits_per_frame) {
1200         if (s->interlaced)
1201             min_bits_per_frame += min_bits_per_frame + min_bits_per_frame/2;
1202         avctx->bit_rate = av_rescale(min_bits_per_frame, avctx->time_base.den,
1203                                      avctx->time_base.num);
1204         av_log(avctx, AV_LOG_WARNING,
1205                "Bitrate too low, clipping to minimum = %li Mbps!\n",
1206                avctx->bit_rate/1000000);
1207     }
1208
1209     return 0;
1210
1211 alloc_fail:
1212     vc2_encode_end(avctx);
1213     av_log(avctx, AV_LOG_ERROR, "Unable to allocate memory!\n");
1214     return AVERROR(ENOMEM);
1215 }
1216
1217 #define VC2ENC_FLAGS (AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
1218 static const AVOption vc2enc_options[] = {
1219     {"tolerance",     "Max undershoot in percent", offsetof(VC2EncContext, tolerance), AV_OPT_TYPE_DOUBLE, {.dbl = 5.0f}, 0.0f, 45.0f, VC2ENC_FLAGS, "tolerance"},
1220     {"slice_width",   "Slice width",  offsetof(VC2EncContext, slice_width), AV_OPT_TYPE_INT, {.i64 = 64}, 32, 1024, VC2ENC_FLAGS, "slice_width"},
1221     {"slice_height",  "Slice height", offsetof(VC2EncContext, slice_height), AV_OPT_TYPE_INT, {.i64 = 32}, 8, 1024, VC2ENC_FLAGS, "slice_height"},
1222     {"wavelet_depth", "Transform depth", offsetof(VC2EncContext, wavelet_depth), AV_OPT_TYPE_INT, {.i64 = 4}, 1, 5, VC2ENC_FLAGS, "wavelet_depth"},
1223     {"wavelet_type",  "Transform type",  offsetof(VC2EncContext, wavelet_idx), AV_OPT_TYPE_INT, {.i64 = VC2_TRANSFORM_9_7}, 0, VC2_TRANSFORMS_NB, VC2ENC_FLAGS, "wavelet_idx"},
1224         {"9_7",          "Deslauriers-Dubuc (9,7)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_9_7},    INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1225         {"5_3",          "LeGall (5,3)",            0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_5_3},    INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1226         {"haar",         "Haar (with shift)",       0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_HAAR_S}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1227         {"haar_noshift", "Haar (without shift)",    0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_HAAR},   INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1228     {"qm", "Custom quantization matrix", offsetof(VC2EncContext, quant_matrix), AV_OPT_TYPE_INT, {.i64 = VC2_QM_DEF}, 0, VC2_QM_NB, VC2ENC_FLAGS, "quant_matrix"},
1229         {"default",   "Default from the specifications", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_DEF}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1230         {"color",     "Prevents low bitrate discoloration", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_COL}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1231         {"flat",      "Optimize for PSNR", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_FLAT}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1232     {NULL}
1233 };
1234
1235 static const AVClass vc2enc_class = {
1236     .class_name = "SMPTE VC-2 encoder",
1237     .category = AV_CLASS_CATEGORY_ENCODER,
1238     .option = vc2enc_options,
1239     .item_name = av_default_item_name,
1240     .version = LIBAVUTIL_VERSION_INT
1241 };
1242
1243 static const AVCodecDefault vc2enc_defaults[] = {
1244     { "b",              "600000000"   },
1245     { NULL },
1246 };
1247
1248 static const enum AVPixelFormat allowed_pix_fmts[] = {
1249     AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV444P,
1250     AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
1251     AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
1252     AV_PIX_FMT_NONE
1253 };
1254
1255 AVCodec ff_vc2_encoder = {
1256     .name           = "vc2",
1257     .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-2"),
1258     .type           = AVMEDIA_TYPE_VIDEO,
1259     .id             = AV_CODEC_ID_DIRAC,
1260     .priv_data_size = sizeof(VC2EncContext),
1261     .init           = vc2_encode_init,
1262     .close          = vc2_encode_end,
1263     .capabilities   = AV_CODEC_CAP_SLICE_THREADS,
1264     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
1265     .encode2        = vc2_encode_frame,
1266     .priv_class     = &vc2enc_class,
1267     .defaults       = vc2enc_defaults,
1268     .pix_fmts       = allowed_pix_fmts
1269 };