processing.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. package processing
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "runtime"
  8. "slices"
  9. "github.com/imgproxy/imgproxy/v3/auximageprovider"
  10. "github.com/imgproxy/imgproxy/v3/config"
  11. "github.com/imgproxy/imgproxy/v3/imagedata"
  12. "github.com/imgproxy/imgproxy/v3/imagetype"
  13. "github.com/imgproxy/imgproxy/v3/options"
  14. "github.com/imgproxy/imgproxy/v3/processing/pipeline"
  15. "github.com/imgproxy/imgproxy/v3/security"
  16. "github.com/imgproxy/imgproxy/v3/server"
  17. "github.com/imgproxy/imgproxy/v3/svg"
  18. "github.com/imgproxy/imgproxy/v3/vips"
  19. )
  20. // The main processing pipeline (without finalization).
  21. // Applied to non-animated images and individual frames of animated images.
  22. var mainPipeline = Pipeline{
  23. vectorGuardScale,
  24. trim,
  25. prepare,
  26. scaleOnLoad,
  27. colorspaceToProcessing,
  28. crop,
  29. scale,
  30. rotateAndFlip,
  31. cropToResult,
  32. applyFilters,
  33. extend,
  34. extendAspectRatio,
  35. padding,
  36. fixSize,
  37. flatten,
  38. watermark,
  39. }
  40. // The finalization pipeline.
  41. // Applied right before saving the image.
  42. var finalizePipeline = Pipeline{
  43. colorspaceToResult,
  44. stripMetadata,
  45. }
  46. func ValidatePreferredFormats() error {
  47. filtered := config.PreferredFormats[:0]
  48. for _, t := range config.PreferredFormats {
  49. if !vips.SupportsSave(t) {
  50. slog.Warn(fmt.Sprintf("%s can't be a preferred format as it's saving is not supported", t))
  51. } else {
  52. filtered = append(filtered, t)
  53. }
  54. }
  55. if len(filtered) == 0 {
  56. return errors.New("no supported preferred formats specified")
  57. }
  58. config.PreferredFormats = filtered
  59. return nil
  60. }
  61. // Result holds the result of image processing.
  62. type Result struct {
  63. OutData imagedata.ImageData
  64. OriginWidth int
  65. OriginHeight int
  66. ResultWidth int
  67. ResultHeight int
  68. }
  69. // ProcessImage processes the image according to the provided processing options
  70. // and returns a [Result] that includes the processed image data and dimensions.
  71. //
  72. // The provided processing options may be modified during processing.
  73. func ProcessImage(
  74. ctx context.Context,
  75. imgdata imagedata.ImageData,
  76. po *options.ProcessingOptions,
  77. watermarkProvider auximageprovider.Provider,
  78. ) (*Result, error) {
  79. runtime.LockOSThread()
  80. defer runtime.UnlockOSThread()
  81. defer vips.Cleanup()
  82. img := new(vips.Image)
  83. defer img.Clear()
  84. // Load a single page/frame of the image so we can analyze it
  85. // and decide how to process it further
  86. thumbnailLoaded, err := initialLoadImage(img, imgdata, po.EnforceThumbnail)
  87. if err != nil {
  88. return nil, err
  89. }
  90. // Let's check if we should skip standard processing
  91. if shouldSkipStandardProcessing(imgdata.Format(), po) {
  92. return skipStandardProcessing(img, imgdata, po)
  93. }
  94. // Check if we expect image to be processed as animated.
  95. // If MaxAnimationFrames is 1, we never process as animated since we can only
  96. // process a single frame.
  97. animated := po.SecurityOptions.MaxAnimationFrames > 1 &&
  98. img.IsAnimated()
  99. // Determine output format and check if it's supported.
  100. // The determined format is stored in po.Format.
  101. if err = determineOutputFormat(img, imgdata, po, animated); err != nil {
  102. return nil, err
  103. }
  104. // Now, as we know the output format, we know for sure if the image
  105. // should be processed as animated
  106. animated = animated && po.Format.SupportsAnimationSave()
  107. // Load required number of frames/pages for processing
  108. // and remove animation-related data if not animated.
  109. // Don't reload if we initially loaded a thumbnail.
  110. if !thumbnailLoaded {
  111. if err = reloadImageForProcessing(img, imgdata, po, animated); err != nil {
  112. return nil, err
  113. }
  114. }
  115. // Check image dimensions and number of frames for security reasons
  116. originWidth, originHeight, err := checkImageSize(img, imgdata.Format(), po.SecurityOptions)
  117. if err != nil {
  118. return nil, err
  119. }
  120. // Transform the image (resize, crop, etc)
  121. if err = transformImage(ctx, img, po, imgdata, animated, watermarkProvider); err != nil {
  122. return nil, err
  123. }
  124. // NOTE: THIS IS TEMPORARY
  125. runner, err := tmpNewRunner(watermarkProvider)
  126. if err != nil {
  127. return nil, err
  128. }
  129. // NOTE: END TEMPORARY BLOCK
  130. // Finalize the image (colorspace conversion, metadata stripping, etc)
  131. if err = runner.Run(finalizePipeline, ctx, img, po, imgdata); err != nil {
  132. return nil, err
  133. }
  134. outData, err := saveImage(ctx, img, po)
  135. if err != nil {
  136. return nil, err
  137. }
  138. resultWidth, resultHeight, _ := getImageSize(img)
  139. return &Result{
  140. OutData: outData,
  141. OriginWidth: originWidth,
  142. OriginHeight: originHeight,
  143. ResultWidth: resultWidth,
  144. ResultHeight: resultHeight,
  145. }, nil
  146. }
  147. // initialLoadImage loads a single page/frame of the image.
  148. // If the image format supports thumbnails and thumbnail loading is enforced,
  149. // it tries to load the thumbnail first.
  150. func initialLoadImage(
  151. img *vips.Image,
  152. imgdata imagedata.ImageData,
  153. enforceThumbnail bool,
  154. ) (bool, error) {
  155. if enforceThumbnail && imgdata.Format().SupportsThumbnail() {
  156. if err := img.LoadThumbnail(imgdata); err == nil {
  157. return true, nil
  158. } else {
  159. slog.Debug(fmt.Sprintf("Can't load thumbnail: %s", err))
  160. }
  161. }
  162. return false, img.Load(imgdata, 1, 1.0, 1)
  163. }
  164. // reloadImageForProcessing reloads the image for processing.
  165. // For animated images, it loads all frames up to MaxAnimationFrames.
  166. func reloadImageForProcessing(
  167. img *vips.Image,
  168. imgdata imagedata.ImageData,
  169. po *options.ProcessingOptions,
  170. asAnimated bool,
  171. ) error {
  172. // If we are going to process the image as animated, we need to load all frames
  173. // up to MaxAnimationFrames
  174. if asAnimated {
  175. frames := min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
  176. return img.Load(imgdata, 1, 1.0, frames)
  177. }
  178. // Otherwise, we just need to remove any animation-related data
  179. return img.RemoveAnimation()
  180. }
  181. // checkImageSize checks the image dimensions and number of frames against security options.
  182. // It returns the image width, height and a security check error, if any.
  183. func checkImageSize(
  184. img *vips.Image,
  185. imgtype imagetype.Type,
  186. secops security.Options,
  187. ) (int, int, error) {
  188. width, height, frames := getImageSize(img)
  189. if imgtype.IsVector() {
  190. // We don't check vector image dimensions as we can render it in any size
  191. return width, height, nil
  192. }
  193. err := secops.CheckDimensions(width, height, frames)
  194. return width, height, err
  195. }
  196. // getImageSize returns the width and height of the image, taking into account
  197. // orientation and animation.
  198. func getImageSize(img *vips.Image) (int, int, int) {
  199. width, height := img.Width(), img.Height()
  200. frames := 1
  201. if img.IsAnimated() {
  202. // Animated images contain multiple frames, and libvips loads them stacked vertically.
  203. // We want to return the size of a single frame
  204. height = img.PageHeight()
  205. frames = img.PagesLoaded()
  206. }
  207. // If the image is rotated by 90 or 270 degrees, we need to swap width and height
  208. orientation := img.Orientation()
  209. if orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8 {
  210. width, height = height, width
  211. }
  212. return width, height, frames
  213. }
  214. // Returns true if image should not be processed as usual
  215. func shouldSkipStandardProcessing(inFormat imagetype.Type, po *options.ProcessingOptions) bool {
  216. outFormat := po.Format
  217. skipProcessingFormatEnabled := slices.Contains(po.SkipProcessingFormats, inFormat)
  218. if inFormat == imagetype.SVG {
  219. isOutUnknown := outFormat == imagetype.Unknown
  220. switch {
  221. case outFormat == imagetype.SVG:
  222. return true
  223. case isOutUnknown && !config.AlwaysRasterizeSvg:
  224. return true
  225. case isOutUnknown && config.AlwaysRasterizeSvg && skipProcessingFormatEnabled:
  226. return true
  227. default:
  228. return false
  229. }
  230. } else {
  231. return skipProcessingFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
  232. }
  233. }
  234. // skipStandardProcessing skips standard image processing and returns the original image data.
  235. //
  236. // SVG images may be sanitized if configured to do so.
  237. func skipStandardProcessing(
  238. img *vips.Image,
  239. imgdata imagedata.ImageData,
  240. po *options.ProcessingOptions,
  241. ) (*Result, error) {
  242. // Even if we skip standard processing, we still need to check image dimensions
  243. // to not send an image bomb to the client
  244. originWidth, originHeight, err := checkImageSize(img, imgdata.Format(), po.SecurityOptions)
  245. if err != nil {
  246. return nil, err
  247. }
  248. // Even in this case, SVG is an exception
  249. if imgdata.Format() == imagetype.SVG && config.SanitizeSvg {
  250. sanitized, err := svg.Sanitize(imgdata)
  251. if err != nil {
  252. return nil, err
  253. }
  254. return &Result{
  255. OutData: sanitized,
  256. OriginWidth: originWidth,
  257. OriginHeight: originHeight,
  258. ResultWidth: originWidth,
  259. ResultHeight: originHeight,
  260. }, nil
  261. }
  262. // Return the original image
  263. return &Result{
  264. OutData: imgdata,
  265. OriginWidth: originWidth,
  266. OriginHeight: originHeight,
  267. ResultWidth: originWidth,
  268. ResultHeight: originHeight,
  269. }, nil
  270. }
  271. // determineOutputFormat determines the output image format based on the processing options
  272. // and image properties.
  273. //
  274. // It modifies the ProcessingOptions in place to set the output format.
  275. func determineOutputFormat(
  276. img *vips.Image,
  277. imgdata imagedata.ImageData,
  278. po *options.ProcessingOptions,
  279. animated bool,
  280. ) error {
  281. // Check if the image may have transparency
  282. expectTransparency := !po.Flatten &&
  283. (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  284. switch {
  285. case po.Format == imagetype.SVG:
  286. // At this point we can't allow requested format to be SVG as we can't save SVGs
  287. return newSaveFormatError(po.Format)
  288. case po.Format == imagetype.Unknown:
  289. switch {
  290. case po.PreferJxl && !animated:
  291. po.Format = imagetype.JXL
  292. case po.PreferAvif && !animated:
  293. po.Format = imagetype.AVIF
  294. case po.PreferWebP:
  295. po.Format = imagetype.WEBP
  296. case isImageTypePreferred(imgdata.Format()):
  297. po.Format = imgdata.Format()
  298. default:
  299. po.Format = findPreferredFormat(animated, expectTransparency)
  300. }
  301. case po.EnforceJxl && !animated:
  302. po.Format = imagetype.JXL
  303. case po.EnforceAvif && !animated:
  304. po.Format = imagetype.AVIF
  305. case po.EnforceWebP:
  306. po.Format = imagetype.WEBP
  307. }
  308. if !vips.SupportsSave(po.Format) {
  309. return newSaveFormatError(po.Format)
  310. }
  311. return nil
  312. }
  313. // isImageTypePreferred checks if the given image type is in the list of preferred formats.
  314. func isImageTypePreferred(imgtype imagetype.Type) bool {
  315. return slices.Contains(config.PreferredFormats, imgtype)
  316. }
  317. // isImageTypeCompatible checks if the given image type is compatible with the image properties.
  318. func isImageTypeCompatible(imgtype imagetype.Type, animated, expectTransparency bool) bool {
  319. if animated && !imgtype.SupportsAnimationSave() {
  320. return false
  321. }
  322. if expectTransparency && !imgtype.SupportsAlpha() {
  323. return false
  324. }
  325. return true
  326. }
  327. // findPreferredFormat finds a suitable preferred format based on image's properties.
  328. func findPreferredFormat(animated, expectTransparency bool) imagetype.Type {
  329. for _, t := range config.PreferredFormats {
  330. if isImageTypeCompatible(t, animated, expectTransparency) {
  331. return t
  332. }
  333. }
  334. return config.PreferredFormats[0]
  335. }
  336. func transformImage(
  337. ctx context.Context,
  338. img *vips.Image,
  339. po *options.ProcessingOptions,
  340. imgdata imagedata.ImageData,
  341. asAnimated bool,
  342. watermark auximageprovider.Provider,
  343. ) error {
  344. if asAnimated {
  345. return transformAnimated(ctx, img, po, watermark)
  346. }
  347. // NOTE: THIS IS TEMPORARY
  348. runner, err := tmpNewRunner(watermark)
  349. if err != nil {
  350. return err
  351. }
  352. // NOTE: END TEMPORARY BLOCK
  353. return runner.Run(mainPipeline, ctx, img, po, imgdata)
  354. }
  355. func transformAnimated(
  356. ctx context.Context,
  357. img *vips.Image,
  358. po *options.ProcessingOptions,
  359. watermark auximageprovider.Provider,
  360. ) error {
  361. // NOTE: THIS IS TEMPORARY
  362. runner, rerr := tmpNewRunner(watermark)
  363. if rerr != nil {
  364. return rerr
  365. }
  366. // NOTE: END TEMPORARY BLOCK
  367. if po.Trim.Enabled {
  368. slog.Warn("Trim is not supported for animated images")
  369. po.Trim.Enabled = false
  370. }
  371. imgWidth := img.Width()
  372. frameHeight := img.PageHeight()
  373. framesCount := img.PagesLoaded()
  374. // Get frame delays. We'll need to set them back later.
  375. // If we don't have delay info, we'll set a default delay later.
  376. delay, err := img.GetIntSliceDefault("delay", nil)
  377. if err != nil {
  378. return err
  379. }
  380. // Get loop count. We'll need to set it back later.
  381. // 0 means infinite looping.
  382. loop, err := img.GetIntDefault("loop", 0)
  383. if err != nil {
  384. return err
  385. }
  386. // Disable watermarking for individual frames.
  387. // It's more efficient to apply watermark to all frames at once after they are processed.
  388. watermarkEnabled := po.Watermark.Enabled
  389. po.Watermark.Enabled = false
  390. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  391. // Make a slice to hold processed frames and ensure they are cleared on function exit
  392. frames := make([]*vips.Image, 0, framesCount)
  393. defer func() {
  394. for _, frame := range frames {
  395. if frame != nil {
  396. frame.Clear()
  397. }
  398. }
  399. }()
  400. for i := 0; i < framesCount; i++ {
  401. frame := new(vips.Image)
  402. // Extract an individual frame from the image.
  403. // Libvips loads animated images as a single image with frames stacked vertically.
  404. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  405. return err
  406. }
  407. frames = append(frames, frame)
  408. // Transform the frame using the main pipeline.
  409. // We don't provide imgdata here to prevent scale-on-load.
  410. // Watermarking is disabled for individual frames (see above)
  411. if err = runner.Run(mainPipeline, ctx, frame, po, nil); err != nil {
  412. return err
  413. }
  414. // If the frame was scaled down, it's better to copy it to RAM
  415. // to speed up further processing.
  416. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  417. if err = frame.CopyMemory(); err != nil {
  418. return err
  419. }
  420. if err = server.CheckTimeout(ctx); err != nil {
  421. return err
  422. }
  423. }
  424. }
  425. // Join processed frames back into a single image.
  426. if err = img.Arrayjoin(frames); err != nil {
  427. return err
  428. }
  429. // Apply watermark to all frames at once if it was requested.
  430. // This is much more efficient than applying watermark to individual frames.
  431. if watermarkEnabled && watermark != nil {
  432. // Get DPR scale to apply watermark correctly on HiDPI images.
  433. // `imgproxy-dpr-scale` is set by the pipeline.
  434. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  435. if derr != nil {
  436. dprScale = 1.0
  437. }
  438. if err = applyWatermark(ctx, runner, img, watermark, po, dprScale, framesCount); err != nil {
  439. return err
  440. }
  441. }
  442. if len(delay) == 0 {
  443. // if we don't have delay info, set it to 40ms for each frame (25 FPS).
  444. delay = make([]int, framesCount)
  445. for i := range delay {
  446. delay[i] = 40
  447. }
  448. } else if len(delay) > framesCount {
  449. // if we have more delay entries than frames, truncate it.
  450. delay = delay[:framesCount]
  451. }
  452. // Mark the image as animated so img.Strip() doesn't remove animation data.
  453. img.SetInt("imgproxy-is-animated", 1)
  454. // Set animation data back.
  455. img.SetInt("page-height", frames[0].Height())
  456. img.SetIntSlice("delay", delay)
  457. img.SetInt("loop", loop)
  458. img.SetInt("n-pages", img.Height()/frames[0].Height())
  459. return nil
  460. }
  461. func saveImage(
  462. ctx context.Context,
  463. img *vips.Image,
  464. po *options.ProcessingOptions,
  465. ) (imagedata.ImageData, error) {
  466. // AVIF has a minimal dimension of 16 pixels.
  467. // If one of the dimensions is less, we need to switch to another format.
  468. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  469. if img.HasAlpha() {
  470. po.Format = imagetype.PNG
  471. } else {
  472. po.Format = imagetype.JPEG
  473. }
  474. slog.Warn(fmt.Sprintf(
  475. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  476. img.Width(), img.Height(), po.Format,
  477. ))
  478. }
  479. // If we want and can fit the image into the specified number of bytes,
  480. // let's do it.
  481. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  482. return saveImageToFitBytes(ctx, po, img)
  483. }
  484. // Otherwise, just save the image with the specified quality.
  485. return img.Save(po.Format, po.GetQuality())
  486. }
  487. func tmpNewRunner(watermarkProvider auximageprovider.Provider) (*Runner, error) {
  488. // NOTE: THIS IS TEMPORARY
  489. config, err := pipeline.LoadConfigFromEnv(nil)
  490. if err != nil {
  491. return nil, err
  492. }
  493. runner := New(config, watermarkProvider)
  494. return runner, nil
  495. // NOTE: END TEMPORARY BLOCK
  496. }