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