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 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 "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     /* Left pixel is actually prev_row[width] */
00251     L = buf[width - stride - 1];
00252     if (!line) {
00253         /* Left prediction only for first line */
00254         L = l->dsp.add_hfyu_left_prediction(buf + 1, buf + 1,
00255                                             width - 1, buf[0]);
00256         return;
00257     } else if (line == 1) {
00258         /* Second line, left predict first pixel, the rest of the line is median predicted
00259          * NOTE: In the case of RGB this pixel is top predicted */
00260         TL = l->avctx->pix_fmt == PIX_FMT_YUV420P ? buf[-stride] : L;
00261     } else {
00262         /* Top left is 2 rows back, last pixel */
00263         TL = buf[width - (2 * stride) - 1];
00264     }
00265 
00266     add_lag_median_prediction(buf, buf - stride, buf,
00267                               width, &L, &TL);
00268 }
00269 
00270 static int lag_decode_line(LagarithContext *l, lag_rac *rac,
00271                            uint8_t *dst, int width, int stride,
00272                            int esc_count)
00273 {
00274     int i = 0;
00275     int ret = 0;
00276 
00277     if (!esc_count)
00278         esc_count = -1;
00279 
00280     /* Output any zeros remaining from the previous run */
00281 handle_zeros:
00282     if (l->zeros_rem) {
00283         int count = FFMIN(l->zeros_rem, width - i);
00284         memset(dst + i, 0, count);
00285         i += count;
00286         l->zeros_rem -= count;
00287     }
00288 
00289     while (i < width) {
00290         dst[i] = lag_get_rac(rac);
00291         ret++;
00292 
00293         if (dst[i])
00294             l->zeros = 0;
00295         else
00296             l->zeros++;
00297 
00298         i++;
00299         if (l->zeros == esc_count) {
00300             int index = lag_get_rac(rac);
00301             ret++;
00302 
00303             l->zeros = 0;
00304 
00305             l->zeros_rem = lag_calc_zero_run(index);
00306             goto handle_zeros;
00307         }
00308     }
00309     return ret;
00310 }
00311 
00312 static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst,
00313                                     const uint8_t *src, int width,
00314                                     int esc_count)
00315 {
00316     int i = 0;
00317     int count;
00318     uint8_t zero_run = 0;
00319     const uint8_t *start = src;
00320     uint8_t mask1 = -(esc_count < 2);
00321     uint8_t mask2 = -(esc_count < 3);
00322     uint8_t *end = dst + (width - 2);
00323 
00324 output_zeros:
00325     if (l->zeros_rem) {
00326         count = FFMIN(l->zeros_rem, width - i);
00327         memset(dst, 0, count);
00328         l->zeros_rem -= count;
00329         dst += count;
00330     }
00331 
00332     while (dst < end) {
00333         i = 0;
00334         while (!zero_run && dst + i < end) {
00335             i++;
00336             zero_run =
00337                 !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2));
00338         }
00339         if (zero_run) {
00340             zero_run = 0;
00341             i += esc_count;
00342             memcpy(dst, src, i);
00343             dst += i;
00344             l->zeros_rem = lag_calc_zero_run(src[i]);
00345 
00346             src += i + 1;
00347             goto output_zeros;
00348         } else {
00349             memcpy(dst, src, i);
00350             src += i;
00351         }
00352     }
00353     return start - src;
00354 }
00355 
00356 
00357 
00358 static int lag_decode_arith_plane(LagarithContext *l, uint8_t *dst,
00359                                   int width, int height, int stride,
00360                                   const uint8_t *src, int src_size)
00361 {
00362     int i = 0;
00363     int read = 0;
00364     uint32_t length;
00365     uint32_t offset = 1;
00366     int esc_count = src[0];
00367     GetBitContext gb;
00368     lag_rac rac;
00369 
00370     rac.avctx = l->avctx;
00371     l->zeros = 0;
00372 
00373     if (esc_count < 4) {
00374         length = width * height;
00375         if (esc_count && AV_RL32(src + 1) < length) {
00376             length = AV_RL32(src + 1);
00377             offset += 4;
00378         }
00379 
00380         init_get_bits(&gb, src + offset, src_size * 8);
00381 
00382         if (lag_read_prob_header(&rac, &gb) < 0)
00383             return -1;
00384 
00385         lag_rac_init(&rac, &gb, length - stride);
00386 
00387         for (i = 0; i < height; i++)
00388             read += lag_decode_line(l, &rac, dst + (i * stride), width,
00389                                     stride, esc_count);
00390 
00391         if (read > length)
00392             av_log(l->avctx, AV_LOG_WARNING,
00393                    "Output more bytes than length (%d of %d)\n", read,
00394                    length);
00395     } else if (esc_count < 8) {
00396         esc_count -= 4;
00397         if (esc_count > 0) {
00398             /* Zero run coding only, no range coding. */
00399             for (i = 0; i < height; i++)
00400                 src += lag_decode_zero_run_line(l, dst + (i * stride), src,
00401                                                 width, esc_count);
00402         } else {
00403             /* Plane is stored uncompressed */
00404             for (i = 0; i < height; i++) {
00405                 memcpy(dst + (i * stride), src, width);
00406                 src += width;
00407             }
00408         }
00409     } else if (esc_count == 0xff) {
00410         /* Plane is a solid run of given value */
00411         for (i = 0; i < height; i++)
00412             memset(dst + i * stride, src[1], width);
00413         /* Do not apply prediction.
00414            Note: memset to 0 above, setting first value to src[1]
00415            and applying prediction gives the same result. */
00416         return 0;
00417     } else {
00418         av_log(l->avctx, AV_LOG_ERROR,
00419                "Invalid zero run escape code! (%#x)\n", esc_count);
00420         return -1;
00421     }
00422 
00423     for (i = 0; i < height; i++) {
00424         lag_pred_line(l, dst, width, stride, i);
00425         dst += stride;
00426     }
00427 
00428     return 0;
00429 }
00430 
00439 static int lag_decode_frame(AVCodecContext *avctx,
00440                             void *data, int *data_size, AVPacket *avpkt)
00441 {
00442     const uint8_t *buf = avpkt->data;
00443     int buf_size = avpkt->size;
00444     LagarithContext *l = avctx->priv_data;
00445     AVFrame *const p = &l->picture;
00446     uint8_t frametype = 0;
00447     uint32_t offset_gu = 0, offset_bv = 0, offset_ry = 9;
00448     int offs[4];
00449     uint8_t *srcs[4], *dst;
00450     int i, j;
00451 
00452     AVFrame *picture = data;
00453 
00454     if (p->data[0])
00455         avctx->release_buffer(avctx, p);
00456 
00457     p->reference = 0;
00458     p->key_frame = 1;
00459 
00460     frametype = buf[0];
00461 
00462     offset_gu = AV_RL32(buf + 1);
00463     offset_bv = AV_RL32(buf + 5);
00464 
00465     switch (frametype) {
00466     case FRAME_SOLID_RGBA:
00467         avctx->pix_fmt = PIX_FMT_RGB32;
00468 
00469         if (avctx->get_buffer(avctx, p) < 0) {
00470             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00471             return -1;
00472         }
00473 
00474         dst = p->data[0];
00475         for (j = 0; j < avctx->height; j++) {
00476             for (i = 0; i < avctx->width; i++)
00477                 AV_WN32(dst + i * 4, offset_gu);
00478             dst += p->linesize[0];
00479         }
00480         break;
00481     case FRAME_ARITH_RGBA:
00482         avctx->pix_fmt = PIX_FMT_RGB32;
00483 
00484         if (avctx->get_buffer(avctx, p) < 0) {
00485             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00486             return -1;
00487         }
00488         offs[0] = offset_bv;
00489         offs[1] = offset_gu;
00490         offs[2] = 13;
00491         offs[3] = AV_RL32(buf + 9);
00492 
00493         if (!l->rgb_planes) {
00494             l->rgb_stride = FFALIGN(avctx->width, 16);
00495             l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * 4);
00496             if (!l->rgb_planes) {
00497                 av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n");
00498                 return AVERROR(ENOMEM);
00499             }
00500         }
00501         for (i = 0; i < 4; i++)
00502             srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride;
00503         for (i = 0; i < 4; i++)
00504             lag_decode_arith_plane(l, srcs[i],
00505                                    avctx->width, avctx->height,
00506                                    -l->rgb_stride, buf + offs[i],
00507                                    buf_size);
00508         dst = p->data[0];
00509         for (i = 0; i < 4; i++)
00510             srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height;
00511         for (j = 0; j < avctx->height; j++) {
00512             for (i = 0; i < avctx->width; i++) {
00513                 uint8_t r, g, b, a;
00514                 r = srcs[0][i];
00515                 g = srcs[1][i];
00516                 b = srcs[2][i];
00517                 a = srcs[3][i];
00518                 r += g;
00519                 b += g;
00520                 AV_WN32(dst + i * 4, MKBETAG(a, r, g, b));
00521             }
00522             dst += p->linesize[0];
00523             for (i = 0; i < 4; i++)
00524                 srcs[i] += l->rgb_stride;
00525         }
00526         break;
00527     case FRAME_ARITH_RGB24:
00528         avctx->pix_fmt = PIX_FMT_RGB24;
00529 
00530         if (avctx->get_buffer(avctx, p) < 0) {
00531             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00532             return -1;
00533         }
00534         offs[0] = offset_bv;
00535         offs[1] = offset_gu;
00536         offs[2] = 9;
00537 
00538         if (!l->rgb_planes) {
00539             l->rgb_stride = FFALIGN(avctx->width, 16);
00540             l->rgb_planes = av_malloc(l->rgb_stride * avctx->height * 3);
00541             if (!l->rgb_planes) {
00542                 av_log(avctx, AV_LOG_ERROR, "cannot allocate temporary buffer\n");
00543                 return AVERROR(ENOMEM);
00544             }
00545         }
00546         for (i = 0; i < 3; i++)
00547             srcs[i] = l->rgb_planes + (i + 1) * l->rgb_stride * avctx->height - l->rgb_stride;
00548         for (i = 0; i < 3; i++)
00549             lag_decode_arith_plane(l, srcs[i],
00550                                    avctx->width, avctx->height,
00551                                    -l->rgb_stride, buf + offs[i],
00552                                    buf_size);
00553         dst = p->data[0];
00554         for (i = 0; i < 3; i++)
00555             srcs[i] = l->rgb_planes + i * l->rgb_stride * avctx->height;
00556         for (j = 0; j < avctx->height; j++) {
00557             for (i = 0; i < avctx->width; i++) {
00558                 uint8_t r, g, b;
00559                 r = srcs[0][i];
00560                 g = srcs[1][i];
00561                 b = srcs[2][i];
00562                 dst[3*i+0] = r+g;
00563                 dst[3*i+1] = g;
00564                 dst[3*i+2] = b+g;
00565             }
00566             dst += p->linesize[0];
00567             for (i = 0; i < 3; i++)
00568                 srcs[i] += l->rgb_stride;
00569         }
00570         break;
00571     case FRAME_ARITH_YV12:
00572         avctx->pix_fmt = PIX_FMT_YUV420P;
00573 
00574         if (avctx->get_buffer(avctx, p) < 0) {
00575             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00576             return -1;
00577         }
00578 
00579         lag_decode_arith_plane(l, p->data[0], avctx->width, avctx->height,
00580                                p->linesize[0], buf + offset_ry,
00581                                buf_size);
00582         lag_decode_arith_plane(l, p->data[2], avctx->width / 2,
00583                                avctx->height / 2, p->linesize[2],
00584                                buf + offset_gu, buf_size);
00585         lag_decode_arith_plane(l, p->data[1], avctx->width / 2,
00586                                avctx->height / 2, p->linesize[1],
00587                                buf + offset_bv, buf_size);
00588         break;
00589     default:
00590         av_log(avctx, AV_LOG_ERROR,
00591                "Unsupported Lagarith frame type: %#x\n", frametype);
00592         return -1;
00593     }
00594 
00595     *picture = *p;
00596     *data_size = sizeof(AVFrame);
00597 
00598     return buf_size;
00599 }
00600 
00601 static av_cold int lag_decode_init(AVCodecContext *avctx)
00602 {
00603     LagarithContext *l = avctx->priv_data;
00604     l->avctx = avctx;
00605 
00606     dsputil_init(&l->dsp, avctx);
00607 
00608     return 0;
00609 }
00610 
00611 static av_cold int lag_decode_end(AVCodecContext *avctx)
00612 {
00613     LagarithContext *l = avctx->priv_data;
00614 
00615     if (l->picture.data[0])
00616         avctx->release_buffer(avctx, &l->picture);
00617     av_freep(&l->rgb_planes);
00618 
00619     return 0;
00620 }
00621 
00622 AVCodec ff_lagarith_decoder = {
00623     .name           = "lagarith",
00624     .type           = AVMEDIA_TYPE_VIDEO,
00625     .id             = CODEC_ID_LAGARITH,
00626     .priv_data_size = sizeof(LagarithContext),
00627     .init           = lag_decode_init,
00628     .close          = lag_decode_end,
00629     .decode         = lag_decode_frame,
00630     .capabilities   = CODEC_CAP_DR1,
00631     .long_name = NULL_IF_CONFIG_SMALL("Lagarith lossless"),
00632 };