Skip to content

feat: add HEIC/HEIF image format support for Gemini channel - #4049

Merged
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
RedwindA:feat/geminiHEICHEIF
Apr 2, 2026
Merged

Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
RedwindA:feat/geminiHEICHEIF

Conversation

@RedwindA

@RedwindA RedwindA commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

📝 变更描述 / Description

close #3502
Gemini API 支持 HEIC/HEIF 图片格式,但项目之前缺少对该格式的识别与处理。本 PR 新增完整的 HEIC/HEIF 支持链路:

  1. Gemini 渠道白名单:在 geminiSupportedMimeTypes 中添加 image/heic 和 image/heif
  2. MIME 类型检测:通过 ISOBMFF ftyp box 的 major brand 字段识别 HEIC/HEIF 文件(Go 标准库 http.DetectContentType 和 image.DecodeConfig 均不支持该格式)
  3. 文件扩展名映射:在 GetMimeTypeByExtension 中添加 .heic / .heif 扩展名到 MIME 类型的映射
  4. 图片尺寸解析:实现 ISOBMFF box tree 遍历,沿 meta → iprp → ipco → ispe 路径提取宽高
  5. getImageConfig 重构:原实现在首次 image.DecodeConfig 失败后用同一个已耗尽的 io.Reader 重试 webp 解码(实际无效),改为先 io.ReadAll 缓存数据再逐格式尝试,同时增加 HEIF/HEIC 作为第三级 fallback

🚀 变更类型 / Type of change

  • ✨ 新功能 (New feature)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自撰写此描述,去除了 AI 原始输出的冗余。
  • 深度理解: 我已完全理解这些更改的工作原理及潜在影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过了测试或手动验证。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

在本地开发服务器验证了base64和url的heif均能发送给gemini,使用https://convertico.com/samples/heif/convertico-little-sorcerer-heif.heif

Summary by CodeRabbit

  • New Features
    • Added support for HEIC and HEIF image formats with automatic detection and dimension extraction.
    • Extended file type detection to recognize .heic and .heif extensions and map them to the correct MIME types.

Add detection, MIME type mapping, and dimension parsing for HEIC/HEIF
images via ISOBMFF ftyp brand inspection and ispe box parsing. Update
Gemini relay to accept these formats and refactor getImageConfig to
properly retry decoders using buffered data.
@coderabbitai

coderabbitai Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds HEIF/HEIC image support: updates Gemini MIME allowlist, extends extension- and content-based detection to recognize HEIF/HEIC, parses dimensions from ISOBMFF boxes, and integrates HEIF/HEIC handling into image config decoding and reader buffering.

Changes

Cohort / File(s) Summary
Gemini Relay Configuration
relay/channel/gemini/relay-gemini.go
Added image/heic and image/heif to the Gemini MIME allowlist.
File Type Detection
service/file_decoder.go
Mapped .heic → image/heic and .heif → image/heif; call to detectHEIF added to URL/content sniffing path.
HEIF/HEIC Format Support
service/file_service.go
Added detectHEIF, parseHEIFDimensions, findISPE and ISOBMFF-based HEIF detection/width-height extraction; integrated into smartDetectMimeType and decodeImageConfig; new error on failed HEIF dimension parse.
Image Configuration Retrieval
service/image.go
Refactored getImageConfig to buffer reader data for repeated decode attempts; added HEIF/HEIC detection and dimension parsing fallback with explicit HEIF errors and updated logging.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Detector as File Detector
    participant Parser as HEIF/HEIC Parser
    participant Relay as Gemini Relay

    Client->>Detector: Send/read image data
    Detector->>Detector: Try image.DecodeConfig / webp.DecodeConfig
    alt Standard decoder succeeds
        Detector->>Relay: Return format + dimensions
    else Standard decoders fail
        Detector->>Parser: Run detectHEIF on data
        alt HEIF/HEIC detected
            Parser->>Parser: Traverse ISOBMFF boxes (meta → ispe)
            Parser->>Detector: Return width/height + format
            Detector->>Relay: Return HEIF/HEIC format + dimensions
        else Not HEIF/HEIC
            Detector->>Relay: Return unknown/unsupported format
        end
    end
    Relay->>Relay: Validate MIME against allowlist
    Relay->>Client: Proceed with Gemini processing
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • creamlike1024

