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;
48 av_freep(&avctx->coded_frame);
49 av_freep(&c->slice_bits);
50 av_freep(&c->slice_buffer);
55 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
57 UtvideoContext *c = avctx->priv_data;
59 uint32_t original_format;
62 c->frame_info_size = 4;
64 switch (avctx->pix_fmt) {
67 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
68 original_format = UTVIDEO_RGB;
72 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
73 original_format = UTVIDEO_RGBA;
76 if (avctx->width & 1 || avctx->height & 1) {
77 av_log(avctx, AV_LOG_ERROR,
78 "4:2:0 video requires even width and height.\n");
79 return AVERROR_INVALIDDATA;
82 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
83 original_format = UTVIDEO_420;
86 if (avctx->width & 1) {
87 av_log(avctx, AV_LOG_ERROR,
88 "4:2:2 video requires even width.\n");
89 return AVERROR_INVALIDDATA;
92 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
93 original_format = UTVIDEO_422;
96 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
98 return AVERROR_INVALIDDATA;
101 ff_dsputil_init(&c->dsp, avctx);
103 /* Check the prediction method, and error out if unsupported */
104 if (avctx->prediction_method < 0 || avctx->prediction_method > 4) {
105 av_log(avctx, AV_LOG_WARNING,
106 "Prediction method %d is not supported in Ut Video.\n",
107 avctx->prediction_method);
108 return AVERROR_OPTION_NOT_FOUND;
111 if (avctx->prediction_method == FF_PRED_PLANE) {
112 av_log(avctx, AV_LOG_ERROR,
113 "Plane prediction is not supported in Ut Video.\n");
114 return AVERROR_OPTION_NOT_FOUND;
117 /* Convert from libavcodec prediction type to Ut Video's */
118 c->frame_pred = ff_ut_pred_order[avctx->prediction_method];
120 if (c->frame_pred == PRED_GRADIENT) {
121 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
122 return AVERROR_OPTION_NOT_FOUND;
125 avctx->coded_frame = avcodec_alloc_frame();
127 if (!avctx->coded_frame) {
128 av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
129 utvideo_encode_close(avctx);
130 return AVERROR(ENOMEM);
133 /* extradata size is 4 * 32bit */
134 avctx->extradata_size = 16;
136 avctx->extradata = av_mallocz(avctx->extradata_size +
137 FF_INPUT_BUFFER_PADDING_SIZE);
139 if (!avctx->extradata) {
140 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
141 utvideo_encode_close(avctx);
142 return AVERROR(ENOMEM);
145 c->slice_buffer = av_malloc(avctx->width * avctx->height +
146 FF_INPUT_BUFFER_PADDING_SIZE);
148 if (!c->slice_buffer) {
149 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
150 utvideo_encode_close(avctx);
151 return AVERROR(ENOMEM);
155 * Set the version of the encoder.
156 * Last byte is "implementation ID", which is
157 * obtained from the creator of the format.
158 * Libavcodec has been assigned with the ID 0xF0.
160 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
163 * Set the "original format"
164 * Not used for anything during decoding.
166 AV_WL32(avctx->extradata + 4, original_format);
168 /* Write 4 as the 'frame info size' */
169 AV_WL32(avctx->extradata + 8, c->frame_info_size);
172 * Set how many slices are going to be used.
173 * Set one slice for now.
177 /* Set compression mode */
178 c->compression = COMP_HUFF;
181 * Set the encoding flags:
182 * - Slice count minus 1
183 * - Interlaced encoding mode flag, set to zero for now.
184 * - Compression mode (none/huff)
185 * And write the flags.
187 c->flags = (c->slices - 1) << 24;
188 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
189 c->flags |= c->compression;
191 AV_WL32(avctx->extradata + 12, c->flags);
196 static void mangle_rgb_planes(uint8_t *src, int step, int stride, int width,
202 for (j = 0; j < height; j++) {
203 for (i = 0; i < width * step; i += step) {
208 src[i] = r - g + 0x80;
209 src[i + 2] = b - g + 0x80;
215 /* Write data to a plane, no prediction applied */
216 static void write_plane(uint8_t *src, uint8_t *dst, int step, int stride,
217 int width, int height)
221 for (j = 0; j < height; j++) {
222 for (i = 0; i < width * step; i += step)
229 /* Write data to a plane with left prediction */
230 static void left_predict(uint8_t *src, uint8_t *dst, int step, int stride,
231 int width, int height)
236 prev = 0x80; /* Set the initial value */
237 for (j = 0; j < height; j++) {
238 for (i = 0; i < width * step; i += step) {
239 *dst++ = src[i] - prev;
246 /* Write data to a plane with median prediction */
247 static void median_predict(uint8_t *src, uint8_t *dst, int step, int stride,
248 int width, int height)
254 /* First line uses left neighbour prediction */
255 prev = 0x80; /* Set the initial value */
256 for (i = 0; i < width * step; i += step) {
257 *dst++ = src[i] - prev;
267 * Second line uses top prediction for the first sample,
268 * and median for the rest.
273 for (i = step; i < width * step; i += step) {
275 *dst++ = src[i] - mid_pred(A, B, (A + B - C) & 0xFF);
282 /* Rest of the coded part uses median prediction */
283 for (j = 2; j < height; j++) {
284 for (i = 0; i < width * step; i += step) {
286 *dst++ = src[i] - mid_pred(A, B, (A + B - C) & 0xFF);
294 /* Count the usage of values in a plane */
295 static void count_usage(uint8_t *src, int width,
296 int height, uint64_t *counts)
300 for (j = 0; j < height; j++) {
301 for (i = 0; i < width; i++) {
308 /* Calculate the actual huffman codes from the code lengths */
309 static void calculate_codes(HuffEntry *he)
314 qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);
317 while (he[last].len == 255 && last)
321 for (i = last; i >= 0; i--) {
322 he[i].code = code >> (32 - he[i].len);
323 code += 0x80000000u >> (he[i].len - 1);
326 qsort(he, 256, sizeof(*he), huff_cmp_sym);
329 /* Write huffman bit codes to a memory block */
330 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
331 int width, int height, HuffEntry *he)
337 init_put_bits(&pb, dst, dst_size);
339 /* Write the codes */
340 for (j = 0; j < height; j++) {
341 for (i = 0; i < width; i++)
342 put_bits(&pb, he[src[i]].len, he[src[i]].code);
347 /* Pad output to a 32bit boundary */
348 count = put_bits_count(&pb) & 0x1F;
351 put_bits(&pb, 32 - count, 0);
353 /* Get the amount of bits written */
354 count = put_bits_count(&pb);
356 /* Flush the rest with zeroes */
362 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
363 uint8_t *dst, int step, int stride,
364 int width, int height, PutByteContext *pb)
366 UtvideoContext *c = avctx->priv_data;
367 uint8_t lengths[256];
368 uint64_t counts[256] = { 0 };
372 uint32_t offset = 0, slice_len = 0;
373 int i, sstart, send = 0;
376 /* Do prediction / make planes */
377 switch (c->frame_pred) {
379 for (i = 0; i < c->slices; i++) {
381 send = height * (i + 1) / c->slices;
382 write_plane(src + sstart * stride, dst + sstart * width,
383 step, stride, width, send - sstart);
387 for (i = 0; i < c->slices; i++) {
389 send = height * (i + 1) / c->slices;
390 left_predict(src + sstart * stride, dst + sstart * width,
391 step, stride, width, send - sstart);
395 for (i = 0; i < c->slices; i++) {
397 send = height * (i + 1) / c->slices;
398 median_predict(src + sstart * stride, dst + sstart * width,
399 step, stride, width, send - sstart);
403 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
405 return AVERROR_OPTION_NOT_FOUND;
408 /* Count the usage of values */
409 count_usage(dst, width, height, counts);
411 /* Check for a special case where only one symbol was used */
412 for (symbol = 0; symbol < 256; symbol++) {
413 /* If non-zero count is found, see if it matches width * height */
414 if (counts[symbol]) {
415 /* Special case if only one symbol was used */
416 if (counts[symbol] == width * height) {
418 * Write a zero for the single symbol
419 * used in the plane, else 0xFF.
421 for (i = 0; i < 256; i++) {
423 bytestream2_put_byte(pb, 0);
425 bytestream2_put_byte(pb, 0xFF);
428 /* Write zeroes for lengths */
429 for (i = 0; i < c->slices; i++)
430 bytestream2_put_le32(pb, 0);
432 /* And that's all for that plane folks */
439 /* Calculate huffman lengths */
440 ff_huff_gen_len_table(lengths, counts);
443 * Write the plane's header into the output packet:
444 * - huffman code lengths (256 bytes)
445 * - slice end offsets (gotten from the slice lengths)
447 for (i = 0; i < 256; i++) {
448 bytestream2_put_byte(pb, lengths[i]);
450 he[i].len = lengths[i];
454 /* Calculate the huffman codes themselves */
458 for (i = 0; i < c->slices; i++) {
460 send = height * (i + 1) / c->slices;
463 * Write the huffman codes to a buffer,
464 * get the offset in bits and convert to bytes.
466 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
467 width * (send - sstart), width,
468 send - sstart, he) >> 3;
470 slice_len = offset - slice_len;
472 /* Byteswap the written huffman codes */
473 c->dsp.bswap_buf((uint32_t *) c->slice_bits,
474 (uint32_t *) c->slice_bits,
477 /* Write the offset to the stream */
478 bytestream2_put_le32(pb, offset);
480 /* Seek to the data part of the packet */
481 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
482 offset - slice_len, SEEK_CUR);
484 /* Write the slices' data into the output packet */
485 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
487 /* Seek back to the slice offsets */
488 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
494 /* And at the end seek to the end of written slice(s) */
495 bytestream2_seek_p(pb, offset, SEEK_CUR);
500 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
501 const AVFrame *pic, int *got_packet)
503 UtvideoContext *c = avctx->priv_data;
510 int width = avctx->width, height = avctx->height;
513 /* Allocate a new packet if needed, and set it to the pointer dst */
514 ret = ff_alloc_packet(pkt, (256 + 4 * c->slices + width * height) *
518 av_log(avctx, AV_LOG_ERROR,
519 "Error allocating the output packet, or the provided packet "
526 bytestream2_init_writer(&pb, dst, pkt->size);
528 av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
529 width * height + FF_INPUT_BUFFER_PADDING_SIZE);
531 if (!c->slice_bits) {
532 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
533 return AVERROR(ENOMEM);
536 /* In case of RGB, mangle the planes to Ut Video's format */
537 if (avctx->pix_fmt == PIX_FMT_RGBA || avctx->pix_fmt == PIX_FMT_RGB24)
538 mangle_rgb_planes(pic->data[0], c->planes, pic->linesize[0], width,
541 /* Deal with the planes */
542 switch (avctx->pix_fmt) {
545 for (i = 0; i < c->planes; i++) {
546 ret = encode_plane(avctx, pic->data[0] + ff_ut_rgb_order[i],
547 c->slice_buffer, c->planes, pic->linesize[0],
551 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
556 case PIX_FMT_YUV422P:
557 for (i = 0; i < c->planes; i++) {
558 ret = encode_plane(avctx, pic->data[i], c->slice_buffer, 1,
559 pic->linesize[i], width >> !!i, height, &pb);
562 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
567 case PIX_FMT_YUV420P:
568 for (i = 0; i < c->planes; i++) {
569 ret = encode_plane(avctx, pic->data[i], c->slice_buffer, 1,
570 pic->linesize[i], width >> !!i, height >> !!i,
574 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
580 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
582 return AVERROR_INVALIDDATA;
586 * Write frame information (LE 32bit unsigned)
587 * into the output packet.
588 * Contains the prediction method.
590 frame_info = c->frame_pred << 8;
591 bytestream2_put_le32(&pb, frame_info);
594 * At least currently Ut Video is IDR only.
595 * Set flags accordingly.
597 avctx->coded_frame->reference = 0;
598 avctx->coded_frame->key_frame = 1;
599 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
601 pkt->size = bytestream2_tell_p(&pb);
602 pkt->flags |= AV_PKT_FLAG_KEY;
604 /* Packet should be done */
610 AVCodec ff_utvideo_encoder = {
612 .type = AVMEDIA_TYPE_VIDEO,
613 .id = CODEC_ID_UTVIDEO,
614 .priv_data_size = sizeof(UtvideoContext),
615 .init = utvideo_encode_init,
616 .encode2 = utvideo_encode_frame,
617 .close = utvideo_encode_close,
618 .pix_fmts = (const enum PixelFormat[]) {
619 PIX_FMT_RGB24, PIX_FMT_RGBA, PIX_FMT_YUV422P,
620 PIX_FMT_YUV420P, PIX_FMT_NONE
622 .long_name = NULL_IF_CONFIG_SMALL("Ut Video"),