You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1197 lines
38KB

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