]> git.sesse.net Git - ffmpeg/blobdiff - libavcodec/mjpeg.c
fixing aspect (hopefully, i couldnt reproduce the bug)
[ffmpeg] / libavcodec / mjpeg.c
index baaf8ad532e1ece02cdc6cb447faa359d8d5af84..2e6dd8f0be67359ef7303dd8f0f5d5059ee958e2 100644 (file)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * Support for external huffman table, various fixes (AVID workaround),
- * aspecting and new decode_frame mechanism
+ * aspecting, new decode_frame mechanism and apple mjpeg-b support
  *                                  by Alex Beregszaszi <alex@naxine.org>
  */
-#define DEBUG
+//#define DEBUG
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 
-#ifdef USE_FASTMEMCPY
-#include "fastmemcpy.h"
-#endif
-
 /* use two quantizer tables (one for luminance and one for chrominance) */
 /* not yet working */
 #undef TWOMATRIXES
@@ -474,9 +470,73 @@ void mjpeg_picture_header(MpegEncContext *s)
     put_bits(&s->pb, 8, 0); /* Ah/Al (not used) */
 }
 
+static void escape_FF(MpegEncContext *s, int start)
+{
+    int size= get_bit_count(&s->pb) - start*8;
+    int i, ff_count;
+    uint8_t *buf= s->pb.buf + start;
+    int align= (-(int)(buf))&3;
+    
+    assert((size&7) == 0);
+    size >>= 3;
+    
+    ff_count=0;
+    for(i=0; i<size && i<align; i++){
+        if(buf[i]==0xFF) ff_count++;
+    }
+    for(; i<size-15; i+=16){
+        int acc, v;
+
+        v= *(uint32_t*)(&buf[i]);
+        acc= (((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
+        v= *(uint32_t*)(&buf[i+4]);
+        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
+        v= *(uint32_t*)(&buf[i+8]);
+        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
+        v= *(uint32_t*)(&buf[i+12]);
+        acc+=(((v & (v>>4))&0x0F0F0F0F)+0x01010101)&0x10101010;
+
+        acc>>=4;
+        acc+= (acc>>16);
+        acc+= (acc>>8);
+        ff_count+= acc&0xFF;
+    }
+    for(; i<size; i++){
+        if(buf[i]==0xFF) ff_count++;
+    }
+
+    if(ff_count==0) return;
+    
+    /* skip put bits */
+    for(i=0; i<ff_count-3; i+=4)
+        put_bits(&s->pb, 32, 0);
+    put_bits(&s->pb, (ff_count-i)*8, 0);
+    flush_put_bits(&s->pb); 
+
+    for(i=size-1; ff_count; i--){
+        int v= buf[i];
+
+        if(v==0xFF){
+//printf("%d %d\n", i, ff_count);
+            buf[i+ff_count]= 0;
+            ff_count--;
+        }
+
+        buf[i+ff_count]= v;
+    }
+}
+
 void mjpeg_picture_trailer(MpegEncContext *s)
 {
-    jflush_put_bits(&s->pb);
+    int pad= (-get_bit_count(&s->pb))&7;
+    
+    put_bits(&s->pb, pad,0xFF>>(8-pad));
+    flush_put_bits(&s->pb);
+
+    assert((s->header_bits&7)==0);
+    
+    escape_FF(s, s->header_bits>>3);
+
     put_marker(&s->pb, EOI);
 }
 
@@ -486,7 +546,7 @@ static inline void mjpeg_encode_dc(MpegEncContext *s, int val,
     int mant, nbits;
 
     if (val == 0) {
-        jput_bits(&s->pb, huff_size[0], huff_code[0]);
+        put_bits(&s->pb, huff_size[0], huff_code[0]);
     } else {
         mant = val;
         if (val < 0) {
@@ -501,9 +561,9 @@ static inline void mjpeg_encode_dc(MpegEncContext *s, int val,
             nbits++;
         }
             
-        jput_bits(&s->pb, huff_size[nbits], huff_code[nbits]);
+        put_bits(&s->pb, huff_size[nbits], huff_code[nbits]);
         
-        jput_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
+        put_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
     }
 }
 
@@ -541,7 +601,7 @@ static void encode_block(MpegEncContext *s, DCTELEM *block, int n)
             run++;
         } else {
             while (run >= 16) {
-                jput_bits(&s->pb, huff_size_ac[0xf0], huff_code_ac[0xf0]);
+                put_bits(&s->pb, huff_size_ac[0xf0], huff_code_ac[0xf0]);
                 run -= 16;
             }
             mant = val;
@@ -558,16 +618,16 @@ static void encode_block(MpegEncContext *s, DCTELEM *block, int n)
             }
             code = (run << 4) | nbits;
 
-            jput_bits(&s->pb, huff_size_ac[code], huff_code_ac[code]);
+            put_bits(&s->pb, huff_size_ac[code], huff_code_ac[code]);
         
-            jput_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
+            put_bits(&s->pb, nbits, mant & ((1 << nbits) - 1));
             run = 0;
         }
     }
 
     /* output EOB only if not already 64 values */
     if (last_index < 63 || run != 0)
-        jput_bits(&s->pb, huff_size_ac[0], huff_code_ac[0]);
+        put_bits(&s->pb, huff_size_ac[0], huff_code_ac[0]);
 }
 
 void mjpeg_encode_mb(MpegEncContext *s, 
@@ -582,9 +642,6 @@ void mjpeg_encode_mb(MpegEncContext *s,
 /******************************************/
 /* decoding */
 
-/* compressed picture size */
-#define PICTURE_BUFFER_SIZE 100000
-
 #define MAX_COMPONENTS 4
 
 typedef struct MJpegDecodeContext {
@@ -615,13 +672,14 @@ typedef struct MJpegDecodeContext {
     UINT8 *current_picture[MAX_COMPONENTS]; /* picture structure */
     int linesize[MAX_COMPONENTS];
     DCTELEM block[64] __align8;
+    ScanTable scantable;
+    void (*idct_put)(UINT8 *dest/*align 8*/, int line_size, DCTELEM *block/*align 16*/);
 
-    int buggy_avid;
     int restart_interval;
     int restart_count;
-    int interleaved_rows;
-    ScanTable scantable;
-    void (*idct_put)(UINT8 *dest/*align 8*/, int line_size, DCTELEM *block/*align 16*/);
+
+    int buggy_avid;
+    int interlace_polarity;
 } MJpegDecodeContext;
 
 static int mjpeg_decode_dht(MJpegDecodeContext *s);
@@ -659,8 +717,8 @@ static int mjpeg_decode_init(AVCodecContext *avctx)
     MPV_common_end(&s2);
 
     s->mpeg_enc_ctx_allocated = 0;
-    s->buffer_size = PICTURE_BUFFER_SIZE - 1; /* minus 1 to take into
-                                                 account FF 00 case */
+    s->buffer_size = 102400; /* smaller buffer should be enough,
+                               but photojpg files could ahive bigger sizes */
     s->buffer = av_malloc(s->buffer_size);
     s->start_code = -1;
     s->first_picture = 1;
@@ -806,6 +864,7 @@ static int mjpeg_decode_sof0(MJpegDecodeContext *s)
             s->org_height != 0 &&
             s->height < ((s->org_height * 3) / 4)) {
             s->interlaced = 1;
+//         s->bottom_field = (s->interlace_polarity) ? 1 : 0;
            s->bottom_field = 0;
         }
 
@@ -818,8 +877,12 @@ static int mjpeg_decode_sof0(MJpegDecodeContext *s)
             if (s->interlaced)
                 w *= 2;
             s->linesize[i] = w;
-            /* memory test is done in mjpeg_decode_sos() */
             s->current_picture[i] = av_mallocz(w * h);
+           if (!s->current_picture[i])
+           {
+               dprintf("error: no picture buffers allocated\n");
+               return -1;
+           }
         }
         s->first_picture = 0;
     }
