Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F85950019
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Flag For Later
Award Token
Authored By
Unknown
Size
10 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/changelog.d/animated-webp-upload.fix b/changelog.d/animated-webp-upload.fix
new file mode 100644
index 0000000000..c5306a3484
--- /dev/null
+++ b/changelog.d/animated-webp-upload.fix
@@ -0,0 +1 @@
+Animated WebP and AVIF pictures keep their animation when image compression is on
diff --git a/src/components/media_upload/media_upload.js b/src/components/media_upload/media_upload.js
index 4e11f5540e..bf29cf6d0c 100644
--- a/src/components/media_upload/media_upload.js
+++ b/src/components/media_upload/media_upload.js
@@ -1,197 +1,179 @@
import fileSizeFormatService from '../../services/file_size_format/file_size_format.js'
import statusPosterService from '../../services/status_poster/status_poster.service.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useMergedConfigStore } from 'src/stores/merged_config.js'
+import { isAnimated } from 'src/services/animated_image/animated_image.js'
+
import { library } from '@fortawesome/fontawesome-svg-core'
import { faCircleNotch, faUpload } from '@fortawesome/free-solid-svg-icons'
library.add(faUpload, faCircleNotch)
const mediaUpload = {
data() {
return {
uploadCount: 0,
uploadReady: true,
}
},
computed: {
uploading() {
return this.uploadCount > 0
},
},
methods: {
onClick() {
if (this.uploadReady) {
this.$refs.input.click()
}
},
async resizeImage(file) {
// Skip if not an image or if it's a GIF
if (!file.type.startsWith('image/') || file.type === 'image/gif') {
return file
}
// Skip if image compression is disabled
if (!useMergedConfigStore().mergedConfig.imageCompression) {
return file
}
- // For PNGs, check if animated
- if (file.type === 'image/png') {
- const isAnimated = await this.isAnimatedPng(file)
- if (isAnimated) {
- return file
- }
+ // Animated pictures would lose their animation on the canvas
+ if (await isAnimated(file)) {
+ return file
}
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
// Calculate new dimensions
let width = img.width
let height = img.height
const maxSize = 2048
if (width > maxSize || height > maxSize) {
if (width > height) {
height = Math.round((height * maxSize) / width)
width = maxSize
} else {
width = Math.round((width * maxSize) / height)
height = maxSize
}
}
// Create canvas and resize
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
// Check WebP support by trying to create a WebP canvas
const testCanvas = document.createElement('canvas')
const supportsWebP = testCanvas
.toDataURL('image/webp')
.startsWith('data:image/webp')
// Convert to WebP if supported and alwaysUseJpeg is false, otherwise JPEG
const type =
!useMergedConfigStore().mergedConfig.alwaysUseJpeg && supportsWebP
? 'image/webp'
: 'image/jpeg'
const extension = type === 'image/webp' ? '.webp' : '.jpg'
// Remove the original extension and add new one
const newFileName = file.name.replace(/\.[^/.]+$/, '') + extension
canvas.toBlob(
(blob) => {
resolve(
new File([blob], newFileName, {
type,
lastModified: Date.now(),
}),
)
},
type,
0.85,
)
}
img.src = URL.createObjectURL(file)
})
},
- async isAnimatedPng(file) {
- const buffer = await file.arrayBuffer()
- const view = new Uint8Array(buffer)
- // Look for animated PNG chunks (acTL)
- for (let i = 0; i < view.length - 8; i++) {
- if (
- view[i] === 0x61 && // a
- view[i + 1] === 0x63 && // c
- view[i + 2] === 0x54 && // T
- view[i + 3] === 0x4c
- ) {
- // L
- return true
- }
- }
- return false
- },
async uploadFile(file) {
if (file.size > useInstanceStore().uploadlimit) {
const filesize = fileSizeFormatService.fileSizeFormat(file.size)
const allowedsize = fileSizeFormatService.fileSizeFormat(
useInstanceStore().uploadlimit,
)
this.$emit('upload-failed', 'file_too_big', {
filesize: filesize.num,
filesizeunit: filesize.unit,
allowedsize: allowedsize.num,
allowedsizeunit: allowedsize.unit,
})
return
}
// Resize image if needed
const processedFile = await this.resizeImage(file)
const formData = new FormData()
formData.append('file', processedFile)
this.$emit('uploading')
this.uploadCount++
statusPosterService.uploadMedia({ formData }).then(
(fileData) => {
this.$emit('uploaded', fileData)
this.decreaseUploadCount()
},
(error) => {
console.error('Error uploading file', error)
this.$emit('upload-failed', 'default')
this.decreaseUploadCount()
},
)
},
decreaseUploadCount() {
this.uploadCount--
if (this.uploadCount === 0) {
this.$emit('all-uploaded')
}
},
clearFile() {
this.uploadReady = false
this.$nextTick(() => {
this.uploadReady = true
})
},
multiUpload(files) {
for (const file of files) {
this.uploadFile(file)
}
},
change({ target }) {
this.multiUpload(target.files)
},
},
props: {
dropFiles: Object,
disabled: Boolean,
normalButton: Boolean,
acceptTypes: {
type: String,
default: '*/*',
},
},
watch: {
dropFiles: function (fileInfos) {
if (!this.uploading) {
this.multiUpload(fileInfos)
}
},
},
}
export default mediaUpload
diff --git a/src/services/animated_image/animated_image.js b/src/services/animated_image/animated_image.js
new file mode 100644
index 0000000000..7062645c85
--- /dev/null
+++ b/src/services/animated_image/animated_image.js
@@ -0,0 +1,46 @@
+// Whether a picture is animated, read from its bytes: the browser takes the
+// type from the file name, and an animated WebP named .gif is common.
+
+const ascii = (bytes, start, end) =>
+ String.fromCharCode(...bytes.subarray(start, end))
+
+const head = async (file) =>
+ new Uint8Array(await file.slice(0, 64).arrayBuffer())
+
+// a VP8X chunk with the animation flag
+export const isAnimatedWebP = async (file) => {
+ const bytes = await head(file)
+ return (
+ ascii(bytes, 0, 4) === 'RIFF' &&
+ ascii(bytes, 8, 16) === 'WEBPVP8X' &&
+ (bytes[20] & 0x02) !== 0
+ )
+}
+
+// the avis brand in the ftyp box: the major brand, or a compatible brand
+// after the minor version. A box size of 0 goes to the end of the file.
+export const isAnimatedAvif = async (file) => {
+ const bytes = await head(file)
+ if (ascii(bytes, 4, 8) !== 'ftyp') return false
+ const size = new DataView(bytes.buffer).getUint32(0)
+ const end = size === 0 ? bytes.length : Math.min(size, bytes.length)
+ if (ascii(bytes, 8, 12) === 'avis') return true
+ for (let i = 16; i + 4 <= end; i += 4) {
+ if (ascii(bytes, i, i + 4) === 'avis') return true
+ }
+ return false
+}
+
+// an acTL chunk
+export const isAnimatedPng = async (file) => {
+ const bytes = new Uint8Array(await file.arrayBuffer())
+ for (let i = 0; i < bytes.length - 3; i++) {
+ if (ascii(bytes, i, i + 4) === 'acTL') return true
+ }
+ return false
+}
+
+export const isAnimated = async (file) =>
+ (await isAnimatedWebP(file)) ||
+ (await isAnimatedAvif(file)) ||
+ (file.type === 'image/png' && (await isAnimatedPng(file)))
diff --git a/test/unit/specs/services/animated_image.spec.js b/test/unit/specs/services/animated_image.spec.js
new file mode 100644
index 0000000000..c5066e4e9f
--- /dev/null
+++ b/test/unit/specs/services/animated_image.spec.js
@@ -0,0 +1,66 @@
+import {
+ isAnimated,
+ isAnimatedAvif,
+ isAnimatedPng,
+ isAnimatedWebP,
+} from 'src/services/animated_image/animated_image.js'
+
+const bytes = (...parts) =>
+ new Uint8Array(
+ parts.flatMap((p) =>
+ typeof p === 'string' ? [...p].map((c) => c.charCodeAt(0)) : p,
+ ),
+ )
+const file = (data, type = 'image/png') => new File([data], 'f', { type })
+
+// RIFF header and VP8X chunk with the given flags
+const vp8x = (flags) =>
+ file(bytes('RIFF', [0, 0, 0, 0], 'WEBPVP8X', [10, 0, 0, 0, flags, 0, 0, 0]))
+// an ftyp box: major brand, minor version, compatible brands
+const ftyp = (size, major, ...compatible) =>
+ file(bytes([0, 0, 0, size], 'ftyp', major, [0, 0, 0, 0], ...compatible))
+
+describe('animated pictures', () => {
+ it('finds the animation flag of a WebP', async () => {
+ expect(await isAnimatedWebP(vp8x(0x02))).to.equal(true)
+ expect(await isAnimatedWebP(vp8x(0x12))).to.equal(true)
+ expect(await isAnimatedWebP(vp8x(0x10))).to.equal(false)
+ const still = file(bytes('RIFF', [0, 0, 0, 0], 'WEBPVP8 '))
+ expect(await isAnimatedWebP(still)).to.equal(false)
+ expect(await isAnimatedWebP(file(''))).to.equal(false)
+ })
+
+ it('finds the avis brand of an AVIF', async () => {
+ expect(await isAnimatedAvif(ftyp(24, 'avis', 'avif', 'mif1'))).to.equal(
+ true,
+ )
+ expect(
+ await isAnimatedAvif(ftyp(28, 'avif', 'mif1', 'miaf', 'avis')),
+ ).to.equal(true)
+ expect(await isAnimatedAvif(ftyp(0, 'avif', 'mif1', 'avis'))).to.equal(true)
+ expect(await isAnimatedAvif(ftyp(24, 'avif', 'mif1', 'miaf'))).to.equal(
+ false,
+ )
+ // a brand after the end of the box is not one
+ expect(await isAnimatedAvif(ftyp(20, 'avif', 'mif1', 'avis'))).to.equal(
+ false,
+ )
+ })
+
+ it('finds the acTL chunk of a PNG', async () => {
+ expect(await isAnimatedPng(file(bytes([0x89], 'PNG', 'acTL')))).to.equal(
+ true,
+ )
+ expect(await isAnimatedPng(file(bytes([0x89], 'PNG', 'IDAT')))).to.equal(
+ false,
+ )
+ })
+
+ it('reads the bytes whatever the type says', async () => {
+ const webp = bytes('RIFF', [0, 0, 0, 0], 'WEBPVP8X', [10, 0, 0, 0, 2])
+ expect(await isAnimated(file(webp, 'image/gif'))).to.equal(true)
+ expect(await isAnimated(file(webp, 'image/jpeg'))).to.equal(true)
+ expect(await isAnimated(file(bytes('acTL'), 'image/png'))).to.equal(true)
+ expect(await isAnimated(file(bytes('x'), 'image/jpeg'))).to.equal(false)
+ })
+})
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Wed, Nov 18, 10:47 AM (1 d, 8 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1840357
Default Alt Text
(10 KB)
Attached To
Mode
rPUFE pleroma-fe-upstream
Attached
Detach File
Event Timeline