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.

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