Unverified Commit 44b4dbcd authored by Steven's avatar Steven Committed by GitHub

Adjust AVIF size so that its smaller than WebP size (#31494)

Generally, AVIF quality can be lower compared to WebP so we can adjust this for the user so that it looks roughly the same depending on if the browser supports AVIF or WebP.

- Fixes #31254 
- Related to https://github.com/lovell/sharp/issues/2850
parent 0cf70618
...@@ -58,7 +58,7 @@ ...@@ -58,7 +58,7 @@
"@types/http-proxy": "1.17.3", "@types/http-proxy": "1.17.3",
"@types/jest": "24.0.13", "@types/jest": "24.0.13",
"@types/selenium-webdriver": "4.0.15", "@types/selenium-webdriver": "4.0.15",
"@types/sharp": "0.28.4", "@types/sharp": "0.29.3",
"@types/string-hash": "1.1.1", "@types/string-hash": "1.1.1",
"@typescript-eslint/eslint-plugin": "4.29.1", "@typescript-eslint/eslint-plugin": "4.29.1",
"@typescript-eslint/parser": "4.29.1", "@typescript-eslint/parser": "4.29.1",
......
...@@ -363,7 +363,11 @@ export async function imageOptimizer( ...@@ -363,7 +363,11 @@ export async function imageOptimizer(
if (contentType === AVIF) { if (contentType === AVIF) {
if (transformer.avif) { if (transformer.avif) {
transformer.avif({ quality }) const avifQuality = quality - 15
transformer.avif({
quality: Math.max(avifQuality, 0),
chromaSubsampling: '4:2:0', // same as webp
})
} else { } else {
console.warn( console.warn(
chalk.yellow.bold('Warning: ') + chalk.yellow.bold('Warning: ') +
......
...@@ -118,12 +118,12 @@ export async function encodeAvif( ...@@ -118,12 +118,12 @@ export async function encodeAvif(
const e = supportedFormats['avif'] const e = supportedFormats['avif']
const m = await e.enc() const m = await e.enc()
await maybeDelay() await maybeDelay()
const val = e.autoOptimize.min const val = e.autoOptimize.min || 62
const r = await m.encode(image.data, image.width, image.height, { const r = await m.encode(image.data, image.width, image.height, {
...e.defaultEncoderOptions, ...e.defaultEncoderOptions,
// Think of cqLevel as the "amount" of quantization (0 to 62), // Think of cqLevel as the "amount" of quantization (0 to 62),
// so a lower value yields higher quality (0 to 100). // so a lower value yields higher quality (0 to 100).
cqLevel: quality === 0 ? val : Math.round(val - (quality / 100) * val), cqLevel: Math.round(val - (quality / 100) * val),
}) })
return Buffer.from(r) return Buffer.from(r)
} }
......
...@@ -65,7 +65,12 @@ export async function processBuffer( ...@@ -65,7 +65,12 @@ export async function processBuffer(
case 'webp': case 'webp':
return Buffer.from(await worker.encodeWebp(imageData, { quality })) return Buffer.from(await worker.encodeWebp(imageData, { quality }))
case 'avif': case 'avif':
return Buffer.from(await worker.encodeAvif(imageData, { quality })) const avifQuality = quality - 20
return Buffer.from(
await worker.encodeAvif(imageData, {
quality: Math.max(avifQuality, 0),
})
)
case 'png': case 'png':
return Buffer.from(await worker.encodePng(imageData)) return Buffer.from(await worker.encodePng(imageData))
default: default:
......
...@@ -48,6 +48,40 @@ async function expectWidth(res, w) { ...@@ -48,6 +48,40 @@ async function expectWidth(res, w) {
expect(d.width).toBe(w) expect(d.width).toBe(w)
} }
async function expectAvifSmallerThanWebp(w, q) {
const query = { url: '/mountains.jpg', w, q }
const res1 = await fetchViaHTTP(appPort, '/_next/image', query, {
headers: {
accept: 'image/avif',
},
})
expect(res1.status).toBe(200)
expect(res1.headers.get('Content-Type')).toBe('image/avif')
const res2 = await fetchViaHTTP(appPort, '/_next/image', query, {
headers: {
accept: 'image/webp',
},
})
expect(res2.status).toBe(200)
expect(res2.headers.get('Content-Type')).toBe('image/webp')
const res3 = await fetchViaHTTP(appPort, '/_next/image', query, {
headers: {
accept: 'image/jpeg',
},
})
expect(res3.status).toBe(200)
expect(res3.headers.get('Content-Type')).toBe('image/jpeg')
const avif = (await res1.buffer()).byteLength
const webp = (await res2.buffer()).byteLength
const jpeg = (await res3.buffer()).byteLength
expect(webp).toBeLessThan(jpeg)
expect(avif).toBeLessThanOrEqual(webp)
}
function runTests({ function runTests({
w, w,
isDev, isDev,
...@@ -410,6 +444,18 @@ function runTests({ ...@@ -410,6 +444,18 @@ function runTests({
// See https://github.com/image-size/image-size/issues/348 // See https://github.com/image-size/image-size/issues/348
//await expectWidth(res, w) //await expectWidth(res, w)
}) })
it('should compress avif smaller than webp at q=100', async () => {
await expectAvifSmallerThanWebp(w, 100)
})
it('should compress avif smaller than webp at q=75', async () => {
await expectAvifSmallerThanWebp(w, 75)
})
it('should compress avif smaller than webp at q=50', async () => {
await expectAvifSmallerThanWebp(w, 50)
})
} }
if (domains.includes('localhost')) { if (domains.includes('localhost')) {
...@@ -1205,7 +1251,7 @@ describe('Image Optimizer', () => { ...@@ -1205,7 +1251,7 @@ describe('Image Optimizer', () => {
}) })
describe('dev support with next.config.js', () => { describe('dev support with next.config.js', () => {
const size = 64 const size = 400
beforeAll(async () => { beforeAll(async () => {
const json = JSON.stringify({ const json = JSON.stringify({
images: { images: {
...@@ -1273,7 +1319,7 @@ describe('Image Optimizer', () => { ...@@ -1273,7 +1319,7 @@ describe('Image Optimizer', () => {
}) })
describe('Server support with next.config.js', () => { describe('Server support with next.config.js', () => {
const size = 128 const size = 399
beforeAll(async () => { beforeAll(async () => {
const json = JSON.stringify({ const json = JSON.stringify({
images: { images: {
......
...@@ -4829,10 +4829,10 @@ ...@@ -4829,10 +4829,10 @@
"@types/express-serve-static-core" "*" "@types/express-serve-static-core" "*"
"@types/mime" "*" "@types/mime" "*"
"@types/sharp@0.28.4": "@types/sharp@0.29.3":
version "0.28.4" version "0.29.3"
resolved "https://registry.yarnpkg.com/@types/sharp/-/sharp-0.28.4.tgz#7afdcf979069ddc68a915603fdaa412ada93f833" resolved "https://registry.yarnpkg.com/@types/sharp/-/sharp-0.29.3.tgz#54ceb81b68bb99a0e62db2b52f4fb0bea84878ac"
integrity sha512-vfz+RlJU5FgXyyf9w8wc+JwwT8MFI98NZr0272umQegrggAQhTwwb8pKZn0PTtd+j0crXkZDWw5ABG/i6Lu/Lw== integrity sha512-83Xp05eK2hvfNnmKLr2Fz0C2A0jrr2TnSLqKRbkLTYuAu+Erj6mKQLoEMGafE73Om8p3q3ryZxtHFM/7hy4Adg==
dependencies: dependencies:
"@types/node" "*" "@types/node" "*"
...@@ -8707,7 +8707,7 @@ enhanced-resolve@^4.3.0: ...@@ -8707,7 +8707,7 @@ enhanced-resolve@^4.3.0:
memory-fs "^0.5.0" memory-fs "^0.5.0"
tapable "^1.0.0" tapable "^1.0.0"
enhanced-resolve@^5.8.3, enhanced-resolve@webpack/enhanced-resolve#feature/use-cached-stat-for-read: enhanced-resolve@^5.8.3:
version "5.8.3" version "5.8.3"
resolved "https://codeload.github.com/webpack/enhanced-resolve/tar.gz/a7c161eeb141bfc7fda375df36c13df006a8cf76" resolved "https://codeload.github.com/webpack/enhanced-resolve/tar.gz/a7c161eeb141bfc7fda375df36c13df006a8cf76"
dependencies: dependencies:
...@@ -19994,11 +19994,6 @@ webpack-bundle-analyzer@4.3.0: ...@@ -19994,11 +19994,6 @@ webpack-bundle-analyzer@4.3.0:
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.2.tgz#d88e3741833efec57c4c789b6010db9977545260" resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.2.tgz#d88e3741833efec57c4c789b6010db9977545260"
integrity sha512-cp5qdmHnu5T8wRg2G3vZZHoJPN14aqQ89SyQ11NpGH5zEMDCclt49rzo+MaRazk7/UeILhAI+/sEtcM+7Fr0nw== integrity sha512-cp5qdmHnu5T8wRg2G3vZZHoJPN14aqQ89SyQ11NpGH5zEMDCclt49rzo+MaRazk7/UeILhAI+/sEtcM+7Fr0nw==
webpack-sources@^3.2.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.1.tgz#251a7d9720d75ada1469ca07dbb62f3641a05b6d"
integrity sha512-t6BMVLQ0AkjBOoRTZgqrWm7xbXMBzD+XDq2EZ96+vMfn3qKgsvdXZhbPZ4ElUOpdv4u+iiGe+w3+J75iy/bYGA==
"webpack4@npm:webpack@4.44.1": "webpack4@npm:webpack@4.44.1":
version "4.44.1" version "4.44.1"
resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.44.1.tgz#17e69fff9f321b8f117d1fda714edfc0b939cc21" resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.44.1.tgz#17e69fff9f321b8f117d1fda714edfc0b939cc21"
......
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