3 * Copyright (c) 2012 Jan Ekström
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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"
32 #include "bytestream.h"
34 #include "huffyuvencdsp.h"
39 /* Compare huffentry symbols */
40 static int huff_cmp_sym(const void *a, const void *b)
42 const HuffEntry *aa = a, *bb = b;
43 return aa->sym - bb->sym;
46 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
48 UtvideoContext *c = avctx->priv_data;
51 av_freep(&c->slice_bits);
52 for (i = 0; i < 4; i++)
53 av_freep(&c->slice_buffer[i]);
58 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
60 UtvideoContext *c = avctx->priv_data;
61 int i, subsampled_height;
62 uint32_t original_format;
65 c->frame_info_size = 4;
66 c->slice_stride = FFALIGN(avctx->width, 32);
68 switch (avctx->pix_fmt) {
69 case AV_PIX_FMT_RGB24:
71 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
72 original_format = UTVIDEO_RGB;
76 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
77 original_format = UTVIDEO_RGBA;
79 case AV_PIX_FMT_YUV420P:
80 if (avctx->width & 1 || avctx->height & 1) {
81 av_log(avctx, AV_LOG_ERROR,
82 "4:2:0 video requires even width and height.\n");
83 return AVERROR_INVALIDDATA;
86 if (avctx->colorspace == AVCOL_SPC_BT709)
87 avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
89 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
90 original_format = UTVIDEO_420;
92 case AV_PIX_FMT_YUV422P:
93 if (avctx->width & 1) {
94 av_log(avctx, AV_LOG_ERROR,
95 "4:2:2 video requires even width.\n");
96 return AVERROR_INVALIDDATA;
99 if (avctx->colorspace == AVCOL_SPC_BT709)
100 avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
102 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
103 original_format = UTVIDEO_422;
106 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
108 return AVERROR_INVALIDDATA;
111 ff_bswapdsp_init(&c->bdsp);
112 ff_huffyuvencdsp_init(&c->hdsp);
114 /* Check the prediction method, and error out if unsupported */
115 if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
116 av_log(avctx, AV_LOG_WARNING,
117 "Prediction method %d is not supported in Ut Video.\n",
118 avctx->prediction_method);
119 return AVERROR_OPTION_NOT_FOUND;
122 if (avctx->prediction_method == FF_PRED_PLANE) {
123 av_log(avctx, AV_LOG_ERROR,
124 "Plane prediction is not supported in Ut Video.\n");
125 return AVERROR_OPTION_NOT_FOUND;
128 /* Convert from libavcodec prediction type to Ut Video's */
129 c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
131 if (c->frame_pred == PRED_GRADIENT) {
132 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
133 return AVERROR_OPTION_NOT_FOUND;
137 * Check the asked slice count for obviously invalid
138 * values (> 256 or negative).
140 if (avctx->slices > 256 || avctx->slices < 0) {
141 av_log(avctx, AV_LOG_ERROR,
142 "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
144 return AVERROR(EINVAL);
147 /* Check that the slice count is not larger than the subsampled height */
148 subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
149 if (avctx->slices > subsampled_height) {
150 av_log(avctx, AV_LOG_ERROR,
151 "Slice count %d is larger than the subsampling-applied height %d.\n",
152 avctx->slices, subsampled_height);
153 return AVERROR(EINVAL);
156 /* extradata size is 4 * 32bit */
157 avctx->extradata_size = 16;
159 avctx->extradata = av_mallocz(avctx->extradata_size +
160 FF_INPUT_BUFFER_PADDING_SIZE);
162 if (!avctx->extradata) {
163 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
164 utvideo_encode_close(avctx);
165 return AVERROR(ENOMEM);
168 for (i = 0; i < c->planes; i++) {
169 c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
170 FF_INPUT_BUFFER_PADDING_SIZE);
171 if (!c->slice_buffer[i]) {
172 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
173 utvideo_encode_close(avctx);
174 return AVERROR(ENOMEM);
179 * Set the version of the encoder.
180 * Last byte is "implementation ID", which is
181 * obtained from the creator of the format.
182 * Libavcodec has been assigned with the ID 0xF0.
184 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
187 * Set the "original format"
188 * Not used for anything during decoding.
190 AV_WL32(avctx->extradata + 4, original_format);
192 /* Write 4 as the 'frame info size' */
193 AV_WL32(avctx->extradata + 8, c->frame_info_size);
196 * Set how many slices are going to be used.
197 * By default uses multiple slices depending on the subsampled height.
198 * This enables multithreading in the official decoder.
200 if (!avctx->slices) {
201 c->slices = subsampled_height / 120;
205 else if (c->slices > 256)
208 c->slices = avctx->slices;
211 /* Set compression mode */
212 c->compression = COMP_HUFF;
215 * Set the encoding flags:
216 * - Slice count minus 1
217 * - Interlaced encoding mode flag, set to zero for now.
218 * - Compression mode (none/huff)
219 * And write the flags.
221 c->flags = (c->slices - 1) << 24;
222 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
223 c->flags |= c->compression;
225 AV_WL32(avctx->extradata + 12, c->flags);
230 static void mangle_rgb_planes(uint8_t *dst[4], int dst_stride, uint8_t *src,
231 int step, int stride, int width, int height)
234 int k = 2 * dst_stride;
237 for (j = 0; j < height; j++) {
239 for (i = 0; i < width * step; i += step) {
243 dst[1][k] = src[i + 2] - g;
244 dst[2][k] = src[i + 0] - g;
248 for (i = 0; i < width * step; i += step) {
252 dst[1][k] = src[i + 2] - g;
253 dst[2][k] = src[i + 0] - g;
254 dst[3][k] = src[i + 3];
258 k += dst_stride - width;
263 /* Write data to a plane with left prediction */
264 static void left_predict(uint8_t *src, uint8_t *dst, int stride,
265 int width, int height)
270 prev = 0x80; /* Set the initial value */
271 for (j = 0; j < height; j++) {
272 for (i = 0; i < width; i++) {
273 *dst++ = src[i] - prev;
280 /* Write data to a plane with median prediction */
281 static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst, int stride,
282 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->hdsp.sub_hfyu_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), ff_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 32bit boundary */
368 count = put_bits_count(&pb) & 0x1F;
371 put_bits(&pb, 32 - count, 0);
373 /* Get the amount of bits written */
374 count = put_bits_count(&pb);
376 /* Flush the rest with zeroes */
382 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
383 uint8_t *dst, int stride,
384 int width, int height, PutByteContext *pb)
386 UtvideoContext *c = avctx->priv_data;
387 uint8_t lengths[256];
388 uint64_t counts[256] = { 0 };
392 uint32_t offset = 0, slice_len = 0;
393 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;
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;
411 left_predict(src + sstart * stride, dst + sstart * width,
412 stride, width, send - sstart);
416 for (i = 0; i < c->slices; i++) {
418 send = height * (i + 1) / c->slices;
419 median_predict(c, src + sstart * stride, dst + sstart * width,
420 stride, width, send - sstart);
424 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
426 return AVERROR_OPTION_NOT_FOUND;
429 /* Count the usage of values */
430 count_usage(dst, width, height, counts);
432 /* Check for a special case where only one symbol was used */
433 for (symbol = 0; symbol < 256; symbol++) {
434 /* If non-zero count is found, see if it matches width * height */
435 if (counts[symbol]) {
436 /* Special case if only one symbol was used */
437 if (counts[symbol] == width * height) {
439 * Write a zero for the single symbol
440 * used in the plane, else 0xFF.
442 for (i = 0; i < 256; i++) {
444 bytestream2_put_byte(pb, 0);
446 bytestream2_put_byte(pb, 0xFF);
449 /* Write zeroes for lengths */
450 for (i = 0; i < c->slices; i++)
451 bytestream2_put_le32(pb, 0);
453 /* And that's all for that plane folks */
460 /* Calculate huffman lengths */
461 ff_huff_gen_len_table(lengths, counts);
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;
484 * Write the huffman codes to a buffer,
485 * get the offset in bits and convert to bytes.
487 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
488 width * (send - sstart), width,
489 send - sstart, he) >> 3;
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_packet(pkt, (256 + 4 * c->slices + width * height) *
539 av_log(avctx, AV_LOG_ERROR,
540 "Error allocating the output packet, or the provided packet "
547 bytestream2_init_writer(&pb, dst, pkt->size);
549 av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
550 width * height + FF_INPUT_BUFFER_PADDING_SIZE);
552 if (!c->slice_bits) {
553 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
554 return AVERROR(ENOMEM);
557 /* In case of RGB, mangle the planes to Ut Video's format */
558 if (avctx->pix_fmt == AV_PIX_FMT_RGBA || avctx->pix_fmt == AV_PIX_FMT_RGB24)
559 mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data[0],
560 c->planes, pic->linesize[0], width, height);
562 /* Deal with the planes */
563 switch (avctx->pix_fmt) {
564 case AV_PIX_FMT_RGB24:
565 case AV_PIX_FMT_RGBA:
566 for (i = 0; i < c->planes; i++) {
567 ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
568 c->slice_buffer[i], c->slice_stride,
572 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
577 case AV_PIX_FMT_YUV422P:
578 for (i = 0; i < c->planes; i++) {
579 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
580 pic->linesize[i], width >> !!i, height, &pb);
583 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
588 case AV_PIX_FMT_YUV420P:
589 for (i = 0; i < c->planes; i++) {
590 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
591 pic->linesize[i], width >> !!i, height >> !!i,
595 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
601 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
603 return AVERROR_INVALIDDATA;
607 * Write frame information (LE 32bit unsigned)
608 * into the output packet.
609 * Contains the prediction method.
611 frame_info = c->frame_pred << 8;
612 bytestream2_put_le32(&pb, frame_info);
615 * At least currently Ut Video is IDR only.
616 * Set flags accordingly.
618 #if FF_API_CODED_FRAME
619 FF_DISABLE_DEPRECATION_WARNINGS
620 avctx->coded_frame->key_frame = 1;
621 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
622 FF_ENABLE_DEPRECATION_WARNINGS
625 pkt->size = bytestream2_tell_p(&pb);
626 pkt->flags |= AV_PKT_FLAG_KEY;
628 /* Packet should be done */
634 AVCodec ff_utvideo_encoder = {
636 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),
637 .type = AVMEDIA_TYPE_VIDEO,
638 .id = AV_CODEC_ID_UTVIDEO,
639 .priv_data_size = sizeof(UtvideoContext),
640 .init = utvideo_encode_init,
641 .encode2 = utvideo_encode_frame,
642 .close = utvideo_encode_close,
643 .pix_fmts = (const enum AVPixelFormat[]) {
644 AV_PIX_FMT_RGB24, AV_PIX_FMT_RGBA, AV_PIX_FMT_YUV422P,
645 AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE