3 * Copyright (c) 2012 Jan Ekström
5 * This file is part of FFmpeg.
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.
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.
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
27 #include "libavutil/imgutils.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/opt.h"
34 #include "bytestream.h"
40 typedef struct HuffEntry {
46 /* Compare huffman tree nodes */
47 static int ut_huff_cmp_len(const void *a, const void *b)
49 const HuffEntry *aa = a, *bb = b;
50 return (aa->len - bb->len)*256 + aa->sym - bb->sym;
53 /* Compare huffentry symbols */
54 static int huff_cmp_sym(const void *a, const void *b)
56 const HuffEntry *aa = a, *bb = b;
57 return aa->sym - bb->sym;
60 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
62 UtvideoContext *c = avctx->priv_data;
65 av_freep(&c->slice_bits);
66 for (i = 0; i < 4; i++)
67 av_freep(&c->slice_buffer[i]);
72 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
74 UtvideoContext *c = avctx->priv_data;
75 int i, subsampled_height;
76 uint32_t original_format;
79 c->frame_info_size = 4;
80 c->slice_stride = FFALIGN(avctx->width, 32);
82 switch (avctx->pix_fmt) {
85 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
86 original_format = UTVIDEO_RGB;
88 case AV_PIX_FMT_GBRAP:
90 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
91 original_format = UTVIDEO_RGBA;
92 avctx->bits_per_coded_sample = 32;
94 case AV_PIX_FMT_YUV420P:
95 if (avctx->width & 1 || avctx->height & 1) {
96 av_log(avctx, AV_LOG_ERROR,
97 "4:2:0 video requires even width and height.\n");
98 return AVERROR_INVALIDDATA;
101 if (avctx->colorspace == AVCOL_SPC_BT709)
102 avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
104 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
105 original_format = UTVIDEO_420;
107 case AV_PIX_FMT_YUV422P:
108 if (avctx->width & 1) {
109 av_log(avctx, AV_LOG_ERROR,
110 "4:2:2 video requires even width.\n");
111 return AVERROR_INVALIDDATA;
114 if (avctx->colorspace == AVCOL_SPC_BT709)
115 avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
117 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
118 original_format = UTVIDEO_422;
120 case AV_PIX_FMT_YUV444P:
122 if (avctx->colorspace == AVCOL_SPC_BT709)
123 avctx->codec_tag = MKTAG('U', 'L', 'H', '4');
125 avctx->codec_tag = MKTAG('U', 'L', 'Y', '4');
126 original_format = UTVIDEO_444;
129 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
131 return AVERROR_INVALIDDATA;
134 ff_bswapdsp_init(&c->bdsp);
135 ff_llvidencdsp_init(&c->llvidencdsp);
137 if (c->frame_pred == PRED_GRADIENT) {
138 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
139 return AVERROR_OPTION_NOT_FOUND;
143 * Check the asked slice count for obviously invalid
144 * values (> 256 or negative).
146 if (avctx->slices > 256 || avctx->slices < 0) {
147 av_log(avctx, AV_LOG_ERROR,
148 "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
150 return AVERROR(EINVAL);
153 /* Check that the slice count is not larger than the subsampled height */
154 subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
155 if (avctx->slices > subsampled_height) {
156 av_log(avctx, AV_LOG_ERROR,
157 "Slice count %d is larger than the subsampling-applied height %d.\n",
158 avctx->slices, subsampled_height);
159 return AVERROR(EINVAL);
162 /* extradata size is 4 * 32 bits */
163 avctx->extradata_size = 16;
165 avctx->extradata = av_mallocz(avctx->extradata_size +
166 AV_INPUT_BUFFER_PADDING_SIZE);
168 if (!avctx->extradata) {
169 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
170 utvideo_encode_close(avctx);
171 return AVERROR(ENOMEM);
174 for (i = 0; i < c->planes; i++) {
175 c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
176 AV_INPUT_BUFFER_PADDING_SIZE);
177 if (!c->slice_buffer[i]) {
178 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
179 utvideo_encode_close(avctx);
180 return AVERROR(ENOMEM);
185 * Set the version of the encoder.
186 * Last byte is "implementation ID", which is
187 * obtained from the creator of the format.
188 * Libavcodec has been assigned with the ID 0xF0.
190 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
193 * Set the "original format"
194 * Not used for anything during decoding.
196 AV_WL32(avctx->extradata + 4, original_format);
198 /* Write 4 as the 'frame info size' */
199 AV_WL32(avctx->extradata + 8, c->frame_info_size);
202 * Set how many slices are going to be used.
203 * By default uses multiple slices depending on the subsampled height.
204 * This enables multithreading in the official decoder.
206 if (!avctx->slices) {
207 c->slices = subsampled_height / 120;
211 else if (c->slices > 256)
214 c->slices = avctx->slices;
217 /* Set compression mode */
218 c->compression = COMP_HUFF;
221 * Set the encoding flags:
222 * - Slice count minus 1
223 * - Interlaced encoding mode flag, set to zero for now.
224 * - Compression mode (none/huff)
225 * And write the flags.
227 c->flags = (c->slices - 1) << 24;
228 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
229 c->flags |= c->compression;
231 AV_WL32(avctx->extradata + 12, c->flags);
236 static void mangle_rgb_planes(uint8_t *dst[4], ptrdiff_t dst_stride,
237 uint8_t *const src[4], int planes, const int stride[4],
238 int width, int height)
241 int k = 2 * dst_stride;
242 const uint8_t *sg = src[0];
243 const uint8_t *sb = src[1];
244 const uint8_t *sr = src[2];
245 const uint8_t *sa = src[3];
248 for (j = 0; j < height; j++) {
250 for (i = 0; i < width; i++) {
254 dst[1][k] = sb[i] - g;
255 dst[2][k] = sr[i] - g;
259 for (i = 0; i < width; i++) {
263 dst[1][k] = sb[i] - g;
264 dst[2][k] = sr[i] - g;
270 k += dst_stride - width;
280 /* Write data to a plane with median prediction */
281 static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst,
282 ptrdiff_t stride, int width, int height)
288 /* First line uses left neighbour prediction */
289 prev = 0x80; /* Set the initial value */
290 for (i = 0; i < width; i++) {
291 *dst++ = src[i] - prev;
301 * Second line uses top prediction for the first sample,
302 * and median for the rest.
306 /* Rest of the coded part uses median prediction */
307 for (j = 1; j < height; j++) {
308 c->llvidencdsp.sub_median_pred(dst, src - stride, src, width, &A, &B);
314 /* Count the usage of values in a plane */
315 static void count_usage(uint8_t *src, int width,
316 int height, uint64_t *counts)
320 for (j = 0; j < height; j++) {
321 for (i = 0; i < width; i++) {
328 /* Calculate the actual huffman codes from the code lengths */
329 static void calculate_codes(HuffEntry *he)
334 qsort(he, 256, sizeof(*he), ut_huff_cmp_len);
337 while (he[last].len == 255 && last)
341 for (i = last; i >= 0; i--) {
342 he[i].code = code >> (32 - he[i].len);
343 code += 0x80000000u >> (he[i].len - 1);
346 qsort(he, 256, sizeof(*he), huff_cmp_sym);
349 /* Write huffman bit codes to a memory block */
350 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
351 int width, int height, HuffEntry *he)
357 init_put_bits(&pb, dst, dst_size);
359 /* Write the codes */
360 for (j = 0; j < height; j++) {
361 for (i = 0; i < width; i++)
362 put_bits(&pb, he[src[i]].len, he[src[i]].code);
367 /* Pad output to a 32-bit boundary */
368 count = put_bits_count(&pb) & 0x1F;
371 put_bits(&pb, 32 - count, 0);
373 /* Flush the rest with zeroes */
376 /* Return the amount of bytes written */
377 return put_bytes_output(&pb);
380 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
381 uint8_t *dst, ptrdiff_t stride, int plane_no,
382 int width, int height, PutByteContext *pb)
384 UtvideoContext *c = avctx->priv_data;
385 uint8_t lengths[256];
386 uint64_t counts[256] = { 0 };
390 uint32_t offset = 0, slice_len = 0;
391 const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
392 int i, sstart, send = 0;
396 /* Do prediction / make planes */
397 switch (c->frame_pred) {
399 for (i = 0; i < c->slices; i++) {
401 send = height * (i + 1) / c->slices & cmask;
402 av_image_copy_plane(dst + sstart * width, width,
403 src + sstart * stride, stride,
404 width, send - sstart);
408 for (i = 0; i < c->slices; i++) {
410 send = height * (i + 1) / c->slices & cmask;
411 c->llvidencdsp.sub_left_predict(dst + sstart * width, src + sstart * stride, stride, width, send - sstart);
415 for (i = 0; i < c->slices; i++) {
417 send = height * (i + 1) / c->slices & cmask;
418 median_predict(c, src + sstart * stride, dst + sstart * width,
419 stride, width, send - sstart);
423 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
425 return AVERROR_OPTION_NOT_FOUND;
428 /* Count the usage of values */
429 count_usage(dst, width, height, counts);
431 /* Check for a special case where only one symbol was used */
432 for (symbol = 0; symbol < 256; symbol++) {
433 /* If non-zero count is found, see if it matches width * height */
434 if (counts[symbol]) {
435 /* Special case if only one symbol was used */
436 if (counts[symbol] == width * (int64_t)height) {
438 * Write a zero for the single symbol
439 * used in the plane, else 0xFF.
441 for (i = 0; i < 256; i++) {
443 bytestream2_put_byte(pb, 0);
445 bytestream2_put_byte(pb, 0xFF);
448 /* Write zeroes for lengths */
449 for (i = 0; i < c->slices; i++)
450 bytestream2_put_le32(pb, 0);
452 /* And that's all for that plane folks */
459 /* Calculate huffman lengths */
460 if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
464 * Write the plane's header into the output packet:
465 * - huffman code lengths (256 bytes)
466 * - slice end offsets (gotten from the slice lengths)
468 for (i = 0; i < 256; i++) {
469 bytestream2_put_byte(pb, lengths[i]);
471 he[i].len = lengths[i];
475 /* Calculate the huffman codes themselves */
479 for (i = 0; i < c->slices; i++) {
481 send = height * (i + 1) / c->slices & cmask;
484 * Write the huffman codes to a buffer,
485 * get the offset in bytes.
487 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
488 width * height + 4, width,
491 slice_len = offset - slice_len;
493 /* Byteswap the written huffman codes */
494 c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
495 (uint32_t *) c->slice_bits,
498 /* Write the offset to the stream */
499 bytestream2_put_le32(pb, offset);
501 /* Seek to the data part of the packet */
502 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
503 offset - slice_len, SEEK_CUR);
505 /* Write the slices' data into the output packet */
506 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
508 /* Seek back to the slice offsets */
509 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
515 /* And at the end seek to the end of written slice(s) */
516 bytestream2_seek_p(pb, offset, SEEK_CUR);
521 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
522 const AVFrame *pic, int *got_packet)
524 UtvideoContext *c = avctx->priv_data;
531 int width = avctx->width, height = avctx->height;
534 /* Allocate a new packet if needed, and set it to the pointer dst */
535 ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
543 bytestream2_init_writer(&pb, dst, pkt->size);
545 av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
547 if (!c->slice_bits) {
548 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
549 return AVERROR(ENOMEM);
552 /* In case of RGB, mangle the planes to Ut Video's format */
553 if (avctx->pix_fmt == AV_PIX_FMT_GBRAP || avctx->pix_fmt == AV_PIX_FMT_GBRP)
554 mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data,
555 c->planes, pic->linesize, width, height);
557 /* Deal with the planes */
558 switch (avctx->pix_fmt) {
559 case AV_PIX_FMT_GBRP:
560 case AV_PIX_FMT_GBRAP:
561 for (i = 0; i < c->planes; i++) {
562 ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
563 c->slice_buffer[i], c->slice_stride, i,
567 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
572 case AV_PIX_FMT_YUV444P:
573 for (i = 0; i < c->planes; i++) {
574 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
575 pic->linesize[i], i, width, height, &pb);
578 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
583 case AV_PIX_FMT_YUV422P:
584 for (i = 0; i < c->planes; i++) {
585 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
586 pic->linesize[i], i, width >> !!i, height, &pb);
589 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
594 case AV_PIX_FMT_YUV420P:
595 for (i = 0; i < c->planes; i++) {
596 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
597 pic->linesize[i], i, width >> !!i, height >> !!i,
601 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
607 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
609 return AVERROR_INVALIDDATA;
613 * Write frame information (LE 32-bit unsigned)
614 * into the output packet.
615 * Contains the prediction method.
617 frame_info = c->frame_pred << 8;
618 bytestream2_put_le32(&pb, frame_info);
621 * At least currently Ut Video is IDR only.
622 * Set flags accordingly.
624 pkt->flags |= AV_PKT_FLAG_KEY;
625 pkt->size = bytestream2_tell_p(&pb);
627 /* Packet should be done */
633 #define OFFSET(x) offsetof(UtvideoContext, x)
634 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
635 static const AVOption options[] = {
636 { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
637 { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
638 { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
639 { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
640 { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
645 static const AVClass utvideo_class = {
646 .class_name = "utvideo",
647 .item_name = av_default_item_name,
649 .version = LIBAVUTIL_VERSION_INT,
652 AVCodec ff_utvideo_encoder = {
654 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
655 .type = AVMEDIA_TYPE_VIDEO,
656 .id = AV_CODEC_ID_UTVIDEO,
657 .priv_data_size = sizeof(UtvideoContext),
658 .priv_class = &utvideo_class,
659 .init = utvideo_encode_init,
660 .encode2 = utvideo_encode_frame,
661 .close = utvideo_encode_close,
662 .capabilities = AV_CODEC_CAP_FRAME_THREADS,
663 .pix_fmts = (const enum AVPixelFormat[]) {
664 AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP, AV_PIX_FMT_YUV422P,
665 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE