Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support HEIC and HEIF image previews https://github.com/siyuan-note/siyuan/issues/18760

Danielb9028c0ed34d
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 58fa3ae1f8..c5818936d8 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -160,6 +160,7 @@ The following inventory is the union generated by `go list -deps -json ./...` fo
| `github.com/flopp/go-findfont` | v0.1.0 | MIT | [source](https://pkg.go.dev/github.com/flopp/[email protected]) |
| `github.com/fsnotify/fsnotify` | v1.9.0 | BSD-3-Clause | [source](https://pkg.go.dev/github.com/fsnotify/[email protected]) |
| `github.com/gabriel-vasile/mimetype` | v1.4.12 | MIT | [source](https://pkg.go.dev/github.com/gabriel-vasile/[email protected]) |
+| `github.com/gen2brain/h265` | v0.1.1 | MIT | [source](https://pkg.go.dev/github.com/gen2brain/[email protected]) |
| `github.com/gigawattio/window` | v0.0.0-20180317192513-0f5467e35573 | MIT | [source](https://pkg.go.dev/github.com/gigawattio/[email protected]) |
| `github.com/gin-contrib/gzip` | v1.2.3 | MIT | [source](https://pkg.go.dev/github.com/gin-contrib/[email protected]) |
| `github.com/gin-contrib/sessions` | v1.0.4 | MIT | [source](https://pkg.go.dev/github.com/gin-contrib/[email protected]) |
@@ -11432,6 +11433,33 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+### github.com/gen2brain/h265 v0.1.1 - LICENSE
+
+```text
+MIT License
+
+Copyright (c) 2025 roticv
+Copyright (c) 2026 Karpeles Lab Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
### github.com/gigawattio/window v0.0.0-20180317192513-0f5467e35573 - LICENSE
```text
diff --git a/app/src/asset/renderAssets.ts b/app/src/asset/renderAssets.ts
index 1a96bc267d..681fe51912 100644
--- a/app/src/asset/renderAssets.ts
+++ b/app/src/asset/renderAssets.ts
@@ -6,6 +6,7 @@ import {getAssetExtension} from "../util/pathName";
import * as dayjs from "dayjs";
import {escapeAttr} from "../util/escape";
import {getHTMLAssetIFrameSrc, isHTMLFilePath} from "./html";
+import {isBrowserRenderableImagePath} from "../util/imageURL";
export const renderAssetsPreview = (pathString: string) => {
if (!pathString) {
@@ -68,7 +69,7 @@ export const genAssetHTML = (type: string, pathString: string, imgName: string,
html = `<div data-node-id="${Lute.NewNodeID()}" data-type="NodeIFrame" class="iframe" updated="${dayjs().format("YYYYMMDDHHmmss")}"><div class="iframe-content">${Constants.ZWSP}<iframe sandbox="allow-scripts" src="${iframeSrc}" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe><span class="protyle-action__drag" contenteditable="false"></span></div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;
} else if (Constants.SIYUAN_ASSETS_AUDIO.includes(type)) {
html = `<div data-node-id="${Lute.NewNodeID()}" data-type="NodeAudio" class="iframe" updated="${dayjs().format("YYYYMMDDHHmmss")}"><div class="iframe-content"><audio controls="controls" src="${pathString}"></audio>${Constants.ZWSP}</div><div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;
- } else if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {
+ } else if (Constants.SIYUAN_ASSETS_IMAGE.includes(type) && isBrowserRenderableImagePath(pathString)) {
let netHTML = "";
if (!pathString.startsWith("assets/")) {
netHTML = '<span class="img__net"><svg><use xlink:href="#iconGlobe"></use></svg></span>';
diff --git a/app/src/constants.ts b/app/src/constants.ts
index 0bae9e132b..9bb9583664 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -847,7 +847,7 @@ export abstract class Constants {
</svg>`;
// assets
- public static readonly SIYUAN_ASSETS_IMAGE: string[] = [".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif", ".tiff", ".tif"];
+ public static readonly SIYUAN_ASSETS_IMAGE: string[] = [".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif", ".tiff", ".tif", ".heic", ".heif"];
public static readonly SIYUAN_ASSETS_AUDIO: string[] = [".mp3", ".wav", ".ogg", ".m4a", ".aac", ".flac"];
public static readonly SIYUAN_ASSETS_VIDEO: string[] = [".mov", ".weba", ".mkv", ".mp4", ".webm"];
public static readonly SIYUAN_ASSETS_EXTS: string[] = [".pdf"].concat(Constants.SIYUAN_ASSETS_IMAGE, Constants.SIYUAN_ASSETS_AUDIO, Constants.SIYUAN_ASSETS_VIDEO);
diff --git a/app/src/editor/openLink.ts b/app/src/editor/openLink.ts
index 5d2f613f72..69085e5746 100644
--- a/app/src/editor/openLink.ts
+++ b/app/src/editor/openLink.ts
@@ -11,6 +11,7 @@ import {openAsset, openBy} from "./util";
import {showMessage} from "../dialog/message";
import {isInIOS, isInAndroid, isInHarmony} from "../protyle/util/compatibility";
import type {App} from "../index";
+import {isBrowserRenderableImagePath} from "../util/imageURL";
export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPressed = false) => {
let linkAddress = Lute.UnEscapeHTMLStr(aLink);
@@ -32,8 +33,9 @@ export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPres
openByMobile(linkAddress);
/// #else
if (isLocalPath(linkAddress)) {
- const extension = getAssetExtension(linkAddress);
+ const extension = getAssetExtension(linkAddress).toLowerCase();
if (Constants.SIYUAN_ASSETS_EXTS.includes(extension) &&
+ isBrowserRenderableImagePath(linkAddress) &&
(
extension !== ".pdf" ||
// 本地 pdf 仅 assets/ 开头的才使用 siyuan 打开
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index 6e1d4f1ccd..0a718d4b6c 100644
--- a/app/src/editor/util.ts
+++ b/app/src/editor/util.ts
@@ -34,6 +34,7 @@ import {preventScroll} from "../protyle/scroll/preventScroll";
import {clearOBG} from "../layout/dock/util";
import {Model} from "../layout/Model";
import {hideElements} from "../protyle/ui/hideElements";
+import {isBrowserRenderableImagePath} from "../util/imageURL";
const isSameCustomTab = (type: string, data: any, options: IOpenFileOptions) => {
if (!options.custom || (options.custom.id && options.custom.id !== type)) {
@@ -90,8 +91,8 @@ export const openFileById = async (options: {
};
export const openAsset = (app: App, assetPath: string, page: number | string, position?: string) => {
- const suffix = getAssetExtension(assetPath);
- if (!Constants.SIYUAN_ASSETS_EXTS.includes(suffix)) {
+ const suffix = getAssetExtension(assetPath).toLowerCase();
+ if (!Constants.SIYUAN_ASSETS_EXTS.includes(suffix) || !isBrowserRenderableImagePath(assetPath)) {
return;
}
openFile({
@@ -495,8 +496,9 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IMod
const newTab = (options: IOpenFileOptions) => {
let tab: Tab;
if (options.assetPath) {
- const suffix = getAssetExtension(options.assetPath);
- if (Constants.SIYUAN_ASSETS_EXTS.includes(suffix)) {
+ const suffix = getAssetExtension(options.assetPath).toLowerCase();
+ if (Constants.SIYUAN_ASSETS_EXTS.includes(suffix) &&
+ isBrowserRenderableImagePath(options.assetPath)) {
let icon = "iconPDF";
if (Constants.SIYUAN_ASSETS_IMAGE.includes(suffix)) {
icon = "iconImage";
diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.ts
index 29d025bb5d..484a791701 100644
--- a/app/src/menus/commonMenuItem.ts
+++ b/app/src/menus/commonMenuItem.ts
@@ -36,6 +36,7 @@ import {hideElements} from "../protyle/ui/hideElements";
import {Protyle} from "../protyle";
import {getAllEditor} from "../layout/getAll";
import {hasClosestByClassName} from "../protyle/util/hasClosest";
+import {isBrowserRenderableImagePath} from "../util/imageURL";
const bindAttrInput = (inputElement: HTMLInputElement, id: string) => {
inputElement.addEventListener("change", () => {
@@ -855,8 +856,9 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAccelerat
});
/// #else
if (isLocalPath(src)) {
- const extension = getAssetExtension(src);
+ const extension = getAssetExtension(src).toLowerCase();
if (Constants.SIYUAN_ASSETS_EXTS.includes(extension) &&
+ isBrowserRenderableImagePath(src) &&
(extension !== ".pdf" ||
(extension === ".pdf" && !src.startsWith("file://")))
) {
diff --git a/app/src/menus/util.ts b/app/src/menus/util.ts
index 5b827c185c..c30c33f322 100644
--- a/app/src/menus/util.ts
+++ b/app/src/menus/util.ts
@@ -14,6 +14,7 @@ import {checkFold} from "../util/noRelyPCFunction";
import {showMessage} from "../dialog/message";
import type {Editor} from "../editor";
import {setEditMode} from "../protyle/util/setEditMode";
+import {getDownloadURL} from "../util/imageURL";
export const exportAsset = (src: string) => {
return {
@@ -22,7 +23,7 @@ export const exportAsset = (src: string) => {
icon: "iconUpload",
async click() {
/// #if BROWSER
- saveExportFile(src);
+ saveExportFile(getDownloadURL(src));
/// #else
const result = await ipcRenderer.invoke(Constants.SIYUAN_GET, {
cmd: "showSaveDialog",
diff --git a/app/src/protyle/export/index.ts b/app/src/protyle/export/index.ts
index 13e63f6b2d..9f9fbd37ca 100644
--- a/app/src/protyle/export/index.ts
+++ b/app/src/protyle/export/index.ts
@@ -747,6 +747,23 @@ ${getIconScript(servePath)}
parentWindowId: ${currentWindowId},
};
};
+ const waitForImages = () => Promise.all(Array.from(previewElement.querySelectorAll("img")).map((image) => {
+ image.loading = "eager";
+ if (image.complete) {
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => {
+ const finish = () => {
+ clearTimeout(timeout);
+ image.removeEventListener("load", finish);
+ image.removeEventListener("error", finish);
+ resolve();
+ };
+ const timeout = setTimeout(finish, 30000);
+ image.addEventListener("load", finish, {once: true});
+ image.addEventListener("error", finish, {once: true});
+ });
+ }));
actionElement.querySelector('.b3-button--text').addEventListener('click', async () => {
const {ipcRenderer} = require("electron");
const result = await ipcRenderer.invoke("${Constants.SIYUAN_GET}", {
@@ -757,6 +774,7 @@ ${getIconScript(servePath)}
if (result.canceled || result.filePaths.length === 0) {
return;
}
+ await waitForImages();
const isPaged = actionElement.querySelector("#paged").checked;
let exportConfig;
if (!isPaged) {
diff --git a/app/src/protyle/preview/image.ts b/app/src/protyle/preview/image.ts
index e217477e7b..af588bb9bc 100644
--- a/app/src/protyle/preview/image.ts
+++ b/app/src/protyle/preview/image.ts
@@ -1,6 +1,7 @@
import {Constants} from "../../constants";
import {addScript} from "../util/addScript";
import {fetchPost} from "../../util/fetch";
+import {isBrowserRenderableImagePath} from "../../util/imageURL";
export const previewImages = (srcList: string[], currentSrc?: string, onHidden?: () => void) => {
addScript(`${Constants.PROTYLE_CDN}/js/viewerjs/viewer.js?v=1.11.7`, "protyleViewerScript").then(() => {
@@ -67,6 +68,6 @@ export const previewAttrViewImages = (currentSrc: string, avID: string, viewID:
viewID,
query,
}, (response) => {
- previewImages(response.data, currentSrc);
+ previewImages(response.data.filter((item: string) => isBrowserRenderableImagePath(item)), currentSrc);
});
};
diff --git a/app/src/protyle/preview/index.ts b/app/src/protyle/preview/index.ts
index 1b9e84dde6..1f3f79c39f 100644
--- a/app/src/protyle/preview/index.ts
+++ b/app/src/protyle/preview/index.ts
@@ -26,6 +26,7 @@ import {getPadding} from "../ui/initUI";
import {hasTopClosestByAttribute} from "../util/hasClosest";
import {addScriptSync} from "../util/addScript";
import {prepareWechatCopy, prepareZhihuCopy} from "./platformCopy";
+import {isHEIFPath, isBrowserRenderableImagePath} from "../../util/imageURL";
export class Preview {
public element: HTMLElement;
@@ -142,7 +143,9 @@ export class Preview {
openBy(linkAddress, "folder");
} else if (event.shiftKey) {
openBy(linkAddress, "app");
- } else if (Constants.SIYUAN_ASSETS_EXTS.includes(pathPosix().extname((linkAddress).split("?")[0]))) {
+ } else if (isHEIFPath(linkAddress) && !isBrowserRenderableImagePath(linkAddress)) {
+ openBy(linkAddress, "app");
+ } else if (Constants.SIYUAN_ASSETS_EXTS.includes(pathPosix().extname((linkAddress).split("?")[0]).toLowerCase())) {
openAsset(protyle.app, linkAddress.split("?page")[0], parseInt(getSearch("page", linkAddress)));
}
/// #endif
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index 5c517d15b5..074ad59d4b 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -23,6 +23,7 @@ import * as dayjs from "dayjs";
import {getColId} from "./col";
import {getFieldIdByCellElement} from "./row";
import {base64ToURL, getCompressURL, removeCompressURL} from "../../../util/image";
+import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {confirmDialog} from "../../../dialog/confirmDialog";
import {filesize} from "filesize";
import {genNetworkImageAssetValue} from "./assetValue";
@@ -82,7 +83,7 @@ export const getAssetHTML = (cellElements: HTMLElement[]) => {
const batchMode = getAVBatchEditMode(cellElements[0]);
getVisibleAssetValues(cellElements).forEach((item, index) => {
let contentHTML;
- if (item.type === "image") {
+ if (item.type === "image" && isBrowserRenderableImagePath(item.content)) {
contentHTML = `<span data-type="openAssetItem" class="fn__flex-1 ariaLabel" aria-label="${escapeAriaLabel(item.content)}">
<img style="max-height: 180px;max-width: 360px;border-radius: var(--b3-border-radius);margin: 4px 0;" src="${getCompressURL(encodeURI(item.content))}"/>
</span>`;
@@ -382,7 +383,7 @@ export const editAssetItem = (options: {
if (type !== "file" || openSubMenu.length > 0) {
menu.addSeparator({id: "separator_2"});
}
- if (type !== "file") {
+ if (type !== "file" && isBrowserRenderableImagePath(linkAddress)) {
menu.addItem({
id: "cardPreview",
icon: "iconPreview",
diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.ts
index 46468d209a..150d34615e 100644
--- a/app/src/protyle/render/av/attributeValue.ts
+++ b/app/src/protyle/render/av/attributeValue.ts
@@ -2,6 +2,7 @@ import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
import {unicode2Emoji} from "../../../emoji";
import {Constants} from "../../../constants";
import {getCompressURL} from "../../../util/image";
+import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {formatDateDisplay, formatDateValue} from "./dateFormat";
import {getAVBlockRefSubtype} from "./cellValue";
@@ -142,7 +143,7 @@ export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat =
break;
case "mAsset":
value.mAsset?.forEach(item => {
- if (item.type === "image") {
+ if (item.type === "image" && isBrowserRenderableImagePath(item.content)) {
html += `<img loading="lazy" class="av__cellassetimg ariaLabel" aria-label="${escapeAriaLabel(item.content)}" src="${getCompressURL(item.content)}">`;
} else {
html += `<span class="b3-chip b3-chip--middle av__celltext--url ariaLabel" aria-label="${escapeAriaLabel(item.content)}" data-name="${escapeAttr(item.name)}" data-url="${escapeAttr(item.content)}">${escapeHtml(item.name || item.content)}</span>`;
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index bbc10990e6..949ef59da0 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -20,6 +20,7 @@ import {formatDateDisplay, formatDateValue, parseDateValue} from "./dateFormat";
import {getFieldIdByCellElement} from "./row";
import {getFieldsByData} from "./view";
import {getCompressURL, removeCompressURL} from "../../../util/image";
+import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {callMobileAppShowKeyboard} from "../../../mobile/util/mobileAppUtil";
import {
cellValueIsEmpty,
@@ -232,7 +233,8 @@ const transformCellValue = (colType: TAVCol, value: IAVCellValue): IAVCellValue
} else if (colType === "mAsset") {
const content = getCellValueContent(value).toString();
newValue.mAsset = [{
- type: Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(content).toLowerCase()) ? "image" : "file",
+ type: Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(content).toLowerCase()) &&
+ isBrowserRenderableImagePath(content) ? "image" : "file",
content,
name: "",
}];
@@ -308,7 +310,8 @@ export const genCellValue = (colType: TAVCol, value: string | any, dateFormat: T
cellValue = {
type: colType,
mAsset: [{
- type: Constants.SIYUAN_ASSETS_IMAGE.includes(type) ? "image" : "file",
+ type: Constants.SIYUAN_ASSETS_IMAGE.includes(type) &&
+ isBrowserRenderableImagePath(value) ? "image" : "file",
content: value,
name: "",
}]
@@ -1147,7 +1150,7 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru
text = `<span class="av__celltext" data-value='${rowIndex + 1}'>${rowIndex + 1}</span>`;
} else if (cellValue.type === "mAsset") {
cellValue?.mAsset?.forEach((item) => {
- if (item.type === "image") {
+ if (item.type === "image" && isBrowserRenderableImagePath(item.content)) {
text += `<img loading="lazy" class="av__cellassetimg ariaLabel" aria-label="${escapeAriaLabel(item.content)}" src="${getCompressURL(encodeURI(item.content))}">`;
} else {
text += `<span class="b3-chip av__celltext--url ariaLabel" aria-label="${escapeAriaLabel(item.content)}" data-name="${escapeAttr(item.name)}" data-url="${escapeAttr(item.content)}">${escapeHtml(item.name || item.content)}</span>`;
diff --git a/app/src/protyle/render/av/cover.test.ts b/app/src/protyle/render/av/cover.test.ts
index aa7a672c1d..c313332cd6 100644
--- a/app/src/protyle/render/av/cover.test.ts
+++ b/app/src/protyle/render/av/cover.test.ts
@@ -36,6 +36,14 @@ describe("getCardCoverImageHTML", () => {
assert.match(html, /src="assets\/cover\.png\?style=thumb"/);
});
+ it("does not render cross-origin HEIF covers", () => {
+ assert.equal(getCardCoverImageHTML(
+ "https://example.com/cover.heic",
+ "https://example.com/cover.heic",
+ false,
+ ), "");
+ });
+
it("applies a stored position only to the same image", () => {
const position = {image: "assets/cover.png", x: 12.5, y: 87.5};
diff --git a/app/src/protyle/render/av/cover.ts b/app/src/protyle/render/av/cover.ts
index 2fa49d115f..7ae345d64a 100644
--- a/app/src/protyle/render/av/cover.ts
+++ b/app/src/protyle/render/av/cover.ts
@@ -1,4 +1,5 @@
import {escapeAttr} from "../../../util/escape";
+import {isBrowserRenderableImagePath} from "../../../util/imageURL";
const TRANSPARENT_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
@@ -32,6 +33,9 @@ export const getCardCoverImageHTML = (coverURL: string, imageURL: string, fitIma
if (coverURL.startsWith("background")) {
return `<img class="av__gallery-img" src="${TRANSPARENT_IMAGE}" style="${escapeAttr(coverURL)}">`;
}
+ if (!isBrowserRenderableImagePath(coverURL)) {
+ return "";
+ }
const objectPosition = position?.image === coverURL ? ` style="object-position:${position.x}% ${position.y}%"` : "";
return `<img loading="lazy" class="av__gallery-img${fitImage ? " av__gallery-img--fit" : ""}" src="${escapeAttr(imageURL)}"${objectPosition}>`;
};
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index d27e404243..fd5fc25c0b 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -39,6 +39,7 @@ import {addAssetLink, bindAssetEvent, editAssetItem, getAssetHTML, updateAssetCe
import {Constants} from "../../../constants";
import {hideElements} from "../../ui/hideElements";
import {getAssetExtension} from "../../../util/pathName";
+import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {openEmojiPanel, unicode2Emoji} from "../../../emoji";
import {isMobile} from "../../../util/functions";
import {openLink} from "../../../editor/openLink";
@@ -1751,7 +1752,8 @@ export const openMenuPanel = (options: {
h: rect.height
}, (url, name) => {
let value: IAVCellAssetValue;
- if (Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(url).toLowerCase())) {
+ if (Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(url).toLowerCase()) &&
+ isBrowserRenderableImagePath(url)) {
value = {
type: "image",
content: url,
@@ -1779,7 +1781,8 @@ export const openMenuPanel = (options: {
break;
} else if (type === "openAssetItem") {
const assetLink = target.parentElement.dataset.content;
- if (target.parentElement.dataset.type === "image") {
+ if (target.parentElement.dataset.type === "image" &&
+ isBrowserRenderableImagePath(assetLink)) {
previewAttrViewImages(assetLink, avID, options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW),
options.blockElement.querySelector('[data-type="av-search"]')?.textContent.trim() || "");
} else {
diff --git a/app/src/util/image.test.ts b/app/src/util/image.test.ts
new file mode 100644
index 0000000000..842700959b
--- /dev/null
+++ b/app/src/util/image.test.ts
@@ -0,0 +1,118 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ getCompressURL,
+ getDownloadURL,
+ isBrowserRenderableImagePath,
+ isHEIFPath,
+ isInternalHEIFPath,
+ removeCompressURL,
+} from "./imageURL";
+
+const TEST_ORIGIN = "https://siyuan.local";
+
+describe("getCompressURL", () => {
+ it("adds thumbnail styles to supported image assets regardless of extension case", () => {
+ assert.equal(getCompressURL("assets/image.png"), "assets/image.png?style=thumb");
+ assert.equal(getCompressURL("assets/image.JPG"), "assets/image.JPG?style=thumb");
+ assert.equal(getCompressURL("assets/image.HeIc"), "assets/image.HeIc?style=thumb");
+ assert.equal(getCompressURL("assets/image.HEIF"), "assets/image.HEIF?style=thumb");
+ });
+
+ it("preserves existing queries and fragments", () => {
+ assert.equal(
+ getCompressURL("assets/image.heic?box=20260816000000-test#preview"),
+ "assets/image.heic?box=20260816000000-test&style=thumb#preview",
+ );
+ assert.equal(getCompressURL("assets/image.jpeg#preview"), "assets/image.jpeg?style=thumb#preview");
+ });
+
+ it("keeps one thumbnail style when called repeatedly", () => {
+ assert.equal(
+ getCompressURL("assets/image.heif?box=test&style=thumb#preview"),
+ "assets/image.heif?box=test&style=thumb#preview",
+ );
+ assert.equal(
+ getCompressURL("assets/image.heif?style=original&box=test"),
+ "assets/image.heif?style=thumb&box=test",
+ );
+ });
+
+ it("does not change unsupported or non-asset URLs", () => {
+ assert.equal(getCompressURL("assets/image.gif?box=test#preview"), "assets/image.gif?box=test#preview");
+ assert.equal(getCompressURL("https://example.com/assets/image.heic"), "https://example.com/assets/image.heic");
+ });
+});
+
+describe("removeCompressURL", () => {
+ it("removes thumbnail styles while preserving other queries and fragments", () => {
+ assert.equal(
+ removeCompressURL("assets/image.HEIC?box=20260816000000-test&style=thumb#preview"),
+ "assets/image.HEIC?box=20260816000000-test#preview",
+ );
+ assert.equal(
+ removeCompressURL("assets/image.jpg?style=thumb&box=20260816000000-test#preview"),
+ "assets/image.jpg?box=20260816000000-test#preview",
+ );
+ assert.equal(removeCompressURL("assets/image.heif?style=thumb#preview"), "assets/image.heif#preview");
+ });
+
+ it("does not change URLs without a thumbnail style", () => {
+ assert.equal(removeCompressURL("assets/image.heic?box=test#preview"), "assets/image.heic?box=test#preview");
+ assert.equal(removeCompressURL("assets/image.gif?style=thumb"), "assets/image.gif?style=thumb");
+ });
+});
+
+describe("HEIF paths", () => {
+ it("recognizes every supported internal asset URL form", () => {
+ assert.equal(isInternalHEIFPath("assets/image.heic", TEST_ORIGIN), true);
+ assert.equal(isInternalHEIFPath("./assets/image.heic", TEST_ORIGIN), true);
+ assert.equal(isInternalHEIFPath("/assets/image.heic", TEST_ORIGIN), true);
+ assert.equal(isInternalHEIFPath("https://siyuan.local/assets/image.HEIF?box=test", TEST_ORIGIN), true);
+ });
+
+ it("rejects HEIF paths that cannot use the same-origin asset converter", () => {
+ assert.equal(isHEIFPath("file:///tmp/image.HEIC#preview"), true);
+ assert.equal(isHEIFPath("assets/image%2EHEIC"), true);
+ assert.equal(isInternalHEIFPath("https://example.com/assets/image.heic", TEST_ORIGIN), false);
+ assert.equal(isInternalHEIFPath("file:///tmp/image.HEIC#preview", TEST_ORIGIN), false);
+ assert.equal(isInternalHEIFPath("C:\\notes\\image.heic", TEST_ORIGIN), false);
+ assert.equal(isInternalHEIFPath("\\\\server\\share\\image.heic", TEST_ORIGIN), false);
+ assert.equal(isInternalHEIFPath("/ASSETS/image.heic", TEST_ORIGIN), false);
+ assert.equal(isHEIFPath("assets/image.jpeg"), false);
+ });
+});
+
+describe("isBrowserRenderableImagePath", () => {
+ it("renders regular images and same-origin HEIF assets", () => {
+ assert.equal(isBrowserRenderableImagePath("https://example.com/image.jpg", TEST_ORIGIN), true);
+ assert.equal(isBrowserRenderableImagePath("assets/image.heic", TEST_ORIGIN), true);
+ assert.equal(isBrowserRenderableImagePath("./assets/image.heif", TEST_ORIGIN), true);
+ assert.equal(isBrowserRenderableImagePath("/assets/image.heic", TEST_ORIGIN), true);
+ assert.equal(
+ isBrowserRenderableImagePath("https://siyuan.local/assets/image.heif?box=test", TEST_ORIGIN),
+ true,
+ );
+ });
+
+ it("does not render HEIF paths that bypass the asset converter", () => {
+ assert.equal(isBrowserRenderableImagePath("https://example.com/assets/image.heic", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("file:///tmp/image.heic", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("C:\\notes\\image.heic", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("\\\\server\\share\\image.heic", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("assets/image.heic?download=true", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("assets/image.heic?download=TRUE", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("assets/image.heic?%64ownload=true", TEST_ORIGIN), false);
+ assert.equal(isBrowserRenderableImagePath("assets/image.heic?download=false", TEST_ORIGIN), true);
+ });
+});
+
+describe("getDownloadURL", () => {
+ it("sets the download parameter while preserving asset context", () => {
+ assert.equal(
+ getDownloadURL("assets/image.heic?box=20260816000000-test#preview"),
+ "assets/image.heic?box=20260816000000-test&download=true#preview",
+ );
+ assert.equal(getDownloadURL("assets/image.heif?download=false"), "assets/image.heif?download=true");
+ });
+});
diff --git a/app/src/util/image.ts b/app/src/util/image.ts
index a321c70a5a..d7a8e2e0b0 100644
--- a/app/src/util/image.ts
+++ b/app/src/util/image.ts
@@ -1,21 +1,7 @@
import {fetchSyncPost} from "./fetch";
import {Constants} from "../constants";
-export const getCompressURL = (url: string) => {
- if (url.startsWith("assets/") &&
- (url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith(".jpeg"))) {
- return url + "?style=thumb";
- }
- return url;
-};
-
-export const removeCompressURL = (url: string) => {
- if (url.startsWith("assets/") &&
- (url.endsWith(".png?style=thumb") || url.endsWith(".jpg?style=thumb") || url.endsWith(".jpeg?style=thumb"))) {
- return url.replace("?style=thumb", "");
- }
- return url;
-};
+export {getCompressURL, removeCompressURL} from "./imageURL";
export const base64ToURL = async (base64SrcList: string[]) => {
const formData = new FormData();
diff --git a/app/src/util/imageURL.ts b/app/src/util/imageURL.ts
new file mode 100644
index 0000000000..1b9dcab2c6
--- /dev/null
+++ b/app/src/util/imageURL.ts
@@ -0,0 +1,132 @@
+const THUMBNAIL_EXTENSIONS = [".png", ".jpg", ".jpeg", ".heic", ".heif"];
+const HEIF_EXTENSIONS = [".heic", ".heif"];
+const FALLBACK_ORIGIN = "http://siyuan.invalid";
+
+interface IAssetURLParts {
+ path: string;
+ query?: string;
+ fragment: string;
+}
+
+const getDecodedPath = (url: string) => {
+ const path = url.trim().split(/[?#]/, 1)[0];
+ try {
+ return decodeURIComponent(path).toLowerCase();
+ } catch {
+ return path.toLowerCase();
+ }
+};
+
+const resolveHTTPURL = (url: string, origin?: string) => {
+ const value = url.trim();
+ if (!value || /^file:/i.test(value) || /^[a-z]:[\\/]/i.test(value) || value.startsWith("\\\\")) {
+ return;
+ }
+ const currentOrigin = origin || (typeof location === "undefined" ? FALLBACK_ORIGIN : location.origin);
+ try {
+ const baseURL = new URL(currentOrigin);
+ if (baseURL.protocol !== "http:" && baseURL.protocol !== "https:") {
+ return;
+ }
+ const resolvedURL = new URL(value, `${baseURL.origin}/`);
+ if ((resolvedURL.protocol !== "http:" && resolvedURL.protocol !== "https:") ||
+ resolvedURL.origin !== baseURL.origin) {
+ return;
+ }
+ return resolvedURL;
+ } catch {
+ return;
+ }
+};
+
+const parseAssetURL = (url: string): IAssetURLParts | undefined => {
+ const fragmentIndex = url.indexOf("#");
+ const fragment = fragmentIndex === -1 ? "" : url.substring(fragmentIndex);
+ const urlWithoutFragment = fragmentIndex === -1 ? url : url.substring(0, fragmentIndex);
+ const queryIndex = urlWithoutFragment.indexOf("?");
+ const path = queryIndex === -1 ? urlWithoutFragment : urlWithoutFragment.substring(0, queryIndex);
+ if (!path.startsWith("assets/") || !THUMBNAIL_EXTENSIONS.some(extension => path.toLowerCase().endsWith(extension))) {
+ return;
+ }
+ return {
+ path,
+ query: queryIndex === -1 ? undefined : urlWithoutFragment.substring(queryIndex + 1),
+ fragment,
+ };
+};
+
+export const isHEIFPath = (url: string) => {
+ const path = getDecodedPath(url);
+ return HEIF_EXTENSIONS.some(extension => path.endsWith(extension));
+};
+
+export const isInternalHEIFPath = (url: string, origin?: string) => {
+ if (!isHEIFPath(url)) {
+ return false;
+ }
+ const resolvedURL = resolveHTTPURL(url, origin);
+ if (!resolvedURL) {
+ return false;
+ }
+ try {
+ return decodeURIComponent(resolvedURL.pathname).startsWith("/assets/");
+ } catch {
+ return false;
+ }
+};
+
+export const isBrowserRenderableImagePath = (url: string, origin?: string) => {
+ if (!isHEIFPath(url)) {
+ return true;
+ }
+ const resolvedURL = resolveHTTPURL(url, origin);
+ return isInternalHEIFPath(url, origin) &&
+ !resolvedURL?.searchParams.getAll("download").some(value => value.toLowerCase() === "true");
+};
+
+export const getDownloadURL = (url: string) => {
+ const fragmentIndex = url.indexOf("#");
+ const fragment = fragmentIndex === -1 ? "" : url.substring(fragmentIndex);
+ const urlWithoutFragment = fragmentIndex === -1 ? url : url.substring(0, fragmentIndex);
+ const queryIndex = urlWithoutFragment.indexOf("?");
+ const path = queryIndex === -1 ? urlWithoutFragment : urlWithoutFragment.substring(0, queryIndex);
+ const parameters = new URLSearchParams(queryIndex === -1 ? "" : urlWithoutFragment.substring(queryIndex + 1));
+ parameters.set("download", "true");
+ return `${path}?${parameters.toString()}${fragment}`;
+};
+
+export const getCompressURL = (url: string) => {
+ const parts = parseAssetURL(url);
+ if (!parts) {
+ return url;
+ }
+ const parameters = parts.query ? parts.query.split("&") : [];
+ let hasStyle = false;
+ const updatedParameters = parameters.reduce<string[]>((result, parameter) => {
+ if (parameter.split("=", 1)[0] !== "style") {
+ result.push(parameter);
+ } else if (!hasStyle) {
+ result.push("style=thumb");
+ hasStyle = true;
+ }
+ return result;
+ }, []);
+ if (!hasStyle) {
+ updatedParameters.push("style=thumb");
+ }
+ return `${parts.path}?${updatedParameters.join("&")}${parts.fragment}`;
+};
+
+export const removeCompressURL = (url: string) => {
+ const parts = parseAssetURL(url);
+ if (!parts?.query) {
+ return url;
+ }
+ const parameters = parts.query.split("&");
+ const remainingParameters = parameters.filter(parameter => parameter !== "style=thumb");
+ if (remainingParameters.length === parameters.length) {
+ return url;
+ }
+ const query = remainingParameters.length > 0 ? `?${remainingParameters.join("&")}` : "";
+ return `${parts.path}${query}${parts.fragment}`;
+};
diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.ts
index 85c415fdef..a7aa515f08 100644
--- a/app/src/window/openNewWindow.ts
+++ b/app/src/window/openNewWindow.ts
@@ -8,6 +8,7 @@ import {fetchSyncPost} from "../util/fetch";
import {showMessage} from "../dialog/message";
import {getAssetExtension, getDisplayName} from "../util/pathName";
import {getSearch} from "../util/functions";
+import {isBrowserRenderableImagePath} from "../util/imageURL";
interface windowOptions {
position?: {
@@ -77,8 +78,9 @@ export const openNewWindowById = async (id: string | string[], options: windowOp
export const openAssetNewWindow = (assetPath: string, options: windowOptions = {}) => {
/// #if !BROWSER
- const suffix = getAssetExtension(assetPath);
- if (Constants.SIYUAN_ASSETS_EXTS.includes(suffix)) {
+ const suffix = getAssetExtension(assetPath).toLowerCase();
+ if (Constants.SIYUAN_ASSETS_EXTS.includes(suffix) &&
+ isBrowserRenderableImagePath(assetPath)) {
let docIcon = "iconPDF";
if (Constants.SIYUAN_ASSETS_IMAGE.includes(suffix)) {
docIcon = "iconImage";
diff --git a/kernel/go.mod b/kernel/go.mod
index 638e1c3c46..1d394eb73e 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -32,6 +32,7 @@ require (
github.com/flopp/go-findfont v0.1.0
github.com/fsnotify/fsnotify v1.10.1
github.com/gabriel-vasile/mimetype v1.4.15
+ github.com/gen2brain/h265 v0.1.1
github.com/gin-contrib/gzip v1.2.6
github.com/gin-contrib/sessions v1.1.0
github.com/gin-contrib/sse v1.1.1
diff --git a/kernel/go.sum b/kernel/go.sum
index 4c15e34c01..809c827fb4 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -171,6 +171,8 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
+github.com/gen2brain/h265 v0.1.1 h1:S+EtCOYeOZ4UQpwzXKCSv37fQ546y4eHHnXye1L236s=
+github.com/gen2brain/h265 v0.1.1/go.mod h1:kefpLxLhGpNCUG/q/aabJcD6GqB9Nhet3fNi9xX9Wzw=
github.com/gigawattio/window v0.0.0-20180317192513-0f5467e35573 h1:u8AQ9bPa9oC+8/A/jlWouakhIvkFfuxgIIRjiy8av7I=
github.com/gigawattio/window v0.0.0-20180317192513-0f5467e35573/go.mod h1:eBvb3i++NHDH4Ugo9qCvMw8t0mTSctaEa5blJbWcNxs=
github.com/gin-contrib/gzip v1.2.6 h1:OtN8DplD5DNZCSLAnQ5HxRkD2qZ5VU+JhOrcfJrcRvg=
diff --git a/kernel/heif/cache.go b/kernel/heif/cache.go
new file mode 100644
index 0000000000..55ea7723a5
--- /dev/null
+++ b/kernel/heif/cache.go
@@ -0,0 +1,307 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package heif
+
+import (
+ "bytes"
+ "container/list"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "golang.org/x/sync/singleflight"
+)
+
+const (
+ cacheVersion = "h265-safe-still-jpeg-v1"
+ memoryCacheMaxBytes = 128 * 1024 * 1024
+ diskCacheMaxBytes = 512 * 1024 * 1024
+ conversionTimeout = 30 * time.Second
+)
+
+type Options struct {
+ Mode Mode
+ BoxID string
+ Encrypted bool
+}
+
+type Result struct {
+ Data []byte
+ Path string
+ ETag string
+}
+
+type memoryEntry struct {
+ key string
+ boxID string
+ data []byte
+}
+
+type diskEntry struct {
+ path string
+ size int64
+ modTime time.Time
+}
+
+var (
+ conversions singleflight.Group
+ diskCacheLock sync.Mutex
+ memoryCacheLock sync.Mutex
+ memoryCacheList = list.New()
+ memoryCacheItems = map[string]*list.Element{}
+ memoryCacheBytes int
+)
+
+func IsPath(path string) bool {
+ path = strings.ToLower(path)
+ if index := strings.IndexAny(path, "?#"); index >= 0 {
+ path = path[:index]
+ }
+ ext := filepath.Ext(path)
+ return ext == ".heic" || ext == ".heif"
+}
+
+func GetOrCreate(ctx context.Context, source []byte, options Options) (Result, error) {
+ if options.Mode != ModePreview && options.Mode != ModeThumbnail {
+ return Result{}, ErrInvalidMode
+ }
+ if options.Encrypted && options.BoxID == "" {
+ return Result{}, errors.New("encrypted HEIF cache requires a notebook ID")
+ }
+ if len(source) == 0 {
+ return Result{}, errors.New("empty HEIF image")
+ }
+ if len(source) > MaxInputBytes {
+ return Result{}, ErrInputTooLarge
+ }
+ if err := ctx.Err(); err != nil {
+ return Result{}, err
+ }
+
+ digest := cacheDigest(source, options.Mode)
+ etag := `"heif-` + digest + `"`
+ cacheKey := digest
+ if options.Encrypted {
+ cacheKey = options.BoxID + ":" + digest
+ if data := getMemoryCache(cacheKey); data != nil {
+ return Result{Data: data, ETag: etag}, nil
+ }
+ } else if cachePath := existingDiskCache(options.Mode, digest); cachePath != "" {
+ return Result{Path: cachePath, ETag: etag}, nil
+ }
+
+ flightKey := "disk:" + cacheKey
+ if options.Encrypted {
+ flightKey = "memory:" + cacheKey
+ }
+ value, err, _ := conversions.Do(flightKey, func() (any, error) {
+ if options.Encrypted {
+ if data := getMemoryCache(cacheKey); data != nil {
+ return Result{Data: data, ETag: etag}, nil
+ }
+ } else if cachePath := existingDiskCache(options.Mode, digest); cachePath != "" {
+ return Result{Path: cachePath, ETag: etag}, nil
+ }
+
+ data, err := convert(ctx, source, options.Mode)
+ if err != nil {
+ return Result{}, err
+ }
+ if options.Encrypted {
+ putMemoryCache(cacheKey, options.BoxID, data)
+ return Result{Data: data, ETag: etag}, nil
+ }
+ cachePath, cached, err := writeDiskCache(options.Mode, digest, data)
+ if err != nil {
+ return Result{Data: data, ETag: etag}, nil
+ }
+ if !cached {
+ return Result{Data: data, ETag: etag}, nil
+ }
+ return Result{Path: cachePath, ETag: etag}, nil
+ })
+ if err != nil {
+ return Result{}, err
+ }
+ return cloneResult(value.(Result)), nil
+}
+
+func ClearMemoryCache(boxID string) {
+ memoryCacheLock.Lock()
+ defer memoryCacheLock.Unlock()
+ for key, element := range memoryCacheItems {
+ entry := element.Value.(*memoryEntry)
+ if boxID != "" && entry.boxID != boxID {
+ continue
+ }
+ clear(entry.data)
+ memoryCacheBytes -= len(entry.data)
+ memoryCacheList.Remove(element)
+ delete(memoryCacheItems, key)
+ }
+}
+
+func cacheDigest(source []byte, mode Mode) string {
+ hash := sha256.New()
+ hash.Write([]byte(cacheVersion))
+ hash.Write([]byte{0})
+ hash.Write([]byte(mode))
+ hash.Write([]byte{0})
+ hash.Write(source)
+ return hex.EncodeToString(hash.Sum(nil))
+}
+
+func getMemoryCache(key string) []byte {
+ memoryCacheLock.Lock()
+ defer memoryCacheLock.Unlock()
+ element := memoryCacheItems[key]
+ if element == nil {
+ return nil
+ }
+ memoryCacheList.MoveToFront(element)
+ return bytes.Clone(element.Value.(*memoryEntry).data)
+}
+
+func putMemoryCache(key, boxID string, data []byte) {
+ if len(data) > memoryCacheMaxBytes {
+ return
+ }
+ memoryCacheLock.Lock()
+ defer memoryCacheLock.Unlock()
+ if existing := memoryCacheItems[key]; existing != nil {
+ memoryCacheList.MoveToFront(existing)
+ return
+ }
+ element := memoryCacheList.PushFront(&memoryEntry{key: key, boxID: boxID, data: bytes.Clone(data)})
+ memoryCacheItems[key] = element
+ memoryCacheBytes += len(data)
+ for memoryCacheBytes > memoryCacheMaxBytes {
+ oldest := memoryCacheList.Back()
+ if oldest == nil {
+ break
+ }
+ entry := oldest.Value.(*memoryEntry)
+ clear(entry.data)
+ memoryCacheBytes -= len(entry.data)
+ delete(memoryCacheItems, entry.key)
+ memoryCacheList.Remove(oldest)
+ }
+}
+
+func cloneResult(result Result) Result {
+ result.Data = bytes.Clone(result.Data)
+ return result
+}
+
+func diskCachePath(mode Mode, digest string) string {
+ return filepath.Join(util.TempDir, "assets-cache", "heif", string(mode), digest[:2], digest+".jpg")
+}
+
+func existingDiskCache(mode Mode, digest string) string {
+ cachePath := diskCachePath(mode, digest)
+ info, err := os.Stat(cachePath)
+ if err != nil || !info.Mode().IsRegular() || info.Size() == 0 {
+ return ""
+ }
+ now := time.Now()
+ _ = os.Chtimes(cachePath, now, now)
+ return cachePath
+}
+
+func writeDiskCache(mode Mode, digest string, data []byte) (string, bool, error) {
+ if int64(len(data)) > diskCacheMaxBytes {
+ return "", false, nil
+ }
+ diskCacheLock.Lock()
+ defer diskCacheLock.Unlock()
+ if cachePath := existingDiskCache(mode, digest); cachePath != "" {
+ return cachePath, true, nil
+ }
+
+ cachePath := diskCachePath(mode, digest)
+ if err := os.MkdirAll(filepath.Dir(cachePath), 0755); err != nil {
+ return "", false, err
+ }
+ temporary, err := os.CreateTemp(filepath.Dir(cachePath), ".heif-*.tmp")
+ if err != nil {
+ return "", false, err
+ }
+ temporaryPath := temporary.Name()
+ defer os.Remove(temporaryPath)
+ if err = temporary.Chmod(0600); err == nil {
+ _, err = temporary.Write(data)
+ }
+ if closeErr := temporary.Close(); err == nil {
+ err = closeErr
+ }
+ if err != nil {
+ return "", false, err
+ }
+ if err = os.Rename(temporaryPath, cachePath); err != nil {
+ if existing := existingDiskCache(mode, digest); existing != "" {
+ return existing, true, nil
+ }
+ return "", false, err
+ }
+ pruneDiskCacheLocked()
+ return cachePath, true, nil
+}
+
+func pruneDiskCacheLocked() {
+ root := filepath.Join(util.TempDir, "assets-cache", "heif")
+ var total int64
+ var entries []diskEntry
+ _ = filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil || entry.IsDir() {
+ return nil
+ }
+ info, err := entry.Info()
+ if err != nil {
+ return nil
+ }
+ if strings.HasSuffix(entry.Name(), ".tmp") {
+ _ = os.Remove(path)
+ return nil
+ }
+ total += info.Size()
+ entries = append(entries, diskEntry{path: path, size: info.Size(), modTime: info.ModTime()})
+ return nil
+ })
+ if total <= diskCacheMaxBytes {
+ return
+ }
+ sort.Slice(entries, func(i, j int) bool {
+ return entries[i].modTime.Before(entries[j].modTime)
+ })
+ for _, entry := range entries {
+ if total <= diskCacheMaxBytes {
+ break
+ }
+ if err := os.Remove(entry.path); err == nil {
+ total -= entry.size
+ }
+ }
+}
diff --git a/kernel/heif/cache_test.go b/kernel/heif/cache_test.go
new file mode 100644
index 0000000000..c4b07878f7
--- /dev/null
+++ b/kernel/heif/cache_test.go
@@ -0,0 +1,167 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package heif
+
+import (
+ "bytes"
+ "context"
+ "image/jpeg"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestIsPath(t *testing.T) {
+ tests := map[string]bool{
+ "assets/photo.heic": true,
+ "assets/photo.HEIF?box=test#preview": true,
+ "assets/photo.jpeg": false,
+ "assets/photo.heic.txt": false,
+ }
+ for path, want := range tests {
+ if got := IsPath(path); got != want {
+ t.Fatalf("IsPath(%q) = %v, want %v", path, got, want)
+ }
+ }
+}
+
+func TestMemoryCacheCopiesAndClearsByBox(t *testing.T) {
+ ClearMemoryCache("")
+ t.Cleanup(func() {
+ ClearMemoryCache("")
+ })
+
+ source := []byte{1, 2, 3}
+ putMemoryCache("box-a:key", "box-a", source)
+ source[0] = 9
+ first := getMemoryCache("box-a:key")
+ if !bytes.Equal(first, []byte{1, 2, 3}) {
+ t.Fatalf("cache retained caller-owned bytes: %v", first)
+ }
+ first[1] = 9
+ second := getMemoryCache("box-a:key")
+ if !bytes.Equal(second, []byte{1, 2, 3}) {
+ t.Fatalf("cache returned mutable storage: %v", second)
+ }
+
+ ClearMemoryCache("box-b")
+ if got := getMemoryCache("box-a:key"); got == nil {
+ t.Fatal("clearing another notebook removed the cache entry")
+ }
+ ClearMemoryCache("box-a")
+ if got := getMemoryCache("box-a:key"); got != nil {
+ t.Fatalf("cache entry was not cleared: %v", got)
+ }
+ if !bytes.Equal(second, []byte{1, 2, 3}) {
+ t.Fatalf("clearing the cache modified an in-use copy: %v", second)
+ }
+}
+
+func TestCacheDigestSeparatesModes(t *testing.T) {
+ source := []byte("image")
+ preview := cacheDigest(source, ModePreview)
+ if preview != cacheDigest(source, ModePreview) {
+ t.Fatal("preview cache digest is not stable")
+ }
+ if preview == cacheDigest(source, ModeThumbnail) {
+ t.Fatal("preview and thumbnail cache digests are equal")
+ }
+}
+
+func TestGetOrCreateValidatesOptionsBeforeDecode(t *testing.T) {
+ if _, err := GetOrCreate(context.Background(), []byte("image"), Options{}); err != ErrInvalidMode {
+ t.Fatalf("unexpected invalid mode error: %v", err)
+ }
+ if _, err := GetOrCreate(context.Background(), []byte("image"), Options{
+ Mode: ModePreview,
+ Encrypted: true,
+ }); err == nil {
+ t.Fatal("encrypted cache accepted an empty notebook ID")
+ }
+}
+
+func TestValidDimensions(t *testing.T) {
+ if !validDimensions(8064, 6048) {
+ t.Fatal("a 48 megapixel image was rejected")
+ }
+ if validDimensions(0, 1) || validDimensions(maxDimension+1, 1) || validDimensions(10_001, 10_001) {
+ t.Fatal("an invalid or oversized image was accepted")
+ }
+}
+
+func TestReadFileLimited(t *testing.T) {
+ path := t.TempDir() + "/image.heic"
+ if err := os.WriteFile(path, []byte{1, 2, 3, 4}, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ReadFileLimited(path, 3); err != ErrInputTooLarge {
+ t.Fatalf("unexpected oversized read error: %v", err)
+ }
+ data, err := ReadFileLimited(path, 4)
+ if err != nil || !bytes.Equal(data, []byte{1, 2, 3, 4}) {
+ t.Fatalf("unexpected bounded read: %v, %v", data, err)
+ }
+}
+
+func TestConvertStillImages(t *testing.T) {
+ tests := []string{"basic.heic"}
+ for _, name := range tests {
+ t.Run(name, func(t *testing.T) {
+ source, err := os.ReadFile("testdata/" + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ preview, err := convert(context.Background(), source, ModePreview)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config, err := jpeg.DecodeConfig(bytes.NewReader(preview))
+ if err != nil {
+ t.Fatalf("preview is not a JPEG: %v", err)
+ }
+ if !validDimensions(config.Width, config.Height) {
+ t.Fatalf("invalid preview dimensions: %dx%d", config.Width, config.Height)
+ }
+ })
+ }
+}
+
+func TestGetOrCreateFallsBackToMemoryWhenDiskCacheFails(t *testing.T) {
+ source, err := os.ReadFile("testdata/basic.heic")
+ if err != nil {
+ t.Fatal(err)
+ }
+ blocked := filepath.Join(t.TempDir(), "blocked")
+ if err = os.WriteFile(blocked, []byte("file"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ previousTempDir := util.TempDir
+ util.TempDir = blocked
+ defer func() {
+ util.TempDir = previousTempDir
+ }()
+
+ result, err := GetOrCreate(context.Background(), source, Options{Mode: ModePreview})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.Path != "" || len(result.Data) == 0 {
+ t.Fatalf("unexpected cache fallback result: path=%q data=%d", result.Path, len(result.Data))
+ }
+}
diff --git a/kernel/heif/convert.go b/kernel/heif/convert.go
new file mode 100644
index 0000000000..e0e78a224c
--- /dev/null
+++ b/kernel/heif/convert.go
@@ -0,0 +1,218 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package heif
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "image"
+ "image/jpeg"
+ "io"
+ "os"
+ "runtime"
+
+ "github.com/disintegration/imaging"
+ goheic "github.com/siyuan-note/siyuan/kernel/heif/internal/h265heic"
+)
+
+const (
+ thumbnailWidth = 520
+ previewQuality = 90
+ thumbnailQuality = 85
+ MaxInputBytes = 32 * 1024 * 1024
+ maxDimension = 65535
+ desktopMaxPixels = 50_000_000
+ mobileMaxPixels = 12_500_000
+ // 解码层仅接受至多 10-bit 4:2:0、无透明通道的单 slice 图像;这里按解码面、CTU 表、
+ // NRGBA 和一次合并变换预留每像素 16 字节,再单独预留源文件、RBSP 副本与 JPEG 输出。
+ workingBytesPerPixel = 16
+ desktopWorkingBudget = 960 * 1024 * 1024
+ mobileWorkingBudget = 320 * 1024 * 1024
+ desktopOutputReserve = 96 * 1024 * 1024
+ mobileOutputReserve = 32 * 1024 * 1024
+)
+
+var (
+ ErrInputTooLarge = errors.New("HEIF image exceeds the input size limit")
+ ErrImageTooLarge = errors.New("HEIF image exceeds the dimension limit")
+ ErrInvalidMode = errors.New("invalid HEIF conversion mode")
+
+ conversionSlots = make(chan struct{}, 1)
+ maxPixels = platformMaxPixels()
+)
+
+func platformMaxPixels() int {
+ if runtime.GOOS == "android" || runtime.GOOS == "ios" {
+ return pixelsWithinBudget(mobileWorkingBudget, mobileOutputReserve, mobileMaxPixels)
+ }
+ return pixelsWithinBudget(desktopWorkingBudget, desktopOutputReserve, desktopMaxPixels)
+}
+
+func ReadFileLimited(path string, maxBytes int64) ([]byte, error) {
+ if maxBytes <= 0 {
+ return nil, ErrInputTooLarge
+ }
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ data, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(data)) > maxBytes {
+ return nil, ErrInputTooLarge
+ }
+ return data, nil
+}
+
+func pixelsWithinBudget(workingBudget, outputReserve, hardLimit int) int {
+ available := workingBudget - 2*MaxInputBytes - outputReserve
+ if available <= 0 {
+ return 0
+ }
+ return min(available/workingBytesPerPixel, hardLimit)
+}
+
+type Mode string
+
+const (
+ ModePreview Mode = "preview"
+ ModeThumbnail Mode = "thumb"
+)
+
+func convert(ctx context.Context, source []byte, mode Mode) ([]byte, error) {
+ if len(source) == 0 {
+ return nil, errors.New("empty HEIF image")
+ }
+ if len(source) > MaxInputBytes {
+ return nil, ErrInputTooLarge
+ }
+ if mode != ModePreview && mode != ModeThumbnail {
+ return nil, ErrInvalidMode
+ }
+
+ select {
+ case conversionSlots <- struct{}{}:
+ defer func() {
+ <-conversionSlots
+ }()
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ conversionContext, cancel := context.WithTimeout(ctx, conversionTimeout)
+ defer cancel()
+
+ img, err := decodeImage(source)
+ if err != nil {
+ return nil, err
+ }
+ if !validDimensions(img.Bounds().Dx(), img.Bounds().Dy()) {
+ return nil, ErrImageTooLarge
+ }
+ if err = conversionContext.Err(); err != nil {
+ return nil, err
+ }
+ if mode == ModeThumbnail && img.Bounds().Dx() > thumbnailWidth {
+ img = imaging.Resize(img, thumbnailWidth, 0, imaging.Lanczos)
+ }
+ if err = conversionContext.Err(); err != nil {
+ return nil, err
+ }
+
+ quality := previewQuality
+ if mode == ModeThumbnail {
+ quality = thumbnailQuality
+ }
+ output := bytes.NewBuffer(make([]byte, 0, estimatedJPEGSize(img)))
+ if err = jpeg.Encode(output, img, &jpeg.Options{Quality: quality}); err != nil {
+ return nil, fmt.Errorf("encode HEIF preview: %w", err)
+ }
+ if err = conversionContext.Err(); err != nil {
+ return nil, err
+ }
+ return output.Bytes(), nil
+}
+
+func ImageSize(source []byte) (width, height int, err error) {
+ if len(source) == 0 {
+ return 0, 0, errors.New("empty HEIF image")
+ }
+ if len(source) > MaxInputBytes {
+ return 0, 0, ErrInputTooLarge
+ }
+ conversionSlots <- struct{}{}
+ defer func() {
+ <-conversionSlots
+ }()
+ img, err := decodeImage(source)
+ if err != nil {
+ return 0, 0, err
+ }
+ width, height = img.Bounds().Dx(), img.Bounds().Dy()
+ if !validDimensions(width, height) {
+ return 0, 0, ErrImageTooLarge
+ }
+ return width, height, nil
+}
+
+func decodeImage(source []byte) (img image.Image, err error) {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ img = nil
+ err = fmt.Errorf("decode HEIF image: %v", recovered)
+ }
+ }()
+
+ config, err := goheic.DecodeConfigBytes(source)
+ if err != nil {
+ return nil, fmt.Errorf("read HEIF image dimensions: %w", err)
+ }
+ if !validDimensions(config.Width, config.Height) {
+ return nil, ErrImageTooLarge
+ }
+
+ img, err = goheic.DecodeBytes(source, goheic.Options{
+ AutoRotate: true,
+ FrameSizeLimit: maxPixels,
+ Threads: 1,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("decode HEIF image: %w", err)
+ }
+ return img, nil
+}
+
+func validDimensions(width, height int) bool {
+ return width > 0 && height > 0 && width <= maxDimension && height <= maxDimension &&
+ uint64(width)*uint64(height) <= uint64(maxPixels)
+}
+
+func estimatedJPEGSize(img image.Image) int {
+ pixels := int64(img.Bounds().Dx()) * int64(img.Bounds().Dy())
+ estimate := pixels / 2
+ if estimate < 64*1024 {
+ estimate = 64 * 1024
+ }
+ if estimate > 32*1024*1024 {
+ estimate = 32 * 1024 * 1024
+ }
+ return int(estimate)
+}
diff --git a/kernel/heif/internal/h265heic/LICENSE b/kernel/heif/internal/h265heic/LICENSE
new file mode 100644
index 0000000000..91d5b9171a
--- /dev/null
+++ b/kernel/heif/internal/h265heic/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2025 roticv
+Copyright (c) 2026 Karpeles Lab Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/kernel/heif/internal/h265heic/README.md b/kernel/heif/internal/h265heic/README.md
new file mode 100644
index 0000000000..d8debdfb16
--- /dev/null
+++ b/kernel/heif/internal/h265heic/README.md
@@ -0,0 +1,7 @@
+# h265heic
+
+本目录派生自 `github.com/gen2brain/h265/heic` v0.1.1,用于 SiYuan 的受限 HEIF 静态图像预览。代码保留上游 MIT 许可证,并在容器、参数集、NAL、网格、单帧、累计编码数据和解码内存层增加资源边界。
+
+该适配层只接受 `hvc1`、单个 IDR VCL NAL、最高 10-bit 4:2:0 或单色且不含透明辅助图的静态图像,单个容器和累计实际解码数据均不得超过 32 MiB,不支持 HEIF 序列。若扩展到多 slice、CRA、非 IDR、透明辅助图或序列,必须先为底层 HEVC 解码器增加对应的累计工作量和总 DPB 资源上限。
+
+上游的 MIT 许可证不授予 HEVC 编解码相关专利权;发布包含该解码器的二进制前,应单独确认目标分发地区和使用方式所需的专利许可。
diff --git a/kernel/heif/internal/h265heic/color.go b/kernel/heif/internal/h265heic/color.go
new file mode 100644
index 0000000000..f7c94801f7
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color.go
@@ -0,0 +1,435 @@
+package heic
+
+import (
+ "github.com/gen2brain/h265/hevc"
+)
+
+const (
+ mcIdentity = 0
+ mcBT709 = 1
+ mcUnspec = 2
+ mcFCC = 4
+ mcBT470BG = 5
+ mcBT601 = 6
+ mcSMPTE240 = 7
+ mcYCgCo = 8
+ mcBT2020NCL = 9
+)
+
+func yuvCoefficients(matrix int) (float32, float32, float32) {
+ kr, kb := float32(0.299), float32(0.114)
+
+ switch matrix {
+ case mcBT709:
+ kr, kb = 0.2126, 0.0722
+ case mcFCC:
+ kr, kb = 0.30, 0.11
+ case mcBT470BG, mcBT601:
+ kr, kb = 0.299, 0.114
+ case mcSMPTE240:
+ kr, kb = 0.212, 0.087
+ case mcBT2020NCL:
+ kr, kb = 0.2627, 0.0593
+ }
+
+ return kr, 1 - kr - kb, kb
+}
+
+// planeView is one plane of a decoded picture with the conformance window
+// already applied, so the rest of this package never sees the crop.
+type planeView struct {
+ p8 []uint8
+ p16 []uint16
+ stride int
+ w, h int
+}
+
+func (v planeView) valid() bool { return v.p8 != nil || v.p16 != nil }
+
+func viewOf(p8 []uint8, p16 []uint16, stride, x, y, w, h int) planeView {
+ v := planeView{stride: stride, w: w, h: h}
+
+ off := y*stride + x
+ if p16 != nil {
+ v.p16 = p16[off:]
+ } else if p8 != nil {
+ v.p8 = p8[off:]
+ }
+
+ return v
+}
+
+// views returns the luma and chroma planes of pic, cropped to the conformance
+// window. Chroma is empty for monochrome.
+func views(pic *hevc.Picture) (y, cb, cr planeView) {
+ cw, ch := pic.CropW, pic.CropH
+ sw, sh := 1, 1
+
+ switch pic.ChromaFormat {
+ case 1:
+ sw, sh = 2, 2
+ case 2:
+ sw = 2
+ }
+
+ y = viewOf(pic.Y, pic.Y16, pic.StrideY, pic.CropX, pic.CropY, cw, ch)
+
+ if pic.ChromaFormat == 0 {
+ return y, cb, cr
+ }
+
+ ux, uy := pic.CropX/sw, pic.CropY/sh
+ uw, uh := (cw+sw-1)/sw, (ch+sh-1)/sh
+
+ cb = viewOf(pic.Cb, pic.Cb16, pic.StrideC, ux, uy, uw, uh)
+ cr = viewOf(pic.Cr, pic.Cr16, pic.StrideC, ux, uy, uw, uh)
+
+ return y, cb, cr
+}
+
+type colorState struct {
+ matrix int
+ fullRange bool
+ depth int
+ maxChannel int
+ outMax float32
+
+ kr, kg, kb float32
+ crCoef, cbCoef float32
+ gcr, gcb float32
+
+ tableY []float32
+ tableUV []float32
+ pixLUT []uint16
+
+ biasY, rangeY float32
+ biasUV, rangeUV float32
+
+ ssHor, ssVer int
+ hasColor bool
+ unsupported bool
+
+ uvIdx, uvAdj []int
+ yRow []uint16
+ uRow, vRow [2][]uint16
+ cbRow, crRow []float32
+
+ yf []float32
+ uPad, vPad [2][]float32
+ row convertRow
+ row16 convertRow16
+ consts rowConsts
+}
+
+func newColorState(pic *hevc.Picture, ci ColorInfo, outDepth int) *colorState {
+ s := &colorState{
+ matrix: int(ci.Matrix),
+ fullRange: ci.FullRange,
+ depth: pic.BitDepth,
+ }
+
+ if s.matrix == mcUnspec {
+ s.matrix = mcBT601
+ }
+
+ s.maxChannel = 1<<s.depth - 1
+ s.outMax = float32(int(1)<<outDepth - 1)
+ s.hasColor = pic.ChromaFormat != 0
+
+ switch pic.ChromaFormat {
+ case 1:
+ s.ssHor, s.ssVer = 1, 1
+ case 2:
+ s.ssHor = 1
+ }
+
+ s.kr, s.kg, s.kb = yuvCoefficients(s.matrix)
+
+ switch s.matrix {
+ case mcIdentity:
+ if pic.ChromaFormat != 3 && pic.ChromaFormat != 0 {
+ s.unsupported = true
+ }
+ case mcYCgCo:
+ if !s.fullRange {
+ s.unsupported = true
+ }
+ case 3, 10, 11, 12, 13, 14:
+ s.unsupported = true
+ }
+
+ shift := s.depth - 8
+
+ biasY, rangeY := float32(0), float32(s.maxChannel)
+ if !s.fullRange {
+ biasY = float32(int(16) << shift)
+ rangeY = float32(int(219) << shift)
+ }
+
+ biasUV := float32(int(1) << (s.depth - 1))
+ rangeUV := float32(s.maxChannel)
+
+ if !s.fullRange {
+ rangeUV = float32(int(224) << shift)
+ }
+
+ s.biasY, s.rangeY = biasY, rangeY
+ s.biasUV, s.rangeUV = biasUV, rangeUV
+
+ n := 1 << s.depth
+
+ s.tableY = make([]float32, n)
+ for i := range n {
+ s.tableY[i] = (float32(i) - biasY) / rangeY
+ }
+
+ if s.matrix == mcIdentity {
+ s.tableUV = s.tableY
+ } else {
+ s.tableUV = make([]float32, n)
+ for i := range n {
+ s.tableUV[i] = (float32(i) - biasUV) / rangeUV
+ }
+ }
+
+ s.derive()
+
+ return s
+}
+
+// alphaState is the luma-only conversion an alpha auxiliary item needs.
+func alphaState(pic *hevc.Picture, outDepth int, full bool) *colorState {
+ s := &colorState{
+ depth: pic.BitDepth,
+ maxChannel: 1<<pic.BitDepth - 1,
+ outMax: float32(int(1)<<outDepth - 1),
+ }
+
+ shift := s.depth - 8
+
+ bias, rng := float32(0), float32(s.maxChannel)
+ if !full {
+ bias, rng = float32(int(16)<<shift), float32(int(219)<<shift)
+ }
+
+ s.biasY, s.rangeY = bias, rng
+
+ n := 1 << s.depth
+
+ s.tableY = make([]float32, n)
+ for i := range n {
+ s.tableY[i] = (float32(i) - bias) / rng
+ }
+
+ s.tableUV = s.tableY
+ s.derive()
+
+ return s
+}
+
+func (s *colorState) derive() {
+ s.pixLUT = make([]uint16, len(s.tableY))
+ for i, v := range s.tableY {
+ s.pixLUT[i] = uint16(0.5 + clampF(v)*s.outMax)
+ }
+
+ s.crCoef, s.cbCoef = 2*(1-s.kr), 2*(1-s.kb)
+ s.gcr, s.gcb = s.kr*(1-s.kr), s.kb*(1-s.kb)
+}
+
+func clampF(v float32) float32 {
+ if v < 0 {
+ return 0
+ }
+
+ if v > 1 {
+ return 1
+ }
+
+ return v
+}
+
+// prepare sizes the row scratch and precomputes the chroma sample each output
+// column interpolates against.
+func (s *colorState) prepare(w int) {
+ uw := (w + s.ssHor) >> s.ssHor
+
+ s.yRow = make([]uint16, w)
+
+ for i := range s.uRow {
+ s.uRow[i] = make([]uint16, uw)
+ s.vRow[i] = make([]uint16, uw)
+ }
+
+ s.cbRow = make([]float32, w)
+ s.crRow = make([]float32, w)
+
+ s.yf = make([]float32, w)
+
+ for i := range s.uPad {
+ s.uPad[i] = make([]float32, uw+2)
+ s.vPad[i] = make([]float32, uw+2)
+ }
+
+ s.uvIdx = make([]int, w)
+ s.uvAdj = make([]int, w)
+
+ for x := range w {
+ uvX := x >> s.ssHor
+ adj := 0
+
+ if x != 0 && !(x == w-1 && x%2 != 0) {
+ if x%2 != 0 {
+ adj = 1
+ } else {
+ adj = -1
+ }
+ }
+
+ s.uvIdx[x] = uvX
+ s.uvAdj[x] = min(max(uvX+adj, 0), uw-1)
+ }
+}
+
+// fillRow copies one row of a plane into 16-bit scratch, which lets the LUTs
+// be indexed the same way at every bit depth.
+func (s *colorState) fillRow(v planeView, y, n int, dst []uint16) {
+ dst = dst[:n]
+
+ if v.p16 != nil {
+ row := v.p16[y*v.stride:]
+ maxCh := uint16(s.maxChannel)
+
+ for i := range dst {
+ dst[i] = min(row[i], maxCh)
+ }
+
+ return
+ }
+
+ row := v.p8[y*v.stride : y*v.stride+n]
+ for i, c := range row {
+ dst[i] = uint16(c)
+ }
+}
+
+func (s *colorState) lumaRow(v planeView, y, w int) []uint16 {
+ s.fillRow(v, y, w, s.yRow)
+
+ return s.yRow
+}
+
+// chromaRow expands one row of Cb and Cr to full width. 4:2:0 interpolates
+// with the 9/3/3/1 weights libavif uses, so both packages upsample alike.
+func (s *colorState) chromaRow(cb, cr planeView, y, w, h int) {
+ uvY := y >> s.ssVer
+ uw := (w + s.ssHor) >> s.ssHor
+
+ s.fillRow(cb, uvY, uw, s.uRow[0])
+ s.fillRow(cr, uvY, uw, s.vRow[0])
+
+ tab := s.tableUV
+ cbRow, crRow := s.cbRow[:w], s.crRow[:w]
+
+ if s.ssHor == 0 {
+ u, v := s.uRow[0][:w], s.vRow[0][:w]
+
+ for x := range cbRow {
+ cbRow[x] = tab[u[x]]
+ crRow[x] = tab[v[x]]
+ }
+
+ return
+ }
+
+ adjRow := 0
+ if s.ssVer != 0 && y != 0 && !(y == h-1 && y%2 != 0) {
+ if y%2 != 0 {
+ adjRow = 1
+ } else {
+ adjRow = -1
+ }
+ }
+
+ u1, v1 := s.uRow[0], s.vRow[0]
+
+ if adjRow != 0 {
+ ay := min(max(uvY+adjRow, 0), cb.h-1)
+
+ s.fillRow(cb, ay, uw, s.uRow[1])
+ s.fillRow(cr, ay, uw, s.vRow[1])
+
+ u1, v1 = s.uRow[1], s.vRow[1]
+ }
+
+ const w0, w1, w2, w3 = 9.0 / 16.0, 3.0 / 16.0, 3.0 / 16.0, 1.0 / 16.0
+
+ u0, v0 := s.uRow[0], s.vRow[0]
+
+ for x := range w {
+ i, j := s.uvIdx[x], s.uvAdj[x]
+
+ cbRow[x] = w0*tab[u0[i]] + w1*tab[u0[j]] + w2*tab[u1[i]] + w3*tab[u1[j]]
+ crRow[x] = w0*tab[v0[i]] + w1*tab[v0[j]] + w2*tab[v1[i]] + w3*tab[v1[j]]
+ }
+}
+
+// rgbRow converts one row to RGB at the output depth.
+func (s *colorState) rgbRow(y, cb, cr planeView, row int, dst []uint16) {
+ w := y.w
+ luma := s.lumaRow(y, row, w)
+
+ if !s.hasColor {
+ for x := range w {
+ v := s.pixLUT[luma[x]]
+ dst[3*x], dst[3*x+1], dst[3*x+2] = v, v, v
+ }
+
+ return
+ }
+
+ s.chromaRow(cb, cr, row, w, y.h)
+
+ tab := s.tableY
+ cbf, crf := s.cbRow, s.crRow
+
+ switch s.matrix {
+ case mcIdentity:
+ for x := range w {
+ g, b, r := tab[luma[x]], cbf[x], crf[x]
+ s.store(dst[3*x:], r, g, b)
+ }
+
+ case mcYCgCo:
+ for x := range w {
+ yv, cg, co := tab[luma[x]], cbf[x], crf[x]
+ t := yv - cg
+ s.store(dst[3*x:], t+co, yv+cg, t-co)
+ }
+
+ default:
+ for x := range w {
+ yv, u, v := tab[luma[x]], cbf[x], crf[x]
+
+ r := yv + s.crCoef*v
+ b := yv + s.cbCoef*u
+ g := yv - (s.gcr*v+s.gcb*u)*2/s.kg
+
+ s.store(dst[3*x:], r, g, b)
+ }
+ }
+}
+
+func (s *colorState) store(dst []uint16, r, g, b float32) {
+ dst[0] = uint16(0.5 + clampF(r)*s.outMax)
+ dst[1] = uint16(0.5 + clampF(g)*s.outMax)
+ dst[2] = uint16(0.5 + clampF(b)*s.outMax)
+}
+
+func (s *colorState) alphaRow(v planeView, row, w int, dst []uint16) {
+ luma := s.lumaRow(v, row, w)
+
+ for x := range w {
+ dst[x] = s.pixLUT[luma[x]]
+ }
+}
diff --git a/kernel/heif/internal/h265heic/color_amd64.go b/kernel/heif/internal/h265heic/color_amd64.go
new file mode 100644
index 0000000000..9ba29fe064
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_amd64.go
@@ -0,0 +1,126 @@
+//go:build amd64 && !noasm
+
+package heic
+
+//go:noescape
+func convertRow8AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+
+//go:noescape
+func convertRow444AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+
+func rowFn(ssHor int) convertRow {
+ if ssHor == 0 {
+ if !hasAVX2 {
+ return convertRow444Go
+ }
+
+ return convertRow444AVX2Row
+ }
+ if !hasAVX2 {
+ return convertRowGo
+ }
+
+ return convertRowAVX2
+}
+
+func convertRow444AVX2Row(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ if n8 := n &^ 7; n8 > 0 {
+ convertRow444AVX2(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n8, c)
+ if n8 == n {
+ return
+ }
+ dst, yf, a, n = dst[4*n8:], yf[n8:], a[n8:], n-n8
+ u0, u1, v0, v1 = u0[n8:], u1[n8:], v0[n8:], v1[n8:]
+ }
+
+ convertRow444Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+func convertRowAVX2(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ if n8 := n &^ 7; n8 > 0 {
+ convertRow8AVX2(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n8, c)
+ if n8 == n {
+ return
+ }
+ dst, yf, a, n = dst[4*n8:], yf[n8:], a[n8:], n-n8
+ u0, u1 = u0[n8/2:], u1[n8/2:]
+ v0, v1 = v0[n8/2:], v1[n8/2:]
+ }
+
+ convertRowGo(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+//go:noescape
+func convertRow16x8AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+
+//go:noescape
+func convertRow16x444AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+
+func rowFn16(ssHor int) convertRow16 {
+ if ssHor == 0 {
+ if !hasAVX2 {
+ return convertRow16x444Go
+ }
+
+ return convertRow16x444AVX2Row
+ }
+ if !hasAVX2 {
+ return convertRow16Go
+ }
+
+ return convertRow16AVX2
+}
+
+func convertRow16x444AVX2Row(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ if n8 := n &^ 7; n8 > 0 {
+ convertRow16x444AVX2(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n8, c)
+ if n8 == n {
+ return
+ }
+ dst, yf, a, n = dst[8*n8:], yf[n8:], a[n8:], n-n8
+ u0, u1, v0, v1 = u0[n8:], u1[n8:], v0[n8:], v1[n8:]
+ }
+
+ convertRow16x444Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+func convertRow16AVX2(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ if n8 := n &^ 7; n8 > 0 {
+ convertRow16x8AVX2(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n8, c)
+ if n8 == n {
+ return
+ }
+ dst, yf, a, n = dst[8*n8:], yf[n8:], a[n8:], n-n8
+ u0, u1 = u0[n8/2:], u1[n8/2:]
+ v0, v1 = v0[n8/2:], v1[n8/2:]
+ }
+
+ convertRow16Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+//go:noescape
+func normRow8AVX2(dst *float32, src *uint8, n int, bias, rng float32)
+
+func normRow(dst []float32, src []uint8, bias, rng float32) {
+ if n8 := len(dst) &^ 7; hasAVX2 && n8 > 0 {
+ normRow8AVX2(&dst[0], &src[0], n8, bias, rng)
+ if n8 == len(dst) {
+ return
+ }
+ dst, src = dst[n8:], src[n8:]
+ }
+
+ normRowGo(dst, src, bias, rng)
+}
+
+func normRow16(dst []float32, src []uint16, maxCh uint16, bias, rng float32) {
+ normRow16Go(dst, src, maxCh, bias, rng)
+}
diff --git a/kernel/heif/internal/h265heic/color_amd64.s b/kernel/heif/internal/h265heic/color_amd64.s
new file mode 100644
index 0000000000..45801fe133
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_amd64.s
@@ -0,0 +1,214 @@
+//go:build amd64 && !noasm
+
+#include "textflag.h"
+
+DATA rowPermC<>+0(SB)/8, $0x0000000100000001
+DATA rowPermC<>+8(SB)/8, $0x0000000200000002
+DATA rowPermC<>+16(SB)/8, $0x0000000300000003
+DATA rowPermC<>+24(SB)/8, $0x0000000400000004
+GLOBL rowPermC<>(SB), RODATA|NOPTR, $32
+
+DATA rowPermN<>+0(SB)/8, $0x0000000200000000
+DATA rowPermN<>+8(SB)/8, $0x0000000300000001
+DATA rowPermN<>+16(SB)/8, $0x0000000400000002
+DATA rowPermN<>+24(SB)/8, $0x0000000500000003
+GLOBL rowPermN<>(SB), RODATA|NOPTR, $32
+
+DATA rowShuf<>+0(SB)/8, $0x0d0905010c080400
+DATA rowShuf<>+8(SB)/8, $0x0f0b07030e0a0602
+GLOBL rowShuf<>(SB), RODATA|NOPTR, $16
+
+#define CHROMA(P0, P1, OUT) \
+ VMOVUPS (P0), Y3; \
+ VPERMPS Y3, Y13, Y4; \
+ VPERMPS Y3, Y14, Y5; \
+ VMULPS Y8, Y4, OUT; \
+ VMULPS Y9, Y5, Y5; \
+ VADDPS Y5, OUT, OUT; \
+ VMOVUPS (P1), Y3; \
+ VPERMPS Y3, Y13, Y4; \
+ VPERMPS Y3, Y14, Y5; \
+ VMULPS Y9, Y4, Y4; \
+ VADDPS Y4, OUT, OUT; \
+ VMULPS Y10, Y5, Y5; \
+ VADDPS Y5, OUT, OUT
+
+#define CHROMA444(P0, P1, OUT) \
+ VMOVUPS 4(P0), OUT
+
+#define PIXEL(V) \
+ VMAXPS Y1, V, V; \
+ VMINPS Y2, V, V; \
+ VMULPS Y6, V, V; \
+ VADDPS Y7, V, V; \
+ VCVTTPS2DQ V, V
+
+DATA rowSwap<>+0(SB)/8, $0x0607040502030001
+DATA rowSwap<>+8(SB)/8, $0x0e0f0c0d0a0b0809
+GLOBL rowSwap<>(SB), RODATA|NOPTR, $16
+
+#define ROW8(CH, UVSTEP) \
+ MOVQ dst+0(FP), DI; \
+ MOVQ yf+8(FP), SI; \
+ MOVQ u0+16(FP), R8; \
+ MOVQ u1+24(FP), R9; \
+ MOVQ v0+32(FP), R10; \
+ MOVQ v1+40(FP), R11; \
+ MOVQ a+48(FP), R12; \
+ MOVQ n+56(FP), DX; \
+ MOVQ c+64(FP), CX; \
+ VBROADCASTSS 0(CX), Y8; \
+ VBROADCASTSS 4(CX), Y9; \
+ VBROADCASTSS 8(CX), Y10; \
+ VBROADCASTSS 12(CX), Y11; \
+ VBROADCASTSS 16(CX), Y12; \
+ VMOVDQU rowPermC<>(SB), Y13; \
+ VMOVDQU rowPermN<>(SB), Y14; \
+ VBROADCASTI128 rowShuf<>(SB), Y15; \
+loop:; \
+ VMOVUPS (SI), Y0; \
+ CH(R8, R9, Y1); \
+ CH(R10, R11, Y2); \
+ VMULPS Y11, Y2, Y3; \
+ VADDPS Y3, Y0, Y3; \
+ VMULPS Y12, Y1, Y4; \
+ VADDPS Y4, Y0, Y4; \
+ VBROADCASTSS 20(CX), Y5; \
+ VMULPS Y5, Y2, Y5; \
+ VBROADCASTSS 24(CX), Y6; \
+ VMULPS Y6, Y1, Y6; \
+ VADDPS Y6, Y5, Y5; \
+ VADDPS Y5, Y5, Y5; \
+ VBROADCASTSS 28(CX), Y6; \
+ VDIVPS Y6, Y5, Y5; \
+ VSUBPS Y5, Y0, Y5; \
+ VPXOR Y1, Y1, Y1; \
+ VBROADCASTSS 36(CX), Y2; \
+ VBROADCASTSS 32(CX), Y6; \
+ VBROADCASTSS 40(CX), Y7; \
+ PIXEL(Y3); \
+ PIXEL(Y5); \
+ PIXEL(Y4); \
+ VPMOVZXBD (R12), Y1; \
+ VPACKUSDW Y5, Y3, Y3; \
+ VPACKUSDW Y1, Y4, Y4; \
+ VPACKUSWB Y4, Y3, Y3; \
+ VPSHUFB Y15, Y3, Y3; \
+ VMOVDQU Y3, (DI); \
+ ADDQ $32, SI; \
+ ADDQ $UVSTEP, R8; \
+ ADDQ $UVSTEP, R9; \
+ ADDQ $UVSTEP, R10; \
+ ADDQ $UVSTEP, R11; \
+ ADDQ $8, R12; \
+ ADDQ $32, DI; \
+ SUBQ $8, DX; \
+ JNZ loop; \
+ VZEROUPPER
+
+#define ROW16(CH, UVSTEP) \
+ MOVQ dst+0(FP), DI; \
+ MOVQ yf+8(FP), SI; \
+ MOVQ u0+16(FP), R8; \
+ MOVQ u1+24(FP), R9; \
+ MOVQ v0+32(FP), R10; \
+ MOVQ v1+40(FP), R11; \
+ MOVQ a+48(FP), R12; \
+ MOVQ n+56(FP), DX; \
+ MOVQ c+64(FP), CX; \
+ VBROADCASTSS 0(CX), Y8; \
+ VBROADCASTSS 4(CX), Y9; \
+ VBROADCASTSS 8(CX), Y10; \
+ VBROADCASTSS 12(CX), Y11; \
+ VBROADCASTSS 16(CX), Y12; \
+ VMOVDQU rowPermC<>(SB), Y13; \
+ VMOVDQU rowPermN<>(SB), Y14; \
+ VBROADCASTI128 rowSwap<>(SB), Y15; \
+loop16:; \
+ VMOVUPS (SI), Y0; \
+ CH(R8, R9, Y1); \
+ CH(R10, R11, Y2); \
+ VMULPS Y11, Y2, Y3; \
+ VADDPS Y3, Y0, Y3; \
+ VMULPS Y12, Y1, Y4; \
+ VADDPS Y4, Y0, Y4; \
+ VBROADCASTSS 20(CX), Y5; \
+ VMULPS Y5, Y2, Y5; \
+ VBROADCASTSS 24(CX), Y6; \
+ VMULPS Y6, Y1, Y6; \
+ VADDPS Y6, Y5, Y5; \
+ VADDPS Y5, Y5, Y5; \
+ VBROADCASTSS 28(CX), Y6; \
+ VDIVPS Y6, Y5, Y5; \
+ VSUBPS Y5, Y0, Y5; \
+ VPXOR Y1, Y1, Y1; \
+ VBROADCASTSS 36(CX), Y2; \
+ VBROADCASTSS 32(CX), Y6; \
+ VBROADCASTSS 40(CX), Y7; \
+ PIXEL(Y3); \
+ PIXEL(Y5); \
+ PIXEL(Y4); \
+ VPMOVZXWD (R12), Y1; \
+ VPACKUSDW Y5, Y3, Y3; \
+ VPACKUSDW Y1, Y4, Y4; \
+ VPUNPCKLWD Y4, Y3, Y0; \
+ VPUNPCKHWD Y4, Y3, Y2; \
+ VPUNPCKLWD Y2, Y0, Y5; \
+ VPUNPCKHWD Y2, Y0, Y6; \
+ VPERM2I128 $0x20, Y6, Y5, Y7; \
+ VPERM2I128 $0x31, Y6, Y5, Y1; \
+ VPSHUFB Y15, Y7, Y7; \
+ VPSHUFB Y15, Y1, Y1; \
+ VMOVDQU Y7, (DI); \
+ VMOVDQU Y1, 32(DI); \
+ ADDQ $32, SI; \
+ ADDQ $UVSTEP, R8; \
+ ADDQ $UVSTEP, R9; \
+ ADDQ $UVSTEP, R10; \
+ ADDQ $UVSTEP, R11; \
+ ADDQ $16, R12; \
+ ADDQ $64, DI; \
+ SUBQ $8, DX; \
+ JNZ loop16; \
+ VZEROUPPER
+
+// func convertRow8AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+TEXT ·convertRow8AVX2(SB), NOSPLIT, $0-72
+ ROW8(CHROMA, 16)
+ RET
+
+// func convertRow444AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+TEXT ·convertRow444AVX2(SB), NOSPLIT, $0-72
+ ROW8(CHROMA444, 32)
+ RET
+
+// func convertRow16x8AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+TEXT ·convertRow16x8AVX2(SB), NOSPLIT, $0-72
+ ROW16(CHROMA, 16)
+ RET
+
+// func convertRow16x444AVX2(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+TEXT ·convertRow16x444AVX2(SB), NOSPLIT, $0-72
+ ROW16(CHROMA444, 32)
+ RET
+
+// func normRow8AVX2(dst *float32, src *uint8, n int, bias, rng float32)
+TEXT ·normRow8AVX2(SB), NOSPLIT, $0-32
+ MOVQ dst+0(FP), DI
+ MOVQ src+8(FP), SI
+ MOVQ n+16(FP), DX
+ VBROADCASTSS bias+24(FP), Y1
+ VBROADCASTSS rng+28(FP), Y2
+
+loop8:
+ VPMOVZXBD (SI), Y0
+ VCVTDQ2PS Y0, Y0
+ VSUBPS Y1, Y0, Y0
+ VDIVPS Y2, Y0, Y0
+ VMOVUPS Y0, (DI)
+ ADDQ $8, SI
+ ADDQ $32, DI
+ SUBQ $8, DX
+ JNZ loop8
+ VZEROUPPER
+ RET
diff --git a/kernel/heif/internal/h265heic/color_arm64.go b/kernel/heif/internal/h265heic/color_arm64.go
new file mode 100644
index 0000000000..d375136c35
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_arm64.go
@@ -0,0 +1,112 @@
+//go:build arm64 && !noasm
+
+package heic
+
+//go:noescape
+func convertRow4NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+
+//go:noescape
+func convertRow444NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+
+func rowFn(ssHor int) convertRow {
+ if ssHor == 0 {
+ return convertRow444NEONRow
+ }
+
+ return convertRowNEON
+}
+
+func convertRow444NEONRow(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ if n4 := n &^ 3; n4 > 0 {
+ convertRow444NEON(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n4, c)
+ if n4 == n {
+ return
+ }
+ dst, yf, a, n = dst[4*n4:], yf[n4:], a[n4:], n-n4
+ u0, u1, v0, v1 = u0[n4:], u1[n4:], v0[n4:], v1[n4:]
+ }
+
+ convertRow444Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+func convertRowNEON(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ if n4 := n &^ 3; n4 > 0 {
+ convertRow4NEON(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n4, c)
+ if n4 == n {
+ return
+ }
+ dst, yf, a, n = dst[4*n4:], yf[n4:], a[n4:], n-n4
+ u0, u1 = u0[n4/2:], u1[n4/2:]
+ v0, v1 = v0[n4/2:], v1[n4/2:]
+ }
+
+ convertRowGo(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+//go:noescape
+func convertRow16x4NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+
+//go:noescape
+func convertRow16x444NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+
+func rowFn16(ssHor int) convertRow16 {
+ if ssHor == 0 {
+ return convertRow16x444NEONRow
+ }
+
+ return convertRow16NEON
+}
+
+func convertRow16x444NEONRow(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ if n4 := n &^ 3; n4 > 0 {
+ convertRow16x444NEON(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n4, c)
+ if n4 == n {
+ return
+ }
+ dst, yf, a, n = dst[8*n4:], yf[n4:], a[n4:], n-n4
+ u0, u1, v0, v1 = u0[n4:], u1[n4:], v0[n4:], v1[n4:]
+ }
+
+ convertRow16x444Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+func convertRow16NEON(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ if n4 := n &^ 3; n4 > 0 {
+ convertRow16x4NEON(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n4, c)
+ if n4 == n {
+ return
+ }
+ dst, yf, a, n = dst[8*n4:], yf[n4:], a[n4:], n-n4
+ u0, u1 = u0[n4/2:], u1[n4/2:]
+ v0, v1 = v0[n4/2:], v1[n4/2:]
+ }
+
+ convertRow16Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+//go:noescape
+func normRow8NEON(dst *float32, src *uint8, n int, bias, rng float32)
+
+func normRow(dst []float32, src []uint8, bias, rng float32) {
+ if n8 := len(dst) &^ 7; n8 > 0 {
+ normRow8NEON(&dst[0], &src[0], n8, bias, rng)
+ if n8 == len(dst) {
+ return
+ }
+ dst, src = dst[n8:], src[n8:]
+ }
+
+ normRowGo(dst, src, bias, rng)
+}
+
+func normRow16(dst []float32, src []uint16, maxCh uint16, bias, rng float32) {
+ normRow16Go(dst, src, maxCh, bias, rng)
+}
diff --git a/kernel/heif/internal/h265heic/color_arm64.s b/kernel/heif/internal/h265heic/color_arm64.s
new file mode 100644
index 0000000000..3f82d4972e
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_arm64.s
@@ -0,0 +1,259 @@
+//go:build arm64 && !noasm
+
+#include "textflag.h"
+
+#define FMUL(Vd, Vn, Vm) WORD $(0x6E20DC00 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+#define FADD(Vd, Vn, Vm) WORD $(0x4E20D400 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+#define FSUB(Vd, Vn, Vm) WORD $(0x4EA0D400 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+#define FDIV(Vd, Vn, Vm) WORD $(0x6E20FC00 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+#define FMAX(Vd, Vn, Vm) WORD $(0x4E20F400 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+#define FMIN(Vd, Vn, Vm) WORD $(0x4EA0F400 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+#define FCVTZS(Vd, Vn) WORD $(0x4EA1B800 | ((Vn) << 5) | (Vd))
+
+DATA rowSelC<>+0(SB)/8, $0x0706050407060504
+DATA rowSelC<>+8(SB)/8, $0x0b0a09080b0a0908
+GLOBL rowSelC<>(SB), RODATA|NOPTR, $16
+
+DATA rowSelN<>+0(SB)/8, $0x0b0a090803020100
+DATA rowSelN<>+8(SB)/8, $0x0f0e0d0c07060504
+GLOBL rowSelN<>(SB), RODATA|NOPTR, $16
+
+DATA rowSelP<>+0(SB)/8, $0x3424140430201000
+DATA rowSelP<>+8(SB)/8, $0x3c2c1c0c38281808
+GLOBL rowSelP<>(SB), RODATA|NOPTR, $16
+
+#define CHROMA(P0, P1, OUT, VOUT) \
+ VLD1 (P0), [V4.S4]; \
+ VTBL V16.B16, [V4.B16], V5.B16; \
+ VTBL V17.B16, [V4.B16], V6.B16; \
+ FMUL(OUT, 5, 20); \
+ FMUL(6, 6, 21); \
+ FADD(OUT, OUT, 6); \
+ VLD1 (P1), [V4.S4]; \
+ VTBL V16.B16, [V4.B16], V5.B16; \
+ VTBL V17.B16, [V4.B16], V6.B16; \
+ FMUL(5, 5, 21); \
+ FADD(OUT, OUT, 5); \
+ FMUL(6, 6, 22); \
+ FADD(OUT, OUT, 6)
+
+#define CHROMA444(P0, P1, OUT, VOUT) \
+ ADD $4, P0, R9; \
+ VLD1 (R9), [VOUT]
+
+#define PIXEL(V) \
+ FMAX(V, V, 24); \
+ FMIN(V, V, 25); \
+ FMUL(V, V, 26); \
+ FADD(V, V, 27); \
+ FCVTZS(V, V)
+
+#define ROW8(CH, UVSTEP) \
+ MOVD dst+0(FP), R0; \
+ MOVD yf+8(FP), R1; \
+ MOVD u0+16(FP), R2; \
+ MOVD u1+24(FP), R3; \
+ MOVD v0+32(FP), R4; \
+ MOVD v1+40(FP), R5; \
+ MOVD a+48(FP), R6; \
+ MOVD n+56(FP), R7; \
+ MOVD c+64(FP), R8; \
+ MOVD $rowSelC<>(SB), R9; \
+ VLD1 (R9), [V16.B16]; \
+ MOVD $rowSelN<>(SB), R9; \
+ VLD1 (R9), [V17.B16]; \
+ MOVD $rowSelP<>(SB), R9; \
+ VLD1 (R9), [V18.B16]; \
+ MOVW 0(R8), R9; \
+ VDUP R9, V20.S4; \
+ MOVW 4(R8), R9; \
+ VDUP R9, V21.S4; \
+ MOVW 8(R8), R9; \
+ VDUP R9, V22.S4; \
+ MOVW 12(R8), R9; \
+ VDUP R9, V23.S4; \
+ MOVW 16(R8), R9; \
+ VDUP R9, V28.S4; \
+ MOVW 20(R8), R9; \
+ VDUP R9, V29.S4; \
+ MOVW 24(R8), R9; \
+ VDUP R9, V30.S4; \
+ MOVW 28(R8), R9; \
+ VDUP R9, V31.S4; \
+ MOVW 32(R8), R9; \
+ VDUP R9, V26.S4; \
+ MOVW 36(R8), R9; \
+ VDUP R9, V25.S4; \
+ MOVW 40(R8), R9; \
+ VDUP R9, V27.S4; \
+ VEOR V24.B16, V24.B16, V24.B16; \
+loop: \
+ VLD1 (R1), [V0.S4]; \
+ CH(R2, R3, 1, V1.S4); \
+ CH(R4, R5, 2, V2.S4); \
+ FMUL(7, 2, 23); \
+ FADD(7, 0, 7); \
+ FMUL(8, 1, 28); \
+ FADD(8, 0, 8); \
+ FMUL(9, 2, 29); \
+ FMUL(10, 1, 30); \
+ FADD(9, 9, 10); \
+ FADD(9, 9, 9); \
+ FDIV(9, 9, 31); \
+ FSUB(9, 0, 9); \
+ PIXEL(7); \
+ PIXEL(9); \
+ PIXEL(8); \
+ VLD1 (R6), [V10.B8]; \
+ VUSHLL $0, V10.B8, V10.H8; \
+ VUSHLL $0, V10.H4, V10.S4; \
+ VMOV V7.B16, V12.B16; \
+ VMOV V9.B16, V13.B16; \
+ VMOV V8.B16, V14.B16; \
+ VMOV V10.B16, V15.B16; \
+ VTBL V18.B16, [V12.B16, V13.B16, V14.B16, V15.B16], V11.B16; \
+ VST1 [V11.B16], (R0); \
+ ADD $16, R1; \
+ ADD $UVSTEP, R2; \
+ ADD $UVSTEP, R3; \
+ ADD $UVSTEP, R4; \
+ ADD $UVSTEP, R5; \
+ ADD $4, R6; \
+ ADD $16, R0; \
+ SUB $4, R7; \
+ CBNZ R7, loop
+
+#define ROW16(CH, UVSTEP) \
+ MOVD dst+0(FP), R0; \
+ MOVD yf+8(FP), R1; \
+ MOVD u0+16(FP), R2; \
+ MOVD u1+24(FP), R3; \
+ MOVD v0+32(FP), R4; \
+ MOVD v1+40(FP), R5; \
+ MOVD a+48(FP), R6; \
+ MOVD n+56(FP), R7; \
+ MOVD c+64(FP), R8; \
+ MOVD $rowSelC<>(SB), R9; \
+ VLD1 (R9), [V16.B16]; \
+ MOVD $rowSelN<>(SB), R9; \
+ VLD1 (R9), [V17.B16]; \
+ MOVD $rowSelD<>(SB), R9; \
+ VLD1 (R9), [V18.B16]; \
+ MOVD $rowSelE<>(SB), R9; \
+ VLD1 (R9), [V19.B16]; \
+ MOVW 0(R8), R9; \
+ VDUP R9, V20.S4; \
+ MOVW 4(R8), R9; \
+ VDUP R9, V21.S4; \
+ MOVW 8(R8), R9; \
+ VDUP R9, V22.S4; \
+ MOVW 12(R8), R9; \
+ VDUP R9, V23.S4; \
+ MOVW 16(R8), R9; \
+ VDUP R9, V28.S4; \
+ MOVW 20(R8), R9; \
+ VDUP R9, V29.S4; \
+ MOVW 24(R8), R9; \
+ VDUP R9, V30.S4; \
+ MOVW 28(R8), R9; \
+ VDUP R9, V31.S4; \
+ MOVW 32(R8), R9; \
+ VDUP R9, V26.S4; \
+ MOVW 36(R8), R9; \
+ VDUP R9, V25.S4; \
+ MOVW 40(R8), R9; \
+ VDUP R9, V27.S4; \
+ VEOR V24.B16, V24.B16, V24.B16; \
+loop16: \
+ VLD1 (R1), [V0.S4]; \
+ CH(R2, R3, 1, V1.S4); \
+ CH(R4, R5, 2, V2.S4); \
+ FMUL(7, 2, 23); \
+ FADD(7, 0, 7); \
+ FMUL(8, 1, 28); \
+ FADD(8, 0, 8); \
+ FMUL(9, 2, 29); \
+ FMUL(10, 1, 30); \
+ FADD(9, 9, 10); \
+ FADD(9, 9, 9); \
+ FDIV(9, 9, 31); \
+ FSUB(9, 0, 9); \
+ PIXEL(7); \
+ PIXEL(9); \
+ PIXEL(8); \
+ VLD1 (R6), [V10.H4]; \
+ VUSHLL $0, V10.H4, V10.S4; \
+ VMOV V7.B16, V12.B16; \
+ VMOV V9.B16, V13.B16; \
+ VMOV V8.B16, V14.B16; \
+ VMOV V10.B16, V15.B16; \
+ VTBL V18.B16, [V12.B16, V13.B16, V14.B16, V15.B16], V11.B16; \
+ VST1.P [V11.B16], 16(R0); \
+ VTBL V19.B16, [V12.B16, V13.B16, V14.B16, V15.B16], V11.B16; \
+ VST1.P [V11.B16], 16(R0); \
+ ADD $16, R1; \
+ ADD $UVSTEP, R2; \
+ ADD $UVSTEP, R3; \
+ ADD $UVSTEP, R4; \
+ ADD $UVSTEP, R5; \
+ ADD $8, R6; \
+ SUB $4, R7; \
+ CBNZ R7, loop16
+
+DATA rowSelD<>+0(SB)/8, $0x3031202110110001
+DATA rowSelD<>+8(SB)/8, $0x3435242514150405
+GLOBL rowSelD<>(SB), RODATA|NOPTR, $16
+
+DATA rowSelE<>+0(SB)/8, $0x3839282918190809
+DATA rowSelE<>+8(SB)/8, $0x3c3d2c2d1c1d0c0d
+GLOBL rowSelE<>(SB), RODATA|NOPTR, $16
+
+// func convertRow4NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+TEXT ·convertRow4NEON(SB), NOSPLIT, $0-72
+ ROW8(CHROMA, 8)
+ RET
+
+// func convertRow444NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+TEXT ·convertRow444NEON(SB), NOSPLIT, $0-72
+ ROW8(CHROMA444, 16)
+ RET
+
+// func convertRow16x4NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+TEXT ·convertRow16x4NEON(SB), NOSPLIT, $0-72
+ ROW16(CHROMA, 8)
+ RET
+
+// func convertRow16x444NEON(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+TEXT ·convertRow16x444NEON(SB), NOSPLIT, $0-72
+ ROW16(CHROMA444, 16)
+ RET
+
+#define UCVTF(Vd, Vn) WORD $(0x6E21D800 | ((Vn) << 5) | (Vd))
+#define UMINH(Vd, Vn, Vm) WORD $(0x6E606C00 | ((Vm) << 16) | ((Vn) << 5) | (Vd))
+
+// func normRow8NEON(dst *float32, src *uint8, n int, bias, rng float32)
+TEXT ·normRow8NEON(SB), NOSPLIT, $0-32
+ MOVD dst+0(FP), R0
+ MOVD src+8(FP), R1
+ MOVD n+16(FP), R2
+ MOVW bias+24(FP), R3
+ VDUP R3, V1.S4
+ MOVW rng+28(FP), R3
+ VDUP R3, V2.S4
+
+loop8:
+ VLD1.P 8(R1), [V0.B8]
+ VUSHLL $0, V0.B8, V0.H8
+ VUSHLL $0, V0.H4, V3.S4
+ VUSHLL2 $0, V0.H8, V4.S4
+ UCVTF(3, 3)
+ UCVTF(4, 4)
+ FSUB(3, 3, 1)
+ FSUB(4, 4, 1)
+ FDIV(3, 3, 2)
+ FDIV(4, 4, 2)
+ VST1.P [V3.S4, V4.S4], 32(R0)
+ SUB $8, R2
+ CBNZ R2, loop8
+
+ RET
diff --git a/kernel/heif/internal/h265heic/color_noasm.go b/kernel/heif/internal/h265heic/color_noasm.go
new file mode 100644
index 0000000000..ccc35eba71
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_noasm.go
@@ -0,0 +1,27 @@
+//go:build noasm || (!amd64 && !arm64 && !(riscv64 && riscv64.rva23u64))
+
+package heic
+
+func rowFn(ssHor int) convertRow {
+ if ssHor == 0 {
+ return convertRow444Go
+ }
+
+ return convertRowGo
+}
+
+func rowFn16(ssHor int) convertRow16 {
+ if ssHor == 0 {
+ return convertRow16x444Go
+ }
+
+ return convertRow16Go
+}
+
+func normRow(dst []float32, src []uint8, bias, rng float32) {
+ normRowGo(dst, src, bias, rng)
+}
+
+func normRow16(dst []float32, src []uint16, maxCh uint16, bias, rng float32) {
+ normRow16Go(dst, src, maxCh, bias, rng)
+}
diff --git a/kernel/heif/internal/h265heic/color_riscv64.go b/kernel/heif/internal/h265heic/color_riscv64.go
new file mode 100644
index 0000000000..9595388480
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_riscv64.go
@@ -0,0 +1,92 @@
+//go:build riscv64 && riscv64.rva23u64 && !noasm
+
+package heic
+
+//go:noescape
+func convertRowRVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+
+//go:noescape
+func convertRow444RVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+
+func rowFn(ssHor int) convertRow {
+ if ssHor == 0 {
+ return convertRow444Vec
+ }
+
+ return convertRowVec
+}
+
+func convertRow444Vec(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ if n > 0 {
+ convertRow444RVV(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n, c)
+ }
+}
+
+func convertRowVec(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ if n4 := n &^ 3; n4 > 0 {
+ convertRowRVV(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n4, c)
+ if n4 == n {
+ return
+ }
+ dst, yf, a, n = dst[4*n4:], yf[n4:], a[n4:], n-n4
+ u0, u1 = u0[n4/2:], u1[n4/2:]
+ v0, v1 = v0[n4/2:], v1[n4/2:]
+ }
+
+ convertRowGo(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+//go:noescape
+func convertRow16RVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+
+//go:noescape
+func convertRow16x444RVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+
+func rowFn16(ssHor int) convertRow16 {
+ if ssHor == 0 {
+ return convertRow16x444Vec
+ }
+
+ return convertRow16Vec
+}
+
+func convertRow16x444Vec(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ if n > 0 {
+ convertRow16x444RVV(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n, c)
+ }
+}
+
+func convertRow16Vec(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ if n4 := n &^ 3; n4 > 0 {
+ convertRow16RVV(&dst[0], &yf[0], &u0[0], &u1[0], &v0[0], &v1[0], &a[0], n4, c)
+ if n4 == n {
+ return
+ }
+ dst, yf, a, n = dst[8*n4:], yf[n4:], a[n4:], n-n4
+ u0, u1 = u0[n4/2:], u1[n4/2:]
+ v0, v1 = v0[n4/2:], v1[n4/2:]
+ }
+
+ convertRow16Go(dst, yf, u0, u1, v0, v1, a, n, c)
+}
+
+//go:noescape
+func normRow8RVV(dst *float32, src *uint8, n int, bias, rng float32)
+
+func normRow(dst []float32, src []uint8, bias, rng float32) {
+ if len(dst) > 0 {
+ normRow8RVV(&dst[0], &src[0], len(dst), bias, rng)
+ }
+}
+
+func normRow16(dst []float32, src []uint16, maxCh uint16, bias, rng float32) {
+ normRow16Go(dst, src, maxCh, bias, rng)
+}
diff --git a/kernel/heif/internal/h265heic/color_riscv64.s b/kernel/heif/internal/h265heic/color_riscv64.s
new file mode 100644
index 0000000000..4237735df2
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_riscv64.s
@@ -0,0 +1,392 @@
+//go:build riscv64 && riscv64.rva23u64 && !noasm
+
+#include "textflag.h"
+
+#define CHROMA(P0, P1, OUT) \
+ VLE32V (P0), V3; \
+ VRGATHERVV V6, V3, V4; \
+ VRGATHERVV V7, V3, V5; \
+ VFMULVF F0, V4, OUT; \
+ VFMULVF F1, V5, V5; \
+ VFADDVV V5, OUT, OUT; \
+ VLE32V (P1), V3; \
+ VRGATHERVV V6, V3, V4; \
+ VRGATHERVV V7, V3, V5; \
+ VFMULVF F1, V4, V4; \
+ VFADDVV V4, OUT, OUT; \
+ VFMULVF F2, V5, V5; \
+ VFADDVV V5, OUT, OUT
+
+#define PIXEL(V) \
+ VFMAXVF F11, V, V; \
+ VFMINVF F9, V, V; \
+ VFMULVF F8, V, V; \
+ VFADDVF F10, V, V; \
+ VFCVTRTZXFV V, V
+
+#define NARROW(SRC, DST) \
+ VSETVLI X5, E16, MF2, TA, MA, X6; \
+ VNSRLWI $0, SRC, V20; \
+ VSETVLI X5, E8, MF4, TA, MA, X6; \
+ VNSRLWI $0, V20, DST; \
+ VSETVLI X5, E32, M1, TA, MA, X6
+
+// func convertRowRVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+TEXT ·convertRowRVV(SB), NOSPLIT, $0-72
+ MOV dst+0(FP), X10
+ MOV yf+8(FP), X11
+ MOV u0+16(FP), X12
+ MOV u1+24(FP), X13
+ MOV v0+32(FP), X14
+ MOV v1+40(FP), X15
+ MOV a+48(FP), X16
+ MOV n+56(FP), X17
+ MOV c+64(FP), X18
+
+ MOVF 0(X18), F0
+ MOVF 4(X18), F1
+ MOVF 8(X18), F2
+ MOVF 12(X18), F3
+ MOVF 16(X18), F4
+ MOVF 20(X18), F5
+ MOVF 24(X18), F6
+ MOVF 28(X18), F7
+ MOVF 32(X18), F8
+ MOVF 36(X18), F9
+ MOVF 40(X18), F10
+ MOVF 44(X18), F11
+
+loop:
+ MOV $16, X19
+ MIN X17, X19, X19
+ VSETVLI X19, E32, M1, TA, MA, X5
+
+ VIDV V3
+ VSRLVI $1, V3, V4
+ VADDVI $1, V4, V6
+ VANDVI $1, V3, V5
+ VADDVV V5, V5, V5
+ VADDVV V5, V4, V7
+
+ VLE32V (X11), V0
+ CHROMA(X12, X13, V1)
+ CHROMA(X14, X15, V2)
+
+ VFMULVF F3, V2, V8
+ VFADDVV V0, V8, V8
+
+ VFMULVF F4, V1, V10
+ VFADDVV V0, V10, V10
+
+ VFMULVF F5, V2, V9
+ VFMULVF F6, V1, V4
+ VFADDVV V4, V9, V9
+ VFADDVV V9, V9, V9
+ VFDIVVF F7, V9, V9
+ VFSUBVV V9, V0, V9
+
+ PIXEL(V8)
+ PIXEL(V9)
+ PIXEL(V10)
+
+ VSETVLI X5, E8, MF4, TA, MA, X6
+ VLE8V (X16), V11
+ VSETVLI X5, E32, M1, TA, MA, X6
+ VZEXTVF4 V11, V12
+
+ NARROW(V8, V16)
+ NARROW(V9, V17)
+ NARROW(V10, V18)
+ NARROW(V12, V19)
+
+ VSETVLI X5, E8, MF4, TA, MA, X6
+ VSSEG4E8V V16, (X10)
+ VSETVLI X5, E32, M1, TA, MA, X6
+
+ SLLI $2, X5, X6
+ ADD X6, X11
+ ADD X6, X10
+ ADD X6, X10
+ ADD X6, X10
+ ADD X6, X10
+ SUB X6, X10
+ SUB X6, X10
+ SUB X6, X10
+ SRLI $1, X6, X20
+ ADD X20, X12
+ ADD X20, X13
+ ADD X20, X14
+ ADD X20, X15
+ ADD X5, X16
+ SUB X5, X17
+ BNEZ X17, loop
+
+ RET
+
+#define SWAP16(SRC, DST) \
+ VSETVLI X5, E16, MF2, TA, MA, X6; \
+ VNSRLWI $0, SRC, DST; \
+ VSRLVI $8, DST, V20; \
+ VSLLVI $8, DST, DST; \
+ VORVV V20, DST, DST; \
+ VSETVLI X5, E32, M1, TA, MA, X6
+
+// func convertRow16RVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+TEXT ·convertRow16RVV(SB), NOSPLIT, $0-72
+ MOV dst+0(FP), X10
+ MOV yf+8(FP), X11
+ MOV u0+16(FP), X12
+ MOV u1+24(FP), X13
+ MOV v0+32(FP), X14
+ MOV v1+40(FP), X15
+ MOV a+48(FP), X16
+ MOV n+56(FP), X17
+ MOV c+64(FP), X18
+
+ MOVF 0(X18), F0
+ MOVF 4(X18), F1
+ MOVF 8(X18), F2
+ MOVF 12(X18), F3
+ MOVF 16(X18), F4
+ MOVF 20(X18), F5
+ MOVF 24(X18), F6
+ MOVF 28(X18), F7
+ MOVF 32(X18), F8
+ MOVF 36(X18), F9
+ MOVF 40(X18), F10
+ MOVF 44(X18), F11
+
+loop16:
+ MOV $16, X19
+ MIN X17, X19, X19
+ VSETVLI X19, E32, M1, TA, MA, X5
+
+ VIDV V3
+ VSRLVI $1, V3, V4
+ VADDVI $1, V4, V6
+ VANDVI $1, V3, V5
+ VADDVV V5, V5, V5
+ VADDVV V5, V4, V7
+
+ VLE32V (X11), V0
+ CHROMA(X12, X13, V1)
+ CHROMA(X14, X15, V2)
+
+ VFMULVF F3, V2, V8
+ VFADDVV V0, V8, V8
+
+ VFMULVF F4, V1, V10
+ VFADDVV V0, V10, V10
+
+ VFMULVF F5, V2, V9
+ VFMULVF F6, V1, V4
+ VFADDVV V4, V9, V9
+ VFADDVV V9, V9, V9
+ VFDIVVF F7, V9, V9
+ VFSUBVV V9, V0, V9
+
+ PIXEL(V8)
+ PIXEL(V9)
+ PIXEL(V10)
+
+ VSETVLI X5, E16, MF2, TA, MA, X6
+ VLE16V (X16), V11
+ VSETVLI X5, E32, M1, TA, MA, X6
+ VZEXTVF2 V11, V12
+
+ SWAP16(V8, V16)
+ SWAP16(V9, V17)
+ SWAP16(V10, V18)
+ SWAP16(V12, V19)
+
+ VSETVLI X5, E16, MF2, TA, MA, X6
+ VSSEG4E16V V16, (X10)
+ VSETVLI X5, E32, M1, TA, MA, X6
+
+ SLLI $2, X5, X6
+ ADD X6, X11
+ SLLI $3, X5, X21
+ ADD X21, X10
+ SRLI $1, X6, X20
+ ADD X20, X12
+ ADD X20, X13
+ ADD X20, X14
+ ADD X20, X15
+ SLLI $1, X5, X22
+ ADD X22, X16
+ SUB X5, X17
+ BNEZ X17, loop16
+
+ RET
+
+// func convertRow444RVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint8, n int, c *rowConsts)
+TEXT ·convertRow444RVV(SB), NOSPLIT, $0-72
+ MOV dst+0(FP), X10
+ MOV yf+8(FP), X11
+ MOV u0+16(FP), X12
+ MOV v0+32(FP), X14
+ MOV a+48(FP), X16
+ MOV n+56(FP), X17
+ MOV c+64(FP), X18
+
+ MOVF 12(X18), F3
+ MOVF 16(X18), F4
+ MOVF 20(X18), F5
+ MOVF 24(X18), F6
+ MOVF 28(X18), F7
+ MOVF 32(X18), F8
+ MOVF 36(X18), F9
+ MOVF 40(X18), F10
+ MOVF 44(X18), F11
+
+l444:
+ MOV $16, X19
+ MIN X17, X19, X19
+ VSETVLI X19, E32, M1, TA, MA, X5
+
+ VLE32V (X11), V0
+ ADD $4, X12, X23
+ VLE32V (X23), V1
+ ADD $4, X14, X23
+ VLE32V (X23), V2
+
+ VFMULVF F3, V2, V8
+ VFADDVV V0, V8, V8
+
+ VFMULVF F4, V1, V10
+ VFADDVV V0, V10, V10
+
+ VFMULVF F5, V2, V9
+ VFMULVF F6, V1, V4
+ VFADDVV V4, V9, V9
+ VFADDVV V9, V9, V9
+ VFDIVVF F7, V9, V9
+ VFSUBVV V9, V0, V9
+
+ PIXEL(V8)
+ PIXEL(V9)
+ PIXEL(V10)
+
+ VSETVLI X5, E8, MF4, TA, MA, X6
+ VLE8V (X16), V11
+ VSETVLI X5, E32, M1, TA, MA, X6
+ VZEXTVF4 V11, V12
+
+ NARROW(V8, V16)
+ NARROW(V9, V17)
+ NARROW(V10, V18)
+ NARROW(V12, V19)
+
+ VSETVLI X5, E8, MF4, TA, MA, X6
+ VSSEG4E8V V16, (X10)
+ VSETVLI X5, E32, M1, TA, MA, X6
+
+ SLLI $2, X5, X6
+ ADD X6, X11
+ ADD X6, X12
+ ADD X6, X14
+ ADD X6, X10
+ ADD X5, X16
+ SUB X5, X17
+ BNEZ X17, l444
+
+ RET
+
+// func convertRow16x444RVV(dst *uint8, yf, u0, u1, v0, v1 *float32, a *uint16, n int, c *rowConsts)
+TEXT ·convertRow16x444RVV(SB), NOSPLIT, $0-72
+ MOV dst+0(FP), X10
+ MOV yf+8(FP), X11
+ MOV u0+16(FP), X12
+ MOV v0+32(FP), X14
+ MOV a+48(FP), X16
+ MOV n+56(FP), X17
+ MOV c+64(FP), X18
+
+ MOVF 12(X18), F3
+ MOVF 16(X18), F4
+ MOVF 20(X18), F5
+ MOVF 24(X18), F6
+ MOVF 28(X18), F7
+ MOVF 32(X18), F8
+ MOVF 36(X18), F9
+ MOVF 40(X18), F10
+ MOVF 44(X18), F11
+
+l16444:
+ MOV $16, X19
+ MIN X17, X19, X19
+ VSETVLI X19, E32, M1, TA, MA, X5
+
+ VLE32V (X11), V0
+ ADD $4, X12, X23
+ VLE32V (X23), V1
+ ADD $4, X14, X23
+ VLE32V (X23), V2
+
+ VFMULVF F3, V2, V8
+ VFADDVV V0, V8, V8
+
+ VFMULVF F4, V1, V10
+ VFADDVV V0, V10, V10
+
+ VFMULVF F5, V2, V9
+ VFMULVF F6, V1, V4
+ VFADDVV V4, V9, V9
+ VFADDVV V9, V9, V9
+ VFDIVVF F7, V9, V9
+ VFSUBVV V9, V0, V9
+
+ PIXEL(V8)
+ PIXEL(V9)
+ PIXEL(V10)
+
+ VSETVLI X5, E16, MF2, TA, MA, X6
+ VLE16V (X16), V11
+ VSETVLI X5, E32, M1, TA, MA, X6
+ VZEXTVF2 V11, V12
+
+ SWAP16(V8, V16)
+ SWAP16(V9, V17)
+ SWAP16(V10, V18)
+ SWAP16(V12, V19)
+
+ VSETVLI X5, E16, MF2, TA, MA, X6
+ VSSEG4E16V V16, (X10)
+ VSETVLI X5, E32, M1, TA, MA, X6
+
+ SLLI $2, X5, X6
+ ADD X6, X11
+ ADD X6, X12
+ ADD X6, X14
+ SLLI $3, X5, X21
+ ADD X21, X10
+ SLLI $1, X5, X22
+ ADD X22, X16
+ SUB X5, X17
+ BNEZ X17, l16444
+
+ RET
+
+// func normRow8RVV(dst *float32, src *uint8, n int, bias, rng float32)
+TEXT ·normRow8RVV(SB), NOSPLIT, $0-32
+ MOV dst+0(FP), X10
+ MOV src+8(FP), X11
+ MOV n+16(FP), X12
+ MOVF bias+24(FP), F0
+ MOVF rng+28(FP), F1
+
+loop8:
+ VSETVLI X12, E32, M1, TA, MA, X13
+ VLE8V (X11), V1
+ VZEXTVF4 V1, V2
+ VFCVTFXUV V2, V2
+ VFSUBVF F0, V2, V2
+ VFDIVVF F1, V2, V2
+ VSE32V V2, (X10)
+ ADD X13, X11
+ SLLI $2, X13, X14
+ ADD X14, X10
+ SUB X13, X12
+ BNEZ X12, loop8
+
+ RET
diff --git a/kernel/heif/internal/h265heic/color_row.go b/kernel/heif/internal/h265heic/color_row.go
new file mode 100644
index 0000000000..2af9014e60
--- /dev/null
+++ b/kernel/heif/internal/h265heic/color_row.go
@@ -0,0 +1,209 @@
+package heic
+
+import "encoding/binary"
+
+type rowConsts struct {
+ w0, w1, w2 float32
+ crCoef, cbCoef float32
+ gcr, gcb, kg float32
+ outMax float32
+ one, half float32
+ zero float32
+}
+
+type convertRow func(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts)
+
+type convertRow16 func(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts)
+
+// forceScalarRow drops back to rgbRow, so a test can compare the two paths.
+var forceScalarRow bool
+
+func (s *colorState) fastRow(outDepth int) bool {
+ if forceScalarRow {
+ return false
+ }
+
+ if !s.hasColor {
+ return false
+ }
+ if s.depth == 8 != (outDepth == 8) {
+ return false
+ }
+ switch s.matrix {
+ case mcIdentity, mcYCgCo:
+ return false
+ }
+
+ return true
+}
+
+func (s *colorState) rowConsts() rowConsts {
+ const w0, w1, w2 = 9.0 / 16.0, 3.0 / 16.0, 1.0 / 16.0
+
+ return rowConsts{
+ w0: w0, w1: w1, w2: w2,
+ crCoef: s.crCoef, cbCoef: s.cbCoef,
+ gcr: s.gcr, gcb: s.gcb, kg: s.kg,
+ outMax: s.outMax, one: 1, half: 0.5,
+ }
+}
+
+func normRowGo(dst []float32, src []uint8, bias, rng float32) {
+ src = src[:len(dst)]
+ for i, v := range src {
+ dst[i] = (float32(v) - bias) / rng
+ }
+}
+
+func normRow16Go(dst []float32, src []uint16, maxCh uint16, bias, rng float32) {
+ src = src[:len(dst)]
+ for i, v := range src {
+ dst[i] = (float32(min(v, maxCh)) - bias) / rng
+ }
+}
+
+func convertRow444Go(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ for x := range n {
+ yy := yf[x]
+ cb, cr := u0[x+1], v0[x+1]
+
+ r := yy + c.crCoef*cr
+ b := yy + c.cbCoef*cb
+ g := yy - (2*((c.gcr*cr)+(c.gcb*cb)))/c.kg
+
+ dst[4*x] = uint8(0.5 + clampF(r)*c.outMax)
+ dst[4*x+1] = uint8(0.5 + clampF(g)*c.outMax)
+ dst[4*x+2] = uint8(0.5 + clampF(b)*c.outMax)
+ dst[4*x+3] = a[x]
+ }
+}
+
+func convertRow16x444Go(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ for x := range n {
+ yy := yf[x]
+ cb, cr := u0[x+1], v0[x+1]
+
+ r := yy + c.crCoef*cr
+ b := yy + c.cbCoef*cb
+ g := yy - (2*((c.gcr*cr)+(c.gcb*cb)))/c.kg
+
+ o := dst[8*x : 8*x+8 : 8*x+8]
+ binary.BigEndian.PutUint16(o[0:], uint16(0.5+clampF(r)*c.outMax))
+ binary.BigEndian.PutUint16(o[2:], uint16(0.5+clampF(g)*c.outMax))
+ binary.BigEndian.PutUint16(o[4:], uint16(0.5+clampF(b)*c.outMax))
+ binary.BigEndian.PutUint16(o[6:], a[x])
+ }
+}
+
+func convertRow16Go(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint16,
+ n int, c *rowConsts,
+) {
+ for x := range n {
+ k := x >> 1
+ j := k
+ if x&1 != 0 {
+ j = k + 2
+ }
+ k++
+
+ yy := yf[x]
+ cb := u0[k]*c.w0 + u0[j]*c.w1 + u1[k]*c.w1 + u1[j]*c.w2
+ cr := v0[k]*c.w0 + v0[j]*c.w1 + v1[k]*c.w1 + v1[j]*c.w2
+
+ r := yy + c.crCoef*cr
+ b := yy + c.cbCoef*cb
+ g := yy - (2*((c.gcr*cr)+(c.gcb*cb)))/c.kg
+
+ o := dst[8*x : 8*x+8 : 8*x+8]
+ binary.BigEndian.PutUint16(o[0:], uint16(0.5+clampF(r)*c.outMax))
+ binary.BigEndian.PutUint16(o[2:], uint16(0.5+clampF(g)*c.outMax))
+ binary.BigEndian.PutUint16(o[4:], uint16(0.5+clampF(b)*c.outMax))
+ binary.BigEndian.PutUint16(o[6:], a[x])
+ }
+}
+
+func convertRowGo(dst []uint8, yf, u0, u1, v0, v1 []float32, a []uint8,
+ n int, c *rowConsts,
+) {
+ for x := range n {
+ k := x >> 1
+ j := k
+ if x&1 != 0 {
+ j = k + 2
+ }
+ k++
+
+ yy := yf[x]
+ cb := u0[k]*c.w0 + u0[j]*c.w1 + u1[k]*c.w1 + u1[j]*c.w2
+ cr := v0[k]*c.w0 + v0[j]*c.w1 + v1[k]*c.w1 + v1[j]*c.w2
+
+ r := yy + c.crCoef*cr
+ b := yy + c.cbCoef*cb
+ g := yy - (2*((c.gcr*cr)+(c.gcb*cb)))/c.kg
+
+ dst[4*x] = uint8(0.5 + clampF(r)*c.outMax)
+ dst[4*x+1] = uint8(0.5 + clampF(g)*c.outMax)
+ dst[4*x+2] = uint8(0.5 + clampF(b)*c.outMax)
+ dst[4*x+3] = a[x]
+ }
+}
+
+// rowPlanes normalises the chroma rows one output row needs, padded by one
+// sample at each end so the kernels can read a neighbour without a bounds
+// check at the edges.
+func (s *colorState) rowPlanes(cb, cr planeView, y, w, h int) (u0, u1, v0, v1 []float32) {
+ uvY := y >> s.ssVer
+ uw := (w + s.ssHor) >> s.ssHor
+
+ adjRow := 0
+ if s.ssVer != 0 && y != 0 && !(y == h-1 && y%2 != 0) {
+ if y%2 != 0 {
+ adjRow = 1
+ } else {
+ adjRow = -1
+ }
+ }
+
+ u0 = s.padRow(s.uPad[0], cb, uvY, uw)
+ v0 = s.padRow(s.vPad[0], cr, uvY, uw)
+
+ if adjRow == 0 {
+ return u0, u0, v0, v0
+ }
+
+ ay := min(max(uvY+adjRow, 0), cb.h-1)
+
+ u1 = s.padRow(s.uPad[1], cb, ay, uw)
+ v1 = s.padRow(s.vPad[1], cr, ay, uw)
+
+ return u0, u1, v0, v1
+}
+
+func (s *colorState) padRow(dst []float32, v planeView, y, uw int) []float32 {
+ if v.p16 != nil {
+ normRow16(dst[1:1+uw], v.p16[y*v.stride:], uint16(s.maxChannel), s.biasUV, s.rangeUV)
+ } else {
+ normRow(dst[1:1+uw], v.p8[y*v.stride:y*v.stride+uw], s.biasUV, s.rangeUV)
+ }
+
+ dst[0] = dst[1]
+ dst[uw+1] = dst[uw]
+
+ return dst
+}
+
+func (s *colorState) lumaRowF(v planeView, y, w int) []float32 {
+ if v.p16 != nil {
+ normRow16(s.yf[:w], v.p16[y*v.stride:], uint16(s.maxChannel), s.biasY, s.rangeY)
+ } else {
+ normRow(s.yf[:w], v.p8[y*v.stride:y*v.stride+w], s.biasY, s.rangeY)
+ }
+
+ return s.yf
+}
diff --git a/kernel/heif/internal/h265heic/cpu_amd64.go b/kernel/heif/internal/h265heic/cpu_amd64.go
new file mode 100644
index 0000000000..39e4bc2250
--- /dev/null
+++ b/kernel/heif/internal/h265heic/cpu_amd64.go
@@ -0,0 +1,7 @@
+//go:build amd64 && !noasm
+
+package heic
+
+var hasAVX2 = cpuidAVX2()
+
+func cpuidAVX2() bool
diff --git a/kernel/heif/internal/h265heic/cpu_amd64.s b/kernel/heif/internal/h265heic/cpu_amd64.s
new file mode 100644
index 0000000000..a1071c5c49
--- /dev/null
+++ b/kernel/heif/internal/h265heic/cpu_amd64.s
@@ -0,0 +1,35 @@
+//go:build amd64 && !noasm
+
+#include "textflag.h"
+
+// cpuidAVX2 reports whether the CPU has AVX2 and the OS saves the YMM state.
+TEXT ·cpuidAVX2(SB), NOSPLIT, $0-1
+ MOVL $0, AX
+ CPUID
+ CMPL AX, $7
+ JL no
+
+ MOVL $1, AX
+ MOVL $0, CX
+ CPUID
+ BTL $27, CX // OSXSAVE
+ JNC no
+
+ MOVL $0, CX
+ XGETBV
+ ANDL $6, AX // XMM and YMM state
+ CMPL AX, $6
+ JNE no
+
+ MOVL $7, AX
+ MOVL $0, CX
+ CPUID
+ BTL $5, BX // AVX2
+ JNC no
+
+ MOVB $1, ret+0(FP)
+ RET
+
+no:
+ MOVB $0, ret+0(FP)
+ RET
diff --git a/kernel/heif/internal/h265heic/exif.go b/kernel/heif/internal/h265heic/exif.go
new file mode 100644
index 0000000000..d0001f9177
--- /dev/null
+++ b/kernel/heif/internal/h265heic/exif.go
@@ -0,0 +1,501 @@
+package heic
+
+import (
+ "encoding/binary"
+ "errors"
+ "io"
+ "slices"
+)
+
+// ErrNoExif is returned when the file carries no Exif item.
+var ErrNoExif = errors.New("avif: no exif data")
+
+// ErrNoXMP is returned when the file carries no XMP item.
+var ErrNoXMP = errors.New("avif: no xmp data")
+
+const xmpContentType = "application/rdf+xml"
+
+// Exif holds the Exif metadata decoded from an HEIC image.
+type Exif struct {
+ // Orientation is the Exif orientation, 1 to 8, where 1 is upright.
+ Orientation int
+ // Width and Height are the dimensions the Exif tags report, which need
+ // not be the dimensions the image decodes to.
+ Width int
+ Height int
+
+ // Make and Model name the camera, Software what wrote the file.
+ Make string
+ Model string
+ Software string
+
+ // DateTime and DateTimeOriginal are "YYYY:MM:DD HH:MM:SS", the first the
+ // file's own time and the second the time the photo was taken.
+ DateTime string
+ DateTimeOriginal string
+
+ // ExposureTime is in seconds and FocalLength in millimetres.
+ ExposureTime float64
+ FNumber float64
+ ISOSpeed int
+ FocalLength float64
+ Flash int
+
+ // GPSLatitude and GPSLongitude are decimal degrees, positive north and
+ // east. GPSAltitude is metres above sea level.
+ GPSLatitude float64
+ GPSLongitude float64
+ GPSAltitude float64
+
+ Copyright string
+ Artist string
+}
+
+// DecodeExif reads the Exif metadata of an HEIC image. Tags the file omits
+// stay zero. It returns ErrNoExif when the file carries no Exif item.
+func DecodeExif(r io.Reader) (*Exif, error) {
+ tiff, err := RawExif(r)
+ if err != nil {
+ return nil, err
+ }
+
+ exif := &Exif{Orientation: 1}
+ if err := parseExifData(tiff, exif); err != nil {
+ return nil, err
+ }
+
+ return exif, nil
+}
+
+// RawExif returns the TIFF payload of the Exif item, without the
+// exif_tiff_header_offset the HEIC container puts in front of it. It aliases a
+// buffered input rather than copying it, so it must not be written to.
+func RawExif(r io.Reader) ([]byte, error) {
+ f, err := readFile(r)
+ if err != nil {
+ return nil, err
+ }
+
+ it := f.descItem("Exif", "")
+ if it == nil {
+ return nil, ErrNoExif
+ }
+ b, err := f.meta.data(it, f.src)
+ if err != nil {
+ return nil, err
+ }
+ tiff := exifTIFF(b)
+ if tiff == nil {
+ return nil, ErrNoExif
+ }
+
+ return tiff, nil
+}
+
+// RawXMP returns the XMP packet of the file. It aliases a buffered input
+// rather than copying it, so it must not be written to.
+func RawXMP(r io.Reader) ([]byte, error) {
+ f, err := readFile(r)
+ if err != nil {
+ return nil, err
+ }
+
+ it := f.descItem("mime", xmpContentType)
+ if it == nil {
+ return nil, ErrNoXMP
+ }
+
+ return f.meta.data(it, f.src)
+}
+
+func readFile(r io.Reader) (*file, error) {
+ src, err := srcFor(r)
+ if err != nil {
+ return nil, err
+ }
+
+ return parse(src)
+}
+
+// descItem finds the metadata item describing the primary image. A file with
+// no image item at all still gives up its metadata.
+func (f *file) descItem(typ, contentType string) *item {
+ m := f.meta
+ primary, _ := f.primary()
+
+ for _, id := range m.order {
+ it := m.items[id]
+ if it == nil || it.typ != typ || it.unsupported {
+ continue
+ }
+ if it.contentType != contentType {
+ continue
+ }
+ if primary != nil && !slices.Contains(m.refsTo("cdsc", it.id), primary.id) {
+ continue
+ }
+
+ return it
+ }
+
+ return nil
+}
+
+func isTIFFHeader(b []byte) bool {
+ if len(b) < 4 {
+ return false
+ }
+
+ return (b[0] == 'I' && b[1] == 'I' && b[2] == 42 && b[3] == 0) ||
+ (b[0] == 'M' && b[1] == 'M' && b[2] == 0 && b[3] == 42)
+}
+
+// exifTIFF strips the exif_tiff_header_offset of ISO/IEC 23008-12 Annex A.2.1.
+// A file that gets the offset wrong still parses, from the header found by
+// scanning, which is the offset the writer should have signalled.
+func exifTIFF(b []byte) []byte {
+ if len(b) < 4 {
+ return nil
+ }
+ off := uint64(binary.BigEndian.Uint32(b))
+ b = b[4:]
+
+ if off <= uint64(len(b)) && isTIFFHeader(b[off:]) {
+ return b[off:]
+ }
+ for i := range b {
+ if isTIFFHeader(b[i:]) {
+ return b[i:]
+ }
+ }
+
+ return nil
+}
+
+const (
+ tagOrientation = 0x0112
+ tagImageWidth = 0x0100
+ tagImageLength = 0x0101
+ tagMake = 0x010F
+ tagModel = 0x0110
+ tagSoftware = 0x0131
+ tagDateTime = 0x0132
+ tagArtist = 0x013B
+ tagCopyright = 0x8298
+ tagExifIFDPointer = 0x8769
+ tagGPSIFDPointer = 0x8825
+
+ tagExposureTime = 0x829A
+ tagFNumber = 0x829D
+ tagISOSpeedRatings = 0x8827
+ tagDateTimeOriginal = 0x9003
+ tagFlash = 0x9209
+ tagFocalLength = 0x920A
+
+ tagGPSLatitudeRef = 0x0001
+ tagGPSLatitude = 0x0002
+ tagGPSLongitudeRef = 0x0003
+ tagGPSLongitude = 0x0004
+ tagGPSAltitudeRef = 0x0005
+ tagGPSAltitude = 0x0006
+)
+
+const (
+ typeUnsignedByte = 1
+ typeASCIIString = 2
+ typeUnsignedShort = 3
+ typeUnsignedLong = 4
+ typeUnsignedRational = 5
+ typeSignedByte = 6
+ typeUndefined = 7
+ typeSignedShort = 8
+ typeSignedLong = 9
+ typeSignedRational = 10
+ typeSingleFloat = 11
+ typeDoubleFloat = 12
+)
+
+type exifReader struct {
+ data []byte
+ littleEndian bool
+}
+
+func (r *exifReader) uint16(offset int) uint16 {
+ if offset < 0 || offset+1 >= len(r.data) {
+ return 0
+ }
+ if r.littleEndian {
+ return uint16(r.data[offset]) | uint16(r.data[offset+1])<<8
+ }
+
+ return uint16(r.data[offset])<<8 | uint16(r.data[offset+1])
+}
+
+func (r *exifReader) uint32(offset int) uint32 {
+ if offset < 0 || offset+3 >= len(r.data) {
+ return 0
+ }
+ if r.littleEndian {
+ return uint32(r.data[offset]) | uint32(r.data[offset+1])<<8 |
+ uint32(r.data[offset+2])<<16 | uint32(r.data[offset+3])<<24
+ }
+
+ return uint32(r.data[offset])<<24 | uint32(r.data[offset+1])<<16 |
+ uint32(r.data[offset+2])<<8 | uint32(r.data[offset+3])
+}
+
+func (r *exifReader) readString(offset, maxLen int) string {
+ if offset < 0 || offset >= len(r.data) {
+ return ""
+ }
+ end := offset
+ for end < len(r.data) && end < offset+maxLen && r.data[end] != 0 {
+ end++
+ }
+
+ return string(r.data[offset:end])
+}
+
+func (r *exifReader) readRational(offset int) float64 {
+ if offset < 0 || offset+7 >= len(r.data) {
+ return 0
+ }
+ num, den := r.uint32(offset), r.uint32(offset+4)
+ if den == 0 {
+ return 0
+ }
+
+ return float64(num) / float64(den)
+}
+
+func parseExifData(data []byte, exif *Exif) error {
+ if len(data) < 8 {
+ return errors.New("avif: exif data too short")
+ }
+
+ r := &exifReader{data: data}
+ switch {
+ case data[0] == 'I' && data[1] == 'I':
+ r.littleEndian = true
+ case data[0] == 'M' && data[1] == 'M':
+ default:
+ return errors.New("avif: invalid exif byte order marker")
+ }
+
+ if r.uint16(2) != 42 {
+ return errors.New("avif: invalid exif magic number")
+ }
+
+ ifdOffset := r.uint32(4)
+ if ifdOffset < 8 || int(ifdOffset) >= len(data) {
+ return errors.New("avif: invalid exif ifd offset")
+ }
+
+ exifIFDOffset, gpsIFDOffset := parseIFD(r, int(ifdOffset), exif)
+ if exifIFDOffset > 0 {
+ parseExifSubIFD(r, exifIFDOffset, exif)
+ }
+ if gpsIFDOffset > 0 {
+ parseGPSSubIFD(r, gpsIFDOffset, exif)
+ }
+
+ return nil
+}
+
+// eachEntry walks the entries of an IFD, resolving each value to its offset.
+func eachEntry(r *exifReader, offset int, fn func(tag, dataType uint16, count uint32, valueOffset int)) {
+ if offset < 0 || offset+1 >= len(r.data) {
+ return
+ }
+
+ n := int(r.uint16(offset))
+ offset += 2
+
+ for i := range n {
+ entry := offset + i*12
+ if entry+11 >= len(r.data) {
+ break
+ }
+
+ tag := r.uint16(entry)
+ dataType := r.uint16(entry + 2)
+ count := r.uint32(entry + 4)
+ valueOffset := entry + 8
+
+ if getDataSize(dataType, count) > 4 {
+ valueOffset = int(r.uint32(valueOffset))
+ if valueOffset >= len(r.data) {
+ continue
+ }
+ }
+
+ fn(tag, dataType, count, valueOffset)
+ }
+}
+
+func parseIFD(r *exifReader, offset int, exif *Exif) (exifIFDOffset, gpsIFDOffset int) {
+ eachEntry(r, offset, func(tag, dataType uint16, count uint32, valueOffset int) {
+ switch tag {
+ case tagOrientation:
+ if dataType == typeUnsignedShort {
+ exif.Orientation = int(r.uint16(valueOffset))
+ }
+ case tagImageWidth:
+ switch dataType {
+ case typeUnsignedShort:
+ exif.Width = int(r.uint16(valueOffset))
+ case typeUnsignedLong:
+ exif.Width = int(r.uint32(valueOffset))
+ }
+ case tagImageLength:
+ switch dataType {
+ case typeUnsignedShort:
+ exif.Height = int(r.uint16(valueOffset))
+ case typeUnsignedLong:
+ exif.Height = int(r.uint32(valueOffset))
+ }
+ case tagMake:
+ if dataType == typeASCIIString {
+ exif.Make = r.readString(valueOffset, int(count))
+ }
+ case tagModel:
+ if dataType == typeASCIIString {
+ exif.Model = r.readString(valueOffset, int(count))
+ }
+ case tagSoftware:
+ if dataType == typeASCIIString {
+ exif.Software = r.readString(valueOffset, int(count))
+ }
+ case tagDateTime:
+ if dataType == typeASCIIString {
+ exif.DateTime = r.readString(valueOffset, int(count))
+ }
+ case tagArtist:
+ if dataType == typeASCIIString {
+ exif.Artist = r.readString(valueOffset, int(count))
+ }
+ case tagCopyright:
+ if dataType == typeASCIIString {
+ exif.Copyright = r.readString(valueOffset, int(count))
+ }
+ case tagExifIFDPointer:
+ if dataType == typeUnsignedLong {
+ exifIFDOffset = int(r.uint32(valueOffset))
+ }
+ case tagGPSIFDPointer:
+ if dataType == typeUnsignedLong {
+ gpsIFDOffset = int(r.uint32(valueOffset))
+ }
+ }
+ })
+
+ return exifIFDOffset, gpsIFDOffset
+}
+
+func parseExifSubIFD(r *exifReader, offset int, exif *Exif) {
+ eachEntry(r, offset, func(tag, dataType uint16, count uint32, valueOffset int) {
+ switch tag {
+ case tagExposureTime:
+ if dataType == typeUnsignedRational {
+ exif.ExposureTime = r.readRational(valueOffset)
+ }
+ case tagFNumber:
+ if dataType == typeUnsignedRational {
+ exif.FNumber = r.readRational(valueOffset)
+ }
+ case tagISOSpeedRatings:
+ if dataType == typeUnsignedShort {
+ exif.ISOSpeed = int(r.uint16(valueOffset))
+ }
+ case tagDateTimeOriginal:
+ if dataType == typeASCIIString {
+ exif.DateTimeOriginal = r.readString(valueOffset, int(count))
+ }
+ case tagFlash:
+ if dataType == typeUnsignedShort {
+ exif.Flash = int(r.uint16(valueOffset))
+ }
+ case tagFocalLength:
+ if dataType == typeUnsignedRational {
+ exif.FocalLength = r.readRational(valueOffset)
+ }
+ }
+ })
+}
+
+func parseGPSSubIFD(r *exifReader, offset int, exif *Exif) {
+ var latRef, lonRef string
+ var lat, lon []float64
+ var altRef uint8
+
+ eachEntry(r, offset, func(tag, dataType uint16, count uint32, valueOffset int) {
+ switch tag {
+ case tagGPSLatitudeRef:
+ if dataType == typeASCIIString {
+ latRef = r.readString(valueOffset, 2)
+ }
+ case tagGPSLatitude:
+ if dataType == typeUnsignedRational && count == 3 {
+ lat = []float64{
+ r.readRational(valueOffset),
+ r.readRational(valueOffset + 8),
+ r.readRational(valueOffset + 16),
+ }
+ }
+ case tagGPSLongitudeRef:
+ if dataType == typeASCIIString {
+ lonRef = r.readString(valueOffset, 2)
+ }
+ case tagGPSLongitude:
+ if dataType == typeUnsignedRational && count == 3 {
+ lon = []float64{
+ r.readRational(valueOffset),
+ r.readRational(valueOffset + 8),
+ r.readRational(valueOffset + 16),
+ }
+ }
+ case tagGPSAltitudeRef:
+ if dataType == typeUnsignedByte && valueOffset < len(r.data) {
+ altRef = r.data[valueOffset]
+ }
+ case tagGPSAltitude:
+ if dataType == typeUnsignedRational {
+ exif.GPSAltitude = r.readRational(valueOffset)
+ }
+ }
+ })
+
+ if altRef == 1 {
+ exif.GPSAltitude = -exif.GPSAltitude
+ }
+ if len(lat) == 3 {
+ exif.GPSLatitude = lat[0] + lat[1]/60 + lat[2]/3600
+ if latRef == "S" {
+ exif.GPSLatitude = -exif.GPSLatitude
+ }
+ }
+ if len(lon) == 3 {
+ exif.GPSLongitude = lon[0] + lon[1]/60 + lon[2]/3600
+ if lonRef == "W" {
+ exif.GPSLongitude = -exif.GPSLongitude
+ }
+ }
+}
+
+func getDataSize(dataType uint16, count uint32) int {
+ var size int
+ switch dataType {
+ case typeUnsignedByte, typeSignedByte, typeASCIIString, typeUndefined:
+ size = 1
+ case typeUnsignedShort, typeSignedShort:
+ size = 2
+ case typeUnsignedLong, typeSignedLong, typeSingleFloat:
+ size = 4
+ case typeUnsignedRational, typeSignedRational, typeDoubleFloat:
+ size = 8
+ default:
+ size = 1
+ }
+
+ return size * int(count)
+}
diff --git a/kernel/heif/internal/h265heic/grid.go b/kernel/heif/internal/h265heic/grid.go
new file mode 100644
index 0000000000..ea01aa8a7b
--- /dev/null
+++ b/kernel/heif/internal/h265heic/grid.go
@@ -0,0 +1,411 @@
+package heic
+
+import (
+ "sync"
+ "sync/atomic"
+
+ "github.com/gen2brain/h265/hevc"
+)
+
+const maxGridTiles = 256
+
+type gridInfo struct {
+ rows, cols int
+ w, h int
+}
+
+func parseGrid(b []byte) (gridInfo, error) {
+ r := &reader{b: b}
+ r.u8()
+
+ flags := r.u8()
+
+ var g gridInfo
+
+ g.rows = int(r.u8()) + 1
+ g.cols = int(r.u8()) + 1
+
+ if flags&1 != 0 {
+ g.w, g.h = int(r.u32()), int(r.u32())
+ } else {
+ g.w, g.h = int(r.u16()), int(r.u16())
+ }
+
+ if r.err || g.w <= 0 || g.h <= 0 {
+ return g, ErrInvalid
+ }
+ if g.rows*g.cols > maxGridTiles {
+ return g, ErrUnsupported
+ }
+
+ return g, nil
+}
+
+func (f *file) gridOf(it *item) (gridInfo, []uint32, error) {
+ dataSize, err := f.meta.dataSize(it, f.src)
+ if err != nil {
+ return gridInfo{}, nil, err
+ }
+ if dataSize > 12 {
+ return gridInfo{}, nil, ErrUnsupported
+ }
+ data, err := f.meta.data(it, f.src)
+ if err != nil {
+ return gridInfo{}, nil, err
+ }
+
+ g, err := parseGrid(data)
+ if err != nil {
+ return gridInfo{}, nil, err
+ }
+
+ tiles := f.meta.refsTo("dimg", it.id)
+ if len(tiles) != g.rows*g.cols {
+ return gridInfo{}, nil, ErrInvalid
+ }
+
+ return g, tiles, nil
+}
+
+// decodeImage decodes an item, stitching the tiles first when it is a grid.
+func (f *file) decodeImage(it *item) (*hevc.Picture, error) {
+ if it.unsupported {
+ return nil, ErrUnsupported
+ }
+
+ if it.typ != "grid" {
+ var dec itemDecoder
+ frameLimit := f.limit()
+ if p := f.meta.prop(it, "ispe"); p != nil {
+ frameLimit = codedFrameLimit(uint64(p.w)*uint64(p.h), frameLimit)
+ }
+
+ return f.decodeItem(dec.use(f.workers(0), frameLimit), it)
+ }
+
+ g, tiles, err := f.gridOf(it)
+ if err != nil {
+ return nil, err
+ }
+
+ if n := f.limit(); n > 0 && uint64(g.w)*uint64(g.h) > uint64(n) {
+ return nil, ErrUnsupported
+ }
+
+ return f.decodeTiles(g, tiles)
+}
+
+// decodeTiles decodes the tiles and copies each into its place in the output.
+func (f *file) decodeTiles(g gridInfo, tiles []uint32) (*hevc.Picture, error) {
+ if len(tiles) == 0 {
+ return nil, ErrInvalid
+ }
+ seen := make(map[uint32]struct{}, len(tiles))
+ for _, id := range tiles {
+ if _, exists := seen[id]; exists {
+ return nil, ErrUnsupported
+ }
+ seen[id] = struct{}{}
+ }
+
+ totalFrameLimit := f.limit()
+ if totalFrameLimit > 0 {
+ displayPixels := uint64(g.w) * uint64(g.h)
+ totalFrameLimit = codedFrameLimit(displayPixels+uint64(codedPixelSlack*(len(tiles)-1)), totalFrameLimit)
+ }
+ tileFrameLimit := (totalFrameLimit + len(tiles) - 1) / len(tiles)
+
+ var (
+ out *hevc.Picture
+ tw, th int
+ ready = make(chan struct{})
+ next atomic.Int64
+ fail atomic.Pointer[error]
+ wg sync.WaitGroup
+ )
+
+ setErr := func(err error) { fail.CompareAndSwap(nil, &err) }
+
+ next.Store(1)
+
+ // The tiles already spread across the budget, so each one's wavefront
+ // takes only what is left over rather than multiplying it.
+ tileWorkers := f.workers(len(tiles))
+ perTile := max(f.workers(0)/tileWorkers, 1)
+
+ for range tileWorkers - 1 {
+ wg.Add(1)
+
+ go func() {
+ defer wg.Done()
+
+ var dec itemDecoder
+
+ dec.use(perTile, tileFrameLimit)
+
+ for {
+ i := int(next.Add(1)) - 1
+ if i >= len(tiles) || fail.Load() != nil {
+ return
+ }
+
+ p, err := f.decodeTile(&dec, tiles[i])
+ if err != nil {
+ setErr(err)
+
+ return
+ }
+
+ <-ready
+
+ if fail.Load() != nil {
+ p.Release()
+
+ return
+ }
+
+ if p.CropW != tw || p.CropH != th ||
+ p.ChromaFormat != out.ChromaFormat || p.BitDepth != out.BitDepth ||
+ p.BitDepthC != out.BitDepthC {
+ p.Release()
+ setErr(ErrInvalid)
+
+ return
+ }
+
+ blit(out, p, g, i, tw, th)
+ p.Release()
+ }
+ }()
+ }
+
+ var dec itemDecoder
+
+ dec.use(perTile, tileFrameLimit)
+
+ func() {
+ defer close(ready)
+
+ p, err := f.decodeTile(&dec, tiles[0])
+ if err != nil {
+ setErr(err)
+
+ return
+ }
+
+ defer p.Release()
+
+ tw, th = p.CropW, p.CropH
+ if totalFrameLimit > 0 && uint64(tw)*uint64(th)*uint64(len(tiles)) > uint64(totalFrameLimit) {
+ setErr(ErrUnsupported)
+
+ return
+ }
+ if tw*g.cols < g.w || th*g.rows < g.h {
+ setErr(ErrInvalid)
+
+ return
+ }
+
+ out = newGrid(p, g)
+
+ blit(out, p, g, 0, tw, th)
+ }()
+
+ for fail.Load() == nil {
+ i := int(next.Add(1)) - 1
+ if i >= len(tiles) {
+ break
+ }
+
+ p, err := f.decodeTile(&dec, tiles[i])
+ if err != nil {
+ setErr(err)
+
+ break
+ }
+
+ if p.CropW != tw || p.CropH != th ||
+ p.ChromaFormat != out.ChromaFormat || p.BitDepth != out.BitDepth ||
+ p.BitDepthC != out.BitDepthC {
+ p.Release()
+ setErr(ErrInvalid)
+
+ break
+ }
+
+ blit(out, p, g, i, tw, th)
+ p.Release()
+ }
+
+ wg.Wait()
+
+ if err := fail.Load(); err != nil {
+ return nil, *err
+ }
+
+ return out, nil
+}
+
+func (f *file) decodeTile(dec *itemDecoder, id uint32) (*hevc.Picture, error) {
+ t := f.meta.items[id]
+ if t == nil {
+ return nil, ErrInvalid
+ }
+
+ return f.decodeItem(dec, t)
+}
+
+// newGrid allocates the stitched picture, which may be smaller than the tiles
+// cover.
+func newGrid(first *hevc.Picture, g gridInfo) *hevc.Picture {
+ sw, sh := subsampling(first.ChromaFormat)
+
+ out := &hevc.Picture{
+ Width: g.w,
+ Height: g.h,
+ CropW: g.w,
+ CropH: g.h,
+ ChromaFormat: first.ChromaFormat,
+ BitDepth: first.BitDepth,
+ BitDepthC: first.BitDepthC,
+ StrideY: g.w,
+ }
+
+ if first.ChromaFormat != 0 {
+ out.WidthC = (g.w + sw - 1) / sw
+ out.HeightC = (g.h + sh - 1) / sh
+ out.StrideC = out.WidthC
+ }
+
+ if first.BitDepth > 8 {
+ out.Y16 = make([]uint16, out.StrideY*g.h)
+ out.Cb16 = make([]uint16, out.StrideC*out.HeightC)
+ out.Cr16 = make([]uint16, out.StrideC*out.HeightC)
+
+ return out
+ }
+
+ out.Y = make([]uint8, out.StrideY*g.h)
+ out.Cb = make([]uint8, out.StrideC*out.HeightC)
+ out.Cr = make([]uint8, out.StrideC*out.HeightC)
+
+ return out
+}
+
+func subsampling(chromaFormat int) (int, int) {
+ switch chromaFormat {
+ case 1:
+ return 2, 2
+ case 2:
+ return 2, 1
+ }
+
+ return 1, 1
+}
+
+// blit copies tile i of the grid into its place in out.
+func blit(out, p *hevc.Picture, g gridInfo, i, tw, th int) {
+ sw, sh := subsampling(out.ChromaFormat)
+ row, col := i/g.cols, i%g.cols
+
+ for pl := range 3 {
+ sx, sy := col*tw, row*th
+ cw, ch := tw, th
+ ow, oh := g.w, g.h
+ ss, ds := p.StrideY, out.StrideY
+ sox, soy := p.CropX, p.CropY
+
+ if pl != 0 {
+ if out.ChromaFormat == 0 {
+ return
+ }
+
+ sx, sy = sx/sw, sy/sh
+ cw, ch = cw/sw, ch/sh
+ ow, oh = out.WidthC, out.HeightC
+ ss, ds = p.StrideC, out.StrideC
+ sox, soy = sox/sw, soy/sh
+ }
+
+ cw = min(cw, ow-sx)
+ ch = min(ch, oh-sy)
+
+ if cw <= 0 || ch <= 0 {
+ continue
+ }
+
+ if out.BitDepth > 8 {
+ src, dst := planes16(p, out, pl)
+ for y := range ch {
+ copy(dst[(sy+y)*ds+sx:][:cw], src[(soy+y)*ss+sox:][:cw])
+ }
+
+ continue
+ }
+
+ src, dst := planes8(p, out, pl)
+ for y := range ch {
+ copy(dst[(sy+y)*ds+sx:][:cw], src[(soy+y)*ss+sox:][:cw])
+ }
+ }
+}
+
+func planes8(src, dst *hevc.Picture, pl int) ([]uint8, []uint8) {
+ switch pl {
+ case 0:
+ return src.Y, dst.Y
+ case 1:
+ return src.Cb, dst.Cb
+ default:
+ return src.Cr, dst.Cr
+ }
+}
+
+func planes16(src, dst *hevc.Picture, pl int) ([]uint16, []uint16) {
+ switch pl {
+ case 0:
+ return src.Y16, dst.Y16
+ case 1:
+ return src.Cb16, dst.Cb16
+ default:
+ return src.Cr16, dst.Cr16
+ }
+}
+
+// gridAlpha assembles a grid's alpha from the auxiliary items on its tiles.
+func (f *file) gridAlpha(it *item) (*hevc.Picture, error) {
+ g, tiles, err := f.gridOf(it)
+ if err != nil {
+ return nil, err
+ }
+
+ alpha := make([]uint32, len(tiles))
+
+ for i, id := range tiles {
+ a := f.alphaOf(id)
+ if a == nil {
+ return nil, nil
+ }
+
+ alpha[i] = a.id
+ }
+
+ return f.decodeTiles(g, alpha)
+}
+
+func (f *file) hasAlpha(it *item) (bool, error) {
+ if it.typ != "grid" {
+ return f.alphaOf(it.id) != nil, nil
+ }
+ _, tiles, err := f.gridOf(it)
+ if err != nil {
+ return false, err
+ }
+ for _, id := range tiles {
+ if f.alphaOf(id) != nil {
+ return true, nil
+ }
+ }
+ return false, nil
+}
diff --git a/kernel/heif/internal/h265heic/heic.go b/kernel/heif/internal/h265heic/heic.go
new file mode 100644
index 0000000000..c1506a8e57
--- /dev/null
+++ b/kernel/heif/internal/h265heic/heic.go
@@ -0,0 +1,696 @@
+/*
+Package heic decodes HEIF images that carry HEVC-coded item data, the format
+commonly called HEIC.
+
+# Color
+
+[Decode] returns RGB, converted with the matrix and range the file declares in
+its nclx color description. [Options.ToYCbCr] skips that and hands back the
+planes the bitstream carries: *[image.YCbCr], *[image.NYCbCrA] with alpha, or
+*[image.Gray] for monochrome. Above 8 bits there is no such image type, so
+*[image.NRGBA64] is returned anyway.
+
+[image.YCbCr] reads its planes as full-range BT.601 whatever the file signals,
+which is rarely what a HEIC file means. [DecodeColor] reports what they
+actually are, so ToYCbCr is for reaching the samples rather than for display:
+
+ img, ci, err := heic.DecodeColor(r, heic.Options{ToYCbCr: true})
+
+[ColorInfo] carries the CICP code points and the range flag, plus the ICC
+profile when the file has one. Matrix and FullRange are what the conversion to
+RGB uses. Primaries and Transfer are reported but not applied, so RGB output
+stays in the file's own color space.
+
+# Metadata
+
+[DecodeExif] reads the Exif item a file describes its image with, and
+[RawExif] and [RawXMP] return the payloads unparsed.
+*/
+package heic
+
+import (
+ "errors"
+ "image"
+ "io"
+ "runtime"
+
+ "github.com/gen2brain/h265/hevc"
+)
+
+// ErrUnsupported is returned for a file this package cannot render but which
+// is otherwise well formed: an essential property it does not implement, or a
+// sample format it has no conversion for. A caller that has another decoder to
+// fall back on should test for this one rather than [ErrInvalid].
+var ErrUnsupported = errors.New("heic: unsupported image")
+
+// DefaultFrameSizeLimit 限制文件头能够请求分配的像素面积。
+const DefaultFrameSizeLimit = 50_000_000
+
+// ColorInfo describes the color space an image was decoded from.
+type ColorInfo struct {
+ Primaries uint16
+ Transfer uint16
+ Matrix uint16
+ FullRange bool
+ // ICCP is the embedded ICC profile, for files that carry one in place of
+ // an nclx description. It aliases the input, so it is not a copy.
+ ICCP []byte
+}
+
+// Options controls decoding.
+type Options struct {
+ // AutoRotate applies the clap/irot/imir transforms, forcing NRGBA output
+ // when it transforms.
+ AutoRotate bool
+ // FrameSizeLimit 限制单帧的像素面积,零值或过大的值会使用 DefaultFrameSizeLimit。
+ FrameSizeLimit int
+ // ToYCbCr forces the image's native color space instead of NRGBA:
+ // *image.YCbCr, *image.NYCbCrA when there is alpha, or *image.Gray when
+ // the image is monochrome. Above 8 bits NRGBA64 is returned anyway.
+ // image.YCbCr reads the planes as full-range BT.601 whatever the file
+ // signals, so this is for reaching the samples, not for display.
+ // DecodeColor reports what the samples actually are.
+ ToYCbCr bool
+ // Threads 保留接口兼容性,解码始终使用单线程。
+ Threads int
+}
+
+func options(opts []Options) Options {
+ var ret Options
+ if len(opts) > 0 {
+ ret = opts[0]
+ }
+ if ret.FrameSizeLimit <= 0 || ret.FrameSizeLimit > DefaultFrameSizeLimit {
+ ret.FrameSizeLimit = DefaultFrameSizeLimit
+ }
+ ret.Threads = 1
+
+ return ret
+}
+
+type file struct {
+ src *source
+ meta *metaBox
+ frameSizeLimit int
+ threads int
+ decodedBytes uint64
+}
+
+func (f *file) consumeDecodedBytes(size uint64) error {
+ if f.decodedBytes > maxItemDataBytes || size > maxItemDataBytes-f.decodedBytes {
+ return ErrUnsupported
+ }
+ f.decodedBytes += size
+ return nil
+}
+
+// workers is how many goroutines a grid may use, never more than it has tiles.
+func (f *file) workers(n int) int {
+ w := f.threads
+ if w == 0 {
+ w = runtime.GOMAXPROCS(0)
+ }
+
+ if n <= 0 {
+ return max(w, 1)
+ }
+
+ return max(min(w, n), 1)
+}
+
+// HEIC holds the images of a file, which may be an image sequence.
+type HEIC struct {
+ // Image holds the decoded frames, *image.NRGBA or *image.NRGBA64.
+ Image []image.Image
+ // Delay holds each frame's duration in seconds.
+ Delay []float64
+ // LoopCount controls how many times the animation restarts, following
+ // image/gif: zero loops forever, -1 shows each frame once, and any other
+ // value plays the animation LoopCount+1 times.
+ LoopCount int
+ // Color describes the color space the frames were decoded from.
+ Color ColorInfo
+}
+
+func parse(src *source) (*file, error) {
+ if src == nil || src.size == 0 {
+ return nil, ErrInvalid
+ }
+ if src.size > maxContainerBytes {
+ return nil, ErrUnsupported
+ }
+
+ f := &file{src: src}
+
+ seen := false
+
+ err := src.eachBox(func(typ string, off, n uint64) error {
+ // Only these carry anything parse needs, so the media data is never
+ // read here: the items that reference it are read on demand.
+ switch typ {
+ case "ftyp":
+ seen = true
+
+ return nil
+ case "meta":
+ if f.meta != nil {
+ return nil
+ }
+ if n > maxMetadataBytes {
+ return ErrUnsupported
+ }
+
+ b, err := src.at(off, n)
+ if err != nil {
+ return err
+ }
+ m, err := parseMeta(b)
+ if err != nil {
+ return err
+ }
+ f.meta = m
+
+ return nil
+ case "moov", "mini":
+ // The MinimizedImageBox of the low overhead profile carries the
+ // whole description in place of meta, so a file built on it is one
+ // we can read nothing from rather than a malformed one.
+ return ErrUnsupported
+ default:
+ return nil
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if !seen || f.meta == nil {
+ return nil, ErrInvalid
+ }
+
+ return f, nil
+}
+
+// srcFor addresses the file by range when the reader allows it, so only the
+// items a decode reaches are read. Anything else is buffered whole, which is
+// what image.Decode leaves us with: it hands the decoder a bufio.Reader.
+func srcFor(r io.Reader) (*source, error) {
+ ra, raOK := r.(io.ReaderAt)
+ sk, skOK := r.(io.Seeker)
+
+ if raOK && skOK {
+ cur, err1 := sk.Seek(0, io.SeekCurrent)
+ end, err2 := sk.Seek(0, io.SeekEnd)
+
+ if err1 == nil && err2 == nil && end > cur {
+ n := end - cur
+ if n > maxContainerBytes {
+ return nil, ErrUnsupported
+ }
+
+ return &source{r: io.NewSectionReader(ra, cur, n), size: uint64(n)}, nil
+ }
+ }
+
+ data, err := io.ReadAll(io.LimitReader(r, maxContainerBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(data) > maxContainerBytes {
+ return nil, ErrUnsupported
+ }
+
+ return memSource(data), nil
+}
+
+// parseHeader reads only the boxes a configuration needs and stops as soon as
+// one can be derived, so a stream that cannot be addressed by range still
+// costs no more than its header.
+func parseHeader(r io.Reader) (*file, error) {
+ f := &file{}
+
+ seen := false
+
+ err := eachBoxReader(r, func(typ string, n int64, body io.Reader) error {
+ switch typ {
+ case "ftyp":
+ seen = true
+
+ case "meta":
+ if f.meta != nil {
+ return nil
+ }
+
+ b, err := boxBytes(body, n)
+ if err != nil {
+ return err
+ }
+
+ m, err := parseMeta(b)
+ if err != nil {
+ return err
+ }
+
+ f.meta = m
+
+ case "moov":
+ return ErrUnsupported
+
+ default:
+ return nil
+ }
+
+ // Only a configuration from the primary item ends the walk. A picture
+ // track is the fallback for a file that has no usable image item, and
+ // a meta box after moov would still outrank it.
+ if seen {
+ if _, err := f.config(); err == nil {
+ return errStop
+ }
+ }
+
+ return nil
+ })
+ if err != nil && !errors.Is(err, errStop) {
+ return nil, err
+ }
+
+ if !seen || f.meta == nil {
+ return nil, ErrInvalid
+ }
+
+ return f, nil
+}
+
+// config is the image configuration of the primary item, or of the picture
+// track when a file carries no image item.
+func (f *file) config() (image.Config, error) {
+ it, err := f.primary()
+ if err != nil {
+ return image.Config{}, err
+ }
+
+ w, h, err := f.size(it)
+ if err != nil {
+ return image.Config{}, err
+ }
+
+ return image.Config{Width: w, Height: h, ColorModel: colorModelFor(f, it)}, nil
+}
+
+func (f *file) limit() int {
+ switch {
+ case f.frameSizeLimit < 0:
+ return 0
+ case f.frameSizeLimit == 0:
+ return DefaultFrameSizeLimit
+ }
+
+ return f.frameSizeLimit
+}
+
+// primary is the item a file describes itself with.
+func (f *file) primary() (*item, error) {
+ if f.meta == nil {
+ return nil, ErrInvalid
+ }
+
+ it := f.meta.items[f.meta.primary]
+ if it == nil {
+ return nil, ErrInvalid
+ }
+
+ if it.unsupported {
+ return nil, ErrUnsupported
+ }
+
+ return it, nil
+}
+
+// alphaOf finds the auxiliary item that carries this item's alpha channel.
+func (f *file) alphaOf(id uint32) *item {
+ for _, r := range f.meta.refs {
+ if r.typ != "auxl" || len(r.to) == 0 || r.to[0] != id {
+ continue
+ }
+
+ it := f.meta.items[r.from]
+ if it == nil || it.unsupported {
+ continue
+ }
+
+ if p := f.meta.prop(it, "auxC"); p != nil && isAlphaURN(p.auxC) {
+ return it
+ }
+ }
+
+ return nil
+}
+
+func isAlphaURN(s string) bool {
+ return s == "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha" ||
+ s == "urn:mpeg:hevc:2015:auxid:1"
+}
+
+// itemDecoder carries the decoder across the tiles of a grid, which keeps the
+// per-picture buffers allocated once, together with the configuration already
+// fed to it so the tiles after the first skip the parameter sets they share.
+type itemDecoder struct {
+ d hevc.Decoder
+ cfg *hevcConfig
+ frameSizeLimit int
+}
+
+// use 设置解码器的并发和分配上限。
+func (dec *itemDecoder) use(threads, frameSizeLimit int) *itemDecoder {
+ dec.d.Threads(threads)
+ dec.d.FrameSizeLimit(frameSizeLimit)
+ dec.frameSizeLimit = frameSizeLimit
+
+ return dec
+}
+
+func (f *file) decodeItem(dec *itemDecoder, it *item) (*hevc.Picture, error) {
+ if it.typ == "grid" {
+ return nil, ErrUnsupported
+ }
+
+ if it.typ != "hvc1" {
+ return nil, ErrUnsupported
+ }
+
+ cfg := f.meta.prop(it, "hvcC")
+ if cfg == nil || cfg.hvcC == nil {
+ return nil, ErrInvalid
+ }
+
+ if n := f.limit(); n > 0 {
+ if p := f.meta.prop(it, "ispe"); p != nil && uint64(p.w)*uint64(p.h) > uint64(n) {
+ return nil, ErrUnsupported
+ }
+ }
+
+ if dec.cfg != cfg.hvcC {
+ spsCount := 0
+ for _, nal := range cfg.hvcC.paramSets {
+ u, ok := hevc.ParseNAL(nal)
+ if !ok || u.Type.IsVCL() {
+ return nil, ErrInvalid
+ }
+ if u.Type == hevc.NALSPS {
+ spsCount++
+ if err := validateSPSLimits(u, dec.frameSizeLimit); err != nil {
+ return nil, err
+ }
+ }
+
+ if _, err := dec.d.DecodeNAL(u); err != nil {
+ return nil, wrap(err)
+ }
+ }
+ if spsCount == 0 {
+ return nil, ErrInvalid
+ }
+
+ dec.cfg = cfg.hvcC
+ }
+
+ dataSize, err := f.meta.dataSize(it, f.src)
+ if err != nil {
+ return nil, err
+ }
+ if err = f.consumeDecodedBytes(dataSize); err != nil {
+ return nil, err
+ }
+ data, err := f.meta.data(it, f.src)
+ if err != nil {
+ return nil, err
+ }
+
+ pictureStarts := 0
+ vclCount := 0
+ err = eachHVCC(data, cfg.hvcC.lengthSize, func(u hevc.NALUnit) error {
+ if !u.Type.IsVCL() {
+ if u.Type == hevc.NALVPS || u.Type == hevc.NALSPS || u.Type == hevc.NALPPS {
+ return ErrUnsupported
+ }
+ return nil
+ }
+ if u.Type != hevc.NALIdrWRadl && u.Type != hevc.NALIdrNLP {
+ return ErrUnsupported
+ }
+ vclCount++
+ if vclCount > 1 {
+ return ErrUnsupported
+ }
+ if len(u.RBSP) == 0 {
+ return ErrInvalid
+ }
+ if u.RBSP[0]&0x80 != 0 {
+ pictureStarts++
+ if pictureStarts > 1 {
+ return ErrUnsupported
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ if pictureStarts != 1 || vclCount != 1 {
+ return nil, ErrInvalid
+ }
+
+ var out []*hevc.Picture
+ err = eachHVCC(data, cfg.hvcC.lengthSize, func(u hevc.NALUnit) error {
+ pics, decodeErr := dec.d.DecodeNAL(u)
+ if decodeErr != nil {
+ return wrap(decodeErr)
+ }
+ out = append(out, pics...)
+ if len(out) > 1 {
+ return ErrUnsupported
+ }
+ return nil
+ })
+ if err != nil {
+ for _, pic := range out {
+ pic.Release()
+ }
+ return nil, err
+ }
+ out = append(out, dec.d.Flush()...)
+
+ if len(out) != 1 {
+ for _, pic := range out {
+ pic.Release()
+ }
+ if len(out) > 1 {
+ return nil, ErrUnsupported
+ }
+ return nil, ErrInvalid
+ }
+
+ return out[0], nil
+}
+
+func eachHVCC(data []byte, lengthSize int, fn func(hevc.NALUnit) error) error {
+ if lengthSize < 1 || lengthSize > 4 {
+ return ErrInvalid
+ }
+ count := 0
+ for offset := 0; offset < len(data); {
+ if len(data)-offset < lengthSize {
+ return ErrInvalid
+ }
+ n := uint64(0)
+ for range lengthSize {
+ n = n<<8 | uint64(data[offset])
+ offset++
+ }
+ if n < 2 || n > maxNALBytes || n > uint64(len(data)-offset) {
+ return ErrInvalid
+ }
+ count++
+ if count > maxNALUnits {
+ return ErrUnsupported
+ }
+ nal, ok := hevc.ParseNAL(data[offset : offset+int(n)])
+ if !ok {
+ return ErrInvalid
+ }
+ if err := fn(nal); err != nil {
+ return err
+ }
+ offset += int(n)
+ }
+ if count == 0 {
+ return ErrInvalid
+ }
+ return nil
+}
+
+func wrap(err error) error {
+ if errors.Is(err, hevc.ErrUnsupported) {
+ return ErrUnsupported
+ }
+
+ return ErrInvalid
+}
+
+// decodeStill decodes the primary item, its alpha, and any grid it derives
+// from, and converts the result.
+func (f *file) decodeStill(o Options) (image.Image, ColorInfo, error) {
+ it, err := f.primary()
+ if err != nil {
+ return nil, ColorInfo{}, err
+ }
+ hasAlpha, err := f.hasAlpha(it)
+ if err != nil {
+ return nil, ColorInfo{}, err
+ }
+ if hasAlpha {
+ return nil, ColorInfo{}, ErrUnsupported
+ }
+
+ pic, err := f.decodeImage(it)
+ if err != nil {
+ return nil, ColorInfo{}, err
+ }
+ defer pic.Release()
+
+ // ISO/IEC 23008-12 7.2.1: ispe is the displayed size.
+ f.clampToISPE(it, pic)
+
+ ci := f.colorInfo(it, pic)
+
+ img, err := toImage(pic, nil, ci, o.ToYCbCr)
+ if err != nil {
+ return nil, ci, err
+ }
+
+ if o.AutoRotate {
+ img, err = f.transform(it, img)
+ if err != nil {
+ return nil, ci, err
+ }
+ }
+
+ return img, ci, nil
+}
+
+// Decode 将 HEIC 静态图像解码为 *image.NRGBA。
+func Decode(r io.Reader, opts ...Options) (image.Image, error) {
+ img, _, err := decode(r, opts...)
+
+ return img, err
+}
+
+// DecodeBytes 直接使用调用方提供的只读字节,避免复制单 extent 图像数据。
+func DecodeBytes(data []byte, opts ...Options) (image.Image, error) {
+ img, _, err := decodeSource(memSource(data), opts...)
+
+ return img, err
+}
+
+// DecodeColor is Decode, and also reports the color space the image was
+// decoded from.
+func DecodeColor(r io.Reader, opts ...Options) (image.Image, ColorInfo, error) {
+ return decode(r, opts...)
+}
+
+func decode(r io.Reader, opts ...Options) (image.Image, ColorInfo, error) {
+ src, err := srcFor(r)
+ if err != nil {
+ return nil, ColorInfo{}, err
+ }
+ return decodeSource(src, opts...)
+}
+
+func decodeSource(src *source, opts ...Options) (image.Image, ColorInfo, error) {
+ f, err := parse(src)
+ if err != nil {
+ return nil, ColorInfo{}, err
+ }
+
+ o := options(opts)
+ f.frameSizeLimit = o.FrameSizeLimit
+ f.threads = o.Threads
+
+ return f.decodeStill(o)
+}
+
+// DecodeAll 返回包含单张静态图像的结果;序列容器不在该适配层的支持范围内。
+func DecodeAll(r io.Reader, opts ...Options) (*HEIC, error) {
+ src, err := srcFor(r)
+ if err != nil {
+ return nil, err
+ }
+
+ f, err := parse(src)
+ if err != nil {
+ return nil, err
+ }
+
+ o := options(opts)
+ f.frameSizeLimit = o.FrameSizeLimit
+ f.threads = o.Threads
+
+ img, ci, err := f.decodeStill(o)
+ if err != nil {
+ return nil, err
+ }
+
+ return &HEIC{Image: []image.Image{img}, Delay: []float64{0}, Color: ci}, nil
+}
+
+// DecodeConfig returns the dimensions and color model without decoding the
+// image data.
+func DecodeConfig(r io.Reader) (image.Config, error) {
+ src, err := srcFor(r)
+ if err != nil {
+ return image.Config{}, err
+ }
+ f, err := parse(src)
+ if err != nil {
+ return image.Config{}, err
+ }
+
+ return f.config()
+}
+
+// DecodeConfigBytes 读取调用方提供的只读字节并返回静态图像尺寸。
+func DecodeConfigBytes(data []byte) (image.Config, error) {
+ f, err := parse(memSource(data))
+ if err != nil {
+ return image.Config{}, err
+ }
+
+ return f.config()
+}
+
+// clampToISPE trims a decoded picture to the size the item declares.
+func (f *file) clampToISPE(it *item, pic *hevc.Picture) {
+ p := f.meta.prop(it, "ispe")
+ if p == nil {
+ return
+ }
+
+ pic.CropW = min(pic.CropW, int(p.w))
+ pic.CropH = min(pic.CropH, int(p.h))
+}
+
+// size is the stored size of an item, which is what Decode returns unless
+// AutoRotate transforms it.
+func (f *file) size(it *item) (int, int, error) {
+ p := f.meta.prop(it, "ispe")
+ if p == nil {
+ return 0, 0, ErrInvalid
+ }
+
+ if p.w == 0 || p.h == 0 || p.w > 1<<20 || p.h > 1<<20 {
+ return 0, 0, ErrInvalid
+ }
+
+ return int(p.w), int(p.h), nil
+}
diff --git a/kernel/heif/internal/h265heic/image.go b/kernel/heif/internal/h265heic/image.go
new file mode 100644
index 0000000000..11f2736635
--- /dev/null
+++ b/kernel/heif/internal/h265heic/image.go
@@ -0,0 +1,243 @@
+package heic
+
+import (
+ "image"
+ "image/color"
+
+ "github.com/gen2brain/h265/hevc"
+)
+
+func colorModelFor(f *file, it *item) color.Model {
+ return color.NRGBAModel
+}
+
+func (f *file) colorInfo(it *item, pic *hevc.Picture) ColorInfo {
+ ci := ColorInfo{Matrix: mcUnspec, Primaries: 2, Transfer: 2}
+
+ p := f.meta.prop(it, "colr")
+ if p == nil || p.colr == nil {
+ return ci
+ }
+
+ if p.colr.hasNCLX {
+ ci.Primaries = p.colr.primaries
+ ci.Transfer = p.colr.transfer
+ ci.Matrix = p.colr.matrix
+ ci.FullRange = p.colr.fullRange
+ }
+
+ ci.ICCP = p.colr.icc
+
+ return ci
+}
+
+// aliasesPicture reports whether img shares memory with the decoded planes.
+func aliasesPicture(img image.Image) bool {
+ switch img.(type) {
+ case *image.YCbCr, *image.NYCbCrA, *image.Gray:
+ return true
+ }
+
+ return false
+}
+
+// planar wraps the decoded planes without converting them, which is what the
+// bitstream already holds.
+func planar(pic, alpha *hevc.Picture) (image.Image, bool) {
+ if pic.BitDepth != 8 {
+ return nil, false
+ }
+
+ y, cb, cr := views(pic)
+ rect := image.Rect(0, 0, pic.CropW, pic.CropH)
+
+ if pic.ChromaFormat == 0 {
+ if alpha != nil {
+ return nil, false
+ }
+
+ return &image.Gray{Pix: y.p8, Stride: y.stride, Rect: rect}, true
+ }
+
+ var ratio image.YCbCrSubsampleRatio
+
+ switch pic.ChromaFormat {
+ case 1:
+ ratio = image.YCbCrSubsampleRatio420
+ case 2:
+ ratio = image.YCbCrSubsampleRatio422
+ case 3:
+ ratio = image.YCbCrSubsampleRatio444
+ default:
+ return nil, false
+ }
+
+ yc := image.YCbCr{
+ Y: y.p8, Cb: cb.p8, Cr: cr.p8,
+ YStride: y.stride, CStride: cb.stride,
+ SubsampleRatio: ratio, Rect: rect,
+ }
+
+ if alpha == nil {
+ return &yc, true
+ }
+
+ if alpha.BitDepth != 8 || alpha.ChromaFormat != 0 {
+ return nil, false
+ }
+
+ ay, _, _ := views(alpha)
+ if ay.w != pic.CropW || ay.h != pic.CropH {
+ return nil, false
+ }
+
+ return &image.NYCbCrA{YCbCr: yc, A: ay.p8, AStride: ay.stride}, true
+}
+
+func toImage(pic, alpha *hevc.Picture, ci ColorInfo, ycbcr bool) (image.Image, error) {
+ if ycbcr {
+ if img, ok := planar(pic, alpha); ok {
+ return img, nil
+ }
+ }
+
+ const outDepth = 8
+
+ cs := newColorState(pic, ci, outDepth)
+ if cs.unsupported {
+ return nil, ErrUnsupported
+ }
+
+ y, cb, cr := views(pic)
+ if !y.valid() {
+ return nil, ErrInvalid
+ }
+
+ w, h := y.w, y.h
+ rect := image.Rect(0, 0, w, h)
+
+ cs.prepare(w)
+
+ if cs.fastRow(outDepth) {
+ cs.consts = cs.rowConsts()
+
+ if outDepth == 8 {
+ cs.row = rowFn(cs.ssHor)
+ } else {
+ cs.row16 = rowFn16(cs.ssHor)
+ }
+ }
+
+ var (
+ as *colorState
+ av planeView
+ )
+
+ if alpha != nil {
+ // An auxiliary alpha image carries its values in the luma channel, so
+ // chroma planes are padding whatever the file codes them as.
+ av, _, _ = views(alpha)
+ if av.w != w || av.h != h {
+ return nil, ErrUnsupported
+ }
+
+ as = alphaState(alpha, outDepth, true)
+ as.prepare(w)
+ }
+
+ rgb := make([]uint16, 3*w)
+ aRow := make([]uint16, w)
+
+ if as == nil {
+ for x := range aRow {
+ aRow[x] = uint16(cs.outMax)
+ }
+ }
+
+ if outDepth == 8 {
+ dst := image.NewNRGBA(rect)
+
+ if cs.row != nil {
+ ab := make([]uint8, w)
+ for i := range ab {
+ ab[i] = 0xff
+ }
+
+ for row := range h {
+ if as != nil {
+ as.alphaRow(av, row, w, aRow)
+
+ for i, v := range aRow {
+ ab[i] = uint8(v)
+ }
+ }
+
+ u0, u1, v0, v1 := cs.rowPlanes(cb, cr, row, w, h)
+ cs.row(dst.Pix[row*dst.Stride:], cs.lumaRowF(y, row, w),
+ u0, u1, v0, v1, ab, w, &cs.consts)
+ }
+
+ return dst, nil
+ }
+
+ for row := range h {
+ cs.rgbRow(y, cb, cr, row, rgb)
+
+ if as != nil {
+ as.alphaRow(av, row, w, aRow)
+ }
+
+ o := row * dst.Stride
+ for x := range w {
+ dst.Pix[o] = uint8(rgb[3*x])
+ dst.Pix[o+1] = uint8(rgb[3*x+1])
+ dst.Pix[o+2] = uint8(rgb[3*x+2])
+ dst.Pix[o+3] = uint8(aRow[x])
+ o += 4
+ }
+ }
+
+ return dst, nil
+ }
+
+ dst := image.NewNRGBA64(rect)
+
+ if cs.row16 != nil {
+ for row := range h {
+ if as != nil {
+ as.alphaRow(av, row, w, aRow)
+ }
+
+ u0, u1, v0, v1 := cs.rowPlanes(cb, cr, row, w, h)
+ cs.row16(dst.Pix[row*dst.Stride:], cs.lumaRowF(y, row, w),
+ u0, u1, v0, v1, aRow, w, &cs.consts)
+ }
+
+ return dst, nil
+ }
+
+ for row := range h {
+ cs.rgbRow(y, cb, cr, row, rgb)
+
+ if as != nil {
+ as.alphaRow(av, row, w, aRow)
+ }
+
+ o := row * dst.Stride
+ for x := range w {
+ r, g, b, a := rgb[3*x], rgb[3*x+1], rgb[3*x+2], aRow[x]
+
+ dst.Pix[o] = uint8(r >> 8)
+ dst.Pix[o+1] = uint8(r)
+ dst.Pix[o+2] = uint8(g >> 8)
+ dst.Pix[o+3] = uint8(g)
+ dst.Pix[o+4] = uint8(b >> 8)
+ dst.Pix[o+5] = uint8(b)
+ dst.Pix[o+6] = uint8(a >> 8)
+ dst.Pix[o+7] = uint8(a)
+ o += 8
+ }
+ }
+
+ return dst, nil
+}
diff --git a/kernel/heif/internal/h265heic/isobmff.go b/kernel/heif/internal/h265heic/isobmff.go
new file mode 100644
index 0000000000..87e1a899b3
--- /dev/null
+++ b/kernel/heif/internal/h265heic/isobmff.go
@@ -0,0 +1,984 @@
+package heic
+
+import (
+ "errors"
+ "io"
+ "slices"
+)
+
+const (
+ maxContainerBytes = 32 << 20
+ maxMetadataBytes = 16 << 20
+ maxItems = 4096
+ maxProperties = 4096
+ maxItemExtents = 16384
+ maxItemReferences = 16384
+ maxItemProperties = 16384
+ maxItemDataBytes = 32 << 20
+ maxParameterSets = 64
+ maxParameterBytes = 1 << 20
+ maxNALUnits = 65536
+ maxNALBytes = 32 << 20
+ maxMetadataBoxes = 65536
+ maxTopLevelBoxes = 4096
+)
+
+// ErrInvalid is returned when a file is not a HEIF, or is malformed past the
+// point where anything can be decoded from it.
+var ErrInvalid = errors.New("heic: invalid file")
+
+type reader struct {
+ b []byte
+ i int
+ err bool
+}
+
+func (r *reader) remaining() int {
+ if r.err {
+ return 0
+ }
+
+ return len(r.b) - r.i
+}
+
+func (r *reader) fail() {
+ r.err = true
+ r.i = len(r.b)
+}
+
+func (r *reader) bytes(n int) []byte {
+ if n < 0 || r.remaining() < n {
+ r.fail()
+
+ return nil
+ }
+ v := r.b[r.i : r.i+n]
+ r.i += n
+
+ return v
+}
+
+func (r *reader) skip(n int) {
+ r.bytes(n)
+}
+
+func (r *reader) u8() uint8 {
+ b := r.bytes(1)
+ if b == nil {
+ return 0
+ }
+
+ return b[0]
+}
+
+func (r *reader) uint(n int) uint64 {
+ b := r.bytes(n)
+ var v uint64
+ for _, c := range b {
+ v = v<<8 | uint64(c)
+ }
+
+ return v
+}
+
+func (r *reader) u16() uint16 { return uint16(r.uint(2)) }
+func (r *reader) u32() uint32 { return uint32(r.uint(4)) }
+func (r *reader) u64() uint64 { return r.uint(8) }
+
+// boxNames interns the four-character codes the parser compares against, so
+// reading a header allocates nothing. An unknown box is skipped on its size
+// alone, and its name never leaves this function.
+var boxNames = func() map[[4]byte]string {
+ m := make(map[[4]byte]string)
+
+ for _, s := range []string{
+ "ftyp", "meta", "hdlr", "pitm", "iinf", "infe", "iloc", "iref", "iprp",
+ "ipco", "ipma", "hvcC", "ispe", "colr", "pixi", "irot", "imir", "clap",
+ "auxC", "idat", "mdat", "moov", "trak", "mdia", "minf", "stbl", "stsd",
+ "stts", "stsc", "stsz", "stco", "co64", "tkhd", "mvhd", "hvc1", "hvc2",
+ "grid", "Exif", "mime", "iprd", "free", "skip", "url ", "dinf", "dref",
+ } {
+ m[[4]byte([]byte(s))] = s
+ }
+
+ return m
+}()
+
+func (r *reader) str4() string {
+ b := r.bytes(4)
+ if b == nil {
+ return ""
+ }
+
+ if s, ok := boxNames[[4]byte(b)]; ok {
+ return s
+ }
+
+ return string(b)
+}
+
+func (r *reader) cstr() string {
+ for j := r.i; j < len(r.b); j++ {
+ if r.b[j] == 0 {
+ s := string(r.b[r.i:j])
+ r.i = j + 1
+
+ return s
+ }
+ }
+ r.fail()
+
+ return ""
+}
+
+func (r *reader) fullBox() (uint8, uint32) {
+ v := r.u32()
+
+ return uint8(v >> 24), v & 0xffffff
+}
+
+// eachBox calls fn for every box in b.
+func eachBox(b []byte, fn func(typ string, payload []byte) error) error {
+ r := &reader{b: b}
+ count := 0
+
+ for r.remaining() >= 8 {
+ count++
+ if count > maxMetadataBoxes {
+ return ErrUnsupported
+ }
+ start := r.i
+ size := uint64(r.u32())
+ typ := r.str4()
+ hdr := 8
+
+ switch size {
+ case 1:
+ size = r.u64()
+ hdr = 16
+ case 0:
+ size = uint64(len(b) - start)
+ }
+ if r.err || size < uint64(hdr) || size > uint64(len(b)-start) {
+ return ErrInvalid
+ }
+
+ payload := b[start+hdr : start+int(size)]
+ if typ == "uuid" {
+ r.i = start + int(size)
+
+ continue
+ }
+ if err := fn(typ, payload); err != nil {
+ return err
+ }
+ r.i = start + int(size)
+ }
+
+ if r.err {
+ return ErrInvalid
+ }
+
+ return nil
+}
+
+type extent struct {
+ off, len uint64
+}
+
+type item struct {
+ id uint32
+ typ string
+ contentType string
+ extents []extent
+
+ method uint8
+ baseOffset uint64
+
+ props []itemProp
+
+ unsupported bool
+}
+
+type itemProp struct {
+ idx int
+ essential bool
+}
+
+type itemRef struct {
+ typ string
+ from uint32
+ to []uint32
+}
+
+type property struct {
+ typ string
+
+ w, h uint32
+ hvcC *hevcConfig
+ pixi []uint8
+ auxC string
+ angle uint8
+ axis uint8
+ clap [8]uint32
+ colr *colorInfo
+}
+
+// hevcConfig is the HEVCDecoderConfigurationRecord of ISO/IEC 14496-15. The
+// parameter sets travel in it rather than in the item data.
+type hevcConfig struct {
+ chromaFormat uint8
+ bitDepthLuma uint8
+ bitDepthChroma uint8
+ lengthSize int
+ paramSets [][]byte
+}
+
+type colorInfo struct {
+ icc []byte
+ primaries uint16
+ transfer uint16
+ matrix uint16
+ fullRange bool
+ hasNCLX bool
+}
+
+type metaBox struct {
+ primary uint32
+ items map[uint32]*item
+ order []uint32
+ props []property
+ refs []itemRef
+ idat []byte
+
+ extentCount int
+ referenceCount int
+ propertyCount int
+}
+
+// source is the file, addressed by range. b carries it when it is buffered,
+// and r reads it a range at a time when it is not.
+type source struct {
+ b []byte
+ r io.ReaderAt
+ size uint64
+}
+
+func memSource(b []byte) *source {
+ return &source{b: b, size: uint64(len(b))}
+}
+
+// at returns n bytes at off. It aliases a buffered file, so the result must
+// not be written to.
+func (s *source) at(off, n uint64) ([]byte, error) {
+ if off > s.size || n > s.size-off {
+ return nil, ErrInvalid
+ }
+
+ if s.r == nil {
+ return s.b[off : off+n], nil
+ }
+
+ buf := make([]byte, n)
+
+ _, err := io.ReadFull(io.NewSectionReader(s.r, int64(off), int64(n)), buf)
+
+ switch {
+ case err == nil:
+ return buf, nil
+ case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
+ return nil, ErrInvalid
+ }
+
+ return nil, err
+}
+
+// eachBox reports where each top level payload lives without reading it.
+func (s *source) eachBox(fn func(typ string, off, n uint64) error) error {
+ count := 0
+ for off := uint64(0); off+8 <= s.size; {
+ count++
+ if count > maxTopLevelBoxes {
+ return ErrUnsupported
+ }
+ b, err := s.at(off, 8)
+ if err != nil {
+ return err
+ }
+
+ r := &reader{b: b}
+ size := uint64(r.u32())
+ typ := r.str4()
+ head := uint64(8)
+
+ switch size {
+ case 1:
+ if off+16 > s.size {
+ return ErrInvalid
+ }
+
+ b, err = s.at(off+8, 8)
+ if err != nil {
+ return err
+ }
+
+ rr := &reader{b: b}
+ size = rr.u64()
+ head = 16
+ r.err = r.err || rr.err
+
+ case 0:
+ size = s.size - off
+ }
+
+ if r.err || size < head || size > s.size-off {
+ return ErrInvalid
+ }
+
+ if typ != "uuid" {
+ if err := fn(typ, off+head, size-head); err != nil {
+ return err
+ }
+ }
+
+ off += size
+ }
+
+ return nil
+}
+
+// maxHeaderBox bounds a box eachBoxReader buffers, since its size comes from
+// the file being read.
+const maxHeaderBox = maxMetadataBytes
+
+// errStop ends a walk from inside the callback.
+var errStop = errors.New("heic: stop")
+
+// eachBoxReader walks the top-level boxes of a stream. fn reads as much of a
+// box as it wants from body, whose length is n, or -1 when the box runs to the
+// end of the file; the rest is discarded before the next box. Boxes fn does
+// not read are never buffered, so a caller after the header alone does not pay
+// for the media data behind it.
+func eachBoxReader(r io.Reader, fn func(typ string, n int64, body io.Reader) error) error {
+ var hdr [16]byte
+ count := 0
+
+ for {
+ count++
+ if count > maxTopLevelBoxes {
+ return ErrUnsupported
+ }
+ // A short read at a box boundary is the end of the walk, which is
+ // what the in-memory form does with a trailing partial header.
+ if _, err := io.ReadFull(r, hdr[:8]); err != nil {
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ return nil
+ }
+
+ return ErrInvalid
+ }
+
+ size := uint64(hdr[0])<<24 | uint64(hdr[1])<<16 | uint64(hdr[2])<<8 | uint64(hdr[3])
+ typ := string(hdr[4:8])
+ head := uint64(8)
+
+ if size == 1 {
+ if _, err := io.ReadFull(r, hdr[8:16]); err != nil {
+ return ErrInvalid
+ }
+
+ size = 0
+ for _, b := range hdr[8:16] {
+ size = size<<8 | uint64(b)
+ }
+
+ head = 16
+ }
+
+ n := int64(-1)
+ if size != 0 {
+ if size < head {
+ return ErrInvalid
+ }
+
+ n = int64(size - head)
+ }
+
+ body := &io.LimitedReader{R: r, N: maxHeaderBox}
+ if n >= 0 {
+ body.N = n
+ }
+
+ err := fn(typ, n, body)
+
+ if _, derr := io.Copy(io.Discard, body); derr != nil {
+ return ErrInvalid
+ }
+
+ if err != nil {
+ return err
+ }
+
+ if n < 0 {
+ return nil
+ }
+ }
+}
+
+// boxBytes reads a whole box payload, refusing one too large to be a header.
+func boxBytes(body io.Reader, n int64) ([]byte, error) {
+ if n < 0 {
+ return io.ReadAll(body)
+ }
+
+ if n > maxHeaderBox {
+ return nil, ErrInvalid
+ }
+
+ b := make([]byte, n)
+ if _, err := io.ReadFull(body, b); err != nil {
+ return nil, ErrInvalid
+ }
+
+ return b, nil
+}
+
+func parseMeta(payload []byte) (*metaBox, error) {
+ r := &reader{b: payload}
+ r.fullBox()
+ if r.err {
+ return nil, ErrInvalid
+ }
+
+ m := &metaBox{items: map[uint32]*item{}}
+
+ err := eachBox(payload[r.i:], func(typ string, b []byte) error {
+ switch typ {
+ case "pitm":
+ rr := &reader{b: b}
+ v, _ := rr.fullBox()
+ if v == 0 {
+ m.primary = uint32(rr.u16())
+ } else {
+ m.primary = rr.u32()
+ }
+ if rr.err {
+ return ErrInvalid
+ }
+
+ case "iloc":
+ return m.parseIloc(b)
+
+ case "iinf":
+ return m.parseIinf(b)
+
+ case "iref":
+ return m.parseIref(b)
+
+ case "idat":
+ m.idat = b
+
+ case "iprp":
+ return eachBox(b, func(typ string, b []byte) error {
+ switch typ {
+ case "ipco":
+ return m.parseIpco(b)
+ case "ipma":
+ return m.parseIpma(b)
+ }
+
+ return nil
+ })
+ }
+
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ m.markUnsupported()
+
+ return m, nil
+}
+
+// knownProps are the property types this reader implements. An item with an
+// essential association to anything else must not be processed.
+var knownProps = map[string]bool{
+ "ispe": true, "hvcC": true, "pixi": true, "auxC": true,
+ "irot": true, "imir": true, "clap": true, "colr": true,
+}
+
+func (m *metaBox) markUnsupported() {
+ for _, it := range m.items {
+ for _, ip := range it.props {
+ if !ip.essential {
+ continue
+ }
+ if ip.idx >= len(m.props) || !knownProps[m.props[ip.idx].typ] {
+ it.unsupported = true
+
+ break
+ }
+ }
+ }
+}
+
+func (m *metaBox) item(id uint32) (*item, error) {
+ it := m.items[id]
+ if it == nil {
+ if len(m.items) >= maxItems {
+ return nil, ErrUnsupported
+ }
+ it = &item{id: id}
+ m.items[id] = it
+ m.order = append(m.order, id)
+ }
+
+ return it, nil
+}
+
+func (m *metaBox) parseIloc(b []byte) error {
+ r := &reader{b: b}
+ v, _ := r.fullBox()
+
+ sizes := r.u8()
+ offSize, lenSize := int(sizes>>4), int(sizes&0xf)
+ sizes = r.u8()
+ baseSize, idxSize := int(sizes>>4), int(sizes&0xf)
+ if v < 1 {
+ idxSize = 0
+ }
+ for _, n := range []int{offSize, lenSize, baseSize, idxSize} {
+ if n != 0 && n != 4 && n != 8 {
+ return ErrInvalid
+ }
+ }
+
+ count := int(r.u16())
+ if v == 2 {
+ r.i -= 2
+ count = int(r.u32())
+ }
+ if r.err || count > maxItems {
+ return ErrUnsupported
+ }
+
+ for range count {
+ var id uint32
+ if v < 2 {
+ id = uint32(r.u16())
+ } else {
+ id = r.u32()
+ }
+ it, err := m.item(id)
+ if err != nil {
+ return err
+ }
+ if v >= 1 {
+ it.method = uint8(r.u16() & 0xf)
+ }
+ r.skip(2)
+ it.baseOffset = r.uint(baseSize)
+
+ n := int(r.u16())
+ if n > maxItemExtents-m.extentCount {
+ return ErrUnsupported
+ }
+ m.extentCount += n
+ for range n {
+ r.skip(idxSize)
+ off := r.uint(offSize)
+ l := r.uint(lenSize)
+ if r.err {
+ return ErrInvalid
+ }
+ it.extents = append(it.extents, extent{off: off, len: l})
+ }
+ if r.err {
+ return ErrInvalid
+ }
+ }
+
+ return nil
+}
+
+func (m *metaBox) parseIinf(b []byte) error {
+ r := &reader{b: b}
+ v, _ := r.fullBox()
+ if v == 0 {
+ r.u16()
+ } else {
+ r.u32()
+ }
+ if r.err {
+ return ErrInvalid
+ }
+
+ return eachBox(b[r.i:], func(typ string, b []byte) error {
+ if typ != "infe" {
+ return nil
+ }
+ rr := &reader{b: b}
+ v, _ := rr.fullBox()
+ if v < 2 {
+ return nil
+ }
+
+ var id uint32
+ if v == 2 {
+ id = uint32(rr.u16())
+ } else {
+ id = rr.u32()
+ }
+ rr.skip(2)
+ itemType := rr.str4()
+ if rr.err {
+ return ErrInvalid
+ }
+
+ it, err := m.item(id)
+ if err != nil {
+ return err
+ }
+ it.typ = itemType
+
+ if itemType == "mime" {
+ rr.cstr()
+ if ct := rr.cstr(); !rr.err {
+ it.contentType = ct
+ }
+ }
+
+ return nil
+ })
+}
+
+func (m *metaBox) parseIref(b []byte) error {
+ r := &reader{b: b}
+ v, _ := r.fullBox()
+ if r.err {
+ return ErrInvalid
+ }
+
+ return eachBox(b[r.i:], func(typ string, b []byte) error {
+ rr := &reader{b: b}
+ ref := itemRef{typ: typ}
+ if v == 0 {
+ ref.from = uint32(rr.u16())
+ } else {
+ ref.from = rr.u32()
+ }
+ n := int(rr.u16())
+ if n > maxItemReferences-m.referenceCount {
+ return ErrUnsupported
+ }
+ m.referenceCount += n
+ for range n {
+ var to uint32
+ if v == 0 {
+ to = uint32(rr.u16())
+ } else {
+ to = rr.u32()
+ }
+ ref.to = append(ref.to, to)
+ }
+ if rr.err {
+ return ErrInvalid
+ }
+ if len(m.refs) >= maxItemReferences {
+ return ErrUnsupported
+ }
+ m.refs = append(m.refs, ref)
+
+ return nil
+ })
+}
+
+func (m *metaBox) parseIpco(b []byte) error {
+ return eachBox(b, func(typ string, b []byte) error {
+ if len(m.props) >= maxProperties {
+ return ErrUnsupported
+ }
+ p := property{typ: typ}
+ r := &reader{b: b}
+
+ switch typ {
+ case "ispe":
+ r.fullBox()
+ p.w = r.u32()
+ p.h = r.u32()
+
+ case "hvcC":
+ c, err := parseHvcC(r)
+ if err != nil {
+ return err
+ }
+ p.hvcC = c
+
+ case "pixi":
+ r.fullBox()
+ n := int(r.u8())
+ for range n {
+ p.pixi = append(p.pixi, r.u8())
+ }
+
+ case "auxC":
+ r.fullBox()
+ p.auxC = r.cstr()
+
+ case "irot":
+ p.angle = r.u8() & 3
+
+ case "imir":
+ p.axis = r.u8() & 1
+
+ case "clap":
+ for i := range 8 {
+ p.clap[i] = r.u32()
+ }
+
+ case "colr":
+ switch r.str4() {
+ case "nclx":
+ p.colr = &colorInfo{hasNCLX: true}
+ p.colr.primaries = r.u16()
+ p.colr.transfer = r.u16()
+ p.colr.matrix = r.u16()
+ p.colr.fullRange = r.u8()>>7 != 0
+ case "rICC", "prof":
+ p.colr = &colorInfo{icc: b[4:]}
+ }
+ }
+
+ if r.err {
+ return ErrInvalid
+ }
+ m.props = append(m.props, p)
+
+ return nil
+ })
+}
+
+func (m *metaBox) parseIpma(b []byte) error {
+ r := &reader{b: b}
+ v, flags := r.fullBox()
+ count := int(r.u32())
+ if r.err || count > maxItems {
+ return ErrInvalid
+ }
+
+ for range count {
+ var id uint32
+ if v < 1 {
+ id = uint32(r.u16())
+ } else {
+ id = r.u32()
+ }
+ it, err := m.item(id)
+ if err != nil {
+ return err
+ }
+
+ n := int(r.u8())
+ if n > maxItemProperties-m.propertyCount {
+ return ErrUnsupported
+ }
+ m.propertyCount += n
+ it.props = slices.Grow(it.props, n)
+
+ for range n {
+ var idx int
+ var essential bool
+ if flags&1 != 0 {
+ v := r.u16()
+ idx, essential = int(v&0x7fff), v&0x8000 != 0
+ } else {
+ v := r.u8()
+ idx, essential = int(v&0x7f), v&0x80 != 0
+ }
+ if r.err {
+ return ErrInvalid
+ }
+ if idx == 0 {
+ continue
+ }
+ it.props = append(it.props, itemProp{idx: idx - 1, essential: essential})
+ }
+ if r.err {
+ return ErrInvalid
+ }
+ }
+
+ return nil
+}
+
+func (m *metaBox) dataSource(it *item, src *source) (*source, error) {
+ if it.method == 1 {
+ return memSource(m.idat), nil
+ } else if it.method != 0 {
+ return nil, ErrInvalid
+ }
+ return src, nil
+}
+
+func dataSpan(it *item, src *source, e extent) (uint64, uint64, error) {
+ if e.off > ^uint64(0)-it.baseOffset {
+ return 0, 0, ErrInvalid
+ }
+ off, n := it.baseOffset+e.off, e.len
+ if n == 0 {
+ if off > src.size {
+ return 0, 0, ErrInvalid
+ }
+
+ n = src.size - off
+ }
+
+ if off > src.size || n > src.size-off {
+ return 0, 0, ErrInvalid
+ }
+
+ return off, n, nil
+}
+
+func (m *metaBox) dataSize(it *item, src *source) (uint64, error) {
+ src, err := m.dataSource(it, src)
+ if err != nil {
+ return 0, err
+ }
+ total := uint64(0)
+ for _, e := range it.extents {
+ _, n, err := dataSpan(it, src, e)
+ if err != nil {
+ return 0, err
+ }
+ if n > maxItemDataBytes-total {
+ return 0, ErrUnsupported
+ }
+ total += n
+ }
+ if total == 0 {
+ return 0, ErrInvalid
+ }
+ return total, nil
+}
+
+// data gathers an item's extents out of the file or, for construction method 1, out of idat.
+func (m *metaBox) data(it *item, src *source) ([]byte, error) {
+ src, err := m.dataSource(it, src)
+ if err != nil {
+ return nil, err
+ }
+ total, err := m.dataSize(it, src)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(it.extents) == 1 {
+ off, n, err := dataSpan(it, src, it.extents[0])
+ if err != nil {
+ return nil, err
+ }
+
+ return src.at(off, n)
+ }
+
+ out := make([]byte, 0, int(total))
+ for _, e := range it.extents {
+ off, n, err := dataSpan(it, src, e)
+ if err != nil {
+ return nil, err
+ }
+ b, err := src.at(off, n)
+ if err != nil {
+ return nil, err
+ }
+
+ out = append(out, b...)
+ }
+
+ return out, nil
+}
+
+func (m *metaBox) prop(it *item, typ string) *property {
+ if it == nil {
+ return nil
+ }
+ for _, ip := range it.props {
+ if ip.idx < len(m.props) && m.props[ip.idx].typ == typ {
+ return &m.props[ip.idx]
+ }
+ }
+
+ return nil
+}
+
+func (m *metaBox) refsTo(typ string, from uint32) []uint32 {
+ for _, r := range m.refs {
+ if r.typ == typ && r.from == from {
+ return r.to
+ }
+ }
+
+ return nil
+}
+
+// parseHvcC reads the HEVCDecoderConfigurationRecord. Everything before the
+// arrays is fixed width, and the profile and level fields are not needed once
+// the parameter sets themselves are in hand.
+func parseHvcC(r *reader) (*hevcConfig, error) {
+ if r.u8() != 1 {
+ return nil, ErrInvalid
+ }
+
+ r.skip(12)
+
+ c := &hevcConfig{}
+
+ r.skip(2)
+ r.skip(1)
+ c.chromaFormat = r.u8() & 3
+ c.bitDepthLuma = r.u8()&7 + 8
+ c.bitDepthChroma = r.u8()&7 + 8
+
+ r.skip(2)
+ c.lengthSize = int(r.u8()&3) + 1
+
+ arrays := int(r.u8())
+ if r.err {
+ return nil, ErrInvalid
+ }
+
+ totalSets, totalBytes := 0, 0
+ for range arrays {
+ r.skip(1)
+
+ n := int(r.u16())
+ if n > maxParameterSets-totalSets {
+ return nil, ErrUnsupported
+ }
+ totalSets += n
+ c.paramSets = slices.Grow(c.paramSets, n)
+
+ for range n {
+ nalBytes := int(r.u16())
+ if nalBytes > maxParameterBytes-totalBytes {
+ return nil, ErrUnsupported
+ }
+ totalBytes += nalBytes
+ nal := r.bytes(nalBytes)
+ if r.err {
+ return nil, ErrInvalid
+ }
+
+ c.paramSets = append(c.paramSets, nal)
+ }
+ }
+
+ if r.err {
+ return nil, ErrInvalid
+ }
+
+ return c, nil
+}
diff --git a/kernel/heif/internal/h265heic/limits.go b/kernel/heif/internal/h265heic/limits.go
new file mode 100644
index 0000000000..67e12f8c94
--- /dev/null
+++ b/kernel/heif/internal/h265heic/limits.go
@@ -0,0 +1,169 @@
+package heic
+
+import "github.com/gen2brain/h265/hevc"
+
+const codedPixelSlack = 64 * 64
+
+type limitBits struct {
+ data []byte
+ pos int
+ err bool
+}
+
+func (r *limitBits) bit() uint32 {
+ if r.pos >= len(r.data)*8 {
+ r.err = true
+ return 0
+ }
+ value := uint32(r.data[r.pos/8] >> (7 - r.pos%8) & 1)
+ r.pos++
+ return value
+}
+
+func (r *limitBits) bits(count int) uint32 {
+ if count < 0 || count > 32 || count > len(r.data)*8-r.pos {
+ r.err = true
+ return 0
+ }
+ var value uint32
+ for range count {
+ value = value<<1 | r.bit()
+ }
+ return value
+}
+
+func (r *limitBits) skip(count int) {
+ if count < 0 || count > len(r.data)*8-r.pos {
+ r.err = true
+ return
+ }
+ r.pos += count
+}
+
+func (r *limitBits) ue() uint32 {
+ zeros := 0
+ for r.bit() == 0 {
+ zeros++
+ if r.err || zeros > 31 {
+ r.err = true
+ return 0
+ }
+ }
+ if zeros == 0 {
+ return 0
+ }
+ return 1<<zeros - 1 + r.bits(zeros)
+}
+
+type spsLimits struct {
+ width uint32
+ height uint32
+ chromaFormat uint32
+ bitDepthLuma uint32
+ bitDepthChroma uint32
+ confWinLeft uint32
+ confWinRight uint32
+ confWinTop uint32
+ confWinBottom uint32
+ separateColours bool
+}
+
+// inspectSPSLimits 只解析分配图像内存前所需的 SPS 字段。
+func inspectSPSLimits(rbsp []byte) (spsLimits, error) {
+ r := &limitBits{data: rbsp}
+ r.skip(4)
+ maxSubLayersMinus1 := int(r.bits(3))
+ if maxSubLayersMinus1 > 6 {
+ return spsLimits{}, ErrInvalid
+ }
+ r.skip(1)
+
+ // general_profile_tier_level 和各子层声明均为定长字段。
+ r.skip(2 + 1 + 5 + 32 + 48 + 8)
+ profilePresent := make([]bool, maxSubLayersMinus1)
+ levelPresent := make([]bool, maxSubLayersMinus1)
+ for i := range maxSubLayersMinus1 {
+ profilePresent[i] = r.bit() != 0
+ levelPresent[i] = r.bit() != 0
+ }
+ if maxSubLayersMinus1 > 0 {
+ r.skip(2 * (8 - maxSubLayersMinus1))
+ }
+ for i := range maxSubLayersMinus1 {
+ if profilePresent[i] {
+ r.skip(88)
+ }
+ if levelPresent[i] {
+ r.skip(8)
+ }
+ }
+
+ r.ue() // sps_seq_parameter_set_id
+ limits := spsLimits{chromaFormat: r.ue()}
+ if limits.chromaFormat > 3 {
+ return spsLimits{}, ErrInvalid
+ }
+ if limits.chromaFormat == 3 {
+ limits.separateColours = r.bit() != 0
+ }
+ limits.width = r.ue()
+ limits.height = r.ue()
+ if r.bit() != 0 {
+ limits.confWinLeft = r.ue()
+ limits.confWinRight = r.ue()
+ limits.confWinTop = r.ue()
+ limits.confWinBottom = r.ue()
+ }
+ limits.bitDepthLuma = r.ue() + 8
+ limits.bitDepthChroma = r.ue() + 8
+ if r.err || limits.width == 0 || limits.height == 0 {
+ return spsLimits{}, ErrInvalid
+ }
+ return limits, nil
+}
+
+func validateSPSLimits(nal hevc.NALUnit, frameSizeLimit int) error {
+ limits, err := inspectSPSLimits(nal.RBSP)
+ if err != nil {
+ return err
+ }
+ return validateParsedSPSLimits(limits, frameSizeLimit)
+}
+
+func validateParsedSPSLimits(limits spsLimits, frameSizeLimit int) error {
+ if limits.separateColours || limits.chromaFormat > 1 ||
+ limits.bitDepthLuma > 10 || limits.bitDepthChroma > 10 ||
+ limits.bitDepthLuma != limits.bitDepthChroma {
+ return ErrUnsupported
+ }
+ if frameSizeLimit <= 0 || uint64(limits.width)*uint64(limits.height) > uint64(frameSizeLimit) {
+ return ErrUnsupported
+ }
+ subWidth, subHeight := uint64(1), uint64(1)
+ if limits.chromaFormat == 1 {
+ subWidth, subHeight = 2, 2
+ }
+ croppedWidth := subWidth * (uint64(limits.confWinLeft) + uint64(limits.confWinRight))
+ croppedHeight := subHeight * (uint64(limits.confWinTop) + uint64(limits.confWinBottom))
+ if croppedWidth >= uint64(limits.width) || croppedHeight >= uint64(limits.height) {
+ return ErrUnsupported
+ }
+ return nil
+}
+
+func codedFrameLimit(displayPixels uint64, globalLimit int) int {
+ if globalLimit <= 0 || displayPixels == 0 {
+ return 0
+ }
+ if displayPixels >= uint64(globalLimit) {
+ return globalLimit
+ }
+ limit := displayPixels + codedPixelSlack
+ if doubled := displayPixels * 2; doubled > limit {
+ limit = doubled
+ }
+ if limit > uint64(globalLimit) {
+ limit = uint64(globalLimit)
+ }
+ return int(limit)
+}
diff --git a/kernel/heif/internal/h265heic/security_test.go b/kernel/heif/internal/h265heic/security_test.go
new file mode 100644
index 0000000000..1b9f414860
--- /dev/null
+++ b/kernel/heif/internal/h265heic/security_test.go
@@ -0,0 +1,164 @@
+package heic
+
+import (
+ "bytes"
+ "errors"
+ "image"
+ "testing"
+
+ "github.com/gen2brain/h265/hevc"
+)
+
+func TestDecodeConfigRejectsSequenceContainer(t *testing.T) {
+ data := append(testBox("ftyp"), testBox("moov")...)
+ if _, err := DecodeConfig(bytes.NewReader(data)); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected sequence error: %v", err)
+ }
+}
+
+func TestOptionsClampResourceLimits(t *testing.T) {
+ got := options([]Options{{FrameSizeLimit: DefaultFrameSizeLimit + 1, Threads: 8}})
+ if got.FrameSizeLimit != DefaultFrameSizeLimit || got.Threads != 1 {
+ t.Fatalf("unexpected options: %+v", got)
+ }
+ got = options([]Options{{FrameSizeLimit: -1}})
+ if got.FrameSizeLimit != DefaultFrameSizeLimit || got.Threads != 1 {
+ t.Fatalf("unexpected negative-limit options: %+v", got)
+ }
+}
+
+func TestSPSLimitsRejectUnsafeCropAndMixedBitDepth(t *testing.T) {
+ valid := spsLimits{
+ width: 16,
+ height: 16,
+ chromaFormat: 1,
+ bitDepthLuma: 8,
+ bitDepthChroma: 8,
+ }
+ if err := validateParsedSPSLimits(valid, 256); err != nil {
+ t.Fatalf("valid SPS limits were rejected: %v", err)
+ }
+
+ mixedDepth := valid
+ mixedDepth.bitDepthChroma = 10
+ if err := validateParsedSPSLimits(mixedDepth, 256); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected mixed bit-depth error: %v", err)
+ }
+
+ invalidCrop := valid
+ invalidCrop.confWinLeft = 8
+ if err := validateParsedSPSLimits(invalidCrop, 256); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected conformance-window error: %v", err)
+ }
+}
+
+func TestParseRejectsOversizedContainerBeforeReading(t *testing.T) {
+ src := &source{size: maxContainerBytes + 1}
+ if _, err := parse(src); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected oversized-container error: %v", err)
+ }
+}
+
+func TestEachHVCCStreamsOneNAL(t *testing.T) {
+ data := []byte{0, 0, 0, 3, byte(hevc.NALIdrWRadl << 1), 1, 0x80}
+ count := 0
+ err := eachHVCC(data, 4, func(_ hevc.NALUnit) error {
+ count++
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if count != 1 {
+ t.Fatalf("decoded %d NAL units", count)
+ }
+}
+
+func TestItemDataLimitPrecedesRead(t *testing.T) {
+ source := &source{size: maxItemDataBytes + 1}
+ item := &item{extents: []extent{{len: maxItemDataBytes + 1}}}
+ if _, err := (&metaBox{}).data(item, source); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected item data error: %v", err)
+ }
+}
+
+func TestDecodedItemDataUsesSharedBudget(t *testing.T) {
+ f := &file{}
+ f.decodedBytes = maxItemDataBytes
+ if err := f.consumeDecodedBytes(1); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected shared data-budget error: %v", err)
+ }
+}
+
+func TestGridTileLimit(t *testing.T) {
+ data := []byte{0, 0, 16, 16, 0, 1, 0, 1}
+ if _, err := parseGrid(data); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected grid error: %v", err)
+ }
+}
+
+func TestGridRejectsDuplicateTiles(t *testing.T) {
+ if _, err := (&file{}).decodeTiles(gridInfo{}, []uint32{1, 1}); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected duplicate tile error: %v", err)
+ }
+}
+
+func TestTopLevelBoxLimit(t *testing.T) {
+ data := make([]byte, 0, (maxTopLevelBoxes+1)*8)
+ for range maxTopLevelBoxes + 1 {
+ data = append(data, testBox("free")...)
+ }
+ if err := memSource(data).eachBox(func(string, uint64, uint64) error { return nil }); !errors.Is(err, ErrUnsupported) {
+ t.Fatalf("unexpected top-level box error: %v", err)
+ }
+}
+
+func TestTenBitPictureUsesEightBitOutput(t *testing.T) {
+ picture := &hevc.Picture{
+ Width: 2,
+ Height: 2,
+ CropW: 2,
+ CropH: 2,
+ ChromaFormat: 0,
+ BitDepth: 10,
+ BitDepthC: 10,
+ Y16: []uint16{0, 256, 512, 1023},
+ StrideY: 2,
+ }
+ decoded, err := toImage(picture, nil, ColorInfo{}, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := decoded.(*image.NRGBA); !ok {
+ t.Fatalf("unexpected decoded image type: %T", decoded)
+ }
+}
+
+func TestCombinedCropRotateAndMirror(t *testing.T) {
+ source := image.NewNRGBA(image.Rect(0, 0, 3, 2))
+ for i := range 6 {
+ source.Pix[i*4] = uint8(i + 1)
+ source.Pix[i*4+3] = 0xff
+ }
+ f := &file{meta: &metaBox{props: []property{
+ {typ: "clap", clap: [8]uint32{1, 1, 2, 1, 0, 1, 0, 1}},
+ {typ: "irot", angle: 1},
+ {typ: "imir", axis: 1},
+ }}}
+ it := &item{props: []itemProp{{idx: 0}, {idx: 1}, {idx: 2}}}
+ transformed, err := f.applyTransforms(source, it)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, ok := transformed.(*image.NRGBA)
+ if !ok {
+ t.Fatalf("unexpected transformed image type: %T", transformed)
+ }
+ if got.Bounds().Dx() != 2 || got.Bounds().Dy() != 1 || got.Pix[0] != 5 || got.Pix[4] != 2 {
+ t.Fatalf("unexpected transformed pixels: bounds=%v pix=%v", got.Bounds(), got.Pix)
+ }
+}
+
+func testBox(name string) []byte {
+ return []byte{0, 0, 0, 8, name[0], name[1], name[2], name[3]}
+}
diff --git a/kernel/heif/internal/h265heic/transform.go b/kernel/heif/internal/h265heic/transform.go
new file mode 100644
index 0000000000..8ced951d1d
--- /dev/null
+++ b/kernel/heif/internal/h265heic/transform.go
@@ -0,0 +1,218 @@
+package heic
+
+import "image"
+
+type raw struct {
+ pix []byte
+ stride int
+ w, h int
+ psize int
+}
+
+func toRaw(img image.Image) (*raw, bool) {
+ switch m := img.(type) {
+ case *image.NRGBA:
+ return &raw{m.Pix, m.Stride, m.Rect.Dx(), m.Rect.Dy(), 4}, true
+ case *image.NRGBA64:
+ return &raw{m.Pix, m.Stride, m.Rect.Dx(), m.Rect.Dy(), 8}, true
+ }
+
+ return nil, false
+}
+
+func (r *raw) toImage() image.Image {
+ rect := image.Rect(0, 0, r.w, r.h)
+ if r.psize == 4 {
+ return &image.NRGBA{Pix: r.pix, Stride: r.stride, Rect: rect}
+ }
+
+ return &image.NRGBA64{Pix: r.pix, Stride: r.stride, Rect: rect}
+}
+
+func (r *raw) alloc(w, h int) *raw {
+ return &raw{pix: make([]byte, w*h*r.psize), stride: w * r.psize, w: w, h: h, psize: r.psize}
+}
+
+func (r *raw) at(x, y int) []byte {
+ o := y*r.stride + x*r.psize
+
+ return r.pix[o : o+r.psize]
+}
+
+func (r *raw) crop(x, y, w, h int) *raw {
+ out := r.alloc(w, h)
+ for j := range h {
+ copy(out.pix[j*out.stride:][:w*r.psize], r.at(x, y+j)[:w*r.psize])
+ }
+
+ return out
+}
+
+// rotate turns the image anti-clockwise by angle quarter turns.
+func (r *raw) rotate(angle int) *raw {
+ if angle == 0 {
+ return r
+ }
+ w, h := r.w, r.h
+ if angle&1 != 0 {
+ w, h = h, w
+ }
+ out := r.alloc(w, h)
+
+ for j := range r.h {
+ for i := range r.w {
+ var dx, dy int
+ switch angle {
+ case 1:
+ dx, dy = j, r.w-1-i
+ case 2:
+ dx, dy = r.w-1-i, r.h-1-j
+ default:
+ dx, dy = r.h-1-j, i
+ }
+ copy(out.at(dx, dy), r.at(i, j))
+ }
+ }
+
+ return out
+}
+
+func (r *raw) mirror(axis int) *raw {
+ if axis == 0 {
+ for y := range r.h / 2 {
+ a := r.pix[y*r.stride:][:r.w*r.psize]
+ b := r.pix[(r.h-1-y)*r.stride:][:r.w*r.psize]
+ for i := range a {
+ a[i], b[i] = b[i], a[i]
+ }
+ }
+
+ return r
+ }
+
+ for y := range r.h {
+ for x := range r.w / 2 {
+ a, b := r.at(x, y), r.at(r.w-1-x, y)
+ for i := range a {
+ a[i], b[i] = b[i], a[i]
+ }
+ }
+ }
+
+ return r
+}
+
+// cropRect derives the clean aperture rectangle, in fractions throughout.
+func cropRect(clap *[8]uint32, w, h int) (int, int, int, int, bool) {
+ widthN, widthD := int64(int32(clap[0])), int64(int32(clap[1]))
+ heightN, heightD := int64(int32(clap[2])), int64(int32(clap[3]))
+ horizN, horizD := int64(int32(clap[4])), int64(int32(clap[5]))
+ vertN, vertD := int64(int32(clap[6])), int64(int32(clap[7]))
+
+ if widthD <= 0 || heightD <= 0 || horizD <= 0 || vertD <= 0 ||
+ widthN < 0 || heightN < 0 {
+ return 0, 0, 0, 0, false
+ }
+ if widthN%widthD != 0 || heightN%heightD != 0 {
+ return 0, 0, 0, 0, false
+ }
+ clapW, clapH := widthN/widthD, heightN/heightD
+
+ numX := int64(w)*horizD + 2*horizN - clapW*horizD
+ denX := 2 * horizD
+ numY := int64(h)*vertD + 2*vertN - clapH*vertD
+ denY := 2 * vertD
+ if numX%denX != 0 || numY%denY != 0 {
+ return 0, 0, 0, 0, false
+ }
+ x, y := numX/denX, numY/denY
+
+ if x < 0 || y < 0 || clapW <= 0 || clapH <= 0 ||
+ x+clapW > int64(w) || y+clapH > int64(h) {
+ return 0, 0, 0, 0, false
+ }
+
+ return int(x), int(y), int(clapW), int(clapH), true
+}
+
+// applyTransforms runs clean aperture, then rotation, then mirroring, per MIAF 7.3.6.7.
+// hasTransform reports whether AutoRotate would have to touch the pixels.
+func (f *file) hasTransform(it *item) bool {
+ return f.meta.prop(it, "clap") != nil || f.meta.prop(it, "irot") != nil ||
+ f.meta.prop(it, "imir") != nil
+}
+
+func (f *file) applyTransforms(img image.Image, it *item) (image.Image, error) {
+ clap := f.meta.prop(it, "clap")
+ irot := f.meta.prop(it, "irot")
+ imir := f.meta.prop(it, "imir")
+ if clap == nil && irot == nil && imir == nil {
+ return img, nil
+ }
+
+ r, ok := toRaw(img)
+ if !ok {
+ return nil, ErrUnsupported
+ }
+
+ x, y, w, h := 0, 0, r.w, r.h
+ if clap != nil {
+ x, y, w, h, ok = cropRect(&clap.clap, r.w, r.h)
+ if !ok {
+ return nil, ErrInvalid
+ }
+ }
+ angle := 0
+ if irot != nil {
+ angle = int(irot.angle)
+ }
+ if x == 0 && y == 0 && w == r.w && h == r.h && angle == 0 {
+ if imir != nil {
+ r = r.mirror(int(imir.axis))
+ }
+ return r.toImage(), nil
+ }
+
+ outW, outH := w, h
+ if angle&1 != 0 {
+ outW, outH = h, w
+ }
+ out := r.alloc(outW, outH)
+ for sourceY := range h {
+ for sourceX := range w {
+ destX, destY := sourceX, sourceY
+ switch angle {
+ case 1:
+ destX, destY = sourceY, w-1-sourceX
+ case 2:
+ destX, destY = w-1-sourceX, h-1-sourceY
+ case 3:
+ destX, destY = h-1-sourceY, sourceX
+ }
+ if imir != nil {
+ if imir.axis == 0 {
+ destY = outH - 1 - destY
+ } else {
+ destX = outW - 1 - destX
+ }
+ }
+ copy(out.at(destX, destY), r.at(x+sourceX, y+sourceY))
+ }
+ }
+
+ return out.toImage(), nil
+}
+
+// transform applies the clap, irot and imir properties. The planar images the
+// ToYCbCr path returns alias the decoded planes, so they are converted first.
+func (f *file) transform(it *item, img image.Image) (image.Image, error) {
+ if !f.hasTransform(it) {
+ return img, nil
+ }
+
+ if aliasesPicture(img) {
+ return nil, ErrUnsupported
+ }
+
+ return f.applyTransforms(img, it)
+}
diff --git a/kernel/heif/testdata/basic.heic b/kernel/heif/testdata/basic.heic
new file mode 100644
index 0000000000..8c192524a6
Binary files /dev/null and b/kernel/heif/testdata/basic.heic differ
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index fc268f7787..81b96baecc 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -47,6 +47,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/search"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -63,6 +64,14 @@ func GetAssetImgSizeInBox(assetPath, boxID string) (width, height int) {
logging.LogErrorf("get asset [%s] abs path failed: %s", assetPath, err)
return
}
+ defer clear(data)
+ if heif.IsPath(assetPath) {
+ width, height, err = heif.ImageSize(data)
+ if err != nil {
+ logging.LogErrorf("open asset image [%s] failed: %s", assetPath, err)
+ }
+ return
+ }
img, err := imaging.Decode(bytes.NewReader(data))
if err != nil {
@@ -82,7 +91,17 @@ func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error) {
if err != nil {
return nil, err
}
- data, readErr := os.ReadFile(absPath)
+ var data []byte
+ var readErr error
+ if heif.IsPath(relativePath) {
+ limit := int64(heif.MaxInputBytes)
+ if effectiveBoxID := ExtractBoxIDFromAssetsPath(absPath); effectiveBoxID != "" && IsEncryptedBox(effectiveBoxID) {
+ limit += 2 * 1024 * 1024
+ }
+ data, readErr = heif.ReadFileLimited(absPath, limit)
+ } else {
+ data, readErr = os.ReadFile(absPath)
+ }
if readErr != nil {
return nil, readErr
}
@@ -95,12 +114,17 @@ func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error) {
ReleaseBoxReadLock(effectiveBoxID)
return nil, dekErr
}
+ defer clear(dek)
defer ReleaseBoxReadLock(effectiveBoxID)
diskName := filepath.Base(AssetPathWithoutQuery(relativePath))
plain, decErr := DecryptAsset(effectiveBoxID, diskName, dek, data)
if decErr != nil {
return nil, decErr
}
+ if heif.IsPath(relativePath) && len(plain) > heif.MaxInputBytes {
+ clear(plain)
+ return nil, heif.ErrInputTooLarge
+ }
return plain, nil
}
return data, nil
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 488d0c3740..4cbb06bb76 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -40,6 +40,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -809,8 +810,9 @@ func ClearTempFiles() {
}
func clearTempFiles(count *int, size *int64) {
+ heif.ClearMemoryCache("")
for _, name := range []string{
- "bazaar", "export", "import", "convert", "pandoc", "os", "base64", "install", "thumbnails", "repo", "clipboard",
+ "assets-cache", "bazaar", "export", "import", "convert", "pandoc", "os", "base64", "install", "thumbnails", "repo", "clipboard",
} {
clearTempDir(filepath.Join(util.TempDir, name), count, size)
}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index b663887e8d..d5fcbf737b 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -38,6 +38,7 @@ import (
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -1467,6 +1468,8 @@ func clearCorruptedNotebooks() {
}
func clearWorkspaceTemp(preserveInstallPkgs bool) {
+ heif.ClearMemoryCache("")
+ os.RemoveAll(filepath.Join(util.TempDir, "assets-cache"))
os.RemoveAll(filepath.Join(util.TempDir, "bazaar"))
os.RemoveAll(filepath.Join(util.TempDir, "export"))
os.RemoveAll(filepath.Join(util.TempDir, "import"))
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index fc38ab6e2f..956b5dd8b1 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -43,6 +43,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -1521,6 +1522,8 @@ func lockBoxWithPreparationHeld(boxID string, prepare func()) {
// lockBoxHeld 在已持有 box 写锁的前提下执行该 box 的锁定清理(不含全局缓存刷新)。
func lockBoxHeld(boxID string) {
+ // 此时已排空在途操作并持有 box 写锁,可以安全清除该笔记本的明文 HEIF 预览缓存。
+ heif.ClearMemoryCache(boxID)
RevokeManagedEncryptedExportsForBox(boxID)
ClearRichClipboardBox(boxID)
@@ -2641,6 +2644,8 @@ func cleanupFailedEncryptedBox(boxID string) {
return
}
+ // 创建失败路径不经过常规锁定流程,防御性清理可能生成的明文 HEIF 预览缓存。
+ heif.ClearMemoryCache(boxID)
cachedDEKsLock.Lock()
if cachedDEK, ok := cachedDEKs[boxID]; ok {
zeroAndClear(cachedDEK)
diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.go
index c010496937..8d7fca0374 100644
--- a/kernel/model/crypto_lifecycle_test.go
+++ b/kernel/model/crypto_lifecycle_test.go
@@ -123,6 +123,71 @@ func TestEncryptedBoxLifecycleWaitsForActiveOperations(t *testing.T) {
}
}
+func TestActiveOperationAllowsNestedAssetReadWhileLockWaits(t *testing.T) {
+ boxID := "20260816193000-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+ originalWorkspaceDir := util.WorkspaceDir
+ util.WorkspaceDir = filepath.Dir(util.DataDir)
+ defer func() {
+ util.WorkspaceDir = originalWorkspaceDir
+ }()
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+
+ dek, err := GetDEKIfUnlocked(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ diskName := "asset-20260816193001-abcdefg.bin"
+ plaintext := []byte("nested encrypted asset")
+ ciphertext, err := EncryptAsset(boxID, diskName, diskName, dek, plaintext)
+ clear(dek)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assetDir := filepath.Join(util.DataDir, boxID, "assets")
+ if err = os.MkdirAll(assetDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(assetDir, diskName), ciphertext, 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {
+ t.Fatal(err)
+ }
+ HoldBoxReadLock(boxID)
+ lockDone := make(chan struct{})
+ go func() {
+ beginEncryptedBoxLock(boxID)
+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)
+ close(lockDone)
+ }()
+ deadline := time.Now().Add(time.Second)
+ for GetEncryptedBoxState(boxID) != EncryptedBoxStateLocking && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateLocking {
+ ReleaseBoxReadLock(boxID)
+ ReleaseEncryptedBoxOperation(boxID)
+ t.Fatalf("expected Locking state, got %s", state)
+ }
+
+ read, readErr := ReadAssetBytesInBox(boxID, "assets/"+diskName)
+ if readErr != nil || !bytes.Equal(read, plaintext) {
+ ReleaseBoxReadLock(boxID)
+ ReleaseEncryptedBoxOperation(boxID)
+ t.Fatalf("nested asset read failed: data=%q err=%v", read, readErr)
+ }
+ ReleaseBoxReadLock(boxID)
+ ReleaseEncryptedBoxOperation(boxID)
+ select {
+ case <-lockDone:
+ case <-time.After(time.Second):
+ t.Fatal("lock transition did not finish after the outer operation ended")
+ }
+}
+
func TestEncryptedBoxReadLockDoesNotWaitDuringLocking(t *testing.T) {
boxID := "20260731160008-abcdefg"
cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 3b9db163ec..edcd434512 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -573,7 +573,7 @@ func exportLockedByBlockID(id string) bool {
// withExportReadLockByBlockID 由 blockID 反查 boxID,若属于加密笔记本则全程持读锁执行 fn。
// 持锁期间 LockBox(自动锁定)会阻塞等待,避免操作中途清 DEK/删导出目录导致部分明文写出。
-// 普通笔记本或块树不存在时直接执行 fn。嵌套调用安全:sync.RWMutex.RLock 可重入。
+// 准入租约先于读锁取得,确保嵌套资源读取期间不会出现等待中的写锁。
func withExportReadLockByBlockID(id string, fn func() error) error {
bt := getExportBlockTree(id)
if nil == bt || !IsEncryptedBox(bt.BoxID) {
@@ -582,11 +582,17 @@ func withExportReadLockByBlockID(id string, fn func() error) error {
if !IsBoxUnlocked(bt.BoxID) {
return errors.New(Conf.Language(314))
}
+ if err := AcquireEncryptedBoxOperation(bt.BoxID); err != nil {
+ return errors.New(Conf.Language(314))
+ }
+ defer ReleaseEncryptedBoxOperation(bt.BoxID)
HoldBoxReadLock(bt.BoxID)
defer ReleaseBoxReadLock(bt.BoxID)
- if _, dekErr := GetDEKIfUnlocked(bt.BoxID); dekErr != nil {
+ dek, dekErr := GetDEKIfUnlocked(bt.BoxID)
+ if dekErr != nil {
return errors.New(Conf.Language(314))
}
+ clear(dek)
return fn()
}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index e271851d2e..5f21ef67ca 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -58,6 +58,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -519,12 +520,18 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
repoBoxID = parts[0]
}
if repoBoxID != "" && IsEncryptedBox(repoBoxID) {
+ // 加密仓库快照的 HEIF 预览不落盘,保持与旧版普通文件展示行为一致。
+ if heif.IsPath(file.Path) {
+ return
+ }
HoldBoxReadLock(repoBoxID)
defer ReleaseBoxReadLock(repoBoxID)
// 加密 asset:尝试解密后预览,无法解密则 fail-closed
if dek, dekErr := GetDEKIfUnlocked(repoBoxID); dekErr == nil && dek != nil {
diskName := filepath.Base(file.Path)
- if plainData, decErr := DecryptAsset(repoBoxID, diskName, dek, data); decErr == nil {
+ plainData, decErr := DecryptAsset(repoBoxID, diskName, dek, data)
+ clear(dek)
+ if decErr == nil {
data = plainData
} else {
logging.LogWarnf("decrypt repo snapshot asset [%s] failed: %s", file.Path, decErr)
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 257648fe67..a9f4f17b20 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -46,6 +46,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/api"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/cmd"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/mcp"
mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client"
"github.com/siyuan-note/siyuan/kernel/model"
@@ -978,8 +979,20 @@ func serveAssets(ginServer *gin.Engine) {
return
}
- if serveThumbnail(context, p, requestPath) || serveSVG(context, p) {
- return
+ if heif.IsPath(p) {
+ // 下载始终返回原文件;预览请求统一转成浏览器可显示的 JPEG。
+ if !strings.EqualFold(context.Query("download"), "true") {
+ if !acquireHEIFPreviewSlot(context) {
+ return
+ }
+ defer releaseHEIFPreviewSlot()
+ serveHEIFPreview(context, p)
+ return
+ }
+ } else {
+ if serveThumbnail(context, p, requestPath) || serveSVG(context, p) {
+ return
+ }
}
// 加密笔记本的 assets 是密文,需先解密再输出
@@ -993,13 +1006,12 @@ func serveAssets(ginServer *gin.Engine) {
})
ginServer.GET("/history/*path", model.CheckAuth, model.CheckAdminRole, func(context *gin.Context) {
- requestPath := context.Param("path")
- // 与 /repo/diff 一致,先拒绝路径穿越
- if strings.Contains(requestPath, "..") {
+ requestPath, valid := cleanHistoryRequestPath(context.Param("path"))
+ if !valid {
context.Status(http.StatusUnauthorized)
return
}
- p := filepath.Join(util.HistoryDir, requestPath)
+ p := filepath.Join(util.HistoryDir, filepath.FromSlash(strings.TrimPrefix(requestPath, "/")))
// 历史快照可能包含敏感文件副本(如 data/.siyuan/publishAccess.json、data/templates 下的文件),
// 去掉快照目录前缀后按数据相对路径拒绝访问(见 kernel/util/path_guard.go 的 IsForbiddenDataRelPath)
rel := strings.TrimPrefix(requestPath, "/")
@@ -1012,20 +1024,55 @@ func serveAssets(ginServer *gin.Engine) {
context.Status(http.StatusForbidden)
return
}
+ if heif.IsPath(p) && !strings.EqualFold(context.Query("download"), "true") {
+ if !acquireHEIFPreviewSlot(context) {
+ return
+ }
+ defer releaseHEIFPreviewSlot()
+ }
// 加密笔记本的历史是密文(.sy/assets/AV),需先解密再输出
if serveEncryptedHistory(context, p) {
return
}
+ if heif.IsPath(p) && !strings.EqualFold(context.Query("download"), "true") {
+ servePlainHEIFPreview(context, p, "", false)
+ return
+ }
secureAssetContentHeaders(context, p, p)
http.ServeFile(context.Writer, context.Request, p)
})
}
+var heifPreviewSlots = make(chan struct{}, 1)
+
+func acquireHEIFPreviewSlot(c *gin.Context) bool {
+ timer := time.NewTimer(30 * time.Second)
+ defer timer.Stop()
+ select {
+ case heifPreviewSlots <- struct{}{}:
+ return true
+ case <-c.Request.Context().Done():
+ return false
+ case <-timer.C:
+ c.Status(http.StatusServiceUnavailable)
+ return false
+ }
+}
+
+func releaseHEIFPreviewSlot() {
+ <-heifPreviewSlots
+}
+
+func setEncryptedAssetCacheHeaders(c *gin.Context) {
+ c.Header("Cache-Control", "private, no-store")
+}
+
func serveSVG(context *gin.Context, assetAbsPath string) bool {
if strings.HasSuffix(assetAbsPath, ".svg") {
boxID := model.ExtractBoxIDFromAssetsPath(assetAbsPath)
var dek []byte
if boxID != "" && model.IsEncryptedBox(boxID) {
+ setEncryptedAssetCacheHeaders(context)
if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
context.Status(http.StatusForbidden)
return true
@@ -1039,6 +1086,7 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {
context.Status(http.StatusForbidden)
return true
}
+ defer clear(dek)
defer model.ReleaseBoxReadLock(boxID)
}
data, err := readAssetBytesLocked(assetAbsPath, boxID, dek)
@@ -1050,6 +1098,13 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {
}
return false
}
+ if boxID != "" && model.IsEncryptedBox(boxID) {
+ decrypted := data
+ defer clear(decrypted)
+ defer func() {
+ clear(data)
+ }()
+ }
if !model.Conf.Editor.AllowSVGScript {
sanitized, sanitizeErr := util.SanitizeSVG(string(data))
@@ -1072,7 +1127,17 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {
// readAssetBytesLocked 读取 asset 文件字节;读取加密笔记本资源时调用方必须持有对应的 box 读锁。
func readAssetBytesLocked(absPath, boxID string, dek []byte) ([]byte, error) {
- data, err := os.ReadFile(absPath)
+ var data []byte
+ var err error
+ if heif.IsPath(absPath) {
+ limit := int64(heif.MaxInputBytes)
+ if boxID != "" && model.IsEncryptedBox(boxID) {
+ limit += 2 * 1024 * 1024
+ }
+ data, err = heif.ReadFileLimited(absPath, limit)
+ } else {
+ data, err = os.ReadFile(absPath)
+ }
if err != nil {
return nil, err
}
@@ -1082,11 +1147,144 @@ func readAssetBytesLocked(absPath, boxID string, dek []byte) ([]byte, error) {
if decErr != nil {
return nil, decErr
}
+ if len(plain) > heif.MaxInputBytes {
+ clear(plain)
+ return nil, heif.ErrInputTooLarge
+ }
return plain, nil
}
return data, nil
}
+// serveHEIFPreview 将 HEIF/HEIC 资源按需转成 JPEG。加密笔记本只使用受限内存缓存,不把明文写入磁盘。
+func serveHEIFPreview(c *gin.Context, absPath string) {
+ boxID := model.ExtractBoxIDFromAssetsPath(absPath)
+ encrypted := boxID != "" && model.IsEncryptedBox(boxID)
+ var dek []byte
+ if encrypted {
+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ defer model.ReleaseEncryptedBoxOperation(boxID)
+ model.HoldBoxReadLock(boxID)
+ var err error
+ dek, err = model.GetDEKIfUnlocked(boxID)
+ if err != nil {
+ model.ReleaseBoxReadLock(boxID)
+ c.Status(http.StatusForbidden)
+ return
+ }
+ defer clear(dek)
+ defer model.ReleaseBoxReadLock(boxID)
+ }
+ if rejectOversizedHEIF(c, absPath, encrypted) {
+ return
+ }
+
+ source, err := readAssetBytesLocked(absPath, boxID, dek)
+ clear(dek)
+ dek = nil
+ if err != nil {
+ if errors.Is(err, heif.ErrInputTooLarge) {
+ c.Status(http.StatusRequestEntityTooLarge)
+ } else if os.IsNotExist(err) {
+ c.Status(http.StatusNotFound)
+ } else {
+ logging.LogErrorf("read HEIF asset [%s] failed: %s", absPath, err)
+ c.Status(http.StatusInternalServerError)
+ }
+ return
+ }
+ if encrypted {
+ defer clear(source)
+ }
+ writeHEIFPreview(c, absPath, source, boxID, encrypted)
+}
+
+func servePlainHEIFPreview(c *gin.Context, absPath string, boxID string, encrypted bool) {
+ if rejectOversizedHEIF(c, absPath, encrypted) {
+ return
+ }
+ source, err := heif.ReadFileLimited(absPath, int64(heif.MaxInputBytes))
+ if err != nil {
+ if errors.Is(err, heif.ErrInputTooLarge) {
+ c.Status(http.StatusRequestEntityTooLarge)
+ } else if os.IsNotExist(err) {
+ c.Status(http.StatusNotFound)
+ } else {
+ logging.LogErrorf("read HEIF asset [%s] failed: %s", absPath, err)
+ c.Status(http.StatusInternalServerError)
+ }
+ return
+ }
+ if encrypted {
+ defer clear(source)
+ }
+ writeHEIFPreview(c, absPath, source, boxID, encrypted)
+}
+
+func rejectOversizedHEIF(c *gin.Context, absPath string, encrypted bool) bool {
+ info, err := os.Stat(absPath)
+ if err != nil {
+ return false
+ }
+ limit := int64(heif.MaxInputBytes)
+ if encrypted {
+ // 加密资源容器还包含名称元数据、分块长度和认证标签。
+ limit += 2 * 1024 * 1024
+ }
+ if info.Size() <= limit {
+ return false
+ }
+ c.Status(http.StatusRequestEntityTooLarge)
+ return true
+}
+
+func writeHEIFPreview(c *gin.Context, absPath string, source []byte, boxID string, encrypted bool) {
+ mode := heif.ModePreview
+ if c.Query("style") == "thumb" {
+ mode = heif.ModeThumbnail
+ }
+ result, err := heif.GetOrCreate(c.Request.Context(), source, heif.Options{
+ Mode: mode,
+ BoxID: boxID,
+ Encrypted: encrypted,
+ })
+ if err != nil {
+ if errors.Is(err, c.Request.Context().Err()) {
+ return
+ }
+ status := http.StatusUnprocessableEntity
+ if errors.Is(err, heif.ErrInputTooLarge) || errors.Is(err, heif.ErrImageTooLarge) {
+ status = http.StatusRequestEntityTooLarge
+ } else if errors.Is(err, context.DeadlineExceeded) {
+ status = http.StatusGatewayTimeout
+ }
+ logging.LogWarnf("convert HEIF asset [%s] failed: %s", absPath, err)
+ c.Status(status)
+ return
+ }
+
+ c.Header("X-Content-Type-Options", "nosniff")
+ c.Header("Content-Type", "image/jpeg")
+ if encrypted {
+ c.Header("Cache-Control", "private, no-store")
+ defer clear(result.Data)
+ } else {
+ c.Header("ETag", result.ETag)
+ if c.GetHeader("If-None-Match") == result.ETag {
+ c.Status(http.StatusNotModified)
+ return
+ }
+ }
+ if result.Path != "" {
+ http.ServeFile(c.Writer, c.Request, result.Path)
+ return
+ }
+ c.Data(http.StatusOK, "image/jpeg", result.Data)
+}
+
// serveEncryptedAsset 处理加密笔记本 asset 的 HTTP 输出。
// 若 absPath 在已解锁的加密笔记本下,读密文→解密→按扩展名设置 Content-Type→输出,返回 true;
// 否则返回 false,由调用方走原 http.ServeFile 路径。
@@ -1095,6 +1293,7 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
if boxID == "" || !model.IsEncryptedBox(boxID) {
return false // 非加密 box,走原路径
}
+ setEncryptedAssetCacheHeaders(context)
if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
context.Status(http.StatusForbidden)
return true
@@ -1108,8 +1307,15 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
context.Status(http.StatusForbidden)
return true
}
+ defer clear(dek)
defer model.ReleaseBoxReadLock(boxID)
- ciphertext, readErr := os.ReadFile(absPath)
+ var ciphertext []byte
+ var readErr error
+ if heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true") {
+ ciphertext, readErr = heif.ReadFileLimited(absPath, int64(heif.MaxInputBytes)+2*1024*1024)
+ } else {
+ ciphertext, readErr = os.ReadFile(absPath)
+ }
if readErr != nil {
context.Status(http.StatusNotFound)
return true
@@ -1121,6 +1327,7 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
context.Status(http.StatusInternalServerError)
return true
}
+ defer clear(plain)
// 下载时用原始文件名(查加密映射),查不到则退回磁盘名
dispositionName := absPath
if originalName := model.LookupAssetOriginalNameLocked(boxID, diskName); originalName != "" {
@@ -1162,6 +1369,7 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
context.Status(http.StatusForbidden)
return true
}
+ setEncryptedAssetCacheHeaders(context)
if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
context.Status(http.StatusForbidden)
return true
@@ -1175,10 +1383,26 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
context.Status(http.StatusForbidden)
return true
}
+ defer clear(dek)
defer model.ReleaseBoxReadLock(boxID)
- ciphertext, readErr := os.ReadFile(absPath)
+ if heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true") &&
+ rejectOversizedHEIF(context, absPath, true) {
+ return true
+ }
+ heifPreview := heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true")
+ var ciphertext []byte
+ var readErr error
+ if heifPreview {
+ ciphertext, readErr = heif.ReadFileLimited(absPath, int64(heif.MaxInputBytes)+2*1024*1024)
+ } else {
+ ciphertext, readErr = os.ReadFile(absPath)
+ }
if readErr != nil {
- context.Status(http.StatusNotFound)
+ if errors.Is(readErr, heif.ErrInputTooLarge) {
+ context.Status(http.StatusRequestEntityTooLarge)
+ } else {
+ context.Status(http.StatusNotFound)
+ }
return true
}
var plain []byte
@@ -1200,11 +1424,21 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
diskName := filepath.Base(absPath)
plain, decErr = model.DecryptAsset(boxID, diskName, dek, ciphertext)
}
+ clear(dek)
if decErr != nil {
logging.LogErrorf("decrypt history [%s] failed: %s", absPath, decErr)
context.Status(http.StatusInternalServerError)
return true
}
+ defer clear(plain)
+ if heifPreview && len(plain) > heif.MaxInputBytes {
+ context.Status(http.StatusRequestEntityTooLarge)
+ return true
+ }
+ if heifPreview {
+ writeHEIFPreview(context, absPath, plain, boxID, true)
+ return true
+ }
secureAssetContentHeaders(context, absPath, absPath)
contentType := mime.TypeByExtension(filepath.Ext(absPath))
if contentType == "" {
@@ -1258,8 +1492,8 @@ func serveThumbnail(context *gin.Context, assetAbsPath, requestPath string) bool
func serveRepoDiff(ginServer *gin.Engine) {
repoDiffBaseDir := filepath.Join(util.TempDir, "repo", "diff")
ginServer.GET("/repo/diff/*path", model.CheckAuth, model.CheckAdminRole, func(context *gin.Context) {
- requestPath := filepath.Clean(context.Param("path"))
- if strings.Contains(requestPath, "..") {
+ requestPath, valid := cleanRepoDiffRequestPath(context.Param("path"))
+ if !valid {
context.Status(http.StatusUnauthorized)
return
}
@@ -1268,9 +1502,19 @@ func serveRepoDiff(ginServer *gin.Engine) {
context.Status(http.StatusForbidden)
return
}
+ heifPreview := heif.IsPath(requestPath) && !strings.EqualFold(context.Query("download"), "true")
+ if heifPreview {
+ if !acquireHEIFPreviewSlot(context) {
+ return
+ }
+ defer releaseHEIFPreviewSlot()
+ }
// 从路径提取 boxID,加密笔记本已锁定时拒绝访问(锁定后 repo 预览解密文件仍存在磁盘上)
parts := strings.SplitN(strings.TrimPrefix(requestPath, "/"), "/", 2)
+ encryptedBoxID := ""
if len(parts) >= 1 && model.IsEncryptedBox(parts[0]) {
+ encryptedBoxID = parts[0]
+ setEncryptedAssetCacheHeaders(context)
if err := model.AcquireEncryptedBoxOperation(parts[0]); err != nil {
context.Status(http.StatusForbidden)
return
@@ -1278,20 +1522,43 @@ func serveRepoDiff(ginServer *gin.Engine) {
defer model.ReleaseEncryptedBoxOperation(parts[0])
model.HoldBoxReadLock(parts[0])
defer model.ReleaseBoxReadLock(parts[0])
- if _, dekErr := model.GetDEKIfUnlocked(parts[0]); dekErr != nil {
+ dek, dekErr := model.GetDEKIfUnlocked(parts[0])
+ if dekErr != nil {
context.Status(http.StatusForbidden)
return
}
+ clear(dek)
}
- p := filepath.Join(repoDiffBaseDir, requestPath)
+ p := filepath.Join(repoDiffBaseDir, filepath.FromSlash(strings.TrimPrefix(requestPath, "/")))
if !gulu.File.IsSubPath(repoDiffBaseDir, p) {
context.Status(http.StatusUnauthorized)
return
}
+ if heifPreview {
+ servePlainHEIFPreview(context, p, encryptedBoxID, encryptedBoxID != "")
+ return
+ }
+ secureAssetContentHeaders(context, p, p)
http.ServeFile(context.Writer, context.Request, p)
})
}
+func cleanRepoDiffRequestPath(requestPath string) (string, bool) {
+ return cleanURLFileRequestPath(requestPath)
+}
+
+func cleanHistoryRequestPath(requestPath string) (string, bool) {
+ return cleanURLFileRequestPath(requestPath)
+}
+
+func cleanURLFileRequestPath(requestPath string) (string, bool) {
+ // URL 路径只接受正斜杠,避免 Windows 在落盘阶段把反斜杠重新解释为目录分隔符。
+ if strings.Contains(requestPath, `\`) || strings.Contains(requestPath, "..") {
+ return "", false
+ }
+ return path.Clean("/" + strings.TrimPrefix(requestPath, "/")), true
+}
+
func serveDebug(ginServer *gin.Engine) {
// 调试端点默认不注册,仅 --enable-pprof 显式开启;即使开启也要求管理员鉴权 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-9cqq-p2hw-mj3f
if !util.EnablePprof {
diff --git a/kernel/server/serve_assets_test.go b/kernel/server/serve_assets_test.go
index 529a6423ca..abecf728e0 100644
--- a/kernel/server/serve_assets_test.go
+++ b/kernel/server/serve_assets_test.go
@@ -288,3 +288,12 @@ func TestSecureAssetContentHeadersKeepsExplicitDownload(t *testing.T) {
t.Fatalf("explicit download=true must return attachment, got Content-Disposition %q", recorder.Header().Get("Content-Disposition"))
}
}
+
+func TestEncryptedAssetCacheHeaders(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ setEncryptedAssetCacheHeaders(context)
+ if got := recorder.Header().Get("Cache-Control"); got != "private, no-store" {
+ t.Fatalf("unexpected encrypted asset cache policy: %q", got)
+ }
+}
diff --git a/kernel/server/serve_history_guard_test.go b/kernel/server/serve_history_guard_test.go
index a3c19ef117..9809739c74 100644
--- a/kernel/server/serve_history_guard_test.go
+++ b/kernel/server/serve_history_guard_test.go
@@ -13,6 +13,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "strings"
"testing"
"github.com/gin-gonic/gin"
@@ -61,6 +62,7 @@ func TestHistoryRouteBlocksSensitiveSnapshots(t *testing.T) {
{"/history/2026-08-15-120000-sync/.siyuan/publishAccess.json", http.StatusForbidden},
{"/history/2026-08-15-120000-sync/templates/private.md", http.StatusForbidden},
{"/history/2026-08-15-120000-sync/snippets/conf.json", http.StatusForbidden},
+ {"/history/2026-08-15-120000-sync%5ctemplates%5cprivate.md", http.StatusUnauthorized},
{"/history/2026-08-15-120000-sync/assets/image.png", http.StatusOK},
} {
recorder := httptest.NewRecorder()
@@ -91,6 +93,11 @@ func TestRepoDiffRouteBlocksSensitivePaths(t *testing.T) {
if err := os.WriteFile(allowedPath, []byte("asset"), 0644); err != nil {
t.Fatal(err)
}
+ for _, name := range []string{"script.svg", "image.heic"} {
+ if err := os.WriteFile(filepath.Join(diffDir, "assets", name), []byte("asset"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
engine := gin.New()
engine.Use(func(c *gin.Context) {
@@ -114,4 +121,51 @@ func TestRepoDiffRouteBlocksSensitivePaths(t *testing.T) {
t.Fatalf("GET %s returned %d, want %d", test.requestPath, recorder.Code, test.wantStatus)
}
}
+
+ for _, requestPath := range []string{
+ "/repo/diff/assets/script.svg",
+ "/repo/diff/assets/image.heic?download=true",
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, requestPath, nil))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("GET %s returned %d, want %d", requestPath, recorder.Code, http.StatusOK)
+ }
+ if disposition := recorder.Header().Get("Content-Disposition"); !strings.HasPrefix(disposition, "attachment") {
+ t.Fatalf("GET %s must download, got Content-Disposition %q", requestPath, disposition)
+ }
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("GET %s missing X-Content-Type-Options", requestPath)
+ }
+ }
+}
+
+func TestCleanRepoDiffRequestPathUsesURLSeparators(t *testing.T) {
+ const requestPath = "/20260816000000-box001/assets/image.heic"
+ if got, valid := cleanRepoDiffRequestPath(requestPath); !valid || got != requestPath {
+ t.Fatalf("cleaned repository diff path is %q, want %q", got, requestPath)
+ }
+ for _, invalid := range []string{
+ `/20260816000000-box001\assets\image.heic`,
+ "/20260816000000-box001/../assets/image.heic",
+ } {
+ if got, valid := cleanRepoDiffRequestPath(invalid); valid {
+ t.Fatalf("unsafe repository diff path %q was accepted as %q", invalid, got)
+ }
+ }
+}
+
+func TestCleanHistoryRequestPathUsesURLSeparators(t *testing.T) {
+ const requestPath = "/2026-08-15-120000-sync/assets/image.heic"
+ if got, valid := cleanHistoryRequestPath(requestPath); !valid || got != requestPath {
+ t.Fatalf("cleaned history path is %q, want %q", got, requestPath)
+ }
+ for _, invalid := range []string{
+ `/2026-08-15-120000-sync\templates\private.md`,
+ "/2026-08-15-120000-sync/../templates/private.md",
+ } {
+ if got, valid := cleanHistoryRequestPath(invalid); valid {
+ t.Fatalf("unsafe history path %q was accepted as %q", invalid, got)
+ }
+ }
}
diff --git a/kernel/util/file.go b/kernel/util/file.go
index bcd50e87a9..7717ed7b4b 100644
--- a/kernel/util/file.go
+++ b/kernel/util/file.go
@@ -163,7 +163,7 @@ func RemoveID(name string) string {
}
var commonSuffixes = []string{
- ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp", ".tif", ".tiff",
+ ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp", ".tif", ".tiff", ".heic", ".heif",
".txt", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".md", ".rtf",
".zip", ".rar", ".7z", ".tar", ".gz", ".bz2",
".mp3", ".wav", ".aac", ".flac", ".ogg", ".m4a",
diff --git a/kernel/util/path.go b/kernel/util/path.go
index 3581703db4..cc85c3d371 100644
--- a/kernel/util/path.go
+++ b/kernel/util/path.go
@@ -337,14 +337,18 @@ func IsAssetLinkDest(dest []byte, includeServePath bool) bool {
}
var (
- SiYuanAssetsImage = []string{".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif"}
+ SiYuanAssetsImage = []string{".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif", ".heic", ".heif"}
SiYuanAssetsAudio = []string{".mp3", ".wav", ".ogg", ".m4a", ".flac"}
SiYuanAssetsVideo = []string{".mov", ".weba", ".mkv", ".mp4", ".webm"}
)
// IsPossiblyImage 模糊判断指定文件链接是否可能是图片。
func IsPossiblyImage(assetPath string) bool {
- ext := strings.ToLower(filepath.Ext(assetPath))
+ extensionPath := assetPath
+ if index := strings.IndexAny(extensionPath, "?#"); index >= 0 {
+ extensionPath = extensionPath[:index]
+ }
+ ext := strings.ToLower(filepath.Ext(extensionPath))
if "" != ext {
return gulu.Str.Contains(ext, SiYuanAssetsImage)
}
diff --git a/kernel/util/path_test.go b/kernel/util/path_test.go
index 573ae44694..4fcb2f963e 100644
--- a/kernel/util/path_test.go
+++ b/kernel/util/path_test.go
@@ -39,6 +39,18 @@ func TestFilterSelfChildDocsPreservesInputOrder(t *testing.T) {
}
}
+func TestIsPossiblyImageWithQueryAndFragment(t *testing.T) {
+ for _, assetPath := range []string{
+ "assets/photo.heic",
+ "assets/photo.HEIF?box=20260816000000-abcdefg",
+ "assets/photo.heic?box=20260816000000-abcdefg#preview",
+ } {
+ if !IsPossiblyImage(assetPath) {
+ t.Fatalf("HEIF asset was not recognized as an image: %s", assetPath)
+ }
+ }
+}
+
func TestFilterSelfChildDocsRemovesChildrenAndDuplicates(t *testing.T) {
parentPath := "/20260810000001-abcdefg.sy"
childPath := "/20260810000001-abcdefg/20260810000002-abcdefg.sy"
diff --git a/kernel/util/working.go b/kernel/util/working.go
index 0973023a3a..590468ff91 100644
--- a/kernel/util/working.go
+++ b/kernel/util/working.go
@@ -569,6 +569,8 @@ func initMime() {
mime.AddExtensionType(".tiff", "image/tiff")
mime.AddExtensionType(".tif", "image/tiff")
mime.AddExtensionType(".webp", "image/webp")
+ mime.AddExtensionType(".heic", "image/heic")
+ mime.AddExtensionType(".heif", "image/heif")
mime.AddExtensionType(".ico", "image/x-icon")
}