libavcodec/lagarith.c
Go to the documentation of this file.
00001 /*
00002  * Lagarith lossless decoder
00003  * Copyright (c) 2009 Nathan Caldwell <saintdev (at) gmail.com>
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav 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  * Libav 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 Libav; 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 "get_bits.h"
00030 #include "mathops.h"
00031 #include "dsputil.h"
00032 #include "lagarithrac.h"
00033 
00034 enum LagarithFrameType {
00035     FRAME_RAW           = 1,    
00036     FRAME_U_RGB24       = 2,    
00037     FRAME_ARITH_YUY2    = 3,    
00038     FRAME_ARITH_RGB24   = 4,    
00039     FRAME_SOLID_GRAY    = 5,    
00040     FRAME_SOLID_COLOR   = 6,    
00041     FRAME_OLD_ARITH_RGB = 7,    
00042     FRAME_ARITH_RGBA    = 8,    
00043     FRAME_SOLID_RGBA    = 9,    
00044     FRAME_ARITH_YV12    = 10,   
00045     FRAME_REDUCED_RES   = 11,   
00046 };
00047 
00048 typedef struct LagarithContext {
00049     AVCodecContext *avctx;
00050     AVFrame picture;
00051     DSPContext dsp;
00052     int zeros;                  
00053     int zeros_rem;              
00054     uint8_t *rgb_planes;
00055     int rgb_stride;
00056 } LagarithContext;
00057 
00066 static uint64_t softfloat_reciprocal(uint32_t denom)
00067 {
00068     int shift = av_log2(denom - 1) + 1;
00069     uint64_t ret = (1ULL << 52) / denom;
00070     uint64_t err = (1ULL << 52) - ret * denom;
00071     ret <<= shift;
00072     err <<= shift;
00073     err +=  denom / 2;
00074     return ret + err / denom;
00075 }
00076 
00085 static uint32_t softfloat_mul(uint32_t x, uint64_t mantissa)
00086 {
00087     uint64_t l = x * (mantissa & 0xffffffff);
00088     uint64_t h = x * (mantissa >> 32);
00089     h += l >> 32;
00090     l &= 0xffffffff;
00091     l += 1 << av_log2(h >> 21);
00092     h += l >> 32;
00093     return h >> 20;
00094 }
00095 
00096 static uint8_t lag_calc_zero_run(int8_t x)
00097 {
00098     return (x << 1) ^ (x >> 7);
00099 }
00100 
00101 static int lag_decode_prob(GetBitContext *gb, uint32_t *value)
00102 {
00103     static const uint8_t series[] = { 1, 2, 3, 5, 8, 13, 21 };
00104     int i;
00105     int bit     = 0;
00106     int bits    = 0;
00107     int prevbit = 0;
00108     unsigned val;
00109 
00110     for (i = 0; i < 7; i++) {
00111         if (prevbit && bit)
00112             break;
00113         prevbit = bit;
00114         bit = get_bits1(gb);
00115         if (bit && !prevbit)
00116             bits += series[i];
00117     }
00118     bits--;
00119     if (bits < 0 || bits > 31) {
00120         *value = 0;
00121         return -1;
00122     } else if (bits == 0) {
00123         *value = 0;
00124         return 0;
00125     }
00126 
00127     val  = get_bits_long(gb, bits);
00128     val |= 1 << bits;
00129 
00130     *value = val - 1;
00131 
00132     return 0;
00133 }
00134 
00135 static int lag_read_prob_header(lag_rac *rac, GetBitContext *gb)
00136 {
00137     int i, j, scale_factor;
00138     unsigned prob, cumulative_target;
00139     unsigned cumul_prob = 0;
00140     unsigned scaled_cumul_prob = 0;
00141 
00142     rac->prob[0] = 0;
00143     rac->prob[257] = UINT_MAX;
00144     /* Read probabilities from bitstream */
00145     for (i = 1; i < 257; i++) {
00146         if (lag_decode_prob(gb, &rac->prob[i]) < 0) {
00147             av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability encountered.\n");
00148             return -1;
00149         }
00150         if ((uint64_t)cumul_prob + rac->prob[i] > UINT_MAX) {
00151             av_log(rac->avctx, AV_LOG_ERROR, "Integer overflow encountered in cumulative probability calculation.\n");
00152             return -1;
00153         }
00154         cumul_prob += rac->prob[i];
00155         if (!rac->prob[i]) {
00156             if (lag_decode_prob(gb, &prob)) {
00157                 av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability run encountered.\n");
00158                 return -1;
00159             }
00160             if (prob > 257 - i)
00161                 prob = 257 - i;
00162             for (j = 0; j < prob; j++)
00163                 rac->prob[++i] = 0;
00164         }
00165     }
00166 
00167     if (!cumul_prob) {
00168         av_log(rac->avctx, AV_LOG_ERROR, "All probabilities are 0!\n");
00169         return -1;
00170     }
00171 
00172     /* Scale probabilities so cumulative probability is an even power of 2. */
00173     scale_factor = av_log2(cumul_prob);
00174 
00175     if (cumul_prob & (cumul_prob - 1)) {
00176         uint64_t mul = softfloat_reciprocal(cumul_prob);
00177         for (i = 1; i < 257; i++) {
00178             rac->prob[i] = softfloat_mul(rac->prob[i], mul);
00179             scaled_cumul_prob += rac->prob[i];
00180         }
00181 
00182         scale_factor++;
00183         cumulative_target = 1 << scale_factor;
00184 
00185         if (scaled_cumul_prob > cumulative_target) {
00186             av_log(rac->avctx, AV_LOG_ERROR,
00187                    "Scaled probabilities are larger than target!\n");
00188             return -1;
00189         }
00190 
00191         scaled_cumul_prob = cumulative_target - scaled_cumul_prob;
00192 
00193         for (i = 1; scaled_cumul_prob; i = (i & 0x7f) + 1) {
00194             if (rac->prob[i]) {
00195                 rac->prob[i]++;
00196                 scaled_cumul_prob--;
00197             }
00198             /* Comment from reference source:
00199              * if (b & 0x80 == 0) {     // order of operations is 'wrong'; it has been left this way
00200              *                          // since the compression change is negligable and fixing it
00201              *                          // breaks backwards compatibilty
00202              *      b =- (signed int)b;
00203              *      b &= 0xFF;
00204              * } else {
00205              *      b++;
00206              *      b &= 0x7f;
00207              * }
00208              */
00209         }
00210     }
00211 
00212     rac->scale = scale_factor;
00213 
00214     /* Fill probability array with cumulative probability for each symbol. */
00215     for (i = 1; i < 257; i++)
00216         rac->prob[i] += rac->prob[i - 1];
00217 
00218     return 0;
00219 }
00220 
00221 static void add_lag_median_prediction(uint8_t *dst, uint8_t *src1,
00222                                       uint8_t *diff, int w, int *left,
00223                                       int *left_top)
00224 {
00225     /* This is almost identical to add_hfyu_median_prediction in dsputil.h.
00226      * However the &0xFF on the gradient predictor yealds incorrect output
00227      * for lagarith.
00228      */
00229     int i;
00230     uint8_t l, lt;
00231 
00232     l  = *left;
00233     lt = *left_top;
00234 
00235     for (i = 0; i < w; i++) {
00236         l = mid_pred(l, src1[i], l + src1[i] - lt) + diff[i];
00237         lt = src1[i];
00238         dst[i] = l;
00239     }
00240 
00241     *left     = l;
00242     *left_top = lt;
00243 }
00244 
00245 static void lag_pred_line(LagarithContext *l, uint8_t *buf,
00246                           int width, int stride, int line)
00247 {
00248     int L, TL;
00249 
00250     if (!line) {
00251         /* Left prediction only for first line */
00252         L = l->dsp.add_hfyu_left_prediction(buf + 1, buf + 1,
00253                                             width - 1, buf[0]);
00254     } else {
00255         /* Left pixel is actually prev_row[width] */
00256         L = buf[width - stride - 1];
00257 
00258         if (line == 1) {
00259             /* Second line, left predict first pixel, the rest of the line is median predicted
00260              * NOTE: In the case of RGB this pixel is top predicted */
00261             TL = l->avctx->pix_fmt == PIX_FMT_YUV420P ? buf[-stride] : L;
00262         } else {
00263             /* Top left is 2 rows back, last pixel */
00264             TL = buf[width - (2 * stride) - 1];
00265         }
00266 
00267         add_lag_median_prediction(buf, buf - stride, buf,
00268                                   width, &L, &TL);
00269     }
00270 }
00271 
00272 static int lag_decode_line(LagarithContext *l, lag_rac *rac,
00273                            uint8_t *dst, int width, int stride,
00274                            int esc_count)
00275 {
00276     int i = 0;
00277     int ret = 0;
00278 
00279     if (!esc_count)
00280         esc_count = -1;
00281 
00282     /* Output any zeros remaining from the previous run */
00283 handle_zeros:
00284     if (l->zeros_rem) {
00285         int count = FFMIN(l->zeros_rem, width - i);
00286         memset(dst + i, 0, count);
00287         i += count;
00288         l->zeros_rem -= count;
00289     }
00290 
00291     while (i < width) {
00292         dst[i] = lag_get_rac(rac);
00293         ret++;
00294 
00295         if (dst[i])
00296             l->zeros = 0;
00297         else
00298             l->zeros++;
00299 
00300         i++;
00301         if (l->zeros == esc_count) {
00302             int index = lag_get_rac(rac);
00303             ret++;
00304 
00305             l->zeros = 0;
00306 
00307             l->zeros_rem = lag_calc_zero_run(index);
00308             goto handle_zeros;
00309         }
00310     }
00311     return ret;
00312 }
00313 
00314 static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst,
00315                                     const uint8_t *src, const uint8_t *src_end,
00316                                     int width, int esc_count)
00317 {
00318     int i = 0;
00319     int count;
00320     uint8_t zero_run = 0;
00321     const uint8_t *src_start = src;
00322     uint8_t mask1 = -(esc_count < 2);
00323     uint8_t mask2 = -(esc_count < 3);
00324     uint8_t *end = dst + (width - 2);
00325 
00326 output_zeros:
00327     if (l->zeros_rem) {
00328         count = FFMIN(l->zeros_rem, width - i);
00329         memset(dst, 0, count);
00330         l->zeros_rem -= count;
00331         dst += count;
00332     }
00333 
00334     while (dst < end) {
00335         i = 0;
00336         while (!zero_run && dst + i < end) {
00337             i++;
00338             if (src + i >= src_end)
00339                 return AVERROR_INVALIDDATA;
00340             zero_run =
00341                 !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2));
00342         }
00343         if (zero_run) {
00344             zero_run = 0;
00345             i += esc_count;
00346             memcpy(dst, src, i);
00347             dst += i;
00348             l->zeros_rem = lag_calc_zero_run(src[i]);
00349 
00350             src += i + 1;
00351             goto output_zeros;
00352         } else {
00353             memcpy(dst, src, i);
00354             src += i;
00355             dst += i;
00356         }
00357     }
00358     return src_start - src;
00359 }
00360 
00361 
00362 
00363 static int lag_decode_arith_plane(LagarithContext *l, uint8_t *dst,
00364                                   int width, int height, int stride,
00365                                   const uint8_t *src, int src_size)
00366 {
00367     int i = 0;
00368     int read = 0;
00369     uint32_t length;
00370     uint32_t offset = 1;
00371     int esc_count = src[0];
00372     GetBitContext gb;
00373     lag_rac rac;
00374     const uint8_t *src_end = src + src_size;
00375 
00376     rac.avctx = l->avctx;
00377     l->zeros = 0;
00378 
00379     if (esc_count < 4) {
00380         length = width * height;
00381         if (esc_count && AV_RL32(src + 1) < length) {
00382             length = AV_RL32(src + 1);
00383             offset += 4;
00384         }
00385 
00386         init_get_bits(&gb, src + offset, src_size * 8);
00387 
00388         if (lag_read_prob_header(&rac, &gb) < 0)
00389             return -1;
00390 
00391         lag_rac_init(&rac, &gb, length - stride);
00392 
00393         for (i = 0; i < height; i++)
00394             read += lag_decode_line(l, &rac, dst + (i * stride), width,
00395                                     stride, esc_count);
00396 
00397         if (read > length)
00398             av_log(l->avctx, AV_LOG_WARNING,
00399                    "Output more bytes than length (%d of %d)\n", read,
00400                    length);
00401     } else if (esc_count < 8) {
00402         esc_count -= 4;
00403         if (esc_count > 0) {
00404             /* Zero run coding only, no range coding. */
00405             for (i = 0; i < height; i++) {
00406                 int res = lag_decode_zero_run_line(l, dst + (i * stride), src,
00407                                                    src_end, width, esc_count);
00408                 if (res < 0)
00409                     return res;
00410                 src += res;
00411             }
00412         } else {
00413             if (src_size < width * height)
00414                 return AVERROR_INVALIDDATA; // buffer not big enough
00415             /* Plane is stored uncompressed */
00416             for (i = 0; i < height; i++) {
00417                 memcpy(dst + (i * stride), src, width);
00418                 src += width;
00419             }
00420         }
00421     } else if (esc_count == 0xff) {
00422         /* Plane is a solid run of given value */
00423         for (i = 0; i < height; i++)
00424             memset(dst + i * stride, src[1], width);
00425         /* Do not apply prediction.
00426            Note: memset to 0 above, setting first value to src[1]
00427            and applying prediction gives the same result. */
00428         return 0;
00429     } else {
00430         av_log(l->avctx, AV_LOG_ERROR,
00431                "Invalid zero run escape code! (%#x)\n", esc_count);
00432         return -1;
00433     }
00434 
00435     for (i = 0; i < height; i++) {
00436         lag_pred_line(l, dst, width, stride, i);
00437         dst += stride;
00438     }
00439 
00440     return 0;
00441 }
00442 
00451 static int lag_decode_frame(AVCodecContext *avctx,
00452                             void *data, int *data_size, AVPacket *avpkt)
00453 {
00454     const uint8_t *buf = avpkt->data;
00455     int buf_size = avpkt->size;
00456     LagarithContext *l = avctx->priv_data;
00457     AVFrame *const p = &l->picture;
00458     uint8_t frametype = 0;
00459     uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9;
00460     int offs[4];
00461     uint8_t *srcs[4], *dst;
00462     int i, j, planes = 3;
00463 
00464     AVFrame *picture = data;
00465 
00466     if (p->data[0])
00467         avctx->release_buffer(avctx, p);
00468 
00469     p->reference = 0;
00470     p->key_frame = 1;
00471 
00472     frametype = buf[0];
00473 
00474     offset_gu = AV_RL32(buf + 1);
00475     offset_bv = AV_RL32(buf + 5);
00476 
00477     switch (frametype) {
00478     case FRAME_SOLID_RGBA:
00479         avctx->pix_fmt = PIX_FMT_RGB32;
00480 
00481         if (avctx->get_buffer(avctx, p) < 0) {
00482             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00483             return -1;
00484         }
00485 
00486         dst = p->data[0];
00487         for (j = 0; j < avctx->height; j++) {
00488             for (i = 0; i < avctx->width; i++)
00489                 AV_WN32(dst + i * 4, offset_gu);
00490             dst += p->linesize[0];
00491         }
00492         break;
00493     case FRAME_ARITH_RGBA:
00494         avctx->pix_fmt = PIX_FMT_RGB32;
00495         planes = 4;
00496         offset_ry += 4;
00497         offs[3] = AV_RL32(buf + 9);
00498     case FRAME_ARITH_RGB24:
00499         if (frametype == FRAME_ARITH_RGB24)
00500             avctx->pix_fmt = PIX_FMT_RGB24;
00501 
00502         if (avctx->get_buffer(avctx, p) < 0) {
00503             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00504             return -1;
00505         }
00506 
00507         offs[0] = offset_bv;
00508         offs[1] = offset_gu;
00509         offs[2] = offset_ry;
00510 
00511         if (!l->rgb_planes) {
00512             l->rgb_stride = FFALIGN(avctx->width, 16);
00513             l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * planes);
00514             if (!l->rgb_planes) {
00515                 av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n");
00516                 return AVERROR(ENOMEM);
00517             }
00518         }
00519         for (i = 0; i < planes; i++)
00520             srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride;
00521         if (offset_ry >= buf_size ||
00522             offset_gu >= buf_size ||
00523             offset_bv >= buf_size ||
00524             (planes == 4 && offs[3] >= buf_size)) {
00525             av_log(avctx, AV_LOG_ERROR,
00526                     "Invalid frame offsets\n");
00527             return AVERROR_INVALIDDATA;
00528         }
00529         for (i = 0; i < planes; i++)
00530             lag_decode_arith_plane(l, srcs[i],
00531                                    avctx->width, avctx->height,
00532                                    -l->rgb_stride, buf + offs[i],
00533                                    buf_size - offs[i]);
00534         dst = p->data[0];
00535         for (i = 0; i < planes; i++)
00536             srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height;
00537         for (j = 0; j < avctx->height; j++) {
00538             for (i = 0; i < avctx->width; i++) {
00539                 uint8_t r, g, b, a;
00540                 r = srcs[0][i];
00541                 g = srcs[1][i];
00542                 b = srcs[2][i];
00543                 r += g;
00544                 b += g;
00545                 if (frametype == FRAME_ARITH_RGBA) {
00546                     a = srcs[3][i];
00547                     AV_WN32(dst + i * 4, MKBETAG(a, r, g, b));
00548                 } else {
00549                     dst[i * 3 + 0] = r;
00550                     dst[i * 3 + 1] = g;
00551                     dst[i * 3 + 2] = b;
00552                 }
00553             }
00554             dst += p->linesize[0];
00555             for (i = 0; i < planes; i++)
00556                 srcs[i] += l->rgb_stride;
00557         }
00558         break;
00559     case FRAME_ARITH_YV12:
00560         avctx->pix_fmt = PIX_FMT_YUV420P;
00561 
00562         if (avctx->get_buffer(avctx, p) < 0) {
00563             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00564             return -1;
00565         }
00566 
00567         if (offset_ry >= buf_size ||
00568             offset_gu >= buf_size ||
00569             offset_bv >= buf_size) {
00570             av_log(avctx, AV_LOG_ERROR,
00571                    "Invalid frame offsets\n");
00572             return AVERROR_INVALIDDATA;
00573         }
00574 
00575         lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,
00576                                p->linesize[0], buf + offset_ry,
00577                                buf_size - offset_ry);
00578         lag_decode_arith_plane(l, p->data[2], avctx->width / 2,
00579                                avctx->height / 2, p->linesize[2],
00580                                buf + offset_gu, buf_size - offset_gu);
00581         lag_decode_arith_plane(l, p->data[1], avctx->width / 2,
00582                                avctx->height / 2, p->linesize[1],
00583                                buf + offset_bv, buf_size - offset_bv);
00584         break;
00585     default:
00586         av_log(avctx, AV_LOG_ERROR,
00587                "Unsupported Lagarith frame type: %#x\n", frametype);
00588         return -1;
00589     }
00590 
00591     *picture = *p;
00592     *data_size = sizeof(AVFrame);
00593 
00594     return buf_size;
00595 }
00596 
00597 static av_cold int lag_decode_init(AVCodecContext *avctx)
00598 {
00599     LagarithContext *l = avctx->priv_data;
00600     l->avctx = avctx;
00601 
00602     dsputil_init(&l->dsp, avctx);
00603 
00604     return 0;
00605 }
00606 
00607 static av_cold int lag_decode_end(AVCodecContext *avctx)
00608 {
00609     LagarithContext *l = avctx->priv_data;
00610 
00611     if (l->picture.data[0])
00612         avctx->release_buffer(avctx, &l->picture);
00613     av_freep(&l->rgb_planes);
00614 
00615     return 0;
00616 }
00617 
00618 AVCodec ff_lagarith_decoder = {
00619     .name           = "lagarith",
00620     .type           = AVMEDIA_TYPE_VIDEO,
00621     .id             = CODEC_ID_LAGARITH,
00622     .priv_data_size = sizeof(LagarithContext),
00623     .init           = lag_decode_init,
00624     .close          = lag_decode_end,
00625     .decode         = lag_decode_frame,
00626     .capabilities   = CODEC_CAP_DR1,
00627     .long_name = NULL_IF_CONFIG_SMALL("Lagarith lossless"),
00628 };