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.

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