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