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.

647 lines
19KB

  1. /*
  2. * Ut Video encoder
  3. * Copyright (c) 2012 Jan Ekström
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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. FF_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. FF_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, int plane_no,
  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. const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
  336. int i, sstart, send = 0;
  337. int symbol;
  338. int ret;
  339. /* Do prediction / make planes */
  340. switch (c->frame_pred) {
  341. case PRED_NONE:
  342. for (i = 0; i < c->slices; i++) {
  343. sstart = send;
  344. send = height * (i + 1) / c->slices & cmask;
  345. av_image_copy_plane(dst + sstart * width, width,
  346. src + sstart * stride, stride,
  347. width, send - sstart);
  348. }
  349. break;
  350. case PRED_LEFT:
  351. for (i = 0; i < c->slices; i++) {
  352. sstart = send;
  353. send = height * (i + 1) / c->slices & cmask;
  354. left_predict(src + sstart * stride, dst + sstart * width,
  355. stride, width, send - sstart);
  356. }
  357. break;
  358. case PRED_MEDIAN:
  359. for (i = 0; i < c->slices; i++) {
  360. sstart = send;
  361. send = height * (i + 1) / c->slices & cmask;
  362. median_predict(c, src + sstart * stride, dst + sstart * width,
  363. stride, width, send - sstart);
  364. }
  365. break;
  366. default:
  367. av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
  368. c->frame_pred);
  369. return AVERROR_OPTION_NOT_FOUND;
  370. }
  371. /* Count the usage of values */
  372. count_usage(dst, width, height, counts);
  373. /* Check for a special case where only one symbol was used */
  374. for (symbol = 0; symbol < 256; symbol++) {
  375. /* If non-zero count is found, see if it matches width * height */
  376. if (counts[symbol]) {
  377. /* Special case if only one symbol was used */
  378. if (counts[symbol] == width * (int64_t)height) {
  379. /*
  380. * Write a zero for the single symbol
  381. * used in the plane, else 0xFF.
  382. */
  383. for (i = 0; i < 256; i++) {
  384. if (i == symbol)
  385. bytestream2_put_byte(pb, 0);
  386. else
  387. bytestream2_put_byte(pb, 0xFF);
  388. }
  389. /* Write zeroes for lengths */
  390. for (i = 0; i < c->slices; i++)
  391. bytestream2_put_le32(pb, 0);
  392. /* And that's all for that plane folks */
  393. return 0;
  394. }
  395. break;
  396. }
  397. }
  398. /* Calculate huffman lengths */
  399. if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
  400. return ret;
  401. /*
  402. * Write the plane's header into the output packet:
  403. * - huffman code lengths (256 bytes)
  404. * - slice end offsets (gotten from the slice lengths)
  405. */
  406. for (i = 0; i < 256; i++) {
  407. bytestream2_put_byte(pb, lengths[i]);
  408. he[i].len = lengths[i];
  409. he[i].sym = i;
  410. }
  411. /* Calculate the huffman codes themselves */
  412. calculate_codes(he);
  413. send = 0;
  414. for (i = 0; i < c->slices; i++) {
  415. sstart = send;
  416. send = height * (i + 1) / c->slices & cmask;
  417. /*
  418. * Write the huffman codes to a buffer,
  419. * get the offset in bits and convert to bytes.
  420. */
  421. offset += write_huff_codes(dst + sstart * width, c->slice_bits,
  422. width * height + 4, width,
  423. send - sstart, he) >> 3;
  424. slice_len = offset - slice_len;
  425. /* Byteswap the written huffman codes */
  426. c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
  427. (uint32_t *) c->slice_bits,
  428. slice_len >> 2);
  429. /* Write the offset to the stream */
  430. bytestream2_put_le32(pb, offset);
  431. /* Seek to the data part of the packet */
  432. bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
  433. offset - slice_len, SEEK_CUR);
  434. /* Write the slices' data into the output packet */
  435. bytestream2_put_buffer(pb, c->slice_bits, slice_len);
  436. /* Seek back to the slice offsets */
  437. bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
  438. SEEK_CUR);
  439. slice_len = offset;
  440. }
  441. /* And at the end seek to the end of written slice(s) */
  442. bytestream2_seek_p(pb, offset, SEEK_CUR);
  443. return 0;
  444. }
  445. static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  446. const AVFrame *pic, int *got_packet)
  447. {
  448. UtvideoContext *c = avctx->priv_data;
  449. PutByteContext pb;
  450. uint32_t frame_info;
  451. uint8_t *dst;
  452. int width = avctx->width, height = avctx->height;
  453. int i, ret = 0;
  454. /* Allocate a new packet if needed, and set it to the pointer dst */
  455. ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
  456. c->planes + 4, 0);
  457. if (ret < 0)
  458. return ret;
  459. dst = pkt->data;
  460. bytestream2_init_writer(&pb, dst, pkt->size);
  461. av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
  462. if (!c->slice_bits) {
  463. av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
  464. return AVERROR(ENOMEM);
  465. }
  466. /* In case of RGB, mangle the planes to Ut Video's format */
  467. if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
  468. mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
  469. c->planes, pic->linesize[0], width, height);
  470. /* Deal with the planes */
  471. switch (avctx->pix_fmt) {
  472. case AV_PIX_FMT_RGB24:
  473. case AV_PIX_FMT_RGBA:
  474. for (i = 0; i < c->planes; i++) {
  475. ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
  476. c->slice_buffer[i], c->slice_stride, i,
  477. width, height, &pb);
  478. if (ret) {
  479. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  480. return ret;
  481. }
  482. }
  483. break;
  484. case AV_PIX_FMT_YUV422P:
  485. for (i = 0; i < c->planes; i++) {
  486. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  487. pic->linesize[i], i, width >> !!i, height, &pb);
  488. if (ret) {
  489. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  490. return ret;
  491. }
  492. }
  493. break;
  494. case AV_PIX_FMT_YUV420P:
  495. for (i = 0; i < c->planes; i++) {
  496. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  497. pic->linesize[i], i, width >> !!i, height >> !!i,
  498. &pb);
  499. if (ret) {
  500. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  501. return ret;
  502. }
  503. }
  504. break;
  505. default:
  506. av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
  507. avctx->pix_fmt);
  508. return AVERROR_INVALIDDATA;
  509. }
  510. /*
  511. * Write frame information (LE 32bit unsigned)
  512. * into the output packet.
  513. * Contains the prediction method.
  514. */
  515. frame_info = c->frame_pred << 8;
  516. bytestream2_put_le32(&pb, frame_info);
  517. /*
  518. * At least currently Ut Video is IDR only.
  519. * Set flags accordingly.
  520. */
  521. #if FF_API_CODED_FRAME
  522. FF_DISABLE_DEPRECATION_WARNINGS
  523. avctx->coded_frame->key_frame = 1;
  524. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  525. FF_ENABLE_DEPRECATION_WARNINGS
  526. #endif
  527. pkt->size = bytestream2_tell_p(&pb);
  528. pkt->flags |= AV_PKT_FLAG_KEY;
  529. /* Packet should be done */
  530. *got_packet = 1;
  531. return 0;
  532. }
  533. AVCodec ff_utvideo_encoder = {
  534. .name = "utvideo",
  535. .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
  536. .type = AVMEDIA_TYPE_VIDEO,
  537. .id = AV_CODEC_ID_UTVIDEO,
  538. .priv_data_size = sizeof(UtvideoContext),
  539. .init = utvideo_encode_init,
  540. .encode2 = utvideo_encode_frame,
  541. .close = utvideo_encode_close,
  542. .capabilities = CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
  543. .pix_fmts = (const enum AVPixelFormat[]) {
  544. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
  545. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  546. },
  547. };