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/intreadwrite.h"
30 #include "bytestream.h"
37 /* Compare huffentry symbols */
38 static int huff_cmp_sym(const void *a, const void *b)
40 const HuffEntry *aa = a, *bb = b;
41 return aa->sym - bb->sym;
44 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
46 UtvideoContext *c = avctx->priv_data;
49 av_freep(&avctx->coded_frame);
50 av_freep(&c->slice_bits);
51 for (i = 0; i < 4; i++)
52 av_freep(&c->slice_buffer[i]);
57 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
59 UtvideoContext *c = avctx->priv_data;
61 uint32_t original_format;
64 c->frame_info_size = 4;
66 switch (avctx->pix_fmt) {
69 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
70 original_format = UTVIDEO_RGB;
74 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
75 original_format = UTVIDEO_RGBA;
78 if (avctx->width & 1 || avctx->height & 1) {
79 av_log(avctx, AV_LOG_ERROR,
80 "4:2:0 video requires even width and height.\n");
81 return AVERROR_INVALIDDATA;
84 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
85 original_format = UTVIDEO_420;
88 if (avctx->width & 1) {
89 av_log(avctx, AV_LOG_ERROR,
90 "4:2:2 video requires even width.\n");
91 return AVERROR_INVALIDDATA;
94 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
95 original_format = UTVIDEO_422;
98 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
100 return AVERROR_INVALIDDATA;
103 ff_dsputil_init(&c->dsp, avctx);
105 /* Check the prediction method, and error out if unsupported */
106 if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
107 av_log(avctx, AV_LOG_WARNING,
108 "Prediction method %d is not supported in Ut Video.\n",
109 avctx->prediction_method);
110 return AVERROR_OPTION_NOT_FOUND;
113 if (avctx->prediction_method == FF_PRED_PLANE) {
114 av_log(avctx, AV_LOG_ERROR,
115 "Plane prediction is not supported in Ut Video.\n");
116 return AVERROR_OPTION_NOT_FOUND;
119 /* Convert from libavcodec prediction type to Ut Video's */
120 c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
122 if (c->frame_pred == PRED_GRADIENT) {
123 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
124 return AVERROR_OPTION_NOT_FOUND;
127 avctx->coded_frame = avcodec_alloc_frame();
129 if (!avctx->coded_frame) {
130 av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
131 utvideo_encode_close(avctx);
132 return AVERROR(ENOMEM);
135 /* extradata size is 4 * 32bit */
136 avctx->extradata_size = 16;
138 avctx->extradata = av_mallocz(avctx->extradata_size +
139 FF_INPUT_BUFFER_PADDING_SIZE);
141 if (!avctx->extradata) {
142 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
143 utvideo_encode_close(avctx);
144 return AVERROR(ENOMEM);
147 for (i = 0; i < c->planes; i++) {
148 c->slice_buffer[i] = av_malloc(avctx->width * (avctx->height + 1) +
149 FF_INPUT_BUFFER_PADDING_SIZE);
150 if (!c->slice_buffer[i]) {
151 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
152 utvideo_encode_close(avctx);
153 return AVERROR(ENOMEM);
158 * Set the version of the encoder.
159 * Last byte is "implementation ID", which is
160 * obtained from the creator of the format.
161 * Libavcodec has been assigned with the ID 0xF0.
163 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
166 * Set the "original format"
167 * Not used for anything during decoding.
169 AV_WL32(avctx->extradata + 4, original_format);
171 /* Write 4 as the 'frame info size' */
172 AV_WL32(avctx->extradata + 8, c->frame_info_size);
175 * Set how many slices are going to be used.
176 * Set one slice for now.
180 /* Set compression mode */
181 c->compression = COMP_HUFF;
184 * Set the encoding flags:
185 * - Slice count minus 1
186 * - Interlaced encoding mode flag, set to zero for now.
187 * - Compression mode (none/huff)
188 * And write the flags.
190 c->flags = (c->slices - 1) << 24;
191 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
192 c->flags |= c->compression;
194 AV_WL32(avctx->extradata + 12, c->flags);
199 static void mangle_rgb_planes(uint8_t *dst[4], uint8_t *src, int step,
200 int stride, int width, int height)
206 for (j = 0; j < height; j++) {
208 for (i = 0; i < width * step; i += step) {
212 dst[1][k] = src[i + 2] - g;
213 dst[2][k] = src[i + 0] - g;
217 for (i = 0; i < width * step; i += step) {
221 dst[1][k] = src[i + 2] - g;
222 dst[2][k] = src[i + 0] - g;
223 dst[3][k] = src[i + 3];
231 /* Write data to a plane, no prediction applied */
232 static void write_plane(uint8_t *src, uint8_t *dst, int step, int stride,
233 int width, int height)
237 for (j = 0; j < height; j++) {
238 for (i = 0; i < width * step; i += step)
245 /* Write data to a plane with left prediction */
246 static void left_predict(uint8_t *src, uint8_t *dst, int step, int stride,
247 int width, int height)
252 prev = 0x80; /* Set the initial value */
253 for (j = 0; j < height; j++) {
254 for (i = 0; i < width * step; i += step) {
255 *dst++ = src[i] - prev;
262 /* Write data to a plane with median prediction */
263 static void median_predict(uint8_t *src, uint8_t *dst, int step, int stride,
264 int width, int height)
270 /* First line uses left neighbour prediction */
271 prev = 0x80; /* Set the initial value */
272 for (i = 0; i < width * step; i += step) {
273 *dst++ = src[i] - prev;
283 * Second line uses top prediction for the first sample,
284 * and median for the rest.
289 for (i = step; i < width * step; i += step) {
291 *dst++ = src[i] - mid_pred(A, B, (A + B - C) & 0xFF);
298 /* Rest of the coded part uses median prediction */
299 for (j = 2; j < height; j++) {
300 for (i = 0; i < width * step; i += step) {
302 *dst++ = src[i] - mid_pred(A, B, (A + B - C) & 0xFF);
310 /* Count the usage of values in a plane */
311 static void count_usage(uint8_t *src, int width,
312 int height, uint64_t *counts)
316 for (j = 0; j < height; j++) {
317 for (i = 0; i < width; i++) {
324 /* Calculate the actual huffman codes from the code lengths */
325 static void calculate_codes(HuffEntry *he)
330 qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
333 while (he[last].len == 255 && last)
337 for (i = last; i >= 0; i--) {
338 he[i].code = code >> (32 - he[i].len);
339 code += 0x80000000u >> (he[i].len - 1);
342 qsort(he, 256, sizeof(*he), huff_cmp_sym);
345 /* Write huffman bit codes to a memory block */
346 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
347 int width, int height, HuffEntry *he)
353 init_put_bits(&pb, dst, dst_size);
355 /* Write the codes */
356 for (j = 0; j < height; j++) {
357 for (i = 0; i < width; i++)
358 put_bits(&pb, he[src[i]].len, he[src[i]].code);
363 /* Pad output to a 32bit boundary */
364 count = put_bits_count(&pb) & 0x1F;
367 put_bits(&pb, 32 - count, 0);
369 /* Get the amount of bits written */
370 count = put_bits_count(&pb);
372 /* Flush the rest with zeroes */
378 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
379 uint8_t *dst, int step, int stride,
380 int width, int height, PutByteContext *pb)
382 UtvideoContext *c = avctx->priv_data;
383 uint8_t lengths[256];
384 uint64_t counts[256] = { 0 };
388 uint32_t offset = 0, slice_len = 0;
389 int i, sstart, send = 0;
392 /* Do prediction / make planes */
393 switch (c->frame_pred) {
395 for (i = 0; i < c->slices; i++) {
397 send = height * (i + 1) / c->slices;
398 write_plane(src + sstart * stride, dst + sstart * width,
399 step, stride, width, send - sstart);
403 for (i = 0; i < c->slices; i++) {
405 send = height * (i + 1) / c->slices;
406 left_predict(src + sstart * stride, dst + sstart * width,
407 step, stride, width, send - sstart);
411 for (i = 0; i < c->slices; i++) {
413 send = height * (i + 1) / c->slices;
414 median_predict(src + sstart * stride, dst + sstart * width,
415 step, stride, width, send - sstart);
419 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
421 return AVERROR_OPTION_NOT_FOUND;
424 /* Count the usage of values */
425 count_usage(dst, width, height, counts);
427 /* Check for a special case where only one symbol was used */
428 for (symbol = 0; symbol < 256; symbol++) {
429 /* If non-zero count is found, see if it matches width * height */
430 if (counts[symbol]) {
431 /* Special case if only one symbol was used */
432 if (counts[symbol] == width * height) {
434 * Write a zero for the single symbol
435 * used in the plane, else 0xFF.
437 for (i = 0; i < 256; i++) {
439 bytestream2_put_byte(pb, 0);
441 bytestream2_put_byte(pb, 0xFF);
444 /* Write zeroes for lengths */
445 for (i = 0; i < c->slices; i++)
446 bytestream2_put_le32(pb, 0);
448 /* And that's all for that plane folks */
455 /* Calculate huffman lengths */
456 ff_huff_gen_len_table(lengths, counts);
459 * Write the plane's header into the output packet:
460 * - huffman code lengths (256 bytes)
461 * - slice end offsets (gotten from the slice lengths)
463 for (i = 0; i < 256; i++) {
464 bytestream2_put_byte(pb, lengths[i]);
466 he[i].len = lengths[i];
470 /* Calculate the huffman codes themselves */
474 for (i = 0; i < c->slices; i++) {
476 send = height * (i + 1) / c->slices;
479 * Write the huffman codes to a buffer,
480 * get the offset in bits and convert to bytes.
482 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
483 width * (send - sstart), width,
484 send - sstart, he) >> 3;
486 slice_len = offset - slice_len;
488 /* Byteswap the written huffman codes */
489 c->dsp.bswap_buf((uint32_t *) c->slice_bits,
490 (uint32_t *) c->slice_bits,
493 /* Write the offset to the stream */
494 bytestream2_put_le32(pb, offset);
496 /* Seek to the data part of the packet */
497 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
498 offset - slice_len, SEEK_CUR);
500 /* Write the slices' data into the output packet */
501 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
503 /* Seek back to the slice offsets */
504 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
510 /* And at the end seek to the end of written slice(s) */
511 bytestream2_seek_p(pb, offset, SEEK_CUR);
516 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
517 const AVFrame *pic, int *got_packet)
519 UtvideoContext *c = avctx->priv_data;
526 int width = avctx->width, height = avctx->height;
529 /* Allocate a new packet if needed, and set it to the pointer dst */
530 ret = ff_alloc_packet(pkt, (256 + 4 * c->slices + width * height) *
534 av_log(avctx, AV_LOG_ERROR,
535 "Error allocating the output packet, or the provided packet "
542 bytestream2_init_writer(&pb, dst, pkt->size);
544 av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
545 width * height + FF_INPUT_BUFFER_PADDING_SIZE);
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 == PIX_FMT_RGBA || avctx->pix_fmt == PIX_FMT_RGB24)
554 mangle_rgb_planes(c->slice_buffer, pic->data[0], c->planes,
555 pic->linesize[0], width, height);
557 /* Deal with the planes */
558 switch (avctx->pix_fmt) {
561 for (i = 0; i < c->planes; i++) {
562 ret = encode_plane(avctx, c->slice_buffer[i] + width,
563 c->slice_buffer[i], 1, width,
567 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
572 case PIX_FMT_YUV422P:
573 for (i = 0; i < c->planes; i++) {
574 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0], 1,
575 pic->linesize[i], width >> !!i, height, &pb);
578 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
583 case PIX_FMT_YUV420P:
584 for (i = 0; i < c->planes; i++) {
585 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0], 1,
586 pic->linesize[i], width >> !!i, height >> !!i,
590 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
596 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
598 return AVERROR_INVALIDDATA;
602 * Write frame information (LE 32bit unsigned)
603 * into the output packet.
604 * Contains the prediction method.
606 frame_info = c->frame_pred << 8;
607 bytestream2_put_le32(&pb, frame_info);
610 * At least currently Ut Video is IDR only.
611 * Set flags accordingly.
613 avctx->coded_frame->reference = 0;
614 avctx->coded_frame->key_frame = 1;
615 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
617 pkt->size = bytestream2_tell_p(&pb);
618 pkt->flags |= AV_PKT_FLAG_KEY;
620 /* Packet should be done */
626 AVCodec ff_utvideo_encoder = {
628 .type = AVMEDIA_TYPE_VIDEO,
629 .id = CODEC_ID_UTVIDEO,
630 .priv_data_size = sizeof(UtvideoContext),
631 .init = utvideo_encode_init,
632 .encode2 = utvideo_encode_frame,
633 .close = utvideo_encode_close,
634 .pix_fmts = (const enum PixelFormat[]) {
635 PIX_FMT_RGB24, PIX_FMT_RGBA, PIX_FMT_YUV422P,
636 PIX_FMT_YUV420P, PIX_FMT_NONE
638 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),