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 /* Compare huffentry symbols */
41 static int huff_cmp_sym(const void *a, const void *b)
43 const HuffEntry *aa = a, *bb = b;
44 return aa->sym - bb->sym;
47 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
49 UtvideoContext *c = avctx->priv_data;
52 av_freep(&c->slice_bits);
53 for (i = 0; i < 4; i++)
54 av_freep(&c->slice_buffer[i]);
59 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
61 UtvideoContext *c = avctx->priv_data;
62 int i, subsampled_height;
63 uint32_t original_format;
66 c->frame_info_size = 4;
67 c->slice_stride = FFALIGN(avctx->width, 32);
69 switch (avctx->pix_fmt) {
70 case AV_PIX_FMT_RGB24:
72 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
73 original_format = UTVIDEO_RGB;
77 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
78 original_format = UTVIDEO_RGBA;
79 avctx->bits_per_coded_sample = 32;
81 case AV_PIX_FMT_YUV420P:
82 if (avctx->width & 1 || avctx->height & 1) {
83 av_log(avctx, AV_LOG_ERROR,
84 "4:2:0 video requires even width and height.\n");
85 return AVERROR_INVALIDDATA;
88 if (avctx->colorspace == AVCOL_SPC_BT709)
89 avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
91 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
92 original_format = UTVIDEO_420;
94 case AV_PIX_FMT_YUV422P:
95 if (avctx->width & 1) {
96 av_log(avctx, AV_LOG_ERROR,
97 "4:2:2 video requires even width.\n");
98 return AVERROR_INVALIDDATA;
101 if (avctx->colorspace == AVCOL_SPC_BT709)
102 avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
104 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
105 original_format = UTVIDEO_422;
107 case AV_PIX_FMT_YUV444P:
109 if (avctx->colorspace == AVCOL_SPC_BT709)
110 avctx->codec_tag = MKTAG('U', 'L', 'H', '4');
112 avctx->codec_tag = MKTAG('U', 'L', 'Y', '4');
113 original_format = UTVIDEO_444;
116 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
118 return AVERROR_INVALIDDATA;
121 ff_bswapdsp_init(&c->bdsp);
122 ff_llvidencdsp_init(&c->llvidencdsp);
124 #if FF_API_PRIVATE_OPT
125 FF_DISABLE_DEPRECATION_WARNINGS
126 /* Check the prediction method, and error out if unsupported */
127 if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
128 av_log(avctx, AV_LOG_WARNING,
129 "Prediction method %d is not supported in Ut Video.\n",
130 avctx->prediction_method);
131 return AVERROR_OPTION_NOT_FOUND;
134 if (avctx->prediction_method == FF_PRED_PLANE) {
135 av_log(avctx, AV_LOG_ERROR,
136 "Plane prediction is not supported in Ut Video.\n");
137 return AVERROR_OPTION_NOT_FOUND;
140 /* Convert from libavcodec prediction type to Ut Video's */
141 if (avctx->prediction_method)
142 c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
143 FF_ENABLE_DEPRECATION_WARNINGS
146 if (c->frame_pred == PRED_GRADIENT) {
147 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
148 return AVERROR_OPTION_NOT_FOUND;
152 * Check the asked slice count for obviously invalid
153 * values (> 256 or negative).
155 if (avctx->slices > 256 || avctx->slices < 0) {
156 av_log(avctx, AV_LOG_ERROR,
157 "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
159 return AVERROR(EINVAL);
162 /* Check that the slice count is not larger than the subsampled height */
163 subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
164 if (avctx->slices > subsampled_height) {
165 av_log(avctx, AV_LOG_ERROR,
166 "Slice count %d is larger than the subsampling-applied height %d.\n",
167 avctx->slices, subsampled_height);
168 return AVERROR(EINVAL);
171 /* extradata size is 4 * 32 bits */
172 avctx->extradata_size = 16;
174 avctx->extradata = av_mallocz(avctx->extradata_size +
175 AV_INPUT_BUFFER_PADDING_SIZE);
177 if (!avctx->extradata) {
178 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
179 utvideo_encode_close(avctx);
180 return AVERROR(ENOMEM);
183 for (i = 0; i < c->planes; i++) {
184 c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
185 AV_INPUT_BUFFER_PADDING_SIZE);
186 if (!c->slice_buffer[i]) {
187 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
188 utvideo_encode_close(avctx);
189 return AVERROR(ENOMEM);
194 * Set the version of the encoder.
195 * Last byte is "implementation ID", which is
196 * obtained from the creator of the format.
197 * Libavcodec has been assigned with the ID 0xF0.
199 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
202 * Set the "original format"
203 * Not used for anything during decoding.
205 AV_WL32(avctx->extradata + 4, original_format);
207 /* Write 4 as the 'frame info size' */
208 AV_WL32(avctx->extradata + 8, c->frame_info_size);
211 * Set how many slices are going to be used.
212 * By default uses multiple slices depending on the subsampled height.
213 * This enables multithreading in the official decoder.
215 if (!avctx->slices) {
216 c->slices = subsampled_height / 120;
220 else if (c->slices > 256)
223 c->slices = avctx->slices;
226 /* Set compression mode */
227 c->compression = COMP_HUFF;
230 * Set the encoding flags:
231 * - Slice count minus 1
232 * - Interlaced encoding mode flag, set to zero for now.
233 * - Compression mode (none/huff)
234 * And write the flags.
236 c->flags = (c->slices - 1) << 24;
237 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
238 c->flags |= c->compression;
240 AV_WL32(avctx->extradata + 12, c->flags);
245 static void mangle_rgb_planes(uint8_t *dst[4], ptrdiff_t dst_stride,
246 uint8_t *src, int step, ptrdiff_t stride,
247 int width, int height)
250 int k = 2 * dst_stride;
253 for (j = 0; j < height; j++) {
255 for (i = 0; i < width * step; i += step) {
259 dst[1][k] = src[i + 2] - g;
260 dst[2][k] = src[i + 0] - g;
264 for (i = 0; i < width * step; i += step) {
268 dst[1][k] = src[i + 2] - g;
269 dst[2][k] = src[i + 0] - g;
270 dst[3][k] = src[i + 3];
274 k += dst_stride - width;
279 /* Write data to a plane with left prediction */
280 static void left_predict(uint8_t *src, uint8_t *dst, ptrdiff_t stride,
281 int width, int height)
286 prev = 0x80; /* Set the initial value */
287 for (j = 0; j < height; j++) {
288 for (i = 0; i < width; i++) {
289 *dst++ = src[i] - prev;
299 /* Write data to a plane with median prediction */
300 static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst,
301 ptrdiff_t stride, int width, int height)
307 /* First line uses left neighbour prediction */
308 prev = 0x80; /* Set the initial value */
309 for (i = 0; i < width; i++) {
310 *dst++ = src[i] - prev;
320 * Second line uses top prediction for the first sample,
321 * and median for the rest.
325 /* Rest of the coded part uses median prediction */
326 for (j = 1; j < height; j++) {
327 c->llvidencdsp.sub_median_pred(dst, src - stride, src, width, &A, &B);
333 /* Count the usage of values in a plane */
334 static void count_usage(uint8_t *src, int width,
335 int height, uint64_t *counts)
339 for (j = 0; j < height; j++) {
340 for (i = 0; i < width; i++) {
347 /* Calculate the actual huffman codes from the code lengths */
348 static void calculate_codes(HuffEntry *he)
353 qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
356 while (he[last].len == 255 && last)
360 for (i = last; i >= 0; i--) {
361 he[i].code = code >> (32 - he[i].len);
362 code += 0x80000000u >> (he[i].len - 1);
365 qsort(he, 256, sizeof(*he), huff_cmp_sym);
368 /* Write huffman bit codes to a memory block */
369 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
370 int width, int height, HuffEntry *he)
376 init_put_bits(&pb, dst, dst_size);
378 /* Write the codes */
379 for (j = 0; j < height; j++) {
380 for (i = 0; i < width; i++)
381 put_bits(&pb, he[src[i]].len, he[src[i]].code);
386 /* Pad output to a 32-bit boundary */
387 count = put_bits_count(&pb) & 0x1F;
390 put_bits(&pb, 32 - count, 0);
392 /* Get the amount of bits written */
393 count = put_bits_count(&pb);
395 /* Flush the rest with zeroes */
401 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
402 uint8_t *dst, ptrdiff_t stride, int plane_no,
403 int width, int height, PutByteContext *pb)
405 UtvideoContext *c = avctx->priv_data;
406 uint8_t lengths[256];
407 uint64_t counts[256] = { 0 };
411 uint32_t offset = 0, slice_len = 0;
412 const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
413 int i, sstart, send = 0;
417 /* Do prediction / make planes */
418 switch (c->frame_pred) {
420 for (i = 0; i < c->slices; i++) {
422 send = height * (i + 1) / c->slices & cmask;
423 av_image_copy_plane(dst + sstart * width, width,
424 src + sstart * stride, stride,
425 width, send - sstart);
429 for (i = 0; i < c->slices; i++) {
431 send = height * (i + 1) / c->slices & cmask;
432 left_predict(src + sstart * stride, dst + sstart * width,
433 stride, width, send - sstart);
437 for (i = 0; i < c->slices; i++) {
439 send = height * (i + 1) / c->slices & cmask;
440 median_predict(c, src + sstart * stride, dst + sstart * width,
441 stride, width, send - sstart);
445 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
447 return AVERROR_OPTION_NOT_FOUND;
450 /* Count the usage of values */
451 count_usage(dst, width, height, counts);
453 /* Check for a special case where only one symbol was used */
454 for (symbol = 0; symbol < 256; symbol++) {
455 /* If non-zero count is found, see if it matches width * height */
456 if (counts[symbol]) {
457 /* Special case if only one symbol was used */
458 if (counts[symbol] == width * (int64_t)height) {
460 * Write a zero for the single symbol
461 * used in the plane, else 0xFF.
463 for (i = 0; i < 256; i++) {
465 bytestream2_put_byte(pb, 0);
467 bytestream2_put_byte(pb, 0xFF);
470 /* Write zeroes for lengths */
471 for (i = 0; i < c->slices; i++)
472 bytestream2_put_le32(pb, 0);
474 /* And that's all for that plane folks */
481 /* Calculate huffman lengths */
482 if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
486 * Write the plane's header into the output packet:
487 * - huffman code lengths (256 bytes)
488 * - slice end offsets (gotten from the slice lengths)
490 for (i = 0; i < 256; i++) {
491 bytestream2_put_byte(pb, lengths[i]);
493 he[i].len = lengths[i];
497 /* Calculate the huffman codes themselves */
501 for (i = 0; i < c->slices; i++) {
503 send = height * (i + 1) / c->slices & cmask;
506 * Write the huffman codes to a buffer,
507 * get the offset in bits and convert to bytes.
509 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
510 width * height + 4, width,
511 send - sstart, he) >> 3;
513 slice_len = offset - slice_len;
515 /* Byteswap the written huffman codes */
516 c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
517 (uint32_t *) c->slice_bits,
520 /* Write the offset to the stream */
521 bytestream2_put_le32(pb, offset);
523 /* Seek to the data part of the packet */
524 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
525 offset - slice_len, SEEK_CUR);
527 /* Write the slices' data into the output packet */
528 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
530 /* Seek back to the slice offsets */
531 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
537 /* And at the end seek to the end of written slice(s) */
538 bytestream2_seek_p(pb, offset, SEEK_CUR);
543 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
544 const AVFrame *pic, int *got_packet)
546 UtvideoContext *c = avctx->priv_data;
553 int width = avctx->width, height = avctx->height;
556 /* Allocate a new packet if needed, and set it to the pointer dst */
557 ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
565 bytestream2_init_writer(&pb, dst, pkt->size);
567 av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
569 if (!c->slice_bits) {
570 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
571 return AVERROR(ENOMEM);
574 /* In case of RGB, mangle the planes to Ut Video's format */
575 if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
576 mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
577 c->planes, pic->linesize[0], width, height);
579 /* Deal with the planes */
580 switch (avctx->pix_fmt) {
581 case AV_PIX_FMT_RGB24:
582 case AV_PIX_FMT_RGBA:
583 for (i = 0; i < c->planes; i++) {
584 ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
585 c->slice_buffer[i], c->slice_stride, i,
589 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
594 case AV_PIX_FMT_YUV444P:
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, height, &pb);
600 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
605 case AV_PIX_FMT_YUV422P:
606 for (i = 0; i < c->planes; i++) {
607 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
608 pic->linesize[i], i, width >> !!i, height, &pb);
611 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
616 case AV_PIX_FMT_YUV420P:
617 for (i = 0; i < c->planes; i++) {
618 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
619 pic->linesize[i], i, width >> !!i, height >> !!i,
623 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
629 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
631 return AVERROR_INVALIDDATA;
635 * Write frame information (LE 32-bit unsigned)
636 * into the output packet.
637 * Contains the prediction method.
639 frame_info = c->frame_pred << 8;
640 bytestream2_put_le32(&pb, frame_info);
643 * At least currently Ut Video is IDR only.
644 * Set flags accordingly.
646 #if FF_API_CODED_FRAME
647 FF_DISABLE_DEPRECATION_WARNINGS
648 avctx->coded_frame->key_frame = 1;
649 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
650 FF_ENABLE_DEPRECATION_WARNINGS
653 pkt->size = bytestream2_tell_p(&pb);
654 pkt->flags |= AV_PKT_FLAG_KEY;
656 /* Packet should be done */
662 #define OFFSET(x) offsetof(UtvideoContext, x)
663 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
664 static const AVOption options[] = {
665 { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
666 { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
667 { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
668 { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
669 { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
674 static const AVClass utvideo_class = {
675 .class_name = "utvideo",
676 .item_name = av_default_item_name,
678 .version = LIBAVUTIL_VERSION_INT,
681 AVCodec ff_utvideo_encoder = {
683 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
684 .type = AVMEDIA_TYPE_VIDEO,
685 .id = AV_CODEC_ID_UTVIDEO,
686 .priv_data_size = sizeof(UtvideoContext),
687 .priv_class = &utvideo_class,
688 .init = utvideo_encode_init,
689 .encode2 = utvideo_encode_frame,
690 .close = utvideo_encode_close,
691 .capabilities = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
692 .pix_fmts = (const enum AVPixelFormat[]) {
693 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
694 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE