1
0

process.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package main
  2. /*
  3. #cgo pkg-config: vips
  4. #cgo LDFLAGS: -s -w
  5. #include "vips.h"
  6. */
  7. import "C"
  8. import (
  9. "errors"
  10. "log"
  11. "math"
  12. "os"
  13. "runtime"
  14. "unsafe"
  15. )
  16. type imageType int
  17. const (
  18. UNKNOWN = C.UNKNOWN
  19. JPEG = C.JPEG
  20. PNG = C.PNG
  21. WEBP = C.WEBP
  22. GIF = C.GIF
  23. )
  24. var imageTypes = map[string]imageType{
  25. "jpeg": JPEG,
  26. "jpg": JPEG,
  27. "png": PNG,
  28. "webp": WEBP,
  29. "gif": GIF,
  30. }
  31. type gravityType int
  32. const (
  33. CENTER gravityType = iota
  34. NORTH
  35. EAST
  36. SOUTH
  37. WEST
  38. SMART
  39. )
  40. var gravityTypes = map[string]gravityType{
  41. "ce": CENTER,
  42. "no": NORTH,
  43. "ea": EAST,
  44. "so": SOUTH,
  45. "we": WEST,
  46. "sm": SMART,
  47. }
  48. type resizeType int
  49. const (
  50. FIT resizeType = iota
  51. FILL
  52. CROP
  53. )
  54. var resizeTypes = map[string]resizeType{
  55. "fit": FIT,
  56. "fill": FILL,
  57. "crop": CROP,
  58. }
  59. type processingOptions struct {
  60. resize resizeType
  61. width int
  62. height int
  63. gravity gravityType
  64. enlarge bool
  65. format imageType
  66. }
  67. var vipsSupportSmartcrop bool
  68. var vipsTypeSupportLoad = make(map[imageType]bool)
  69. var vipsTypeSupportSave = make(map[imageType]bool)
  70. func initVips() {
  71. runtime.LockOSThread()
  72. defer runtime.UnlockOSThread()
  73. if err := C.vips_initialize(); err != 0 {
  74. C.vips_shutdown()
  75. log.Fatalln("unable to start vips!")
  76. }
  77. C.vips_cache_set_max_mem(100 * 1024 * 1024) // 100Mb
  78. C.vips_cache_set_max(500)
  79. if len(os.Getenv("IMGPROXY_VIPS_LEAK_CHECK")) > 0 {
  80. C.vips_leak_set(C.gboolean(1))
  81. }
  82. if len(os.Getenv("IMGPROXY_VIPS_CACHE_TRACE")) > 0 {
  83. C.vips_cache_set_trace(C.gboolean(1))
  84. }
  85. vipsSupportSmartcrop = C.vips_support_smartcrop() == 1
  86. if int(C.vips_type_find_load_go(C.JPEG)) != 0 {
  87. vipsTypeSupportLoad[JPEG] = true
  88. }
  89. if int(C.vips_type_find_load_go(C.PNG)) != 0 {
  90. vipsTypeSupportLoad[PNG] = true
  91. }
  92. if int(C.vips_type_find_load_go(C.WEBP)) != 0 {
  93. vipsTypeSupportLoad[WEBP] = true
  94. }
  95. if int(C.vips_type_find_load_go(C.GIF)) != 0 {
  96. vipsTypeSupportLoad[GIF] = true
  97. }
  98. if int(C.vips_type_find_save_go(C.JPEG)) != 0 {
  99. vipsTypeSupportSave[JPEG] = true
  100. }
  101. if int(C.vips_type_find_save_go(C.PNG)) != 0 {
  102. vipsTypeSupportSave[PNG] = true
  103. }
  104. if int(C.vips_type_find_save_go(C.WEBP)) != 0 {
  105. vipsTypeSupportSave[WEBP] = true
  106. }
  107. }
  108. func shutdownVips() {
  109. C.vips_shutdown()
  110. }
  111. func randomAccessRequired(po processingOptions) int {
  112. if po.gravity == SMART {
  113. return 1
  114. }
  115. return 0
  116. }
  117. func round(f float64) int {
  118. return int(f + .5)
  119. }
  120. func extractMeta(img *C.VipsImage) (int, int, int, bool) {
  121. width := int(img.Xsize)
  122. height := int(img.Ysize)
  123. angle := C.VIPS_ANGLE_D0
  124. flip := false
  125. orientation := C.vips_get_exif_orientation(img)
  126. if orientation >= 5 && orientation <= 8 {
  127. width, height = height, width
  128. }
  129. if orientation == 3 || orientation == 4 {
  130. angle = C.VIPS_ANGLE_D180
  131. }
  132. if orientation == 5 || orientation == 6 {
  133. angle = C.VIPS_ANGLE_D90
  134. }
  135. if orientation == 7 || orientation == 8 {
  136. angle = C.VIPS_ANGLE_D270
  137. }
  138. if orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7 {
  139. flip = true
  140. }
  141. return width, height, angle, flip
  142. }
  143. func calcScale(width, height int, po processingOptions) float64 {
  144. if (po.width == width && po.height == height) || (po.resize != FILL && po.resize != FIT) {
  145. return 1
  146. }
  147. fsw, fsh, fow, foh := float64(width), float64(height), float64(po.width), float64(po.height)
  148. wr := fow / fsw
  149. hr := foh / fsh
  150. if po.resize == FIT {
  151. return math.Min(wr, hr)
  152. }
  153. return math.Max(wr, hr)
  154. }
  155. func calcShink(scale float64, imgtype imageType) int {
  156. shrink := int(1.0 / scale)
  157. if imgtype != JPEG {
  158. return shrink
  159. }
  160. switch {
  161. case shrink >= 16:
  162. return 8
  163. case shrink >= 8:
  164. return 4
  165. case shrink >= 4:
  166. return 2
  167. }
  168. return 1
  169. }
  170. func calcCrop(width, height int, po processingOptions) (left, top int) {
  171. left = (width - po.width + 1) / 2
  172. top = (height - po.height + 1) / 2
  173. if po.gravity == NORTH {
  174. top = 0
  175. }
  176. if po.gravity == EAST {
  177. left = width - po.width
  178. }
  179. if po.gravity == SOUTH {
  180. top = height - po.height
  181. }
  182. if po.gravity == WEST {
  183. left = 0
  184. }
  185. return
  186. }
  187. func processImage(data []byte, imgtype imageType, po processingOptions, t *timer) ([]byte, error) {
  188. defer C.vips_cleanup()
  189. defer keepAlive(data)
  190. if po.gravity == SMART && !vipsSupportSmartcrop {
  191. return nil, errors.New("Smart crop is not supported by used version of libvips")
  192. }
  193. img, err := vipsLoadImage(data, imgtype, 1)
  194. if err != nil {
  195. return nil, err
  196. }
  197. defer C.clear_image(&img)
  198. t.Check()
  199. imgWidth, imgHeight, angle, flip := extractMeta(img)
  200. // Ensure we won't crop out of bounds
  201. if !po.enlarge || po.resize == CROP {
  202. if imgWidth < po.width {
  203. po.width = imgWidth
  204. }
  205. if imgHeight < po.height {
  206. po.height = imgHeight
  207. }
  208. }
  209. if po.width != imgWidth || po.height != imgHeight {
  210. if po.resize == FILL || po.resize == FIT {
  211. scale := calcScale(imgWidth, imgHeight, po)
  212. // Do some shrink-on-load
  213. if scale < 1.0 {
  214. if imgtype == JPEG || imgtype == WEBP {
  215. shrink := calcShink(scale, imgtype)
  216. scale = scale * float64(shrink)
  217. if tmp, e := vipsLoadImage(data, imgtype, shrink); e == nil {
  218. C.swap_and_clear(&img, tmp)
  219. } else {
  220. return nil, e
  221. }
  222. }
  223. }
  224. have_premultiplied := false
  225. var bandFormat C.VipsBandFormat
  226. if vipsImageHasAlpha(img) {
  227. if bandFormat, err = vipsPremultiply(&img); err != nil {
  228. return nil, err
  229. }
  230. have_premultiplied = true
  231. }
  232. if err = vipsResize(&img, scale); err != nil {
  233. return nil, err
  234. }
  235. if have_premultiplied {
  236. if err = vipsUnpremultiply(&img, bandFormat); err != nil {
  237. return nil, err
  238. }
  239. }
  240. }
  241. if err = vipsFixColourspace(&img); err != nil {
  242. return nil, err
  243. }
  244. t.Check()
  245. if angle != C.VIPS_ANGLE_D0 || flip {
  246. if err = vipsImageCopyMemory(&img); err != nil {
  247. return nil, err
  248. }
  249. if angle != C.VIPS_ANGLE_D0 {
  250. if err = vipsRotate(&img, angle); err != nil {
  251. return nil, err
  252. }
  253. }
  254. if flip {
  255. if err = vipsFlip(&img); err != nil {
  256. return nil, err
  257. }
  258. }
  259. }
  260. t.Check()
  261. if po.resize == FILL || po.resize == CROP {
  262. if po.gravity == SMART {
  263. if err = vipsImageCopyMemory(&img); err != nil {
  264. return nil, err
  265. }
  266. if err = vipsSmartCrop(&img, po.width, po.height); err != nil {
  267. return nil, err
  268. }
  269. } else {
  270. left, top := calcCrop(int(img.Xsize), int(img.Ysize), po)
  271. if err = vipsCrop(&img, left, top, po.width, po.height); err != nil {
  272. return nil, err
  273. }
  274. }
  275. }
  276. }
  277. t.Check()
  278. return vipsSaveImage(img, po.format)
  279. }
  280. func vipsLoadImage(data []byte, imgtype imageType, shrink int) (*C.struct__VipsImage, error) {
  281. var img *C.struct__VipsImage
  282. if C.vips_load_buffer(unsafe.Pointer(&data[0]), C.size_t(len(data)), C.int(imgtype), C.int(shrink), &img) != 0 {
  283. return nil, vipsError()
  284. }
  285. return img, nil
  286. }
  287. func vipsSaveImage(img *C.struct__VipsImage, imgtype imageType) ([]byte, error) {
  288. var ptr unsafe.Pointer
  289. defer C.g_free_go(&ptr)
  290. err := C.int(0)
  291. imgsize := C.size_t(0)
  292. switch imgtype {
  293. case JPEG:
  294. err = C.vips_jpegsave_go(img, &ptr, &imgsize, 1, C.int(conf.Quality), 0)
  295. case PNG:
  296. err = C.vips_pngsave_go(img, &ptr, &imgsize)
  297. case WEBP:
  298. err = C.vips_webpsave_go(img, &ptr, &imgsize, 1, C.int(conf.Quality))
  299. }
  300. if err != 0 {
  301. return nil, vipsError()
  302. }
  303. return C.GoBytes(ptr, C.int(imgsize)), nil
  304. }
  305. func vipsImageHasAlpha(img *C.struct__VipsImage) bool {
  306. return C.vips_image_hasalpha_go(img) > 0
  307. }
  308. func vipsPremultiply(img **C.struct__VipsImage) (C.VipsBandFormat, error) {
  309. var tmp *C.struct__VipsImage
  310. format := C.vips_band_format(*img)
  311. if C.vips_premultiply_go(*img, &tmp) != 0 {
  312. return 0, vipsError()
  313. }
  314. C.swap_and_clear(img, tmp)
  315. return format, nil
  316. }
  317. func vipsUnpremultiply(img **C.struct__VipsImage, format C.VipsBandFormat) error {
  318. var tmp *C.struct__VipsImage
  319. if C.vips_unpremultiply_go(*img, &tmp) != 0 {
  320. return vipsError()
  321. }
  322. C.swap_and_clear(img, tmp)
  323. if C.vips_cast_go(*img, &tmp, format) != 0 {
  324. return vipsError()
  325. }
  326. C.swap_and_clear(img, tmp)
  327. return nil
  328. }
  329. func vipsResize(img **C.struct__VipsImage, scale float64) error {
  330. var tmp *C.struct__VipsImage
  331. if C.vips_resize_go(*img, &tmp, C.double(scale)) != 0 {
  332. return vipsError()
  333. }
  334. C.swap_and_clear(img, tmp)
  335. return nil
  336. }
  337. func vipsRotate(img **C.struct__VipsImage, angle int) error {
  338. var tmp *C.struct__VipsImage
  339. if C.vips_rot_go(*img, &tmp, C.VipsAngle(angle)) != 0 {
  340. return vipsError()
  341. }
  342. C.swap_and_clear(img, tmp)
  343. return nil
  344. }
  345. func vipsFlip(img **C.struct__VipsImage) error {
  346. var tmp *C.struct__VipsImage
  347. if C.vips_flip_horizontal_go(*img, &tmp) != 0 {
  348. return vipsError()
  349. }
  350. C.swap_and_clear(img, tmp)
  351. return nil
  352. }
  353. func vipsCrop(img **C.struct__VipsImage, left, top, width, height int) error {
  354. var tmp *C.struct__VipsImage
  355. if C.vips_extract_area_go(*img, &tmp, C.int(left), C.int(top), C.int(width), C.int(height)) != 0 {
  356. return vipsError()
  357. }
  358. C.swap_and_clear(img, tmp)
  359. return nil
  360. }
  361. func vipsSmartCrop(img **C.struct__VipsImage, width, height int) error {
  362. var tmp *C.struct__VipsImage
  363. if C.vips_smartcrop_go(*img, &tmp, C.int(width), C.int(height)) != 0 {
  364. return vipsError()
  365. }
  366. C.swap_and_clear(img, tmp)
  367. return nil
  368. }
  369. func vipsFixColourspace(img **C.struct__VipsImage) error {
  370. var tmp *C.struct__VipsImage
  371. if C.vips_image_guess_interpretation(*img) != C.VIPS_INTERPRETATION_sRGB {
  372. if C.vips_colourspace_go(*img, &tmp, C.VIPS_INTERPRETATION_sRGB) != 0 {
  373. return vipsError()
  374. }
  375. C.swap_and_clear(img, tmp)
  376. }
  377. return nil
  378. }
  379. func vipsImageCopyMemory(img **C.struct__VipsImage) error {
  380. var tmp *C.struct__VipsImage
  381. if tmp = C.vips_image_copy_memory(*img); tmp == nil {
  382. return vipsError()
  383. }
  384. C.swap_and_clear(img, tmp)
  385. return nil
  386. }
  387. func vipsError() error {
  388. return errors.New(C.GoString(C.vips_error_buffer()))
  389. }