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