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 #if FF_API_PRIVATE_OPT
47 static const int ut_pred_order[5] = {
48 PRED_LEFT, PRED_MEDIAN, PRED_MEDIAN, PRED_NONE, PRED_GRADIENT
52 /* Compare huffman tree nodes */
53 static int ut_huff_cmp_len(const void *a, const void *b)
55 const HuffEntry *aa = a, *bb = b;
56 return (aa->len - bb->len)*256 + aa->sym - bb->sym;
59 /* Compare huffentry symbols */
60 static int huff_cmp_sym(const void *a, const void *b)
62 const HuffEntry *aa = a, *bb = b;
63 return aa->sym - bb->sym;
66 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
68 UtvideoContext *c = avctx->priv_data;
71 av_freep(&c->slice_bits);
72 for (i = 0; i < 4; i++)
73 av_freep(&c->slice_buffer[i]);
78 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
80 UtvideoContext *c = avctx->priv_data;
81 int i, subsampled_height;
82 uint32_t original_format;
85 c->frame_info_size = 4;
86 c->slice_stride = FFALIGN(avctx->width, 32);
88 switch (avctx->pix_fmt) {
91 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
92 original_format = UTVIDEO_RGB;
94 case AV_PIX_FMT_GBRAP:
96 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
97 original_format = UTVIDEO_RGBA;
98 avctx->bits_per_coded_sample = 32;
100 case AV_PIX_FMT_YUV420P:
101 if (avctx->width & 1 || avctx->height & 1) {
102 av_log(avctx, AV_LOG_ERROR,
103 "4:2:0 video requires even width and height.\n");
104 return AVERROR_INVALIDDATA;
107 if (avctx->colorspace == AVCOL_SPC_BT709)
108 avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
110 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
111 original_format = UTVIDEO_420;
113 case AV_PIX_FMT_YUV422P:
114 if (avctx->width & 1) {
115 av_log(avctx, AV_LOG_ERROR,
116 "4:2:2 video requires even width.\n");
117 return AVERROR_INVALIDDATA;
120 if (avctx->colorspace == AVCOL_SPC_BT709)
121 avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
123 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
124 original_format = UTVIDEO_422;
126 case AV_PIX_FMT_YUV444P:
128 if (avctx->colorspace == AVCOL_SPC_BT709)
129 avctx->codec_tag = MKTAG('U', 'L', 'H', '4');
131 avctx->codec_tag = MKTAG('U', 'L', 'Y', '4');
132 original_format = UTVIDEO_444;
135 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
137 return AVERROR_INVALIDDATA;
140 ff_bswapdsp_init(&c->bdsp);
141 ff_llvidencdsp_init(&c->llvidencdsp);
143 #if FF_API_PRIVATE_OPT
144 FF_DISABLE_DEPRECATION_WARNINGS
145 /* Check the prediction method, and error out if unsupported */
146 if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
147 av_log(avctx, AV_LOG_WARNING,
148 "Prediction method %d is not supported in Ut Video.\n",
149 avctx->prediction_method);
150 return AVERROR_OPTION_NOT_FOUND;
153 if (avctx->prediction_method == FF_PRED_PLANE) {
154 av_log(avctx, AV_LOG_ERROR,
155 "Plane prediction is not supported in Ut Video.\n");
156 return AVERROR_OPTION_NOT_FOUND;
159 /* Convert from libavcodec prediction type to Ut Video's */
160 if (avctx->prediction_method)
161 c->frame_pred = ut_pred_order[avctx->prediction_method];
162 FF_ENABLE_DEPRECATION_WARNINGS
165 if (c->frame_pred == PRED_GRADIENT) {
166 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
167 return AVERROR_OPTION_NOT_FOUND;
171 * Check the asked slice count for obviously invalid
172 * values (> 256 or negative).
174 if (avctx->slices > 256 || avctx->slices < 0) {
175 av_log(avctx, AV_LOG_ERROR,
176 "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
178 return AVERROR(EINVAL);
181 /* Check that the slice count is not larger than the subsampled height */
182 subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
183 if (avctx->slices > subsampled_height) {
184 av_log(avctx, AV_LOG_ERROR,
185 "Slice count %d is larger than the subsampling-applied height %d.\n",
186 avctx->slices, subsampled_height);
187 return AVERROR(EINVAL);
190 /* extradata size is 4 * 32 bits */
191 avctx->extradata_size = 16;
193 avctx->extradata = av_mallocz(avctx->extradata_size +
194 AV_INPUT_BUFFER_PADDING_SIZE);
196 if (!avctx->extradata) {
197 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
198 utvideo_encode_close(avctx);
199 return AVERROR(ENOMEM);
202 for (i = 0; i < c->planes; i++) {
203 c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
204 AV_INPUT_BUFFER_PADDING_SIZE);
205 if (!c->slice_buffer[i]) {
206 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
207 utvideo_encode_close(avctx);
208 return AVERROR(ENOMEM);
213 * Set the version of the encoder.
214 * Last byte is "implementation ID", which is
215 * obtained from the creator of the format.
216 * Libavcodec has been assigned with the ID 0xF0.
218 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
221 * Set the "original format"
222 * Not used for anything during decoding.
224 AV_WL32(avctx->extradata + 4, original_format);
226 /* Write 4 as the 'frame info size' */
227 AV_WL32(avctx->extradata + 8, c->frame_info_size);
230 * Set how many slices are going to be used.
231 * By default uses multiple slices depending on the subsampled height.
232 * This enables multithreading in the official decoder.
234 if (!avctx->slices) {
235 c->slices = subsampled_height / 120;
239 else if (c->slices > 256)
242 c->slices = avctx->slices;
245 /* Set compression mode */
246 c->compression = COMP_HUFF;
249 * Set the encoding flags:
250 * - Slice count minus 1
251 * - Interlaced encoding mode flag, set to zero for now.
252 * - Compression mode (none/huff)
253 * And write the flags.
255 c->flags = (c->slices - 1) << 24;
256 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
257 c->flags |= c->compression;
259 AV_WL32(avctx->extradata + 12, c->flags);
264 static void mangle_rgb_planes(uint8_t *dst[4], ptrdiff_t dst_stride,
265 uint8_t *const src[4], int planes, const int stride[4],
266 int width, int height)
269 int k = 2 * dst_stride;
270 const uint8_t *sg = src[0];
271 const uint8_t *sb = src[1];
272 const uint8_t *sr = src[2];
273 const uint8_t *sa = src[3];
276 for (j = 0; j < height; j++) {
278 for (i = 0; i < width; i++) {
282 dst[1][k] = sb[i] - g;
283 dst[2][k] = sr[i] - g;
287 for (i = 0; i < width; i++) {
291 dst[1][k] = sb[i] - g;
292 dst[2][k] = sr[i] - g;
298 k += dst_stride - width;
308 /* Write data to a plane with median prediction */
309 static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst,
310 ptrdiff_t stride, int width, int height)
316 /* First line uses left neighbour prediction */
317 prev = 0x80; /* Set the initial value */
318 for (i = 0; i < width; i++) {
319 *dst++ = src[i] - prev;
329 * Second line uses top prediction for the first sample,
330 * and median for the rest.
334 /* Rest of the coded part uses median prediction */
335 for (j = 1; j < height; j++) {
336 c->llvidencdsp.sub_median_pred(dst, src - stride, src, width, &A, &B);
342 /* Count the usage of values in a plane */
343 static void count_usage(uint8_t *src, int width,
344 int height, uint64_t *counts)
348 for (j = 0; j < height; j++) {
349 for (i = 0; i < width; i++) {
356 /* Calculate the actual huffman codes from the code lengths */
357 static void calculate_codes(HuffEntry *he)
362 qsort(he, 256, sizeof(*he), ut_huff_cmp_len);
365 while (he[last].len == 255 && last)
369 for (i = last; i >= 0; i--) {
370 he[i].code = code >> (32 - he[i].len);
371 code += 0x80000000u >> (he[i].len - 1);
374 qsort(he, 256, sizeof(*he), huff_cmp_sym);
377 /* Write huffman bit codes to a memory block */
378 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
379 int width, int height, HuffEntry *he)
385 init_put_bits(&pb, dst, dst_size);
387 /* Write the codes */
388 for (j = 0; j < height; j++) {
389 for (i = 0; i < width; i++)
390 put_bits(&pb, he[src[i]].len, he[src[i]].code);
395 /* Pad output to a 32-bit boundary */
396 count = put_bits_count(&pb) & 0x1F;
399 put_bits(&pb, 32 - count, 0);
401 /* Get the amount of bits written */
402 count = put_bits_count(&pb);
404 /* Flush the rest with zeroes */
410 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
411 uint8_t *dst, ptrdiff_t stride, int plane_no,
412 int width, int height, PutByteContext *pb)
414 UtvideoContext *c = avctx->priv_data;
415 uint8_t lengths[256];
416 uint64_t counts[256] = { 0 };
420 uint32_t offset = 0, slice_len = 0;
421 const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
422 int i, sstart, send = 0;
426 /* Do prediction / make planes */
427 switch (c->frame_pred) {
429 for (i = 0; i < c->slices; i++) {
431 send = height * (i + 1) / c->slices & cmask;
432 av_image_copy_plane(dst + sstart * width, width,
433 src + sstart * stride, stride,
434 width, send - sstart);
438 for (i = 0; i < c->slices; i++) {
440 send = height * (i + 1) / c->slices & cmask;
441 c->llvidencdsp.sub_left_predict(dst + sstart * width, src + sstart * stride, stride, width, send - sstart);
445 for (i = 0; i < c->slices; i++) {
447 send = height * (i + 1) / c->slices & cmask;
448 median_predict(c, src + sstart * stride, dst + sstart * width,
449 stride, width, send - sstart);
453 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
455 return AVERROR_OPTION_NOT_FOUND;
458 /* Count the usage of values */
459 count_usage(dst, width, height, counts);
461 /* Check for a special case where only one symbol was used */
462 for (symbol = 0; symbol < 256; symbol++) {
463 /* If non-zero count is found, see if it matches width * height */
464 if (counts[symbol]) {
465 /* Special case if only one symbol was used */
466 if (counts[symbol] == width * (int64_t)height) {
468 * Write a zero for the single symbol
469 * used in the plane, else 0xFF.
471 for (i = 0; i < 256; i++) {
473 bytestream2_put_byte(pb, 0);
475 bytestream2_put_byte(pb, 0xFF);
478 /* Write zeroes for lengths */
479 for (i = 0; i < c->slices; i++)
480 bytestream2_put_le32(pb, 0);
482 /* And that's all for that plane folks */
489 /* Calculate huffman lengths */
490 if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
494 * Write the plane's header into the output packet:
495 * - huffman code lengths (256 bytes)
496 * - slice end offsets (gotten from the slice lengths)
498 for (i = 0; i < 256; i++) {
499 bytestream2_put_byte(pb, lengths[i]);
501 he[i].len = lengths[i];
505 /* Calculate the huffman codes themselves */
509 for (i = 0; i < c->slices; i++) {
511 send = height * (i + 1) / c->slices & cmask;
514 * Write the huffman codes to a buffer,
515 * get the offset in bits and convert to bytes.
517 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
518 width * height + 4, width,
519 send - sstart, he) >> 3;
521 slice_len = offset - slice_len;
523 /* Byteswap the written huffman codes */
524 c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
525 (uint32_t *) c->slice_bits,
528 /* Write the offset to the stream */
529 bytestream2_put_le32(pb, offset);
531 /* Seek to the data part of the packet */
532 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
533 offset - slice_len, SEEK_CUR);
535 /* Write the slices' data into the output packet */
536 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
538 /* Seek back to the slice offsets */
539 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
545 /* And at the end seek to the end of written slice(s) */
546 bytestream2_seek_p(pb, offset, SEEK_CUR);
551 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
552 const AVFrame *pic, int *got_packet)
554 UtvideoContext *c = avctx->priv_data;
561 int width = avctx->width, height = avctx->height;
564 /* Allocate a new packet if needed, and set it to the pointer dst */
565 ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
573 bytestream2_init_writer(&pb, dst, pkt->size);
575 av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
577 if (!c->slice_bits) {
578 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
579 return AVERROR(ENOMEM);
582 /* In case of RGB, mangle the planes to Ut Video's format */
583 if (avctx->pix_fmt == AV_PIX_FMT_GBRAP || avctx->pix_fmt == AV_PIX_FMT_GBRP)
584 mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data,
585 c->planes, pic->linesize, width, height);
587 /* Deal with the planes */
588 switch (avctx->pix_fmt) {
589 case AV_PIX_FMT_GBRP:
590 case AV_PIX_FMT_GBRAP:
591 for (i = 0; i < c->planes; i++) {
592 ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
593 c->slice_buffer[i], c->slice_stride, i,
597 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
602 case AV_PIX_FMT_YUV444P:
603 for (i = 0; i < c->planes; i++) {
604 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
605 pic->linesize[i], i, width, height, &pb);
608 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
613 case AV_PIX_FMT_YUV422P:
614 for (i = 0; i < c->planes; i++) {
615 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
616 pic->linesize[i], i, width >> !!i, height, &pb);
619 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
624 case AV_PIX_FMT_YUV420P:
625 for (i = 0; i < c->planes; i++) {
626 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
627 pic->linesize[i], i, width >> !!i, height >> !!i,
631 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
637 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
639 return AVERROR_INVALIDDATA;
643 * Write frame information (LE 32-bit unsigned)
644 * into the output packet.
645 * Contains the prediction method.
647 frame_info = c->frame_pred << 8;
648 bytestream2_put_le32(&pb, frame_info);
651 * At least currently Ut Video is IDR only.
652 * Set flags accordingly.
654 #if FF_API_CODED_FRAME
655 FF_DISABLE_DEPRECATION_WARNINGS
656 avctx->coded_frame->key_frame = 1;
657 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
658 FF_ENABLE_DEPRECATION_WARNINGS
661 pkt->size = bytestream2_tell_p(&pb);
662 pkt->flags |= AV_PKT_FLAG_KEY;
664 /* Packet should be done */
670 #define OFFSET(x) offsetof(UtvideoContext, x)
671 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
672 static const AVOption options[] = {
673 { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
674 { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
675 { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
676 { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
677 { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
682 static const AVClass utvideo_class = {
683 .class_name = "utvideo",
684 .item_name = av_default_item_name,
686 .version = LIBAVUTIL_VERSION_INT,
689 AVCodec ff_utvideo_encoder = {
691 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
692 .type = AVMEDIA_TYPE_VIDEO,
693 .id = AV_CODEC_ID_UTVIDEO,
694 .priv_data_size = sizeof(UtvideoContext),
695 .priv_class = &utvideo_class,
696 .init = utvideo_encode_init,
697 .encode2 = utvideo_encode_frame,
698 .close = utvideo_encode_close,
699 .capabilities = AV_CODEC_CAP_FRAME_THREADS,
700 .pix_fmts = (const enum AVPixelFormat[]) {
701 AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP, AV_PIX_FMT_YUV422P,
702 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE