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