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.

675 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], int dst_stride, uint8_t *src,
  207. int step, int stride, int width, int height)
  208. {
  209. int i, j;
  210. int k = 2 * dst_stride;
  211. unsigned int g;
  212. for (j = 0; j < height; j++) {
  213. if (step == 3) {
  214. for (i = 0; i < width * step; i += step) {
  215. g = src[i + 1];
  216. dst[0][k] = g;
  217. g += 0x80;
  218. dst[1][k] = src[i + 2] - g;
  219. dst[2][k] = src[i + 0] - g;
  220. k++;
  221. }
  222. } else {
  223. for (i = 0; i < width * step; i += step) {
  224. g = src[i + 1];
  225. dst[0][k] = g;
  226. g += 0x80;
  227. dst[1][k] = src[i + 2] - g;
  228. dst[2][k] = src[i + 0] - g;
  229. dst[3][k] = src[i + 3];
  230. k++;
  231. }
  232. }
  233. k += dst_stride - width;
  234. src += stride;
  235. }
  236. }
  237. /* Write data to a plane with left prediction */
  238. static void left_predict(uint8_t *src, uint8_t *dst, int stride,
  239. int width, int height)
  240. {
  241. int i, j;
  242. uint8_t prev;
  243. prev = 0x80; /* Set the initial value */
  244. for (j = 0; j < height; j++) {
  245. for (i = 0; i < width; i++) {
  246. *dst++ = src[i] - prev;
  247. prev = src[i];
  248. }
  249. src += stride;
  250. }
  251. }
  252. /* Write data to a plane with median prediction */
  253. static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst, int stride,
  254. int width, int height)
  255. {
  256. int i, j;
  257. int A, B;
  258. uint8_t prev;
  259. /* First line uses left neighbour prediction */
  260. prev = 0x80; /* Set the initial value */
  261. for (i = 0; i < width; i++) {
  262. *dst++ = src[i] - prev;
  263. prev = src[i];
  264. }
  265. if (height == 1)
  266. return;
  267. src += stride;
  268. /*
  269. * Second line uses top prediction for the first sample,
  270. * and median for the rest.
  271. */
  272. A = B = 0;
  273. /* Rest of the coded part uses median prediction */
  274. for (j = 1; j < height; j++) {
  275. c->hdsp.sub_hfyu_median_pred(dst, src - stride, src, width, &A, &B);
  276. dst += width;
  277. src += stride;
  278. }
  279. }
  280. /* Count the usage of values in a plane */
  281. static void count_usage(uint8_t *src, int width,
  282. int height, uint64_t *counts)
  283. {
  284. int i, j;
  285. for (j = 0; j < height; j++) {
  286. for (i = 0; i < width; i++) {
  287. counts[src[i]]++;
  288. }
  289. src += width;
  290. }
  291. }
  292. /* Calculate the actual huffman codes from the code lengths */
  293. static void calculate_codes(HuffEntry *he)
  294. {
  295. int last, i;
  296. uint32_t code;
  297. qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
  298. last = 255;
  299. while (he[last].len == 255 && last)
  300. last--;
  301. code = 1;
  302. for (i = last; i >= 0; i--) {
  303. he[i].code = code >> (32 - he[i].len);
  304. code += 0x80000000u >> (he[i].len - 1);
  305. }
  306. qsort(he, 256, sizeof(*he), huff_cmp_sym);
  307. }
  308. /* Write huffman bit codes to a memory block */
  309. static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
  310. int width, int height, HuffEntry *he)
  311. {
  312. PutBitContext pb;
  313. int i, j;
  314. int count;
  315. init_put_bits(&pb, dst, dst_size);
  316. /* Write the codes */
  317. for (j = 0; j < height; j++) {
  318. for (i = 0; i < width; i++)
  319. put_bits(&pb, he[src[i]].len, he[src[i]].code);
  320. src += width;
  321. }
  322. /* Pad output to a 32-bit boundary */
  323. count = put_bits_count(&pb) & 0x1F;
  324. if (count)
  325. put_bits(&pb, 32 - count, 0);
  326. /* Get the amount of bits written */
  327. count = put_bits_count(&pb);
  328. /* Flush the rest with zeroes */
  329. flush_put_bits(&pb);
  330. return count;
  331. }
  332. static int encode_plane(AVCodecContext *avctx, uint8_t *src,
  333. uint8_t *dst, int stride,
  334. int width, int height, PutByteContext *pb)
  335. {
  336. UtvideoContext *c = avctx->priv_data;
  337. uint8_t lengths[256];
  338. uint64_t counts[256] = { 0 };
  339. HuffEntry he[256];
  340. uint32_t offset = 0, slice_len = 0;
  341. int i, sstart, send = 0;
  342. int symbol;
  343. /* Do prediction / make planes */
  344. switch (c->frame_pred) {
  345. case PRED_NONE:
  346. for (i = 0; i < c->slices; i++) {
  347. sstart = send;
  348. send = height * (i + 1) / c->slices;
  349. av_image_copy_plane(dst + sstart * width, width,
  350. src + sstart * stride, stride,
  351. width, send - sstart);
  352. }
  353. break;
  354. case PRED_LEFT:
  355. for (i = 0; i < c->slices; i++) {
  356. sstart = send;
  357. send = height * (i + 1) / c->slices;
  358. left_predict(src + sstart * stride, dst + sstart * width,
  359. stride, width, send - sstart);
  360. }
  361. break;
  362. case PRED_MEDIAN:
  363. for (i = 0; i < c->slices; i++) {
  364. sstart = send;
  365. send = height * (i + 1) / c->slices;
  366. median_predict(c, src + sstart * stride, dst + sstart * width,
  367. stride, width, send - sstart);
  368. }
  369. break;
  370. default:
  371. av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
  372. c->frame_pred);
  373. return AVERROR_OPTION_NOT_FOUND;
  374. }
  375. /* Count the usage of values */
  376. count_usage(dst, width, height, counts);
  377. /* Check for a special case where only one symbol was used */
  378. for (symbol = 0; symbol < 256; symbol++) {
  379. /* If non-zero count is found, see if it matches width * height */
  380. if (counts[symbol]) {
  381. /* Special case if only one symbol was used */
  382. if (counts[symbol] == width * height) {
  383. /*
  384. * Write a zero for the single symbol
  385. * used in the plane, else 0xFF.
  386. */
  387. for (i = 0; i < 256; i++) {
  388. if (i == symbol)
  389. bytestream2_put_byte(pb, 0);
  390. else
  391. bytestream2_put_byte(pb, 0xFF);
  392. }
  393. /* Write zeroes for lengths */
  394. for (i = 0; i < c->slices; i++)
  395. bytestream2_put_le32(pb, 0);
  396. /* And that's all for that plane folks */
  397. return 0;
  398. }
  399. break;
  400. }
  401. }
  402. /* Calculate huffman lengths */
  403. ff_huff_gen_len_table(lengths, counts);
  404. /*
  405. * Write the plane's header into the output packet:
  406. * - huffman code lengths (256 bytes)
  407. * - slice end offsets (gotten from the slice lengths)
  408. */
  409. for (i = 0; i < 256; i++) {
  410. bytestream2_put_byte(pb, lengths[i]);
  411. he[i].len = lengths[i];
  412. he[i].sym = i;
  413. }
  414. /* Calculate the huffman codes themselves */
  415. calculate_codes(he);
  416. send = 0;
  417. for (i = 0; i < c->slices; i++) {
  418. sstart = send;
  419. send = height * (i + 1) / c->slices;
  420. /*
  421. * Write the huffman codes to a buffer,
  422. * get the offset in bits and convert to bytes.
  423. */
  424. offset += write_huff_codes(dst + sstart * width, c->slice_bits,
  425. width * (send - sstart), width,
  426. send - sstart, he) >> 3;
  427. slice_len = offset - slice_len;
  428. /* Byteswap the written huffman codes */
  429. c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
  430. (uint32_t *) c->slice_bits,
  431. slice_len >> 2);
  432. /* Write the offset to the stream */
  433. bytestream2_put_le32(pb, offset);
  434. /* Seek to the data part of the packet */
  435. bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
  436. offset - slice_len, SEEK_CUR);
  437. /* Write the slices' data into the output packet */
  438. bytestream2_put_buffer(pb, c->slice_bits, slice_len);
  439. /* Seek back to the slice offsets */
  440. bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
  441. SEEK_CUR);
  442. slice_len = offset;
  443. }
  444. /* And at the end seek to the end of written slice(s) */
  445. bytestream2_seek_p(pb, offset, SEEK_CUR);
  446. return 0;
  447. }
  448. static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  449. const AVFrame *pic, int *got_packet)
  450. {
  451. UtvideoContext *c = avctx->priv_data;
  452. PutByteContext pb;
  453. uint32_t frame_info;
  454. uint8_t *dst;
  455. int width = avctx->width, height = avctx->height;
  456. int i, ret = 0;
  457. /* Allocate a new packet if needed, and set it to the pointer dst */
  458. ret = ff_alloc_packet(pkt, (256 + 4 * c->slices + width * height) *
  459. c->planes + 4);
  460. if (ret < 0) {
  461. av_log(avctx, AV_LOG_ERROR,
  462. "Error allocating the output packet, or the provided packet "
  463. "was too small.\n");
  464. return ret;
  465. }
  466. dst = pkt->data;
  467. bytestream2_init_writer(&pb, dst, pkt->size);
  468. av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
  469. width * height + AV_INPUT_BUFFER_PADDING_SIZE);
  470. if (!c->slice_bits) {
  471. av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
  472. return AVERROR(ENOMEM);
  473. }
  474. /* In case of RGB, mangle the planes to Ut Video's format */
  475. if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
  476. mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
  477. c->planes, pic->linesize[0], width, height);
  478. /* Deal with the planes */
  479. switch (avctx->pix_fmt) {
  480. case AV_PIX_FMT_RGB24:
  481. case AV_PIX_FMT_RGBA:
  482. for (i = 0; i < c->planes; i++) {
  483. ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
  484. c->slice_buffer[i], c->slice_stride,
  485. width, height, &pb);
  486. if (ret) {
  487. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  488. return ret;
  489. }
  490. }
  491. break;
  492. case AV_PIX_FMT_YUV422P:
  493. for (i = 0; i < c->planes; i++) {
  494. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  495. pic->linesize[i], width >> !!i, height, &pb);
  496. if (ret) {
  497. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  498. return ret;
  499. }
  500. }
  501. break;
  502. case AV_PIX_FMT_YUV420P:
  503. for (i = 0; i < c->planes; i++) {
  504. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  505. pic->linesize[i], width >> !!i, height >> !!i,
  506. &pb);
  507. if (ret) {
  508. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  509. return ret;
  510. }
  511. }
  512. break;
  513. default:
  514. av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
  515. avctx->pix_fmt);
  516. return AVERROR_INVALIDDATA;
  517. }
  518. /*
  519. * Write frame information (LE 32-bit unsigned)
  520. * into the output packet.
  521. * Contains the prediction method.
  522. */
  523. frame_info = c->frame_pred << 8;
  524. bytestream2_put_le32(&pb, frame_info);
  525. /*
  526. * At least currently Ut Video is IDR only.
  527. * Set flags accordingly.
  528. */
  529. #if FF_API_CODED_FRAME
  530. FF_DISABLE_DEPRECATION_WARNINGS
  531. avctx->coded_frame->key_frame = 1;
  532. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  533. FF_ENABLE_DEPRECATION_WARNINGS
  534. #endif
  535. pkt->size = bytestream2_tell_p(&pb);
  536. pkt->flags |= AV_PKT_FLAG_KEY;
  537. /* Packet should be done */
  538. *got_packet = 1;
  539. return 0;
  540. }
  541. #define OFFSET(x) offsetof(UtvideoContext, x)
  542. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  543. static const AVOption options[] = {
  544. { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
  545. { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
  546. { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
  547. { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
  548. { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
  549. { NULL},
  550. };
  551. static const AVClass utvideo_class = {
  552. .class_name = "utvideo",
  553. .item_name = av_default_item_name,
  554. .option = options,
  555. .version = LIBAVUTIL_VERSION_INT,
  556. };
  557. AVCodec ff_utvideo_encoder = {
  558. .name = "utvideo",
  559. .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
  560. .type = AVMEDIA_TYPE_VIDEO,
  561. .id = AV_CODEC_ID_UTVIDEO,
  562. .priv_data_size = sizeof(UtvideoContext),
  563. .priv_class = &utvideo_class,
  564. .init = utvideo_encode_init,
  565. .encode2 = utvideo_encode_frame,
  566. .close = utvideo_encode_close,
  567. .pix_fmts = (const enum AVPixelFormat[]) {
  568. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
  569. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  570. },
  571. };