You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.6KB

  1. /*
  2. * RLE encoder
  3. * Copyright (c) 2007 Bobby Bingham
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  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. *
  12. * Libav is distributed in the hope that it will be useful,
  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
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/common.h"
  22. #include "avcodec.h"
  23. #include "rle.h"
  24. int ff_rle_count_pixels(const uint8_t *start, int len, int bpp, int same)
  25. {
  26. const uint8_t *pos;
  27. int count = 1;
  28. for (pos = start + bpp; count < FFMIN(127, len); pos += bpp, count++) {
  29. if (same != !memcmp(pos - bpp, pos, bpp)) {
  30. if (!same) {
  31. /* if bpp == 1, then 0 1 1 0 is more efficiently encoded as a
  32. * single raw block of pixels. For larger bpp, RLE is as good
  33. * or better */
  34. if (bpp == 1 && count + 1 < FFMIN(127, len) && *pos != *(pos + 1))
  35. continue;
  36. /* if RLE can encode the next block better than as a raw block,
  37. * back up and leave _all_ the identical pixels for RLE */
  38. count--;
  39. }
  40. break;
  41. }
  42. }
  43. return count;
  44. }
  45. int ff_rle_encode(uint8_t *outbuf, int out_size, const uint8_t *ptr, int bpp,
  46. int w, int add_rep, int xor_rep, int add_raw, int xor_raw)
  47. {
  48. int count, x;
  49. uint8_t *out = outbuf;
  50. for (x = 0; x < w; x += count) {
  51. /* see if we can encode the next set of pixels with RLE */
  52. if ((count = ff_rle_count_pixels(ptr, w - x, bpp, 1)) > 1) {
  53. if (out + bpp + 1 > outbuf + out_size)
  54. return -1;
  55. *out++ = (count ^ xor_rep) + add_rep;
  56. memcpy(out, ptr, bpp);
  57. out += bpp;
  58. } else {
  59. /* fall back on uncompressed */
  60. count = ff_rle_count_pixels(ptr, w - x, bpp, 0);
  61. if (out + bpp * count >= outbuf + out_size)
  62. return -1;
  63. *out++ = (count ^ xor_raw) + add_raw;
  64. memcpy(out, ptr, bpp * count);
  65. out += bpp * count;
  66. }
  67. ptr += count * bpp;
  68. }
  69. return out - outbuf;
  70. }