process.go 10 KB

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