PackDecode.c 1.5 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(Imaging im, ImagingCodecState state,
  18. UINT8* buf, Py_ssize_t bytes)
  19. {
  20. UINT8 n;
  21. UINT8* ptr;
  22. int i;
  23. ptr = buf;
  24. for (;;) {
  25. if (bytes < 1)
  26. return ptr - buf;
  27. if (ptr[0] & 0x80) {
  28. if (ptr[0] == 0x80) {
  29. /* Nop */
  30. ptr++; bytes--;
  31. continue;
  32. }
  33. /* Run */
  34. if (bytes < 2)
  35. return ptr - buf;
  36. for (n = 257 - ptr[0]; n > 0; n--) {
  37. if (state->x >= state->bytes) {
  38. /* state->errcode = IMAGING_CODEC_OVERRUN; */
  39. break;
  40. }
  41. state->buffer[state->x++] = ptr[1];
  42. }
  43. ptr += 2; bytes -= 2;
  44. } else {
  45. /* Literal */
  46. n = ptr[0]+2;
  47. if (bytes < n)
  48. return ptr - buf;
  49. for (i = 1; i < n; i++) {
  50. if (state->x >= state->bytes) {
  51. /* state->errcode = IMAGING_CODEC_OVERRUN; */
  52. break;
  53. }
  54. state->buffer[state->x++] = ptr[i];
  55. }
  56. ptr += n; bytes -= n;
  57. }
  58. if (state->x >= state->bytes) {
  59. /* Got a full line, unpack it */
  60. state->shuffle((UINT8*) im->image[state->y + state->yoff] +
  61. state->xoff * im->pixelsize, state->buffer,
  62. state->xsize);
  63. state->x = 0;
  64. if (++state->y >= state->ysize) {
  65. /* End of file (errcode = 0) */
  66. return -1;
  67. }
  68. }
  69. }
  70. }