utvideoenc.c 18 KB

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