Poem

🐰
I nibble bytes and hop through frames,
HEIF and HEIC now learn their names.
Boxes parsed and sizes found,
Inline images leap unbound.
Hooray — the pixels dance around!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main objective of the PR: adding HEIC/HEIF image format support for the Gemini channel. It uses a descriptive, specific format and is concise.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@RedwindA
RedwindA marked this pull request as draft April 2, 2026 08:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
service/image.go (1)

181-191: Duplicate HEIF/HEIC handling logic.

This code block is nearly identical to lines 458-467 in file_service.go::decodeImageConfig. Consider extracting this into a shared helper function to reduce duplication and ensure consistent behavior.

♻️ Proposed helper function

In file_service.go, add a helper:

// tryDecodeHEIFConfig attempts to decode HEIF/HEIC image config.
// Returns (config, format, ok).
func tryDecodeHEIFConfig(data []byte) (image.Config, string, bool) {
	heifMime := detectHEIF(data)
	if heifMime == "" {
		return image.Config{}, "", false
	}
	formatName := "heif"
	if heifMime == "image/heic" {
		formatName = "heic"
	}
	if w, h, ok := parseHEIFDimensions(data); ok {
		return image.Config{Width: w, Height: h}, formatName, true
	}
	return image.Config{}, "", false
}

Then in both decodeImageConfig and getImageConfig:

