1/*
2 * Copyright (c) 1990 James Ashton - Sydney University
3 * Copyright (c) 2012 Stefano Sabatini
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 * X-Face encoder, based on libcompface, by James Ashton.
25 */
26
27#include "xface.h"
28#include "avcodec.h"
29#include "internal.h"
30
31typedef struct XFaceContext {
32    AVClass *class;
33    uint8_t bitmap[XFACE_PIXELS]; ///< image used internally for decoding
34    int max_line_len;             ///< max line length for compressed data
35    int set_header;               ///< set X-Face header in the output
36} XFaceContext;
37
38static int all_same(char *bitmap, int w, int h)
39{
40    char val, *row;
41    int x;
42
43    val = *bitmap;
44    while (h--) {
45        row = bitmap;
46        x = w;
47        while (x--)
48            if (*(row++) != val)
49                return 0;
50        bitmap += XFACE_WIDTH;
51    }
52    return 1;
53}
54
55static int all_black(char *bitmap, int w, int h)
56{
57    if (w > 3) {
58        w /= 2;
59        h /= 2;
60        return (all_black(bitmap, w, h) && all_black(bitmap + w, w, h) &&
61                all_black(bitmap + XFACE_WIDTH * h, w, h) &&
62                all_black(bitmap + XFACE_WIDTH * h + w, w, h));
63    } else {
64        /* at least one pixel in the 2x2 grid is non-zero */
65        return *bitmap || *(bitmap + 1) ||
66               *(bitmap + XFACE_WIDTH) || *(bitmap + XFACE_WIDTH + 1);
67    }
68}
69
70static int all_white(char *bitmap, int w, int h)
71{
72    return *bitmap == 0 && all_same(bitmap, w, h);
73}
74
75typedef struct {
76    const ProbRange *prob_ranges[XFACE_PIXELS*2];
77    int prob_ranges_idx;
78} ProbRangesQueue;
79
80static inline int pq_push(ProbRangesQueue *pq, const ProbRange *p)
81{
82    if (pq->prob_ranges_idx >= XFACE_PIXELS * 2 - 1)
83        return -1;
84    pq->prob_ranges[pq->prob_ranges_idx++] = p;
85    return 0;
86}
87
88static void push_greys(ProbRangesQueue *pq, char *bitmap, int w, int h)
89{
90    if (w > 3) {
91        w /= 2;
92        h /= 2;
93        push_greys(pq, bitmap,                       w, h);
94        push_greys(pq, bitmap + w,                   w, h);
95        push_greys(pq, bitmap + XFACE_WIDTH * h,     w, h);
96        push_greys(pq, bitmap + XFACE_WIDTH * h + w, w, h);
97    } else {
98        const ProbRange *p = ff_xface_probranges_2x2 +
99                 *bitmap +
100            2 * *(bitmap + 1) +
101            4 * *(bitmap + XFACE_WIDTH) +
102            8 * *(bitmap + XFACE_WIDTH + 1);
103        pq_push(pq, p);
104    }
105}
106
107static void encode_block(char *bitmap, int w, int h, int level, ProbRangesQueue *pq)
108{
109    if (all_white(bitmap, w, h)) {
110        pq_push(pq, &ff_xface_probranges_per_level[level][XFACE_COLOR_WHITE]);
111    } else if (all_black(bitmap, w, h)) {
112        pq_push(pq, &ff_xface_probranges_per_level[level][XFACE_COLOR_BLACK]);
113        push_greys(pq, bitmap, w, h);
114    } else {
115        pq_push(pq, &ff_xface_probranges_per_level[level][XFACE_COLOR_GREY]);
116        w /= 2;
117        h /= 2;
118        level++;
119        encode_block(bitmap,                       w, h, level, pq);
120        encode_block(bitmap + w,                   w, h, level, pq);
121        encode_block(bitmap + h * XFACE_WIDTH,     w, h, level, pq);
122        encode_block(bitmap + w + h * XFACE_WIDTH, w, h, level, pq);
123    }
124}
125
126static av_cold int xface_encode_init(AVCodecContext *avctx)
127{
128    avctx->coded_frame = av_frame_alloc();
129    if (!avctx->coded_frame)
130        return AVERROR(ENOMEM);
131    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
132
133    return 0;
134}
135
136static void push_integer(BigInt *b, const ProbRange *prange)
137{
138    uint8_t r;
139
140    ff_big_div(b, prange->range, &r);
141    ff_big_mul(b, 0);
142    ff_big_add(b, r + prange->offset);
143}
144
145static int xface_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
146                              const AVFrame *frame, int *got_packet)
147{
148    XFaceContext *xface = avctx->priv_data;
149    ProbRangesQueue pq = {{ 0 }, 0};
150    uint8_t bitmap_copy[XFACE_PIXELS];
151    BigInt b = {0};
152    int i, j, k, ret = 0;
153    const uint8_t *buf;
154    uint8_t *p;
155    char intbuf[XFACE_MAX_DIGITS];
156
157    if (avctx->width || avctx->height) {
158        if (avctx->width != XFACE_WIDTH || avctx->height != XFACE_HEIGHT) {
159            av_log(avctx, AV_LOG_ERROR,
160                   "Size value %dx%d not supported, only accepts a size of %dx%d\n",
161                   avctx->width, avctx->height, XFACE_WIDTH, XFACE_HEIGHT);
162            return AVERROR(EINVAL);
163        }
164    }
165    avctx->width  = XFACE_WIDTH;
166    avctx->height = XFACE_HEIGHT;
167
168    /* convert image from MONOWHITE to 1=black 0=white bitmap */
169    buf = frame->data[0];
170    i = j = 0;
171    do {
172        for (k = 0; k < 8; k++)
173            xface->bitmap[i++] = (buf[j]>>(7-k))&1;
174        if (++j == XFACE_WIDTH/8) {
175            buf += frame->linesize[0];
176            j = 0;
177        }
178    } while (i < XFACE_PIXELS);
179
180    /* create a copy of bitmap */
181    memcpy(bitmap_copy, xface->bitmap, XFACE_PIXELS);
182    ff_xface_generate_face(xface->bitmap, bitmap_copy);
183
184    encode_block(xface->bitmap,                         16, 16, 0, &pq);
185    encode_block(xface->bitmap + 16,                    16, 16, 0, &pq);
186    encode_block(xface->bitmap + 32,                    16, 16, 0, &pq);
187    encode_block(xface->bitmap + XFACE_WIDTH * 16,      16, 16, 0, &pq);
188    encode_block(xface->bitmap + XFACE_WIDTH * 16 + 16, 16, 16, 0, &pq);
189    encode_block(xface->bitmap + XFACE_WIDTH * 16 + 32, 16, 16, 0, &pq);
190    encode_block(xface->bitmap + XFACE_WIDTH * 32,      16, 16, 0, &pq);
191    encode_block(xface->bitmap + XFACE_WIDTH * 32 + 16, 16, 16, 0, &pq);
192    encode_block(xface->bitmap + XFACE_WIDTH * 32 + 32, 16, 16, 0, &pq);
193
194    while (pq.prob_ranges_idx > 0)
195        push_integer(&b, pq.prob_ranges[--pq.prob_ranges_idx]);
196
197    /* write the inverted big integer in b to intbuf */
198    i = 0;
199    while (b.nb_words) {
200        uint8_t r;
201        ff_big_div(&b, XFACE_PRINTS, &r);
202        intbuf[i++] = r + XFACE_FIRST_PRINT;
203    }
204
205    if ((ret = ff_alloc_packet2(avctx, pkt, i+2)) < 0)
206        return ret;
207
208    /* revert the number, and close the buffer */
209    p = pkt->data;
210    while (--i >= 0)
211        *(p++) = intbuf[i];
212    *(p++) = '\n';
213    *(p++) = 0;
214
215    pkt->flags |= AV_PKT_FLAG_KEY;
216    *got_packet = 1;
217
218    return 0;
219}
220
221static av_cold int xface_encode_close(AVCodecContext *avctx)
222{
223    av_freep(&avctx->coded_frame);
224
225    return 0;
226}
227
228AVCodec ff_xface_encoder = {
229    .name           = "xface",
230    .long_name      = NULL_IF_CONFIG_SMALL("X-face image"),
231    .type           = AVMEDIA_TYPE_VIDEO,
232    .id             = AV_CODEC_ID_XFACE,
233    .priv_data_size = sizeof(XFaceContext),
234    .init           = xface_encode_init,
235    .close          = xface_encode_close,
236    .encode2        = xface_encode_frame,
237    .pix_fmts       = (const enum PixelFormat[]) { AV_PIX_FMT_MONOWHITE, AV_PIX_FMT_NONE },
238};
239