2 * Copyright (C) 2016 Open Broadcast Systems Ltd.
3 * Author 2016 Rostislav Pehlivanov <atomnuker@gmail.com>
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/pixdesc.h"
23 #include "libavutil/opt.h"
29 #include "vc2enc_dwt.h"
32 /* Quantizations above this usually zero coefficients and lower the quality */
33 #define MAX_QUANT_INDEX 50
35 /* Total range is -COEF_LUT_TAB to +COEFF_LUT_TAB, but total tab size is half
36 * (COEF_LUT_TAB*MAX_QUANT_INDEX) since the sign is appended during encoding */
37 #define COEF_LUT_TAB 2048
39 /* Decides the cutoff point in # of slices to distribute the leftover bytes */
40 #define SLICE_REDIST_TOTAL 150
50 typedef struct SubBand {
57 typedef struct Plane {
58 SubBand band[MAX_DWT_LEVELS][4];
64 ptrdiff_t coef_stride;
67 typedef struct SliceArgs {
69 int cache[MAX_QUANT_INDEX];
80 typedef struct TransformArgs {
86 VC2TransformContext t;
89 typedef struct VC2EncContext {
93 AVCodecContext *avctx;
96 SliceArgs *slice_args;
97 TransformArgs transform_args[3];
99 /* For conversion from unsigned pixel values to signed */
104 uint32_t picture_number;
106 /* Base video format */
111 /* Quantization matrix */
112 uint8_t quant[MAX_DWT_LEVELS][4];
114 /* Coefficient LUT */
115 uint32_t *coef_lut_val;
116 uint8_t *coef_lut_len;
118 int num_x; /* #slices horizontally */
119 int num_y; /* #slices vertically */
125 /* Rate control stuff */
135 int strict_compliance;
139 enum VC2_QM quant_matrix;
141 /* Parse code state */
142 uint32_t next_parse_offset;
143 enum DiracParseCodes last_parse_code;
146 static av_always_inline void put_vc2_ue_uint(PutBitContext *pb, uint32_t val)
149 int pbits = 0, bits = 0, topbit = 1, maxval = 1;
156 while (val > maxval) {
162 bits = ff_log2(topbit);
164 for (i = 0; i < bits; i++) {
171 put_bits(pb, bits*2 + 1, (pbits << 1) | 1);
174 static av_always_inline int count_vc2_ue_uint(uint32_t val)
176 int topbit = 1, maxval = 1;
181 while (val > maxval) {
187 return ff_log2(topbit)*2 + 1;
190 static av_always_inline void get_vc2_ue_uint(int val, uint8_t *nbits,
194 int pbits = 0, bits = 0, topbit = 1, maxval = 1;
202 while (val > maxval) {
208 bits = ff_log2(topbit);
210 for (i = 0; i < bits; i++) {
218 *eval = (pbits << 1) | 1;
221 /* VC-2 10.4 - parse_info() */
222 static void encode_parse_info(VC2EncContext *s, enum DiracParseCodes pcode)
224 uint32_t cur_pos, dist;
226 avpriv_align_put_bits(&s->pb);
228 cur_pos = put_bits_count(&s->pb) >> 3;
231 avpriv_put_string(&s->pb, "BBCD", 0);
234 put_bits(&s->pb, 8, pcode);
236 /* Next parse offset */
237 dist = cur_pos - s->next_parse_offset;
238 AV_WB32(s->pb.buf + s->next_parse_offset + 5, dist);
239 s->next_parse_offset = cur_pos;
240 put_bits32(&s->pb, pcode == DIRAC_PCODE_END_SEQ ? 13 : 0);
242 /* Last parse offset */
243 put_bits32(&s->pb, s->last_parse_code == DIRAC_PCODE_END_SEQ ? 13 : dist);
245 s->last_parse_code = pcode;
248 /* VC-2 11.1 - parse_parameters()
249 * The level dictates what the decoder should expect in terms of resolution
250 * and allows it to quickly reject whatever it can't support. Remember,
251 * this codec kinda targets cheapo FPGAs without much memory. Unfortunately
252 * it also limits us greatly in our choice of formats, hence the flag to disable
253 * strict_compliance */
254 static void encode_parse_params(VC2EncContext *s)
256 put_vc2_ue_uint(&s->pb, s->ver.major); /* VC-2 demands this to be 2 */
257 put_vc2_ue_uint(&s->pb, s->ver.minor); /* ^^ and this to be 0 */
258 put_vc2_ue_uint(&s->pb, s->profile); /* 3 to signal HQ profile */
259 put_vc2_ue_uint(&s->pb, s->level); /* 3 - 1080/720, 6 - 4K */
262 /* VC-2 11.3 - frame_size() */
263 static void encode_frame_size(VC2EncContext *s)
265 put_bits(&s->pb, 1, !s->strict_compliance);
266 if (!s->strict_compliance) {
267 AVCodecContext *avctx = s->avctx;
268 put_vc2_ue_uint(&s->pb, avctx->width);
269 put_vc2_ue_uint(&s->pb, avctx->height);
273 /* VC-2 11.3.3 - color_diff_sampling_format() */
274 static void encode_sample_fmt(VC2EncContext *s)
276 put_bits(&s->pb, 1, !s->strict_compliance);
277 if (!s->strict_compliance) {
279 if (s->chroma_x_shift == 1 && s->chroma_y_shift == 0)
281 else if (s->chroma_x_shift == 1 && s->chroma_y_shift == 1)
285 put_vc2_ue_uint(&s->pb, idx);
289 /* VC-2 11.3.4 - scan_format() */
290 static void encode_scan_format(VC2EncContext *s)
292 put_bits(&s->pb, 1, !s->strict_compliance);
293 if (!s->strict_compliance)
294 put_vc2_ue_uint(&s->pb, s->interlaced);
297 /* VC-2 11.3.5 - frame_rate() */
298 static void encode_frame_rate(VC2EncContext *s)
300 put_bits(&s->pb, 1, !s->strict_compliance);
301 if (!s->strict_compliance) {
302 AVCodecContext *avctx = s->avctx;
303 put_vc2_ue_uint(&s->pb, 0);
304 put_vc2_ue_uint(&s->pb, avctx->time_base.den);
305 put_vc2_ue_uint(&s->pb, avctx->time_base.num);
309 /* VC-2 11.3.6 - aspect_ratio() */
310 static void encode_aspect_ratio(VC2EncContext *s)
312 put_bits(&s->pb, 1, !s->strict_compliance);
313 if (!s->strict_compliance) {
314 AVCodecContext *avctx = s->avctx;
315 put_vc2_ue_uint(&s->pb, 0);
316 put_vc2_ue_uint(&s->pb, avctx->sample_aspect_ratio.num);
317 put_vc2_ue_uint(&s->pb, avctx->sample_aspect_ratio.den);
321 /* VC-2 11.3.7 - clean_area() */
322 static void encode_clean_area(VC2EncContext *s)
324 put_bits(&s->pb, 1, 0);
327 /* VC-2 11.3.8 - signal_range() */
328 static void encode_signal_range(VC2EncContext *s)
331 AVCodecContext *avctx = s->avctx;
332 const AVPixFmtDescriptor *fmt = av_pix_fmt_desc_get(avctx->pix_fmt);
333 const int depth = fmt->comp[0].depth;
334 if (depth == 8 && avctx->color_range == AVCOL_RANGE_JPEG) {
337 s->diff_offset = 128;
338 } else if (depth == 8 && (avctx->color_range == AVCOL_RANGE_MPEG ||
339 avctx->color_range == AVCOL_RANGE_UNSPECIFIED)) {
342 s->diff_offset = 128;
343 } else if (depth == 10) {
346 s->diff_offset = 512;
350 s->diff_offset = 2048;
352 put_bits(&s->pb, 1, !s->strict_compliance);
353 if (!s->strict_compliance)
354 put_vc2_ue_uint(&s->pb, idx);
357 /* VC-2 11.3.9 - color_spec() */
358 static void encode_color_spec(VC2EncContext *s)
360 AVCodecContext *avctx = s->avctx;
361 put_bits(&s->pb, 1, !s->strict_compliance);
362 if (!s->strict_compliance) {
364 put_vc2_ue_uint(&s->pb, 0);
367 put_bits(&s->pb, 1, 1);
368 if (avctx->color_primaries == AVCOL_PRI_BT470BG)
370 else if (avctx->color_primaries == AVCOL_PRI_SMPTE170M)
372 else if (avctx->color_primaries == AVCOL_PRI_SMPTE240M)
376 put_vc2_ue_uint(&s->pb, val);
379 put_bits(&s->pb, 1, 1);
380 if (avctx->colorspace == AVCOL_SPC_RGB)
382 else if (avctx->colorspace == AVCOL_SPC_YCOCG)
384 else if (avctx->colorspace == AVCOL_SPC_BT470BG)
388 put_vc2_ue_uint(&s->pb, val);
390 /* transfer function */
391 put_bits(&s->pb, 1, 1);
392 if (avctx->color_trc == AVCOL_TRC_LINEAR)
394 else if (avctx->color_trc == AVCOL_TRC_BT1361_ECG)
398 put_vc2_ue_uint(&s->pb, val);
402 /* VC-2 11.3 - source_parameters() */
403 static void encode_source_params(VC2EncContext *s)
405 encode_frame_size(s);
406 encode_sample_fmt(s);
407 encode_scan_format(s);
408 encode_frame_rate(s);
409 encode_aspect_ratio(s);
410 encode_clean_area(s);
411 encode_signal_range(s);
412 encode_color_spec(s);
415 /* VC-2 11 - sequence_header() */
416 static void encode_seq_header(VC2EncContext *s)
418 avpriv_align_put_bits(&s->pb);
419 encode_parse_params(s);
420 put_vc2_ue_uint(&s->pb, s->base_vf);
421 encode_source_params(s);
422 put_vc2_ue_uint(&s->pb, s->interlaced); /* Frames or fields coding */
425 /* VC-2 12.1 - picture_header() */
426 static void encode_picture_header(VC2EncContext *s)
428 avpriv_align_put_bits(&s->pb);
429 put_bits32(&s->pb, s->picture_number++);
432 /* VC-2 12.3.4.1 - slice_parameters() */
433 static void encode_slice_params(VC2EncContext *s)
435 put_vc2_ue_uint(&s->pb, s->num_x);
436 put_vc2_ue_uint(&s->pb, s->num_y);
437 put_vc2_ue_uint(&s->pb, s->prefix_bytes);
438 put_vc2_ue_uint(&s->pb, s->size_scaler);
441 /* 1st idx = LL, second - vertical, third - horizontal, fourth - total */
442 const uint8_t vc2_qm_col_tab[][4] = {
450 const uint8_t vc2_qm_flat_tab[][4] = {
458 static void init_custom_qm(VC2EncContext *s)
460 int level, orientation;
462 if (s->quant_matrix == VC2_QM_DEF) {
463 for (level = 0; level < s->wavelet_depth; level++) {
464 for (orientation = 0; orientation < 4; orientation++) {
466 s->quant[level][orientation] = ff_dirac_default_qmat[s->wavelet_idx][level][orientation];
468 s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];
471 } else if (s->quant_matrix == VC2_QM_COL) {
472 for (level = 0; level < s->wavelet_depth; level++) {
473 for (orientation = 0; orientation < 4; orientation++) {
474 s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];
478 for (level = 0; level < s->wavelet_depth; level++) {
479 for (orientation = 0; orientation < 4; orientation++) {
480 s->quant[level][orientation] = vc2_qm_flat_tab[level][orientation];
486 /* VC-2 12.3.4.2 - quant_matrix() */
487 static void encode_quant_matrix(VC2EncContext *s)
489 int level, custom_quant_matrix = 0;
490 if (s->wavelet_depth > 4 || s->quant_matrix != VC2_QM_DEF)
491 custom_quant_matrix = 1;
492 put_bits(&s->pb, 1, custom_quant_matrix);
493 if (custom_quant_matrix) {
495 put_vc2_ue_uint(&s->pb, s->quant[0][0]);
496 for (level = 0; level < s->wavelet_depth; level++) {
497 put_vc2_ue_uint(&s->pb, s->quant[level][1]);
498 put_vc2_ue_uint(&s->pb, s->quant[level][2]);
499 put_vc2_ue_uint(&s->pb, s->quant[level][3]);
502 for (level = 0; level < s->wavelet_depth; level++) {
503 s->quant[level][0] = ff_dirac_default_qmat[s->wavelet_idx][level][0];
504 s->quant[level][1] = ff_dirac_default_qmat[s->wavelet_idx][level][1];
505 s->quant[level][2] = ff_dirac_default_qmat[s->wavelet_idx][level][2];
506 s->quant[level][3] = ff_dirac_default_qmat[s->wavelet_idx][level][3];
511 /* VC-2 12.3 - transform_parameters() */
512 static void encode_transform_params(VC2EncContext *s)
514 put_vc2_ue_uint(&s->pb, s->wavelet_idx);
515 put_vc2_ue_uint(&s->pb, s->wavelet_depth);
517 encode_slice_params(s);
518 encode_quant_matrix(s);
521 /* VC-2 12.2 - wavelet_transform() */
522 static void encode_wavelet_transform(VC2EncContext *s)
524 encode_transform_params(s);
525 avpriv_align_put_bits(&s->pb);
526 /* Continued after DWT in encode_transform_data() */
529 /* VC-2 12 - picture_parse() */
530 static void encode_picture_start(VC2EncContext *s)
532 avpriv_align_put_bits(&s->pb);
533 encode_picture_header(s);
534 avpriv_align_put_bits(&s->pb);
535 encode_wavelet_transform(s);
538 #define QUANT(c, qf) (((c) << 2)/(qf))
540 /* VC-2 13.5.5.2 - slice_band() */
541 static void encode_subband(VC2EncContext *s, PutBitContext *pb, int sx, int sy,
542 SubBand *b, int quant)
546 const int left = b->width * (sx+0) / s->num_x;
547 const int right = b->width * (sx+1) / s->num_x;
548 const int top = b->height * (sy+0) / s->num_y;
549 const int bottom = b->height * (sy+1) / s->num_y;
551 const int qfactor = ff_dirac_qscale_tab[quant];
552 const uint8_t *len_lut = &s->coef_lut_len[quant*COEF_LUT_TAB];
553 const uint32_t *val_lut = &s->coef_lut_val[quant*COEF_LUT_TAB];
555 dwtcoef *coeff = b->buf + top * b->stride;
557 for (y = top; y < bottom; y++) {
558 for (x = left; x < right; x++) {
559 const int neg = coeff[x] < 0;
560 uint32_t c_abs = FFABS(coeff[x]);
561 if (c_abs < COEF_LUT_TAB) {
562 const uint8_t len = len_lut[c_abs];
566 put_bits(pb, len + 1, (val_lut[c_abs] << 1) | neg);
568 c_abs = QUANT(c_abs, qfactor);
569 put_vc2_ue_uint(pb, c_abs);
571 put_bits(pb, 1, neg);
578 static int count_hq_slice(VC2EncContext *s, int *cache,
579 int slice_x, int slice_y, int quant_idx)
582 uint8_t quants[MAX_DWT_LEVELS][4];
583 int bits = 0, p, level, orientation;
585 if (cache && cache[quant_idx])
586 return cache[quant_idx];
588 bits += 8*s->prefix_bytes;
589 bits += 8; /* quant_idx */
591 for (level = 0; level < s->wavelet_depth; level++)
592 for (orientation = !!level; orientation < 4; orientation++)
593 quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);
595 for (p = 0; p < 3; p++) {
596 int bytes_start, bytes_len, pad_s, pad_c;
597 bytes_start = bits >> 3;
599 for (level = 0; level < s->wavelet_depth; level++) {
600 for (orientation = !!level; orientation < 4; orientation++) {
601 SubBand *b = &s->plane[p].band[level][orientation];
603 const int q_idx = quants[level][orientation];
604 const uint8_t *len_lut = &s->coef_lut_len[q_idx*COEF_LUT_TAB];
605 const int qfactor = ff_dirac_qscale_tab[q_idx];
607 const int left = b->width * slice_x / s->num_x;
608 const int right = b->width *(slice_x+1) / s->num_x;
609 const int top = b->height * slice_y / s->num_y;
610 const int bottom = b->height *(slice_y+1) / s->num_y;
612 dwtcoef *buf = b->buf + top * b->stride;
614 for (y = top; y < bottom; y++) {
615 for (x = left; x < right; x++) {
616 uint32_t c_abs = FFABS(buf[x]);
617 if (c_abs < COEF_LUT_TAB) {
618 const int len = len_lut[c_abs];
619 bits += len + (len != 1);
621 c_abs = QUANT(c_abs, qfactor);
622 bits += count_vc2_ue_uint(c_abs);
630 bits += FFALIGN(bits, 8) - bits;
631 bytes_len = (bits >> 3) - bytes_start - 1;
632 pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;
633 pad_c = (pad_s*s->size_scaler) - bytes_len;
638 cache[quant_idx] = bits;
643 /* Approaches the best possible quantizer asymptotically, its kinda exaustive
644 * but we have a LUT to get the coefficient size in bits. Guaranteed to never
645 * overshoot, which is apparently very important when streaming */
646 static int rate_control(AVCodecContext *avctx, void *arg)
648 SliceArgs *slice_dat = arg;
649 VC2EncContext *s = slice_dat->ctx;
650 const int sx = slice_dat->x;
651 const int sy = slice_dat->y;
652 int bits_last = INT_MAX, quant_buf[2] = {-1, -1};
653 int quant = slice_dat->quant_idx, range = quant/5;
654 const int top = slice_dat->bits_ceil;
655 const int bottom = slice_dat->bits_floor;
656 int bits = count_hq_slice(s, slice_dat->cache, sx, sy, quant);
657 range -= range & 1; /* Make it an even number */
658 while ((bits > top) || (bits < bottom)) {
659 range *= bits > top ? +1 : -1;
660 quant = av_clip(quant + range, 0, s->q_ceil);
661 bits = count_hq_slice(s, slice_dat->cache, sx, sy, quant);
662 range = av_clip(range/2, 1, s->q_ceil);
663 if (quant_buf[1] == quant) {
664 quant = bits_last < bits ? quant_buf[0] : quant;
665 bits = bits_last < bits ? bits_last : bits;
668 quant_buf[1] = quant_buf[0];
669 quant_buf[0] = quant;
672 slice_dat->quant_idx = av_clip(quant, 0, s->q_ceil);
673 slice_dat->bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;
674 slice_dat->bytes_left = s->slice_max_bytes - slice_dat->bytes;
679 static void calc_slice_sizes(VC2EncContext *s)
681 int slice_x, slice_y;
682 SliceArgs *enc_args = s->slice_args;
684 for (slice_y = 0; slice_y < s->num_y; slice_y++) {
685 for (slice_x = 0; slice_x < s->num_x; slice_x++) {
686 SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
690 args->bits_ceil = s->slice_max_bytes << 3;
691 args->bits_floor = s->slice_min_bytes << 3;
692 memset(args->cache, 0, MAX_QUANT_INDEX*sizeof(*args->cache));
696 /* Determine quantization indices and bytes per slice */
697 s->avctx->execute(s->avctx, rate_control, enc_args, NULL, s->num_x*s->num_y,
701 /* VC-2 13.5.3 - hq_slice */
702 static int encode_hq_slice(AVCodecContext *avctx, void *arg)
704 SliceArgs *slice_dat = arg;
705 VC2EncContext *s = slice_dat->ctx;
706 PutBitContext *pb = &slice_dat->pb;
707 const int slice_x = slice_dat->x;
708 const int slice_y = slice_dat->y;
709 const int quant_idx = slice_dat->quant_idx;
710 const int slice_bytes_max = slice_dat->bytes;
711 uint8_t quants[MAX_DWT_LEVELS][4];
712 int p, level, orientation;
714 avpriv_align_put_bits(pb);
715 skip_put_bytes(pb, s->prefix_bytes);
716 put_bits(pb, 8, quant_idx);
718 /* Slice quantization (slice_quantizers() in the specs) */
719 for (level = 0; level < s->wavelet_depth; level++)
720 for (orientation = !!level; orientation < 4; orientation++)
721 quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);
723 /* Luma + 2 Chroma planes */
724 for (p = 0; p < 3; p++) {
725 int bytes_start, bytes_len, pad_s, pad_c;
726 bytes_start = put_bits_count(pb) >> 3;
728 for (level = 0; level < s->wavelet_depth; level++) {
729 for (orientation = !!level; orientation < 4; orientation++) {
730 encode_subband(s, pb, slice_x, slice_y,
731 &s->plane[p].band[level][orientation],
732 quants[level][orientation]);
735 avpriv_align_put_bits(pb);
736 bytes_len = (put_bits_count(pb) >> 3) - bytes_start - 1;
738 int len_diff = slice_bytes_max - (put_bits_count(pb) >> 3);
739 pad_s = FFALIGN((bytes_len + len_diff), s->size_scaler)/s->size_scaler;
740 pad_c = (pad_s*s->size_scaler) - bytes_len;
742 pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;
743 pad_c = (pad_s*s->size_scaler) - bytes_len;
745 pb->buf[bytes_start] = pad_s;
747 skip_put_bytes(pb, pad_c);
753 /* VC-2 13.5.1 - low_delay_transform_data() */
754 static int encode_slices(VC2EncContext *s)
757 int i, slice_x, slice_y, skip = 0;
759 SliceArgs *enc_args = s->slice_args;
761 int bytes_top[SLICE_REDIST_TOTAL] = {0};
762 SliceArgs *top_loc[SLICE_REDIST_TOTAL] = {NULL};
764 avpriv_align_put_bits(&s->pb);
765 flush_put_bits(&s->pb);
766 buf = put_bits_ptr(&s->pb);
768 for (slice_y = 0; slice_y < s->num_y; slice_y++) {
769 for (slice_x = 0; slice_x < s->num_x; slice_x++) {
770 SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
771 bytes_left += args->bytes_left;
772 for (i = 0; i < FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y); i++) {
773 if (args->bytes > bytes_top[i]) {
774 bytes_top[i] = args->bytes;
784 for (i = 0; i < FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y); i++) {
786 int bits, bytes, diff, prev_bytes, new_idx;
789 if (!top_loc[i] || !top_loc[i]->quant_idx)
792 prev_bytes = args->bytes;
793 new_idx = av_clip(args->quant_idx - 1, 0, s->q_ceil);
794 bits = count_hq_slice(s, args->cache, args->x, args->y, new_idx);
795 bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes;
796 diff = bytes - prev_bytes;
797 if ((bytes_left - diff) >= 0) {
798 args->quant_idx = new_idx;
808 for (slice_y = 0; slice_y < s->num_y; slice_y++) {
809 for (slice_x = 0; slice_x < s->num_x; slice_x++) {
810 SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
811 init_put_bits(&args->pb, buf + skip, args->bytes);
812 s->q_avg = (s->q_avg + args->quant_idx)/2;
817 s->avctx->execute(s->avctx, encode_hq_slice, enc_args, NULL, s->num_x*s->num_y,
820 skip_put_bytes(&s->pb, skip);
826 * Transform basics for a 3 level transform
827 * |---------------------------------------------------------------------|
828 * | LL-0 | HL-0 | | |
829 * |--------|-------| HL-1 | |
830 * | LH-0 | HH-0 | | |
831 * |----------------|-----------------| HL-2 |
835 * |----------------------------------|----------------------------------|
843 * |---------------------------------------------------------------------|
845 * DWT transforms are generally applied by splitting the image in two vertically
846 * and applying a low pass transform on the left part and a corresponding high
847 * pass transform on the right hand side. This is known as the horizontal filter
849 * After that, the same operation is performed except the image is divided
850 * horizontally, with the high pass on the lower and the low pass on the higher
852 * Therefore, you're left with 4 subdivisions - known as low-low, low-high,
853 * high-low and high-high. They're referred to as orientations in the decoder
856 * The LL (low-low) area contains the original image downsampled by the amount
857 * of levels. The rest of the areas can be thought as the details needed
858 * to restore the image perfectly to its original size.
860 static int dwt_plane(AVCodecContext *avctx, void *arg)
862 TransformArgs *transform_dat = arg;
863 VC2EncContext *s = transform_dat->ctx;
864 const void *frame_data = transform_dat->idata;
865 const ptrdiff_t linesize = transform_dat->istride;
866 const int field = transform_dat->field;
867 const Plane *p = transform_dat->plane;
868 VC2TransformContext *t = &transform_dat->t;
869 dwtcoef *buf = p->coef_buf;
870 const int idx = s->wavelet_idx;
871 const int skip = 1 + s->interlaced;
873 int x, y, level, offset;
874 ptrdiff_t pix_stride = linesize >> (s->bpp - 1);
879 } else if (field == 2) {
887 const uint8_t *pix = (const uint8_t *)frame_data + offset;
888 for (y = 0; y < p->height*skip; y+=skip) {
889 for (x = 0; x < p->width; x++) {
890 buf[x] = pix[x] - s->diff_offset;
892 buf += p->coef_stride;
896 const uint16_t *pix = (const uint16_t *)frame_data + offset;
897 for (y = 0; y < p->height*skip; y+=skip) {
898 for (x = 0; x < p->width; x++) {
899 buf[x] = pix[x] - s->diff_offset;
901 buf += p->coef_stride;
906 memset(buf, 0, p->coef_stride * (p->dwt_height - p->height) * sizeof(dwtcoef));
908 for (level = s->wavelet_depth-1; level >= 0; level--) {
909 const SubBand *b = &p->band[level][0];
910 t->vc2_subband_dwt[idx](t, p->coef_buf, p->coef_stride,
911 b->width, b->height);
917 static void encode_frame(VC2EncContext *s, const AVFrame *frame,
918 const char *aux_data, int field)
922 /* Sequence header */
923 encode_parse_info(s, DIRAC_PCODE_SEQ_HEADER);
924 encode_seq_header(s);
926 /* Encoder version */
928 encode_parse_info(s, DIRAC_PCODE_AUX);
929 avpriv_put_string(&s->pb, aux_data, 1);
933 encode_parse_info(s, DIRAC_PCODE_PICTURE_HQ);
934 encode_picture_start(s);
936 for (i = 0; i < 3; i++) {
937 s->transform_args[i].ctx = s;
938 s->transform_args[i].field = field;
939 s->transform_args[i].plane = &s->plane[i];
940 s->transform_args[i].idata = frame->data[i];
941 s->transform_args[i].istride = frame->linesize[i];
944 /* Do a DWT transform */
945 s->avctx->execute(s->avctx, dwt_plane, s->transform_args, NULL, 3,
946 sizeof(TransformArgs));
948 /* Calculate per-slice quantizers and sizes */
951 /* Init planes and encode slices */
955 encode_parse_info(s, DIRAC_PCODE_END_SEQ);
958 static av_cold int vc2_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
959 const AVFrame *frame, int *got_packet_ptr)
962 int max_frame_bytes, sig_size = 256;
963 VC2EncContext *s = avctx->priv_data;
964 const char aux_data[] = LIBAVCODEC_IDENT;
965 const int aux_data_size = sizeof(aux_data);
966 const int header_size = 100 + aux_data_size;
967 int64_t r_bitrate = avctx->bit_rate >> (s->interlaced);
972 s->last_parse_code = 0;
973 s->next_parse_offset = 0;
976 max_frame_bytes = (av_rescale(r_bitrate, s->avctx->time_base.num,
977 s->avctx->time_base.den) >> 3) - header_size;
979 /* Find an appropriate size scaler */
980 while (sig_size > 255) {
981 s->slice_max_bytes = FFALIGN(av_rescale(max_frame_bytes, 1,
982 s->num_x*s->num_y), s->size_scaler);
983 s->slice_max_bytes += 4 + s->prefix_bytes;
984 sig_size = s->slice_max_bytes/s->size_scaler; /* Signalled slize size */
985 s->size_scaler <<= 1;
988 s->slice_min_bytes = s->slice_max_bytes - s->slice_max_bytes*(s->tolerance/100.0f);
990 ret = ff_alloc_packet2(avctx, avpkt, max_frame_bytes*3, 0);
992 av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
995 init_put_bits(&s->pb, avpkt->data, avpkt->size);
998 encode_frame(s, frame, aux_data, s->interlaced);
1000 encode_frame(s, frame, NULL, 2);
1002 flush_put_bits(&s->pb);
1003 avpkt->size = put_bits_count(&s->pb) >> 3;
1005 *got_packet_ptr = 1;
1010 static av_cold int vc2_encode_end(AVCodecContext *avctx)
1013 VC2EncContext *s = avctx->priv_data;
1015 av_log(avctx, AV_LOG_INFO, "Qavg: %i\n", s->q_avg);
1017 for (i = 0; i < 3; i++) {
1018 ff_vc2enc_free_transforms(&s->transform_args[i].t);
1019 av_freep(&s->plane[i].coef_buf);
1022 av_freep(&s->slice_args);
1023 av_freep(&s->coef_lut_len);
1024 av_freep(&s->coef_lut_val);
1029 static int minimum_frame_bits(VC2EncContext *s)
1031 int slice_x, slice_y, bits = 0;
1032 s->size_scaler = 64;
1033 for (slice_y = 0; slice_y < s->num_y; slice_y++) {
1034 for (slice_x = 0; slice_x < s->num_x; slice_x++) {
1035 bits += count_hq_slice(s, NULL, slice_x, slice_y, s->q_ceil);
1041 static av_cold int vc2_encode_init(AVCodecContext *avctx)
1045 int i, j, level, o, shift;
1046 int64_t bits_per_frame, min_bits_per_frame;
1047 VC2EncContext *s = avctx->priv_data;
1049 s->picture_number = 0;
1051 /* Total allowed quantization range */
1052 s->q_ceil = MAX_QUANT_INDEX;
1060 s->strict_compliance = 1;
1063 s->slice_max_bytes = 0;
1064 s->slice_min_bytes = 0;
1066 /* Mark unknown as progressive */
1067 s->interlaced = !((avctx->field_order == AV_FIELD_UNKNOWN) ||
1068 (avctx->field_order == AV_FIELD_PROGRESSIVE));
1070 if (avctx->pix_fmt == AV_PIX_FMT_YUV422P10) {
1071 if (avctx->width == 1280 && avctx->height == 720) {
1073 if (avctx->time_base.num == 1001 && avctx->time_base.den == 60000)
1075 if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1077 } else if (avctx->width == 1920 && avctx->height == 1080) {
1079 if (s->interlaced) {
1080 if (avctx->time_base.num == 1001 && avctx->time_base.den == 30000)
1082 if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1085 if (avctx->time_base.num == 1001 && avctx->time_base.den == 60000)
1087 if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1089 if (avctx->time_base.num == 1001 && avctx->time_base.den == 24000)
1092 } else if (avctx->width == 3840 && avctx->height == 2160) {
1094 if (avctx->time_base.num == 1001 && avctx->time_base.den == 60000)
1096 if (avctx->time_base.num == 1 && avctx->time_base.den == 50)
1101 if (s->interlaced && s->base_vf <= 0) {
1102 av_log(avctx, AV_LOG_ERROR, "Interlacing not supported with non standard formats!\n");
1103 return AVERROR_UNKNOWN;
1107 av_log(avctx, AV_LOG_WARNING, "Interlacing enabled!\n");
1109 if ((s->slice_width & (s->slice_width - 1)) ||
1110 (s->slice_height & (s->slice_height - 1))) {
1111 av_log(avctx, AV_LOG_ERROR, "Slice size is not a power of two!\n");
1112 return AVERROR_UNKNOWN;
1115 if ((s->slice_width > avctx->width) ||
1116 (s->slice_height > avctx->height)) {
1117 av_log(avctx, AV_LOG_ERROR, "Slice size is bigger than the image!\n");
1118 return AVERROR_UNKNOWN;
1121 if (s->base_vf <= 0) {
1122 if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
1123 s->strict_compliance = s->base_vf = 0;
1124 av_log(avctx, AV_LOG_WARNING, "Disabling strict compliance\n");
1126 av_log(avctx, AV_LOG_WARNING, "Given format does not strictly comply with "
1127 "the specifications, please add a -strict -1 flag to use it\n");
1128 return AVERROR_UNKNOWN;
1131 av_log(avctx, AV_LOG_INFO, "Selected base video format = %i\n", s->base_vf);
1134 avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1136 /* Planes initialization */
1137 for (i = 0; i < 3; i++) {
1140 p->width = avctx->width >> (i ? s->chroma_x_shift : 0);
1141 p->height = avctx->height >> (i ? s->chroma_y_shift : 0);
1144 p->dwt_width = w = FFALIGN(p->width, (1 << s->wavelet_depth));
1145 p->dwt_height = h = FFALIGN(p->height, (1 << s->wavelet_depth));
1146 p->coef_stride = FFALIGN(p->dwt_width, 32);
1147 p->coef_buf = av_malloc(p->coef_stride*p->dwt_height*sizeof(dwtcoef));
1150 for (level = s->wavelet_depth-1; level >= 0; level--) {
1153 for (o = 0; o < 4; o++) {
1154 b = &p->band[level][o];
1157 b->stride = p->coef_stride;
1158 shift = (o > 1)*b->height*b->stride + (o & 1)*b->width;
1159 b->buf = p->coef_buf + shift;
1164 if (ff_vc2enc_init_transforms(&s->transform_args[i].t,
1165 s->plane[i].coef_stride,
1166 s->plane[i].dwt_height))
1171 s->num_x = s->plane[0].dwt_width/s->slice_width;
1172 s->num_y = s->plane[0].dwt_height/s->slice_height;
1174 s->slice_args = av_malloc(s->num_x*s->num_y*sizeof(SliceArgs));
1179 s->coef_lut_len = av_malloc(COEF_LUT_TAB*s->q_ceil*sizeof(*s->coef_lut_len));
1180 if (!s->coef_lut_len)
1183 s->coef_lut_val = av_malloc(COEF_LUT_TAB*s->q_ceil*sizeof(*s->coef_lut_val));
1184 if (!s->coef_lut_val)
1187 for (i = 0; i < s->q_ceil; i++) {
1188 for (j = 0; j < COEF_LUT_TAB; j++) {
1189 uint8_t *len_lut = &s->coef_lut_len[i*COEF_LUT_TAB];
1190 uint32_t *val_lut = &s->coef_lut_val[i*COEF_LUT_TAB];
1191 get_vc2_ue_uint(QUANT(j, ff_dirac_qscale_tab[i]),
1192 &len_lut[j], &val_lut[j]);
1196 bits_per_frame = av_rescale(avctx->bit_rate, avctx->time_base.num,
1197 avctx->time_base.den);
1198 min_bits_per_frame = minimum_frame_bits(s) + 8*sizeof(LIBAVCODEC_IDENT) + 8*40 + 8*20000;
1199 if (bits_per_frame < min_bits_per_frame) {
1201 min_bits_per_frame += min_bits_per_frame + min_bits_per_frame/2;
1202 avctx->bit_rate = av_rescale(min_bits_per_frame, avctx->time_base.den,
1203 avctx->time_base.num);
1204 av_log(avctx, AV_LOG_WARNING,
1205 "Bitrate too low, clipping to minimum = %li Mbps!\n",
1206 avctx->bit_rate/1000000);
1212 vc2_encode_end(avctx);
1213 av_log(avctx, AV_LOG_ERROR, "Unable to allocate memory!\n");
1214 return AVERROR(ENOMEM);
1217 #define VC2ENC_FLAGS (AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
1218 static const AVOption vc2enc_options[] = {
1219 {"tolerance", "Max undershoot in percent", offsetof(VC2EncContext, tolerance), AV_OPT_TYPE_DOUBLE, {.dbl = 5.0f}, 0.0f, 45.0f, VC2ENC_FLAGS, "tolerance"},
1220 {"slice_width", "Slice width", offsetof(VC2EncContext, slice_width), AV_OPT_TYPE_INT, {.i64 = 64}, 32, 1024, VC2ENC_FLAGS, "slice_width"},
1221 {"slice_height", "Slice height", offsetof(VC2EncContext, slice_height), AV_OPT_TYPE_INT, {.i64 = 32}, 8, 1024, VC2ENC_FLAGS, "slice_height"},
1222 {"wavelet_depth", "Transform depth", offsetof(VC2EncContext, wavelet_depth), AV_OPT_TYPE_INT, {.i64 = 4}, 1, 5, VC2ENC_FLAGS, "wavelet_depth"},
1223 {"wavelet_type", "Transform type", offsetof(VC2EncContext, wavelet_idx), AV_OPT_TYPE_INT, {.i64 = VC2_TRANSFORM_9_7}, 0, VC2_TRANSFORMS_NB, VC2ENC_FLAGS, "wavelet_idx"},
1224 {"9_7", "Deslauriers-Dubuc (9,7)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_9_7}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1225 {"5_3", "LeGall (5,3)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_5_3}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1226 {"haar", "Haar (with shift)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_HAAR_S}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1227 {"haar_noshift", "Haar (without shift)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_HAAR}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1228 {"qm", "Custom quantization matrix", offsetof(VC2EncContext, quant_matrix), AV_OPT_TYPE_INT, {.i64 = VC2_QM_DEF}, 0, VC2_QM_NB, VC2ENC_FLAGS, "quant_matrix"},
1229 {"default", "Default from the specifications", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_DEF}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1230 {"color", "Prevents low bitrate discoloration", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_COL}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1231 {"flat", "Optimize for PSNR", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_FLAT}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1235 static const AVClass vc2enc_class = {
1236 .class_name = "SMPTE VC-2 encoder",
1237 .category = AV_CLASS_CATEGORY_ENCODER,
1238 .option = vc2enc_options,
1239 .item_name = av_default_item_name,
1240 .version = LIBAVUTIL_VERSION_INT
1243 static const AVCodecDefault vc2enc_defaults[] = {
1244 { "b", "600000000" },
1248 static const enum AVPixelFormat allowed_pix_fmts[] = {
1249 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
1250 AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
1251 AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
1255 AVCodec ff_vc2_encoder = {
1257 .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-2"),
1258 .type = AVMEDIA_TYPE_VIDEO,
1259 .id = AV_CODEC_ID_DIRAC,
1260 .priv_data_size = sizeof(VC2EncContext),
1261 .init = vc2_encode_init,
1262 .close = vc2_encode_end,
1263 .capabilities = AV_CODEC_CAP_SLICE_THREADS,
1264 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1265 .encode2 = vc2_encode_frame,
1266 .priv_class = &vc2enc_class,
1267 .defaults = vc2enc_defaults,
1268 .pix_fmts = allowed_pix_fmts