process.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. var vipsSupportSmartcrop bool
  17. var vipsTypeSupportLoad = make(map[imageType]bool)
  18. var vipsTypeSupportSave = make(map[imageType]bool)
  19. type cConfig struct {
  20. Quality C.int
  21. JpegProgressive C.int
  22. PngInterlaced C.int
  23. }
  24. var cConf cConfig
  25. func initVips() {
  26. runtime.LockOSThread()
  27. defer runtime.UnlockOSThread()
  28. if err := C.vips_initialize(); err != 0 {
  29. C.vips_shutdown()
  30. log.Fatalln("unable to start vips!")
  31. }
  32. // Disable libvips cache. Since processing pipeline is fine tuned, we won't get much profit from it.
  33. // Enabled cache can cause SIGSEGV on Musl-based systems like Alpine.
  34. C.vips_cache_set_max_mem(0)
  35. C.vips_cache_set_max(0)
  36. if len(os.Getenv("IMGPROXY_VIPS_LEAK_CHECK")) > 0 {
  37. C.vips_leak_set(C.gboolean(1))
  38. }
  39. if len(os.Getenv("IMGPROXY_VIPS_CACHE_TRACE")) > 0 {
  40. C.vips_cache_set_trace(C.gboolean(1))
  41. }
  42. vipsSupportSmartcrop = C.vips_support_smartcrop() == 1
  43. if int(C.vips_type_find_load_go(imageTypeJPEG)) != 0 {
  44. vipsTypeSupportLoad[imageTypeJPEG] = true
  45. }
  46. if int(C.vips_type_find_load_go(imageTypePNG)) != 0 {
  47. vipsTypeSupportLoad[imageTypePNG] = true
  48. }
  49. if int(C.vips_type_find_load_go(imageTypeWEBP)) != 0 {
  50. vipsTypeSupportLoad[imageTypeWEBP] = true
  51. }
  52. if int(C.vips_type_find_load_go(imageTypeGIF)) != 0 {
  53. vipsTypeSupportLoad[imageTypeGIF] = true
  54. }
  55. if int(C.vips_type_find_save_go(imageTypeJPEG)) != 0 {
  56. vipsTypeSupportSave[imageTypeJPEG] = true
  57. }
  58. if int(C.vips_type_find_save_go(imageTypePNG)) != 0 {
  59. vipsTypeSupportSave[imageTypePNG] = true
  60. }
  61. if int(C.vips_type_find_save_go(imageTypeWEBP)) != 0 {
  62. vipsTypeSupportSave[imageTypeWEBP] = true
  63. }
  64. cConf.Quality = C.int(conf.Quality)
  65. if conf.JpegProgressive {
  66. cConf.JpegProgressive = C.int(1)
  67. }
  68. if conf.PngInterlaced {
  69. cConf.PngInterlaced = C.int(1)
  70. }
  71. }
  72. func shutdownVips() {
  73. C.vips_shutdown()
  74. }
  75. func randomAccessRequired(po processingOptions) int {
  76. if po.Gravity == gravitySmart {
  77. return 1
  78. }
  79. return 0
  80. }
  81. func round(f float64) int {
  82. return int(f + .5)
  83. }
  84. func extractMeta(img *C.VipsImage) (int, int, int, bool) {
  85. width := int(img.Xsize)
  86. height := int(img.Ysize)
  87. angle := C.VIPS_ANGLE_D0
  88. flip := false
  89. orientation := C.vips_get_exif_orientation(img)
  90. if orientation >= 5 && orientation <= 8 {
  91. width, height = height, width
  92. }
  93. if orientation == 3 || orientation == 4 {
  94. angle = C.VIPS_ANGLE_D180
  95. }
  96. if orientation == 5 || orientation == 6 {
  97. angle = C.VIPS_ANGLE_D90
  98. }
  99. if orientation == 7 || orientation == 8 {
  100. angle = C.VIPS_ANGLE_D270
  101. }
  102. if orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7 {
  103. flip = true
  104. }
  105. return width, height, angle, flip
  106. }
  107. func needToScale(width, height int, po processingOptions) bool {
  108. return ((po.Width != 0 && po.Width != width) || (po.Height != 0 && po.Height != height)) &&
  109. (po.Resize == resizeFill || po.Resize == resizeFit)
  110. }
  111. func needToCrop(width, height int, po processingOptions) bool {
  112. return (po.Width != width || po.Height != height) &&
  113. (po.Resize == resizeFill || po.Resize == resizeCrop)
  114. }
  115. func calcScale(width, height int, po processingOptions) float64 {
  116. fsw, fsh, fow, foh := float64(width), float64(height), float64(po.Width), float64(po.Height)
  117. wr := fow / fsw
  118. hr := foh / fsh
  119. if po.Width == 0 {
  120. return hr
  121. }
  122. if po.Height == 0 {
  123. return wr
  124. }
  125. if po.Resize == resizeFit {
  126. return math.Min(wr, hr)
  127. }
  128. return math.Max(wr, hr)
  129. }
  130. func calcShink(scale float64, imgtype imageType) int {
  131. shrink := int(1.0 / scale)
  132. if imgtype != imageTypeJPEG {
  133. return shrink
  134. }
  135. switch {
  136. case shrink >= 16:
  137. return 8
  138. case shrink >= 8:
  139. return 4
  140. case shrink >= 4:
  141. return 2
  142. }
  143. return 1
  144. }
  145. func calcCrop(width, height int, po processingOptions) (left, top int) {
  146. left = (width - po.Width + 1) / 2
  147. top = (height - po.Height + 1) / 2
  148. if po.Gravity == gravityNorth {
  149. top = 0
  150. }
  151. if po.Gravity == gravityEast {
  152. left = width - po.Width
  153. }
  154. if po.Gravity == gravitySouth {
  155. top = height - po.Height
  156. }
  157. if po.Gravity == gravityWest {
  158. left = 0
  159. }
  160. return
  161. }
  162. func processImage(data []byte, imgtype imageType, po processingOptions, t *timer) ([]byte, error) {
  163. defer C.vips_cleanup()
  164. defer runtime.KeepAlive(data)
  165. if po.Gravity == gravitySmart && !vipsSupportSmartcrop {
  166. return nil, errors.New("Smart crop is not supported by used version of libvips")
  167. }
  168. img, err := vipsLoadImage(data, imgtype, 1)
  169. if err != nil {
  170. return nil, err
  171. }
  172. defer C.clear_image(&img)
  173. t.Check()
  174. imgWidth, imgHeight, angle, flip := extractMeta(img)
  175. // Ensure we won't crop out of bounds
  176. if !po.Enlarge || po.Resize == resizeCrop {
  177. if imgWidth < po.Width {
  178. po.Width = imgWidth
  179. }
  180. if imgHeight < po.Height {
  181. po.Height = imgHeight
  182. }
  183. }
  184. if needToScale(imgWidth, imgHeight, po) {
  185. scale := calcScale(imgWidth, imgHeight, po)
  186. // Do some shrink-on-load
  187. if scale < 1.0 {
  188. if imgtype == imageTypeJPEG || imgtype == imageTypeWEBP {
  189. shrink := calcShink(scale, imgtype)
  190. scale = scale * float64(shrink)
  191. if tmp, e := vipsLoadImage(data, imgtype, shrink); e == nil {
  192. C.swap_and_clear(&img, tmp)
  193. } else {
  194. return nil, e
  195. }
  196. }
  197. }
  198. premultiplied := false
  199. var bandFormat C.VipsBandFormat
  200. if vipsImageHasAlpha(img) {
  201. if bandFormat, err = vipsPremultiply(&img); err != nil {
  202. return nil, err
  203. }
  204. premultiplied = true
  205. }
  206. if err = vipsResize(&img, scale); err != nil {
  207. return nil, err
  208. }
  209. // Update actual image size after resize
  210. imgWidth, imgHeight, _, _ = extractMeta(img)
  211. if premultiplied {
  212. if err = vipsUnpremultiply(&img, bandFormat); err != nil {
  213. return nil, err
  214. }
  215. }
  216. }
  217. if err = vipsImportColourProfile(&img); err != nil {
  218. return nil, err
  219. }
  220. if err = vipsFixColourspace(&img); err != nil {
  221. return nil, err
  222. }
  223. t.Check()
  224. if angle != C.VIPS_ANGLE_D0 || flip {
  225. if err = vipsImageCopyMemory(&img); err != nil {
  226. return nil, err
  227. }
  228. if angle != C.VIPS_ANGLE_D0 {
  229. if err = vipsRotate(&img, angle); err != nil {
  230. return nil, err
  231. }
  232. }
  233. if flip {
  234. if err = vipsFlip(&img); err != nil {
  235. return nil, err
  236. }
  237. }
  238. }
  239. t.Check()
  240. if po.Width == 0 {
  241. po.Width = imgWidth
  242. }
  243. if po.Height == 0 {
  244. po.Height = imgHeight
  245. }
  246. if needToCrop(imgWidth, imgHeight, po) {
  247. if po.Gravity == gravitySmart {
  248. if err = vipsImageCopyMemory(&img); err != nil {
  249. return nil, err
  250. }
  251. if err = vipsSmartCrop(&img, po.Width, po.Height); err != nil {
  252. return nil, err
  253. }
  254. } else {
  255. left, top := calcCrop(imgWidth, imgHeight, po)
  256. if err = vipsCrop(&img, left, top, po.Width, po.Height); err != nil {
  257. return nil, err
  258. }
  259. }
  260. t.Check()
  261. }
  262. if po.Blur > 0 {
  263. if err = vipsBlur(&img, po.Blur); err != nil {
  264. return nil, err
  265. }
  266. }
  267. if po.Sharpen > 0 {
  268. if err = vipsSharpen(&img, po.Sharpen); err != nil {
  269. return nil, err
  270. }
  271. }
  272. t.Check()
  273. return vipsSaveImage(img, po.Format)
  274. }
  275. func vipsLoadImage(data []byte, imgtype imageType, shrink int) (*C.struct__VipsImage, error) {
  276. var img *C.struct__VipsImage
  277. if C.vips_load_buffer(unsafe.Pointer(&data[0]), C.size_t(len(data)), C.int(imgtype), C.int(shrink), &img) != 0 {
  278. return nil, vipsError()
  279. }
  280. return img, nil
  281. }
  282. func vipsSaveImage(img *C.struct__VipsImage, imgtype imageType) ([]byte, error) {
  283. var ptr unsafe.Pointer
  284. defer C.g_free_go(&ptr)
  285. err := C.int(0)
  286. imgsize := C.size_t(0)
  287. switch imgtype {
  288. case imageTypeJPEG:
  289. err = C.vips_jpegsave_go(img, &ptr, &imgsize, 1, cConf.Quality, cConf.JpegProgressive)
  290. case imageTypePNG:
  291. err = C.vips_pngsave_go(img, &ptr, &imgsize, cConf.PngInterlaced)
  292. case imageTypeWEBP:
  293. err = C.vips_webpsave_go(img, &ptr, &imgsize, 1, cConf.Quality)
  294. }
  295. if err != 0 {
  296. return nil, vipsError()
  297. }
  298. return C.GoBytes(ptr, C.int(imgsize)), nil
  299. }
  300. func vipsImageHasAlpha(img *C.struct__VipsImage) bool {
  301. return C.vips_image_hasalpha_go(img) > 0
  302. }
  303. func vipsPremultiply(img **C.struct__VipsImage) (C.VipsBandFormat, error) {
  304. var tmp *C.struct__VipsImage
  305. format := C.vips_band_format(*img)
  306. if C.vips_premultiply_go(*img, &tmp) != 0 {
  307. return 0, vipsError()
  308. }
  309. C.swap_and_clear(img, tmp)
  310. return format, nil
  311. }
  312. func vipsUnpremultiply(img **C.struct__VipsImage, format C.VipsBandFormat) error {
  313. var tmp *C.struct__VipsImage
  314. if C.vips_unpremultiply_go(*img, &tmp) != 0 {
  315. return vipsError()
  316. }
  317. C.swap_and_clear(img, tmp)
  318. if C.vips_cast_go(*img, &tmp, format) != 0 {
  319. return vipsError()
  320. }
  321. C.swap_and_clear(img, tmp)
  322. return nil
  323. }
  324. func vipsResize(img **C.struct__VipsImage, scale float64) error {
  325. var tmp *C.struct__VipsImage
  326. if C.vips_resize_go(*img, &tmp, C.double(scale)) != 0 {
  327. return vipsError()
  328. }
  329. C.swap_and_clear(img, tmp)
  330. return nil
  331. }
  332. func vipsRotate(img **C.struct__VipsImage, angle int) error {
  333. var tmp *C.struct__VipsImage
  334. if C.vips_rot_go(*img, &tmp, C.VipsAngle(angle)) != 0 {
  335. return vipsError()
  336. }
  337. C.swap_and_clear(img, tmp)
  338. return nil
  339. }
  340. func vipsFlip(img **C.struct__VipsImage) error {
  341. var tmp *C.struct__VipsImage
  342. if C.vips_flip_horizontal_go(*img, &tmp) != 0 {
  343. return vipsError()
  344. }
  345. C.swap_and_clear(img, tmp)
  346. return nil
  347. }
  348. func vipsCrop(img **C.struct__VipsImage, left, top, width, height int) error {
  349. var tmp *C.struct__VipsImage
  350. if C.vips_extract_area_go(*img, &tmp, C.int(left), C.int(top), C.int(width), C.int(height)) != 0 {
  351. return vipsError()
  352. }
  353. C.swap_and_clear(img, tmp)
  354. return nil
  355. }
  356. func vipsSmartCrop(img **C.struct__VipsImage, width, height int) error {
  357. var tmp *C.struct__VipsImage
  358. if C.vips_smartcrop_go(*img, &tmp, C.int(width), C.int(height)) != 0 {
  359. return vipsError()
  360. }
  361. C.swap_and_clear(img, tmp)
  362. return nil
  363. }
  364. func vipsBlur(img **C.struct__VipsImage, sigma float32) error {
  365. var tmp *C.struct__VipsImage
  366. if C.vips_gaussblur_go(*img, &tmp, C.double(sigma)) != 0 {
  367. return vipsError()
  368. }
  369. C.swap_and_clear(img, tmp)
  370. return nil
  371. }
  372. func vipsSharpen(img **C.struct__VipsImage, sigma float32) error {
  373. var tmp *C.struct__VipsImage
  374. if C.vips_sharpen_go(*img, &tmp, C.double(sigma)) != 0 {
  375. return vipsError()
  376. }
  377. C.swap_and_clear(img, tmp)
  378. return nil
  379. }
  380. func vipsImportColourProfile(img **C.struct__VipsImage) error {
  381. var tmp *C.struct__VipsImage
  382. if C.vips_need_icc_import(*img) > 0 {
  383. profile, err := cmykProfilePath()
  384. if err != nil {
  385. return err
  386. }
  387. if C.vips_icc_import_go(*img, &tmp, C.CString(profile)) != 0 {
  388. return vipsError()
  389. }
  390. C.swap_and_clear(img, tmp)
  391. }
  392. return nil
  393. }
  394. func vipsFixColourspace(img **C.struct__VipsImage) error {
  395. var tmp *C.struct__VipsImage
  396. if C.vips_image_guess_interpretation(*img) != C.VIPS_INTERPRETATION_sRGB {
  397. if C.vips_colourspace_go(*img, &tmp, C.VIPS_INTERPRETATION_sRGB) != 0 {
  398. return vipsError()
  399. }
  400. C.swap_and_clear(img, tmp)
  401. }
  402. return nil
  403. }
  404. func vipsImageCopyMemory(img **C.struct__VipsImage) error {
  405. var tmp *C.struct__VipsImage
  406. if tmp = C.vips_image_copy_memory(*img); tmp == nil {
  407. return vipsError()
  408. }
  409. C.swap_and_clear(img, tmp)
  410. return nil
  411. }
  412. func vipsError() error {
  413. return errors.New(C.GoString(C.vips_error_buffer()))
  414. }