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.

612 lines
18KB

  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 "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 = av_frame_alloc();
  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. int ret;
  310. /* Do prediction / make planes */
  311. switch (c->frame_pred) {
  312. case PRED_NONE:
  313. for (i = 0; i < c->slices; i++) {
  314. sstart = send;
  315. send = height * (i + 1) / c->slices;
  316. av_image_copy_plane(dst + sstart * width, width,
  317. src + sstart * stride, stride,
  318. 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. 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(c, src + sstart * stride, dst + sstart * width,
  334. 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 * (int64_t)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. if ((ret = ff_huff_gen_len_table(lengths, counts, 256)) < 0)
  371. return ret;
  372. /*
  373. * Write the plane's header into the output packet:
  374. * - huffman code lengths (256 bytes)
  375. * - slice end offsets (gotten from the slice lengths)
  376. */
  377. for (i = 0; i < 256; i++) {
  378. bytestream2_put_byte(pb, lengths[i]);
  379. he[i].len = lengths[i];
  380. he[i].sym = i;
  381. }
  382. /* Calculate the huffman codes themselves */
  383. calculate_codes(he);
  384. send = 0;
  385. for (i = 0; i < c->slices; i++) {
  386. sstart = send;
  387. send = height * (i + 1) / c->slices;
  388. /*
  389. * Write the huffman codes to a buffer,
  390. * get the offset in bits and convert to bytes.
  391. */
  392. offset += write_huff_codes(dst + sstart * width, c->slice_bits,
  393. width * (send - sstart), width,
  394. send - sstart, he) >> 3;
  395. slice_len = offset - slice_len;
  396. /* Byteswap the written huffman codes */
  397. c->dsp.bswap_buf((uint32_t *) c->slice_bits,
  398. (uint32_t *) c->slice_bits,
  399. slice_len >> 2);
  400. /* Write the offset to the stream */
  401. bytestream2_put_le32(pb, offset);
  402. /* Seek to the data part of the packet */
  403. bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
  404. offset - slice_len, SEEK_CUR);
  405. /* Write the slices' data into the output packet */
  406. bytestream2_put_buffer(pb, c->slice_bits, slice_len);
  407. /* Seek back to the slice offsets */
  408. bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
  409. SEEK_CUR);
  410. slice_len = offset;
  411. }
  412. /* And at the end seek to the end of written slice(s) */
  413. bytestream2_seek_p(pb, offset, SEEK_CUR);
  414. return 0;
  415. }
  416. static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  417. const AVFrame *pic, int *got_packet)
  418. {
  419. UtvideoContext *c = avctx->priv_data;
  420. PutByteContext pb;
  421. uint32_t frame_info;
  422. uint8_t *dst;
  423. int width = avctx->width, height = avctx->height;
  424. int i, ret = 0;
  425. /* Allocate a new packet if needed, and set it to the pointer dst */
  426. ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
  427. c->planes + 4);
  428. if (ret < 0)
  429. return ret;
  430. dst = pkt->data;
  431. bytestream2_init_writer(&pb, dst, pkt->size);
  432. av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height);
  433. if (!c->slice_bits) {
  434. av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
  435. return AVERROR(ENOMEM);
  436. }
  437. /* In case of RGB, mangle the planes to Ut Video's format */
  438. if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
  439. mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
  440. c->planes, pic->linesize[0], width, height);
  441. /* Deal with the planes */
  442. switch (avctx->pix_fmt) {
  443. case AV_PIX_FMT_RGB24:
  444. case AV_PIX_FMT_RGBA:
  445. for (i = 0; i < c->planes; i++) {
  446. ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
  447. c->slice_buffer[i], c->slice_stride,
  448. width, height, &pb);
  449. if (ret) {
  450. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  451. return ret;
  452. }
  453. }
  454. break;
  455. case AV_PIX_FMT_YUV422P:
  456. for (i = 0; i < c->planes; i++) {
  457. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  458. pic->linesize[i], width >> !!i, height, &pb);
  459. if (ret) {
  460. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  461. return ret;
  462. }
  463. }
  464. break;
  465. case AV_PIX_FMT_YUV420P:
  466. for (i = 0; i < c->planes; i++) {
  467. ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
  468. pic->linesize[i], width >> !!i, height >> !!i,
  469. &pb);
  470. if (ret) {
  471. av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
  472. return ret;
  473. }
  474. }
  475. break;
  476. default:
  477. av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
  478. avctx->pix_fmt);
  479. return AVERROR_INVALIDDATA;
  480. }
  481. /*
  482. * Write frame information (LE 32bit unsigned)
  483. * into the output packet.
  484. * Contains the prediction method.
  485. */
  486. frame_info = c->frame_pred << 8;
  487. bytestream2_put_le32(&pb, frame_info);
  488. /*
  489. * At least currently Ut Video is IDR only.
  490. * Set flags accordingly.
  491. */
  492. avctx->coded_frame->key_frame = 1;
  493. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  494. pkt->size = bytestream2_tell_p(&pb);
  495. pkt->flags |= AV_PKT_FLAG_KEY;
  496. /* Packet should be done */
  497. *got_packet = 1;
  498. return 0;
  499. }
  500. AVCodec ff_utvideo_encoder = {
  501. .name = "utvideo",
  502. .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
  503. .type = AVMEDIA_TYPE_VIDEO,
  504. .id = AV_CODEC_ID_UTVIDEO,
  505. .priv_data_size = sizeof(UtvideoContext),
  506. .init = utvideo_encode_init,
  507. .encode2 = utvideo_encode_frame,
  508. .close = utvideo_encode_close,
  509. .pix_fmts = (const enum AVPixelFormat[]) {
  510. AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
  511. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE
  512. },
  513. };