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