Repository navigation
feat: add HEIC/HEIF image format support for Gemini channel - #4049
Conversation
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.
WalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
decodeImageConfigandgetImageConfig:- // 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
📒 Files selected for processing (4)
relay/channel/gemini/relay-gemini.goservice/file_decoder.goservice/file_service.goservice/image.go
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
service/file_service.go
…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.
…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.
…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.
📝 变更描述 / Description
close #3502
Gemini API 支持 HEIC/HEIF 图片格式,但项目之前缺少对该格式的识别与处理。本 PR 新增完整的 HEIC/HEIF 支持链路:
geminiSupportedMimeTypes中添加image/heic和image/heifftypbox 的 major brand 字段识别 HEIC/HEIF 文件(Go 标准库http.DetectContentType和image.DecodeConfig均不支持该格式)GetMimeTypeByExtension中添加.heic/.heif扩展名到 MIME 类型的映射meta → iprp → ipco → ispe路径提取宽高getImageConfig重构:原实现在首次image.DecodeConfig失败后用同一个已耗尽的io.Reader重试 webp 解码(实际无效),改为先io.ReadAll缓存数据再逐格式尝试,同时增加 HEIF/HEIC 作为第三级 fallback🚀 变更类型 / Type of change
✅ 提交前检查项 / Checklist
📸 运行证明 / Proof of Work
在本地开发服务器验证了base64和url的heif均能发送给gemini,使用https://convertico.com/samples/heif/convertico-little-sorcerer-heif.heif
Summary by CodeRabbit