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.

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