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