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 /* The limited size resolution of each slice forces us to do this */
33 #define SSIZE_ROUND(b) (FFALIGN((b), s->size_scaler) + 4 + s->prefix_bytes)
35 /* Decides the cutoff point in # of slices to distribute the leftover bytes */
36 #define SLICE_REDIST_TOTAL 150
38 typedef struct VC2BaseVideoFormat {
39 enum AVPixelFormat pix_fmt;
41 int width, height, interlaced, level;
45 static const VC2BaseVideoFormat base_video_fmts[] = {
46 { 0 }, /* Custom format, here just to make indexing equal to base_vf */
47 { AV_PIX_FMT_YUV420P, { 1001, 15000 }, 176, 120, 0, 1, "QSIF525" },
48 { AV_PIX_FMT_YUV420P, { 2, 25 }, 176, 144, 0, 1, "QCIF" },
49 { AV_PIX_FMT_YUV420P, { 1001, 15000 }, 352, 240, 0, 1, "SIF525" },
50 { AV_PIX_FMT_YUV420P, { 2, 25 }, 352, 288, 0, 1, "CIF" },
51 { AV_PIX_FMT_YUV420P, { 1001, 15000 }, 704, 480, 0, 1, "4SIF525" },
52 { AV_PIX_FMT_YUV420P, { 2, 25 }, 704, 576, 0, 1, "4CIF" },
54 { AV_PIX_FMT_YUV422P10, { 1001, 30000 }, 720, 480, 1, 2, "SD480I-60" },
55 { AV_PIX_FMT_YUV422P10, { 1, 25 }, 720, 576, 1, 2, "SD576I-50" },
57 { AV_PIX_FMT_YUV422P10, { 1001, 60000 }, 1280, 720, 0, 3, "HD720P-60" },
58 { AV_PIX_FMT_YUV422P10, { 1, 50 }, 1280, 720, 0, 3, "HD720P-50" },
59 { AV_PIX_FMT_YUV422P10, { 1001, 30000 }, 1920, 1080, 1, 3, "HD1080I-60" },
60 { AV_PIX_FMT_YUV422P10, { 1, 25 }, 1920, 1080, 1, 3, "HD1080I-50" },
61 { AV_PIX_FMT_YUV422P10, { 1001, 60000 }, 1920, 1080, 0, 3, "HD1080P-60" },
62 { AV_PIX_FMT_YUV422P10, { 1, 50 }, 1920, 1080, 0, 3, "HD1080P-50" },
64 { AV_PIX_FMT_YUV444P12, { 1, 24 }, 2048, 1080, 0, 4, "DC2K" },
65 { AV_PIX_FMT_YUV444P12, { 1, 24 }, 4096, 2160, 0, 5, "DC4K" },
67 { AV_PIX_FMT_YUV422P10, { 1001, 60000 }, 3840, 2160, 0, 6, "UHDTV 4K-60" },
68 { AV_PIX_FMT_YUV422P10, { 1, 50 }, 3840, 2160, 0, 6, "UHDTV 4K-50" },
70 { AV_PIX_FMT_YUV422P10, { 1001, 60000 }, 7680, 4320, 0, 7, "UHDTV 8K-60" },
71 { AV_PIX_FMT_YUV422P10, { 1, 50 }, 7680, 4320, 0, 7, "UHDTV 8K-50" },
73 { AV_PIX_FMT_YUV422P10, { 1001, 24000 }, 1920, 1080, 0, 3, "HD1080P-24" },
74 { AV_PIX_FMT_YUV422P10, { 1001, 30000 }, 720, 486, 1, 2, "SD Pro486" },
76 static const int base_video_fmts_len = FF_ARRAY_ELEMS(base_video_fmts);
86 typedef struct SubBand {
93 typedef struct Plane {
94 SubBand band[MAX_DWT_LEVELS][4];
100 ptrdiff_t coef_stride;
103 typedef struct SliceArgs {
105 int cache[DIRAC_MAX_QUANT_INDEX];
115 typedef struct TransformArgs {
121 VC2TransformContext t;
124 typedef struct VC2EncContext {
128 AVCodecContext *avctx;
129 DiracVersionInfo ver;
131 SliceArgs *slice_args;
132 TransformArgs transform_args[3];
134 /* For conversion from unsigned pixel values to signed */
140 uint32_t picture_number;
142 /* Base video format */
147 /* Quantization matrix */
148 uint8_t quant[MAX_DWT_LEVELS][4];
149 int custom_quant_matrix;
152 uint32_t qmagic_lut[116][2];
154 int num_x; /* #slices horizontally */
155 int num_y; /* #slices vertically */
161 /* Rate control stuff */
172 int strict_compliance;
176 enum VC2_QM quant_matrix;
178 /* Parse code state */
179 uint32_t next_parse_offset;
180 enum DiracParseCodes last_parse_code;
183 static av_always_inline void put_vc2_ue_uint(PutBitContext *pb, uint32_t val)
186 int pbits = 0, bits = 0, topbit = 1, maxval = 1;
193 while (val > maxval) {
199 bits = ff_log2(topbit);
201 for (i = 0; i < bits; i++) {
208 put_bits(pb, bits*2 + 1, (pbits << 1) | 1);
211 static av_always_inline int count_vc2_ue_uint(uint32_t val)
213 int topbit = 1, maxval = 1;
218 while (val > maxval) {
224 return ff_log2(topbit)*2 + 1;
227 /* VC-2 10.4 - parse_info() */
228 static void encode_parse_info(VC2EncContext *s, enum DiracParseCodes pcode)
230 uint32_t cur_pos, dist;
232 avpriv_align_put_bits(&s->pb);
234 cur_pos = put_bits_count(&s->pb) >> 3;
237 avpriv_put_string(&s->pb, "BBCD", 0);
240 put_bits(&s->pb, 8, pcode);
242 /* Next parse offset */
243 dist = cur_pos - s->next_parse_offset;
244 AV_WB32(s->pb.buf + s->next_parse_offset + 5, dist);
245 s->next_parse_offset = cur_pos;
246 put_bits32(&s->pb, pcode == DIRAC_PCODE_END_SEQ ? 13 : 0);
248 /* Last parse offset */
249 put_bits32(&s->pb, s->last_parse_code == DIRAC_PCODE_END_SEQ ? 13 : dist);
251 s->last_parse_code = pcode;
254 /* VC-2 11.1 - parse_parameters()
255 * The level dictates what the decoder should expect in terms of resolution
256 * and allows it to quickly reject whatever it can't support. Remember,
257 * this codec kinda targets cheapo FPGAs without much memory. Unfortunately
258 * it also limits us greatly in our choice of formats, hence the flag to disable
259 * strict_compliance */
260 static void encode_parse_params(VC2EncContext *s)
262 put_vc2_ue_uint(&s->pb, s->ver.major); /* VC-2 demands this to be 2 */
263 put_vc2_ue_uint(&s->pb, s->ver.minor); /* ^^ and this to be 0 */
264 put_vc2_ue_uint(&s->pb, s->profile); /* 3 to signal HQ profile */
265 put_vc2_ue_uint(&s->pb, s->level); /* 3 - 1080/720, 6 - 4K */
268 /* VC-2 11.3 - frame_size() */
269 static void encode_frame_size(VC2EncContext *s)
271 put_bits(&s->pb, 1, !s->strict_compliance);
272 if (!s->strict_compliance) {
273 AVCodecContext *avctx = s->avctx;
274 put_vc2_ue_uint(&s->pb, avctx->width);
275 put_vc2_ue_uint(&s->pb, avctx->height);
279 /* VC-2 11.3.3 - color_diff_sampling_format() */
280 static void encode_sample_fmt(VC2EncContext *s)
282 put_bits(&s->pb, 1, !s->strict_compliance);
283 if (!s->strict_compliance) {
285 if (s->chroma_x_shift == 1 && s->chroma_y_shift == 0)
287 else if (s->chroma_x_shift == 1 && s->chroma_y_shift == 1)
291 put_vc2_ue_uint(&s->pb, idx);
295 /* VC-2 11.3.4 - scan_format() */
296 static void encode_scan_format(VC2EncContext *s)
298 put_bits(&s->pb, 1, !s->strict_compliance);
299 if (!s->strict_compliance)
300 put_vc2_ue_uint(&s->pb, s->interlaced);
303 /* VC-2 11.3.5 - frame_rate() */
304 static void encode_frame_rate(VC2EncContext *s)
306 put_bits(&s->pb, 1, !s->strict_compliance);
307 if (!s->strict_compliance) {
308 AVCodecContext *avctx = s->avctx;
309 put_vc2_ue_uint(&s->pb, 0);
310 put_vc2_ue_uint(&s->pb, avctx->time_base.den);
311 put_vc2_ue_uint(&s->pb, avctx->time_base.num);
315 /* VC-2 11.3.6 - aspect_ratio() */
316 static void encode_aspect_ratio(VC2EncContext *s)
318 put_bits(&s->pb, 1, !s->strict_compliance);
319 if (!s->strict_compliance) {
320 AVCodecContext *avctx = s->avctx;
321 put_vc2_ue_uint(&s->pb, 0);
322 put_vc2_ue_uint(&s->pb, avctx->sample_aspect_ratio.num);
323 put_vc2_ue_uint(&s->pb, avctx->sample_aspect_ratio.den);
327 /* VC-2 11.3.7 - clean_area() */
328 static void encode_clean_area(VC2EncContext *s)
330 put_bits(&s->pb, 1, 0);
333 /* VC-2 11.3.8 - signal_range() */
334 static void encode_signal_range(VC2EncContext *s)
336 put_bits(&s->pb, 1, !s->strict_compliance);
337 if (!s->strict_compliance)
338 put_vc2_ue_uint(&s->pb, s->bpp_idx);
341 /* VC-2 11.3.9 - color_spec() */
342 static void encode_color_spec(VC2EncContext *s)
344 AVCodecContext *avctx = s->avctx;
345 put_bits(&s->pb, 1, !s->strict_compliance);
346 if (!s->strict_compliance) {
348 put_vc2_ue_uint(&s->pb, 0);
351 put_bits(&s->pb, 1, 1);
352 if (avctx->color_primaries == AVCOL_PRI_BT470BG)
354 else if (avctx->color_primaries == AVCOL_PRI_SMPTE170M)
356 else if (avctx->color_primaries == AVCOL_PRI_SMPTE240M)
360 put_vc2_ue_uint(&s->pb, val);
363 put_bits(&s->pb, 1, 1);
364 if (avctx->colorspace == AVCOL_SPC_RGB)
366 else if (avctx->colorspace == AVCOL_SPC_YCOCG)
368 else if (avctx->colorspace == AVCOL_SPC_BT470BG)
372 put_vc2_ue_uint(&s->pb, val);
374 /* transfer function */
375 put_bits(&s->pb, 1, 1);
376 if (avctx->color_trc == AVCOL_TRC_LINEAR)
378 else if (avctx->color_trc == AVCOL_TRC_BT1361_ECG)
382 put_vc2_ue_uint(&s->pb, val);
386 /* VC-2 11.3 - source_parameters() */
387 static void encode_source_params(VC2EncContext *s)
389 encode_frame_size(s);
390 encode_sample_fmt(s);
391 encode_scan_format(s);
392 encode_frame_rate(s);
393 encode_aspect_ratio(s);
394 encode_clean_area(s);
395 encode_signal_range(s);
396 encode_color_spec(s);
399 /* VC-2 11 - sequence_header() */
400 static void encode_seq_header(VC2EncContext *s)
402 avpriv_align_put_bits(&s->pb);
403 encode_parse_params(s);
404 put_vc2_ue_uint(&s->pb, s->base_vf);
405 encode_source_params(s);
406 put_vc2_ue_uint(&s->pb, s->interlaced); /* Frames or fields coding */
409 /* VC-2 12.1 - picture_header() */
410 static void encode_picture_header(VC2EncContext *s)
412 avpriv_align_put_bits(&s->pb);
413 put_bits32(&s->pb, s->picture_number++);
416 /* VC-2 12.3.4.1 - slice_parameters() */
417 static void encode_slice_params(VC2EncContext *s)
419 put_vc2_ue_uint(&s->pb, s->num_x);
420 put_vc2_ue_uint(&s->pb, s->num_y);
421 put_vc2_ue_uint(&s->pb, s->prefix_bytes);
422 put_vc2_ue_uint(&s->pb, s->size_scaler);
425 /* 1st idx = LL, second - vertical, third - horizontal, fourth - total */
426 const uint8_t vc2_qm_col_tab[][4] = {
434 const uint8_t vc2_qm_flat_tab[][4] = {
442 static void init_quant_matrix(VC2EncContext *s)
444 int level, orientation;
446 if (s->wavelet_depth <= 4 && s->quant_matrix == VC2_QM_DEF) {
447 s->custom_quant_matrix = 0;
448 for (level = 0; level < s->wavelet_depth; level++) {
449 s->quant[level][0] = ff_dirac_default_qmat[s->wavelet_idx][level][0];
450 s->quant[level][1] = ff_dirac_default_qmat[s->wavelet_idx][level][1];
451 s->quant[level][2] = ff_dirac_default_qmat[s->wavelet_idx][level][2];
452 s->quant[level][3] = ff_dirac_default_qmat[s->wavelet_idx][level][3];
457 s->custom_quant_matrix = 1;
459 if (s->quant_matrix == VC2_QM_DEF) {
460 for (level = 0; level < s->wavelet_depth; level++) {
461 for (orientation = 0; orientation < 4; orientation++) {
463 s->quant[level][orientation] = ff_dirac_default_qmat[s->wavelet_idx][level][orientation];
465 s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];
468 } else if (s->quant_matrix == VC2_QM_COL) {
469 for (level = 0; level < s->wavelet_depth; level++) {
470 for (orientation = 0; orientation < 4; orientation++) {
471 s->quant[level][orientation] = vc2_qm_col_tab[level][orientation];
475 for (level = 0; level < s->wavelet_depth; level++) {
476 for (orientation = 0; orientation < 4; orientation++) {
477 s->quant[level][orientation] = vc2_qm_flat_tab[level][orientation];
483 /* VC-2 12.3.4.2 - quant_matrix() */
484 static void encode_quant_matrix(VC2EncContext *s)
487 put_bits(&s->pb, 1, s->custom_quant_matrix);
488 if (s->custom_quant_matrix) {
489 put_vc2_ue_uint(&s->pb, s->quant[0][0]);
490 for (level = 0; level < s->wavelet_depth; level++) {
491 put_vc2_ue_uint(&s->pb, s->quant[level][1]);
492 put_vc2_ue_uint(&s->pb, s->quant[level][2]);
493 put_vc2_ue_uint(&s->pb, s->quant[level][3]);
498 /* VC-2 12.3 - transform_parameters() */
499 static void encode_transform_params(VC2EncContext *s)
501 put_vc2_ue_uint(&s->pb, s->wavelet_idx);
502 put_vc2_ue_uint(&s->pb, s->wavelet_depth);
504 encode_slice_params(s);
505 encode_quant_matrix(s);
508 /* VC-2 12.2 - wavelet_transform() */
509 static void encode_wavelet_transform(VC2EncContext *s)
511 encode_transform_params(s);
512 avpriv_align_put_bits(&s->pb);
515 /* VC-2 12 - picture_parse() */
516 static void encode_picture_start(VC2EncContext *s)
518 avpriv_align_put_bits(&s->pb);
519 encode_picture_header(s);
520 avpriv_align_put_bits(&s->pb);
521 encode_wavelet_transform(s);
524 #define QUANT(c, mul, add, shift) (((mul) * (c) + (add)) >> (shift))
526 /* VC-2 13.5.5.2 - slice_band() */
527 static void encode_subband(VC2EncContext *s, PutBitContext *pb, int sx, int sy,
528 SubBand *b, int quant)
532 const int left = b->width * (sx+0) / s->num_x;
533 const int right = b->width * (sx+1) / s->num_x;
534 const int top = b->height * (sy+0) / s->num_y;
535 const int bottom = b->height * (sy+1) / s->num_y;
537 dwtcoef *coeff = b->buf + top * b->stride;
538 const uint64_t q_m = ((uint64_t)(s->qmagic_lut[quant][0])) << 2;
539 const uint64_t q_a = s->qmagic_lut[quant][1];
540 const int q_s = av_log2(ff_dirac_qscale_tab[quant]) + 32;
542 for (y = top; y < bottom; y++) {
543 for (x = left; x < right; x++) {
544 uint32_t c_abs = QUANT(FFABS(coeff[x]), q_m, q_a, q_s);
545 put_vc2_ue_uint(pb, c_abs);
547 put_bits(pb, 1, coeff[x] < 0);
553 static int count_hq_slice(SliceArgs *slice, int quant_idx)
556 uint8_t quants[MAX_DWT_LEVELS][4];
557 int bits = 0, p, level, orientation;
558 VC2EncContext *s = slice->ctx;
560 if (slice->cache[quant_idx])
561 return slice->cache[quant_idx];
563 bits += 8*s->prefix_bytes;
564 bits += 8; /* quant_idx */
566 for (level = 0; level < s->wavelet_depth; level++)
567 for (orientation = !!level; orientation < 4; orientation++)
568 quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);
570 for (p = 0; p < 3; p++) {
571 int bytes_start, bytes_len, pad_s, pad_c;
572 bytes_start = bits >> 3;
574 for (level = 0; level < s->wavelet_depth; level++) {
575 for (orientation = !!level; orientation < 4; orientation++) {
576 SubBand *b = &s->plane[p].band[level][orientation];
578 const int q_idx = quants[level][orientation];
579 const uint64_t q_m = ((uint64_t)s->qmagic_lut[q_idx][0]) << 2;
580 const uint64_t q_a = s->qmagic_lut[q_idx][1];
581 const int q_s = av_log2(ff_dirac_qscale_tab[q_idx]) + 32;
583 const int left = b->width * slice->x / s->num_x;
584 const int right = b->width *(slice->x+1) / s->num_x;
585 const int top = b->height * slice->y / s->num_y;
586 const int bottom = b->height *(slice->y+1) / s->num_y;
588 dwtcoef *buf = b->buf + top * b->stride;
590 for (y = top; y < bottom; y++) {
591 for (x = left; x < right; x++) {
592 uint32_t c_abs = QUANT(FFABS(buf[x]), q_m, q_a, q_s);
593 bits += count_vc2_ue_uint(c_abs);
600 bits += FFALIGN(bits, 8) - bits;
601 bytes_len = (bits >> 3) - bytes_start - 1;
602 pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;
603 pad_c = (pad_s*s->size_scaler) - bytes_len;
607 slice->cache[quant_idx] = bits;
612 /* Approaches the best possible quantizer asymptotically, its kinda exaustive
613 * but we have a LUT to get the coefficient size in bits. Guaranteed to never
614 * overshoot, which is apparently very important when streaming */
615 static int rate_control(AVCodecContext *avctx, void *arg)
617 SliceArgs *slice_dat = arg;
618 VC2EncContext *s = slice_dat->ctx;
619 const int top = slice_dat->bits_ceil;
620 const int bottom = slice_dat->bits_floor;
621 int quant_buf[2] = {-1, -1};
622 int quant = slice_dat->quant_idx, step = 1;
623 int bits_last, bits = count_hq_slice(slice_dat, quant);
624 while ((bits > top) || (bits < bottom)) {
625 const int signed_step = bits > top ? +step : -step;
626 quant = av_clip(quant + signed_step, 0, s->q_ceil-1);
627 bits = count_hq_slice(slice_dat, quant);
628 if (quant_buf[1] == quant) {
629 quant = FFMAX(quant_buf[0], quant);
630 bits = quant == quant_buf[0] ? bits_last : bits;
633 step = av_clip(step/2, 1, (s->q_ceil-1)/2);
634 quant_buf[1] = quant_buf[0];
635 quant_buf[0] = quant;
638 slice_dat->quant_idx = av_clip(quant, 0, s->q_ceil-1);
639 slice_dat->bytes = SSIZE_ROUND(bits >> 3);
643 static int calc_slice_sizes(VC2EncContext *s)
645 int i, j, slice_x, slice_y, bytes_left = 0;
646 int bytes_top[SLICE_REDIST_TOTAL] = {0};
647 int64_t total_bytes_needed = 0;
648 int slice_redist_range = FFMIN(SLICE_REDIST_TOTAL, s->num_x*s->num_y);
649 SliceArgs *enc_args = s->slice_args;
650 SliceArgs *top_loc[SLICE_REDIST_TOTAL] = {NULL};
652 init_quant_matrix(s);
654 for (slice_y = 0; slice_y < s->num_y; slice_y++) {
655 for (slice_x = 0; slice_x < s->num_x; slice_x++) {
656 SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
660 args->bits_ceil = s->slice_max_bytes << 3;
661 args->bits_floor = s->slice_min_bytes << 3;
662 memset(args->cache, 0, s->q_ceil*sizeof(*args->cache));
666 /* First pass - determine baseline slice sizes w.r.t. max_slice_size */
667 s->avctx->execute(s->avctx, rate_control, enc_args, NULL, s->num_x*s->num_y,
670 for (i = 0; i < s->num_x*s->num_y; i++) {
671 SliceArgs *args = &enc_args[i];
672 bytes_left += args->bytes;
673 for (j = 0; j < slice_redist_range; j++) {
674 if (args->bytes > bytes_top[j]) {
675 bytes_top[j] = args->bytes;
682 bytes_left = s->frame_max_bytes - bytes_left;
684 /* Second pass - distribute leftover bytes */
685 while (bytes_left > 0) {
687 for (i = 0; i < slice_redist_range; i++) {
689 int bits, bytes, diff, prev_bytes, new_idx;
692 if (!top_loc[i] || !top_loc[i]->quant_idx)
695 prev_bytes = args->bytes;
696 new_idx = FFMAX(args->quant_idx - 1, 0);
697 bits = count_hq_slice(args, new_idx);
698 bytes = SSIZE_ROUND(bits >> 3);
699 diff = bytes - prev_bytes;
700 if ((bytes_left - diff) > 0) {
701 args->quant_idx = new_idx;
711 for (i = 0; i < s->num_x*s->num_y; i++) {
712 SliceArgs *args = &enc_args[i];
713 total_bytes_needed += args->bytes;
714 s->q_avg = (s->q_avg + args->quant_idx)/2;
717 return total_bytes_needed;
720 /* VC-2 13.5.3 - hq_slice */
721 static int encode_hq_slice(AVCodecContext *avctx, void *arg)
723 SliceArgs *slice_dat = arg;
724 VC2EncContext *s = slice_dat->ctx;
725 PutBitContext *pb = &slice_dat->pb;
726 const int slice_x = slice_dat->x;
727 const int slice_y = slice_dat->y;
728 const int quant_idx = slice_dat->quant_idx;
729 const int slice_bytes_max = slice_dat->bytes;
730 uint8_t quants[MAX_DWT_LEVELS][4];
731 int p, level, orientation;
733 /* The reference decoder ignores it, and its typical length is 0 */
734 memset(put_bits_ptr(pb), 0, s->prefix_bytes);
735 skip_put_bytes(pb, s->prefix_bytes);
737 put_bits(pb, 8, quant_idx);
739 /* Slice quantization (slice_quantizers() in the specs) */
740 for (level = 0; level < s->wavelet_depth; level++)
741 for (orientation = !!level; orientation < 4; orientation++)
742 quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);
744 /* Luma + 2 Chroma planes */
745 for (p = 0; p < 3; p++) {
746 int bytes_start, bytes_len, pad_s, pad_c;
747 bytes_start = put_bits_count(pb) >> 3;
749 for (level = 0; level < s->wavelet_depth; level++) {
750 for (orientation = !!level; orientation < 4; orientation++) {
751 encode_subband(s, pb, slice_x, slice_y,
752 &s->plane[p].band[level][orientation],
753 quants[level][orientation]);
756 avpriv_align_put_bits(pb);
757 bytes_len = (put_bits_count(pb) >> 3) - bytes_start - 1;
759 int len_diff = slice_bytes_max - (put_bits_count(pb) >> 3);
760 pad_s = FFALIGN((bytes_len + len_diff), s->size_scaler)/s->size_scaler;
761 pad_c = (pad_s*s->size_scaler) - bytes_len;
763 pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;
764 pad_c = (pad_s*s->size_scaler) - bytes_len;
766 pb->buf[bytes_start] = pad_s;
768 /* vc2-reference uses that padding that decodes to '0' coeffs */
769 memset(put_bits_ptr(pb), 0xFF, pad_c);
770 skip_put_bytes(pb, pad_c);
776 /* VC-2 13.5.1 - low_delay_transform_data() */
777 static int encode_slices(VC2EncContext *s)
780 int slice_x, slice_y, skip = 0;
781 SliceArgs *enc_args = s->slice_args;
783 avpriv_align_put_bits(&s->pb);
784 flush_put_bits(&s->pb);
785 buf = put_bits_ptr(&s->pb);
787 for (slice_y = 0; slice_y < s->num_y; slice_y++) {
788 for (slice_x = 0; slice_x < s->num_x; slice_x++) {
789 SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];
790 init_put_bits(&args->pb, buf + skip, args->bytes+s->prefix_bytes);
795 s->avctx->execute(s->avctx, encode_hq_slice, enc_args, NULL, s->num_x*s->num_y,
798 skip_put_bytes(&s->pb, skip);
804 * Transform basics for a 3 level transform
805 * |---------------------------------------------------------------------|
806 * | LL-0 | HL-0 | | |
807 * |--------|-------| HL-1 | |
808 * | LH-0 | HH-0 | | |
809 * |----------------|-----------------| HL-2 |
813 * |----------------------------------|----------------------------------|
821 * |---------------------------------------------------------------------|
823 * DWT transforms are generally applied by splitting the image in two vertically
824 * and applying a low pass transform on the left part and a corresponding high
825 * pass transform on the right hand side. This is known as the horizontal filter
827 * After that, the same operation is performed except the image is divided
828 * horizontally, with the high pass on the lower and the low pass on the higher
830 * Therefore, you're left with 4 subdivisions - known as low-low, low-high,
831 * high-low and high-high. They're referred to as orientations in the decoder
834 * The LL (low-low) area contains the original image downsampled by the amount
835 * of levels. The rest of the areas can be thought as the details needed
836 * to restore the image perfectly to its original size.
838 static int dwt_plane(AVCodecContext *avctx, void *arg)
840 TransformArgs *transform_dat = arg;
841 VC2EncContext *s = transform_dat->ctx;
842 const void *frame_data = transform_dat->idata;
843 const ptrdiff_t linesize = transform_dat->istride;
844 const int field = transform_dat->field;
845 const Plane *p = transform_dat->plane;
846 VC2TransformContext *t = &transform_dat->t;
847 dwtcoef *buf = p->coef_buf;
848 const int idx = s->wavelet_idx;
849 const int skip = 1 + s->interlaced;
851 int x, y, level, offset;
852 ptrdiff_t pix_stride = linesize >> (s->bpp - 1);
857 } else if (field == 2) {
865 const uint8_t *pix = (const uint8_t *)frame_data + offset;
866 for (y = 0; y < p->height*skip; y+=skip) {
867 for (x = 0; x < p->width; x++) {
868 buf[x] = pix[x] - s->diff_offset;
870 buf += p->coef_stride;
874 const uint16_t *pix = (const uint16_t *)frame_data + offset;
875 for (y = 0; y < p->height*skip; y+=skip) {
876 for (x = 0; x < p->width; x++) {
877 buf[x] = pix[x] - s->diff_offset;
879 buf += p->coef_stride;
884 memset(buf, 0, p->coef_stride * (p->dwt_height - p->height) * sizeof(dwtcoef));
886 for (level = s->wavelet_depth-1; level >= 0; level--) {
887 const SubBand *b = &p->band[level][0];
888 t->vc2_subband_dwt[idx](t, p->coef_buf, p->coef_stride,
889 b->width, b->height);
895 static int encode_frame(VC2EncContext *s, AVPacket *avpkt, const AVFrame *frame,
896 const char *aux_data, const int header_size, int field)
899 int64_t max_frame_bytes;
901 /* Threaded DWT transform */
902 for (i = 0; i < 3; i++) {
903 s->transform_args[i].ctx = s;
904 s->transform_args[i].field = field;
905 s->transform_args[i].plane = &s->plane[i];
906 s->transform_args[i].idata = frame->data[i];
907 s->transform_args[i].istride = frame->linesize[i];
909 s->avctx->execute(s->avctx, dwt_plane, s->transform_args, NULL, 3,
910 sizeof(TransformArgs));
912 /* Calculate per-slice quantizers and sizes */
913 max_frame_bytes = header_size + calc_slice_sizes(s);
916 ret = ff_alloc_packet2(s->avctx, avpkt,
917 max_frame_bytes << s->interlaced,
918 max_frame_bytes << s->interlaced);
920 av_log(s->avctx, AV_LOG_ERROR, "Error getting output packet.\n");
923 init_put_bits(&s->pb, avpkt->data, avpkt->size);
926 /* Sequence header */
927 encode_parse_info(s, DIRAC_PCODE_SEQ_HEADER);
928 encode_seq_header(s);
930 /* Encoder version */
932 encode_parse_info(s, DIRAC_PCODE_AUX);
933 avpriv_put_string(&s->pb, aux_data, 1);
937 encode_parse_info(s, DIRAC_PCODE_PICTURE_HQ);
938 encode_picture_start(s);
944 encode_parse_info(s, DIRAC_PCODE_END_SEQ);
949 static av_cold int vc2_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
950 const AVFrame *frame, int *got_packet)
953 int slice_ceil, sig_size = 256;
954 VC2EncContext *s = avctx->priv_data;
955 const int bitexact = avctx->flags & AV_CODEC_FLAG_BITEXACT;
956 const char *aux_data = bitexact ? "Lavc" : LIBAVCODEC_IDENT;
957 const int aux_data_size = bitexact ? sizeof("Lavc") : sizeof(LIBAVCODEC_IDENT);
958 const int header_size = 100 + aux_data_size;
959 int64_t r_bitrate = avctx->bit_rate >> (s->interlaced);
964 s->last_parse_code = 0;
965 s->next_parse_offset = 0;
968 s->frame_max_bytes = (av_rescale(r_bitrate, s->avctx->time_base.num,
969 s->avctx->time_base.den) >> 3) - header_size;
970 s->slice_max_bytes = slice_ceil = av_rescale(s->frame_max_bytes, 1, s->num_x*s->num_y);
972 /* Find an appropriate size scaler */
973 while (sig_size > 255) {
974 int r_size = SSIZE_ROUND(s->slice_max_bytes);
975 if (r_size > slice_ceil) {
976 s->slice_max_bytes -= r_size - slice_ceil;
977 r_size = SSIZE_ROUND(s->slice_max_bytes);
979 sig_size = r_size/s->size_scaler; /* Signalled slize size */
980 s->size_scaler <<= 1;
983 s->slice_min_bytes = s->slice_max_bytes - s->slice_max_bytes*(s->tolerance/100.0f);
985 ret = encode_frame(s, avpkt, frame, aux_data, header_size, s->interlaced);
989 ret = encode_frame(s, avpkt, frame, aux_data, header_size, 2);
994 flush_put_bits(&s->pb);
995 avpkt->size = put_bits_count(&s->pb) >> 3;
1002 static av_cold int vc2_encode_end(AVCodecContext *avctx)
1005 VC2EncContext *s = avctx->priv_data;
1007 av_log(avctx, AV_LOG_INFO, "Qavg: %i\n", s->q_avg);
1009 for (i = 0; i < 3; i++) {
1010 ff_vc2enc_free_transforms(&s->transform_args[i].t);
1011 av_freep(&s->plane[i].coef_buf);
1014 av_freep(&s->slice_args);
1019 static av_cold int vc2_encode_init(AVCodecContext *avctx)
1023 int i, level, o, shift, ret;
1024 const AVPixFmtDescriptor *fmt = av_pix_fmt_desc_get(avctx->pix_fmt);
1025 const int depth = fmt->comp[0].depth;
1026 VC2EncContext *s = avctx->priv_data;
1028 s->picture_number = 0;
1030 /* Total allowed quantization range */
1031 s->q_ceil = DIRAC_MAX_QUANT_INDEX;
1039 s->strict_compliance = 1;
1042 s->slice_max_bytes = 0;
1043 s->slice_min_bytes = 0;
1045 /* Mark unknown as progressive */
1046 s->interlaced = !((avctx->field_order == AV_FIELD_UNKNOWN) ||
1047 (avctx->field_order == AV_FIELD_PROGRESSIVE));
1049 for (i = 0; i < base_video_fmts_len; i++) {
1050 const VC2BaseVideoFormat *fmt = &base_video_fmts[i];
1051 if (avctx->pix_fmt != fmt->pix_fmt)
1053 if (avctx->time_base.num != fmt->time_base.num)
1055 if (avctx->time_base.den != fmt->time_base.den)
1057 if (avctx->width != fmt->width)
1059 if (avctx->height != fmt->height)
1061 if (s->interlaced != fmt->interlaced)
1064 s->level = base_video_fmts[i].level;
1069 av_log(avctx, AV_LOG_WARNING, "Interlacing enabled!\n");
1071 if ((s->slice_width & (s->slice_width - 1)) ||
1072 (s->slice_height & (s->slice_height - 1))) {
1073 av_log(avctx, AV_LOG_ERROR, "Slice size is not a power of two!\n");
1074 return AVERROR_UNKNOWN;
1077 if ((s->slice_width > avctx->width) ||
1078 (s->slice_height > avctx->height)) {
1079 av_log(avctx, AV_LOG_ERROR, "Slice size is bigger than the image!\n");
1080 return AVERROR_UNKNOWN;
1083 if (s->base_vf <= 0) {
1084 if (avctx->strict_std_compliance < FF_COMPLIANCE_STRICT) {
1085 s->strict_compliance = s->base_vf = 0;
1086 av_log(avctx, AV_LOG_WARNING, "Format does not strictly comply with VC2 specs\n");
1088 av_log(avctx, AV_LOG_WARNING, "Given format does not strictly comply with "
1089 "the specifications, decrease strictness to use it.\n");
1090 return AVERROR_UNKNOWN;
1093 av_log(avctx, AV_LOG_INFO, "Selected base video format = %i (%s)\n",
1094 s->base_vf, base_video_fmts[s->base_vf].name);
1097 /* Chroma subsampling */
1098 ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
1102 /* Bit depth and color range index */
1103 if (depth == 8 && avctx->color_range == AVCOL_RANGE_JPEG) {
1106 s->diff_offset = 128;
1107 } else if (depth == 8 && (avctx->color_range == AVCOL_RANGE_MPEG ||
1108 avctx->color_range == AVCOL_RANGE_UNSPECIFIED)) {
1111 s->diff_offset = 128;
1112 } else if (depth == 10) {
1115 s->diff_offset = 512;
1119 s->diff_offset = 2048;
1122 /* Planes initialization */
1123 for (i = 0; i < 3; i++) {
1126 p->width = avctx->width >> (i ? s->chroma_x_shift : 0);
1127 p->height = avctx->height >> (i ? s->chroma_y_shift : 0);
1130 p->dwt_width = w = FFALIGN(p->width, (1 << s->wavelet_depth));
1131 p->dwt_height = h = FFALIGN(p->height, (1 << s->wavelet_depth));
1132 p->coef_stride = FFALIGN(p->dwt_width, 32);
1133 p->coef_buf = av_mallocz(p->coef_stride*p->dwt_height*sizeof(dwtcoef));
1136 for (level = s->wavelet_depth-1; level >= 0; level--) {
1139 for (o = 0; o < 4; o++) {
1140 b = &p->band[level][o];
1143 b->stride = p->coef_stride;
1144 shift = (o > 1)*b->height*b->stride + (o & 1)*b->width;
1145 b->buf = p->coef_buf + shift;
1150 if (ff_vc2enc_init_transforms(&s->transform_args[i].t,
1151 s->plane[i].coef_stride,
1152 s->plane[i].dwt_height,
1153 s->slice_width, s->slice_height))
1158 s->num_x = s->plane[0].dwt_width/s->slice_width;
1159 s->num_y = s->plane[0].dwt_height/s->slice_height;
1161 s->slice_args = av_calloc(s->num_x*s->num_y, sizeof(SliceArgs));
1165 for (i = 0; i < 116; i++) {
1166 const uint64_t qf = ff_dirac_qscale_tab[i];
1167 const uint32_t m = av_log2(qf);
1168 const uint32_t t = (1ULL << (m + 32)) / qf;
1169 const uint32_t r = (t*qf + qf) & UINT32_MAX;
1170 if (!(qf & (qf - 1))) {
1171 s->qmagic_lut[i][0] = 0xFFFFFFFF;
1172 s->qmagic_lut[i][1] = 0xFFFFFFFF;
1173 } else if (r <= 1 << m) {
1174 s->qmagic_lut[i][0] = t + 1;
1175 s->qmagic_lut[i][1] = 0;
1177 s->qmagic_lut[i][0] = t;
1178 s->qmagic_lut[i][1] = t;
1185 vc2_encode_end(avctx);
1186 av_log(avctx, AV_LOG_ERROR, "Unable to allocate memory!\n");
1187 return AVERROR(ENOMEM);
1190 #define VC2ENC_FLAGS (AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
1191 static const AVOption vc2enc_options[] = {
1192 {"tolerance", "Max undershoot in percent", offsetof(VC2EncContext, tolerance), AV_OPT_TYPE_DOUBLE, {.dbl = 5.0f}, 0.0f, 45.0f, VC2ENC_FLAGS, "tolerance"},
1193 {"slice_width", "Slice width", offsetof(VC2EncContext, slice_width), AV_OPT_TYPE_INT, {.i64 = 32}, 32, 1024, VC2ENC_FLAGS, "slice_width"},
1194 {"slice_height", "Slice height", offsetof(VC2EncContext, slice_height), AV_OPT_TYPE_INT, {.i64 = 16}, 8, 1024, VC2ENC_FLAGS, "slice_height"},
1195 {"wavelet_depth", "Transform depth", offsetof(VC2EncContext, wavelet_depth), AV_OPT_TYPE_INT, {.i64 = 4}, 1, 5, VC2ENC_FLAGS, "wavelet_depth"},
1196 {"wavelet_type", "Transform type", offsetof(VC2EncContext, wavelet_idx), AV_OPT_TYPE_INT, {.i64 = VC2_TRANSFORM_9_7}, 0, VC2_TRANSFORMS_NB, VC2ENC_FLAGS, "wavelet_idx"},
1197 {"9_7", "Deslauriers-Dubuc (9,7)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_9_7}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1198 {"5_3", "LeGall (5,3)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_5_3}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1199 {"haar", "Haar (with shift)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_HAAR_S}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1200 {"haar_noshift", "Haar (without shift)", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_TRANSFORM_HAAR}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "wavelet_idx"},
1201 {"qm", "Custom quantization matrix", offsetof(VC2EncContext, quant_matrix), AV_OPT_TYPE_INT, {.i64 = VC2_QM_DEF}, 0, VC2_QM_NB, VC2ENC_FLAGS, "quant_matrix"},
1202 {"default", "Default from the specifications", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_DEF}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1203 {"color", "Prevents low bitrate discoloration", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_COL}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1204 {"flat", "Optimize for PSNR", 0, AV_OPT_TYPE_CONST, {.i64 = VC2_QM_FLAT}, INT_MIN, INT_MAX, VC2ENC_FLAGS, "quant_matrix"},
1208 static const AVClass vc2enc_class = {
1209 .class_name = "SMPTE VC-2 encoder",
1210 .category = AV_CLASS_CATEGORY_ENCODER,
1211 .option = vc2enc_options,
1212 .item_name = av_default_item_name,
1213 .version = LIBAVUTIL_VERSION_INT
1216 static const AVCodecDefault vc2enc_defaults[] = {
1217 { "b", "600000000" },
1221 static const enum AVPixelFormat allowed_pix_fmts[] = {
1222 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
1223 AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
1224 AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
1228 AVCodec ff_vc2_encoder = {
1230 .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-2"),
1231 .type = AVMEDIA_TYPE_VIDEO,
1232 .id = AV_CODEC_ID_DIRAC,
1233 .priv_data_size = sizeof(VC2EncContext),
1234 .init = vc2_encode_init,
1235 .close = vc2_encode_end,
1236 .capabilities = AV_CODEC_CAP_SLICE_THREADS,
1237 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1238 .encode2 = vc2_encode_frame,
1239 .priv_class = &vc2enc_class,
1240 .defaults = vc2enc_defaults,
1241 .pix_fmts = allowed_pix_fmts