LCOV - code coverage report
Current view: top level - libavcodec - vc2enc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 521 599 87.0 %
Date: 2018-05-20 11:54:08 Functions: 32 32 100.0 %

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

Generated by: LCOV version 1.13