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.

648 lines
19KB

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