TgaRleDecode.c 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /*
  2. * The Python Imaging Library.
  3. * $Id$
  4. *
  5. * decoder for Targa RLE data.
  6. *
  7. * history:
  8. * 97-01-04 fl created
  9. * 98-09-11 fl don't one byte per pixel; take orientation into account
  10. *
  11. * Copyright (c) Fredrik Lundh 1997.
  12. * Copyright (c) Secret Labs AB 1997-98.
  13. *
  14. * See the README file for information on usage and redistribution.
  15. */
  16. #include "Imaging.h"
  17. int
  18. ImagingTgaRleDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {
  19. int n, depth;
  20. UINT8 *ptr;
  21. int extra_bytes = 0;
  22. ptr = buf;
  23. if (state->state == 0) {
  24. /* check image orientation */
  25. if (state->ystep < 0) {
  26. state->y = state->ysize - 1;
  27. state->ystep = -1;
  28. } else {
  29. state->ystep = 1;
  30. }
  31. state->state = 1;
  32. }
  33. depth = state->count;
  34. for (;;) {
  35. if (bytes < 1) {
  36. return ptr - buf;
  37. }
  38. n = depth * ((ptr[0] & 0x7f) + 1);
  39. if (ptr[0] & 0x80) {
  40. /* Run (1 + pixelsize bytes) */
  41. if (bytes < 1 + depth) {
  42. break;
  43. }
  44. if (state->x + n > state->bytes) {
  45. state->errcode = IMAGING_CODEC_OVERRUN;
  46. return -1;
  47. }
  48. if (depth == 1) {
  49. memset(state->buffer + state->x, ptr[1], n);
  50. } else {
  51. int i;
  52. for (i = 0; i < n; i += depth) {
  53. memcpy(state->buffer + state->x + i, ptr + 1, depth);
  54. }
  55. }
  56. ptr += 1 + depth;
  57. bytes -= 1 + depth;
  58. } else {
  59. /* Literal (1+n+1 bytes block) */
  60. if (bytes < 1 + n) {
  61. break;
  62. }
  63. if (state->x + n > state->bytes) {
  64. extra_bytes = n; /* full value */
  65. n = state->bytes - state->x;
  66. extra_bytes -= n;
  67. }
  68. memcpy(state->buffer + state->x, ptr + 1, n);
  69. ptr += 1 + n;
  70. bytes -= 1 + n;
  71. }
  72. for (;;) {
  73. state->x += n;
  74. if (state->x >= state->bytes) {
  75. /* Got a full line, unpack it */
  76. state->shuffle(
  77. (UINT8 *)im->image[state->y + state->yoff] +
  78. state->xoff * im->pixelsize,
  79. state->buffer,
  80. state->xsize);
  81. state->x = 0;
  82. state->y += state->ystep;
  83. if (state->y < 0 || state->y >= state->ysize) {
  84. /* End of file (errcode = 0) */
  85. return -1;
  86. }
  87. }
  88. if (extra_bytes == 0) {
  89. break;
  90. }
  91. if (state->x > 0) {
  92. break; // assert
  93. }
  94. if (extra_bytes >= state->bytes) {
  95. n = state->bytes;
  96. } else {
  97. n = extra_bytes;
  98. }
  99. memcpy(state->buffer + state->x, ptr, n);
  100. ptr += n;
  101. bytes -= n;
  102. extra_bytes -= n;
  103. }
  104. }
  105. return ptr - buf;
  106. }