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"
36 #include "huffyuvencdsp.h"
41 /* Compare huffentry symbols */
42 static int huff_cmp_sym(const void *a, const void *b)
44 const HuffEntry *aa = a, *bb = b;
45 return aa->sym - bb->sym;
48 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
50 UtvideoContext *c = avctx->priv_data;
53 av_freep(&c->slice_bits);
54 for (i = 0; i < 4; i++)
55 av_freep(&c->slice_buffer[i]);
60 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
62 UtvideoContext *c = avctx->priv_data;
63 int i, subsampled_height;
64 uint32_t original_format;
67 c->frame_info_size = 4;
68 c->slice_stride = FFALIGN(avctx->width, 32);
70 switch (avctx->pix_fmt) {
71 case AV_PIX_FMT_RGB24:
73 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
74 original_format = UTVIDEO_RGB;
78 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
79 original_format = UTVIDEO_RGBA;
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;
108 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
110 return AVERROR_INVALIDDATA;
113 ff_bswapdsp_init(&c->bdsp);
114 ff_huffyuvencdsp_init(&c->hdsp);
116 #if FF_API_PRIVATE_OPT
117 FF_DISABLE_DEPRECATION_WARNINGS
118 /* Check the prediction method, and error out if unsupported */
119 if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
120 av_log(avctx, AV_LOG_WARNING,
121 "Prediction method %d is not supported in Ut Video.\n",
122 avctx->prediction_method);
123 return AVERROR_OPTION_NOT_FOUND;
126 if (avctx->prediction_method == FF_PRED_PLANE) {
127 av_log(avctx, AV_LOG_ERROR,
128 "Plane prediction is not supported in Ut Video.\n");
129 return AVERROR_OPTION_NOT_FOUND;
132 /* Convert from libavcodec prediction type to Ut Video's */
133 if (avctx->prediction_method)
134 c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
135 FF_ENABLE_DEPRECATION_WARNINGS
138 if (c->frame_pred == PRED_GRADIENT) {
139 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
140 return AVERROR_OPTION_NOT_FOUND;
144 * Check the asked slice count for obviously invalid
145 * values (> 256 or negative).
147 if (avctx->slices > 256 || avctx->slices < 0) {
148 av_log(avctx, AV_LOG_ERROR,
149 "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
151 return AVERROR(EINVAL);
154 /* Check that the slice count is not larger than the subsampled height */
155 subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
156 if (avctx->slices > subsampled_height) {
157 av_log(avctx, AV_LOG_ERROR,
158 "Slice count %d is larger than the subsampling-applied height %d.\n",
159 avctx->slices, subsampled_height);
160 return AVERROR(EINVAL);
163 /* extradata size is 4 * 32bit */
164 avctx->extradata_size = 16;
166 avctx->extradata = av_mallocz(avctx->extradata_size +
167 AV_INPUT_BUFFER_PADDING_SIZE);
169 if (!avctx->extradata) {
170 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
171 utvideo_encode_close(avctx);
172 return AVERROR(ENOMEM);
175 for (i = 0; i < c->planes; i++) {
176 c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
177 AV_INPUT_BUFFER_PADDING_SIZE);
178 if (!c->slice_buffer[i]) {
179 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
180 utvideo_encode_close(avctx);
181 return AVERROR(ENOMEM);
186 * Set the version of the encoder.
187 * Last byte is "implementation ID", which is
188 * obtained from the creator of the format.
189 * Libavcodec has been assigned with the ID 0xF0.
191 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
194 * Set the "original format"
195 * Not used for anything during decoding.
197 AV_WL32(avctx->extradata + 4, original_format);
199 /* Write 4 as the 'frame info size' */
200 AV_WL32(avctx->extradata + 8, c->frame_info_size);
203 * Set how many slices are going to be used.
204 * By default uses multiple slices depending on the subsampled height.
205 * This enables multithreading in the official decoder.
207 if (!avctx->slices) {
208 c->slices = subsampled_height / 120;
212 else if (c->slices > 256)
215 c->slices = avctx->slices;
218 /* Set compression mode */
219 c->compression = COMP_HUFF;
222 * Set the encoding flags:
223 * - Slice count minus 1
224 * - Interlaced encoding mode flag, set to zero for now.
225 * - Compression mode (none/huff)
226 * And write the flags.
228 c->flags = (c->slices - 1) << 24;
229 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
230 c->flags |= c->compression;
232 AV_WL32(avctx->extradata + 12, c->flags);
237 static void mangle_rgb_planes(uint8_t *dst[4], int dst_stride, uint8_t *src,
238 int step, int stride, int width, int height)
241 int k = 2 * dst_stride;
244 for (j = 0; j < height; j++) {
246 for (i = 0; i < width * step; i += step) {
250 dst[1][k] = src[i + 2] - g;
251 dst[2][k] = src[i + 0] - g;
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;
261 dst[3][k] = src[i + 3];
265 k += dst_stride - width;
270 /* Write data to a plane with left prediction */
271 static void left_predict(uint8_t *src, uint8_t *dst, int stride,
272 int width, int height)
277 prev = 0x80; /* Set the initial value */
278 for (j = 0; j < height; j++) {
279 for (i = 0; i < width; i++) {
280 *dst++ = src[i] - prev;
287 /* Write data to a plane with median prediction */
288 static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst, int stride,
289 int width, int height)
295 /* First line uses left neighbour prediction */
296 prev = 0x80; /* Set the initial value */
297 for (i = 0; i < width; i++) {
298 *dst++ = src[i] - prev;
308 * Second line uses top prediction for the first sample,
309 * and median for the rest.
313 /* Rest of the coded part uses median prediction */
314 for (j = 1; j < height; j++) {
315 c->hdsp.sub_hfyu_median_pred(dst, src - stride, src, width, &A, &B);
321 /* Count the usage of values in a plane */
322 static void count_usage(uint8_t *src, int width,
323 int height, uint64_t *counts)
327 for (j = 0; j < height; j++) {
328 for (i = 0; i < width; i++) {
335 /* Calculate the actual huffman codes from the code lengths */
336 static void calculate_codes(HuffEntry *he)
341 qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
344 while (he[last].len == 255 && last)
348 for (i = last; i >= 0; i--) {
349 he[i].code = code >> (32 - he[i].len);
350 code += 0x80000000u >> (he[i].len - 1);
353 qsort(he, 256, sizeof(*he), huff_cmp_sym);
356 /* Write huffman bit codes to a memory block */
357 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
358 int width, int height, HuffEntry *he)
364 init_put_bits(&pb, dst, dst_size);
366 /* Write the codes */
367 for (j = 0; j < height; j++) {
368 for (i = 0; i < width; i++)
369 put_bits(&pb, he[src[i]].len, he[src[i]].code);
374 /* Pad output to a 32bit boundary */
375 count = put_bits_count(&pb) & 0x1F;
378 put_bits(&pb, 32 - count, 0);
380 /* Get the amount of bits written */
381 count = put_bits_count(&pb);
383 /* Flush the rest with zeroes */
389 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
390 uint8_t *dst, int stride, int plane_no,
391 int width, int height, PutByteContext *pb)
393 UtvideoContext *c = avctx->priv_data;
394 uint8_t lengths[256];
395 uint64_t counts[256] = { 0 };
399 uint32_t offset = 0, slice_len = 0;
400 const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
401 int i, sstart, send = 0;
405 /* Do prediction / make planes */
406 switch (c->frame_pred) {
408 for (i = 0; i < c->slices; i++) {
410 send = height * (i + 1) / c->slices & cmask;
411 av_image_copy_plane(dst + sstart * width, width,
412 src + sstart * stride, stride,
413 width, send - sstart);
417 for (i = 0; i < c->slices; i++) {
419 send = height * (i + 1) / c->slices & cmask;
420 left_predict(src + sstart * stride, dst + sstart * width,
421 stride, width, send - sstart);
425 for (i = 0; i < c->slices; i++) {
427 send = height * (i + 1) / c->slices & cmask;
428 median_predict(c, src + sstart * stride, dst + sstart * width,
429 stride, width, send - sstart);
433 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
435 return AVERROR_OPTION_NOT_FOUND;
438 /* Count the usage of values */
439 count_usage(dst, width, height, counts);
441 /* Check for a special case where only one symbol was used */
442 for (symbol = 0; symbol < 256; symbol++) {
443 /* If non-zero count is found, see if it matches width * height */
444 if (counts[symbol]) {
445 /* Special case if only one symbol was used */
446 if (counts[symbol] == width * (int64_t)height) {
448 * Write a zero for the single symbol
449 * used in the plane, else 0xFF.
451 for (i = 0; i < 256; i++) {
453 bytestream2_put_byte(pb, 0);
455 bytestream2_put_byte(pb, 0xFF);
458 /* Write zeroes for lengths */
459 for (i = 0; i < c->slices; i++)
460 bytestream2_put_le32(pb, 0);
462 /* And that's all for that plane folks */
469 /* Calculate huffman lengths */
470 if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
474 * Write the plane's header into the output packet:
475 * - huffman code lengths (256 bytes)
476 * - slice end offsets (gotten from the slice lengths)
478 for (i = 0; i < 256; i++) {
479 bytestream2_put_byte(pb, lengths[i]);
481 he[i].len = lengths[i];
485 /* Calculate the huffman codes themselves */
489 for (i = 0; i < c->slices; i++) {
491 send = height * (i + 1) / c->slices & cmask;
494 * Write the huffman codes to a buffer,
495 * get the offset in bits and convert to bytes.
497 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
498 width * height + 4, width,
499 send - sstart, he) >> 3;
501 slice_len = offset - slice_len;
503 /* Byteswap the written huffman codes */
504 c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
505 (uint32_t *) c->slice_bits,
508 /* Write the offset to the stream */
509 bytestream2_put_le32(pb, offset);
511 /* Seek to the data part of the packet */
512 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
513 offset - slice_len, SEEK_CUR);
515 /* Write the slices' data into the output packet */
516 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
518 /* Seek back to the slice offsets */
519 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
525 /* And at the end seek to the end of written slice(s) */
526 bytestream2_seek_p(pb, offset, SEEK_CUR);
531 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
532 const AVFrame *pic, int *got_packet)
534 UtvideoContext *c = avctx->priv_data;
541 int width = avctx->width, height = avctx->height;
544 /* Allocate a new packet if needed, and set it to the pointer dst */
545 ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
553 bytestream2_init_writer(&pb, dst, pkt->size);
555 av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
557 if (!c->slice_bits) {
558 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
559 return AVERROR(ENOMEM);
562 /* In case of RGB, mangle the planes to Ut Video's format */
563 if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
564 mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
565 c->planes, pic->linesize[0], width, height);
567 /* Deal with the planes */
568 switch (avctx->pix_fmt) {
569 case AV_PIX_FMT_RGB24:
570 case AV_PIX_FMT_RGBA:
571 for (i = 0; i < c->planes; i++) {
572 ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
573 c->slice_buffer[i], c->slice_stride, i,
577 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
582 case AV_PIX_FMT_YUV422P:
583 for (i = 0; i < c->planes; i++) {
584 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
585 pic->linesize[i], i, width >> !!i, height, &pb);
588 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
593 case AV_PIX_FMT_YUV420P:
594 for (i = 0; i < c->planes; i++) {
595 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
596 pic->linesize[i], i, width >> !!i, height >> !!i,
600 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
606 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
608 return AVERROR_INVALIDDATA;
612 * Write frame information (LE 32bit unsigned)
613 * into the output packet.
614 * Contains the prediction method.
616 frame_info = c->frame_pred << 8;
617 bytestream2_put_le32(&pb, frame_info);
620 * At least currently Ut Video is IDR only.
621 * Set flags accordingly.
623 #if FF_API_CODED_FRAME
624 FF_DISABLE_DEPRECATION_WARNINGS
625 avctx->coded_frame->key_frame = 1;
626 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
627 FF_ENABLE_DEPRECATION_WARNINGS
630 pkt->size = bytestream2_tell_p(&pb);
631 pkt->flags |= AV_PKT_FLAG_KEY;
633 /* Packet should be done */
639 #define OFFSET(x) offsetof(UtvideoContext, x)
640 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
641 static const AVOption options[] = {
642 { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
643 { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
644 { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
645 { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
646 { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
651 static const AVClass utvideo_class = {
652 .class_name = "utvideo",
653 .item_name = av_default_item_name,
655 .version = LIBAVUTIL_VERSION_INT,
658 AVCodec ff_utvideo_encoder = {
660 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
661 .type = AVMEDIA_TYPE_VIDEO,
662 .id = AV_CODEC_ID_UTVIDEO,
663 .priv_data_size = sizeof(UtvideoContext),
664 .priv_class = &utvideo_class,
665 .init = utvideo_encode_init,
666 .encode2 = utvideo_encode_frame,
667 .close = utvideo_encode_close,
668 .capabilities = AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_INTRA_ONLY,
669 .pix_fmts = (const enum AVPixelFormat[]) {
670 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
671 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE