]> git.sesse.net Git - ffmpeg/blob - libavcodec/mjpegenc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / mjpegenc.c
1 /*
2  * MJPEG encoder
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  * Copyright (c) 2003 Alex Beregszaszi
5  * Copyright (c) 2003-2004 Michael Niedermayer
6  *
7  * Support for external huffman table, various fixes (AVID workaround),
8  * aspecting, new decode_frame mechanism and apple mjpeg-b support
9  *                                  by Alex Beregszaszi
10  *
11  * This file is part of FFmpeg.
12  *
13  * FFmpeg is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Lesser General Public
15  * License as published by the Free Software Foundation; either
16  * version 2.1 of the License, or (at your option) any later version.
17  *
18  * FFmpeg is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  * Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public
24  * License along with FFmpeg; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26  */
27
28 /**
29  * @file
30  * MJPEG encoder.
31  */
32
33 #include "avcodec.h"
34 #include "mpegvideo.h"
35 #include "mjpeg.h"
36 #include "mjpegenc.h"
37
38 /* use two quantizer tables (one for luminance and one for chrominance) */
39 /* not yet working */
40 #undef TWOMATRIXES
41
42
43 av_cold int ff_mjpeg_encode_init(MpegEncContext *s)
44 {
45     MJpegContext *m;
46
47     if (s->width > 65500 || s->height > 65500) {
48         av_log(s, AV_LOG_ERROR, "JPEG does not support resolutions above 65500x65500\n");
49         return -1;
50     }
51
52     m = av_malloc(sizeof(MJpegContext));
53     if (!m)
54         return -1;
55
56     s->min_qcoeff=-1023;
57     s->max_qcoeff= 1023;
58
59     /* build all the huffman tables */
60     ff_mjpeg_build_huffman_codes(m->huff_size_dc_luminance,
61                                  m->huff_code_dc_luminance,
62                                  avpriv_mjpeg_bits_dc_luminance,
63                                  avpriv_mjpeg_val_dc);
64     ff_mjpeg_build_huffman_codes(m->huff_size_dc_chrominance,
65                                  m->huff_code_dc_chrominance,
66                                  avpriv_mjpeg_bits_dc_chrominance,
67                                  avpriv_mjpeg_val_dc);
68     ff_mjpeg_build_huffman_codes(m->huff_size_ac_luminance,
69                                  m->huff_code_ac_luminance,
70                                  avpriv_mjpeg_bits_ac_luminance,
71                                  avpriv_mjpeg_val_ac_luminance);
72     ff_mjpeg_build_huffman_codes(m->huff_size_ac_chrominance,
73                                  m->huff_code_ac_chrominance,
74                                  avpriv_mjpeg_bits_ac_chrominance,
75                                  avpriv_mjpeg_val_ac_chrominance);
76
77     s->mjpeg_ctx = m;
78     return 0;
79 }
80
81 void ff_mjpeg_encode_close(MpegEncContext *s)
82 {
83     av_free(s->mjpeg_ctx);
84 }
85
86 /* table_class: 0 = DC coef, 1 = AC coefs */
87 static int put_huffman_table(MpegEncContext *s, int table_class, int table_id,
88                              const uint8_t *bits_table, const uint8_t *value_table)
89 {
90     PutBitContext *p = &s->pb;
91     int n, i;
92
93     put_bits(p, 4, table_class);
94     put_bits(p, 4, table_id);
95
96     n = 0;
97     for(i=1;i<=16;i++) {
98         n += bits_table[i];
99         put_bits(p, 8, bits_table[i]);
100     }
101
102     for(i=0;i<n;i++)
103         put_bits(p, 8, value_table[i]);
104
105     return n + 17;
106 }
107
108 static void jpeg_table_header(MpegEncContext *s)
109 {
110     PutBitContext *p = &s->pb;
111     int i, j, size;
112     uint8_t *ptr;
113
114     /* quant matrixes */
115     put_marker(p, DQT);
116 #ifdef TWOMATRIXES
117     put_bits(p, 16, 2 + 2 * (1 + 64));
118 #else
119     put_bits(p, 16, 2 + 1 * (1 + 64));
120 #endif
121     put_bits(p, 4, 0); /* 8 bit precision */
122     put_bits(p, 4, 0); /* table 0 */
123     for(i=0;i<64;i++) {
124         j = s->intra_scantable.permutated[i];
125         put_bits(p, 8, s->intra_matrix[j]);
126     }
127 #ifdef TWOMATRIXES
128     put_bits(p, 4, 0); /* 8 bit precision */
129     put_bits(p, 4, 1); /* table 1 */
130     for(i=0;i<64;i++) {
131         j = s->intra_scantable.permutated[i];
132         put_bits(p, 8, s->chroma_intra_matrix[j]);
133     }
134 #endif
135
136     if(s->avctx->active_thread_type & FF_THREAD_SLICE){
137         put_marker(p, DRI);
138         put_bits(p, 16, 4);
139         put_bits(p, 16, (s->width-1)/(8*s->mjpeg_hsample[0]) + 1);
140     }
141
142     /* huffman table */
143     put_marker(p, DHT);
144     flush_put_bits(p);
145     ptr = put_bits_ptr(p);
146     put_bits(p, 16, 0); /* patched later */
147     size = 2;
148     size += put_huffman_table(s, 0, 0, avpriv_mjpeg_bits_dc_luminance,
149                               avpriv_mjpeg_val_dc);
150     size += put_huffman_table(s, 0, 1, avpriv_mjpeg_bits_dc_chrominance,
151                               avpriv_mjpeg_val_dc);
152
153     size += put_huffman_table(s, 1, 0, avpriv_mjpeg_bits_ac_luminance,
154                               avpriv_mjpeg_val_ac_luminance);
155     size += put_huffman_table(s, 1, 1, avpriv_mjpeg_bits_ac_chrominance,
156                               avpriv_mjpeg_val_ac_chrominance);
157     AV_WB16(ptr, size);
158 }
159
160 static void jpeg_put_comments(MpegEncContext *s)
161 {
162     PutBitContext *p = &s->pb;
163     int size;
164     uint8_t *ptr;
165
166     if (s->avctx->sample_aspect_ratio.num /* && !lossless */)
167     {
168     /* JFIF header */
169     put_marker(p, APP0);
170     put_bits(p, 16, 16);
171     avpriv_put_string(p, "JFIF", 1); /* this puts the trailing zero-byte too */
172     put_bits(p, 16, 0x0102); /* v 1.02 */
173     put_bits(p, 8, 0); /* units type: 0 - aspect ratio */
174     put_bits(p, 16, s->avctx->sample_aspect_ratio.num);
175     put_bits(p, 16, s->avctx->sample_aspect_ratio.den);
176     put_bits(p, 8, 0); /* thumbnail width */
177     put_bits(p, 8, 0); /* thumbnail height */
178     }
179
180     /* comment */
181     if(!(s->flags & CODEC_FLAG_BITEXACT)){
182         put_marker(p, COM);
183         flush_put_bits(p);
184         ptr = put_bits_ptr(p);
185         put_bits(p, 16, 0); /* patched later */
186         avpriv_put_string(p, LIBAVCODEC_IDENT, 1);
187         size = strlen(LIBAVCODEC_IDENT)+3;
188         AV_WB16(ptr, size);
189     }
190
191     if(  s->avctx->pix_fmt == AV_PIX_FMT_YUV420P
192        ||s->avctx->pix_fmt == AV_PIX_FMT_YUV422P
193        ||s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
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, "CS=ITU601", 1);
199         size = strlen("CS=ITU601")+3;
200         AV_WB16(ptr, size);
201     }
202 }
203
204 void ff_mjpeg_encode_picture_header(MpegEncContext *s)
205 {
206     const int lossless= s->avctx->codec_id != AV_CODEC_ID_MJPEG;
207     int i;
208
209     put_marker(&s->pb, SOI);
210
211     // hack for AMV mjpeg format
212     if(s->avctx->codec_id == AV_CODEC_ID_AMV) goto end;
213
214     jpeg_put_comments(s);
215
216     jpeg_table_header(s);
217
218     switch(s->avctx->codec_id){
219     case AV_CODEC_ID_MJPEG:  put_marker(&s->pb, SOF0 ); break;
220     case AV_CODEC_ID_LJPEG:  put_marker(&s->pb, SOF3 ); break;
221     default: av_assert0(0);
222     }
223
224     put_bits(&s->pb, 16, 17);
225     if(lossless && (s->avctx->pix_fmt == AV_PIX_FMT_BGR0
226                     || s->avctx->pix_fmt == AV_PIX_FMT_BGRA
227                     || s->avctx->pix_fmt == AV_PIX_FMT_BGR24))
228         put_bits(&s->pb, 8, 9); /* 9 bits/component RCT */
229     else
230         put_bits(&s->pb, 8, 8); /* 8 bits/component */
231     put_bits(&s->pb, 16, s->height);
232     put_bits(&s->pb, 16, s->width);
233     put_bits(&s->pb, 8, 3); /* 3 components */
234
235     /* Y component */
236     put_bits(&s->pb, 8, 1); /* component number */
237     put_bits(&s->pb, 4, s->mjpeg_hsample[0]); /* H factor */
238     put_bits(&s->pb, 4, s->mjpeg_vsample[0]); /* V factor */
239     put_bits(&s->pb, 8, 0); /* select matrix */
240
241     /* Cb component */
242     put_bits(&s->pb, 8, 2); /* component number */
243     put_bits(&s->pb, 4, s->mjpeg_hsample[1]); /* H factor */
244     put_bits(&s->pb, 4, s->mjpeg_vsample[1]); /* V factor */
245 #ifdef TWOMATRIXES
246     put_bits(&s->pb, 8, lossless ? 0 : 1); /* select matrix */
247 #else
248     put_bits(&s->pb, 8, 0); /* select matrix */
249 #endif
250
251     /* Cr component */
252     put_bits(&s->pb, 8, 3); /* component number */
253     put_bits(&s->pb, 4, s->mjpeg_hsample[2]); /* H factor */
254     put_bits(&s->pb, 4, s->mjpeg_vsample[2]); /* V factor */
255 #ifdef TWOMATRIXES
256     put_bits(&s->pb, 8, lossless ? 0 : 1); /* select matrix */
257 #else
258     put_bits(&s->pb, 8, 0); /* select matrix */
259 #endif
260
261     /* scan header */
262     put_marker(&s->pb, SOS);
263     put_bits(&s->pb, 16, 12); /* length */
264     put_bits(&s->pb, 8, 3); /* 3 components */
265
266     /* Y component */
267     put_bits(&s->pb, 8, 1); /* index */
268     put_bits(&s->pb, 4, 0); /* DC huffman table index */
269     put_bits(&s->pb, 4, 0); /* AC huffman table index */
270
271     /* Cb component */
272     put_bits(&s->pb, 8, 2); /* index */
273     put_bits(&s->pb, 4, 1); /* DC huffman table index */
274     put_bits(&s->pb, 4, lossless ? 0 : 1); /* AC huffman table index */
275
276     /* Cr component */
277     put_bits(&s->pb, 8, 3); /* index */
278     put_bits(&s->pb, 4, 1); /* DC huffman table index */
279     put_bits(&s->pb, 4, lossless ? 0 : 1); /* AC huffman table index */
280
281     put_bits(&s->pb, 8, lossless ? s->avctx->prediction_method+1 : 0); /* Ss (not used) */
282
283     switch(s->avctx->codec_id){
284     case AV_CODEC_ID_MJPEG:  put_bits(&s->pb, 8, 63); break; /* Se (not used) */
285     case AV_CODEC_ID_LJPEG:  put_bits(&s->pb, 8,  0); break; /* not used */
286     default: av_assert0(0);
287     }
288
289     put_bits(&s->pb, 8, 0); /* Ah/Al (not used) */
290
291 end:
292     s->esc_pos = put_bits_count(&s->pb) >> 3;
293     for(i=1; i<s->slice_context_count; i++)
294         s->thread_context[i]->esc_pos = 0;
295 }
296
297 static void escape_FF(MpegEncContext *s, int start)
298 {
299     int size= put_bits_count(&s->pb) - start*8;
300     int i, ff_count;
301     uint8_t *buf= s->pb.buf + start;
302     int align= (-(size_t)(buf))&3;
303
304     av_assert1((size&7) == 0);
305     size >>= 3;
306
307     ff_count=0;
308     for(i=0; i<size && i<align; i++){
309         if(buf[i]==0xFF) ff_count++;
310     }
311     for(; i<size-15; i+=16){
312         int acc, v;
313
314         v= *(uint32_t*)(&buf[i]);
315         acc= (((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
316         v= *(uint32_t*)(&buf[i+4]);
317         acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
318         v= *(uint32_t*)(&buf[i+8]);
319         acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
320         v= *(uint32_t*)(&buf[i+12]);
321         acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
322
323         acc>>=4;
324         acc+= (acc>>16);
325         acc+= (acc>>8);
326         ff_count+= acc&0xFF;
327     }
328     for(; i<size; i++){
329         if(buf[i]==0xFF) ff_count++;
330     }
331
332     if(ff_count==0) return;
333
334     flush_put_bits(&s->pb);
335     skip_put_bytes(&s->pb, ff_count);
336
337     for(i=size-1; ff_count; i--){
338         int v= buf[i];
339
340         if(v==0xFF){
341             buf[i+ff_count]= 0;
342             ff_count--;
343         }
344
345         buf[i+ff_count]= v;
346     }
347 }
348
349 void ff_mjpeg_encode_stuffing(MpegEncContext *s)
350 {
351     int length, i;
352     PutBitContext *pbc = &s->pb;
353     int mb_y = s->mb_y - !s->mb_x;
354     length= (-put_bits_count(pbc))&7;
355     if(length) put_bits(pbc, length, (1<<length)-1);
356
357     flush_put_bits(&s->pb);
358     escape_FF(s, s->esc_pos);
359
360     if((s->avctx->active_thread_type & FF_THREAD_SLICE) && mb_y < s->mb_height)
361         put_marker(pbc, RST0 + (mb_y&7));
362     s->esc_pos = put_bits_count(pbc) >> 3;
363
364     for(i=0; i<3; i++)
365         s->last_dc[i] = 128 << s->intra_dc_precision;
366 }
367
368 void ff_mjpeg_encode_picture_trailer(MpegEncContext *s)
369 {
370
371     av_assert1((s->header_bits&7)==0);
372
373
374     put_marker(&s->pb, EOI);
375 }
376
377 void ff_mjpeg_encode_dc(MpegEncContext *s, int val,
378                         uint8_t *huff_size, uint16_t *huff_code)
379 {
380     int mant, nbits;
381
382     if (val == 0) {
383         put_bits(&s->pb, huff_size[0], huff_code[0]);
384     } else {
385         mant = val;
386         if (val < 0) {
387             val = -val;
388             mant--;
389         }
390
391         nbits= av_log2_16bit(val) + 1;
392
393         put_bits(&s->pb, huff_size[nbits], huff_code[nbits]);
394
395         put_sbits(&s->pb, nbits, mant);
396     }
397 }
398
399 static void encode_block(MpegEncContext *s, int16_t *block, int n)
400 {
401     int mant, nbits, code, i, j;
402     int component, dc, run, last_index, val;
403     MJpegContext *m = s->mjpeg_ctx;
404     uint8_t *huff_size_ac;
405     uint16_t *huff_code_ac;
406
407     /* DC coef */
408     component = (n <= 3 ? 0 : (n&1) + 1);
409     dc = block[0]; /* overflow is impossible */
410     val = dc - s->last_dc[component];
411     if (n < 4) {
412         ff_mjpeg_encode_dc(s, val, m->huff_size_dc_luminance, m->huff_code_dc_luminance);
413         huff_size_ac = m->huff_size_ac_luminance;
414         huff_code_ac = m->huff_code_ac_luminance;
415     } else {
416         ff_mjpeg_encode_dc(s, val, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);
417         huff_size_ac = m->huff_size_ac_chrominance;
418         huff_code_ac = m->huff_code_ac_chrominance;
419     }
420     s->last_dc[component] = dc;
421
422     /* AC coefs */
423
424     run = 0;
425     last_index = s->block_last_index[n];
426     for(i=1;i<=last_index;i++) {
427         j = s->intra_scantable.permutated[i];
428         val = block[j];
429         if (val == 0) {
430             run++;
431         } else {
432             while (run >= 16) {
433                 put_bits(&s->pb, huff_size_ac[0xf0], huff_code_ac[0xf0]);
434                 run -= 16;
435             }
436             mant = val;
437             if (val < 0) {
438                 val = -val;
439                 mant--;
440             }
441
442             nbits= av_log2(val) + 1;
443             code = (run << 4) | nbits;
444
445             put_bits(&s->pb, huff_size_ac[code], huff_code_ac[code]);
446
447             put_sbits(&s->pb, nbits, mant);
448             run = 0;
449         }
450     }
451
452     /* output EOB only if not already 64 values */
453     if (last_index < 63 || run != 0)
454         put_bits(&s->pb, huff_size_ac[0], huff_code_ac[0]);
455 }
456
457 void ff_mjpeg_encode_mb(MpegEncContext *s, int16_t block[6][64])
458 {
459     int i;
460     if (s->chroma_format == CHROMA_444) {
461         encode_block(s, block[0], 0);
462         encode_block(s, block[2], 2);
463         encode_block(s, block[4], 4);
464         encode_block(s, block[8], 8);
465         encode_block(s, block[5], 5);
466         encode_block(s, block[9], 9);
467
468         if (16*s->mb_x+8 < s->width) {
469             encode_block(s, block[1], 1);
470             encode_block(s, block[3], 3);
471             encode_block(s, block[6], 6);
472             encode_block(s, block[10], 10);
473             encode_block(s, block[7], 7);
474             encode_block(s, block[11], 11);
475         }
476     } else {
477         for(i=0;i<5;i++) {
478             encode_block(s, block[i], i);
479         }
480         if (s->chroma_format == CHROMA_420) {
481             encode_block(s, block[5], 5);
482         } else {
483             encode_block(s, block[6], 6);
484             encode_block(s, block[5], 5);
485             encode_block(s, block[7], 7);
486         }
487     }
488
489     s->i_tex_bits += get_bits_diff(s);
490 }
491
492 // maximum over s->mjpeg_vsample[i]
493 #define V_MAX 2
494 static int amv_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
495                               const AVFrame *pic_arg, int *got_packet)
496
497 {
498     MpegEncContext *s = avctx->priv_data;
499     AVFrame pic = *pic_arg;
500     int i;
501
502     //CODEC_FLAG_EMU_EDGE have to be cleared
503     if(s->avctx->flags & CODEC_FLAG_EMU_EDGE)
504         return -1;
505
506     //picture should be flipped upside-down
507     for(i=0; i < 3; i++) {
508         pic.data[i] += (pic.linesize[i] * (s->mjpeg_vsample[i] * (8 * s->mb_height -((s->height/V_MAX)&7)) - 1 ));
509         pic.linesize[i] *= -1;
510     }
511     return ff_MPV_encode_picture(avctx, pkt, &pic, got_packet);
512 }
513
514 #if CONFIG_MJPEG_ENCODER
515 AVCodec ff_mjpeg_encoder = {
516     .name           = "mjpeg",
517     .type           = AVMEDIA_TYPE_VIDEO,
518     .id             = AV_CODEC_ID_MJPEG,
519     .priv_data_size = sizeof(MpegEncContext),
520     .init           = ff_MPV_encode_init,
521     .encode2        = ff_MPV_encode_picture,
522     .close          = ff_MPV_encode_end,
523     .capabilities   = CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS | CODEC_CAP_INTRA_ONLY,
524     .pix_fmts       = (const enum AVPixelFormat[]){
525         AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE
526     },
527     .long_name      = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
528 };
529 #endif
530 #if CONFIG_AMV_ENCODER
531 AVCodec ff_amv_encoder = {
532     .name           = "amv",
533     .type           = AVMEDIA_TYPE_VIDEO,
534     .id             = AV_CODEC_ID_AMV,
535     .priv_data_size = sizeof(MpegEncContext),
536     .init           = ff_MPV_encode_init,
537     .encode2        = amv_encode_picture,
538     .close          = ff_MPV_encode_end,
539     .pix_fmts       = (const enum AVPixelFormat[]){
540         AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_NONE
541     },
542     .long_name      = NULL_IF_CONFIG_SMALL("AMV Video"),
543 };
544 #endif