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.

621 lines
18KB

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