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