rle: K&R formatting cosmetics
[libav.git] / libavcodec / rle.c
CommitLineData
1ca286e1
MN
1/*
2 * RLE encoder
3 * Copyright (c) 2007 Bobby Bingham
4 *
2912e87a 5 * This file is part of Libav.
1ca286e1 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
1ca286e1
MN
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
1ca286e1
MN
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
2912e87a 18 * License along with Libav; if not, write to the Free Software
1ca286e1 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1ca286e1 20 */
eeb6849c
VG
21
22#include "libavutil/common.h"
23
1ca286e1
MN
24#include "avcodec.h"
25#include "rle.h"
26
59e3f4e5 27int ff_rle_count_pixels(const uint8_t *start, int len, int bpp, int same)
1ca286e1
MN
28{
29 const uint8_t *pos;
30 int count = 1;
31
eeb6849c
VG
32 for (pos = start + bpp; count < FFMIN(127, len); pos += bpp, count++) {
33 if (same != !memcmp(pos - bpp, pos, bpp)) {
34 if (!same) {
35 /* if bpp == 1, then 0 1 1 0 is more efficiently encoded as a
36 * single raw block of pixels. For larger bpp, RLE is as good
37 * or better */
38 if (bpp == 1 && count + 1 < FFMIN(127, len) && *pos != *(pos + 1))
1ca286e1
MN
39 continue;
40
41 /* if RLE can encode the next block better than as a raw block,
42 * back up and leave _all_ the identical pixels for RLE */
eeb6849c 43 count--;
1ca286e1
MN
44 }
45 break;
46 }
47 }
48
49 return count;
50}
51
eeb6849c
VG
52int ff_rle_encode(uint8_t *outbuf, int out_size, const uint8_t *ptr, int bpp,
53 int w, int add_rep, int xor_rep, int add_raw, int xor_raw)
1ca286e1
MN
54{
55 int count, x;
65df5449 56 uint8_t *out = outbuf;
1ca286e1 57
eeb6849c 58 for (x = 0; x < w; x += count) {
eb24fd64 59 /* see if we can encode the next set of pixels with RLE */
59e3f4e5 60 if ((count = ff_rle_count_pixels(ptr, w - x, bpp, 1)) > 1) {
eeb6849c
VG
61 if (out + bpp + 1 > outbuf + out_size)
62 return -1;
63
b25514a4 64 *out++ = (count ^ xor_rep) + add_rep;
eb24fd64
MN
65 memcpy(out, ptr, bpp);
66 out += bpp;
67 } else {
68 /* fall back on uncompressed */
59e3f4e5 69 count = ff_rle_count_pixels(ptr, w - x, bpp, 0);
eeb6849c
VG
70 if (out + bpp * count >= outbuf + out_size)
71 return -1;
1ca286e1 72
eeb6849c 73 *out++ = (count ^ xor_raw) + add_raw;
eb24fd64
MN
74 memcpy(out, ptr, bpp * count);
75 out += bpp * count;
1ca286e1
MN
76 }
77
78 ptr += count * bpp;
79 }
80
81 return out - outbuf;
82}