1/*
2 * TIFF image encoder
3 * Copyright (c) 2007 Bartlomiej Wolowiec
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 * TIFF image encoder
24 * @file
25 * @author Bartlomiej Wolowiec
26 */
27#include "avcodec.h"
28#if CONFIG_ZLIB
29#include <zlib.h>
30#endif
31#include "bytestream.h"
32#include "tiff.h"
33#include "rle.h"
34#include "lzw.h"
35#include "put_bits.h"
36
37#define TIFF_MAX_ENTRY 32
38
39/** sizes of various TIFF field types (string size = 1)*/
40static const uint8_t type_sizes2[6] = {
41    0, 1, 1, 2, 4, 8
42};
43
44typedef struct TiffEncoderContext {
45    AVCodecContext *avctx;
46    AVFrame picture;
47
48    int width;                          ///< picture width
49    int height;                         ///< picture height
50    unsigned int bpp;                   ///< bits per pixel
51    int compr;                          ///< compression level
52    int bpp_tab_size;                   ///< bpp_tab size
53    int photometric_interpretation;     ///< photometric interpretation
54    int strips;                         ///< number of strips
55    int rps;                            ///< row per strip
56    uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header
57    int num_entries;                    ///< number of entires
58    uint8_t **buf;                      ///< actual position in buffer
59    uint8_t *buf_start;                 ///< pointer to first byte in buffer
60    int buf_size;                       ///< buffer size
61    uint16_t subsampling[2];            ///< YUV subsampling factors
62    struct LZWEncodeState *lzws;        ///< LZW Encode state
63} TiffEncoderContext;
64
65
66/**
67 * Check free space in buffer
68 * @param s Tiff context
69 * @param need Needed bytes
70 * @return 0 - ok, 1 - no free space
71 */
72inline static int check_size(TiffEncoderContext * s, uint64_t need)
73{
74    if (s->buf_size < *s->buf - s->buf_start + need) {
75        *s->buf = s->buf_start + s->buf_size + 1;
76        av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n");
77        return 1;
78    }
79    return 0;
80}
81
82/**
83 * Put n values to buffer
84 *
85 * @param p Pointer to pointer to output buffer
86 * @param n Number of values
87 * @param val Pointer to values
88 * @param type Type of values
89 * @param flip =0 - normal copy, >0 - flip
90 */
91static void tnput(uint8_t ** p, int n, const uint8_t * val, enum TiffTypes type,
92                  int flip)
93{
94    int i;
95#if HAVE_BIGENDIAN
96    flip ^= ((int[]) {0, 0, 0, 1, 3, 3})[type];
97#endif
98    for (i = 0; i < n * type_sizes2[type]; i++)
99        *(*p)++ = val[i ^ flip];
100}
101
102/**
103 * Add entry to directory in tiff header.
104 * @param s Tiff context
105 * @param tag Tag that identifies the entry
106 * @param type Entry type
107 * @param count The number of values
108 * @param ptr_val Pointer to values
109 */
110static void add_entry(TiffEncoderContext * s,
111                      enum TiffTags tag, enum TiffTypes type, int count,
112                      const void *ptr_val)
113{
114    uint8_t *entries_ptr = s->entries + 12 * s->num_entries;
115
116    assert(s->num_entries < TIFF_MAX_ENTRY);
117
118    bytestream_put_le16(&entries_ptr, tag);
119    bytestream_put_le16(&entries_ptr, type);
120    bytestream_put_le32(&entries_ptr, count);
121
122    if (type_sizes[type] * count <= 4) {
123        tnput(&entries_ptr, count, ptr_val, type, 0);
124    } else {
125        bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);
126        check_size(s, count * type_sizes2[type]);
127        tnput(s->buf, count, ptr_val, type, 0);
128    }
129
130    s->num_entries++;
131}
132
133static void add_entry1(TiffEncoderContext * s,
134                       enum TiffTags tag, enum TiffTypes type, int val){
135    uint16_t w = val;
136    uint32_t dw= val;
137    add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw);
138}
139
140/**
141 * Encode one strip in tiff file
142 *
143 * @param s Tiff context
144 * @param src Input buffer
145 * @param dst Output buffer
146 * @param n Size of input buffer
147 * @param compr Compression method
148 * @return Number of output bytes. If an output error is encountered, -1 returned
149 */
150static int encode_strip(TiffEncoderContext * s, const int8_t * src,
151                        uint8_t * dst, int n, int compr)
152{
153
154    switch (compr) {
155#if CONFIG_ZLIB
156    case TIFF_DEFLATE:
157    case TIFF_ADOBE_DEFLATE:
158        {
159            unsigned long zlen = s->buf_size - (*s->buf - s->buf_start);
160            if (compress(dst, &zlen, src, n) != Z_OK) {
161                av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n");
162                return -1;
163            }
164            return zlen;
165        }
166#endif
167    case TIFF_RAW:
168        if (check_size(s, n))
169            return -1;
170        memcpy(dst, src, n);
171        return n;
172    case TIFF_PACKBITS:
173        return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start), src, 1, n, 2, 0xff, -1, 0);
174    case TIFF_LZW:
175        return ff_lzw_encode(s->lzws, src, n);
176    default:
177        return -1;
178    }
179}
180
181static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum)
182{
183    AVFrame *p = &s->picture;
184    int i, j, k;
185    int w = (s->width - 1) / s->subsampling[0] + 1;
186    uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]];
187    uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]];
188    for (i = 0; i < w; i++){
189        for (j = 0; j < s->subsampling[1]; j++)
190            for (k = 0; k < s->subsampling[0]; k++)
191                *dst++ = p->data[0][(lnum + j) * p->linesize[0] +
192                                    i * s->subsampling[0] + k];
193        *dst++ = *pu++;
194        *dst++ = *pv++;
195    }
196}
197
198static int encode_frame(AVCodecContext * avctx, unsigned char *buf,
199                        int buf_size, void *data)
200{
201    TiffEncoderContext *s = avctx->priv_data;
202    AVFrame *pict = data;
203    AVFrame *const p = (AVFrame *) & s->picture;
204    int i;
205    int n;
206    uint8_t *ptr = buf;
207    uint8_t *offset;
208    uint32_t strips;
209    uint32_t *strip_sizes = NULL;
210    uint32_t *strip_offsets = NULL;
211    int bytes_per_row;
212    uint32_t res[2] = { 72, 1 };        // image resolution (72/1)
213    static const uint16_t bpp_tab[] = { 8, 8, 8, 8 };
214    int ret = -1;
215    int is_yuv = 0;
216    uint8_t *yuv_line = NULL;
217    int shift_h, shift_v;
218
219    s->buf_start = buf;
220    s->buf = &ptr;
221    s->buf_size = buf_size;
222
223    *p = *pict;
224    p->pict_type = FF_I_TYPE;
225    p->key_frame = 1;
226    avctx->coded_frame= &s->picture;
227
228    s->compr = TIFF_PACKBITS;
229    if (avctx->compression_level == 0) {
230        s->compr = TIFF_RAW;
231    } else if(avctx->compression_level == 2) {
232        s->compr = TIFF_LZW;
233#if CONFIG_ZLIB
234    } else if ((avctx->compression_level >= 3)) {
235        s->compr = TIFF_DEFLATE;
236#endif
237    }
238
239    s->width = avctx->width;
240    s->height = avctx->height;
241    s->subsampling[0] = 1;
242    s->subsampling[1] = 1;
243
244    switch (avctx->pix_fmt) {
245    case PIX_FMT_RGB24:
246        s->bpp = 24;
247        s->photometric_interpretation = 2;
248        break;
249    case PIX_FMT_GRAY8:
250        s->bpp = 8;
251        s->photometric_interpretation = 1;
252        break;
253    case PIX_FMT_PAL8:
254        s->bpp = 8;
255        s->photometric_interpretation = 3;
256        break;
257    case PIX_FMT_MONOBLACK:
258        s->bpp = 1;
259        s->photometric_interpretation = 1;
260        break;
261    case PIX_FMT_MONOWHITE:
262        s->bpp = 1;
263        s->photometric_interpretation = 0;
264        break;
265    case PIX_FMT_YUV420P:
266    case PIX_FMT_YUV422P:
267    case PIX_FMT_YUV444P:
268    case PIX_FMT_YUV410P:
269    case PIX_FMT_YUV411P:
270        s->photometric_interpretation = 6;
271        avcodec_get_chroma_sub_sample(avctx->pix_fmt,
272                &shift_h, &shift_v);
273        s->bpp = 8 + (16 >> (shift_h + shift_v));
274        s->subsampling[0] = 1 << shift_h;
275        s->subsampling[1] = 1 << shift_v;
276        s->bpp_tab_size = 3;
277        is_yuv = 1;
278        break;
279    default:
280        av_log(s->avctx, AV_LOG_ERROR,
281               "This colors format is not supported\n");
282        return -1;
283    }
284    if (!is_yuv)
285        s->bpp_tab_size = (s->bpp >> 3);
286
287    if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW)
288        //best choose for DEFLATE
289        s->rps = s->height;
290    else
291        s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1);     // suggest size of strip
292    s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up
293
294    strips = (s->height - 1) / s->rps + 1;
295
296    if (check_size(s, 8))
297        goto fail;
298
299    // write header
300    bytestream_put_le16(&ptr, 0x4949);
301    bytestream_put_le16(&ptr, 42);
302
303    offset = ptr;
304    bytestream_put_le32(&ptr, 0);
305
306    strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
307    strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
308
309    bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
310                    * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
311    if (is_yuv){
312        yuv_line = av_malloc(bytes_per_row);
313        if (yuv_line == NULL){
314            av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
315            goto fail;
316        }
317    }
318
319#if CONFIG_ZLIB
320    if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {
321        uint8_t *zbuf;
322        int zlen, zn;
323        int j;
324
325        zlen = bytes_per_row * s->rps;
326        zbuf = av_malloc(zlen);
327        strip_offsets[0] = ptr - buf;
328        zn = 0;
329        for (j = 0; j < s->rps; j++) {
330            if (is_yuv){
331                pack_yuv(s, yuv_line, j);
332                memcpy(zbuf + zn, yuv_line, bytes_per_row);
333                j += s->subsampling[1] - 1;
334            }
335            else
336                memcpy(zbuf + j * bytes_per_row,
337                       p->data[0] + j * p->linesize[0], bytes_per_row);
338            zn += bytes_per_row;
339        }
340        n = encode_strip(s, zbuf, ptr, zn, s->compr);
341        av_free(zbuf);
342        if (n<0) {
343            av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
344            goto fail;
345        }
346        ptr += n;
347        strip_sizes[0] = ptr - buf - strip_offsets[0];
348    } else
349#endif
350    {
351        if(s->compr == TIFF_LZW)
352            s->lzws = av_malloc(ff_lzw_encode_state_size);
353        for (i = 0; i < s->height; i++) {
354            if (strip_sizes[i / s->rps] == 0) {
355                if(s->compr == TIFF_LZW){
356                    ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start),
357                                       12, FF_LZW_TIFF, put_bits);
358                }
359                strip_offsets[i / s->rps] = ptr - buf;
360            }
361            if (is_yuv){
362                 pack_yuv(s, yuv_line, i);
363                 n = encode_strip(s, yuv_line, ptr, bytes_per_row, s->compr);
364                 i += s->subsampling[1] - 1;
365            }
366            else
367                n = encode_strip(s, p->data[0] + i * p->linesize[0],
368                        ptr, bytes_per_row, s->compr);
369            if (n < 0) {
370                av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n");
371                goto fail;
372            }
373            strip_sizes[i / s->rps] += n;
374            ptr += n;
375            if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){
376                int ret;
377                ret = ff_lzw_encode_flush(s->lzws, flush_put_bits);
378                strip_sizes[(i / s->rps )] += ret ;
379                ptr += ret;
380            }
381        }
382        if(s->compr == TIFF_LZW)
383            av_free(s->lzws);
384    }
385
386    s->num_entries = 0;
387
388    add_entry1(s,TIFF_SUBFILE,           TIFF_LONG,             0);
389    add_entry1(s,TIFF_WIDTH,             TIFF_LONG,             s->width);
390    add_entry1(s,TIFF_HEIGHT,            TIFF_LONG,             s->height);
391
392    if (s->bpp_tab_size)
393    add_entry(s, TIFF_BPP,               TIFF_SHORT,    s->bpp_tab_size, bpp_tab);
394
395    add_entry1(s,TIFF_COMPR,             TIFF_SHORT,            s->compr);
396    add_entry1(s,TIFF_INVERT,            TIFF_SHORT,            s->photometric_interpretation);
397    add_entry(s, TIFF_STRIP_OFFS,        TIFF_LONG,     strips, strip_offsets);
398
399    if (s->bpp_tab_size)
400    add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT,            s->bpp_tab_size);
401
402    add_entry1(s,TIFF_ROWSPERSTRIP,      TIFF_LONG,             s->rps);
403    add_entry(s, TIFF_STRIP_SIZE,        TIFF_LONG,     strips, strip_sizes);
404    add_entry(s, TIFF_XRES,              TIFF_RATIONAL, 1,      res);
405    add_entry(s, TIFF_YRES,              TIFF_RATIONAL, 1,      res);
406    add_entry1(s,TIFF_RES_UNIT,          TIFF_SHORT,            2);
407
408    if(!(avctx->flags & CODEC_FLAG_BITEXACT))
409    add_entry(s, TIFF_SOFTWARE_NAME,     TIFF_STRING,
410              strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT);
411
412    if (avctx->pix_fmt == PIX_FMT_PAL8) {
413        uint16_t pal[256 * 3];
414        for (i = 0; i < 256; i++) {
415            uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4);
416            pal[i]       = ((rgb >> 16) & 0xff) * 257;
417            pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257;
418            pal[i + 512] = ( rgb        & 0xff) * 257;
419        }
420        add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal);
421    }
422    if (is_yuv){
423        /** according to CCIR Recommendation 601.1 */
424        uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1};
425        add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT,    2, s->subsampling);
426        add_entry(s, TIFF_REFERENCE_BW,      TIFF_RATIONAL, 6, refbw);
427    }
428    bytestream_put_le32(&offset, ptr - buf);    // write offset to dir
429
430    if (check_size(s, 6 + s->num_entries * 12))
431        goto fail;
432    bytestream_put_le16(&ptr, s->num_entries);  // write tag count
433    bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12);
434    bytestream_put_le32(&ptr, 0);
435
436    ret = ptr - buf;
437
438fail:
439    av_free(strip_sizes);
440    av_free(strip_offsets);
441    av_free(yuv_line);
442    return ret;
443}
444
445AVCodec tiff_encoder = {
446    "tiff",
447    AVMEDIA_TYPE_VIDEO,
448    CODEC_ID_TIFF,
449    sizeof(TiffEncoderContext),
450    NULL,
451    encode_frame,
452    NULL,
453    NULL,
454    0,
455    NULL,
456    .pix_fmts =
457        (const enum PixelFormat[]) {PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8,
458                              PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE,
459                              PIX_FMT_YUV420P, PIX_FMT_YUV422P,
460                              PIX_FMT_YUV444P, PIX_FMT_YUV410P,
461                              PIX_FMT_YUV411P,
462                              PIX_FMT_NONE},
463    .long_name = NULL_IF_CONFIG_SMALL("TIFF image"),
464};
465