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.

653 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(&avctx->coded_frame);
  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. /* Check the prediction method, and error out if unsupported */
  105. if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
  106. av_log(avctx, AV_LOG_WARNING,
  107. "Prediction method %d is not supported in Ut Video.\n",
  108. avctx->prediction_method);
  109. return AVERROR_OPTION_NOT_FOUND;
  110. }
  111. if (avctx->prediction_method == FF_PRED_PLANE) {
  112. av_log(avctx, AV_LOG_ERROR,
  113. "Plane prediction is not supported in Ut Video.\n");
  114. return AVERROR_OPTION_NOT_FOUND;
  115. }
  116. /* Convert from libavcodec prediction type to Ut Video's */
  117. c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
  118. if (c->frame_pred == PRED_GRADIENT) {
  119. av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
  120. return AVERROR_OPTION_NOT_FOUND;
  121. }
  122. /*
  123. * Check the asked slice count for obviously invalid
  124. * values (> 256 or negative).
  125. */
  126. if (avctx->slices > 256 || avctx->slices < 0) {
  127. av_log(avctx, AV_LOG_ERROR,
  128. "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
  129. avctx->slices);
  130. return AVERROR(EINVAL);
  131. }
  132. /* Check that the slice count is not larger than the subsampled height */
  133. subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
  134. if (avctx->slices > subsampled_height) {
  135. av_log(avctx, AV_LOG_ERROR,
  136. "Slice count %d is larger than the subsampling-applied height %d.\n",
  137. avctx->slices, subsampled_height);
  138. return AVERROR(EINVAL);
  139. }
  140. avctx->coded_frame = av_frame_alloc();
  141. if (!avctx->coded_frame) {
  142. av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
  143. utvideo_encode_close(avctx);
  144. return AVERROR(ENOMEM);
  145. }
  146. /* extradata size is 4 * 32bit */
  147. avctx->extradata_size = 16;
  148. avctx->extradata = av_mallocz(avctx->extradata_size +
  149. FF_INPUT_BUFFER_PADDING_SIZE);
  150. if (!avctx->extradata) {
  151. av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
  152. utvideo_encode_close(avctx);
  153. return AVERROR(ENOMEM);
  154. }
  155. for (i = 0; i < c->planes; i++) {
  156. c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
  157. FF_INPUT_BUFFER_PADDING_SIZE);
  158. if (!c->slice_buffer[i]) {
  159. av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
  160. utvideo_encode_close(avctx);
  161. return AVERROR(ENOMEM);
  162. }
  163. }
  164. /*
  165. * Set the version of the encoder.
  166. * Last byte is "implementation ID", which is
  167. * obtained from the creator of the format.
  168. * Libavcodec has been assigned with the ID 0xF0.
  169. */
  170. AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
  171. /*
  172. * Set the "original format"
  173. * Not used for anything during decoding.
  174. */
  175. AV_WL32(avctx->extradata + 4, original_format);
  176. /* Write 4 as the 'frame info size' */
  177. AV_WL32(avctx->extradata + 8, c->frame_info_size);
  178. /*
  179. * Set how many slices are going to be used.
  180. * By default uses multiple slices depending on the subsampled height.
  181. * This enables multithreading in the official decoder.
  182. */
  183. if (!avctx->slices) {
  184. c->slices = subsampled_height / 120;
  185. if (!c->slices)
  186. c->slices = 1;
  187. else if (c->slices > 256)
  188. c->slices = 256;
  189. } else {
  190. c->slices = avctx->slices;
  191. }
  192. /* Set compression mode */
  193. c->compression = COMP_HUFF;
  194. /*
  195. * Set the encoding flags:
  196. * - Slice count minus 1
  197. * - Interlaced encoding mode flag, set to zero for now.
  198. * - Compression mode (none/huff)
  199. * And write the flags.
  200. */
  201. c->flags = (c->slices - 1) << 24;
  202. c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
  203. c->flags |= c->compression;
  204. AV_WL32(avctx->extradata + 12, c->flags);
  205. return 0;
  206. }
  207. static void mangle_rgb_planes(uint8_t *dst[4], int dst_stride, uint8_t *src,
  208. int step, int stride, 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, int 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, int stride,
  255. 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 32bit 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, int 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 + FF_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 32bit 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. avctx->coded_frame->key_frame = 1;
  531. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  532. pkt->size = bytestream2_tell_p(&pb);
  533. pkt->flags |= AV_PKT_FLAG_KEY;
  534. /* Packet should be done */
  535. *got_packet = 1;
  536. return 0;
  537. }
  538. AVCodec ff_utvideo_encoder = {
  539. .name = "utvideo",
  540. .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
  541. .type = AVMEDIA_TYPE_VIDEO,
  542. .id = AV_CODEC_ID_UTVIDEO,
  543. .priv_data_size = sizeof(UtvideoContext),
  544. .init = utvideo_encode_init,
  545. .encode2 = utvideo_encode_frame,
  546. .close = utvideo_encode_close,
  547. .pix_fmts = (const enum AVPixelFormat[]) {
  548. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
  549. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  550. },
  551. };