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.

1036 lines
34KB

  1. /*
  2. * Apple ProRes encoder
  3. *
  4. * Copyright (c) 2012 Konstantin Shishkov
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * Libav is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "libavutil/opt.h"
  23. #include "avcodec.h"
  24. #include "put_bits.h"
  25. #include "bytestream.h"
  26. #include "internal.h"
  27. #include "proresdsp.h"
  28. #include "proresdata.h"
  29. #define CFACTOR_Y422 2
  30. #define CFACTOR_Y444 3
  31. #define MAX_MBS_PER_SLICE 8
  32. #define MAX_PLANES 3 // should be increased to 4 when there's PIX_FMT_YUV444AP10
  33. enum {
  34. PRORES_PROFILE_PROXY = 0,
  35. PRORES_PROFILE_LT,
  36. PRORES_PROFILE_STANDARD,
  37. PRORES_PROFILE_HQ,
  38. };
  39. enum {
  40. QUANT_MAT_PROXY = 0,
  41. QUANT_MAT_LT,
  42. QUANT_MAT_STANDARD,
  43. QUANT_MAT_HQ,
  44. QUANT_MAT_DEFAULT,
  45. };
  46. static const uint8_t prores_quant_matrices[][64] = {
  47. { // proxy
  48. 4, 7, 9, 11, 13, 14, 15, 63,
  49. 7, 7, 11, 12, 14, 15, 63, 63,
  50. 9, 11, 13, 14, 15, 63, 63, 63,
  51. 11, 11, 13, 14, 63, 63, 63, 63,
  52. 11, 13, 14, 63, 63, 63, 63, 63,
  53. 13, 14, 63, 63, 63, 63, 63, 63,
  54. 13, 63, 63, 63, 63, 63, 63, 63,
  55. 63, 63, 63, 63, 63, 63, 63, 63,
  56. },
  57. { // LT
  58. 4, 5, 6, 7, 9, 11, 13, 15,
  59. 5, 5, 7, 8, 11, 13, 15, 17,
  60. 6, 7, 9, 11, 13, 15, 15, 17,
  61. 7, 7, 9, 11, 13, 15, 17, 19,
  62. 7, 9, 11, 13, 14, 16, 19, 23,
  63. 9, 11, 13, 14, 16, 19, 23, 29,
  64. 9, 11, 13, 15, 17, 21, 28, 35,
  65. 11, 13, 16, 17, 21, 28, 35, 41,
  66. },
  67. { // standard
  68. 4, 4, 5, 5, 6, 7, 7, 9,
  69. 4, 4, 5, 6, 7, 7, 9, 9,
  70. 5, 5, 6, 7, 7, 9, 9, 10,
  71. 5, 5, 6, 7, 7, 9, 9, 10,
  72. 5, 6, 7, 7, 8, 9, 10, 12,
  73. 6, 7, 7, 8, 9, 10, 12, 15,
  74. 6, 7, 7, 9, 10, 11, 14, 17,
  75. 7, 7, 9, 10, 11, 14, 17, 21,
  76. },
  77. { // high quality
  78. 4, 4, 4, 4, 4, 4, 4, 4,
  79. 4, 4, 4, 4, 4, 4, 4, 4,
  80. 4, 4, 4, 4, 4, 4, 4, 4,
  81. 4, 4, 4, 4, 4, 4, 4, 5,
  82. 4, 4, 4, 4, 4, 4, 5, 5,
  83. 4, 4, 4, 4, 4, 5, 5, 6,
  84. 4, 4, 4, 4, 5, 5, 6, 7,
  85. 4, 4, 4, 4, 5, 6, 7, 7,
  86. },
  87. { // codec default
  88. 4, 4, 4, 4, 4, 4, 4, 4,
  89. 4, 4, 4, 4, 4, 4, 4, 4,
  90. 4, 4, 4, 4, 4, 4, 4, 4,
  91. 4, 4, 4, 4, 4, 4, 4, 4,
  92. 4, 4, 4, 4, 4, 4, 4, 4,
  93. 4, 4, 4, 4, 4, 4, 4, 4,
  94. 4, 4, 4, 4, 4, 4, 4, 4,
  95. 4, 4, 4, 4, 4, 4, 4, 4,
  96. },
  97. };
  98. #define NUM_MB_LIMITS 4
  99. static const int prores_mb_limits[NUM_MB_LIMITS] = {
  100. 1620, // up to 720x576
  101. 2700, // up to 960x720
  102. 6075, // up to 1440x1080
  103. 9216, // up to 2048x1152
  104. };
  105. static const struct prores_profile {
  106. const char *full_name;
  107. uint32_t tag;
  108. int min_quant;
  109. int max_quant;
  110. int br_tab[NUM_MB_LIMITS];
  111. int quant;
  112. } prores_profile_info[4] = {
  113. {
  114. .full_name = "proxy",
  115. .tag = MKTAG('a', 'p', 'c', 'o'),
  116. .min_quant = 4,
  117. .max_quant = 8,
  118. .br_tab = { 300, 242, 220, 194 },
  119. .quant = QUANT_MAT_PROXY,
  120. },
  121. {
  122. .full_name = "LT",
  123. .tag = MKTAG('a', 'p', 'c', 's'),
  124. .min_quant = 1,
  125. .max_quant = 9,
  126. .br_tab = { 720, 560, 490, 440 },
  127. .quant = QUANT_MAT_LT,
  128. },
  129. {
  130. .full_name = "standard",
  131. .tag = MKTAG('a', 'p', 'c', 'n'),
  132. .min_quant = 1,
  133. .max_quant = 6,
  134. .br_tab = { 1050, 808, 710, 632 },
  135. .quant = QUANT_MAT_STANDARD,
  136. },
  137. {
  138. .full_name = "high quality",
  139. .tag = MKTAG('a', 'p', 'c', 'h'),
  140. .min_quant = 1,
  141. .max_quant = 6,
  142. .br_tab = { 1566, 1216, 1070, 950 },
  143. .quant = QUANT_MAT_HQ,
  144. }
  145. // for 4444 profile bitrate numbers are { 2350, 1828, 1600, 1425 }
  146. };
  147. #define TRELLIS_WIDTH 16
  148. #define SCORE_LIMIT INT_MAX / 2
  149. struct TrellisNode {
  150. int prev_node;
  151. int quant;
  152. int bits;
  153. int score;
  154. };
  155. #define MAX_STORED_Q 16
  156. typedef struct ProresThreadData {
  157. DECLARE_ALIGNED(16, DCTELEM, blocks)[MAX_PLANES][64 * 4 * MAX_MBS_PER_SLICE];
  158. DECLARE_ALIGNED(16, uint16_t, emu_buf)[16 * 16];
  159. int16_t custom_q[64];
  160. struct TrellisNode *nodes;
  161. } ProresThreadData;
  162. typedef struct ProresContext {
  163. AVClass *class;
  164. DECLARE_ALIGNED(16, DCTELEM, blocks)[MAX_PLANES][64 * 4 * MAX_MBS_PER_SLICE];
  165. DECLARE_ALIGNED(16, uint16_t, emu_buf)[16*16];
  166. int16_t quants[MAX_STORED_Q][64];
  167. int16_t custom_q[64];
  168. const uint8_t *quant_mat;
  169. ProresDSPContext dsp;
  170. ScanTable scantable;
  171. int mb_width, mb_height;
  172. int mbs_per_slice;
  173. int num_chroma_blocks, chroma_factor;
  174. int slices_width;
  175. int num_slices;
  176. int num_planes;
  177. int bits_per_mb;
  178. int force_quant;
  179. char *vendor;
  180. int quant_sel;
  181. int frame_size;
  182. int profile;
  183. const struct prores_profile *profile_info;
  184. int *slice_q;
  185. ProresThreadData *tdata;
  186. } ProresContext;
  187. static void get_slice_data(ProresContext *ctx, const uint16_t *src,
  188. int linesize, int x, int y, int w, int h,
  189. DCTELEM *blocks, uint16_t *emu_buf,
  190. int mbs_per_slice, int blocks_per_mb, int is_chroma)
  191. {
  192. const uint16_t *esrc;
  193. const int mb_width = 4 * blocks_per_mb;
  194. int elinesize;
  195. int i, j, k;
  196. for (i = 0; i < mbs_per_slice; i++, src += mb_width) {
  197. if (x >= w) {
  198. memset(blocks, 0, 64 * (mbs_per_slice - i) * blocks_per_mb
  199. * sizeof(*blocks));
  200. return;
  201. }
  202. if (x + mb_width <= w && y + 16 <= h) {
  203. esrc = src;
  204. elinesize = linesize;
  205. } else {
  206. int bw, bh, pix;
  207. esrc = emu_buf;
  208. elinesize = 16 * sizeof(*emu_buf);
  209. bw = FFMIN(w - x, mb_width);
  210. bh = FFMIN(h - y, 16);
  211. for (j = 0; j < bh; j++) {
  212. memcpy(emu_buf + j * 16,
  213. (const uint8_t*)src + j * linesize,
  214. bw * sizeof(*src));
  215. pix = emu_buf[j * 16 + bw - 1];
  216. for (k = bw; k < mb_width; k++)
  217. emu_buf[j * 16 + k] = pix;
  218. }
  219. for (; j < 16; j++)
  220. memcpy(emu_buf + j * 16,
  221. emu_buf + (bh - 1) * 16,
  222. mb_width * sizeof(*emu_buf));
  223. }
  224. if (!is_chroma) {
  225. ctx->dsp.fdct(esrc, elinesize, blocks);
  226. blocks += 64;
  227. if (blocks_per_mb > 2) {
  228. ctx->dsp.fdct(src + 8, linesize, blocks);
  229. blocks += 64;
  230. }
  231. ctx->dsp.fdct(src + linesize * 4, linesize, blocks);
  232. blocks += 64;
  233. if (blocks_per_mb > 2) {
  234. ctx->dsp.fdct(src + linesize * 4 + 8, linesize, blocks);
  235. blocks += 64;
  236. }
  237. } else {
  238. ctx->dsp.fdct(esrc, elinesize, blocks);
  239. blocks += 64;
  240. ctx->dsp.fdct(src + linesize * 4, linesize, blocks);
  241. blocks += 64;
  242. if (blocks_per_mb > 2) {
  243. ctx->dsp.fdct(src + 8, linesize, blocks);
  244. blocks += 64;
  245. ctx->dsp.fdct(src + linesize * 4 + 8, linesize, blocks);
  246. blocks += 64;
  247. }
  248. }
  249. x += mb_width;
  250. }
  251. }
  252. /**
  253. * Write an unsigned rice/exp golomb codeword.
  254. */
  255. static inline void encode_vlc_codeword(PutBitContext *pb, unsigned codebook, int val)
  256. {
  257. unsigned int rice_order, exp_order, switch_bits, switch_val;
  258. int exponent;
  259. /* number of prefix bits to switch between Rice and expGolomb */
  260. switch_bits = (codebook & 3) + 1;
  261. rice_order = codebook >> 5; /* rice code order */
  262. exp_order = (codebook >> 2) & 7; /* exp golomb code order */
  263. switch_val = switch_bits << rice_order;
  264. if (val >= switch_val) {
  265. val -= switch_val - (1 << exp_order);
  266. exponent = av_log2(val);
  267. put_bits(pb, exponent - exp_order + switch_bits, 0);
  268. put_bits(pb, 1, 1);
  269. put_bits(pb, exponent, val);
  270. } else {
  271. exponent = val >> rice_order;
  272. if (exponent)
  273. put_bits(pb, exponent, 0);
  274. put_bits(pb, 1, 1);
  275. if (rice_order)
  276. put_sbits(pb, rice_order, val);
  277. }
  278. }
  279. #define GET_SIGN(x) ((x) >> 31)
  280. #define MAKE_CODE(x) (((x) << 1) ^ GET_SIGN(x))
  281. static void encode_dcs(PutBitContext *pb, DCTELEM *blocks,
  282. int blocks_per_slice, int scale)
  283. {
  284. int i;
  285. int codebook = 3, code, dc, prev_dc, delta, sign, new_sign;
  286. prev_dc = (blocks[0] - 0x4000) / scale;
  287. encode_vlc_codeword(pb, FIRST_DC_CB, MAKE_CODE(prev_dc));
  288. sign = 0;
  289. codebook = 3;
  290. blocks += 64;
  291. for (i = 1; i < blocks_per_slice; i++, blocks += 64) {
  292. dc = (blocks[0] - 0x4000) / scale;
  293. delta = dc - prev_dc;
  294. new_sign = GET_SIGN(delta);
  295. delta = (delta ^ sign) - sign;
  296. code = MAKE_CODE(delta);
  297. encode_vlc_codeword(pb, ff_prores_dc_codebook[codebook], code);
  298. codebook = (code + (code & 1)) >> 1;
  299. codebook = FFMIN(codebook, 3);
  300. sign = new_sign;
  301. prev_dc = dc;
  302. }
  303. }
  304. static void encode_acs(PutBitContext *pb, DCTELEM *blocks,
  305. int blocks_per_slice,
  306. int plane_size_factor,
  307. const uint8_t *scan, const int16_t *qmat)
  308. {
  309. int idx, i;
  310. int run, level, run_cb, lev_cb;
  311. int max_coeffs, abs_level;
  312. max_coeffs = blocks_per_slice << 6;
  313. run_cb = ff_prores_run_to_cb_index[4];
  314. lev_cb = ff_prores_lev_to_cb_index[2];
  315. run = 0;
  316. for (i = 1; i < 64; i++) {
  317. for (idx = scan[i]; idx < max_coeffs; idx += 64) {
  318. level = blocks[idx] / qmat[scan[i]];
  319. if (level) {
  320. abs_level = FFABS(level);
  321. encode_vlc_codeword(pb, ff_prores_ac_codebook[run_cb], run);
  322. encode_vlc_codeword(pb, ff_prores_ac_codebook[lev_cb],
  323. abs_level - 1);
  324. put_sbits(pb, 1, GET_SIGN(level));
  325. run_cb = ff_prores_run_to_cb_index[FFMIN(run, 15)];
  326. lev_cb = ff_prores_lev_to_cb_index[FFMIN(abs_level, 9)];
  327. run = 0;
  328. } else {
  329. run++;
  330. }
  331. }
  332. }
  333. }
  334. static int encode_slice_plane(ProresContext *ctx, PutBitContext *pb,
  335. const uint16_t *src, int linesize,
  336. int mbs_per_slice, DCTELEM *blocks,
  337. int blocks_per_mb, int plane_size_factor,
  338. const int16_t *qmat)
  339. {
  340. int blocks_per_slice, saved_pos;
  341. saved_pos = put_bits_count(pb);
  342. blocks_per_slice = mbs_per_slice * blocks_per_mb;
  343. encode_dcs(pb, blocks, blocks_per_slice, qmat[0]);
  344. encode_acs(pb, blocks, blocks_per_slice, plane_size_factor,
  345. ctx->scantable.permutated, qmat);
  346. flush_put_bits(pb);
  347. return (put_bits_count(pb) - saved_pos) >> 3;
  348. }
  349. static int encode_slice(AVCodecContext *avctx, const AVFrame *pic,
  350. PutBitContext *pb,
  351. int sizes[4], int x, int y, int quant,
  352. int mbs_per_slice)
  353. {
  354. ProresContext *ctx = avctx->priv_data;
  355. int i, xp, yp;
  356. int total_size = 0;
  357. const uint16_t *src;
  358. int slice_width_factor = av_log2(mbs_per_slice);
  359. int num_cblocks, pwidth;
  360. int plane_factor, is_chroma;
  361. uint16_t *qmat;
  362. if (ctx->force_quant) {
  363. qmat = ctx->quants[0];
  364. } else if (quant < MAX_STORED_Q) {
  365. qmat = ctx->quants[quant];
  366. } else {
  367. qmat = ctx->custom_q;
  368. for (i = 0; i < 64; i++)
  369. qmat[i] = ctx->quant_mat[i] * quant;
  370. }
  371. for (i = 0; i < ctx->num_planes; i++) {
  372. is_chroma = (i == 1 || i == 2);
  373. plane_factor = slice_width_factor + 2;
  374. if (is_chroma)
  375. plane_factor += ctx->chroma_factor - 3;
  376. if (!is_chroma || ctx->chroma_factor == CFACTOR_Y444) {
  377. xp = x << 4;
  378. yp = y << 4;
  379. num_cblocks = 4;
  380. pwidth = avctx->width;
  381. } else {
  382. xp = x << 3;
  383. yp = y << 4;
  384. num_cblocks = 2;
  385. pwidth = avctx->width >> 1;
  386. }
  387. src = (const uint16_t*)(pic->data[i] + yp * pic->linesize[i]) + xp;
  388. get_slice_data(ctx, src, pic->linesize[i], xp, yp,
  389. pwidth, avctx->height, ctx->blocks[0], ctx->emu_buf,
  390. mbs_per_slice, num_cblocks, is_chroma);
  391. sizes[i] = encode_slice_plane(ctx, pb, src, pic->linesize[i],
  392. mbs_per_slice, ctx->blocks[0],
  393. num_cblocks, plane_factor,
  394. qmat);
  395. total_size += sizes[i];
  396. }
  397. return total_size;
  398. }
  399. static inline int estimate_vlc(unsigned codebook, int val)
  400. {
  401. unsigned int rice_order, exp_order, switch_bits, switch_val;
  402. int exponent;
  403. /* number of prefix bits to switch between Rice and expGolomb */
  404. switch_bits = (codebook & 3) + 1;
  405. rice_order = codebook >> 5; /* rice code order */
  406. exp_order = (codebook >> 2) & 7; /* exp golomb code order */
  407. switch_val = switch_bits << rice_order;
  408. if (val >= switch_val) {
  409. val -= switch_val - (1 << exp_order);
  410. exponent = av_log2(val);
  411. return exponent * 2 - exp_order + switch_bits + 1;
  412. } else {
  413. return (val >> rice_order) + rice_order + 1;
  414. }
  415. }
  416. static int estimate_dcs(int *error, DCTELEM *blocks, int blocks_per_slice,
  417. int scale)
  418. {
  419. int i;
  420. int codebook = 3, code, dc, prev_dc, delta, sign, new_sign;
  421. int bits;
  422. prev_dc = (blocks[0] - 0x4000) / scale;
  423. bits = estimate_vlc(FIRST_DC_CB, MAKE_CODE(prev_dc));
  424. sign = 0;
  425. codebook = 3;
  426. blocks += 64;
  427. *error += FFABS(blocks[0] - 0x4000) % scale;
  428. for (i = 1; i < blocks_per_slice; i++, blocks += 64) {
  429. dc = (blocks[0] - 0x4000) / scale;
  430. *error += FFABS(blocks[0] - 0x4000) % scale;
  431. delta = dc - prev_dc;
  432. new_sign = GET_SIGN(delta);
  433. delta = (delta ^ sign) - sign;
  434. code = MAKE_CODE(delta);
  435. bits += estimate_vlc(ff_prores_dc_codebook[codebook], code);
  436. codebook = (code + (code & 1)) >> 1;
  437. codebook = FFMIN(codebook, 3);
  438. sign = new_sign;
  439. prev_dc = dc;
  440. }
  441. return bits;
  442. }
  443. static int estimate_acs(int *error, DCTELEM *blocks, int blocks_per_slice,
  444. int plane_size_factor,
  445. const uint8_t *scan, const int16_t *qmat)
  446. {
  447. int idx, i;
  448. int run, level, run_cb, lev_cb;
  449. int max_coeffs, abs_level;
  450. int bits = 0;
  451. max_coeffs = blocks_per_slice << 6;
  452. run_cb = ff_prores_run_to_cb_index[4];
  453. lev_cb = ff_prores_lev_to_cb_index[2];
  454. run = 0;
  455. for (i = 1; i < 64; i++) {
  456. for (idx = scan[i]; idx < max_coeffs; idx += 64) {
  457. level = blocks[idx] / qmat[scan[i]];
  458. *error += FFABS(blocks[idx]) % qmat[scan[i]];
  459. if (level) {
  460. abs_level = FFABS(level);
  461. bits += estimate_vlc(ff_prores_ac_codebook[run_cb], run);
  462. bits += estimate_vlc(ff_prores_ac_codebook[lev_cb],
  463. abs_level - 1) + 1;
  464. run_cb = ff_prores_run_to_cb_index[FFMIN(run, 15)];
  465. lev_cb = ff_prores_lev_to_cb_index[FFMIN(abs_level, 9)];
  466. run = 0;
  467. } else {
  468. run++;
  469. }
  470. }
  471. }
  472. return bits;
  473. }
  474. static int estimate_slice_plane(ProresContext *ctx, int *error, int plane,
  475. const uint16_t *src, int linesize,
  476. int mbs_per_slice,
  477. int blocks_per_mb, int plane_size_factor,
  478. const int16_t *qmat, ProresThreadData *td)
  479. {
  480. int blocks_per_slice;
  481. int bits;
  482. blocks_per_slice = mbs_per_slice * blocks_per_mb;
  483. bits = estimate_dcs(error, td->blocks[plane], blocks_per_slice, qmat[0]);
  484. bits += estimate_acs(error, td->blocks[plane], blocks_per_slice,
  485. plane_size_factor, ctx->scantable.permutated, qmat);
  486. return FFALIGN(bits, 8);
  487. }
  488. static int find_slice_quant(AVCodecContext *avctx, const AVFrame *pic,
  489. int trellis_node, int x, int y, int mbs_per_slice,
  490. ProresThreadData *td)
  491. {
  492. ProresContext *ctx = avctx->priv_data;
  493. int i, q, pq, xp, yp;
  494. const uint16_t *src;
  495. int slice_width_factor = av_log2(mbs_per_slice);
  496. int num_cblocks[MAX_PLANES], pwidth;
  497. int plane_factor[MAX_PLANES], is_chroma[MAX_PLANES];
  498. const int min_quant = ctx->profile_info->min_quant;
  499. const int max_quant = ctx->profile_info->max_quant;
  500. int error, bits, bits_limit;
  501. int mbs, prev, cur, new_score;
  502. int slice_bits[TRELLIS_WIDTH], slice_score[TRELLIS_WIDTH];
  503. int overquant;
  504. uint16_t *qmat;
  505. mbs = x + mbs_per_slice;
  506. for (i = 0; i < ctx->num_planes; i++) {
  507. is_chroma[i] = (i == 1 || i == 2);
  508. plane_factor[i] = slice_width_factor + 2;
  509. if (is_chroma[i])
  510. plane_factor[i] += ctx->chroma_factor - 3;
  511. if (!is_chroma[i] || ctx->chroma_factor == CFACTOR_Y444) {
  512. xp = x << 4;
  513. yp = y << 4;
  514. num_cblocks[i] = 4;
  515. pwidth = avctx->width;
  516. } else {
  517. xp = x << 3;
  518. yp = y << 4;
  519. num_cblocks[i] = 2;
  520. pwidth = avctx->width >> 1;
  521. }
  522. src = (const uint16_t*)(pic->data[i] + yp * pic->linesize[i]) + xp;
  523. get_slice_data(ctx, src, pic->linesize[i], xp, yp,
  524. pwidth, avctx->height, td->blocks[i], td->emu_buf,
  525. mbs_per_slice, num_cblocks[i], is_chroma[i]);
  526. }
  527. for (q = min_quant; q < max_quant + 2; q++) {
  528. td->nodes[trellis_node + q].prev_node = -1;
  529. td->nodes[trellis_node + q].quant = q;
  530. }
  531. // todo: maybe perform coarser quantising to fit into frame size when needed
  532. for (q = min_quant; q <= max_quant; q++) {
  533. bits = 0;
  534. error = 0;
  535. for (i = 0; i < ctx->num_planes; i++) {
  536. bits += estimate_slice_plane(ctx, &error, i,
  537. src, pic->linesize[i],
  538. mbs_per_slice,
  539. num_cblocks[i], plane_factor[i],
  540. ctx->quants[q], td);
  541. }
  542. if (bits > 65000 * 8) {
  543. error = SCORE_LIMIT;
  544. break;
  545. }
  546. slice_bits[q] = bits;
  547. slice_score[q] = error;
  548. }
  549. if (slice_bits[max_quant] <= ctx->bits_per_mb * mbs_per_slice) {
  550. slice_bits[max_quant + 1] = slice_bits[max_quant];
  551. slice_score[max_quant + 1] = slice_score[max_quant] + 1;
  552. overquant = max_quant;
  553. } else {
  554. for (q = max_quant + 1; q < 128; q++) {
  555. bits = 0;
  556. error = 0;
  557. if (q < MAX_STORED_Q) {
  558. qmat = ctx->quants[q];
  559. } else {
  560. qmat = td->custom_q;
  561. for (i = 0; i < 64; i++)
  562. qmat[i] = ctx->quant_mat[i] * q;
  563. }
  564. for (i = 0; i < ctx->num_planes; i++) {
  565. bits += estimate_slice_plane(ctx, &error, i,
  566. src, pic->linesize[i],
  567. mbs_per_slice,
  568. num_cblocks[i], plane_factor[i],
  569. qmat, td);
  570. }
  571. if (bits <= ctx->bits_per_mb * mbs_per_slice)
  572. break;
  573. }
  574. slice_bits[max_quant + 1] = bits;
  575. slice_score[max_quant + 1] = error;
  576. overquant = q;
  577. }
  578. td->nodes[trellis_node + max_quant + 1].quant = overquant;
  579. bits_limit = mbs * ctx->bits_per_mb;
  580. for (pq = min_quant; pq < max_quant + 2; pq++) {
  581. prev = trellis_node - TRELLIS_WIDTH + pq;
  582. for (q = min_quant; q < max_quant + 2; q++) {
  583. cur = trellis_node + q;
  584. bits = td->nodes[prev].bits + slice_bits[q];
  585. error = slice_score[q];
  586. if (bits > bits_limit)
  587. error = SCORE_LIMIT;
  588. if (td->nodes[prev].score < SCORE_LIMIT && error < SCORE_LIMIT)
  589. new_score = td->nodes[prev].score + error;
  590. else
  591. new_score = SCORE_LIMIT;
  592. if (td->nodes[cur].prev_node == -1 ||
  593. td->nodes[cur].score >= new_score) {
  594. td->nodes[cur].bits = bits;
  595. td->nodes[cur].score = new_score;
  596. td->nodes[cur].prev_node = prev;
  597. }
  598. }
  599. }
  600. error = td->nodes[trellis_node + min_quant].score;
  601. pq = trellis_node + min_quant;
  602. for (q = min_quant + 1; q < max_quant + 2; q++) {
  603. if (td->nodes[trellis_node + q].score <= error) {
  604. error = td->nodes[trellis_node + q].score;
  605. pq = trellis_node + q;
  606. }
  607. }
  608. return pq;
  609. }
  610. static int find_quant_thread(AVCodecContext *avctx, void *arg,
  611. int jobnr, int threadnr)
  612. {
  613. ProresContext *ctx = avctx->priv_data;
  614. ProresThreadData *td = ctx->tdata + threadnr;
  615. int mbs_per_slice = ctx->mbs_per_slice;
  616. int x, y = jobnr, mb, q = 0;
  617. for (x = mb = 0; x < ctx->mb_width; x += mbs_per_slice, mb++) {
  618. while (ctx->mb_width - x < mbs_per_slice)
  619. mbs_per_slice >>= 1;
  620. q = find_slice_quant(avctx, avctx->coded_frame,
  621. (mb + 1) * TRELLIS_WIDTH, x, y,
  622. mbs_per_slice, td);
  623. }
  624. for (x = ctx->slices_width - 1; x >= 0; x--) {
  625. ctx->slice_q[x + y * ctx->slices_width] = td->nodes[q].quant;
  626. q = td->nodes[q].prev_node;
  627. }
  628. return 0;
  629. }
  630. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  631. const AVFrame *pic, int *got_packet)
  632. {
  633. ProresContext *ctx = avctx->priv_data;
  634. uint8_t *orig_buf, *buf, *slice_hdr, *slice_sizes, *tmp;
  635. uint8_t *picture_size_pos;
  636. PutBitContext pb;
  637. int x, y, i, mb, q = 0;
  638. int sizes[4] = { 0 };
  639. int slice_hdr_size = 2 + 2 * (ctx->num_planes - 1);
  640. int frame_size, picture_size, slice_size;
  641. int pkt_size, ret;
  642. *avctx->coded_frame = *pic;
  643. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  644. avctx->coded_frame->key_frame = 1;
  645. pkt_size = ctx->frame_size + FF_MIN_BUFFER_SIZE;
  646. if ((ret = ff_alloc_packet(pkt, pkt_size)) < 0) {
  647. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  648. return ret;
  649. }
  650. orig_buf = pkt->data;
  651. // frame atom
  652. orig_buf += 4; // frame size
  653. bytestream_put_be32 (&orig_buf, FRAME_ID); // frame container ID
  654. buf = orig_buf;
  655. // frame header
  656. tmp = buf;
  657. buf += 2; // frame header size will be stored here
  658. bytestream_put_be16 (&buf, 0); // version 1
  659. bytestream_put_buffer(&buf, ctx->vendor, 4);
  660. bytestream_put_be16 (&buf, avctx->width);
  661. bytestream_put_be16 (&buf, avctx->height);
  662. bytestream_put_byte (&buf, ctx->chroma_factor << 6); // frame flags
  663. bytestream_put_byte (&buf, 0); // reserved
  664. bytestream_put_byte (&buf, avctx->color_primaries);
  665. bytestream_put_byte (&buf, avctx->color_trc);
  666. bytestream_put_byte (&buf, avctx->colorspace);
  667. bytestream_put_byte (&buf, 0x40); // source format and alpha information
  668. bytestream_put_byte (&buf, 0); // reserved
  669. if (ctx->quant_sel != QUANT_MAT_DEFAULT) {
  670. bytestream_put_byte (&buf, 0x03); // matrix flags - both matrices are present
  671. // luma quantisation matrix
  672. for (i = 0; i < 64; i++)
  673. bytestream_put_byte(&buf, ctx->quant_mat[i]);
  674. // chroma quantisation matrix
  675. for (i = 0; i < 64; i++)
  676. bytestream_put_byte(&buf, ctx->quant_mat[i]);
  677. } else {
  678. bytestream_put_byte (&buf, 0x00); // matrix flags - default matrices are used
  679. }
  680. bytestream_put_be16 (&tmp, buf - orig_buf); // write back frame header size
  681. // picture header
  682. picture_size_pos = buf + 1;
  683. bytestream_put_byte (&buf, 0x40); // picture header size (in bits)
  684. buf += 4; // picture data size will be stored here
  685. bytestream_put_be16 (&buf, ctx->num_slices); // total number of slices
  686. bytestream_put_byte (&buf, av_log2(ctx->mbs_per_slice) << 4); // slice width and height in MBs
  687. // seek table - will be filled during slice encoding
  688. slice_sizes = buf;
  689. buf += ctx->num_slices * 2;
  690. // slices
  691. if (!ctx->force_quant) {
  692. ret = avctx->execute2(avctx, find_quant_thread, NULL, NULL,
  693. ctx->mb_height);
  694. if (ret)
  695. return ret;
  696. }
  697. for (y = 0; y < ctx->mb_height; y++) {
  698. int mbs_per_slice = ctx->mbs_per_slice;
  699. for (x = mb = 0; x < ctx->mb_width; x += mbs_per_slice, mb++) {
  700. q = ctx->force_quant ? ctx->force_quant
  701. : ctx->slice_q[mb + y * ctx->slices_width];
  702. while (ctx->mb_width - x < mbs_per_slice)
  703. mbs_per_slice >>= 1;
  704. bytestream_put_byte(&buf, slice_hdr_size << 3);
  705. slice_hdr = buf;
  706. buf += slice_hdr_size - 1;
  707. init_put_bits(&pb, buf, (pkt_size - (buf - orig_buf)) * 8);
  708. encode_slice(avctx, pic, &pb, sizes, x, y, q, mbs_per_slice);
  709. bytestream_put_byte(&slice_hdr, q);
  710. slice_size = slice_hdr_size + sizes[ctx->num_planes - 1];
  711. for (i = 0; i < ctx->num_planes - 1; i++) {
  712. bytestream_put_be16(&slice_hdr, sizes[i]);
  713. slice_size += sizes[i];
  714. }
  715. bytestream_put_be16(&slice_sizes, slice_size);
  716. buf += slice_size - slice_hdr_size;
  717. }
  718. }
  719. orig_buf -= 8;
  720. frame_size = buf - orig_buf;
  721. picture_size = buf - picture_size_pos - 6;
  722. bytestream_put_be32(&orig_buf, frame_size);
  723. bytestream_put_be32(&picture_size_pos, picture_size);
  724. pkt->size = frame_size;
  725. pkt->flags |= AV_PKT_FLAG_KEY;
  726. *got_packet = 1;
  727. return 0;
  728. }
  729. static av_cold int encode_close(AVCodecContext *avctx)
  730. {
  731. ProresContext *ctx = avctx->priv_data;
  732. int i;
  733. if (avctx->coded_frame->data[0])
  734. avctx->release_buffer(avctx, avctx->coded_frame);
  735. av_freep(&avctx->coded_frame);
  736. if (ctx->tdata) {
  737. for (i = 0; i < avctx->thread_count; i++)
  738. av_free(ctx->tdata[i].nodes);
  739. }
  740. av_freep(&ctx->tdata);
  741. av_freep(&ctx->slice_q);
  742. return 0;
  743. }
  744. static av_cold int encode_init(AVCodecContext *avctx)
  745. {
  746. ProresContext *ctx = avctx->priv_data;
  747. int mps;
  748. int i, j;
  749. int min_quant, max_quant;
  750. avctx->bits_per_raw_sample = 10;
  751. avctx->coded_frame = avcodec_alloc_frame();
  752. if (!avctx->coded_frame)
  753. return AVERROR(ENOMEM);
  754. ff_proresdsp_init(&ctx->dsp);
  755. ff_init_scantable(ctx->dsp.dct_permutation, &ctx->scantable,
  756. ff_prores_progressive_scan);
  757. mps = ctx->mbs_per_slice;
  758. if (mps & (mps - 1)) {
  759. av_log(avctx, AV_LOG_ERROR,
  760. "there should be an integer power of two MBs per slice\n");
  761. return AVERROR(EINVAL);
  762. }
  763. ctx->chroma_factor = avctx->pix_fmt == PIX_FMT_YUV422P10
  764. ? CFACTOR_Y422
  765. : CFACTOR_Y444;
  766. ctx->profile_info = prores_profile_info + ctx->profile;
  767. ctx->num_planes = 3;
  768. ctx->mb_width = FFALIGN(avctx->width, 16) >> 4;
  769. ctx->mb_height = FFALIGN(avctx->height, 16) >> 4;
  770. ctx->slices_width = ctx->mb_width / mps;
  771. ctx->slices_width += av_popcount(ctx->mb_width - ctx->slices_width * mps);
  772. ctx->num_slices = ctx->mb_height * ctx->slices_width;
  773. if (ctx->quant_sel == -1)
  774. ctx->quant_mat = prores_quant_matrices[ctx->profile_info->quant];
  775. else
  776. ctx->quant_mat = prores_quant_matrices[ctx->quant_sel];
  777. if (strlen(ctx->vendor) != 4) {
  778. av_log(avctx, AV_LOG_ERROR, "vendor ID should be 4 bytes\n");
  779. return AVERROR_INVALIDDATA;
  780. }
  781. ctx->force_quant = avctx->global_quality / FF_QP2LAMBDA;
  782. if (!ctx->force_quant) {
  783. if (!ctx->bits_per_mb) {
  784. for (i = 0; i < NUM_MB_LIMITS - 1; i++)
  785. if (prores_mb_limits[i] >= ctx->mb_width * ctx->mb_height)
  786. break;
  787. ctx->bits_per_mb = ctx->profile_info->br_tab[i];
  788. } else if (ctx->bits_per_mb < 128) {
  789. av_log(avctx, AV_LOG_ERROR, "too few bits per MB, please set at least 128\n");
  790. return AVERROR_INVALIDDATA;
  791. }
  792. min_quant = ctx->profile_info->min_quant;
  793. max_quant = ctx->profile_info->max_quant;
  794. for (i = min_quant; i < MAX_STORED_Q; i++) {
  795. for (j = 0; j < 64; j++)
  796. ctx->quants[i][j] = ctx->quant_mat[j] * i;
  797. }
  798. ctx->slice_q = av_malloc(ctx->num_slices * sizeof(*ctx->slice_q));
  799. if (!ctx->slice_q) {
  800. encode_close(avctx);
  801. return AVERROR(ENOMEM);
  802. }
  803. ctx->tdata = av_mallocz(avctx->thread_count * sizeof(*ctx->tdata));
  804. if (!ctx->tdata) {
  805. encode_close(avctx);
  806. return AVERROR(ENOMEM);
  807. }
  808. for (j = 0; j < avctx->thread_count; j++) {
  809. ctx->tdata[j].nodes = av_malloc((ctx->slices_width + 1)
  810. * TRELLIS_WIDTH
  811. * sizeof(*ctx->tdata->nodes));
  812. if (!ctx->tdata[j].nodes) {
  813. encode_close(avctx);
  814. return AVERROR(ENOMEM);
  815. }
  816. for (i = min_quant; i < max_quant + 2; i++) {
  817. ctx->tdata[j].nodes[i].prev_node = -1;
  818. ctx->tdata[j].nodes[i].bits = 0;
  819. ctx->tdata[j].nodes[i].score = 0;
  820. }
  821. }
  822. } else {
  823. int ls = 0;
  824. if (ctx->force_quant > 64) {
  825. av_log(avctx, AV_LOG_ERROR, "too large quantiser, maximum is 64\n");
  826. return AVERROR_INVALIDDATA;
  827. }
  828. for (j = 0; j < 64; j++) {
  829. ctx->quants[0][j] = ctx->quant_mat[j] * ctx->force_quant;
  830. ls += av_log2((1 << 11) / ctx->quants[0][j]) * 2 + 1;
  831. }
  832. ctx->bits_per_mb = ls * 8;
  833. if (ctx->chroma_factor == CFACTOR_Y444)
  834. ctx->bits_per_mb += ls * 4;
  835. if (ctx->num_planes == 4)
  836. ctx->bits_per_mb += ls * 4;
  837. }
  838. ctx->frame_size = ctx->num_slices * (2 + 2 * ctx->num_planes
  839. + (2 * mps * ctx->bits_per_mb) / 8)
  840. + 200;
  841. avctx->codec_tag = ctx->profile_info->tag;
  842. av_log(avctx, AV_LOG_DEBUG, "profile %d, %d slices, %d bits per MB\n",
  843. ctx->profile, ctx->num_slices, ctx->bits_per_mb);
  844. av_log(avctx, AV_LOG_DEBUG, "estimated frame size %d\n",
  845. ctx->frame_size);
  846. return 0;
  847. }
  848. #define OFFSET(x) offsetof(ProresContext, x)
  849. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  850. static const AVOption options[] = {
  851. { "mbs_per_slice", "macroblocks per slice", OFFSET(mbs_per_slice),
  852. AV_OPT_TYPE_INT, { 8 }, 1, MAX_MBS_PER_SLICE, VE },
  853. { "profile", NULL, OFFSET(profile), AV_OPT_TYPE_INT,
  854. { PRORES_PROFILE_STANDARD },
  855. PRORES_PROFILE_PROXY, PRORES_PROFILE_HQ, VE, "profile" },
  856. { "proxy", NULL, 0, AV_OPT_TYPE_CONST, { PRORES_PROFILE_PROXY },
  857. 0, 0, VE, "profile" },
  858. { "lt", NULL, 0, AV_OPT_TYPE_CONST, { PRORES_PROFILE_LT },
  859. 0, 0, VE, "profile" },
  860. { "standard", NULL, 0, AV_OPT_TYPE_CONST, { PRORES_PROFILE_STANDARD },
  861. 0, 0, VE, "profile" },
  862. { "hq", NULL, 0, AV_OPT_TYPE_CONST, { PRORES_PROFILE_HQ },
  863. 0, 0, VE, "profile" },
  864. { "vendor", "vendor ID", OFFSET(vendor),
  865. AV_OPT_TYPE_STRING, { .str = "Lavc" }, CHAR_MIN, CHAR_MAX, VE },
  866. { "bits_per_mb", "desired bits per macroblock", OFFSET(bits_per_mb),
  867. AV_OPT_TYPE_INT, { 0 }, 0, 8192, VE },
  868. { "quant_mat", "quantiser matrix", OFFSET(quant_sel), AV_OPT_TYPE_INT,
  869. { -1 }, -1, QUANT_MAT_DEFAULT, VE, "quant_mat" },
  870. { "auto", NULL, 0, AV_OPT_TYPE_CONST, { -1 },
  871. 0, 0, VE, "quant_mat" },
  872. { "proxy", NULL, 0, AV_OPT_TYPE_CONST, { QUANT_MAT_PROXY },
  873. 0, 0, VE, "quant_mat" },
  874. { "lt", NULL, 0, AV_OPT_TYPE_CONST, { QUANT_MAT_LT },
  875. 0, 0, VE, "quant_mat" },
  876. { "standard", NULL, 0, AV_OPT_TYPE_CONST, { QUANT_MAT_STANDARD },
  877. 0, 0, VE, "quant_mat" },
  878. { "hq", NULL, 0, AV_OPT_TYPE_CONST, { QUANT_MAT_HQ },
  879. 0, 0, VE, "quant_mat" },
  880. { "default", NULL, 0, AV_OPT_TYPE_CONST, { QUANT_MAT_DEFAULT },
  881. 0, 0, VE, "quant_mat" },
  882. { NULL }
  883. };
  884. static const AVClass proresenc_class = {
  885. .class_name = "ProRes encoder",
  886. .item_name = av_default_item_name,
  887. .option = options,
  888. .version = LIBAVUTIL_VERSION_INT,
  889. };
  890. AVCodec ff_prores_encoder = {
  891. .name = "prores",
  892. .type = AVMEDIA_TYPE_VIDEO,
  893. .id = CODEC_ID_PRORES,
  894. .priv_data_size = sizeof(ProresContext),
  895. .init = encode_init,
  896. .close = encode_close,
  897. .encode2 = encode_frame,
  898. .capabilities = CODEC_CAP_SLICE_THREADS,
  899. .long_name = NULL_IF_CONFIG_SMALL("Apple ProRes (iCodec Pro)"),
  900. .pix_fmts = (const enum PixelFormat[]) {
  901. PIX_FMT_YUV422P10, PIX_FMT_YUV444P10, PIX_FMT_NONE
  902. },
  903. .priv_class = &proresenc_class,
  904. };