1/*
2 * lossless JPEG shared bits
3 * Copyright (c) 2000, 2001 Fabrice Bellard
4 * Copyright (c) 2003 Alex Beregszaszi
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include <stdint.h>
24#include <string.h>
25
26#include "libavutil/pixdesc.h"
27#include "libavutil/pixfmt.h"
28
29#include "avcodec.h"
30#include "idctdsp.h"
31#include "jpegtables.h"
32#include "put_bits.h"
33#include "mjpegenc.h"
34#include "mjpegenc_common.h"
35#include "mjpeg.h"
36#include "version.h"
37
38/* table_class: 0 = DC coef, 1 = AC coefs */
39static int put_huffman_table(PutBitContext *p, int table_class, int table_id,
40                             const uint8_t *bits_table, const uint8_t *value_table)
41{
42    int n, i;
43
44    put_bits(p, 4, table_class);
45    put_bits(p, 4, table_id);
46
47    n = 0;
48    for(i=1;i<=16;i++) {
49        n += bits_table[i];
50        put_bits(p, 8, bits_table[i]);
51    }
52
53    for(i=0;i<n;i++)
54        put_bits(p, 8, value_table[i]);
55
56    return n + 17;
57}
58
59static void jpeg_table_header(AVCodecContext *avctx, PutBitContext *p,
60                              MJpegContext *m,
61                              ScanTable *intra_scantable,
62                              uint16_t luma_intra_matrix[64],
63                              uint16_t chroma_intra_matrix[64],
64                              int hsample[3], int use_slices)
65{
66    int i, j, size;
67    uint8_t *ptr;
68
69    if (m) {
70        int matrix_count = 1 + !!memcmp(luma_intra_matrix,
71                                        chroma_intra_matrix,
72                                        sizeof(luma_intra_matrix[0]) * 64);
73        if (m->force_duplicated_matrix)
74            matrix_count = 2;
75        /* quant matrixes */
76        put_marker(p, DQT);
77        put_bits(p, 16, 2 + matrix_count * (1 + 64));
78        put_bits(p, 4, 0); /* 8 bit precision */
79        put_bits(p, 4, 0); /* table 0 */
80        for (int i = 0; i < 64; i++) {
81            uint8_t j = intra_scantable->permutated[i];
82            put_bits(p, 8, luma_intra_matrix[j]);
83        }
84
85        if (matrix_count > 1) {
86            put_bits(p, 4, 0); /* 8 bit precision */
87            put_bits(p, 4, 1); /* table 1 */
88            for(i=0;i<64;i++) {
89                j = intra_scantable->permutated[i];
90                put_bits(p, 8, chroma_intra_matrix[j]);
91            }
92        }
93    }
94
95    if (use_slices) {
96        put_marker(p, DRI);
97        put_bits(p, 16, 4);
98        put_bits(p, 16, (avctx->width-1)/(8*hsample[0]) + 1);
99    }
100
101    /* huffman table */
102    put_marker(p, DHT);
103    flush_put_bits(p);
104    ptr = put_bits_ptr(p);
105    put_bits(p, 16, 0); /* patched later */
106    size = 2;
107
108    // Only MJPEG can have a variable Huffman variable. All other
109    // formats use the default Huffman table.
110    if (m && m->huffman == HUFFMAN_TABLE_OPTIMAL) {
111        size += put_huffman_table(p, 0, 0, m->bits_dc_luminance,
112                                  m->val_dc_luminance);
113        size += put_huffman_table(p, 0, 1, m->bits_dc_chrominance,
114                                  m->val_dc_chrominance);
115
116        size += put_huffman_table(p, 1, 0, m->bits_ac_luminance,
117                                  m->val_ac_luminance);
118        size += put_huffman_table(p, 1, 1, m->bits_ac_chrominance,
119                                  m->val_ac_chrominance);
120    } else {
121        size += put_huffman_table(p, 0, 0, ff_mjpeg_bits_dc_luminance,
122                                  ff_mjpeg_val_dc);
123        size += put_huffman_table(p, 0, 1, ff_mjpeg_bits_dc_chrominance,
124                                  ff_mjpeg_val_dc);
125
126        size += put_huffman_table(p, 1, 0, ff_mjpeg_bits_ac_luminance,
127                                  ff_mjpeg_val_ac_luminance);
128        size += put_huffman_table(p, 1, 1, ff_mjpeg_bits_ac_chrominance,
129                                  ff_mjpeg_val_ac_chrominance);
130    }
131    AV_WB16(ptr, size);
132}
133
134enum {
135    ICC_HDR_SIZE    = 16, /* ICC_PROFILE\0 tag + 4 bytes */
136    ICC_CHUNK_SIZE  = UINT16_MAX - ICC_HDR_SIZE,
137    ICC_MAX_CHUNKS  = UINT8_MAX,
138};
139
140int ff_mjpeg_add_icc_profile_size(AVCodecContext *avctx, const AVFrame *frame,
141                                  size_t *max_pkt_size)
142{
143    const AVFrameSideData *sd;
144    size_t new_pkt_size;
145    int nb_chunks;
146    sd = av_frame_get_side_data(frame, AV_FRAME_DATA_ICC_PROFILE);
147    if (!sd || !sd->size)
148        return 0;
149
150    if (sd->size > ICC_MAX_CHUNKS * ICC_CHUNK_SIZE) {
151        av_log(avctx, AV_LOG_ERROR, "Cannot store %"SIZE_SPECIFIER" byte ICC "
152               "profile: too large for JPEG\n",
153               sd->size);
154        return AVERROR_INVALIDDATA;
155    }
156
157    nb_chunks = (sd->size + ICC_CHUNK_SIZE - 1) / ICC_CHUNK_SIZE;
158    new_pkt_size = *max_pkt_size + nb_chunks * (UINT16_MAX + 2 /* APP2 marker */);
159    if (new_pkt_size < *max_pkt_size) /* overflow */
160        return AVERROR_INVALIDDATA;
161    *max_pkt_size = new_pkt_size;
162    return 0;
163}
164
165static void jpeg_put_comments(AVCodecContext *avctx, PutBitContext *p,
166                              const AVFrame *frame)
167{
168    const AVFrameSideData *sd = NULL;
169    int size;
170    uint8_t *ptr;
171
172    if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
173        AVRational sar = avctx->sample_aspect_ratio;
174
175        if (sar.num > 65535 || sar.den > 65535) {
176            if (!av_reduce(&sar.num, &sar.den, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 65535))
177                av_log(avctx, AV_LOG_WARNING,
178                    "Cannot store exact aspect ratio %d:%d\n",
179                    avctx->sample_aspect_ratio.num,
180                    avctx->sample_aspect_ratio.den);
181        }
182
183        /* JFIF header */
184        put_marker(p, APP0);
185        put_bits(p, 16, 16);
186        ff_put_string(p, "JFIF", 1); /* this puts the trailing zero-byte too */
187        /* The most significant byte is used for major revisions, the least
188         * significant byte for minor revisions. Version 1.02 is the current
189         * released revision. */
190        put_bits(p, 16, 0x0102);
191        put_bits(p,  8, 0);              /* units type: 0 - aspect ratio */
192        put_bits(p, 16, sar.num);
193        put_bits(p, 16, sar.den);
194        put_bits(p, 8, 0); /* thumbnail width */
195        put_bits(p, 8, 0); /* thumbnail height */
196    }
197
198    /* ICC profile */
199    sd = av_frame_get_side_data(frame, AV_FRAME_DATA_ICC_PROFILE);
200    if (sd && sd->size) {
201        const int nb_chunks = (sd->size + ICC_CHUNK_SIZE - 1) / ICC_CHUNK_SIZE;
202        const uint8_t *data = sd->data;
203        size_t remaining = sd->size;
204        /* must already be checked by the packat allocation code */
205        av_assert0(remaining <= ICC_MAX_CHUNKS * ICC_CHUNK_SIZE);
206        flush_put_bits(p);
207        for (int i = 0; i < nb_chunks; i++) {
208            size = FFMIN(remaining, ICC_CHUNK_SIZE);
209            av_assert1(size > 0);
210            ptr = put_bits_ptr(p);
211            ptr[0] = 0xff; /* chunk marker, not part of ICC_HDR_SIZE */
212            ptr[1] = APP2;
213            AV_WB16(ptr+2, size + ICC_HDR_SIZE);
214            AV_WL32(ptr+4,  MKTAG('I','C','C','_'));
215            AV_WL32(ptr+8,  MKTAG('P','R','O','F'));
216            AV_WL32(ptr+12, MKTAG('I','L','E','\0'));
217            ptr[16] = i+1;
218            ptr[17] = nb_chunks;
219            memcpy(&ptr[18], data, size);
220            skip_put_bytes(p, size + ICC_HDR_SIZE + 2);
221            remaining -= size;
222            data += size;
223        }
224        av_assert1(!remaining);
225    }
226
227    /* comment */
228    if (!(avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
229        put_marker(p, COM);
230        flush_put_bits(p);
231        ptr = put_bits_ptr(p);
232        put_bits(p, 16, 0); /* patched later */
233        ff_put_string(p, LIBAVCODEC_IDENT, 1);
234        size = strlen(LIBAVCODEC_IDENT)+3;
235        AV_WB16(ptr, size);
236    }
237
238    if (((avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
239          avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
240          avctx->pix_fmt == AV_PIX_FMT_YUV444P) && avctx->color_range != AVCOL_RANGE_JPEG)
241        || avctx->color_range == AVCOL_RANGE_MPEG) {
242        put_marker(p, COM);
243        flush_put_bits(p);
244        ptr = put_bits_ptr(p);
245        put_bits(p, 16, 0); /* patched later */
246        ff_put_string(p, "CS=ITU601", 1);
247        size = strlen("CS=ITU601")+3;
248        AV_WB16(ptr, size);
249    }
250}
251
252void ff_mjpeg_init_hvsample(AVCodecContext *avctx, int hsample[4], int vsample[4])
253{
254    if (avctx->codec_id == AV_CODEC_ID_LJPEG &&
255        (   avctx->pix_fmt == AV_PIX_FMT_BGR0
256         || avctx->pix_fmt == AV_PIX_FMT_BGRA
257         || avctx->pix_fmt == AV_PIX_FMT_BGR24)) {
258        vsample[0] = hsample[0] =
259        vsample[1] = hsample[1] =
260        vsample[2] = hsample[2] =
261        vsample[3] = hsample[3] = 1;
262    } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P || avctx->pix_fmt == AV_PIX_FMT_YUVJ444P) {
263        vsample[0] = vsample[1] = vsample[2] = 2;
264        hsample[0] = hsample[1] = hsample[2] = 1;
265    } else {
266        int chroma_h_shift, chroma_v_shift;
267        av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift,
268                                         &chroma_v_shift);
269        vsample[0] = 2;
270        vsample[1] = 2 >> chroma_v_shift;
271        vsample[2] = 2 >> chroma_v_shift;
272        hsample[0] = 2;
273        hsample[1] = 2 >> chroma_h_shift;
274        hsample[2] = 2 >> chroma_h_shift;
275    }
276}
277
278void ff_mjpeg_encode_picture_header(AVCodecContext *avctx, PutBitContext *pb,
279                                    const AVFrame *frame, struct MJpegContext *m,
280                                    ScanTable *intra_scantable, int pred,
281                                    uint16_t luma_intra_matrix[64],
282                                    uint16_t chroma_intra_matrix[64],
283                                    int use_slices)
284{
285    const int lossless = !m;
286    int hsample[4], vsample[4];
287    int components = 3 + (avctx->pix_fmt == AV_PIX_FMT_BGRA);
288    int chroma_matrix = !!memcmp(luma_intra_matrix,
289                                 chroma_intra_matrix,
290                                 sizeof(luma_intra_matrix[0])*64);
291
292    ff_mjpeg_init_hvsample(avctx, hsample, vsample);
293
294    put_marker(pb, SOI);
295
296    // hack for AMV mjpeg format
297    if (avctx->codec_id == AV_CODEC_ID_AMV)
298        return;
299
300    jpeg_put_comments(avctx, pb, frame);
301
302    jpeg_table_header(avctx, pb, m, intra_scantable,
303                      luma_intra_matrix, chroma_intra_matrix, hsample,
304                      use_slices);
305
306    switch (avctx->codec_id) {
307    case AV_CODEC_ID_MJPEG:  put_marker(pb, SOF0 ); break;
308    case AV_CODEC_ID_LJPEG:  put_marker(pb, SOF3 ); break;
309    default: av_assert0(0);
310    }
311
312    put_bits(pb, 16, 8 + 3 * components);
313    if (lossless && (  avctx->pix_fmt == AV_PIX_FMT_BGR0
314                    || avctx->pix_fmt == AV_PIX_FMT_BGRA
315                    || avctx->pix_fmt == AV_PIX_FMT_BGR24))
316        put_bits(pb, 8, 9); /* 9 bits/component RCT */
317    else
318        put_bits(pb, 8, 8); /* 8 bits/component */
319    put_bits(pb, 16, avctx->height);
320    put_bits(pb, 16, avctx->width);
321    put_bits(pb, 8, components); /* 3 or 4 components */
322
323    /* Y component */
324    put_bits(pb, 8, 1); /* component number */
325    put_bits(pb, 4, hsample[0]); /* H factor */
326    put_bits(pb, 4, vsample[0]); /* V factor */
327    put_bits(pb, 8, 0); /* select matrix */
328
329    /* Cb component */
330    put_bits(pb, 8, 2); /* component number */
331    put_bits(pb, 4, hsample[1]); /* H factor */
332    put_bits(pb, 4, vsample[1]); /* V factor */
333    put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */
334
335    /* Cr component */
336    put_bits(pb, 8, 3); /* component number */
337    put_bits(pb, 4, hsample[2]); /* H factor */
338    put_bits(pb, 4, vsample[2]); /* V factor */
339    put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */
340
341    if (components == 4) {
342        put_bits(pb, 8, 4); /* component number */
343        put_bits(pb, 4, hsample[3]); /* H factor */
344        put_bits(pb, 4, vsample[3]); /* V factor */
345        put_bits(pb, 8, 0); /* select matrix */
346    }
347
348    /* scan header */
349    put_marker(pb, SOS);
350    put_bits(pb, 16, 6 + 2*components); /* length */
351    put_bits(pb, 8, components); /* 3 components */
352
353    /* Y component */
354    put_bits(pb, 8, 1); /* index */
355    put_bits(pb, 4, 0); /* DC huffman table index */
356    put_bits(pb, 4, 0); /* AC huffman table index */
357
358    /* Cb component */
359    put_bits(pb, 8, 2); /* index */
360    put_bits(pb, 4, 1); /* DC huffman table index */
361    put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */
362
363    /* Cr component */
364    put_bits(pb, 8, 3); /* index */
365    put_bits(pb, 4, 1); /* DC huffman table index */
366    put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */
367
368    if (components == 4) {
369        /* Alpha component */
370        put_bits(pb, 8, 4); /* index */
371        put_bits(pb, 4, 0); /* DC huffman table index */
372        put_bits(pb, 4, 0); /* AC huffman table index */
373    }
374
375    put_bits(pb, 8, pred); /* Ss (not used); pred only nonzero for LJPEG */
376
377    switch (avctx->codec_id) {
378    case AV_CODEC_ID_MJPEG:  put_bits(pb, 8, 63); break; /* Se (not used) */
379    case AV_CODEC_ID_LJPEG:  put_bits(pb, 8,  0); break; /* not used */
380    default: av_assert0(0);
381    }
382
383    put_bits(pb, 8, 0); /* Ah/Al (not used) */
384}
385
386void ff_mjpeg_escape_FF(PutBitContext *pb, int start)
387{
388    int size;
389    int i, ff_count;
390    uint8_t *buf = pb->buf + start;
391    int align= (-(size_t)(buf))&3;
392    int pad = (-put_bits_count(pb))&7;
393
394    if (pad)
395        put_bits(pb, pad, (1<<pad)-1);
396
397    flush_put_bits(pb);
398    size = put_bytes_output(pb) - start;
399
400    ff_count=0;
401    for(i=0; i<size && i<align; i++){
402        if(buf[i]==0xFF) ff_count++;
403    }
404    for(; i<size-15; i+=16){
405        int acc, v;
406
407        v= *(uint32_t*)(&buf[i]);
408        acc= (((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
409        v= *(uint32_t*)(&buf[i+4]);
410        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
411        v= *(uint32_t*)(&buf[i+8]);
412        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
413        v= *(uint32_t*)(&buf[i+12]);
414        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
415
416        acc>>=4;
417        acc+= (acc>>16);
418        acc+= (acc>>8);
419        ff_count+= acc&0xFF;
420    }
421    for(; i<size; i++){
422        if(buf[i]==0xFF) ff_count++;
423    }
424
425    if(ff_count==0) return;
426
427    flush_put_bits(pb);
428    skip_put_bytes(pb, ff_count);
429
430    for(i=size-1; ff_count; i--){
431        int v= buf[i];
432
433        if(v==0xFF){
434            buf[i+ff_count]= 0;
435            ff_count--;
436        }
437
438        buf[i+ff_count]= v;
439    }
440}
441
442/* isn't this function nicer than the one in the libjpeg ? */
443void ff_mjpeg_build_huffman_codes(uint8_t *huff_size, uint16_t *huff_code,
444                                  const uint8_t *bits_table,
445                                  const uint8_t *val_table)
446{
447    int k, code;
448
449    k = 0;
450    code = 0;
451    for (int i = 1; i <= 16; i++) {
452        int nb = bits_table[i];
453        for (int j = 0; j < nb; j++) {
454            int sym = val_table[k++];
455            huff_size[sym] = i;
456            huff_code[sym] = code;
457            code++;
458        }
459        code <<= 1;
460    }
461}
462
463void ff_mjpeg_encode_picture_trailer(PutBitContext *pb, int header_bits)
464{
465    av_assert1((header_bits & 7) == 0);
466
467    put_marker(pb, EOI);
468}
469
470void ff_mjpeg_encode_dc(PutBitContext *pb, int val,
471                        uint8_t *huff_size, uint16_t *huff_code)
472{
473    int mant, nbits;
474
475    if (val == 0) {
476        put_bits(pb, huff_size[0], huff_code[0]);
477    } else {
478        mant = val;
479        if (val < 0) {
480            val = -val;
481            mant--;
482        }
483
484        nbits= av_log2_16bit(val) + 1;
485
486        put_bits(pb, huff_size[nbits], huff_code[nbits]);
487
488        put_sbits(pb, nbits, mant);
489    }
490}
491
492int ff_mjpeg_encode_check_pix_fmt(AVCodecContext *avctx)
493{
494    if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&
495        avctx->color_range != AVCOL_RANGE_JPEG &&
496        (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
497         avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
498         avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
499         avctx->color_range == AVCOL_RANGE_MPEG)) {
500        av_log(avctx, AV_LOG_ERROR,
501               "Non full-range YUV is non-standard, set strict_std_compliance "
502               "to at most unofficial to use it.\n");
503        return AVERROR(EINVAL);
504    }
505    return 0;
506}
507