PackDecode.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * The Python Imaging Library.
  3. * $Id$
  4. *
  5. * decoder for PackBits image data.
  6. *
  7. * history:
  8. * 96-04-19 fl Created
  9. *
  10. * Copyright (c) Fredrik Lundh 1996.
  11. * Copyright (c) Secret Labs AB 1997.
  12. *
  13. * See the README file for information on usage and redistribution.
  14. */
  15. #include "Imaging.h"
  16. int
  17. ImagingPackbitsDecode(
  18. Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {
  19. UINT8 n;
  20. UINT8 *ptr;
  21. int i;
  22. ptr = buf;
  23. for (;;) {
  24. if (bytes < 1) {
  25. return ptr - buf;
  26. }
  27. if (ptr[0] & 0x80) {
  28. if (ptr[0] == 0x80) {
  29. /* Nop */
  30. ptr++;
  31. bytes--;
  32. continue;
  33. }
  34. /* Run */
  35. if (bytes < 2) {
  36. return ptr - buf;
  37. }
  38. for (n = 257 - ptr[0]; n > 0; n--) {
  39. if (state->x >= state->bytes) {
  40. /* state->errcode = IMAGING_CODEC_OVERRUN; */
  41. break;
  42. }
  43. state->buffer[state->x++] = ptr[1];
  44. }
  45. ptr += 2;
  46. bytes -= 2;
  47. } else {
  48. /* Literal */
  49. n = ptr[0] + 2;
  50. if (bytes < n) {
  51. return ptr - buf;
  52. }
  53. for (i = 1; i < n; i++) {
  54. if (state->x >= state->bytes) {
  55. /* state->errcode = IMAGING_CODEC_OVERRUN; */
  56. break;
  57. }
  58. state->buffer[state->x++] = ptr[i];
  59. }
  60. ptr += n;
  61. bytes -= n;
  62. }
  63. if (state->x >= state->bytes) {
  64. /* Got a full line, unpack it */
  65. state->shuffle(
  66. (UINT8 *)im->image[state->y + state->yoff] +
  67. state->xoff * im->pixelsize,
  68. state->buffer,
  69. state->xsize);
  70. state->x = 0;
  71. if (++state->y >= state->ysize) {
  72. /* End of file (errcode = 0) */
  73. return -1;
  74. }
  75. }
  76. }
  77. }