Unverified Commit 409772ec authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[15.5.x] [next/image]: disable avif image optimization

https://github.com/vercel/next-js-mirror/pull/165
parent 9c44b882
...@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer' ...@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer'
const BLUR_IMG_SIZE = 8 const BLUR_IMG_SIZE = 8
const BLUR_QUALITY = 70 const BLUR_QUALITY = 70
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match other usages const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match other usages
export async function getBlurImage( export async function getBlurImage(
content: Buffer, content: Buffer,
......
...@@ -683,6 +683,7 @@ export default function Image({ ...@@ -683,6 +683,7 @@ export default function Image({
} }
let staticSrc = '' let staticSrc = ''
let isStaticAvif = false
if (isStaticImport(src)) { if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src const staticImageData = isStaticRequire(src) ? src.default : src
...@@ -695,6 +696,7 @@ export default function Image({ ...@@ -695,6 +696,7 @@ export default function Image({
} }
blurDataURL = blurDataURL || staticImageData.blurDataURL blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!layout || layout !== 'fill') { if (!layout || layout !== 'fill') {
height = height || staticImageData.height height = height || staticImageData.height
width = width || staticImageData.width width = width || staticImageData.width
...@@ -709,6 +711,12 @@ export default function Image({ ...@@ -709,6 +711,12 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
if (src.startsWith('data:') || src.startsWith('blob:')) { if (src.startsWith('data:') || src.startsWith('blob:')) {
...@@ -839,7 +847,7 @@ export default function Image({ ...@@ -839,7 +847,7 @@ export default function Image({
) )
} }
if (!blurDataURL) { if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
...@@ -50,7 +50,7 @@ const BMP = 'image/bmp' ...@@ -50,7 +50,7 @@ const BMP = 'image/bmp'
const PDF = 'application/pdf' const PDF = 'application/pdf'
const CACHE_VERSION = 4 const CACHE_VERSION = 4
const ANIMATABLE_TYPES = [WEBP, PNG, GIF] const ANIMATABLE_TYPES = [WEBP, PNG, GIF]
const BYPASS_TYPES = [SVG, ICO, ICNS, BMP, JXL, HEIC] const BYPASS_TYPES = [SVG, ICO, ICNS, BMP, JXL, HEIC, AVIF]
const BLUR_IMG_SIZE = 8 // should match `next-image-loader` const BLUR_IMG_SIZE = 8 // should match `next-image-loader`
const BLUR_QUALITY = 70 // should match `next-image-loader` const BLUR_QUALITY = 70 // should match `next-image-loader`
...@@ -92,6 +92,17 @@ export function getSharp(concurrency: number | null | undefined) { ...@@ -92,6 +92,17 @@ export function getSharp(concurrency: number | null | undefined) {
try { try {
// eslint-disable-next-line @next/internal/typechecked-require -- sharp 0.34 and 0.35 type the module differently, see SharpModule // eslint-disable-next-line @next/internal/typechecked-require -- sharp 0.34 and 0.35 type the module differently, see SharpModule
_sharp = require('sharp') as SharpModule _sharp = require('sharp') as SharpModule
_sharp.block({ operation: ['VipsForeignLoad'] })
_sharp.unblock({
operation: [
'VipsForeignLoadJpeg',
'VipsForeignLoadNsgif',
'VipsForeignLoadPng',
'VipsForeignLoadSvg',
'VipsForeignLoadTiff',
'VipsForeignLoadWebp',
],
})
if (_sharp && _sharp.concurrency() > 1) { if (_sharp && _sharp.concurrency() > 1) {
// Reducing concurrency should reduce the memory usage too. // Reducing concurrency should reduce the memory usage too.
// We more aggressively reduce in dev but also reduce in prod. // We more aggressively reduce in dev but also reduce in prod.
......
...@@ -369,6 +369,7 @@ export function getImgProps( ...@@ -369,6 +369,7 @@ export function getImgProps(
let heightInt = getInt(height) let heightInt = getInt(height)
let blurWidth: number | undefined let blurWidth: number | undefined
let blurHeight: number | undefined let blurHeight: number | undefined
let isStaticAvif = false
if (isStaticImport(src)) { if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src const staticImageData = isStaticRequire(src) ? src.default : src
...@@ -391,6 +392,7 @@ export function getImgProps( ...@@ -391,6 +392,7 @@ export function getImgProps(
blurHeight = staticImageData.blurHeight blurHeight = staticImageData.blurHeight
blurDataURL = blurDataURL || staticImageData.blurDataURL blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!fill) { if (!fill) {
if (!widthInt && !heightInt) { if (!widthInt && !heightInt) {
...@@ -407,6 +409,12 @@ export function getImgProps( ...@@ -407,6 +409,12 @@ export function getImgProps(
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
if (!src || src.startsWith('data:') || src.startsWith('blob:')) { if (!src || src.startsWith('data:') || src.startsWith('blob:')) {
...@@ -551,7 +559,7 @@ export function getImgProps( ...@@ -551,7 +559,7 @@ export function getImgProps(
) )
} }
if (placeholder === 'blur' && !blurDataURL) { if (placeholder === 'blur' && !blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader
throw new Error( throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property. `Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
import fs from 'fs-extra'
import { join } from 'path'
import { optimizeImage } from 'next/dist/server/image-optimizer'
describe('with latest sharp', () => {
it('should block avif decoding below the optimizer bypass', async () => {
const buffer = await fs.readFile(join(__dirname, 'app/public/test.avif'))
await expect(
optimizeImage({
buffer,
contentType: 'image/webp',
quality: 75,
width: 100,
})
).rejects.toThrow()
})
})
...@@ -100,6 +100,15 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) { ...@@ -100,6 +100,15 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) {
expect(isAnimated(buffer)).toBe(expectAnimated) expect(isAnimated(buffer)).toBe(expectAnimated)
} }
async function expectUnoptimizedImage(res, filename: string) {
const buffer = Buffer.from(await res.arrayBuffer())
const source = await fs.readFile(join(__dirname, '../app/public', filename))
expect(buffer).toEqual(source)
expect(res.headers.get('Content-Length')).toBe(
Buffer.byteLength(source).toString()
)
}
export const cleanImagesDir = async (ctx: { imagesDir: string }) => { export const cleanImagesDir = async (ctx: { imagesDir: string }) => {
console.warn('Cleaning', ctx.imagesDir) console.warn('Cleaning', ctx.imagesDir)
await fs.remove(ctx.imagesDir) await fs.remove(ctx.imagesDir)
...@@ -523,23 +532,23 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -523,23 +532,23 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should downlevel avif format to jpeg for old Safari', async () => { it('should bypass avif input for old Safari', async () => {
const accept = const accept =
'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5' 'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5'
const query = { w: ctx.w, q: 74, url: '/test.avif' } const query = { w: ctx.w, q: 74, url: '/test.avif' }
const opts = { headers: { accept } } const opts = { headers: { accept } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('image/jpeg') expect(res.headers.get('Content-Type')).toContain('image/avif')
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate` `public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
) )
expect(res.headers.get('Vary')).toBe('Accept') expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.jpeg"` `${contentDispositionType}; filename="test.avif"`
) )
await expectWidth(res, ctx.w) await expectUnoptimizedImage(res, 'test.avif')
}) })
it('should fail when url is missing', async () => { it('should fail when url is missing', async () => {
...@@ -805,21 +814,21 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -805,21 +814,21 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should resize avif', async () => { it('should bypass optimization for avif input', async () => {
const query = { url: '/test.avif', w: ctx.w, q: 75 } const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } } const opts = { headers: { accept: 'image/webp' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/webp') expect(res.headers.get('Content-Type')).toBe('image/avif')
expect(res.headers.get('Cache-Control')).toBe( expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate` `public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
) )
expect(res.headers.get('Vary')).toBe('Accept') expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy() expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.webp"` `${contentDispositionType}; filename="test.avif"`
) )
await expectWidth(res, ctx.w) await expectUnoptimizedImage(res, 'test.avif')
}) })
it('should resize relative url and old Chrome accept header as webp', async () => { it('should resize relative url and old Chrome accept header as webp', async () => {
...@@ -863,8 +872,8 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -863,8 +872,8 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w) await expectWidth(res, ctx.w)
}) })
it('should resize avif and maintain format', async () => { it('should bypass avif input when avif output is enabled', async () => {
const query = { url: '/test.avif', w: ctx.w, q: 75 } const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/avif' } } const opts = { headers: { accept: 'image/avif' } }
const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts) const res = await fetchViaHTTP(ctx.appPort, '/_next/image', query, opts)
expect(res.status).toBe(200) expect(res.status).toBe(200)
...@@ -877,7 +886,7 @@ export function runTests(ctx: RunTestsCtx) { ...@@ -877,7 +886,7 @@ export function runTests(ctx: RunTestsCtx) {
expect(res.headers.get('Content-Disposition')).toBe( expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"` `${contentDispositionType}; filename="test.avif"`
) )
await expectWidth(res, ctx.w) await expectUnoptimizedImage(res, 'test.avif')
}) })
it('should compress avif smaller than webp at q=100', async () => { it('should compress avif smaller than webp at q=100', async () => {
......
...@@ -61,6 +61,36 @@ describe('getImageProps()', () => { ...@@ -61,6 +61,36 @@ describe('getImageProps()', () => {
expect(props.srcSet).toBeString() expect(props.srcSet).toBeString()
}) })
it('should disable an automatic blur placeholder for a static avif', () => {
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
})
expect(props.style).toStrictEqual({ color: 'transparent' })
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
})
expect(props.style?.backgroundImage).toContain(blurDataURL)
})
it('should handle priority', async () => { it('should handle priority', async () => {
const { props } = getImageProps({ const { props } = getImageProps({
alt: 'a nice desc', alt: 'a nice desc',
......
...@@ -80,6 +80,40 @@ describe('Image Legacy Rendering', () => { ...@@ -80,6 +80,40 @@ describe('Image Legacy Rendering', () => {
expect($3('noscript').length).toBe(1) expect($3('noscript').length).toBe(1)
}) })
it('should disable an automatic blur placeholder for a static avif', () => {
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(0)
expect($.html()).not.toContain('background-image')
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(1)
expect($.html()).toContain(blurDataURL)
})
it('should render the correct sizes passed when a noscript element is rendered', async () => { it('should render the correct sizes passed when a noscript element is rendered', async () => {
const element = React.createElement(Image, { const element = React.createElement(Image, {
src: '/test.png', src: '/test.png',
......
...@@ -35,4 +35,22 @@ describe('getBlurImage', () => { ...@@ -35,4 +35,22 @@ describe('getBlurImage', () => {
expect(result).toBeObject() expect(result).toBeObject()
expect(result.dataURL).toBeUndefined() expect(result.dataURL).toBeUndefined()
}) })
it('should not generate a blur placeholder for avif', async () => {
const buffer = await getImage('../image-optimizer/images/test.avif')
const result = await getBlurImage(
buffer,
'avif',
{ width: 400, height: 400 },
{
...context,
outputPath: '/_next/static/media/test.avif',
}
)
expect(result).toBeObject()
expect(result).toStrictEqual({
dataURL: undefined,
width: 0,
height: 0,
})
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment