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.

736 lines
20KB

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