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

Generated by: LCOV version 1.13