-	// Try HEIF/HEIC: parse ISOBMFF ispe box for dimensions
-	if heifMime := detectHEIF(data); heifMime != "" {
-		formatName := "heif"
-		if heifMime == "image/heic" {
-			formatName = "heic"
-		}
-		if w, h, ok := parseHEIFDimensions(data); ok {
-			return image.Config{Width: w, Height: h}, formatName, nil
-		}
-		return image.Config{}, "", fmt.Errorf("failed to decode HEIF/HEIC image dimensions")
-	}
+	if config, format, ok := tryDecodeHEIFConfig(data); ok {
+		return config, format, nil
+	} else if detectHEIF(data) != "" {
+		return image.Config{}, "", fmt.Errorf("failed to decode HEIF/HEIC image dimensions")
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@service/image.go` around lines 181 - 191, Extract the duplicated HEIF/HEIC
logic into a shared helper to avoid repetition: create tryDecodeHEIFConfig(data
[]byte) (image.Config, string, bool) that calls detectHEIF(data), maps the mime
to "heif"/"heic", and uses parseHEIFDimensions(data) to return the config,
format and success flag (true/false) instead of handling errors there; then
replace the duplicated blocks in getImageConfig and decodeImageConfig with calls
to tryDecodeHEIFConfig and handle the returned bool (return the config and
format on true, otherwise continue/fallthrough or return an appropriate error).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@service/file_service.go`:
- Around line 494-521: parseHEIFDimensions fails to handle ISOBMFF extended
sizes: when a box header has boxSize==1 (64-bit extended size) or boxSize==0
(box to EOF) it currently mis-parses or skips boxes; update parseHEIFDimensions
to read the 8-byte extended size when boxSize==1 (ensuring bounds checks for the
extra 8 bytes) and treat boxSize==0 as size = size-offset (remaining bytes to
EOF), validate resulting boxSize >= header length (and >=8 for normal boxes),
and advance offset by the correct total header+payload length; also ensure the
special handling of the "meta" full box accounts for any extended size when
slicing metaData and still skips the 4-byte version/flags before calling
findISPE.

---

Nitpick comments:
In `@service/image.go`:
- Around line 181-191: Extract the duplicated HEIF/HEIC logic into a shared
helper to avoid repetition: create tryDecodeHEIFConfig(data []byte)
(image.Config, string, bool) that calls detectHEIF(data), maps the mime to
"heif"/"heic", and uses parseHEIFDimensions(data) to return the config, format
and success flag (true/false) instead of handling errors there; then replace the
duplicated blocks in getImageConfig and decodeImageConfig with calls to
tryDecodeHEIFConfig and handle the returned bool (return the config and format
on true, otherwise continue/fallthrough or return an appropriate error).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b003b8d0-35f9-4515-acc6-5f85382b09c9

📥 Commits

Reviewing files that changed from the base of the PR and between 41cd051 and 79527c0.

📒 Files selected for processing (4)
  • relay/channel/gemini/relay-gemini.go
  • service/file_decoder.go
  • service/file_service.go
  • service/image.go

Comment thread service/file_service.go Resolved
parseHEIFDimensions now correctly handles boxSize==1 (64-bit extended
size) and boxSize==0 (box-to-EOF), preventing the parser from breaking
out of the loop when encountering these valid ISOBMFF box headers
before reaching the meta box.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@service/file_service.go`:
- Around line 525-531: The current logic in the "meta" box handler returns the
first ispe found (via findISPE(metaData[4:])), which can be a tile/thumbnail
size; instead, resolve the primary image item and pick the ispe associated with
that item: parse the ipco/ipma/pitm structures in the meta box to locate the
primary item id (pitm), use ipma to map that item to the correct property index
in ipco, then read the ispe entry for that specific property entry. Update the
code path that calls findISPE(metaData[4:]) (and the duplicate logic around
lines 540-565) to: parse pitm, parse ipma associations, locate the matching ipco
property slot, and call findISPE only on that property's data so the returned
width/height correspond to the primary image.
- Around line 484-488: The switch handling HEIF/HEIC brands incorrectly maps
sequence brands to still-image MIME types and omits some sequence brands; update
the brand mapping in the switch so that msf1 and the HEVC sequence brands (hevc,
hevx, hevm, hevs) are treated as sequences (return an image/heif-sequence or
image/heic-sequence MIME subtype as appropriate) or explicitly reject them, and
ensure heic-related brands still map to image/heic while mif1/msf1 map to
image/heif-sequence (or are rejected) — adjust the cases for
"msf1","hevc","hevx","hevm","hevs" accordingly in the same switch block.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e5a76ae8-4888-4524-8e36-9a362f4721d6

📥 Commits

Reviewing files that changed from the base of the PR and between 79527c0 and f449e06.

📒 Files selected for processing (1)
  • service/file_service.go

Comment thread service/file_service.go Resolved
Comment thread service/file_service.go Resolved
@RedwindA
RedwindA marked this pull request as ready for review April 2, 2026 09:50
@Calcium-Ion
Calcium-Ion merged commit 9816ad8 into QuantumNous:main Apr 2, 2026
VeryGoodUser1 pushed a commit to xmz-ai/new-api that referenced this pull request Apr 3, 2026
…ous#4049)

* feat: add HEIC/HEIF image format support

Add detection, MIME type mapping, and dimension parsing for HEIC/HEIF
images via ISOBMFF ftyp brand inspection and ispe box parsing. Update
Gemini relay to accept these formats and refactor getImageConfig to
properly retry decoders using buffered data.

* fix: handle ISOBMFF extended sizes in HEIF dimension parser

parseHEIFDimensions now correctly handles boxSize==1 (64-bit extended
size) and boxSize==0 (box-to-EOF), preventing the parser from breaking
out of the loop when encountering these valid ISOBMFF box headers
before reaching the meta box.
@RedwindA
RedwindA deleted the feat/geminiHEICHEIF branch July 23, 2026 07:03
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…ous#4049)

* feat: add HEIC/HEIF image format support

Add detection, MIME type mapping, and dimension parsing for HEIC/HEIF
images via ISOBMFF ftyp brand inspection and ispe box parsing. Update
Gemini relay to accept these formats and refactor getImageConfig to
properly retry decoders using buffered data.

* fix: handle ISOBMFF extended sizes in HEIF dimension parser

parseHEIFDimensions now correctly handles boxSize==1 (64-bit extended
size) and boxSize==0 (box-to-EOF), preventing the parser from breaking
out of the loop when encountering these valid ISOBMFF box headers
before reaching the meta box.
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…ous#4049)

* feat: add HEIC/HEIF image format support

Add detection, MIME type mapping, and dimension parsing for HEIC/HEIF
images via ISOBMFF ftyp brand inspection and ispe box parsing. Update
Gemini relay to accept these formats and refactor getImageConfig to
properly retry decoders using buffered data.

* fix: handle ISOBMFF extended sizes in HEIF dimension parser

parseHEIFDimensions now correctly handles boxSize==1 (64-bit extended
size) and boxSize==0 (box-to-EOF), preventing the parser from breaking
out of the loop when encountering these valid ISOBMFF box headers
before reaching the meta box.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

gemini 支持 heif

2 participants