Be smarter about thumbnails

This commit is contained in:
Jan Hamal Dvořák 2025-03-13 23:42:07 +01:00
parent 1a92ded9a1
commit 9e818dab35

View file

@ -89,30 +89,36 @@ def generate_thumbnail_sync(file_item: FileItem):
if not success: if not success:
raise RuntimeError("Failed to query duration") raise RuntimeError("Failed to query duration")
# Seek to 1/3 of duration def get_sample(seek_pos: int) -> bytes:
seek_pos = duration // 3 pipeline.seek_simple(Gst.Format.TIME, DEFAULT_SEEK_FLAGS, seek_pos)
pipeline.seek_simple(Gst.Format.TIME, DEFAULT_SEEK_FLAGS, seek_pos)
# Start playing to capture frame # Start playing to capture frame
pipeline.set_state(Gst.State.PLAYING) pipeline.set_state(Gst.State.PLAYING)
sample = sink.emit("pull-sample") sample = sink.emit("pull-sample")
if not sample: if not sample:
raise RuntimeError("Failed to pull sample") raise RuntimeError("Failed to pull sample")
# Extract image data # Extract image data
buffer = sample.get_buffer() buffer = sample.get_buffer()
if not buffer: if not buffer:
raise RuntimeError("Failed to get buffer") raise RuntimeError("Failed to get buffer")
success, map_info = buffer.map(Gst.MapFlags.READ) success, map_info = buffer.map(Gst.MapFlags.READ)
if not success: if not success:
raise RuntimeError("Failed to map buffer") raise RuntimeError("Failed to map buffer")
try: try:
thumbnail = bytes(map_info.data) return bytes(map_info.data)
finally: finally:
buffer.unmap(map_info) buffer.unmap(map_info)
candidates: list[bytes] = []
for i in range(3):
candidates.append(get_sample(duration // 3 - Gst.SECOND + i * Gst.SECOND))
thumbnail = max(candidates, key=len)
def set_thumbnail(): def set_thumbnail():
file_item.thumbnail.value = thumbnail file_item.thumbnail.value = thumbnail