@@ -835,9 +898,8 @@ static int mjpeg_decode_sof0(MJpegDecodeContext *s)
 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
 {
     int code, diff;
-#if 0
-    code = get_vlc2(&s->gb, s->vlc[0][dc_index].table,
-       s->vlc[0][dc_index].bits, 1);
+#if 1
+    code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
 #else
     code = get_vlc(&s->gb, &s->vlcs[0][dc_index]);
 #endif
@@ -880,9 +942,8 @@ static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
     ac_vlc = &s->vlcs[1][ac_index];
     i = 1;
     for(;;) {
-#if 0
-       code = get_vlc2(&s->gb, s->vlcs[1][ac_index].table,
-           s->vlcs[1][ac_index].bits, 2);
+#if 1
+       code = get_vlc2(&s->gb, s->vlcs[1][ac_index].table, 9, 2);
 #else
         code = get_vlc(&s->gb, ac_vlc);
 #endif
@@ -1004,7 +1065,7 @@ static int mjpeg_decode_sos(MJpegDecodeContext *s)
         h_count[0] = 1;
         v_count[0] = 1;
     }
-
+    
     for(mb_y = 0; mb_y < mb_height; mb_y++) {
         for(mb_x = 0; mb_x < mb_width; mb_x++) {
             for(i=0;i<nb_components;i++) {
@@ -1040,7 +1101,9 @@ static int mjpeg_decode_sos(MJpegDecodeContext *s)
                     }
                 }
             }
-            if (s->restart_interval && !--s->restart_count) {
+           /* (< 1350) buggy workaround for Spectralfan.mov, should be fixed */
+            if (s->restart_interval && (s->restart_interval < 1350) &&
+               !--s->restart_count) {
                 align_get_bits(&s->gb);
                 skip_bits(&s->gb, 16); /* skip RSTn */
                 for (j=0; j<nb_components; j++) /* reset dc */
@@ -1067,8 +1130,7 @@ static int mjpeg_decode_dri(MJpegDecodeContext *s)
     return 0;
 }
 
-#define FOURCC(a,b,c,d) ((a << 24) | (b << 16) | (c << 8) | d)
-static int mjpeg_decode_app(MJpegDecodeContext *s, int start_code)
+static int mjpeg_decode_app(MJpegDecodeContext *s)
 {
     int len, id;
 
@@ -1078,12 +1140,13 @@ static int mjpeg_decode_app(MJpegDecodeContext *s, int start_code)
        return -1;
 
     id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
+    id = be2me_32(id);
     len -= 6;
 
     /* buggy AVID, it puts EOI only at every 10th frame */
-    /* also this fourcc is used by non-avid files too, it means
-       interleaving, but it's always present in AVID files */
-    if (id == FOURCC('A','V','I','1'))
+    /* also this fourcc is used by non-avid files too, it holds some
+       informations, but it's always present in AVID creates files */
+    if (id == ff_get_fourcc("AVI1"))
     {
        /* structure:
            4bytes      AVI1
@@ -1093,49 +1156,74 @@ static int mjpeg_decode_app(MJpegDecodeContext *s, int start_code)
            4bytes      field_size_less_padding
        */
        s->buggy_avid = 1;
-       if (s->first_picture)
-           printf("mjpeg: workarounding buggy AVID\n");
-       s->interleaved_rows = get_bits(&s->gb, 8);
+//     if (s->first_picture)
+//         printf("mjpeg: workarounding buggy AVID\n");
+       s->interlace_polarity = get_bits(&s->gb, 8);
 #if 0
        skip_bits(&s->gb, 8);
        skip_bits(&s->gb, 32);
        skip_bits(&s->gb, 32);
        len -= 10;
 #endif
-       if (s->interleaved_rows)
-           printf("mjpeg: interleaved rows: %d\n", s->interleaved_rows);
+//     if (s->interlace_polarity)
+//         printf("mjpeg: interlace polarity: %d\n", s->interlace_polarity);
        goto out;
     }
     
-    len -= 2;
+//    len -= 2;
     
-    if (id == FOURCC('J','F','I','F'))
+    if (id == ff_get_fourcc("JFIF"))
     {
+       int t_w, t_h;
        skip_bits(&s->gb, 8); /* the trailing zero-byte */
        printf("mjpeg: JFIF header found (version: %x.%x)\n",
            get_bits(&s->gb, 8), get_bits(&s->gb, 8));
        if (get_bits(&s->gb, 8) == 0)
        {
-           s->avctx->aspect_ratio_info = FF_ASPECT_EXTENDED;
-           s->avctx->aspected_width = get_bits(&s->gb, 16);
-           s->avctx->aspected_height = get_bits(&s->gb, 16);
+           int x_density = get_bits(&s->gb, 16);
+           int y_density = get_bits(&s->gb, 16);
+
+            //MN: needs to be checked
+            if(x_density)
+                s->avctx->aspect_ratio= s->width*y_density/((float)s->height*x_density);
+            else
+                s->avctx->aspect_ratio= 0.0;
        }
        else
        {
            skip_bits(&s->gb, 16);
            skip_bits(&s->gb, 16);
        }
-       skip_bits(&s->gb, 8);
-       skip_bits(&s->gb, 8);
+       t_w = get_bits(&s->gb, 8);
+       t_h = get_bits(&s->gb, 8);
+       if (t_w && t_h)
+       {
+           /* skip thumbnail */
+           if (len-10-(t_w*t_h*3) > 0)
+               len -= t_w*t_h*3;
+       }
+       len -= 10;
+       goto out;
+    }
+    
+    if (id == ff_get_fourcc("Adob") && (get_bits(&s->gb, 8) == 'e'))
+    {
+       printf("mjpeg: Adobe header found\n");
+       skip_bits(&s->gb, 16); /* version */
+       skip_bits(&s->gb, 16); /* flags0 */
+       skip_bits(&s->gb, 16); /* flags1 */
+       skip_bits(&s->gb, 8); /* transform */
+       len -= 7;
        goto out;
     }
     
     /* Apple MJPEG-A */
-    if ((start_code == APP1) && (len > (0x28 - 8)))
+    if ((s->start_code == APP1) && (len > (0x28 - 8)))
     {
        id = (get_bits(&s->gb, 16) << 16) | get_bits(&s->gb, 16);
+       id = be2me_32(id);
        len -= 4;
-        if (id == FOURCC('m','j','p','g')) /* Apple MJPEG-A */
+       if (id == ff_get_fourcc("mjpg")) /* Apple MJPEG-A */
        {
 #if 0
            skip_bits(&s->gb, 32); /* field size */
@@ -1153,11 +1241,14 @@ static int mjpeg_decode_app(MJpegDecodeContext *s, int start_code)
     }
 
 out:
-    /* should check for further values.. */
+    /* slow but needed for extreme adobe jpegs */
+    if (len < 0)
+       printf("mjpeg: error, decode_app parser read over the end\n");
+    while(--len > 0)
+       skip_bits(&s->gb, 8);
 
     return 0;
 }
-#undef FOURCC
 
 static int mjpeg_decode_com(MJpegDecodeContext *s)
 {
@@ -1277,6 +1368,8 @@ static int mjpeg_decode_frame(AVCodecContext *avctx,
                    av_free(s->buffer);
                    s->buffer_size = buf_end-buf_ptr;
                    s->buffer = av_malloc(s->buffer_size);
+                   dprintf("buffer too small, expanding to %d bytes\n",
+                       s->buffer_size);
                }
                
                /* unescape buffer of SOS */
@@ -1287,11 +1380,13 @@ static int mjpeg_decode_frame(AVCodecContext *avctx,
 
                    while (src<buf_end)
                    {
-                       unsigned char *x = *(src++);
-                       
+                       UINT8 x = *(src++);
+
                        *(dst++) = x;
                        if (x == 0xff)
                        {
+                           while(*src == 0xff) src++;
+
                            x = *(src++);
                            if (x >= 0xd0 && x <= 0xd7)
                                *(dst++) = x;
@@ -1299,10 +1394,13 @@ static int mjpeg_decode_frame(AVCodecContext *avctx,
                                break;
                        }
                    }
+                   init_get_bits(&s->gb, s->buffer, dst - s->buffer);
+                   
+                   dprintf("escaping removed %d bytes\n",
+                       (buf_end - buf_ptr) - (dst - s->buffer));
                }
                else
-                   memcpy(s->buffer, buf_ptr, buf_end - buf_ptr);
-               init_get_bits(&s->gb, s->buffer, s->buffer_size);
+                   init_get_bits(&s->gb, buf_ptr, buf_end - buf_ptr);
                
                s->start_code = start_code;
 
@@ -1312,7 +1410,7 @@ static int mjpeg_decode_frame(AVCodecContext *avctx,
                } else if (s->first_picture) {
                    /* APP fields */
                    if (start_code >= 0xe0 && start_code <= 0xef)
-                       mjpeg_decode_app(s, start_code);
+                       mjpeg_decode_app(s);
                    /* Comment */
                    else if (start_code == COM)
                        mjpeg_decode_com(s);
@@ -1330,7 +1428,8 @@ static int mjpeg_decode_frame(AVCodecContext *avctx,
                     mjpeg_decode_dht(s);
                     break;
                 case SOF0:
-                    mjpeg_decode_sof0(s);
+                    if (mjpeg_decode_sof0(s) < 0)
+                       return -1;
                     break;
                case EOI:
 eoi_parser:
@@ -1374,7 +1473,7 @@ eoi_parser:
                         }
                         /* dummy quality */
                         /* XXX: infer it with matrix */
-                       avctx->quality = 3; 
+//                     avctx->quality = 3; 
                         goto the_end;
                     }
                    break;
@@ -1417,12 +1516,136 @@ not_the_end:
         }
     }
 the_end:
-
     dprintf("mjpeg decode frame unused %d bytes\n", buf_end - buf_ptr);
 //    return buf_end - buf_ptr;
     return buf_ptr - buf;
 }
 
+static int mjpegb_decode_frame(AVCodecContext *avctx, 
+                              void *data, int *data_size,
+                              UINT8 *buf, int buf_size)
+{
+    MJpegDecodeContext *s = avctx->priv_data;
+    UINT8 *buf_end, *buf_ptr;
+    int i;
+    AVPicture *picture = data;
+    GetBitContext hgb; /* for the header */
+    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;
+    uint32_t field_size;
+
+    *data_size = 0;
+
+    /* no supplementary picture */
+    if (buf_size == 0)
+        return 0;
+
+    buf_ptr = buf;
+    buf_end = buf + buf_size;
+    
+read_header:
+    /* reset on every SOI */
+    s->restart_interval = 0;
+
+    init_get_bits(&hgb, buf_ptr, /*buf_size*/buf_end - buf_ptr);
+
+    skip_bits(&hgb, 32); /* reserved zeros */
+    
+    if (get_bits(&hgb, 32) != be2me_32(ff_get_fourcc("mjpg")))
+    {
+       dprintf("not mjpeg-b (bad fourcc)\n");
+       return 0;
+    }
+
+    field_size = get_bits(&hgb, 32); /* field size */
+    dprintf("field size: 0x%x\n", field_size);
+    skip_bits(&hgb, 32); /* padded field size */
+    second_field_offs = get_bits(&hgb, 32);
+    dprintf("second field offs: 0x%x\n", second_field_offs);
+    if (second_field_offs)
+       s->interlaced = 1;
+
+    dqt_offs = get_bits(&hgb, 32);
+    dprintf("dqt offs: 0x%x\n", dqt_offs);
+    if (dqt_offs)
+    {
+       init_get_bits(&s->gb, buf+dqt_offs, buf_end - (buf+dqt_offs));
+       s->start_code = DQT;
+       mjpeg_decode_dqt(s);
+    }
+    
+    dht_offs = get_bits(&hgb, 32);
+    dprintf("dht offs: 0x%x\n", dht_offs);
+    if (dht_offs)
+    {
+       init_get_bits(&s->gb, buf+dht_offs, buf_end - (buf+dht_offs));
+       s->start_code = DHT;
+       mjpeg_decode_dht(s);
+    }
+
+    sof_offs = get_bits(&hgb, 32);
+    dprintf("sof offs: 0x%x\n", sof_offs);
+    if (sof_offs)
+    {
+       init_get_bits(&s->gb, buf+sof_offs, buf_end - (buf+sof_offs));
+       s->start_code = SOF0;
+       if (mjpeg_decode_sof0(s) < 0)
+           return -1;
+    }
+
+    sos_offs = get_bits(&hgb, 32);
+    dprintf("sos offs: 0x%x\n", sos_offs);
+    if (sos_offs)
+    {
+//     init_get_bits(&s->gb, buf+sos_offs, buf_end - (buf+sos_offs));
+       init_get_bits(&s->gb, buf+sos_offs, field_size);
+       s->start_code = SOS;
+       mjpeg_decode_sos(s);
+    }
+
+    skip_bits(&hgb, 32); /* start of data offset */
+
+    if (s->interlaced) {
+        s->bottom_field ^= 1;
+        /* if not bottom field, do not output image yet */
+        if (s->bottom_field && second_field_offs)
+       {
+           buf_ptr = buf + second_field_offs;
+           second_field_offs = 0;
+           goto read_header;
+       }
+    }
+
+    for(i=0;i<3;i++) {
+        picture->data[i] = s->current_picture[i];
+        picture->linesize[i] = (s->interlaced) ?
+           s->linesize[i] >> 1 : s->linesize[i];
+    }
+    *data_size = sizeof(AVPicture);
+    avctx->height = s->height;
+    if (s->interlaced)
+        avctx->height *= 2;
+    avctx->width = s->width;
+    /* XXX: not complete test ! */
+    switch((s->h_count[0] << 4) | s->v_count[0]) {
+        case 0x11:
+           avctx->pix_fmt = PIX_FMT_YUV444P;
+            break;
+        case 0x21:
+            avctx->pix_fmt = PIX_FMT_YUV422P;
+            break;
+        default:
+       case 0x22:
+            avctx->pix_fmt = PIX_FMT_YUV420P;
+            break;
+    }
+    /* dummy quality */
+    /* XXX: infer it with matrix */
+//    avctx->quality = 3; 
+
+    return buf_ptr - buf;
+}
+
+
 static int mjpeg_decode_end(AVCodecContext *avctx)
 {
     MJpegDecodeContext *s = avctx->priv_data;
@@ -1450,3 +1673,16 @@ AVCodec mjpeg_decoder = {
     0,
     NULL
 };
+
+AVCodec mjpegb_decoder = {
+    "mjpegb",
+    CODEC_TYPE_VIDEO,
+    CODEC_ID_MJPEGB,
+    sizeof(MJpegDecodeContext),
+    mjpeg_decode_init,
+    NULL,
+    mjpeg_decode_end,
+    mjpegb_decode_frame,
+    0,
+    NULL
+};