]> git.sesse.net Git - ffmpeg/blob - libavcodec/mjpegenc_common.c
Merge commit 'f2f145f3032bc8808708a4bd694fbce5f1b8b63c'
[ffmpeg] / libavcodec / mjpegenc_common.c
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/common.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/pixfmt.h"
29
30 #include "avcodec.h"
31 #include "idctdsp.h"
32 #include "jpegtables.h"
33 #include "put_bits.h"
34 #include "mjpegenc.h"
35 #include "mjpegenc_common.h"
36 #include "mjpegenc_huffman.h"
37 #include "mjpeg.h"
38
39 av_cold void ff_init_uni_ac_vlc(const uint8_t huff_size_ac[256], uint8_t *uni_ac_vlc_len)
40 {
41     int i;
42
43     for (i = 0; i < 128; i++) {
44         int level = i - 64;
45         int run;
46         if (!level)
47             continue;
48         for (run = 0; run < 64; run++) {
49             int len, code, nbits;
50             int alevel = FFABS(level);
51
52             len = (run >> 4) * huff_size_ac[0xf0];
53
54             nbits= av_log2_16bit(alevel) + 1;
55             code = ((15&run) << 4) | nbits;
56
57             len += huff_size_ac[code] + nbits;
58
59             uni_ac_vlc_len[UNI_AC_ENC_INDEX(run, i)] = len;
60             // We ignore EOB as its just a constant which does not change generally
61         }
62     }
63 }
64
65 /* table_class: 0 = DC coef, 1 = AC coefs */
66 static int put_huffman_table(PutBitContext *p, int table_class, int table_id,
67                              const uint8_t *bits_table, const uint8_t *value_table)
68 {
69     int n, i;
70
71     put_bits(p, 4, table_class);
72     put_bits(p, 4, table_id);
73
74     n = 0;
75     for(i=1;i<=16;i++) {
76         n += bits_table[i];
77         put_bits(p, 8, bits_table[i]);
78     }
79
80     for(i=0;i<n;i++)
81         put_bits(p, 8, value_table[i]);
82
83     return n + 17;
84 }
85
86 static void jpeg_table_header(AVCodecContext *avctx, PutBitContext *p,
87                               ScanTable *intra_scantable,
88                               uint16_t luma_intra_matrix[64],
89                               uint16_t chroma_intra_matrix[64],
90                               int hsample[3])
91 {
92     int i, j, size;
93     uint8_t *ptr;
94     MpegEncContext *s = avctx->priv_data;
95
96     if (avctx->codec_id != AV_CODEC_ID_LJPEG) {
97         int matrix_count = 1 + !!memcmp(luma_intra_matrix,
98                                         chroma_intra_matrix,
99                                         sizeof(luma_intra_matrix[0]) * 64);
100     if (s->force_duplicated_matrix)
101         matrix_count = 2;
102     /* quant matrixes */
103     put_marker(p, DQT);
104     put_bits(p, 16, 2 + matrix_count * (1 + 64));
105     put_bits(p, 4, 0); /* 8 bit precision */
106     put_bits(p, 4, 0); /* table 0 */
107     for(i=0;i<64;i++) {
108         j = intra_scantable->permutated[i];
109         put_bits(p, 8, luma_intra_matrix[j]);
110     }
111
112         if (matrix_count > 1) {
113             put_bits(p, 4, 0); /* 8 bit precision */
114             put_bits(p, 4, 1); /* table 1 */
115             for(i=0;i<64;i++) {
116                 j = intra_scantable->permutated[i];
117                 put_bits(p, 8, chroma_intra_matrix[j]);
118             }
119         }
120     }
121
122     if(avctx->active_thread_type & FF_THREAD_SLICE){
123         put_marker(p, DRI);
124         put_bits(p, 16, 4);
125         put_bits(p, 16, (avctx->width-1)/(8*hsample[0]) + 1);
126     }
127
128     /* huffman table */
129     put_marker(p, DHT);
130     flush_put_bits(p);
131     ptr = put_bits_ptr(p);
132     put_bits(p, 16, 0); /* patched later */
133     size = 2;
134
135     // Only MJPEG can have a variable Huffman variable. All other
136     // formats use the default Huffman table.
137     if (s->out_format == FMT_MJPEG && s->huffman == HUFFMAN_TABLE_OPTIMAL) {
138         size += put_huffman_table(p, 0, 0, s->mjpeg_ctx->bits_dc_luminance,
139                                   s->mjpeg_ctx->val_dc_luminance);
140         size += put_huffman_table(p, 0, 1, s->mjpeg_ctx->bits_dc_chrominance,
141                                   s->mjpeg_ctx->val_dc_chrominance);
142
143         size += put_huffman_table(p, 1, 0, s->mjpeg_ctx->bits_ac_luminance,
144                                   s->mjpeg_ctx->val_ac_luminance);
145         size += put_huffman_table(p, 1, 1, s->mjpeg_ctx->bits_ac_chrominance,
146                                   s->mjpeg_ctx->val_ac_chrominance);
147     } else {
148         size += put_huffman_table(p, 0, 0, avpriv_mjpeg_bits_dc_luminance,
149                                   avpriv_mjpeg_val_dc);
150         size += put_huffman_table(p, 0, 1, avpriv_mjpeg_bits_dc_chrominance,
151                                   avpriv_mjpeg_val_dc);
152
153         size += put_huffman_table(p, 1, 0, avpriv_mjpeg_bits_ac_luminance,
154                                   avpriv_mjpeg_val_ac_luminance);
155         size += put_huffman_table(p, 1, 1, avpriv_mjpeg_bits_ac_chrominance,
156                                   avpriv_mjpeg_val_ac_chrominance);
157     }
158     AV_WB16(ptr, size);
159 }
160
161 static void jpeg_put_comments(AVCodecContext *avctx, PutBitContext *p)
162 {
163     int size;
164     uint8_t *ptr;
165
166     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
167         AVRational sar = avctx->sample_aspect_ratio;
168
169         if (sar.num > 65535 || sar.den > 65535) {
170             if (!av_reduce(&sar.num, &sar.den, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 65535))
171                 av_log(avctx, AV_LOG_WARNING,
172                     "Cannot store exact aspect ratio %d:%d\n",
173                     avctx->sample_aspect_ratio.num,
174                     avctx->sample_aspect_ratio.den);
175         }
176
177         /* JFIF header */
178         put_marker(p, APP0);
179         put_bits(p, 16, 16);
180         avpriv_put_string(p, "JFIF", 1); /* this puts the trailing zero-byte too */
181         /* The most significant byte is used for major revisions, the least
182          * significant byte for minor revisions. Version 1.02 is the current
183          * released revision. */
184         put_bits(p, 16, 0x0102);
185         put_bits(p,  8, 0);              /* units type: 0 - aspect ratio */
186         put_bits(p, 16, sar.num);
187         put_bits(p, 16, sar.den);
188         put_bits(p, 8, 0); /* thumbnail width */
189         put_bits(p, 8, 0); /* thumbnail height */
190     }
191
192     /* comment */
193     if (!(avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
194         put_marker(p, COM);
195         flush_put_bits(p);
196         ptr = put_bits_ptr(p);
197         put_bits(p, 16, 0); /* patched later */
198         avpriv_put_string(p, LIBAVCODEC_IDENT, 1);
199         size = strlen(LIBAVCODEC_IDENT)+3;
200         AV_WB16(ptr, size);
201     }
202
203     if (((avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
204           avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
205           avctx->pix_fmt == AV_PIX_FMT_YUV444P) && avctx->color_range != AVCOL_RANGE_JPEG)
206         || avctx->color_range == AVCOL_RANGE_MPEG) {
207         put_marker(p, COM);
208         flush_put_bits(p);
209         ptr = put_bits_ptr(p);
210         put_bits(p, 16, 0); /* patched later */
211         avpriv_put_string(p, "CS=ITU601", 1);
212         size = strlen("CS=ITU601")+3;
213         AV_WB16(ptr, size);
214     }
215 }
216
217 void ff_mjpeg_init_hvsample(AVCodecContext *avctx, int hsample[4], int vsample[4])
218 {
219     int chroma_h_shift, chroma_v_shift;
220
221     av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift,
222                                      &chroma_v_shift);
223     if (avctx->codec->id == AV_CODEC_ID_LJPEG &&
224         (   avctx->pix_fmt == AV_PIX_FMT_BGR0
225          || avctx->pix_fmt == AV_PIX_FMT_BGRA
226          || avctx->pix_fmt == AV_PIX_FMT_BGR24)) {
227         vsample[0] = hsample[0] =
228         vsample[1] = hsample[1] =
229         vsample[2] = hsample[2] =
230         vsample[3] = hsample[3] = 1;
231     } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P || avctx->pix_fmt == AV_PIX_FMT_YUVJ444P) {
232         vsample[0] = vsample[1] = vsample[2] = 2;
233         hsample[0] = hsample[1] = hsample[2] = 1;
234     } else {
235         vsample[0] = 2;
236         vsample[1] = 2 >> chroma_v_shift;
237         vsample[2] = 2 >> chroma_v_shift;
238         hsample[0] = 2;
239         hsample[1] = 2 >> chroma_h_shift;
240         hsample[2] = 2 >> chroma_h_shift;
241     }
242 }
243
244 void ff_mjpeg_encode_picture_header(AVCodecContext *avctx, PutBitContext *pb,
245                                     ScanTable *intra_scantable, int pred,
246                                     uint16_t luma_intra_matrix[64],
247                                     uint16_t chroma_intra_matrix[64])
248 {
249     const int lossless = avctx->codec_id != AV_CODEC_ID_MJPEG && avctx->codec_id != AV_CODEC_ID_AMV;
250     int hsample[4], vsample[4];
251     int i;
252     int components = 3 + (avctx->pix_fmt == AV_PIX_FMT_BGRA);
253     int chroma_matrix = !!memcmp(luma_intra_matrix,
254                                  chroma_intra_matrix,
255                                  sizeof(luma_intra_matrix[0])*64);
256
257     ff_mjpeg_init_hvsample(avctx, hsample, vsample);
258
259     put_marker(pb, SOI);
260
261     // hack for AMV mjpeg format
262     if(avctx->codec_id == AV_CODEC_ID_AMV) goto end;
263
264     jpeg_put_comments(avctx, pb);
265
266     jpeg_table_header(avctx, pb, intra_scantable, luma_intra_matrix, chroma_intra_matrix, hsample);
267
268     switch (avctx->codec_id) {
269     case AV_CODEC_ID_MJPEG:  put_marker(pb, SOF0 ); break;
270     case AV_CODEC_ID_LJPEG:  put_marker(pb, SOF3 ); break;
271     default: av_assert0(0);
272     }
273
274     put_bits(pb, 16, 17);
275     if (lossless && (  avctx->pix_fmt == AV_PIX_FMT_BGR0
276                     || avctx->pix_fmt == AV_PIX_FMT_BGRA
277                     || avctx->pix_fmt == AV_PIX_FMT_BGR24))
278         put_bits(pb, 8, 9); /* 9 bits/component RCT */
279     else
280         put_bits(pb, 8, 8); /* 8 bits/component */
281     put_bits(pb, 16, avctx->height);
282     put_bits(pb, 16, avctx->width);
283     put_bits(pb, 8, components); /* 3 or 4 components */
284
285     /* Y component */
286     put_bits(pb, 8, 1); /* component number */
287     put_bits(pb, 4, hsample[0]); /* H factor */
288     put_bits(pb, 4, vsample[0]); /* V factor */
289     put_bits(pb, 8, 0); /* select matrix */
290
291     /* Cb component */
292     put_bits(pb, 8, 2); /* component number */
293     put_bits(pb, 4, hsample[1]); /* H factor */
294     put_bits(pb, 4, vsample[1]); /* V factor */
295     put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */
296
297     /* Cr component */
298     put_bits(pb, 8, 3); /* component number */
299     put_bits(pb, 4, hsample[2]); /* H factor */
300     put_bits(pb, 4, vsample[2]); /* V factor */
301     put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */
302
303     if (components == 4) {
304         put_bits(pb, 8, 4); /* component number */
305         put_bits(pb, 4, hsample[3]); /* H factor */
306         put_bits(pb, 4, vsample[3]); /* V factor */
307         put_bits(pb, 8, 0); /* select matrix */
308     }
309
310     /* scan header */
311     put_marker(pb, SOS);
312     put_bits(pb, 16, 6 + 2*components); /* length */
313     put_bits(pb, 8, components); /* 3 components */
314
315     /* Y component */
316     put_bits(pb, 8, 1); /* index */
317     put_bits(pb, 4, 0); /* DC huffman table index */
318     put_bits(pb, 4, 0); /* AC huffman table index */
319
320     /* Cb component */
321     put_bits(pb, 8, 2); /* index */
322     put_bits(pb, 4, 1); /* DC huffman table index */
323     put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */
324
325     /* Cr component */
326     put_bits(pb, 8, 3); /* index */
327     put_bits(pb, 4, 1); /* DC huffman table index */
328     put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */
329
330     if (components == 4) {
331         /* Alpha component */
332         put_bits(pb, 8, 4); /* index */
333         put_bits(pb, 4, 0); /* DC huffman table index */
334         put_bits(pb, 4, 0); /* AC huffman table index */
335     }
336
337     put_bits(pb, 8, lossless ? pred : 0); /* Ss (not used) */
338
339     switch (avctx->codec_id) {
340     case AV_CODEC_ID_MJPEG:  put_bits(pb, 8, 63); break; /* Se (not used) */
341     case AV_CODEC_ID_LJPEG:  put_bits(pb, 8,  0); break; /* not used */
342     default: av_assert0(0);
343     }
344
345     put_bits(pb, 8, 0); /* Ah/Al (not used) */
346
347 end:
348     if (!lossless) {
349         MpegEncContext *s = avctx->priv_data;
350         av_assert0(avctx->codec->priv_data_size == sizeof(MpegEncContext));
351
352         s->esc_pos = put_bits_count(pb) >> 3;
353         for(i=1; i<s->slice_context_count; i++)
354             s->thread_context[i]->esc_pos = 0;
355     }
356 }
357
358 void ff_mjpeg_escape_FF(PutBitContext *pb, int start)
359 {
360     int size;
361     int i, ff_count;
362     uint8_t *buf = pb->buf + start;
363     int align= (-(size_t)(buf))&3;
364     int pad = (-put_bits_count(pb))&7;
365
366     if (pad)
367         put_bits(pb, pad, (1<<pad)-1);
368
369     flush_put_bits(pb);
370     size = put_bits_count(pb) - start * 8;
371
372     av_assert1((size&7) == 0);
373     size >>= 3;
374
375     ff_count=0;
376     for(i=0; i<size && i<align; i++){
377         if(buf[i]==0xFF) ff_count++;
378     }
379     for(; i<size-15; i+=16){
380         int acc, v;
381
382         v= *(uint32_t*)(&buf[i]);
383         acc= (((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
384         v= *(uint32_t*)(&buf[i+4]);
385         acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
386         v= *(uint32_t*)(&buf[i+8]);
387         acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
388         v= *(uint32_t*)(&buf[i+12]);
389         acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
390
391         acc>>=4;
392         acc+= (acc>>16);
393         acc+= (acc>>8);
394         ff_count+= acc&0xFF;
395     }
396     for(; i<size; i++){
397         if(buf[i]==0xFF) ff_count++;
398     }
399
400     if(ff_count==0) return;
401
402     flush_put_bits(pb);
403     skip_put_bytes(pb, ff_count);
404
405     for(i=size-1; ff_count; i--){
406         int v= buf[i];
407
408         if(v==0xFF){
409             buf[i+ff_count]= 0;
410             ff_count--;
411         }
412
413         buf[i+ff_count]= v;
414     }
415 }
416
417 /**
418  * Builds all 4 optimal Huffman tables.
419  *
420  * Uses the data stored in the JPEG buffer to compute the tables.
421  * Stores the Huffman tables in the bits_* and val_* arrays in the MJpegContext.
422  *
423  * @param m MJpegContext containing the JPEG buffer.
424  */
425 static void ff_mjpeg_build_optimal_huffman(MJpegContext *m)
426 {
427     int i, table_id, code;
428
429     MJpegEncHuffmanContext dc_luminance_ctx;
430     MJpegEncHuffmanContext dc_chrominance_ctx;
431     MJpegEncHuffmanContext ac_luminance_ctx;
432     MJpegEncHuffmanContext ac_chrominance_ctx;
433     MJpegEncHuffmanContext *ctx[4] = {&dc_luminance_ctx,
434                                       &dc_chrominance_ctx,
435                                       &ac_luminance_ctx,
436                                       &ac_chrominance_ctx};
437     for (i = 0; i < 4; i++) {
438         ff_mjpeg_encode_huffman_init(ctx[i]);
439     }
440     for (i = 0; i < m->huff_ncode; i++) {
441         table_id = m->huff_buffer[i].table_id;
442         code = m->huff_buffer[i].code;
443
444         ff_mjpeg_encode_huffman_increment(ctx[table_id], code);
445     }
446
447     ff_mjpeg_encode_huffman_close(&dc_luminance_ctx,
448                                   m->bits_dc_luminance,
449                                   m->val_dc_luminance, 12);
450     ff_mjpeg_encode_huffman_close(&dc_chrominance_ctx,
451                                   m->bits_dc_chrominance,
452                                   m->val_dc_chrominance, 12);
453     ff_mjpeg_encode_huffman_close(&ac_luminance_ctx,
454                                   m->bits_ac_luminance,
455                                   m->val_ac_luminance, 256);
456     ff_mjpeg_encode_huffman_close(&ac_chrominance_ctx,
457                                   m->bits_ac_chrominance,
458                                   m->val_ac_chrominance, 256);
459
460     ff_mjpeg_build_huffman_codes(m->huff_size_dc_luminance,
461                                  m->huff_code_dc_luminance,
462                                  m->bits_dc_luminance,
463                                  m->val_dc_luminance);
464     ff_mjpeg_build_huffman_codes(m->huff_size_dc_chrominance,
465                                  m->huff_code_dc_chrominance,
466                                  m->bits_dc_chrominance,
467                                  m->val_dc_chrominance);
468     ff_mjpeg_build_huffman_codes(m->huff_size_ac_luminance,
469                                  m->huff_code_ac_luminance,
470                                  m->bits_ac_luminance,
471                                  m->val_ac_luminance);
472     ff_mjpeg_build_huffman_codes(m->huff_size_ac_chrominance,
473                                  m->huff_code_ac_chrominance,
474                                  m->bits_ac_chrominance,
475                                  m->val_ac_chrominance);
476 }
477
478 /**
479  * Writes the complete JPEG frame when optimal huffman tables are enabled,
480  * otherwise writes the stuffing.
481  *
482  * Header + values + stuffing.
483  *
484  * @param s The MpegEncContext.
485  * @return int Error code, 0 if successful.
486  */
487 int ff_mjpeg_encode_stuffing(MpegEncContext *s)
488 {
489     int i;
490     PutBitContext *pbc = &s->pb;
491     int mb_y = s->mb_y - !s->mb_x;
492     int ret;
493     MJpegContext *m;
494
495     m = s->mjpeg_ctx;
496
497     if (s->huffman == HUFFMAN_TABLE_OPTIMAL) {
498         ff_mjpeg_build_optimal_huffman(m);
499
500         // Replace the VLCs with the optimal ones.
501         // The default ones may be used for trellis during quantization.
502         ff_init_uni_ac_vlc(m->huff_size_ac_luminance,   m->uni_ac_vlc_len);
503         ff_init_uni_ac_vlc(m->huff_size_ac_chrominance, m->uni_chroma_ac_vlc_len);
504         s->intra_ac_vlc_length      =
505         s->intra_ac_vlc_last_length = m->uni_ac_vlc_len;
506         s->intra_chroma_ac_vlc_length      =
507         s->intra_chroma_ac_vlc_last_length = m->uni_chroma_ac_vlc_len;
508
509         ff_mjpeg_encode_picture_header(s->avctx, &s->pb, &s->intra_scantable,
510                                        s->pred, s->intra_matrix, s->chroma_intra_matrix);
511         ff_mjpeg_encode_picture_frame(s);
512     }
513
514     ret = ff_mpv_reallocate_putbitbuffer(s, put_bits_count(&s->pb) / 8 + 100,
515                                             put_bits_count(&s->pb) / 4 + 1000);
516
517     if (ret < 0) {
518         av_log(s->avctx, AV_LOG_ERROR, "Buffer reallocation failed\n");
519         goto fail;
520     }
521
522     ff_mjpeg_escape_FF(pbc, s->esc_pos);
523
524     if((s->avctx->active_thread_type & FF_THREAD_SLICE) && mb_y < s->mb_height)
525         put_marker(pbc, RST0 + (mb_y&7));
526     s->esc_pos = put_bits_count(pbc) >> 3;
527 fail:
528
529     for(i=0; i<3; i++)
530         s->last_dc[i] = 128 << s->intra_dc_precision;
531
532     return ret;
533 }
534
535 void ff_mjpeg_encode_picture_trailer(PutBitContext *pb, int header_bits)
536 {
537     av_assert1((header_bits & 7) == 0);
538
539     put_marker(pb, EOI);
540 }
541
542 void ff_mjpeg_encode_dc(PutBitContext *pb, int val,
543                         uint8_t *huff_size, uint16_t *huff_code)
544 {
545     int mant, nbits;
546
547     if (val == 0) {
548         put_bits(pb, huff_size[0], huff_code[0]);
549     } else {
550         mant = val;
551         if (val < 0) {
552             val = -val;
553             mant--;
554         }
555
556         nbits= av_log2_16bit(val) + 1;
557
558         put_bits(pb, huff_size[nbits], huff_code[nbits]);
559
560         put_sbits(pb, nbits, mant);
561     }
562 }