feat: animated GIF covers with config toggle and focus-based pausing
All checks were successful
Build plugin / build (push) Successful in 1m8s
All checks were successful
Build plugin / build (push) Successful in 1m8s
- Add settings menu with 'Animate GIF covers' toggle (default: off) - When enabled: extract all GIF frames via ffmpeg, build AnimatedTexture - When disabled: extract first frame only (static ImageTexture) - AnimatedTexture starts paused — unpauses only when card has focus - Focus-based pausing via gui_focus_changed signal (walks up to GameCard) - Parse GIF89a frame delays for accurate animation speed - Cache invalidation when setting changes (no restart needed) - Cache AnimatedTextures in memory to avoid re-extraction - Bump to v0.1.13
This commit is contained in:
parent
9be6847f14
commit
208dc58f28
5 changed files with 308 additions and 59 deletions
25
core/artprovider_settings.gd
Normal file
25
core/artprovider_settings.gd
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
extends VBoxContainer
|
||||
|
||||
## Settings screen for the itch.io art provider.
|
||||
##
|
||||
## Provides a toggle for animated GIF covers. When enabled, GIF cover art
|
||||
## is extracted frame-by-frame and displayed as an AnimatedTexture that
|
||||
## pauses when the card loses focus.
|
||||
|
||||
var settings_manager := load("res://core/global/settings_manager.tres") as SettingsManager
|
||||
|
||||
const SETTING_SECTION := "plugin.artprovider"
|
||||
const SETTING_ANIMATED_GIFS := "animated_gifs"
|
||||
|
||||
@onready var animated_toggle: Toggle = $%AnimatedGifsToggle
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
animated_toggle.button_pressed = settings_manager.get_value(
|
||||
SETTING_SECTION, SETTING_ANIMATED_GIFS, false
|
||||
) as bool
|
||||
animated_toggle.toggled.connect(_on_animated_gifs_toggled)
|
||||
|
||||
|
||||
func _on_animated_gifs_toggled(pressed: bool) -> void:
|
||||
settings_manager.set_value(SETTING_SECTION, SETTING_ANIMATED_GIFS, pressed)
|
||||
20
core/artprovider_settings.tscn
Normal file
20
core/artprovider_settings.tscn
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
[gd_scene load_steps=3 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://plugins/itch-artprovider/core/artprovider_settings.gd" id="1"]
|
||||
[ext_resource type="PackedScene" uid="uid://d1qb7euwlu7bh" path="res://core/ui/components/toggle.tscn" id="2"]
|
||||
|
||||
[node name="ArtProviderSettings" type="VBoxContainer"]
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
theme_override_constants/separation = 10
|
||||
script = ExtResource("1")
|
||||
|
||||
[node name="AnimatedGifsToggle" parent="." instance=ExtResource("2")]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
text = "Animate GIF covers"
|
||||
description = "Extract all frames from animated GIF covers. Uses more memory but shows the full animation. Pauses when the card is not focused."
|
||||
button_pressed = false
|
||||
|
|
@ -19,11 +19,18 @@ const FFMPEG_BUILDS_URL := "https://github.com/BtbN/FFmpeg-Builds/releases/downl
|
|||
const CONNECT_POLL_DELAY_MS := 50
|
||||
const READ_POLL_DELAY_MS := 10
|
||||
const LOG_URL_MAX_LEN := 80
|
||||
const SETTING_SECTION := "plugin.artprovider"
|
||||
const SETTING_ANIMATED_GIFS := "animated_gifs"
|
||||
const GIF_DEFAULT_FRAME_DELAY_MS := 100
|
||||
|
||||
@export var use_caching: bool = true
|
||||
var http_image := HTTPImageFetcher.new()
|
||||
var _meta_cache_dir := "itch_art"
|
||||
var _enriched_meta: Dictionary = {}
|
||||
var settings_manager := load("res://core/global/settings_manager.tres") as SettingsManager
|
||||
var _animated_texture_cache: Dictionary = {}
|
||||
var _last_animated_setting: bool = false
|
||||
var _focused_animated_texture: AnimatedTexture = null
|
||||
|
||||
var layout_map: Dictionary = {
|
||||
LAYOUT.GRID_PORTRAIT: "-portrait",
|
||||
|
|
@ -46,8 +53,45 @@ func _init() -> void:
|
|||
func _ready() -> void:
|
||||
super()
|
||||
_enriched_meta = _load_enriched_meta()
|
||||
logger.info("itch.io Art Provider loaded")
|
||||
_last_animated_setting = _is_animated_gifs_enabled()
|
||||
logger.info("itch.io Art Provider loaded (animated_gifs=%s)" % str(_last_animated_setting))
|
||||
add_child(http_image)
|
||||
get_viewport().gui_focus_changed.connect(_on_focus_changed)
|
||||
|
||||
|
||||
## Returns whether animated GIF covers are enabled in settings.
|
||||
func _is_animated_gifs_enabled() -> bool:
|
||||
return settings_manager.get_value(SETTING_SECTION, SETTING_ANIMATED_GIFS, false) as bool
|
||||
|
||||
|
||||
## Handles focus changes across the UI. Pauses the previously focused
|
||||
## card's AnimatedTexture and unpauses the newly focused one.
|
||||
func _on_focus_changed(control: Control) -> void:
|
||||
# Pause the previously focused animation.
|
||||
if _focused_animated_texture != null:
|
||||
_focused_animated_texture.pause = true
|
||||
_focused_animated_texture = null
|
||||
|
||||
if control == null:
|
||||
return
|
||||
|
||||
# Walk up the tree to find the GameCard parent.
|
||||
var card: Control = control
|
||||
while card != null:
|
||||
if card is GameCard:
|
||||
break
|
||||
card = card.get_parent()
|
||||
|
||||
if card == null:
|
||||
return
|
||||
|
||||
# Check if the card's TextureRect has an AnimatedTexture.
|
||||
var texture_rect := card.get_node_or_null("%TextureRect") as TextureRect
|
||||
if texture_rect == null:
|
||||
return
|
||||
if texture_rect.texture is AnimatedTexture:
|
||||
_focused_animated_texture = texture_rect.texture as AnimatedTexture
|
||||
_focused_animated_texture.pause = false
|
||||
|
||||
|
||||
## Strips HTML srcset artifacts from a URL. Butlerd sometimes passes through
|
||||
|
|
@ -278,72 +322,43 @@ func _install_ffmpeg() -> bool:
|
|||
return true
|
||||
|
||||
|
||||
## Unified image fetch that routes GIF URLs through ffmpeg first-frame
|
||||
## extraction and non-GIF URLs through the normal HTTPImageFetcher path.
|
||||
## Unified image fetch that routes GIF URLs through ffmpeg and non-GIF URLs
|
||||
## through the normal HTTPImageFetcher path. Checks the animated GIF setting
|
||||
## on each call so toggling takes effect immediately.
|
||||
func _fetch_image(url: String, cache_flags: int) -> Texture2D:
|
||||
if _is_gif_url(url):
|
||||
return await _fetch_gif_first_frame(url, cache_flags)
|
||||
# Invalidate cache when the animated setting changes.
|
||||
var animated: bool = _is_animated_gifs_enabled()
|
||||
if animated != _last_animated_setting:
|
||||
_animated_texture_cache.clear()
|
||||
_last_animated_setting = animated
|
||||
logger.info("Animated GIF setting changed to %s — cache cleared" % str(animated))
|
||||
return await _fetch_gif_as_texture(url, cache_flags)
|
||||
return await http_image.fetch(url, cache_flags)
|
||||
|
||||
|
||||
## Downloads a GIF and extracts the first frame using ffmpeg.
|
||||
## Returns an ImageTexture, or null on failure.
|
||||
func _fetch_gif_first_frame(url: String, cache_flags: int) -> Texture2D:
|
||||
## Downloads a GIF and converts it to a Godot texture. When animated GIFs
|
||||
## are enabled, extracts all frames and returns an AnimatedTexture (paused
|
||||
## by default — the focus handler unpauses it). Otherwise extracts only
|
||||
## the first frame and returns a static ImageTexture.
|
||||
## Results are cached in _animated_texture_cache keyed by URL.
|
||||
func _fetch_gif_as_texture(url: String, cache_flags: int) -> Texture2D:
|
||||
# Return cached result if available.
|
||||
if _animated_texture_cache.has(url):
|
||||
return _animated_texture_cache[url]
|
||||
|
||||
var animated: bool = _is_animated_gifs_enabled()
|
||||
var ffmpeg_bin := await _ensure_ffmpeg()
|
||||
if ffmpeg_bin.is_empty():
|
||||
return null
|
||||
|
||||
var globalized_dir := ProjectSettings.globalize_path(BOXART_DIR)
|
||||
var gif_path := globalized_dir + "/_tmp.gif"
|
||||
var png_path := globalized_dir + "/_tmp.png"
|
||||
|
||||
# Download the GIF bytes via HTTPClient (same pattern as _fetch_game_page_metadata).
|
||||
var http := HTTPClient.new()
|
||||
var parts := url.split("/")
|
||||
var use_tls := parts[0] == "https:"
|
||||
var err := http.connect_to_host(parts[2], 443 if use_tls else 80, TLSOptions.client() if use_tls else null)
|
||||
if err != OK:
|
||||
logger.warn("GIF fetch: HTTP connect failed for %s: %d" % [url.left(LOG_URL_MAX_LEN), err])
|
||||
return null
|
||||
var deadline := Time.get_ticks_msec() + HTTP_TIMEOUT_MS
|
||||
while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:
|
||||
http.poll()
|
||||
if Time.get_ticks_msec() > deadline:
|
||||
http.close()
|
||||
logger.warn("GIF fetch: connect timed out")
|
||||
return null
|
||||
OS.delay_msec(CONNECT_POLL_DELAY_MS)
|
||||
if http.get_status() != HTTPClient.STATUS_CONNECTED:
|
||||
logger.warn("GIF fetch: not connected (status=%d)" % http.get_status())
|
||||
http.close()
|
||||
return null
|
||||
|
||||
http.request(HTTPClient.METHOD_GET, "/" + "/".join(parts.slice(3)), PackedStringArray())
|
||||
deadline = Time.get_ticks_msec() + HTTP_TIMEOUT_MS
|
||||
while http.get_status() == HTTPClient.STATUS_REQUESTING:
|
||||
http.poll()
|
||||
if Time.get_ticks_msec() > deadline:
|
||||
http.close()
|
||||
logger.warn("GIF fetch: request timed out")
|
||||
return null
|
||||
OS.delay_msec(READ_POLL_DELAY_MS)
|
||||
|
||||
var body := PackedByteArray()
|
||||
while http.get_status() == HTTPClient.STATUS_BODY:
|
||||
http.poll()
|
||||
var chunk: PackedByteArray = http.read_response_body_chunk()
|
||||
if chunk.is_empty():
|
||||
if Time.get_ticks_msec() > deadline:
|
||||
http.close()
|
||||
logger.warn("GIF fetch: body read timed out")
|
||||
return null
|
||||
OS.delay_msec(READ_POLL_DELAY_MS)
|
||||
continue
|
||||
body.append_array(chunk)
|
||||
http.close()
|
||||
var frames_dir := globalized_dir + "/_tmp_frames"
|
||||
|
||||
# Download the GIF bytes via HTTPClient.
|
||||
var body := await _download_gif_bytes(url)
|
||||
if body.is_empty():
|
||||
logger.warn("GIF fetch: empty response for %s" % url.left(LOG_URL_MAX_LEN))
|
||||
return null
|
||||
|
||||
# Write GIF to temp file.
|
||||
|
|
@ -354,7 +369,76 @@ func _fetch_gif_first_frame(url: String, cache_flags: int) -> Texture2D:
|
|||
gif_file.store_buffer(body)
|
||||
gif_file.close()
|
||||
|
||||
# Extract first frame with ffmpeg.
|
||||
var result: Texture2D
|
||||
|
||||
if animated:
|
||||
result = await _build_animated_gif_texture(ffmpeg_bin, gif_path, frames_dir, body, url)
|
||||
else:
|
||||
result = await _build_static_gif_texture(ffmpeg_bin, gif_path, globalized_dir + "/_tmp.png", url)
|
||||
|
||||
# Clean up.
|
||||
DirAccess.remove_absolute(gif_path)
|
||||
|
||||
# Cache the result.
|
||||
if result != null:
|
||||
_animated_texture_cache[url] = result
|
||||
|
||||
return result
|
||||
|
||||
|
||||
## Downloads GIF bytes from the given URL. Returns empty PackedByteArray on failure.
|
||||
func _download_gif_bytes(url: String) -> PackedByteArray:
|
||||
var http := HTTPClient.new()
|
||||
var parts := url.split("/")
|
||||
var use_tls := parts[0] == "https:"
|
||||
var err := http.connect_to_host(parts[2], 443 if use_tls else 80, TLSOptions.client() if use_tls else null)
|
||||
if err != OK:
|
||||
logger.warn("GIF fetch: HTTP connect failed for %s: %d" % [url.left(LOG_URL_MAX_LEN), err])
|
||||
return PackedByteArray()
|
||||
var deadline := Time.get_ticks_msec() + HTTP_TIMEOUT_MS
|
||||
while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:
|
||||
http.poll()
|
||||
if Time.get_ticks_msec() > deadline:
|
||||
http.close()
|
||||
logger.warn("GIF fetch: connect timed out")
|
||||
return PackedByteArray()
|
||||
OS.delay_msec(CONNECT_POLL_DELAY_MS)
|
||||
if http.get_status() != HTTPClient.STATUS_CONNECTED:
|
||||
logger.warn("GIF fetch: not connected (status=%d)" % http.get_status())
|
||||
http.close()
|
||||
return PackedByteArray()
|
||||
|
||||
http.request(HTTPClient.METHOD_GET, "/" + "/".join(parts.slice(3)), PackedStringArray())
|
||||
deadline = Time.get_ticks_msec() + HTTP_TIMEOUT_MS
|
||||
while http.get_status() == HTTPClient.STATUS_REQUESTING:
|
||||
http.poll()
|
||||
if Time.get_ticks_msec() > deadline:
|
||||
http.close()
|
||||
logger.warn("GIF fetch: request timed out")
|
||||
return PackedByteArray()
|
||||
OS.delay_msec(READ_POLL_DELAY_MS)
|
||||
|
||||
var body := PackedByteArray()
|
||||
while http.get_status() == HTTPClient.STATUS_BODY:
|
||||
http.poll()
|
||||
var chunk: PackedByteArray = http.read_response_body_chunk()
|
||||
if chunk.is_empty():
|
||||
if Time.get_ticks_msec() > deadline:
|
||||
http.close()
|
||||
logger.warn("GIF fetch: body read timed out")
|
||||
return PackedByteArray()
|
||||
OS.delay_msec(READ_POLL_DELAY_MS)
|
||||
continue
|
||||
body.append_array(chunk)
|
||||
http.close()
|
||||
|
||||
if body.is_empty():
|
||||
logger.warn("GIF fetch: empty response for %s" % url.left(LOG_URL_MAX_LEN))
|
||||
return body
|
||||
|
||||
|
||||
## Extracts the first frame of a GIF using ffmpeg. Returns a static ImageTexture.
|
||||
func _build_static_gif_texture(ffmpeg_bin: String, gif_path: String, png_path: String, url: String) -> Texture2D:
|
||||
var ffmpeg_args: PackedStringArray = [
|
||||
"-y", "-i", gif_path,
|
||||
"-frames:v", "1",
|
||||
|
|
@ -365,12 +449,9 @@ func _fetch_gif_first_frame(url: String, cache_flags: int) -> Texture2D:
|
|||
|
||||
if not FileAccess.file_exists(png_path):
|
||||
logger.warn("GIF fetch: ffmpeg did not produce output for %s" % url.left(LOG_URL_MAX_LEN))
|
||||
DirAccess.remove_absolute(gif_path)
|
||||
return null
|
||||
|
||||
var image := Image.load_from_file(png_path)
|
||||
# Clean up temp files.
|
||||
DirAccess.remove_absolute(gif_path)
|
||||
DirAccess.remove_absolute(png_path)
|
||||
|
||||
if image == null:
|
||||
|
|
@ -381,6 +462,124 @@ func _fetch_gif_first_frame(url: String, cache_flags: int) -> Texture2D:
|
|||
return ImageTexture.create_from_image(image)
|
||||
|
||||
|
||||
## Extracts all frames from a GIF using ffmpeg and builds an AnimatedTexture.
|
||||
## The animation is paused by default — the focus handler unpauses it.
|
||||
func _build_animated_gif_texture(ffmpeg_bin: String, gif_path: String, frames_dir: String, gif_bytes: PackedByteArray, url: String) -> AnimatedTexture:
|
||||
# Parse frame delays from the GIF binary.
|
||||
var delays: Array = _parse_gif_frame_delays(gif_bytes)
|
||||
|
||||
# Extract all frames with ffmpeg.
|
||||
DirAccess.make_dir_recursive_absolute(frames_dir)
|
||||
var ffmpeg_args: PackedStringArray = [
|
||||
"-y", "-i", gif_path,
|
||||
"-vsync", "0",
|
||||
frames_dir + "/frame_%04d.png",
|
||||
]
|
||||
var ret: Array = []
|
||||
OS.execute(ffmpeg_bin, ffmpeg_args, ret)
|
||||
|
||||
# Collect extracted frame files.
|
||||
var dir := DirAccess.open(frames_dir)
|
||||
if dir == null:
|
||||
logger.warn("GIF fetch: cannot open frames dir")
|
||||
return null
|
||||
dir.list_dir_begin()
|
||||
var frame_files: PackedStringArray = []
|
||||
var fname := dir.get_next()
|
||||
while fname != "":
|
||||
if fname.begins_with("frame_") and fname.ends_with(".png"):
|
||||
frame_files.append(fname)
|
||||
fname = dir.get_next()
|
||||
dir.list_dir_end()
|
||||
frame_files.sort()
|
||||
|
||||
if frame_files.is_empty():
|
||||
logger.warn("GIF fetch: no frames extracted for %s" % url.left(LOG_URL_MAX_LEN))
|
||||
DirAccess.remove_absolute(frames_dir)
|
||||
return null
|
||||
|
||||
# Build AnimatedTexture.
|
||||
var anim_tex := AnimatedTexture.new()
|
||||
anim_tex.frames_count = frame_files.size()
|
||||
anim_tex.pause = true # Start paused — focus handler unpauses.
|
||||
|
||||
for i in frame_files.size():
|
||||
var frame_path := frames_dir + "/" + frame_files[i]
|
||||
var image := Image.load_from_file(frame_path)
|
||||
DirAccess.remove_absolute(frame_path)
|
||||
if image == null:
|
||||
logger.warn("GIF fetch: failed to load frame %d" % i)
|
||||
continue
|
||||
anim_tex.set_frame_texture(i, ImageTexture.create_from_image(image))
|
||||
# Use parsed delay if available, otherwise default.
|
||||
var delay_ms: int = delays[i] if i < delays.size() else GIF_DEFAULT_FRAME_DELAY_MS
|
||||
anim_tex.set_frame_delay(i, delay_ms / 1000.0) # AnimatedTexture uses seconds.
|
||||
|
||||
DirAccess.remove_absolute(frames_dir)
|
||||
logger.info("GIF fetch: built AnimatedTexture with %d frames from %s" % [frame_files.size(), url.left(LOG_URL_MAX_LEN)])
|
||||
return anim_tex
|
||||
|
||||
|
||||
## Parses frame delays from a GIF89a binary. Returns an array of delays
|
||||
## in milliseconds, one per frame. Falls back to GIF_DEFAULT_FRAME_DELAY_MS
|
||||
## for frames without a Graphics Control Extension.
|
||||
func _parse_gif_frame_delays(data: PackedByteArray) -> Array:
|
||||
var delays: Array = []
|
||||
if data.size() < 13:
|
||||
return delays
|
||||
|
||||
# Skip header (6) + Logical Screen Descriptor (7).
|
||||
var pos := 13
|
||||
# Skip Global Color Table if present.
|
||||
var packed_byte: int = data[10]
|
||||
if packed_byte & 0x80 != 0:
|
||||
var gct_size := 3 * (1 << ((packed_byte & 0x07) + 1))
|
||||
pos += gct_size
|
||||
|
||||
while pos < data.size() - 1:
|
||||
var byte: int = data[pos]
|
||||
if byte == 0x21:
|
||||
# Extension block.
|
||||
var label: int = data[pos + 1]
|
||||
if label == 0xF9:
|
||||
# Graphics Control Extension — contains frame delay.
|
||||
var delay_cs: int = data[pos + 4] | (data[pos + 5] << 8) # Centiseconds.
|
||||
var delay_ms: int = delay_cs * 10 if delay_cs > 0 else GIF_DEFAULT_FRAME_DELAY_MS
|
||||
delays.append(delay_ms)
|
||||
# Skip extension block.
|
||||
pos += 2
|
||||
while pos < data.size():
|
||||
var block_size: int = data[pos]
|
||||
pos += 1
|
||||
if block_size == 0:
|
||||
break
|
||||
pos += block_size
|
||||
elif byte == 0x2C:
|
||||
# Image descriptor — skip it.
|
||||
pos += 10
|
||||
# Skip Local Color Table if present.
|
||||
var img_packed: int = data[pos - 1]
|
||||
if img_packed & 0x80 != 0:
|
||||
var lct_size := 3 * (1 << ((img_packed & 0x07) + 1))
|
||||
pos += lct_size
|
||||
# Skip LZW Minimum Code Size + sub-blocks.
|
||||
pos += 1 # LZW min code size.
|
||||
while pos < data.size():
|
||||
var block_size: int = data[pos]
|
||||
pos += 1
|
||||
if block_size == 0:
|
||||
break
|
||||
pos += block_size
|
||||
elif byte == 0x3B:
|
||||
# Trailer.
|
||||
break
|
||||
else:
|
||||
# Unknown block — skip.
|
||||
pos += 1
|
||||
|
||||
return delays
|
||||
|
||||
|
||||
## Combines two textures side-by-side into a single banner image.
|
||||
## Both images are scaled to the same height, then placed left and right.
|
||||
func _combine_side_by_side(left: Texture2D, right: Texture2D) -> Texture2D:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue