source.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package vips
  2. /*
  3. #cgo pkg-config: vips
  4. #cgo CFLAGS: -O3
  5. #cgo LDFLAGS: -lm
  6. #include "source.h"
  7. #include "vips.h"
  8. */
  9. import "C"
  10. import (
  11. "io"
  12. "runtime/cgo"
  13. "unsafe"
  14. )
  15. // newVipsSource creates a new VipsAsyncSource from an io.ReadSeeker.
  16. func newVipsImgproxySource(r io.ReadSeeker) *C.VipsImgproxySource {
  17. handler := cgo.NewHandle(r)
  18. return C.vips_new_imgproxy_source(C.uintptr_t(handler))
  19. }
  20. //export closeImgproxyReader
  21. func closeImgproxyReader(handle C.uintptr_t) {
  22. h := cgo.Handle(handle)
  23. h.Delete()
  24. }
  25. // calls seek() on the async reader via it's handle from the C side
  26. //
  27. //export imgproxyReaderSeek
  28. func imgproxyReaderSeek(handle C.uintptr_t, offset C.int64_t, whence int) C.int64_t {
  29. h := cgo.Handle(handle)
  30. r, ok := h.Value().(io.ReadSeeker)
  31. if !ok {
  32. vipsError("imgproxyReaderSeek", "failed to cast handle to io.ReadSeeker")
  33. return -1
  34. }
  35. pos, err := r.Seek(int64(offset), whence)
  36. if err != nil {
  37. vipsError("imgproxyReaderSeek", "failed to seek: %v", err)
  38. return -1
  39. }
  40. return C.int64_t(pos)
  41. }
  42. // calls read() on the async reader via it's handle from the C side
  43. //
  44. //export imgproxyReaderRead
  45. func imgproxyReaderRead(handle C.uintptr_t, pointer unsafe.Pointer, size C.int64_t) C.int64_t {
  46. h := cgo.Handle(handle)
  47. r, ok := h.Value().(io.ReadSeeker)
  48. if !ok {
  49. vipsError("imgproxyReaderRead", "invalid reader handle")
  50. return -1
  51. }
  52. buf := unsafe.Slice((*byte)(pointer), size)
  53. n, err := r.Read(buf)
  54. if err == io.EOF {
  55. return 0
  56. } else if err != nil {
  57. vipsError("imgproxyReaderRead", "error reading from imgproxy source: %v", err)
  58. return -1
  59. }
  60. return C.int64_t(n)
  61. }