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.

676 lines
20KB

  1. /*
  2. * Ut Video encoder
  3. * Copyright (c) 2012 Jan Ekström
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Ut Video encoder
  24. */
  25. #include "libavutil/imgutils.h"
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/opt.h"
  28. #include "avcodec.h"
  29. #include "internal.h"
  30. #include "bswapdsp.h"
  31. #include "bytestream.h"
  32. #include "put_bits.h"
  33. #include "huffyuvencdsp.h"
  34. #include "mathops.h"
  35. #include "utvideo.h"
  36. #include "huffman.h"
  37. /* Compare huffentry symbols */
  38. static int huff_cmp_sym(const void *a, const void *b)
  39. {
  40. const HuffEntry *aa = a, *bb = b;
  41. return aa->sym - bb->sym;
  42. }
  43. static av_cold int utvideo_encode_close(AVCodecContext *avctx)
  44. {
  45. UtvideoContext *c = avctx->priv_data;
  46. int i;
  47. av_freep(&c->slice_bits);
  48. for (i = 0; i < 4; i++)
  49. av_freep(&c->slice_buffer[i]);
  50. return 0;
  51. }
  52. static av_cold int utvideo_encode_init(AVCodecContext *avctx)
  53. {
  54. UtvideoContext *c = avctx->priv_data;
  55. int i, subsampled_height;
  56. uint32_t original_format;
  57. c->avctx = avctx;
  58. c->frame_info_size = 4;
  59. c->slice_stride = FFALIGN(avctx->width, 32);
  60. switch (avctx->pix_fmt) {
  61. case AV_PIX_FMT_RGB24:
  62. c->planes = 3;
  63. avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
  64. original_format = UTVIDEO_RGB;
  65. break;
  66. case AV_PIX_FMT_RGBA:
  67. c->planes = 4;
  68. avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
  69. original_format = UTVIDEO_RGBA;
  70. break;
  71. case AV_PIX_FMT_YUV420P:
  72. if (avctx->width & 1 || avctx->height & 1) {
  73. av_log(avctx, AV_LOG_ERROR,
  74. "4:2:0 video requires even width and height.\n");
  75. return AVERROR_INVALIDDATA;
  76. }
  77. c->planes = 3;
  78. if (avctx->colorspace == AVCOL_SPC_BT709)
  79. avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
  80. else
  81. avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
  82. original_format = UTVIDEO_420;
  83. break;
  84. case AV_PIX_FMT_YUV422P:
  85. if (avctx->width & 1) {
  86. av_log(avctx, AV_LOG_ERROR,
  87. "4:2:2 video requires even width.\n");
  88. return AVERROR_INVALIDDATA;
  89. }
  90. c->planes = 3;
  91. if (avctx->colorspace == AVCOL_SPC_BT709)
  92. avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
  93. else
  94. avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
  95. original_format = UTVIDEO_422;
  96. break;
  97. default:
  98. av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
  99. avctx->pix_fmt);
  100. return AVERROR_INVALIDDATA;
  101. }
  102. ff_bswapdsp_init(&c->bdsp);
  103. ff_huffyuvencdsp_init(&c->hdsp);
  104. #if FF_API_PRIVATE_OPT
  105. FF_DISABLE_DEPRECATION_WARNINGS
  106. /* Check the prediction method, and error out if unsupported */
  107. if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
  108. av_log(avctx, AV_LOG_WARNING,
  109. "Prediction method %d is not supported in Ut Video.\n",
  110. avctx->prediction_method);
  111. return AVERROR_OPTION_NOT_FOUND;
  112. }
  113. if (avctx->prediction_method == FF_PRED_PLANE) {
  114. av_log(avctx, AV_LOG_ERROR,
  115. "Plane prediction is not supported in Ut Video.\n");
  116. return AVERROR_OPTION_NOT_FOUND;
  117. }
  118. /* Convert from libavcodec prediction type to Ut Video's */
  119. if (avctx->prediction_method)
  120. c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
  121. FF_ENABLE_DEPRECATION_WARNINGS
  122. #endif
  123. if (c->frame_pred == PRED_GRADIENT) {
  124. av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
  125. return AVERROR_OPTION_NOT_FOUND;
  126. }
  127. /*
  128. * Check the asked slice count for obviously invalid
  129. * values (> 256 or negative).
  130. */
  131. if (avctx->slices > 256 || avctx->slices < 0) {
  132. av_log(avctx, AV_LOG_ERROR,
  133. "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
  134. avctx->slices);
  135. return AVERROR(EINVAL);
  136. }
  137. /* Check that the slice count is not larger than the subsampled height */
  138. subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
  139. if (avctx->slices > subsampled_height) {
  140. av_log(avctx, AV_LOG_ERROR,
  141. "Slice count %d is larger than the subsampling-applied height %d.\n",
  142. avctx->slices, subsampled_height);
  143. return AVERROR(EINVAL);
  144. }
  145. /* extradata size is 4 * 32 bits */
  146. avctx->extradata_size = 16;
  147. avctx->extradata = av_mallocz(avctx->extradata_size +
  148. AV_INPUT_BUFFER_PADDING_SIZE);
  149. if (!avctx->extradata) {
  150. av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
  151. utvideo_encode_close(avctx);
  152. return AVERROR(ENOMEM);
  153. }
  154. for (i = 0; i < c->planes; i++) {
  155. c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
  156. AV_INPUT_BUFFER_PADDING_SIZE);
  157. if (!c->slice_buffer[i]) {
  158. av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
  159. utvideo_encode_close(avctx);
  160. return AVERROR(ENOMEM);
  161. }
  162. }
  163. /*
  164. * Set the version of the encoder.
  165. * Last byte is "implementation ID", which is
  166. * obtained from the creator of the format.
  167. * Libavcodec has been assigned with the ID 0xF0.
  168. */
  169. AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
  170. /*
  171. * Set the "original format"
  172. * Not used for anything during decoding.
  173. */
  174. AV_WL32(avctx->extradata + 4, original_format);
  175. /* Write 4 as the 'frame info size' */
  176. AV_WL32(avctx->extradata + 8, c->frame_info_size);
  177. /*
  178. * Set how many slices are going to be used.
  179. * By default uses multiple slices depending on the subsampled height.
  180. * This enables multithreading in the official decoder.
  181. */
  182. if (!avctx->slices) {
  183. c->slices = subsampled_height / 120;
  184. if (!c->slices)
  185. c->slices = 1;
  186. else if (c->slices > 256)
  187. c->slices = 256;
  188. } else {
  189. c->slices = avctx->slices;
  190. }
  191. /* Set compression mode */
  192. c->compression = COMP_HUFF;
  193. /*
  194. * Set the encoding flags:
  195. * - Slice count minus 1
  196. * - Interlaced encoding mode flag, set to zero for now.
  197. * - Compression mode (none/huff)
  198. * And write the flags.
  199. */
  200. c->flags = (c->slices - 1) << 24;
  201. c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
  202. c->flags |= c->compression;
  203. AV_WL32(avctx->extradata + 12, c->flags);
  204. return 0;
  205. }
  206. static void mangle_rgb_planes(uint8_t *dst[4], ptrdiff_t dst_stride,
  207. uint8_t *src, int step, ptrdiff_t stride,
  208. int width, int height)
  209. {
  210. int i, j;
  211. int k = 2 * dst_stride;
  212. unsigned int g;
  213. for (j = 0; j < height; j++) {
  214. if (step == 3) {
  215. for (i = 0; i < width * step; i += step) {
  216. g = src[i + 1];
  217. dst[0][k] = g;
  218. g += 0x80;
  219. dst[1][k] = src[i + 2] - g;
  220. dst[2][k] = src[i + 0] - g;
  221. k++;
  222. }
  223. } else {
  224. for (i = 0; i < width * step; i += step) {
  225. g = src[i + 1];
  226. dst[0][k] = g;
  227. g += 0x80;
  228. dst[1][k] = src[i + 2] - g;
  229. dst[2][k] = src[i + 0] - g;
  230. dst[3][k] = src[i + 3];
  231. k++;
  232. }
  233. }
  234. k += dst_stride - width;
  235. src += stride;
  236. }
  237. }
  238. /* Write data to a plane with left prediction */
  239. static void left_predict(uint8_t *src, uint8_t *dst, ptrdiff_t stride,
  240. int width, int height)
  241. {
  242. int i, j;
  243. uint8_t prev;
  244. prev = 0x80; /* Set the initial value */
  245. for (j = 0; j < height; j++) {
  246. for (i = 0; i < width; i++) {
  247. *dst++ = src[i] - prev;
  248. prev = src[i];
  249. }
  250. src += stride;
  251. }
  252. }
  253. /* Write data to a plane with median prediction */
  254. static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst,
  255. ptrdiff_t stride, int width, int height)
  256. {
  257. int i, j;
  258. int A, B;
  259. uint8_t prev;
  260. /* First line uses left neighbour prediction */
  261. prev = 0x80; /* Set the initial value */
  262. for (i = 0; i < width; i++) {
  263. *dst++ = src[i] - prev;
  264. prev = src[i];
  265. }
  266. if (height == 1)
  267. return;
  268. src += stride;
  269. /*
  270. * Second line uses top prediction for the first sample,
  271. * and median for the rest.
  272. */
  273. A = B = 0;
  274. /* Rest of the coded part uses median prediction */
  275. for (j = 1; j < height; j++) {
  276. c->hdsp.sub_hfyu_median_pred(dst, src - stride, src, width, &A, &B);
  277. dst += width;
  278. src += stride;
  279. }
  280. }
  281. /* Count the usage of values in a plane */
  282. static void count_usage(uint8_t *src, int width,
  283. int height, uint64_t *counts)
  284. {
  285. int i, j;
  286. for (j = 0; j < height; j++) {
  287. for (i = 0; i < width; i++) {
  288. counts[src[i]]++;
  289. }
  290. src += width;
  291. }
  292. }
  293. /* Calculate the actual huffman codes from the code lengths */
  294. static void calculate_codes(HuffEntry *he)
  295. {
  296. int last, i;
  297. uint32_t code;
  298. qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
  299. last = 255;
  300. while (he[last].len == 255 && last)
  301. last--;
  302. code = 1;
  303. for (i = last; i >= 0; i--) {
  304. he[i].code = code >> (32 - he[i].len);
  305. code += 0x80000000u >> (he[i].len - 1);
  306. }
  307. qsort(he, 256, sizeof(*he), huff_cmp_sym);
  308. }
  309. /* Write huffman bit codes to a memory block */
  310. static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
  311. int width, int height, HuffEntry *he)
  312. {
  313. PutBitContext pb;
  314. int i, j;
  315. int count;
  316. init_put_bits(&pb, dst, dst_size);
  317. /* Write the codes */
  318. for (j = 0; j < height; j++) {
  319. for (i = 0; i < width; i++)
  320. put_bits(&pb, he[src[i]].len, he[src[i]].code);
  321. src += width;
  322. }
  323. /* Pad output to a 32-bit boundary */
  324. count = put_bits_count(&pb) & 0x1F;
  325. if (count)
  326. put_bits(&pb, 32 - count, 0);
  327. /* Get the amount of bits written */
  328. count = put_bits_count(&pb);
  329. /* Flush the rest with zeroes */
  330. flush_put_bits(&pb);
  331. return count;
  332. }
  333. static int encode_plane(AVCodecContext *avctx, uint8_t *src,
  334. uint8_t *dst, ptrdiff_t stride,
  335. int width, int height, PutByteContext *pb)
  336. {
  337. UtvideoContext *c = avctx->priv_data;
  338. uint8_t lengths[256];
  339. uint64_t counts[256] = { 0 };
  340. HuffEntry he[256];
  341. uint32_t offset = 0, slice_len = 0;
  342. int i, sstart, send = 0;
  343. int symbol;
  344. /* Do prediction / make planes */
  345. switch (c->frame_pred) {
  346. case PRED_NONE:
  347. for (i = 0; i < c->slices; i++) {
  348. sstart = send;
  349. send = height * (i + 1) / c->slices;
  350. av_image_copy_plane(dst + sstart * width, width,
  351. src + sstart * stride, stride,
  352. width, send - sstart);
  353. }
  354. break;
  355. case PRED_LEFT:
  356. for (i = 0; i < c->slices; i++) {
  357. sstart = send;
  358. send = height * (i + 1) / c->slices;
  359. left_predict(src + sstart * stride, dst + sstart * width,
  360. stride, width, send - sstart);
  361. }
  362. break;
  363. case PRED_MEDIAN:
  364. for (i = 0; i < c->slices; i++) {
  365. sstart = send;
  366. send = height * (i + 1) / c->slices;
  367. median_predict(c, src + sstart * stride, dst + sstart * width,
  368. stride, width, send - sstart);
  369. }
  370. break;
  371. default:
  372. av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
  373. c->frame_pred);
  374. return AVERROR_OPTION_NOT_FOUND;
  375. }
  376. /* Count the usage of values */
  377. count_usage(dst, width, height, counts);
  378. /* Check for a special case where only one symbol was used */
  379. for (symbol = 0; symbol < 256; symbol++) {
  380. /* If non-zero count is found, see if it matches width * height */
  381. if (counts[symbol]) {
  382. /* Special case if only one symbol was used */
  383. if (counts[symbol] == width * height) {
  384. /*
  385. * Write a zero for the single symbol
  386. * used in the plane, else 0xFF.
  387. */
  388. for (i = 0; i < 256; i++) {
  389. if (i == symbol)
  390. bytestream2_put_byte(pb, 0);
  391. else
  392. bytestream2_put_byte(pb, 0xFF);
  393. }
  394. /* Write zeroes for lengths */
  395. for (i = 0; i < c->slices; i++)
  396. bytestream2_put_le32(pb, 0);
  397. /* And that's all for that plane folks */
  398. return 0;
  399. }
  400. break;
  401. }
  402. }
  403. /* Calculate huffman lengths */
  404. ff_huff_gen_len_table(lengths, counts);
  405. /*
  406. * Write the plane's header into the output packet:
  407. * - huffman code lengths (256 bytes)
  408. * - slice end offsets (gotten from the slice lengths)
  409. */
  410. for (i = 0; i < 256; i++) {
  411. bytestream2_put_byte(pb, lengths[i]);
  412. he[i].len = lengths[i];
  413. he[i].sym = i;
  414. }
  415. /* Calculate the huffman codes themselves */
  416. calculate_codes(he);
  417. send = 0;
  418. for (i = 0; i < c->slices; i++) {
  419. sstart = send;
  420. send = height * (i + 1) / c->slices;
  421. /*
  422. * Write the huffman codes to a buffer,
  423. * get the offset in bits and convert to bytes.
  424. */
  425. offset += write_huff_codes(dst + sstart * width, c->slice_bits,
  426. width * (send - sstart), width,
  427. send - sstart, he) >> 3;
  428. slice_len = offset - slice_len;
  429. /* Byteswap the written huffman codes */
  430. c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
  431. (uint32_t *) c->slice_bits,
  432. slice_len >> 2);
  433. /* Write the offset to the stream */
  434. bytestream2_put_le32(pb, offset);
  435. /* Seek to the data part of the packet */
  436. bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
  437. offset - slice_len, SEEK_CUR);
  438. /* Write the slices' data into the output packet */
  439. bytestream2_put_buffer(pb, c->slice_bits, slice_len);
  440. /* Seek back to the slice offsets */
  441. bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
  442. SEEK_CUR);
  443. slice_len = offset;
  444. }
  445. /* And at the end seek to the end of written slice(s) */
  446. bytestream2_seek_p(pb, offset, SEEK_CUR);
  447. return 0;
  448. }
  449. static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  450. const AVFrame *pic, int *got_packet)
  451. {
  452. UtvideoContext *c = avctx->priv_data;
  453. PutByteContext pb;
  454. uint32_t frame_info;
  455. uint8_t *dst;
  456. int width = avctx->width, height = avctx->height;
  457. int i, ret = 0;
  458. /* Allocate a new packet if needed, and set it to the pointer dst */
  459. ret = ff_alloc_packet(pkt, (256 + 4 * c->slices + width * height) *
  460. c->planes + 4);
  461. if (ret < 0) {
  462. av_log(avctx, AV_LOG_ERROR,
  463. "Error allocating the output packet, or the provided packet "
  464. "was too small.\n");
  465. return ret;
  466. }
  467. dst = pkt->data;
  468. bytestream2_init_writer(&pb, dst, pkt->size);
  469. av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
  470. width * height + AV_INPUT_BUFFER_PADDING_SIZE);
  471. if (!c->slice_bits) {
  472. av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
  473. return AVERROR(ENOMEM);
  474. }
  475. /* In case of RGB, mangle the planes to Ut Video's format */
  476. if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
  477. mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
  478. c->planes, pic->linesize[0], width, height);
  479. /* Deal with the planes */
  480. switch (avctx->pix_fmt) {
  481. case AV_PIX_FMT_RGB24:
  482. case AV_PIX_FMT_RGBA:
  483. for (i = 0; i < c->planes; i++) {
  484. ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
  485. c->slice_buffer[i], c->slice_stride,
  486. width, height, &pb);
  487. if (ret) {
  488. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  489. return ret;
  490. }
  491. }
  492. break;
  493. case AV_PIX_FMT_YUV422P:
  494. for (i = 0; i < c->planes; i++) {
  495. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  496. pic->linesize[i], width >> !!i, height, &pb);
  497. if (ret) {
  498. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  499. return ret;
  500. }
  501. }
  502. break;
  503. case AV_PIX_FMT_YUV420P:
  504. for (i = 0; i < c->planes; i++) {
  505. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  506. pic->linesize[i], width >> !!i, height >> !!i,
  507. &pb);
  508. if (ret) {
  509. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  510. return ret;
  511. }
  512. }
  513. break;
  514. default:
  515. av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
  516. avctx->pix_fmt);
  517. return AVERROR_INVALIDDATA;
  518. }
  519. /*
  520. * Write frame information (LE 32-bit unsigned)
  521. * into the output packet.
  522. * Contains the prediction method.
  523. */
  524. frame_info = c->frame_pred << 8;
  525. bytestream2_put_le32(&pb, frame_info);
  526. /*
  527. * At least currently Ut Video is IDR only.
  528. * Set flags accordingly.
  529. */
  530. #if FF_API_CODED_FRAME
  531. FF_DISABLE_DEPRECATION_WARNINGS
  532. avctx->coded_frame->key_frame = 1;
  533. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  534. FF_ENABLE_DEPRECATION_WARNINGS
  535. #endif
  536. pkt->size = bytestream2_tell_p(&pb);
  537. pkt->flags |= AV_PKT_FLAG_KEY;
  538. /* Packet should be done */
  539. *got_packet = 1;
  540. return 0;
  541. }
  542. #define OFFSET(x) offsetof(UtvideoContext, x)
  543. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  544. static const AVOption options[] = {
  545. { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
  546. { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
  547. { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
  548. { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
  549. { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
  550. { NULL},
  551. };
  552. static const AVClass utvideo_class = {
  553. .class_name = "utvideo",
  554. .item_name = av_default_item_name,
  555. .option = options,
  556. .version = LIBAVUTIL_VERSION_INT,
  557. };
  558. AVCodec ff_utvideo_encoder = {
  559. .name = "utvideo",
  560. .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
  561. .type = AVMEDIA_TYPE_VIDEO,
  562. .id = AV_CODEC_ID_UTVIDEO,
  563. .priv_data_size = sizeof(UtvideoContext),
  564. .priv_class = &utvideo_class,
  565. .init = utvideo_encode_init,
  566. .encode2 = utvideo_encode_frame,
  567. .close = utvideo_encode_close,
  568. .pix_fmts = (const enum AVPixelFormat[]) {
  569. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
  570. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  571. },
  572. };