2 * lossless JPEG shared bits
3 * Copyright (c) 2000, 2001 Fabrice Bellard
4 * Copyright (c) 2003 Alex Beregszaszi
6 * This file is part of FFmpeg.
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.
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.
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
26 #include "libavutil/common.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/pixfmt.h"
32 #include "jpegtables.h"
35 #include "mjpegenc_common.h"
36 #include "mjpegenc_huffman.h"
39 av_cold void ff_init_uni_ac_vlc(const uint8_t huff_size_ac[256], uint8_t *uni_ac_vlc_len)
43 for (i = 0; i < 128; i++) {
48 for (run = 0; run < 64; run++) {
50 int alevel = FFABS(level);
52 len = (run >> 4) * huff_size_ac[0xf0];
54 nbits= av_log2_16bit(alevel) + 1;
55 code = ((15&run) << 4) | nbits;
57 len += huff_size_ac[code] + nbits;
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
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)
71 put_bits(p, 4, table_class);
72 put_bits(p, 4, table_id);
77 put_bits(p, 8, bits_table[i]);
81 put_bits(p, 8, value_table[i]);
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],
94 MpegEncContext *s = NULL;
96 /* Since avctx->priv_data will point to LJpegEncContext in this case */
97 if (avctx->codec_id != AV_CODEC_ID_LJPEG)
100 if (avctx->codec_id != AV_CODEC_ID_LJPEG) {
101 int matrix_count = 1 + !!memcmp(luma_intra_matrix,
103 sizeof(luma_intra_matrix[0]) * 64);
104 if (s && s->force_duplicated_matrix)
108 put_bits(p, 16, 2 + matrix_count * (1 + 64));
109 put_bits(p, 4, 0); /* 8 bit precision */
110 put_bits(p, 4, 0); /* table 0 */
112 j = intra_scantable->permutated[i];
113 put_bits(p, 8, luma_intra_matrix[j]);
116 if (matrix_count > 1) {
117 put_bits(p, 4, 0); /* 8 bit precision */
118 put_bits(p, 4, 1); /* table 1 */
120 j = intra_scantable->permutated[i];
121 put_bits(p, 8, chroma_intra_matrix[j]);
126 if(avctx->active_thread_type & FF_THREAD_SLICE){
129 put_bits(p, 16, (avctx->width-1)/(8*hsample[0]) + 1);
135 ptr = put_bits_ptr(p);
136 put_bits(p, 16, 0); /* patched later */
139 // Only MJPEG can have a variable Huffman variable. All other
140 // formats use the default Huffman table.
141 if (s && s->huffman == HUFFMAN_TABLE_OPTIMAL) {
142 size += put_huffman_table(p, 0, 0, s->mjpeg_ctx->bits_dc_luminance,
143 s->mjpeg_ctx->val_dc_luminance);
144 size += put_huffman_table(p, 0, 1, s->mjpeg_ctx->bits_dc_chrominance,
145 s->mjpeg_ctx->val_dc_chrominance);
147 size += put_huffman_table(p, 1, 0, s->mjpeg_ctx->bits_ac_luminance,
148 s->mjpeg_ctx->val_ac_luminance);
149 size += put_huffman_table(p, 1, 1, s->mjpeg_ctx->bits_ac_chrominance,
150 s->mjpeg_ctx->val_ac_chrominance);
152 size += put_huffman_table(p, 0, 0, avpriv_mjpeg_bits_dc_luminance,
153 avpriv_mjpeg_val_dc);
154 size += put_huffman_table(p, 0, 1, avpriv_mjpeg_bits_dc_chrominance,
155 avpriv_mjpeg_val_dc);
157 size += put_huffman_table(p, 1, 0, avpriv_mjpeg_bits_ac_luminance,
158 avpriv_mjpeg_val_ac_luminance);
159 size += put_huffman_table(p, 1, 1, avpriv_mjpeg_bits_ac_chrominance,
160 avpriv_mjpeg_val_ac_chrominance);
165 static void jpeg_put_comments(AVCodecContext *avctx, PutBitContext *p)
170 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
171 AVRational sar = avctx->sample_aspect_ratio;
173 if (sar.num > 65535 || sar.den > 65535) {
174 if (!av_reduce(&sar.num, &sar.den, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 65535))
175 av_log(avctx, AV_LOG_WARNING,
176 "Cannot store exact aspect ratio %d:%d\n",
177 avctx->sample_aspect_ratio.num,
178 avctx->sample_aspect_ratio.den);
184 avpriv_put_string(p, "JFIF", 1); /* this puts the trailing zero-byte too */
185 /* The most significant byte is used for major revisions, the least
186 * significant byte for minor revisions. Version 1.02 is the current
187 * released revision. */
188 put_bits(p, 16, 0x0102);
189 put_bits(p, 8, 0); /* units type: 0 - aspect ratio */
190 put_bits(p, 16, sar.num);
191 put_bits(p, 16, sar.den);
192 put_bits(p, 8, 0); /* thumbnail width */
193 put_bits(p, 8, 0); /* thumbnail height */
197 if (!(avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
200 ptr = put_bits_ptr(p);
201 put_bits(p, 16, 0); /* patched later */
202 avpriv_put_string(p, LIBAVCODEC_IDENT, 1);
203 size = strlen(LIBAVCODEC_IDENT)+3;
207 if (((avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
208 avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
209 avctx->pix_fmt == AV_PIX_FMT_YUV444P) && avctx->color_range != AVCOL_RANGE_JPEG)
210 || avctx->color_range == AVCOL_RANGE_MPEG) {
213 ptr = put_bits_ptr(p);
214 put_bits(p, 16, 0); /* patched later */
215 avpriv_put_string(p, "CS=ITU601", 1);
216 size = strlen("CS=ITU601")+3;
221 void ff_mjpeg_init_hvsample(AVCodecContext *avctx, int hsample[4], int vsample[4])
223 int chroma_h_shift, chroma_v_shift;
225 av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift,
227 if (avctx->codec->id == AV_CODEC_ID_LJPEG &&
228 ( avctx->pix_fmt == AV_PIX_FMT_BGR0
229 || avctx->pix_fmt == AV_PIX_FMT_BGRA
230 || avctx->pix_fmt == AV_PIX_FMT_BGR24)) {
231 vsample[0] = hsample[0] =
232 vsample[1] = hsample[1] =
233 vsample[2] = hsample[2] =
234 vsample[3] = hsample[3] = 1;
235 } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P || avctx->pix_fmt == AV_PIX_FMT_YUVJ444P) {
236 vsample[0] = vsample[1] = vsample[2] = 2;
237 hsample[0] = hsample[1] = hsample[2] = 1;
240 vsample[1] = 2 >> chroma_v_shift;
241 vsample[2] = 2 >> chroma_v_shift;
243 hsample[1] = 2 >> chroma_h_shift;
244 hsample[2] = 2 >> chroma_h_shift;
248 void ff_mjpeg_encode_picture_header(AVCodecContext *avctx, PutBitContext *pb,
249 ScanTable *intra_scantable, int pred,
250 uint16_t luma_intra_matrix[64],
251 uint16_t chroma_intra_matrix[64])
253 const int lossless = avctx->codec_id != AV_CODEC_ID_MJPEG && avctx->codec_id != AV_CODEC_ID_AMV;
254 int hsample[4], vsample[4];
256 int components = 3 + (avctx->pix_fmt == AV_PIX_FMT_BGRA);
257 int chroma_matrix = !!memcmp(luma_intra_matrix,
259 sizeof(luma_intra_matrix[0])*64);
261 ff_mjpeg_init_hvsample(avctx, hsample, vsample);
265 // hack for AMV mjpeg format
266 if(avctx->codec_id == AV_CODEC_ID_AMV) goto end;
268 jpeg_put_comments(avctx, pb);
270 jpeg_table_header(avctx, pb, intra_scantable, luma_intra_matrix, chroma_intra_matrix, hsample);
272 switch (avctx->codec_id) {
273 case AV_CODEC_ID_MJPEG: put_marker(pb, SOF0 ); break;
274 case AV_CODEC_ID_LJPEG: put_marker(pb, SOF3 ); break;
275 default: av_assert0(0);
278 put_bits(pb, 16, 17);
279 if (lossless && ( avctx->pix_fmt == AV_PIX_FMT_BGR0
280 || avctx->pix_fmt == AV_PIX_FMT_BGRA
281 || avctx->pix_fmt == AV_PIX_FMT_BGR24))
282 put_bits(pb, 8, 9); /* 9 bits/component RCT */
284 put_bits(pb, 8, 8); /* 8 bits/component */
285 put_bits(pb, 16, avctx->height);
286 put_bits(pb, 16, avctx->width);
287 put_bits(pb, 8, components); /* 3 or 4 components */
290 put_bits(pb, 8, 1); /* component number */
291 put_bits(pb, 4, hsample[0]); /* H factor */
292 put_bits(pb, 4, vsample[0]); /* V factor */
293 put_bits(pb, 8, 0); /* select matrix */
296 put_bits(pb, 8, 2); /* component number */
297 put_bits(pb, 4, hsample[1]); /* H factor */
298 put_bits(pb, 4, vsample[1]); /* V factor */
299 put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */
302 put_bits(pb, 8, 3); /* component number */
303 put_bits(pb, 4, hsample[2]); /* H factor */
304 put_bits(pb, 4, vsample[2]); /* V factor */
305 put_bits(pb, 8, lossless ? 0 : chroma_matrix); /* select matrix */
307 if (components == 4) {
308 put_bits(pb, 8, 4); /* component number */
309 put_bits(pb, 4, hsample[3]); /* H factor */
310 put_bits(pb, 4, vsample[3]); /* V factor */
311 put_bits(pb, 8, 0); /* select matrix */
316 put_bits(pb, 16, 6 + 2*components); /* length */
317 put_bits(pb, 8, components); /* 3 components */
320 put_bits(pb, 8, 1); /* index */
321 put_bits(pb, 4, 0); /* DC huffman table index */
322 put_bits(pb, 4, 0); /* AC huffman table index */
325 put_bits(pb, 8, 2); /* index */
326 put_bits(pb, 4, 1); /* DC huffman table index */
327 put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */
330 put_bits(pb, 8, 3); /* index */
331 put_bits(pb, 4, 1); /* DC huffman table index */
332 put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */
334 if (components == 4) {
335 /* Alpha component */
336 put_bits(pb, 8, 4); /* index */
337 put_bits(pb, 4, 0); /* DC huffman table index */
338 put_bits(pb, 4, 0); /* AC huffman table index */
341 put_bits(pb, 8, lossless ? pred : 0); /* Ss (not used) */
343 switch (avctx->codec_id) {
344 case AV_CODEC_ID_MJPEG: put_bits(pb, 8, 63); break; /* Se (not used) */
345 case AV_CODEC_ID_LJPEG: put_bits(pb, 8, 0); break; /* not used */
346 default: av_assert0(0);
349 put_bits(pb, 8, 0); /* Ah/Al (not used) */
353 MpegEncContext *s = avctx->priv_data;
354 av_assert0(avctx->codec->priv_data_size == sizeof(MpegEncContext));
356 s->esc_pos = put_bits_count(pb) >> 3;
357 for(i=1; i<s->slice_context_count; i++)
358 s->thread_context[i]->esc_pos = 0;
363 * Encodes and outputs the entire frame in the JPEG format.
365 * @param s The MpegEncContext.
367 void ff_mjpeg_encode_picture_frame(MpegEncContext *s)
369 int i, nbits, code, table_id;
370 MJpegContext *m = s->mjpeg_ctx;
371 uint8_t *huff_size[4] = {m->huff_size_dc_luminance,
372 m->huff_size_dc_chrominance,
373 m->huff_size_ac_luminance,
374 m->huff_size_ac_chrominance};
375 uint16_t *huff_code[4] = {m->huff_code_dc_luminance,
376 m->huff_code_dc_chrominance,
377 m->huff_code_ac_luminance,
378 m->huff_code_ac_chrominance};
379 size_t total_bits = 0;
382 s->header_bits = get_bits_diff(s);
383 // Estimate the total size first
384 for (i = 0; i < m->huff_ncode; i++) {
385 table_id = m->huff_buffer[i].table_id;
386 code = m->huff_buffer[i].code;
389 total_bits += huff_size[table_id][code] + nbits;
392 bytes_needed = (total_bits + 7) / 8;
393 ff_mpv_reallocate_putbitbuffer(s, bytes_needed, bytes_needed);
395 for (i = 0; i < m->huff_ncode; i++) {
396 table_id = m->huff_buffer[i].table_id;
397 code = m->huff_buffer[i].code;
400 put_bits(&s->pb, huff_size[table_id][code], huff_code[table_id][code]);
402 put_sbits(&s->pb, nbits, m->huff_buffer[i].mant);
407 s->i_tex_bits = get_bits_diff(s);
410 void ff_mjpeg_escape_FF(PutBitContext *pb, int start)
414 uint8_t *buf = pb->buf + start;
415 int align= (-(size_t)(buf))&3;
416 int pad = (-put_bits_count(pb))&7;
419 put_bits(pb, pad, (1<<pad)-1);
422 size = put_bits_count(pb) - start * 8;
424 av_assert1((size&7) == 0);
428 for(i=0; i<size && i<align; i++){
429 if(buf[i]==0xFF) ff_count++;
431 for(; i<size-15; i+=16){
434 v= *(uint32_t*)(&buf[i]);
435 acc= (((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
436 v= *(uint32_t*)(&buf[i+4]);
437 acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
438 v= *(uint32_t*)(&buf[i+8]);
439 acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
440 v= *(uint32_t*)(&buf[i+12]);
441 acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
449 if(buf[i]==0xFF) ff_count++;
452 if(ff_count==0) return;
455 skip_put_bytes(pb, ff_count);
457 for(i=size-1; ff_count; i--){
470 * Builds all 4 optimal Huffman tables.
472 * Uses the data stored in the JPEG buffer to compute the tables.
473 * Stores the Huffman tables in the bits_* and val_* arrays in the MJpegContext.
475 * @param m MJpegContext containing the JPEG buffer.
477 static void ff_mjpeg_build_optimal_huffman(MJpegContext *m)
479 int i, table_id, code;
481 MJpegEncHuffmanContext dc_luminance_ctx;
482 MJpegEncHuffmanContext dc_chrominance_ctx;
483 MJpegEncHuffmanContext ac_luminance_ctx;
484 MJpegEncHuffmanContext ac_chrominance_ctx;
485 MJpegEncHuffmanContext *ctx[4] = {&dc_luminance_ctx,
488 &ac_chrominance_ctx};
489 for (i = 0; i < 4; i++) {
490 ff_mjpeg_encode_huffman_init(ctx[i]);
492 for (i = 0; i < m->huff_ncode; i++) {
493 table_id = m->huff_buffer[i].table_id;
494 code = m->huff_buffer[i].code;
496 ff_mjpeg_encode_huffman_increment(ctx[table_id], code);
499 ff_mjpeg_encode_huffman_close(&dc_luminance_ctx,
500 m->bits_dc_luminance,
501 m->val_dc_luminance, 12);
502 ff_mjpeg_encode_huffman_close(&dc_chrominance_ctx,
503 m->bits_dc_chrominance,
504 m->val_dc_chrominance, 12);
505 ff_mjpeg_encode_huffman_close(&ac_luminance_ctx,
506 m->bits_ac_luminance,
507 m->val_ac_luminance, 256);
508 ff_mjpeg_encode_huffman_close(&ac_chrominance_ctx,
509 m->bits_ac_chrominance,
510 m->val_ac_chrominance, 256);
512 ff_mjpeg_build_huffman_codes(m->huff_size_dc_luminance,
513 m->huff_code_dc_luminance,
514 m->bits_dc_luminance,
515 m->val_dc_luminance);
516 ff_mjpeg_build_huffman_codes(m->huff_size_dc_chrominance,
517 m->huff_code_dc_chrominance,
518 m->bits_dc_chrominance,
519 m->val_dc_chrominance);
520 ff_mjpeg_build_huffman_codes(m->huff_size_ac_luminance,
521 m->huff_code_ac_luminance,
522 m->bits_ac_luminance,
523 m->val_ac_luminance);
524 ff_mjpeg_build_huffman_codes(m->huff_size_ac_chrominance,
525 m->huff_code_ac_chrominance,
526 m->bits_ac_chrominance,
527 m->val_ac_chrominance);
531 * Writes the complete JPEG frame when optimal huffman tables are enabled,
532 * otherwise writes the stuffing.
534 * Header + values + stuffing.
536 * @param s The MpegEncContext.
537 * @return int Error code, 0 if successful.
539 int ff_mjpeg_encode_stuffing(MpegEncContext *s)
542 PutBitContext *pbc = &s->pb;
543 int mb_y = s->mb_y - !s->mb_x;
549 if (s->huffman == HUFFMAN_TABLE_OPTIMAL) {
550 ff_mjpeg_build_optimal_huffman(m);
552 // Replace the VLCs with the optimal ones.
553 // The default ones may be used for trellis during quantization.
554 ff_init_uni_ac_vlc(m->huff_size_ac_luminance, m->uni_ac_vlc_len);
555 ff_init_uni_ac_vlc(m->huff_size_ac_chrominance, m->uni_chroma_ac_vlc_len);
556 s->intra_ac_vlc_length =
557 s->intra_ac_vlc_last_length = m->uni_ac_vlc_len;
558 s->intra_chroma_ac_vlc_length =
559 s->intra_chroma_ac_vlc_last_length = m->uni_chroma_ac_vlc_len;
561 ff_mjpeg_encode_picture_header(s->avctx, &s->pb, &s->intra_scantable,
562 s->pred, s->intra_matrix, s->chroma_intra_matrix);
563 ff_mjpeg_encode_picture_frame(s);
566 ret = ff_mpv_reallocate_putbitbuffer(s, put_bits_count(&s->pb) / 8 + 100,
567 put_bits_count(&s->pb) / 4 + 1000);
570 av_log(s->avctx, AV_LOG_ERROR, "Buffer reallocation failed\n");
574 ff_mjpeg_escape_FF(pbc, s->esc_pos);
576 if((s->avctx->active_thread_type & FF_THREAD_SLICE) && mb_y < s->mb_height)
577 put_marker(pbc, RST0 + (mb_y&7));
578 s->esc_pos = put_bits_count(pbc) >> 3;
582 s->last_dc[i] = 128 << s->intra_dc_precision;
587 void ff_mjpeg_encode_picture_trailer(PutBitContext *pb, int header_bits)
589 av_assert1((header_bits & 7) == 0);
594 void ff_mjpeg_encode_dc(PutBitContext *pb, int val,
595 uint8_t *huff_size, uint16_t *huff_code)
600 put_bits(pb, huff_size[0], huff_code[0]);
608 nbits= av_log2_16bit(val) + 1;
610 put_bits(pb, huff_size[nbits], huff_code[nbits]);
612 put_sbits(pb, nbits, mant);