avformat/mpeg: demux ivtv captions
[ffmpeg.git] / libavcodec / utvideoenc.c
blob54b1caa9e32797585a3c2ec9fb401ea736061d53
1 /*
2 * Ut Video encoder
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
22 /**
23 * @file
24 * Ut Video encoder
27 #include "libavutil/imgutils.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mem.h"
30 #include "libavutil/opt.h"
32 #include "avcodec.h"
33 #include "codec_internal.h"
34 #include "encode.h"
35 #include "bswapdsp.h"
36 #include "bytestream.h"
37 #include "lossless_videoencdsp.h"
38 #include "put_bits.h"
39 #include "utvideo.h"
40 #include "huffman.h"
42 typedef struct UtvideoContext {
43 const AVClass *class;
44 BswapDSPContext bdsp;
45 LLVidEncDSPContext llvidencdsp;
47 uint32_t frame_info_size, flags;
48 int planes;
49 int slices;
50 int compression;
51 int frame_pred;
53 ptrdiff_t slice_stride;
54 uint8_t *slice_bits, *slice_buffer[4];
55 int slice_bits_size;
56 } UtvideoContext;
58 typedef struct HuffEntry {
59 uint16_t sym;
60 uint8_t len;
61 uint32_t code;
62 } HuffEntry;
64 /* Compare huffman tree nodes */
65 static int ut_huff_cmp_len(const void *a, const void *b)
67 const HuffEntry *aa = a, *bb = b;
68 return (aa->len - bb->len)*256 + aa->sym - bb->sym;
71 /* Compare huffentry symbols */
72 static int huff_cmp_sym(const void *a, const void *b)
74 const HuffEntry *aa = a, *bb = b;
75 return aa->sym - bb->sym;
78 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
80 UtvideoContext *c = avctx->priv_data;
81 int i;
83 av_freep(&c->slice_bits);
84 for (i = 0; i < 4; i++)
85 av_freep(&c->slice_buffer[i]);
87 return 0;
90 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
92 UtvideoContext *c = avctx->priv_data;
93 int i, subsampled_height;
94 uint32_t original_format;
96 c->frame_info_size = 4;
97 c->slice_stride = FFALIGN(avctx->width, 32);
99 switch (avctx->pix_fmt) {
100 case AV_PIX_FMT_GBRP:
101 c->planes = 3;
102 avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
103 original_format = UTVIDEO_RGB;
104 break;
105 case AV_PIX_FMT_GBRAP:
106 c->planes = 4;
107 avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
108 original_format = UTVIDEO_RGBA;
109 avctx->bits_per_coded_sample = 32;
110 break;
111 case AV_PIX_FMT_YUV420P:
112 if (avctx->width & 1 || avctx->height & 1) {
113 av_log(avctx, AV_LOG_ERROR,
114 "4:2:0 video requires even width and height.\n");
115 return AVERROR_INVALIDDATA;
117 c->planes = 3;
118 if (avctx->colorspace == AVCOL_SPC_BT709)
119 avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
120 else
121 avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
122 original_format = UTVIDEO_420;
123 break;
124 case AV_PIX_FMT_YUV422P:
125 if (avctx->width & 1) {
126 av_log(avctx, AV_LOG_ERROR,
127 "4:2:2 video requires even width.\n");
128 return AVERROR_INVALIDDATA;
130 c->planes = 3;
131 if (avctx->colorspace == AVCOL_SPC_BT709)
132 avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
133 else
134 avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
135 original_format = UTVIDEO_422;
136 break;
137 case AV_PIX_FMT_YUV444P:
138 c->planes = 3;
139 if (avctx->colorspace == AVCOL_SPC_BT709)
140 avctx->codec_tag = MKTAG('U', 'L', 'H', '4');
141 else
142 avctx->codec_tag = MKTAG('U', 'L', 'Y', '4');
143 original_format = UTVIDEO_444;
144 break;
145 default:
146 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
147 avctx->pix_fmt);
148 return AVERROR_INVALIDDATA;
151 ff_bswapdsp_init(&c->bdsp);
152 ff_llvidencdsp_init(&c->llvidencdsp);
154 if (c->frame_pred == PRED_GRADIENT) {
155 av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
156 return AVERROR_OPTION_NOT_FOUND;
160 * Check the asked slice count for obviously invalid
161 * values (> 256 or negative).
163 if (avctx->slices > 256 || avctx->slices < 0) {
164 av_log(avctx, AV_LOG_ERROR,
165 "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
166 avctx->slices);
167 return AVERROR(EINVAL);
170 /* Check that the slice count is not larger than the subsampled height */
171 subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
172 if (avctx->slices > subsampled_height) {
173 av_log(avctx, AV_LOG_ERROR,
174 "Slice count %d is larger than the subsampling-applied height %d.\n",
175 avctx->slices, subsampled_height);
176 return AVERROR(EINVAL);
179 /* extradata size is 4 * 32 bits */
180 avctx->extradata_size = 16;
182 avctx->extradata = av_mallocz(avctx->extradata_size +
183 AV_INPUT_BUFFER_PADDING_SIZE);
185 if (!avctx->extradata) {
186 av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
187 return AVERROR(ENOMEM);
190 for (i = 0; i < c->planes; i++) {
191 c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
192 AV_INPUT_BUFFER_PADDING_SIZE);
193 if (!c->slice_buffer[i]) {
194 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
195 return AVERROR(ENOMEM);
200 * Set the version of the encoder.
201 * Last byte is "implementation ID", which is
202 * obtained from the creator of the format.
203 * Libavcodec has been assigned with the ID 0xF0.
205 AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
208 * Set the "original format"
209 * Not used for anything during decoding.
211 AV_WL32(avctx->extradata + 4, original_format);
213 /* Write 4 as the 'frame info size' */
214 AV_WL32(avctx->extradata + 8, c->frame_info_size);
217 * Set how many slices are going to be used.
218 * By default uses multiple slices depending on the subsampled height.
219 * This enables multithreading in the official decoder.
221 if (!avctx->slices) {
222 c->slices = subsampled_height / 120;
224 if (!c->slices)
225 c->slices = 1;
226 else if (c->slices > 256)
227 c->slices = 256;
228 } else {
229 c->slices = avctx->slices;
232 /* Set compression mode */
233 c->compression = COMP_HUFF;
236 * Set the encoding flags:
237 * - Slice count minus 1
238 * - Interlaced encoding mode flag, set to zero for now.
239 * - Compression mode (none/huff)
240 * And write the flags.
242 c->flags = (c->slices - 1U) << 24;
243 c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
244 c->flags |= c->compression;
246 AV_WL32(avctx->extradata + 12, c->flags);
248 return 0;
251 static void mangle_rgb_planes(uint8_t *dst[4], ptrdiff_t dst_stride,
252 uint8_t *const src[4], int planes, const int stride[4],
253 int width, int height)
255 int i, j;
256 int k = 2 * dst_stride;
257 const uint8_t *sg = src[0];
258 const uint8_t *sb = src[1];
259 const uint8_t *sr = src[2];
260 const uint8_t *sa = src[3];
261 unsigned int g;
263 for (j = 0; j < height; j++) {
264 if (planes == 3) {
265 for (i = 0; i < width; i++) {
266 g = sg[i];
267 dst[0][k] = g;
268 g += 0x80;
269 dst[1][k] = sb[i] - g;
270 dst[2][k] = sr[i] - g;
271 k++;
273 } else {
274 for (i = 0; i < width; i++) {
275 g = sg[i];
276 dst[0][k] = g;
277 g += 0x80;
278 dst[1][k] = sb[i] - g;
279 dst[2][k] = sr[i] - g;
280 dst[3][k] = sa[i];
281 k++;
283 sa += stride[3];
285 k += dst_stride - width;
286 sg += stride[0];
287 sb += stride[1];
288 sr += stride[2];
292 #undef A
293 #undef B
295 /* Write data to a plane with median prediction */
296 static void median_predict(UtvideoContext *c, const uint8_t *src, uint8_t *dst,
297 ptrdiff_t stride, int width, int height)
299 int i, j;
300 int A, B;
301 uint8_t prev;
303 /* First line uses left neighbour prediction */
304 prev = 0x80; /* Set the initial value */
305 for (i = 0; i < width; i++) {
306 *dst++ = src[i] - prev;
307 prev = src[i];
310 if (height == 1)
311 return;
313 src += stride;
316 * Second line uses top prediction for the first sample,
317 * and median for the rest.
319 A = B = 0;
321 /* Rest of the coded part uses median prediction */
322 for (j = 1; j < height; j++) {
323 c->llvidencdsp.sub_median_pred(dst, src - stride, src, width, &A, &B);
324 dst += width;
325 src += stride;
329 /* Count the usage of values in a plane */
330 static void count_usage(uint8_t *src, int width,
331 int height, uint64_t *counts)
333 int i, j;
335 for (j = 0; j < height; j++) {
336 for (i = 0; i < width; i++) {
337 counts[src[i]]++;
339 src += width;
343 /* Calculate the actual huffman codes from the code lengths */
344 static void calculate_codes(HuffEntry *he)
346 int last, i;
347 uint32_t code;
349 qsort(he, 256, sizeof(*he), ut_huff_cmp_len);
351 last = 255;
352 while (he[last].len == 255 && last)
353 last--;
355 code = 0;
356 for (i = last; i >= 0; i--) {
357 he[i].code = code >> (32 - he[i].len);
358 code += 0x80000000u >> (he[i].len - 1);
361 qsort(he, 256, sizeof(*he), huff_cmp_sym);
364 /* Write huffman bit codes to a memory block */
365 static int write_huff_codes(uint8_t *src, uint8_t *dst, int dst_size,
366 int width, int height, HuffEntry *he)
368 PutBitContext pb;
369 int i, j;
370 int count;
372 init_put_bits(&pb, dst, dst_size);
374 /* Write the codes */
375 for (j = 0; j < height; j++) {
376 for (i = 0; i < width; i++)
377 put_bits(&pb, he[src[i]].len, he[src[i]].code);
379 src += width;
382 /* Pad output to a 32-bit boundary */
383 count = put_bits_count(&pb) & 0x1F;
385 if (count)
386 put_bits(&pb, 32 - count, 0);
388 /* Flush the rest with zeroes */
389 flush_put_bits(&pb);
391 /* Return the amount of bytes written */
392 return put_bytes_output(&pb);
395 static int encode_plane(AVCodecContext *avctx, const uint8_t *src,
396 uint8_t *dst, ptrdiff_t stride, int plane_no,
397 int width, int height, PutByteContext *pb)
399 UtvideoContext *c = avctx->priv_data;
400 uint8_t lengths[256];
401 uint64_t counts[256] = { 0 };
403 HuffEntry he[256];
405 uint32_t offset = 0, slice_len = 0;
406 const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
407 int i, sstart, send = 0;
408 int symbol;
409 int ret;
411 /* Do prediction / make planes */
412 switch (c->frame_pred) {
413 case PRED_NONE:
414 for (i = 0; i < c->slices; i++) {
415 sstart = send;
416 send = height * (i + 1) / c->slices & cmask;
417 av_image_copy_plane(dst + sstart * width, width,
418 src + sstart * stride, stride,
419 width, send - sstart);
421 break;
422 case PRED_LEFT:
423 for (i = 0; i < c->slices; i++) {
424 sstart = send;
425 send = height * (i + 1) / c->slices & cmask;
426 c->llvidencdsp.sub_left_predict(dst + sstart * width, src + sstart * stride, stride, width, send - sstart);
428 break;
429 case PRED_MEDIAN:
430 for (i = 0; i < c->slices; i++) {
431 sstart = send;
432 send = height * (i + 1) / c->slices & cmask;
433 median_predict(c, src + sstart * stride, dst + sstart * width,
434 stride, width, send - sstart);
436 break;
437 default:
438 av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
439 c->frame_pred);
440 return AVERROR_OPTION_NOT_FOUND;
443 /* Count the usage of values */
444 count_usage(dst, width, height, counts);
446 /* Check for a special case where only one symbol was used */
447 for (symbol = 0; symbol < 256; symbol++) {
448 /* If non-zero count is found, see if it matches width * height */
449 if (counts[symbol]) {
450 /* Special case if only one symbol was used */
451 if (counts[symbol] == width * (int64_t)height) {
453 * Write a zero for the single symbol
454 * used in the plane, else 0xFF.
456 for (i = 0; i < 256; i++) {
457 if (i == symbol)
458 bytestream2_put_byte(pb, 0);
459 else
460 bytestream2_put_byte(pb, 0xFF);
463 /* Write zeroes for lengths */
464 for (i = 0; i < c->slices; i++)
465 bytestream2_put_le32(pb, 0);
467 /* And that's all for that plane folks */
468 return 0;
470 break;
474 /* Calculate huffman lengths */
475 if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
476 return ret;
479 * Write the plane's header into the output packet:
480 * - huffman code lengths (256 bytes)
481 * - slice end offsets (gotten from the slice lengths)
483 for (i = 0; i < 256; i++) {
484 bytestream2_put_byte(pb, lengths[i]);
486 he[i].len = lengths[i];
487 he[i].sym = i;
490 /* Calculate the huffman codes themselves */
491 calculate_codes(he);
493 send = 0;
494 for (i = 0; i < c->slices; i++) {
495 sstart = send;
496 send = height * (i + 1) / c->slices & cmask;
499 * Write the huffman codes to a buffer,
500 * get the offset in bytes.
502 offset += write_huff_codes(dst + sstart * width, c->slice_bits,
503 width * height + 4, width,
504 send - sstart, he);
506 slice_len = offset - slice_len;
508 /* Byteswap the written huffman codes */
509 c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
510 (uint32_t *) c->slice_bits,
511 slice_len >> 2);
513 /* Write the offset to the stream */
514 bytestream2_put_le32(pb, offset);
516 /* Seek to the data part of the packet */
517 bytestream2_seek_p(pb, 4 * (c->slices - i - 1) +
518 offset - slice_len, SEEK_CUR);
520 /* Write the slices' data into the output packet */
521 bytestream2_put_buffer(pb, c->slice_bits, slice_len);
523 /* Seek back to the slice offsets */
524 bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
525 SEEK_CUR);
527 slice_len = offset;
530 /* And at the end seek to the end of written slice(s) */
531 bytestream2_seek_p(pb, offset, SEEK_CUR);
533 return 0;
536 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
537 const AVFrame *pic, int *got_packet)
539 UtvideoContext *c = avctx->priv_data;
540 PutByteContext pb;
542 uint32_t frame_info;
544 uint8_t *dst;
546 int width = avctx->width, height = avctx->height;
547 int i, ret = 0;
549 /* Allocate a new packet if needed, and set it to the pointer dst */
550 ret = ff_alloc_packet(avctx, pkt, (256 + 4 * c->slices + width * height)
551 * c->planes + 4);
553 if (ret < 0)
554 return ret;
556 dst = pkt->data;
558 bytestream2_init_writer(&pb, dst, pkt->size);
560 av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
562 if (!c->slice_bits) {
563 av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
564 return AVERROR(ENOMEM);
567 /* In case of RGB, mangle the planes to Ut Video's format */
568 if (avctx->pix_fmt == AV_PIX_FMT_GBRAP || avctx->pix_fmt == AV_PIX_FMT_GBRP)
569 mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data,
570 c->planes, pic->linesize, width, height);
572 /* Deal with the planes */
573 switch (avctx->pix_fmt) {
574 case AV_PIX_FMT_GBRP:
575 case AV_PIX_FMT_GBRAP:
576 for (i = 0; i < c->planes; i++) {
577 ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
578 c->slice_buffer[i], c->slice_stride, i,
579 width, height, &pb);
581 if (ret) {
582 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
583 return ret;
586 break;
587 case AV_PIX_FMT_YUV444P:
588 for (i = 0; i < c->planes; i++) {
589 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
590 pic->linesize[i], i, width, height, &pb);
592 if (ret) {
593 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
594 return ret;
597 break;
598 case AV_PIX_FMT_YUV422P:
599 for (i = 0; i < c->planes; i++) {
600 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
601 pic->linesize[i], i, width >> !!i, height, &pb);
603 if (ret) {
604 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
605 return ret;
608 break;
609 case AV_PIX_FMT_YUV420P:
610 for (i = 0; i < c->planes; i++) {
611 ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
612 pic->linesize[i], i, width >> !!i, height >> !!i,
613 &pb);
615 if (ret) {
616 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
617 return ret;
620 break;
621 default:
622 av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
623 avctx->pix_fmt);
624 return AVERROR_INVALIDDATA;
628 * Write frame information (LE 32-bit unsigned)
629 * into the output packet.
630 * Contains the prediction method.
632 frame_info = c->frame_pred << 8;
633 bytestream2_put_le32(&pb, frame_info);
635 pkt->size = bytestream2_tell_p(&pb);
637 /* Packet should be done */
638 *got_packet = 1;
640 return 0;
643 #define OFFSET(x) offsetof(UtvideoContext, x)
644 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
645 static const AVOption options[] = {
646 { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, .unit = "pred" },
647 { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, .unit = "pred" },
648 { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, .unit = "pred" },
649 { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, .unit = "pred" },
650 { "median", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, .unit = "pred" },
652 { NULL},
655 static const AVClass utvideo_class = {
656 .class_name = "utvideo",
657 .item_name = av_default_item_name,
658 .option = options,
659 .version = LIBAVUTIL_VERSION_INT,
662 const FFCodec ff_utvideo_encoder = {
663 .p.name = "utvideo",
664 CODEC_LONG_NAME("Ut Video"),
665 .p.type = AVMEDIA_TYPE_VIDEO,
666 .p.id = AV_CODEC_ID_UTVIDEO,
667 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
668 AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
669 .priv_data_size = sizeof(UtvideoContext),
670 .p.priv_class = &utvideo_class,
671 .init = utvideo_encode_init,
672 FF_CODEC_ENCODE_CB(utvideo_encode_frame),
673 .close = utvideo_encode_close,
674 .p.pix_fmts = (const enum AVPixelFormat[]) {
675 AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP, AV_PIX_FMT_YUV422P,
676 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
678 .color_ranges = AVCOL_RANGE_MPEG,
679 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,