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