process.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package main
  2. import (
  3. "context"
  4. "math"
  5. "runtime"
  6. "golang.org/x/sync/errgroup"
  7. )
  8. const msgSmartCropNotSupported = "Smart crop is not supported by used version of libvips"
  9. func extractMeta(img *vipsImage) (int, int, int, bool) {
  10. width := img.Width()
  11. height := img.Height()
  12. angle := vipsAngleD0
  13. flip := false
  14. orientation := img.Orientation()
  15. if orientation >= 5 && orientation <= 8 {
  16. width, height = height, width
  17. }
  18. if orientation == 3 || orientation == 4 {
  19. angle = vipsAngleD180
  20. }
  21. if orientation == 5 || orientation == 6 {
  22. angle = vipsAngleD90
  23. }
  24. if orientation == 7 || orientation == 8 {
  25. angle = vipsAngleD270
  26. }
  27. if orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7 {
  28. flip = true
  29. }
  30. return width, height, angle, flip
  31. }
  32. func calcScale(width, height int, po *processingOptions, imgtype imageType) float64 {
  33. var scale float64
  34. srcW, srcH := float64(width), float64(height)
  35. if (po.Width == 0 || po.Width == width) && (po.Height == 0 || po.Height == height) {
  36. scale = 1
  37. } else {
  38. wr := float64(po.Width) / srcW
  39. hr := float64(po.Height) / srcH
  40. rt := po.Resize
  41. if rt == resizeAuto {
  42. srcD := width - height
  43. dstD := po.Width - po.Height
  44. if (srcD >= 0 && dstD >= 0) || (srcD < 0 && dstD < 0) {
  45. rt = resizeFill
  46. } else {
  47. rt = resizeFit
  48. }
  49. }
  50. if po.Width == 0 {
  51. scale = hr
  52. } else if po.Height == 0 {
  53. scale = wr
  54. } else if rt == resizeFit {
  55. scale = math.Min(wr, hr)
  56. } else {
  57. scale = math.Max(wr, hr)
  58. }
  59. }
  60. scale = scale * po.Dpr
  61. if !po.Enlarge && scale > 1 && imgtype != imageTypeSVG {
  62. return 1
  63. }
  64. if srcW*scale < 1 {
  65. scale = 1 / srcW
  66. }
  67. if srcH*scale < 1 {
  68. scale = 1 / srcH
  69. }
  70. return scale
  71. }
  72. func canScaleOnLoad(imgtype imageType, scale float64) bool {
  73. if imgtype == imageTypeSVG {
  74. return true
  75. }
  76. if conf.DisableShrinkOnLoad || scale >= 1 {
  77. return false
  78. }
  79. return imgtype == imageTypeJPEG || imgtype == imageTypeWEBP
  80. }
  81. func calcJpegShink(scale float64, imgtype imageType) int {
  82. shrink := int(1.0 / scale)
  83. switch {
  84. case shrink >= 8:
  85. return 8
  86. case shrink >= 4:
  87. return 4
  88. case shrink >= 2:
  89. return 2
  90. }
  91. return 1
  92. }
  93. func calcCrop(width, height, cropWidth, cropHeight int, gravity *gravityOptions) (left, top int) {
  94. if gravity.Type == gravityFocusPoint {
  95. pointX := int(float64(width) * gravity.X)
  96. pointY := int(float64(height) * gravity.Y)
  97. left = maxInt(0, minInt(pointX-cropWidth/2, width-cropWidth))
  98. top = maxInt(0, minInt(pointY-cropHeight/2, height-cropHeight))
  99. return
  100. }
  101. offX, offY := int(gravity.X), int(gravity.Y)
  102. left = (width-cropWidth+1)/2 + offX
  103. top = (height-cropHeight+1)/2 + offY
  104. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  105. top = 0 + offY
  106. }
  107. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  108. left = width - cropWidth - offX
  109. }
  110. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  111. top = height - cropHeight - offY
  112. }
  113. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  114. left = 0 + offX
  115. }
  116. left = maxInt(0, minInt(left, width-cropWidth))
  117. top = maxInt(0, minInt(top, height-cropHeight))
  118. return
  119. }
  120. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  121. if cropWidth == 0 && cropHeight == 0 {
  122. return nil
  123. }
  124. imgWidth, imgHeight := img.Width(), img.Height()
  125. if cropWidth == 0 {
  126. cropWidth = imgWidth
  127. } else {
  128. cropWidth = minInt(cropWidth, imgWidth)
  129. }
  130. if cropHeight == 0 {
  131. cropHeight = imgHeight
  132. } else {
  133. cropHeight = minInt(cropHeight, imgHeight)
  134. }
  135. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  136. return nil
  137. }
  138. if gravity.Type == gravitySmart {
  139. if err := img.CopyMemory(); err != nil {
  140. return err
  141. }
  142. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  143. return err
  144. }
  145. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  146. // so we have to copy memory after it
  147. return img.CopyMemory()
  148. }
  149. left, top := calcCrop(imgWidth, imgHeight, cropWidth, cropHeight, gravity)
  150. return img.Crop(left, top, cropWidth, cropHeight)
  151. }
  152. func scaleSize(size int, scale float64) int {
  153. if size == 0 {
  154. return 0
  155. }
  156. return roundToInt(float64(size) * scale)
  157. }
  158. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  159. var err error
  160. srcWidth, srcHeight, angle, flip := extractMeta(img)
  161. cropWidth, cropHeight := po.Crop.Width, po.Crop.Height
  162. cropGravity := po.Crop.Gravity
  163. if cropGravity.Type == gravityUnknown {
  164. cropGravity = po.Gravity
  165. }
  166. widthToScale, heightToScale := srcWidth, srcHeight
  167. if cropWidth > 0 {
  168. widthToScale = minInt(cropWidth, srcWidth)
  169. }
  170. if cropHeight > 0 {
  171. heightToScale = minInt(cropHeight, srcHeight)
  172. }
  173. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  174. cropWidth = scaleSize(cropWidth, scale)
  175. cropHeight = scaleSize(cropHeight, scale)
  176. cropGravity.X = cropGravity.X * scale
  177. cropGravity.Y = cropGravity.Y * scale
  178. if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  179. if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
  180. // Do some scale-on-load
  181. if err := img.Load(data, imgtype, 1, scale, 1); err != nil {
  182. return err
  183. }
  184. } else if imgtype == imageTypeJPEG {
  185. // Do some shrink-on-load
  186. if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
  187. if err := img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
  188. return err
  189. }
  190. }
  191. }
  192. // Update scale after scale-on-load
  193. newWidth, newHeight, _, _ := extractMeta(img)
  194. widthToScale = scaleSize(widthToScale, float64(newWidth)/float64(srcWidth))
  195. heightToScale = scaleSize(heightToScale, float64(newHeight)/float64(srcHeight))
  196. scale = calcScale(widthToScale, heightToScale, po, imgtype)
  197. }
  198. if err = img.Rad2Float(); err != nil {
  199. return err
  200. }
  201. convertToLinear := conf.UseLinearColorspace && (scale != 1 || po.Dpr != 1)
  202. if convertToLinear {
  203. if err = img.ImportColourProfile(true); err != nil {
  204. return err
  205. }
  206. if err = img.LinearColourspace(); err != nil {
  207. return err
  208. }
  209. }
  210. hasAlpha := img.HasAlpha()
  211. if scale != 1 {
  212. if err = img.Resize(scale, hasAlpha); err != nil {
  213. return err
  214. }
  215. }
  216. checkTimeout(ctx)
  217. if angle != vipsAngleD0 || flip {
  218. if err = img.CopyMemory(); err != nil {
  219. return err
  220. }
  221. if angle != vipsAngleD0 {
  222. if err = img.Rotate(angle); err != nil {
  223. return err
  224. }
  225. }
  226. if flip {
  227. if err = img.Flip(); err != nil {
  228. return err
  229. }
  230. }
  231. }
  232. checkTimeout(ctx)
  233. dprWidth := roundToInt(float64(po.Width) * po.Dpr)
  234. dprHeight := roundToInt(float64(po.Height) * po.Dpr)
  235. if cropGravity.Type == po.Gravity.Type && cropGravity.Type != gravityFocusPoint {
  236. if cropWidth == 0 {
  237. cropWidth = dprWidth
  238. } else if dprWidth > 0 {
  239. cropWidth = minInt(cropWidth, dprWidth)
  240. }
  241. if cropHeight == 0 {
  242. cropHeight = dprHeight
  243. } else if dprHeight > 0 {
  244. cropHeight = minInt(cropHeight, dprHeight)
  245. }
  246. sumGravity := gravityOptions{
  247. Type: cropGravity.Type,
  248. X: cropGravity.X + po.Gravity.X,
  249. Y: cropGravity.Y + po.Gravity.Y,
  250. }
  251. if err = cropImage(img, cropWidth, cropHeight, &sumGravity); err != nil {
  252. return err
  253. }
  254. } else {
  255. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  256. return err
  257. }
  258. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  259. return err
  260. }
  261. }
  262. checkTimeout(ctx)
  263. if convertToLinear {
  264. if err = img.RgbColourspace(); err != nil {
  265. return err
  266. }
  267. } else {
  268. if err = img.ImportColourProfile(false); err != nil {
  269. return err
  270. }
  271. }
  272. if hasAlpha && (po.Flatten || po.Format == imageTypeJPEG) {
  273. if err = img.Flatten(po.Background); err != nil {
  274. return err
  275. }
  276. }
  277. if po.Blur > 0 {
  278. if err = img.Blur(po.Blur); err != nil {
  279. return err
  280. }
  281. }
  282. if po.Sharpen > 0 {
  283. if err = img.Sharpen(po.Sharpen); err != nil {
  284. return err
  285. }
  286. }
  287. if po.Extend && (po.Width > img.Width() || po.Height > img.Height()) {
  288. if err = img.Embed(gravityCenter, po.Width, po.Height, 0, 0, po.Background); err != nil {
  289. return err
  290. }
  291. }
  292. checkTimeout(ctx)
  293. if po.Watermark.Enabled {
  294. if err = img.ApplyWatermark(&po.Watermark); err != nil {
  295. return err
  296. }
  297. }
  298. return img.RgbColourspace()
  299. }
  300. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  301. imgWidth := img.Width()
  302. frameHeight, err := img.GetInt("page-height")
  303. if err != nil {
  304. return err
  305. }
  306. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  307. // Double check dimensions because animated image has many frames
  308. if err := checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  309. return err
  310. }
  311. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  312. if nPages, _ := img.GetInt("n-pages"); nPages > 0 {
  313. scale := 1.0
  314. // Don't do scale on load if we need to crop
  315. if po.Crop.Width == 0 && po.Crop.Height == 0 {
  316. scale = calcScale(imgWidth, frameHeight, po, imgtype)
  317. }
  318. if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
  319. logNotice("Animated scale on load")
  320. // Do some scale-on-load and load only the needed frames
  321. if err := img.Load(data, imgtype, 1, scale, framesCount); err != nil {
  322. return err
  323. }
  324. }
  325. imgWidth = img.Width()
  326. frameHeight, err = img.GetInt("page-height")
  327. if err != nil {
  328. return err
  329. }
  330. }
  331. delay, err := img.GetInt("gif-delay")
  332. if err != nil {
  333. return err
  334. }
  335. loop, err := img.GetInt("gif-loop")
  336. if err != nil {
  337. return err
  338. }
  339. frames := make([]*vipsImage, framesCount)
  340. defer func() {
  341. for _, frame := range frames {
  342. frame.Clear()
  343. }
  344. }()
  345. var errg errgroup.Group
  346. for i := 0; i < framesCount; i++ {
  347. ind := i
  348. errg.Go(func() error {
  349. frame := new(vipsImage)
  350. if err := img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
  351. return err
  352. }
  353. if err := transformImage(ctx, frame, nil, po, imgtype); err != nil {
  354. return err
  355. }
  356. frames[ind] = frame
  357. return nil
  358. })
  359. }
  360. if err := errg.Wait(); err != nil {
  361. return err
  362. }
  363. checkTimeout(ctx)
  364. if err := img.Arrayjoin(frames); err != nil {
  365. return err
  366. }
  367. img.SetInt("page-height", frames[0].Height())
  368. img.SetInt("gif-delay", delay)
  369. img.SetInt("gif-loop", loop)
  370. img.SetInt("n-pages", framesCount)
  371. return nil
  372. }
  373. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  374. runtime.LockOSThread()
  375. defer runtime.UnlockOSThread()
  376. if newRelicEnabled {
  377. newRelicCancel := startNewRelicSegment(ctx, "Processing image")
  378. defer newRelicCancel()
  379. }
  380. if prometheusEnabled {
  381. defer startPrometheusDuration(prometheusProcessingDuration)()
  382. }
  383. defer vipsCleanup()
  384. po := getProcessingOptions(ctx)
  385. data := getImageData(ctx).Bytes()
  386. imgtype := getImageType(ctx)
  387. if po.Format == imageTypeUnknown {
  388. if po.PreferWebP && vipsTypeSupportSave[imageTypeWEBP] {
  389. po.Format = imageTypeWEBP
  390. } else if vipsTypeSupportSave[imgtype] && imgtype != imageTypeHEIC {
  391. po.Format = imgtype
  392. } else {
  393. po.Format = imageTypeJPEG
  394. }
  395. } else if po.EnforceWebP && vipsTypeSupportSave[imageTypeWEBP] {
  396. po.Format = imageTypeWEBP
  397. }
  398. if !vipsSupportSmartcrop {
  399. if po.Gravity.Type == gravitySmart {
  400. logWarning(msgSmartCropNotSupported)
  401. po.Gravity.Type = gravityCenter
  402. }
  403. if po.Crop.Gravity.Type == gravitySmart {
  404. logWarning(msgSmartCropNotSupported)
  405. po.Crop.Gravity.Type = gravityCenter
  406. }
  407. }
  408. if po.Resize == resizeCrop {
  409. logWarning("`crop` resizing type is deprecated and will be removed in future versions. Use `crop` processing option instead")
  410. po.Crop.Width, po.Crop.Height = po.Width, po.Height
  411. po.Resize = resizeFit
  412. po.Width, po.Height = 0, 0
  413. }
  414. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgtype) && vipsSupportAnimation(po.Format)
  415. pages := 1
  416. if animationSupport {
  417. pages = -1
  418. }
  419. img := new(vipsImage)
  420. defer img.Clear()
  421. if err := img.Load(data, imgtype, 1, 1.0, pages); err != nil {
  422. return nil, func() {}, err
  423. }
  424. if animationSupport && img.IsAnimated() {
  425. if err := transformAnimated(ctx, img, data, po, imgtype); err != nil {
  426. return nil, func() {}, err
  427. }
  428. } else {
  429. if err := transformImage(ctx, img, data, po, imgtype); err != nil {
  430. return nil, func() {}, err
  431. }
  432. }
  433. checkTimeout(ctx)
  434. if po.Format == imageTypeGIF {
  435. if err := img.CastUchar(); err != nil {
  436. return nil, func() {}, err
  437. }
  438. checkTimeout(ctx)
  439. }
  440. return img.Save(po.Format, po.Quality)
  441. }