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