]> git.sesse.net Git - ffmpeg/blob - libavcodec/utvideoenc.c
avcodec: Constify AVCodecs
[ffmpeg] / libavcodec / utvideoenc.c
1 /*
2  * Ut Video encoder
3  * Copyright (c) 2012 Jan Ekström
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * Ut Video encoder
25  */
26
27 #include "libavutil/imgutils.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/opt.h"
30
31 #include "avcodec.h"
32 #include "internal.h"
33 #include "bswapdsp.h"
34 #include "bytestream.h"
35 #include "put_bits.h"
36 #include "mathops.h"
37 #include "utvideo.h"
38 #include "huffman.h"
39
40 typedef struct HuffEntry {
41     uint16_t sym;
42     uint8_t  len;
43     uint32_t code;
44 } HuffEntry;
45
46 /* Compare huffman tree nodes */
47 static int ut_huff_cmp_len(const void *a, const void *b)
48 {
49     const HuffEntry *aa = a, *bb = b;
50     return (aa->len - bb->len)*256 + aa->sym - bb->sym;
51 }
52
53 /* Compare huffentry symbols */
54 static int huff_cmp_sym(const void *a, const void *b)
55 {
56     const HuffEntry *aa = a, *bb = b;
57     return aa->sym - bb->sym;
58 }
59
60 static av_cold int utvideo_encode_close(AVCodecContext *avctx)
61 {
62     UtvideoContext *c = avctx->priv_data;
63     int i;
64
65     av_freep(&c->slice_bits);
66     for (i = 0; i < 4; i++)
67         av_freep(&c->slice_buffer[i]);
68
69     return 0;
70 }
71
72 static av_cold int utvideo_encode_init(AVCodecContext *avctx)
73 {
74     UtvideoContext *c = avctx->priv_data;
75     int i, subsampled_height;
76     uint32_t original_format;
77
78     c->avctx           = avctx;
79     c->frame_info_size = 4;
80     c->slice_stride    = FFALIGN(avctx->width, 32);
81
82     switch (avctx->pix_fmt) {
83     case AV_PIX_FMT_GBRP:
84         c->planes        = 3;
85         avctx->codec_tag = MKTAG('U', 'L', 'R', 'G');
86         original_format  = UTVIDEO_RGB;
87         break;
88     case AV_PIX_FMT_GBRAP:
89         c->planes        = 4;
90         avctx->codec_tag = MKTAG('U', 'L', 'R', 'A');
91         original_format  = UTVIDEO_RGBA;
92         avctx->bits_per_coded_sample = 32;
93         break;
94     case AV_PIX_FMT_YUV420P:
95         if (avctx->width & 1 || avctx->height & 1) {
96             av_log(avctx, AV_LOG_ERROR,
97                    "4:2:0 video requires even width and height.\n");
98             return AVERROR_INVALIDDATA;
99         }
100         c->planes        = 3;
101         if (avctx->colorspace == AVCOL_SPC_BT709)
102             avctx->codec_tag = MKTAG('U', 'L', 'H', '0');
103         else
104             avctx->codec_tag = MKTAG('U', 'L', 'Y', '0');
105         original_format  = UTVIDEO_420;
106         break;
107     case AV_PIX_FMT_YUV422P:
108         if (avctx->width & 1) {
109             av_log(avctx, AV_LOG_ERROR,
110                    "4:2:2 video requires even width.\n");
111             return AVERROR_INVALIDDATA;
112         }
113         c->planes        = 3;
114         if (avctx->colorspace == AVCOL_SPC_BT709)
115             avctx->codec_tag = MKTAG('U', 'L', 'H', '2');
116         else
117             avctx->codec_tag = MKTAG('U', 'L', 'Y', '2');
118         original_format  = UTVIDEO_422;
119         break;
120     case AV_PIX_FMT_YUV444P:
121         c->planes        = 3;
122         if (avctx->colorspace == AVCOL_SPC_BT709)
123             avctx->codec_tag = MKTAG('U', 'L', 'H', '4');
124         else
125             avctx->codec_tag = MKTAG('U', 'L', 'Y', '4');
126         original_format  = UTVIDEO_444;
127         break;
128     default:
129         av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
130                avctx->pix_fmt);
131         return AVERROR_INVALIDDATA;
132     }
133
134     ff_bswapdsp_init(&c->bdsp);
135     ff_llvidencdsp_init(&c->llvidencdsp);
136
137     if (c->frame_pred == PRED_GRADIENT) {
138         av_log(avctx, AV_LOG_ERROR, "Gradient prediction is not supported.\n");
139         return AVERROR_OPTION_NOT_FOUND;
140     }
141
142     /*
143      * Check the asked slice count for obviously invalid
144      * values (> 256 or negative).
145      */
146     if (avctx->slices > 256 || avctx->slices < 0) {
147         av_log(avctx, AV_LOG_ERROR,
148                "Slice count %d is not supported in Ut Video (theoretical range is 0-256).\n",
149                avctx->slices);
150         return AVERROR(EINVAL);
151     }
152
153     /* Check that the slice count is not larger than the subsampled height */
154     subsampled_height = avctx->height >> av_pix_fmt_desc_get(avctx->pix_fmt)->log2_chroma_h;
155     if (avctx->slices > subsampled_height) {
156         av_log(avctx, AV_LOG_ERROR,
157                "Slice count %d is larger than the subsampling-applied height %d.\n",
158                avctx->slices, subsampled_height);
159         return AVERROR(EINVAL);
160     }
161
162     /* extradata size is 4 * 32 bits */
163     avctx->extradata_size = 16;
164
165     avctx->extradata = av_mallocz(avctx->extradata_size +
166                                   AV_INPUT_BUFFER_PADDING_SIZE);
167
168     if (!avctx->extradata) {
169         av_log(avctx, AV_LOG_ERROR, "Could not allocate extradata.\n");
170         utvideo_encode_close(avctx);
171         return AVERROR(ENOMEM);
172     }
173
174     for (i = 0; i < c->planes; i++) {
175         c->slice_buffer[i] = av_malloc(c->slice_stride * (avctx->height + 2) +
176                                        AV_INPUT_BUFFER_PADDING_SIZE);
177         if (!c->slice_buffer[i]) {
178             av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 1.\n");
179             utvideo_encode_close(avctx);
180             return AVERROR(ENOMEM);
181         }
182     }
183
184     /*
185      * Set the version of the encoder.
186      * Last byte is "implementation ID", which is
187      * obtained from the creator of the format.
188      * Libavcodec has been assigned with the ID 0xF0.
189      */
190     AV_WB32(avctx->extradata, MKTAG(1, 0, 0, 0xF0));
191
192     /*
193      * Set the "original format"
194      * Not used for anything during decoding.
195      */
196     AV_WL32(avctx->extradata + 4, original_format);
197
198     /* Write 4 as the 'frame info size' */
199     AV_WL32(avctx->extradata + 8, c->frame_info_size);
200
201     /*
202      * Set how many slices are going to be used.
203      * By default uses multiple slices depending on the subsampled height.
204      * This enables multithreading in the official decoder.
205      */
206     if (!avctx->slices) {
207         c->slices = subsampled_height / 120;
208
209         if (!c->slices)
210             c->slices = 1;
211         else if (c->slices > 256)
212             c->slices = 256;
213     } else {
214         c->slices = avctx->slices;
215     }
216
217     /* Set compression mode */
218     c->compression = COMP_HUFF;
219
220     /*
221      * Set the encoding flags:
222      * - Slice count minus 1
223      * - Interlaced encoding mode flag, set to zero for now.
224      * - Compression mode (none/huff)
225      * And write the flags.
226      */
227     c->flags  = (c->slices - 1) << 24;
228     c->flags |= 0 << 11; // bit field to signal interlaced encoding mode
229     c->flags |= c->compression;
230
231     AV_WL32(avctx->extradata + 12, c->flags);
232
233     return 0;
234 }
235
236 static void mangle_rgb_planes(uint8_t *dst[4], ptrdiff_t dst_stride,
237                               uint8_t *const src[4], int planes, const int stride[4],
238                               int width, int height)
239 {
240     int i, j;
241     int k = 2 * dst_stride;
242     const uint8_t *sg = src[0];
243     const uint8_t *sb = src[1];
244     const uint8_t *sr = src[2];
245     const uint8_t *sa = src[3];
246     unsigned int g;
247
248     for (j = 0; j < height; j++) {
249         if (planes == 3) {
250             for (i = 0; i < width; i++) {
251                 g         = sg[i];
252                 dst[0][k] = g;
253                 g        += 0x80;
254                 dst[1][k] = sb[i] - g;
255                 dst[2][k] = sr[i] - g;
256                 k++;
257             }
258         } else {
259             for (i = 0; i < width; i++) {
260                 g         = sg[i];
261                 dst[0][k] = g;
262                 g        += 0x80;
263                 dst[1][k] = sb[i] - g;
264                 dst[2][k] = sr[i] - g;
265                 dst[3][k] = sa[i];
266                 k++;
267             }
268             sa += stride[3];
269         }
270         k += dst_stride - width;
271         sg += stride[0];
272         sb += stride[1];
273         sr += stride[2];
274     }
275 }
276
277 #undef A
278 #undef B
279
280 /* Write data to a plane with median prediction */
281 static void median_predict(UtvideoContext *c, uint8_t *src, uint8_t *dst,
282                            ptrdiff_t stride, int width, int height)
283 {
284     int i, j;
285     int A, B;
286     uint8_t prev;
287
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;
292         prev   = src[i];
293     }
294
295     if (height == 1)
296         return;
297
298     src += stride;
299
300     /*
301      * Second line uses top prediction for the first sample,
302      * and median for the rest.
303      */
304     A = B = 0;
305
306     /* Rest of the coded part uses median prediction */
307     for (j = 1; j < height; j++) {
308         c->llvidencdsp.sub_median_pred(dst, src - stride, src, width, &A, &B);
309         dst += width;
310         src += stride;
311     }
312 }
313
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)
317 {
318     int i, j;
319
320     for (j = 0; j < height; j++) {
321         for (i = 0; i < width; i++) {
322             counts[src[i]]++;
323         }
324         src += width;
325     }
326 }
327
328 /* Calculate the actual huffman codes from the code lengths */
329 static void calculate_codes(HuffEntry *he)
330 {
331     int last, i;
332     uint32_t code;
333
334     qsort(he, 256, sizeof(*he), ut_huff_cmp_len);
335
336     last = 255;
337     while (he[last].len == 255 && last)
338         last--;
339
340     code = 0;
341     for (i = last; i >= 0; i--) {
342         he[i].code  = code >> (32 - he[i].len);
343         code       += 0x80000000u >> (he[i].len - 1);
344     }
345
346     qsort(he, 256, sizeof(*he), huff_cmp_sym);
347 }
348
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)
352 {
353     PutBitContext pb;
354     int i, j;
355     int count;
356
357     init_put_bits(&pb, dst, dst_size);
358
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);
363
364         src += width;
365     }
366
367     /* Pad output to a 32-bit boundary */
368     count = put_bits_count(&pb) & 0x1F;
369
370     if (count)
371         put_bits(&pb, 32 - count, 0);
372
373     /* Flush the rest with zeroes */
374     flush_put_bits(&pb);
375
376     /* Return the amount of bytes written */
377     return put_bytes_output(&pb);
378 }
379
380 static int encode_plane(AVCodecContext *avctx, uint8_t *src,
381                         uint8_t *dst, ptrdiff_t stride, int plane_no,
382                         int width, int height, PutByteContext *pb)
383 {
384     UtvideoContext *c        = avctx->priv_data;
385     uint8_t  lengths[256];
386     uint64_t counts[256]     = { 0 };
387
388     HuffEntry he[256];
389
390     uint32_t offset = 0, slice_len = 0;
391     const int cmask = ~(!plane_no && avctx->pix_fmt == AV_PIX_FMT_YUV420P);
392     int      i, sstart, send = 0;
393     int      symbol;
394     int      ret;
395
396     /* Do prediction / make planes */
397     switch (c->frame_pred) {
398     case PRED_NONE:
399         for (i = 0; i < c->slices; i++) {
400             sstart = send;
401             send   = height * (i + 1) / c->slices & cmask;
402             av_image_copy_plane(dst + sstart * width, width,
403                                 src + sstart * stride, stride,
404                                 width, send - sstart);
405         }
406         break;
407     case PRED_LEFT:
408         for (i = 0; i < c->slices; i++) {
409             sstart = send;
410             send   = height * (i + 1) / c->slices & cmask;
411             c->llvidencdsp.sub_left_predict(dst + sstart * width, src + sstart * stride, stride, width, send - sstart);
412         }
413         break;
414     case PRED_MEDIAN:
415         for (i = 0; i < c->slices; i++) {
416             sstart = send;
417             send   = height * (i + 1) / c->slices & cmask;
418             median_predict(c, src + sstart * stride, dst + sstart * width,
419                            stride, width, send - sstart);
420         }
421         break;
422     default:
423         av_log(avctx, AV_LOG_ERROR, "Unknown prediction mode: %d\n",
424                c->frame_pred);
425         return AVERROR_OPTION_NOT_FOUND;
426     }
427
428     /* Count the usage of values */
429     count_usage(dst, width, height, counts);
430
431     /* Check for a special case where only one symbol was used */
432     for (symbol = 0; symbol < 256; symbol++) {
433         /* If non-zero count is found, see if it matches width * height */
434         if (counts[symbol]) {
435             /* Special case if only one symbol was used */
436             if (counts[symbol] == width * (int64_t)height) {
437                 /*
438                  * Write a zero for the single symbol
439                  * used in the plane, else 0xFF.
440                  */
441                 for (i = 0; i < 256; i++) {
442                     if (i == symbol)
443                         bytestream2_put_byte(pb, 0);
444                     else
445                         bytestream2_put_byte(pb, 0xFF);
446                 }
447
448                 /* Write zeroes for lengths */
449                 for (i = 0; i < c->slices; i++)
450                     bytestream2_put_le32(pb, 0);
451
452                 /* And that's all for that plane folks */
453                 return 0;
454             }
455             break;
456         }
457     }
458
459     /* Calculate huffman lengths */
460     if ((ret = ff_huff_gen_len_table(lengths, counts, 256, 1)) < 0)
461         return ret;
462
463     /*
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)
467      */
468     for (i = 0; i < 256; i++) {
469         bytestream2_put_byte(pb, lengths[i]);
470
471         he[i].len = lengths[i];
472         he[i].sym = i;
473     }
474
475     /* Calculate the huffman codes themselves */
476     calculate_codes(he);
477
478     send = 0;
479     for (i = 0; i < c->slices; i++) {
480         sstart  = send;
481         send    = height * (i + 1) / c->slices & cmask;
482
483         /*
484          * Write the huffman codes to a buffer,
485          * get the offset in bytes.
486          */
487         offset += write_huff_codes(dst + sstart * width, c->slice_bits,
488                                    width * height + 4, width,
489                                    send - sstart, he);
490
491         slice_len = offset - slice_len;
492
493         /* Byteswap the written huffman codes */
494         c->bdsp.bswap_buf((uint32_t *) c->slice_bits,
495                           (uint32_t *) c->slice_bits,
496                           slice_len >> 2);
497
498         /* Write the offset to the stream */
499         bytestream2_put_le32(pb, offset);
500
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);
504
505         /* Write the slices' data into the output packet */
506         bytestream2_put_buffer(pb, c->slice_bits, slice_len);
507
508         /* Seek back to the slice offsets */
509         bytestream2_seek_p(pb, -4 * (c->slices - i - 1) - offset,
510                            SEEK_CUR);
511
512         slice_len = offset;
513     }
514
515     /* And at the end seek to the end of written slice(s) */
516     bytestream2_seek_p(pb, offset, SEEK_CUR);
517
518     return 0;
519 }
520
521 static int utvideo_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
522                                 const AVFrame *pic, int *got_packet)
523 {
524     UtvideoContext *c = avctx->priv_data;
525     PutByteContext pb;
526
527     uint32_t frame_info;
528
529     uint8_t *dst;
530
531     int width = avctx->width, height = avctx->height;
532     int i, ret = 0;
533
534     /* Allocate a new packet if needed, and set it to the pointer dst */
535     ret = ff_alloc_packet2(avctx, pkt, (256 + 4 * c->slices + width * height) *
536                            c->planes + 4, 0);
537
538     if (ret < 0)
539         return ret;
540
541     dst = pkt->data;
542
543     bytestream2_init_writer(&pb, dst, pkt->size);
544
545     av_fast_padded_malloc(&c->slice_bits, &c->slice_bits_size, width * height + 4);
546
547     if (!c->slice_bits) {
548         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer 2.\n");
549         return AVERROR(ENOMEM);
550     }
551
552     /* In case of RGB, mangle the planes to Ut Video's format */
553     if (avctx->pix_fmt == AV_PIX_FMT_GBRAP || avctx->pix_fmt == AV_PIX_FMT_GBRP)
554         mangle_rgb_planes(c->slice_buffer, c->slice_stride, pic->data,
555                           c->planes, pic->linesize, width, height);
556
557     /* Deal with the planes */
558     switch (avctx->pix_fmt) {
559     case AV_PIX_FMT_GBRP:
560     case AV_PIX_FMT_GBRAP:
561         for (i = 0; i < c->planes; i++) {
562             ret = encode_plane(avctx, c->slice_buffer[i] + 2 * c->slice_stride,
563                                c->slice_buffer[i], c->slice_stride, i,
564                                width, height, &pb);
565
566             if (ret) {
567                 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
568                 return ret;
569             }
570         }
571         break;
572     case AV_PIX_FMT_YUV444P:
573         for (i = 0; i < c->planes; i++) {
574             ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
575                                pic->linesize[i], i, width, height, &pb);
576
577             if (ret) {
578                 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
579                 return ret;
580             }
581         }
582         break;
583     case AV_PIX_FMT_YUV422P:
584         for (i = 0; i < c->planes; i++) {
585             ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
586                                pic->linesize[i], i, width >> !!i, height, &pb);
587
588             if (ret) {
589                 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
590                 return ret;
591             }
592         }
593         break;
594     case AV_PIX_FMT_YUV420P:
595         for (i = 0; i < c->planes; i++) {
596             ret = encode_plane(avctx, pic->data[i], c->slice_buffer[0],
597                                pic->linesize[i], i, width >> !!i, height >> !!i,
598                                &pb);
599
600             if (ret) {
601                 av_log(avctx, AV_LOG_ERROR, "Error encoding plane %d.\n", i);
602                 return ret;
603             }
604         }
605         break;
606     default:
607         av_log(avctx, AV_LOG_ERROR, "Unknown pixel format: %d\n",
608                avctx->pix_fmt);
609         return AVERROR_INVALIDDATA;
610     }
611
612     /*
613      * Write frame information (LE 32-bit unsigned)
614      * into the output packet.
615      * Contains the prediction method.
616      */
617     frame_info = c->frame_pred << 8;
618     bytestream2_put_le32(&pb, frame_info);
619
620     /*
621      * At least currently Ut Video is IDR only.
622      * Set flags accordingly.
623      */
624     pkt->flags |= AV_PKT_FLAG_KEY;
625     pkt->size   = bytestream2_tell_p(&pb);
626
627     /* Packet should be done */
628     *got_packet = 1;
629
630     return 0;
631 }
632
633 #define OFFSET(x) offsetof(UtvideoContext, x)
634 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
635 static const AVOption options[] = {
636 { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, { .i64 = PRED_LEFT }, PRED_NONE, PRED_MEDIAN, VE, "pred" },
637     { "none",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_NONE }, INT_MIN, INT_MAX, VE, "pred" },
638     { "left",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_LEFT }, INT_MIN, INT_MAX, VE, "pred" },
639     { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_GRADIENT }, INT_MIN, INT_MAX, VE, "pred" },
640     { "median",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PRED_MEDIAN }, INT_MIN, INT_MAX, VE, "pred" },
641
642     { NULL},
643 };
644
645 static const AVClass utvideo_class = {
646     .class_name = "utvideo",
647     .item_name  = av_default_item_name,
648     .option     = options,
649     .version    = LIBAVUTIL_VERSION_INT,
650 };
651
652 const AVCodec ff_utvideo_encoder = {
653     .name           = "utvideo",
654     .long_name      = NULL_IF_CONFIG_SMALL("Ut Video"),
655     .type           = AVMEDIA_TYPE_VIDEO,
656     .id             = AV_CODEC_ID_UTVIDEO,
657     .priv_data_size = sizeof(UtvideoContext),
658     .priv_class     = &utvideo_class,
659     .init           = utvideo_encode_init,
660     .encode2        = utvideo_encode_frame,
661     .close          = utvideo_encode_close,
662     .capabilities   = AV_CODEC_CAP_FRAME_THREADS,
663     .pix_fmts       = (const enum AVPixelFormat[]) {
664                           AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP, AV_PIX_FMT_YUV422P,
665                           AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_NONE
666                       },
667 };