process.go 10 KB

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