libavcodec/j2kdec.c
Go to the documentation of this file.
00001 /*
00002  * JPEG2000 image decoder
00003  * Copyright (c) 2007 Kamil Nowosad
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00028 #include "avcodec.h"
00029 #include "bytestream.h"
00030 #include "j2k.h"
00031 #include "libavutil/common.h"
00032 
00033 #define JP2_SIG_TYPE    0x6A502020
00034 #define JP2_SIG_VALUE   0x0D0A870A
00035 #define JP2_CODESTREAM  0x6A703263
00036 
00037 #define HAD_COC 0x01
00038 #define HAD_QCC 0x02
00039 
00040 typedef struct {
00041    J2kComponent *comp;
00042    uint8_t properties[4];
00043    J2kCodingStyle codsty[4];
00044    J2kQuantStyle  qntsty[4];
00045 } J2kTile;
00046 
00047 typedef struct {
00048     AVCodecContext *avctx;
00049     AVFrame picture;
00050 
00051     int width, height; 
00052     int image_offset_x, image_offset_y;
00053     int tile_offset_x, tile_offset_y;
00054     uint8_t cbps[4]; 
00055     uint8_t sgnd[4]; 
00056     uint8_t properties[4];
00057     int cdx[4], cdy[4];
00058     int precision;
00059     int ncomponents;
00060     int tile_width, tile_height; 
00061     int numXtiles, numYtiles;
00062     int maxtilelen;
00063 
00064     J2kCodingStyle codsty[4];
00065     J2kQuantStyle  qntsty[4];
00066 
00067     const uint8_t *buf_start;
00068     const uint8_t *buf;
00069     const uint8_t *buf_end;
00070     int bit_index;
00071 
00072     int16_t curtileno;
00073 
00074     J2kTile *tile;
00075 } J2kDecoderContext;
00076 
00077 static int get_bits(J2kDecoderContext *s, int n)
00078 {
00079     int res = 0;
00080     if (s->buf_end - s->buf < ((n - s->bit_index) >> 8))
00081         return AVERROR(EINVAL);
00082     while (--n >= 0){
00083         res <<= 1;
00084         if (s->bit_index == 0){
00085             s->bit_index = 7 + (*s->buf != 0xff);
00086             s->buf++;
00087         }
00088         s->bit_index--;
00089         res |= (*s->buf >> s->bit_index) & 1;
00090     }
00091     return res;
00092 }
00093 
00094 static void j2k_flush(J2kDecoderContext *s)
00095 {
00096     if (*s->buf == 0xff)
00097         s->buf++;
00098     s->bit_index = 8;
00099     s->buf++;
00100 }
00101 #if 0
00102 void printcomp(J2kComponent *comp)
00103 {
00104     int i;
00105     for (i = 0; i < comp->y1 - comp->y0; i++)
00106         ff_j2k_printv(comp->data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
00107 }
00108 
00109 static void nspaces(FILE *fd, int n)
00110 {
00111     while(n--) putc(' ', fd);
00112 }
00113 
00114 static void dump(J2kDecoderContext *s, FILE *fd)
00115 {
00116     int tileno, compno, reslevelno, bandno, precno;
00117     fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
00118                 "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
00119                 "tiles:\n",
00120             s->width, s->height, s->tile_width, s->tile_height,
00121             s->numXtiles, s->numYtiles, s->ncomponents);
00122     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
00123         J2kTile *tile = s->tile + tileno;
00124         nspaces(fd, 2);
00125         fprintf(fd, "tile %d:\n", tileno);
00126         for(compno = 0; compno < s->ncomponents; compno++){
00127             J2kComponent *comp = tile->comp + compno;
00128             nspaces(fd, 4);
00129             fprintf(fd, "component %d:\n", compno);
00130             nspaces(fd, 4);
00131             fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
00132                         comp->x0, comp->x1, comp->y0, comp->y1);
00133             for(reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
00134                 J2kResLevel *reslevel = comp->reslevel + reslevelno;
00135                 nspaces(fd, 6);
00136                 fprintf(fd, "reslevel %d:\n", reslevelno);
00137                 nspaces(fd, 6);
00138                 fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
00139                         reslevel->x0, reslevel->x1, reslevel->y0,
00140                         reslevel->y1, reslevel->nbands);
00141                 for(bandno = 0; bandno < reslevel->nbands; bandno++){
00142                     J2kBand *band = reslevel->band + bandno;
00143                     nspaces(fd, 8);
00144                     fprintf(fd, "band %d:\n", bandno);
00145                     nspaces(fd, 8);
00146                     fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
00147                                 "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
00148                                 band->x0, band->x1,
00149                                 band->y0, band->y1,
00150                                 band->codeblock_width, band->codeblock_height,
00151                                 band->cblknx, band->cblkny);
00152                     for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
00153                         J2kPrec *prec = band->prec + precno;
00154                         nspaces(fd, 10);
00155                         fprintf(fd, "prec %d:\n", precno);
00156                         nspaces(fd, 10);
00157                         fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
00158                                      prec->xi0, prec->xi1, prec->yi0, prec->yi1);
00159                     }
00160                 }
00161             }
00162         }
00163     }
00164 }
00165 #endif
00166 
00168 static int tag_tree_decode(J2kDecoderContext *s, J2kTgtNode *node, int threshold)
00169 {
00170     J2kTgtNode *stack[30];
00171     int sp = -1, curval = 0;
00172 
00173     while(node && !node->vis){
00174         stack[++sp] = node;
00175         node = node->parent;
00176     }
00177 
00178     if (node)
00179         curval = node->val;
00180     else
00181         curval = stack[sp]->val;
00182 
00183     while(curval < threshold && sp >= 0){
00184         if (curval < stack[sp]->val)
00185             curval = stack[sp]->val;
00186         while (curval < threshold){
00187             int ret;
00188             if ((ret = get_bits(s, 1)) > 0){
00189                 stack[sp]->vis++;
00190                 break;
00191             } else if (!ret)
00192                 curval++;
00193             else
00194                 return ret;
00195         }
00196         stack[sp]->val = curval;
00197         sp--;
00198     }
00199     return curval;
00200 }
00201 
00202 /* marker segments */
00204 static int get_siz(J2kDecoderContext *s)
00205 {
00206     int i, ret;
00207 
00208     if (s->buf_end - s->buf < 36)
00209         return AVERROR(EINVAL);
00210 
00211                         bytestream_get_be16(&s->buf); // Rsiz (skipped)
00212              s->width = bytestream_get_be32(&s->buf); // width
00213             s->height = bytestream_get_be32(&s->buf); // height
00214     s->image_offset_x = bytestream_get_be32(&s->buf); // X0Siz
00215     s->image_offset_y = bytestream_get_be32(&s->buf); // Y0Siz
00216 
00217         s->tile_width = bytestream_get_be32(&s->buf); // XTSiz
00218        s->tile_height = bytestream_get_be32(&s->buf); // YTSiz
00219      s->tile_offset_x = bytestream_get_be32(&s->buf); // XT0Siz
00220      s->tile_offset_y = bytestream_get_be32(&s->buf); // YT0Siz
00221        s->ncomponents = bytestream_get_be16(&s->buf); // CSiz
00222 
00223     if(s->tile_width<=0 || s->tile_height<=0)
00224         return AVERROR(EINVAL);
00225 
00226     if (s->buf_end - s->buf < 2 * s->ncomponents)
00227         return AVERROR(EINVAL);
00228 
00229     for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
00230         uint8_t x = bytestream_get_byte(&s->buf);
00231         s->cbps[i] = (x & 0x7f) + 1;
00232         s->precision = FFMAX(s->cbps[i], s->precision);
00233         s->sgnd[i] = !!(x & 0x80);
00234         s->cdx[i] = bytestream_get_byte(&s->buf);
00235         s->cdy[i] = bytestream_get_byte(&s->buf);
00236     }
00237 
00238     s->numXtiles = ff_j2k_ceildiv(s->width - s->tile_offset_x, s->tile_width);
00239     s->numYtiles = ff_j2k_ceildiv(s->height - s->tile_offset_y, s->tile_height);
00240 
00241     if(s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(J2kTile))
00242         return AVERROR(EINVAL);
00243 
00244     s->tile = av_mallocz(s->numXtiles * s->numYtiles * sizeof(J2kTile));
00245     if (!s->tile)
00246         return AVERROR(ENOMEM);
00247 
00248     for (i = 0; i < s->numXtiles * s->numYtiles; i++){
00249         J2kTile *tile = s->tile + i;
00250 
00251         tile->comp = av_mallocz(s->ncomponents * sizeof(J2kComponent));
00252         if (!tile->comp)
00253             return AVERROR(ENOMEM);
00254     }
00255 
00256     s->avctx->width = s->width - s->image_offset_x;
00257     s->avctx->height = s->height - s->image_offset_y;
00258 
00259     switch(s->ncomponents){
00260         case 1: if (s->precision > 8) {
00261                     s->avctx->pix_fmt    = PIX_FMT_GRAY16;
00262                 } else s->avctx->pix_fmt = PIX_FMT_GRAY8;
00263                 break;
00264         case 3: if (s->precision > 8) {
00265                     s->avctx->pix_fmt    = PIX_FMT_RGB48;
00266                 } else s->avctx->pix_fmt = PIX_FMT_RGB24;
00267                 break;
00268         case 4: s->avctx->pix_fmt = PIX_FMT_BGRA; break;
00269     }
00270 
00271     if (s->picture.data[0])
00272         s->avctx->release_buffer(s->avctx, &s->picture);
00273 
00274     if ((ret = s->avctx->get_buffer(s->avctx, &s->picture)) < 0)
00275         return ret;
00276 
00277     s->picture.pict_type = AV_PICTURE_TYPE_I;
00278     s->picture.key_frame = 1;
00279 
00280     return 0;
00281 }
00282 
00284 static int get_cox(J2kDecoderContext *s, J2kCodingStyle *c)
00285 {
00286     if (s->buf_end - s->buf < 5)
00287         return AVERROR(EINVAL);
00288           c->nreslevels = bytestream_get_byte(&s->buf) + 1; // num of resolution levels - 1
00289      c->log2_cblk_width = bytestream_get_byte(&s->buf) + 2; // cblk width
00290     c->log2_cblk_height = bytestream_get_byte(&s->buf) + 2; // cblk height
00291 
00292     c->cblk_style = bytestream_get_byte(&s->buf);
00293     if (c->cblk_style != 0){ // cblk style
00294         av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
00295     }
00296     c->transform = bytestream_get_byte(&s->buf); // transformation
00297     if (c->csty & J2K_CSTY_PREC) {
00298         int i;
00299         for (i = 0; i < c->nreslevels; i++)
00300             bytestream_get_byte(&s->buf);
00301     }
00302     return 0;
00303 }
00304 
00306 static int get_cod(J2kDecoderContext *s, J2kCodingStyle *c, uint8_t *properties)
00307 {
00308     J2kCodingStyle tmp;
00309     int compno;
00310 
00311     if (s->buf_end - s->buf < 5)
00312         return AVERROR(EINVAL);
00313 
00314     tmp.log2_prec_width  =
00315     tmp.log2_prec_height = 15;
00316 
00317     tmp.csty = bytestream_get_byte(&s->buf);
00318 
00319     if (bytestream_get_byte(&s->buf)){ // progression level
00320         av_log(s->avctx, AV_LOG_ERROR, "only LRCP progression supported\n");
00321         return -1;
00322     }
00323 
00324     tmp.nlayers = bytestream_get_be16(&s->buf);
00325         tmp.mct = bytestream_get_byte(&s->buf); // multiple component transformation
00326 
00327     get_cox(s, &tmp);
00328     for (compno = 0; compno < s->ncomponents; compno++){
00329         if (!(properties[compno] & HAD_COC))
00330             memcpy(c + compno, &tmp, sizeof(J2kCodingStyle));
00331     }
00332     return 0;
00333 }
00334 
00336 static int get_coc(J2kDecoderContext *s, J2kCodingStyle *c, uint8_t *properties)
00337 {
00338     int compno;
00339 
00340     if (s->buf_end - s->buf < 2)
00341         return AVERROR(EINVAL);
00342 
00343     compno = bytestream_get_byte(&s->buf);
00344 
00345     c += compno;
00346     c->csty = bytestream_get_byte(&s->buf);
00347     get_cox(s, c);
00348 
00349     properties[compno] |= HAD_COC;
00350     return 0;
00351 }
00352 
00354 static int get_qcx(J2kDecoderContext *s, int n, J2kQuantStyle *q)
00355 {
00356     int i, x;
00357 
00358     if (s->buf_end - s->buf < 1)
00359         return AVERROR(EINVAL);
00360 
00361     x = bytestream_get_byte(&s->buf); // Sqcd
00362 
00363     q->nguardbits = x >> 5;
00364       q->quantsty = x & 0x1f;
00365 
00366     if (q->quantsty == J2K_QSTY_NONE){
00367         n -= 3;
00368         if (s->buf_end - s->buf < n || 32*3 < n)
00369             return AVERROR(EINVAL);
00370         for (i = 0; i < n; i++)
00371             q->expn[i] = bytestream_get_byte(&s->buf) >> 3;
00372     } else if (q->quantsty == J2K_QSTY_SI){
00373         if (s->buf_end - s->buf < 2)
00374             return AVERROR(EINVAL);
00375         x = bytestream_get_be16(&s->buf);
00376         q->expn[0] = x >> 11;
00377         q->mant[0] = x & 0x7ff;
00378         for (i = 1; i < 32 * 3; i++){
00379             int curexpn = FFMAX(0, q->expn[0] - (i-1)/3);
00380             q->expn[i] = curexpn;
00381             q->mant[i] = q->mant[0];
00382         }
00383     } else{
00384         n = (n - 3) >> 1;
00385         if (s->buf_end - s->buf < n || 32*3 < n)
00386             return AVERROR(EINVAL);
00387         for (i = 0; i < n; i++){
00388             x = bytestream_get_be16(&s->buf);
00389             q->expn[i] = x >> 11;
00390             q->mant[i] = x & 0x7ff;
00391         }
00392     }
00393     return 0;
00394 }
00395 
00397 static int get_qcd(J2kDecoderContext *s, int n, J2kQuantStyle *q, uint8_t *properties)
00398 {
00399     J2kQuantStyle tmp;
00400     int compno;
00401 
00402     if (get_qcx(s, n, &tmp))
00403         return -1;
00404     for (compno = 0; compno < s->ncomponents; compno++)
00405         if (!(properties[compno] & HAD_QCC))
00406             memcpy(q + compno, &tmp, sizeof(J2kQuantStyle));
00407     return 0;
00408 }
00409 
00411 static int get_qcc(J2kDecoderContext *s, int n, J2kQuantStyle *q, uint8_t *properties)
00412 {
00413     int compno;
00414 
00415     if (s->buf_end - s->buf < 1)
00416         return AVERROR(EINVAL);
00417 
00418     compno = bytestream_get_byte(&s->buf);
00419     properties[compno] |= HAD_QCC;
00420     return get_qcx(s, n-1, q+compno);
00421 }
00422 
00424 static uint8_t get_sot(J2kDecoderContext *s)
00425 {
00426     if (s->buf_end - s->buf < 4)
00427         return AVERROR(EINVAL);
00428 
00429     s->curtileno = bytestream_get_be16(&s->buf); 
00430     if((unsigned)s->curtileno >= s->numXtiles * s->numYtiles){
00431         s->curtileno=0;
00432         return AVERROR(EINVAL);
00433     }
00434 
00435     s->buf += 4; 
00436 
00437     if (!bytestream_get_byte(&s->buf)){ 
00438         J2kTile *tile = s->tile + s->curtileno;
00439 
00440         /* copy defaults */
00441         memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(J2kCodingStyle));
00442         memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(J2kQuantStyle));
00443     }
00444     bytestream_get_byte(&s->buf); 
00445 
00446     return 0;
00447 }
00448 
00449 static int init_tile(J2kDecoderContext *s, int tileno)
00450 {
00451     int compno,
00452         tilex = tileno % s->numXtiles,
00453         tiley = tileno / s->numXtiles;
00454     J2kTile *tile = s->tile + tileno;
00455 
00456     if (!tile->comp)
00457         return AVERROR(ENOMEM);
00458     for (compno = 0; compno < s->ncomponents; compno++){
00459         J2kComponent *comp = tile->comp + compno;
00460         J2kCodingStyle *codsty = tile->codsty + compno;
00461         J2kQuantStyle  *qntsty = tile->qntsty + compno;
00462         int ret; // global bandno
00463 
00464         comp->coord[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
00465         comp->coord[0][1] = FFMIN((tilex+1)*s->tile_width + s->tile_offset_x, s->width);
00466         comp->coord[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
00467         comp->coord[1][1] = FFMIN((tiley+1)*s->tile_height + s->tile_offset_y, s->height);
00468 
00469         if (ret = ff_j2k_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno]))
00470             return ret;
00471     }
00472     return 0;
00473 }
00474 
00476 static int getnpasses(J2kDecoderContext *s)
00477 {
00478     int num;
00479     if (!get_bits(s, 1))
00480         return 1;
00481     if (!get_bits(s, 1))
00482         return 2;
00483     if ((num = get_bits(s, 2)) != 3)
00484         return num < 0 ? num : 3 + num;
00485     if ((num = get_bits(s, 5)) != 31)
00486         return num < 0 ? num : 6 + num;
00487     num = get_bits(s, 7);
00488     return num < 0 ? num : 37 + num;
00489 }
00490 
00491 static int getlblockinc(J2kDecoderContext *s)
00492 {
00493     int res = 0, ret;
00494     while (ret = get_bits(s, 1)){
00495         if (ret < 0)
00496             return ret;
00497         res++;
00498     }
00499     return res;
00500 }
00501 
00502 static int decode_packet(J2kDecoderContext *s, J2kCodingStyle *codsty, J2kResLevel *rlevel, int precno,
00503                          int layno, uint8_t *expn, int numgbits)
00504 {
00505     int bandno, cblkny, cblknx, cblkno, ret;
00506 
00507     if (!(ret = get_bits(s, 1))){
00508         j2k_flush(s);
00509         return 0;
00510     } else if (ret < 0)
00511         return ret;
00512 
00513     for (bandno = 0; bandno < rlevel->nbands; bandno++){
00514         J2kBand *band = rlevel->band + bandno;
00515         J2kPrec *prec = band->prec + precno;
00516         int pos = 0;
00517 
00518         if (band->coord[0][0] == band->coord[0][1]
00519         ||  band->coord[1][0] == band->coord[1][1])
00520             continue;
00521 
00522         for (cblkny = prec->yi0; cblkny < prec->yi1; cblkny++)
00523             for(cblknx = prec->xi0, cblkno = cblkny * band->cblknx + cblknx; cblknx < prec->xi1; cblknx++, cblkno++, pos++){
00524                 J2kCblk *cblk = band->cblk + cblkno;
00525                 int incl, newpasses, llen;
00526 
00527                 if (cblk->npasses)
00528                     incl = get_bits(s, 1);
00529                 else
00530                     incl = tag_tree_decode(s, prec->cblkincl + pos, layno+1) == layno;
00531                 if (!incl)
00532                     continue;
00533                 else if (incl < 0)
00534                     return incl;
00535 
00536                 if (!cblk->npasses)
00537                     cblk->nonzerobits = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + pos, 100);
00538                 if ((newpasses = getnpasses(s)) < 0)
00539                     return newpasses;
00540                 if ((llen = getlblockinc(s)) < 0)
00541                     return llen;
00542                 cblk->lblock += llen;
00543                 if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
00544                     return ret;
00545                 cblk->lengthinc = ret;
00546                 cblk->npasses += newpasses;
00547             }
00548     }
00549     j2k_flush(s);
00550 
00551     if (codsty->csty & J2K_CSTY_EPH) {
00552         if (AV_RB16(s->buf) == J2K_EPH) {
00553             s->buf += 2;
00554         } else {
00555             av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
00556         }
00557     }
00558 
00559     for (bandno = 0; bandno < rlevel->nbands; bandno++){
00560         J2kBand *band = rlevel->band + bandno;
00561         int yi, cblknw = band->prec[precno].xi1 - band->prec[precno].xi0;
00562         for (yi = band->prec[precno].yi0; yi < band->prec[precno].yi1; yi++){
00563             int xi;
00564             for (xi = band->prec[precno].xi0; xi < band->prec[precno].xi1; xi++){
00565                 J2kCblk *cblk = band->cblk + yi * cblknw + xi;
00566                 if (s->buf_end - s->buf < cblk->lengthinc)
00567                     return AVERROR(EINVAL);
00568                 bytestream_get_buffer(&s->buf, cblk->data, cblk->lengthinc);
00569                 cblk->length += cblk->lengthinc;
00570                 cblk->lengthinc = 0;
00571             }
00572         }
00573     }
00574     return 0;
00575 }
00576 
00577 static int decode_packets(J2kDecoderContext *s, J2kTile *tile)
00578 {
00579     int layno, reslevelno, compno, precno, ok_reslevel;
00580     s->bit_index = 8;
00581     for (layno = 0; layno < tile->codsty[0].nlayers; layno++){
00582         ok_reslevel = 1;
00583         for (reslevelno = 0; ok_reslevel; reslevelno++){
00584             ok_reslevel = 0;
00585             for (compno = 0; compno < s->ncomponents; compno++){
00586                 J2kCodingStyle *codsty = tile->codsty + compno;
00587                 J2kQuantStyle  *qntsty = tile->qntsty + compno;
00588                 if (reslevelno < codsty->nreslevels){
00589                     J2kResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
00590                     ok_reslevel = 1;
00591                     for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++){
00592                         if (decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn +
00593                                           (reslevelno ? 3*(reslevelno-1)+1 : 0), qntsty->nguardbits))
00594                             return -1;
00595                     }
00596                 }
00597             }
00598         }
00599     }
00600     return 0;
00601 }
00602 
00603 /* TIER-1 routines */
00604 static void decode_sigpass(J2kT1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol,
00605                            int vert_causal_ctx_csty_symbol)
00606 {
00607     int mask = 3 << (bpno - 1), y0, x, y;
00608 
00609     for (y0 = 0; y0 < height; y0 += 4)
00610         for (x = 0; x < width; x++)
00611             for (y = y0; y < height && y < y0+4; y++){
00612                 if ((t1->flags[y+1][x+1] & J2K_T1_SIG_NB)
00613                 && !(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS))){
00614                     int vert_causal_ctx_csty_loc_symbol = vert_causal_ctx_csty_symbol && (x == 3 && y == 3);
00615                     if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_j2k_getnbctxno(t1->flags[y+1][x+1], bandno,
00616                                       vert_causal_ctx_csty_loc_symbol))){
00617                         int xorbit, ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
00618                         if (bpass_csty_symbol)
00619                              t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
00620                         else
00621                              t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
00622                                                -mask : mask;
00623 
00624                         ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
00625                     }
00626                     t1->flags[y+1][x+1] |= J2K_T1_VIS;
00627                 }
00628             }
00629 }
00630 
00631 static void decode_refpass(J2kT1Context *t1, int width, int height, int bpno)
00632 {
00633     int phalf, nhalf;
00634     int y0, x, y;
00635 
00636     phalf = 1 << (bpno - 1);
00637     nhalf = -phalf;
00638 
00639     for (y0 = 0; y0 < height; y0 += 4)
00640         for (x = 0; x < width; x++)
00641             for (y = y0; y < height && y < y0+4; y++){
00642                 if ((t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)) == J2K_T1_SIG){
00643                     int ctxno = ff_j2k_getrefctxno(t1->flags[y+1][x+1]);
00644                     int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf;
00645                     t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
00646                     t1->flags[y+1][x+1] |= J2K_T1_REF;
00647                 }
00648             }
00649 }
00650 
00651 static void decode_clnpass(J2kDecoderContext *s, J2kT1Context *t1, int width, int height,
00652                            int bpno, int bandno, int seg_symbols)
00653 {
00654     int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
00655 
00656     for (y0 = 0; y0 < height; y0 += 4) {
00657         for (x = 0; x < width; x++){
00658             if (y0 + 3 < height && !(
00659             (t1->flags[y0+1][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
00660             (t1->flags[y0+2][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
00661             (t1->flags[y0+3][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)) ||
00662             (t1->flags[y0+4][x+1] & (J2K_T1_SIG_NB | J2K_T1_VIS | J2K_T1_SIG)))){
00663                 if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
00664                     continue;
00665                 runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
00666                 runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
00667                 dec = 1;
00668             } else{
00669                 runlen = 0;
00670                 dec = 0;
00671             }
00672 
00673             for (y = y0 + runlen; y < y0 + 4 && y < height; y++){
00674                 if (!dec){
00675                     if (!(t1->flags[y+1][x+1] & (J2K_T1_SIG | J2K_T1_VIS)))
00676                         dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_j2k_getnbctxno(t1->flags[y+1][x+1],
00677                                                                                              bandno, 0));
00678                 }
00679                 if (dec){
00680                     int xorbit, ctxno = ff_j2k_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
00681                     t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask;
00682                     ff_j2k_set_significant(t1, x, y, t1->data[y][x] < 0);
00683                 }
00684                 dec = 0;
00685                 t1->flags[y+1][x+1] &= ~J2K_T1_VIS;
00686             }
00687         }
00688     }
00689     if (seg_symbols) {
00690         int val;
00691         val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
00692         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
00693         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
00694         val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
00695         if (val != 0xa) {
00696             av_log(s->avctx, AV_LOG_ERROR,"Segmentation symbol value incorrect\n");
00697         }
00698     }
00699 }
00700 
00701 static int decode_cblk(J2kDecoderContext *s, J2kCodingStyle *codsty, J2kT1Context *t1, J2kCblk *cblk,
00702                        int width, int height, int bandpos)
00703 {
00704     int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y, clnpass_cnt = 0;
00705     int bpass_csty_symbol = J2K_CBLK_BYPASS & codsty->cblk_style;
00706     int vert_causal_ctx_csty_symbol = J2K_CBLK_VSC & codsty->cblk_style;
00707 
00708     for (y = 0; y < height+2; y++)
00709         memset(t1->flags[y], 0, (width+2)*sizeof(int));
00710 
00711     for (y = 0; y < height; y++)
00712         memset(t1->data[y], 0, width*sizeof(int));
00713 
00714     cblk->data[cblk->length] = 0xff;
00715     cblk->data[cblk->length+1] = 0xff;
00716     ff_mqc_initdec(&t1->mqc, cblk->data);
00717 
00718     while(passno--){
00719         switch(pass_t){
00720             case 0: decode_sigpass(t1, width, height, bpno+1, bandpos,
00721                                   bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol);
00722                     break;
00723             case 1: decode_refpass(t1, width, height, bpno+1);
00724                     if (bpass_csty_symbol && clnpass_cnt >= 4)
00725                         ff_mqc_initdec(&t1->mqc, cblk->data);
00726                     break;
00727             case 2: decode_clnpass(s, t1, width, height, bpno+1, bandpos,
00728                                    codsty->cblk_style & J2K_CBLK_SEGSYM);
00729                     clnpass_cnt = clnpass_cnt + 1;
00730                     if (bpass_csty_symbol && clnpass_cnt >= 4)
00731                        ff_mqc_initdec(&t1->mqc, cblk->data);
00732                     break;
00733         }
00734 
00735         pass_t++;
00736         if (pass_t == 3){
00737             bpno--;
00738             pass_t = 0;
00739         }
00740     }
00741     return 0;
00742 }
00743 
00744 static void mct_decode(J2kDecoderContext *s, J2kTile *tile)
00745 {
00746     int i, *src[3], i0, i1, i2, csize = 1;
00747 
00748     for (i = 0; i < 3; i++)
00749         src[i] = tile->comp[i].data;
00750 
00751     for (i = 0; i < 2; i++)
00752         csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
00753 
00754     if (tile->codsty[0].transform == FF_DWT97){
00755         for (i = 0; i < csize; i++){
00756             i0 = *src[0] + (*src[2] * 46802 >> 16);
00757             i1 = *src[0] - (*src[1] * 22553 + *src[2] * 46802 >> 16);
00758             i2 = *src[0] + (116130 * *src[1] >> 16);
00759             *src[0]++ = i0;
00760             *src[1]++ = i1;
00761             *src[2]++ = i2;
00762         }
00763     } else{
00764         for (i = 0; i < csize; i++){
00765             i1 = *src[0] - (*src[2] + *src[1] >> 2);
00766             i0 = i1 + *src[2];
00767             i2 = i1 + *src[1];
00768             *src[0]++ = i0;
00769             *src[1]++ = i1;
00770             *src[2]++ = i2;
00771         }
00772     }
00773 }
00774 
00775 static int decode_tile(J2kDecoderContext *s, J2kTile *tile)
00776 {
00777     int compno, reslevelno, bandno;
00778     int x, y, *src[4];
00779     uint8_t *line;
00780     J2kT1Context t1;
00781 
00782     for (compno = 0; compno < s->ncomponents; compno++){
00783         J2kComponent *comp = tile->comp + compno;
00784         J2kCodingStyle *codsty = tile->codsty + compno;
00785 
00786         for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
00787             J2kResLevel *rlevel = comp->reslevel + reslevelno;
00788             for (bandno = 0; bandno < rlevel->nbands; bandno++){
00789                 J2kBand *band = rlevel->band + bandno;
00790                 int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
00791 
00792                 bandpos = bandno + (reslevelno > 0);
00793 
00794                 yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
00795                 y0 = yy0;
00796                 yy1 = FFMIN(ff_j2k_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,
00797                             band->coord[1][1]) - band->coord[1][0] + yy0;
00798 
00799                 if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
00800                     continue;
00801 
00802                 for (cblky = 0; cblky < band->cblkny; cblky++){
00803                     if (reslevelno == 0 || bandno == 1)
00804                         xx0 = 0;
00805                     else
00806                         xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
00807                     x0 = xx0;
00808                     xx1 = FFMIN(ff_j2k_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,
00809                                 band->coord[0][1]) - band->coord[0][0] + xx0;
00810 
00811                     for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++){
00812                         int y, x;
00813                         decode_cblk(s, codsty, &t1, band->cblk + cblkno, xx1 - xx0, yy1 - yy0, bandpos);
00814                         if (codsty->transform == FF_DWT53){
00815                             for (y = yy0; y < yy1; y+=s->cdy[compno]){
00816                                 int *ptr = t1.data[y-yy0];
00817                                 for (x = xx0; x < xx1; x+=s->cdx[compno]){
00818                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = *ptr++ >> 1;
00819                                 }
00820                             }
00821                         } else{
00822                             for (y = yy0; y < yy1; y+=s->cdy[compno]){
00823                                 int *ptr = t1.data[y-yy0];
00824                                 for (x = xx0; x < xx1; x+=s->cdx[compno]){
00825                                     int tmp = ((int64_t)*ptr++) * ((int64_t)band->stepsize) >> 13, tmp2;
00826                                     tmp2 = FFABS(tmp>>1) + FFABS(tmp&1);
00827                                     comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = tmp < 0 ? -tmp2 : tmp2;
00828                                 }
00829                             }
00830                         }
00831                         xx0 = xx1;
00832                         xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);
00833                     }
00834                     yy0 = yy1;
00835                     yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);
00836                 }
00837             }
00838         }
00839         ff_j2k_dwt_decode(&comp->dwt, comp->data);
00840         src[compno] = comp->data;
00841     }
00842     if (tile->codsty[0].mct)
00843         mct_decode(s, tile);
00844 
00845     if (s->avctx->pix_fmt == PIX_FMT_BGRA) // RGBA -> BGRA
00846         FFSWAP(int *, src[0], src[2]);
00847 
00848     if (s->precision <= 8) {
00849         for (compno = 0; compno < s->ncomponents; compno++){
00850             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
00851             line = s->picture.data[0] + y * s->picture.linesize[0];
00852             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]){
00853                 uint8_t *dst;
00854 
00855                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
00856                 dst = line + x * s->ncomponents + compno;
00857 
00858                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {
00859                     *src[compno] += 1 << (s->cbps[compno]-1);
00860                     if (*src[compno] < 0)
00861                         *src[compno] = 0;
00862                     else if (*src[compno] >= (1 << s->cbps[compno]))
00863                         *src[compno] = (1 << s->cbps[compno]) - 1;
00864                     *dst = *src[compno]++;
00865                     dst += s->ncomponents;
00866                 }
00867                 line += s->picture.linesize[0];
00868             }
00869         }
00870     } else {
00871         for (compno = 0; compno < s->ncomponents; compno++) {
00872             y = tile->comp[compno].coord[1][0] - s->image_offset_y;
00873             line = s->picture.data[0] + y * s->picture.linesize[0];
00874             for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
00875                 uint16_t *dst;
00876                 x = tile->comp[compno].coord[0][0] - s->image_offset_x;
00877                 dst = line + (x * s->ncomponents + compno) * 2;
00878                 for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {
00879                     int32_t val;
00880                     val = *src[compno]++ << (16 - s->cbps[compno]);
00881                     val += 1 << 15;
00882                     val = av_clip(val, 0, (1 << 16) - 1);
00883                     *dst = val;
00884                     dst += s->ncomponents;
00885                 }
00886                 line += s->picture.linesize[0];
00887             }
00888         }
00889     }
00890     return 0;
00891 }
00892 
00893 static void cleanup(J2kDecoderContext *s)
00894 {
00895     int tileno, compno;
00896     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
00897         for (compno = 0; compno < s->ncomponents; compno++){
00898             J2kComponent *comp = s->tile[tileno].comp + compno;
00899             J2kCodingStyle *codsty = s->tile[tileno].codsty + compno;
00900 
00901             ff_j2k_cleanup(comp, codsty);
00902         }
00903         av_freep(&s->tile[tileno].comp);
00904     }
00905     av_freep(&s->tile);
00906 }
00907 
00908 static int decode_codestream(J2kDecoderContext *s)
00909 {
00910     J2kCodingStyle *codsty = s->codsty;
00911     J2kQuantStyle  *qntsty = s->qntsty;
00912     uint8_t *properties = s->properties;
00913 
00914     for (;;){
00915         int marker, len, ret = 0;
00916         const uint8_t *oldbuf;
00917         if (s->buf_end - s->buf < 2){
00918             av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
00919             break;
00920         }
00921 
00922         marker = bytestream_get_be16(&s->buf);
00923         if(s->avctx->debug & FF_DEBUG_STARTCODE)
00924             av_log(s->avctx, AV_LOG_DEBUG, "marker 0x%.4X at pos 0x%tx\n", marker, s->buf - s->buf_start - 4);
00925         oldbuf = s->buf;
00926 
00927         if (marker == J2K_SOD){
00928             J2kTile *tile = s->tile + s->curtileno;
00929             if (ret = init_tile(s, s->curtileno))
00930                 return ret;
00931             if (ret = decode_packets(s, tile))
00932                 return ret;
00933             continue;
00934         }
00935         if (marker == J2K_EOC)
00936             break;
00937 
00938         if (s->buf_end - s->buf < 2)
00939             return AVERROR(EINVAL);
00940         len = bytestream_get_be16(&s->buf);
00941         switch(marker){
00942             case J2K_SIZ:
00943                 ret = get_siz(s); break;
00944             case J2K_COC:
00945                 ret = get_coc(s, codsty, properties); break;
00946             case J2K_COD:
00947                 ret = get_cod(s, codsty, properties); break;
00948             case J2K_QCC:
00949                 ret = get_qcc(s, len, qntsty, properties); break;
00950             case J2K_QCD:
00951                 ret = get_qcd(s, len, qntsty, properties); break;
00952             case J2K_SOT:
00953                 if (!(ret = get_sot(s))){
00954                     codsty = s->tile[s->curtileno].codsty;
00955                     qntsty = s->tile[s->curtileno].qntsty;
00956                     properties = s->tile[s->curtileno].properties;
00957                 }
00958                 break;
00959             case J2K_COM:
00960                 // the comment is ignored
00961                 s->buf += len - 2; break;
00962             default:
00963                 av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%tx\n", marker, s->buf - s->buf_start - 4);
00964                 s->buf += len - 2; break;
00965         }
00966         if (s->buf - oldbuf != len || ret){
00967             av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker);
00968             return ret ? ret : -1;
00969         }
00970     }
00971     return 0;
00972 }
00973 
00974 static int jp2_find_codestream(J2kDecoderContext *s)
00975 {
00976     uint32_t atom_size;
00977     int found_codestream = 0, search_range = 10;
00978 
00979     // skip jpeg2k signature atom
00980     s->buf += 12;
00981 
00982     while(!found_codestream && search_range && s->buf_end - s->buf >= 8) {
00983         atom_size = AV_RB32(s->buf);
00984         if(AV_RB32(s->buf + 4) == JP2_CODESTREAM) {
00985             found_codestream = 1;
00986             s->buf += 8;
00987         } else {
00988             if (s->buf_end - s->buf < atom_size)
00989                 return 0;
00990             s->buf += atom_size;
00991             search_range--;
00992         }
00993     }
00994 
00995     if(found_codestream)
00996         return 1;
00997     return 0;
00998 }
00999 
01000 static int decode_frame(AVCodecContext *avctx,
01001                         void *data, int *data_size,
01002                         AVPacket *avpkt)
01003 {
01004     J2kDecoderContext *s = avctx->priv_data;
01005     AVFrame *picture = data;
01006     int tileno, ret;
01007 
01008     s->avctx = avctx;
01009     av_log(s->avctx, AV_LOG_DEBUG, "start\n");
01010 
01011     // init
01012     s->buf = s->buf_start = avpkt->data;
01013     s->buf_end = s->buf_start + avpkt->size;
01014     s->curtileno = -1;
01015 
01016     ff_j2k_init_tier1_luts();
01017 
01018     if (s->buf_end - s->buf < 2) {
01019         ret = AVERROR(EINVAL);
01020         goto err_out;
01021     }
01022 
01023     // check if the image is in jp2 format
01024     if(s->buf_end - s->buf >= 12 &&
01025        (AV_RB32(s->buf) == 12) && (AV_RB32(s->buf + 4) == JP2_SIG_TYPE) &&
01026        (AV_RB32(s->buf + 8) == JP2_SIG_VALUE)) {
01027         if(!jp2_find_codestream(s)) {
01028             av_log(avctx, AV_LOG_ERROR, "couldn't find jpeg2k codestream atom\n");
01029             ret = -1;
01030             goto err_out;
01031         }
01032     }
01033 
01034     if (bytestream_get_be16(&s->buf) != J2K_SOC){
01035         av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
01036         ret = -1;
01037         goto err_out;
01038     }
01039     if (ret = decode_codestream(s))
01040         goto err_out;
01041 
01042     for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
01043         if (ret = decode_tile(s, s->tile + tileno))
01044             goto err_out;
01045 
01046     cleanup(s);
01047     av_log(s->avctx, AV_LOG_DEBUG, "end\n");
01048 
01049     *data_size = sizeof(AVPicture);
01050     *picture = s->picture;
01051 
01052     return s->buf - s->buf_start;
01053 
01054 err_out:
01055     cleanup(s);
01056     return ret;
01057 }
01058 
01059 static av_cold int j2kdec_init(AVCodecContext *avctx)
01060 {
01061     J2kDecoderContext *s = avctx->priv_data;
01062 
01063     avcodec_get_frame_defaults((AVFrame*)&s->picture);
01064     avctx->coded_frame = (AVFrame*)&s->picture;
01065     return 0;
01066 }
01067 
01068 static av_cold int decode_end(AVCodecContext *avctx)
01069 {
01070     J2kDecoderContext *s = avctx->priv_data;
01071 
01072     if (s->picture.data[0])
01073         avctx->release_buffer(avctx, &s->picture);
01074 
01075     return 0;
01076 }
01077 
01078 AVCodec ff_jpeg2000_decoder = {
01079     .name           = "j2k",
01080     .type           = AVMEDIA_TYPE_VIDEO,
01081     .id             = CODEC_ID_JPEG2000,
01082     .priv_data_size = sizeof(J2kDecoderContext),
01083     .init           = j2kdec_init,
01084     .close          = decode_end,
01085     .decode         = decode_frame,
01086     .capabilities = CODEC_CAP_EXPERIMENTAL,
01087     .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
01088     .pix_fmts =
01089         (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_RGB24, PIX_FMT_NONE}
01090 };