feat(downloads): a clip or an edit can be a GIF, shared as a picture

A clip and an editor range can come out as a silent GIF (long side
320/480/640, 12 fps, at most 30 s, one palette per GIF); one over 30 MB
is not kept. A shared picture is served inline under the preview's
sandbox, and a GIF's link card is the GIF itself up to 15 MB, the still
for Facebook's crawler.
This commit is contained in:
2026-11-11 01:50:55 +01:00
parent fe38c07e7e
commit c221452a00
24 changed files with 885 additions and 58 deletions
+67 -15
View File
@@ -16,6 +16,7 @@ from app.db import SessionLocal
from app.downloads import clip as clipmod
from app.downloads import edit as editmod
from app.downloads import errors as dlerrors
from app.downloads import gif as gifmod
from app.downloads import adapters, credentials, formats, mediakind, playable, probe, quota
from app.downloads import backfill, egress
from app.downloads import service, storage
@@ -874,7 +875,8 @@ def _process_edit(job_id: int, asset_id: int) -> None:
src_ext = src_path.suffix.lstrip(".").lower() or "mp4"
crop = editmod.has_crop(edit_spec)
out_ext = "mp4" if editmod.needs_reencode(edit_spec) else src_ext
gif = edit_spec.get("gif")
out_ext = "gif" if gif else "mp4" if editmod.needs_reencode(edit_spec) else src_ext
total_s = editmod.clip_duration(edit_spec, src_dur) or src_dur or 0
staging = _edit_staging_dir(asset_id)
@@ -885,7 +887,19 @@ def _process_edit(job_id: int, asset_id: int) -> None:
dest_staging = staging / f"out.{out_ext}"
_set_job(job_id, phase="editing", progress=0, speed_bps=None, eta_s=None)
if edit_spec.get("segments"):
if gif:
# One range with an end (the service's check), cropped first if a frame was drawn.
trim = edit_spec["trim"]
start = trim.get("start_s") or 0.0
cmd = gifmod.build_cmd(
src_path,
dest_staging,
start,
trim["end_s"] - start,
pre=editmod.crop_filter(edit_spec["crop"]) if crop else "",
side=gif["side"],
)
elif edit_spec.get("segments"):
cmd, prep = editmod.build_concat_plan(
src_path, dest_staging, edit_spec, out_ext, staging
)
@@ -901,9 +915,12 @@ def _process_edit(job_id: int, asset_id: int) -> None:
)
if not dest_staging.exists():
raise StatedFailure("ffmpeg produced no output file")
# A fast trim stream-copies the source's codecs and container, so the clip is only as
# playable as its source: hold it to the same rule as every other ready file.
dest_staging = _ensure_phone_safe(job_id, dest_staging, staging, "editing", total_s)
if gif:
_hold_gif_cap(dest_staging)
else:
# A fast trim stream-copies the source's codecs and container, so the clip is only as
# playable as its source: hold it to the same rule as every other ready file.
dest_staging = _ensure_phone_safe(job_id, dest_staging, staging, "editing", total_s)
out_ext = dest_staging.suffix.lstrip(".").lower() or out_ext
# New storage on the owner's footprint, held to what is left by its real size, as a
# download and a player clip are.
@@ -917,8 +934,12 @@ def _process_edit(job_id: int, asset_id: int) -> None:
storage.place_file(dest_staging, settings.files_root, rel)
final = storage.abs_path(settings.files_root, rel)
size = final.stat().st_size if final.exists() else None
# The clip's real frame: a re-encode evens an odd crop or source (`editmod.EVEN_FRAME`).
# The clip's real frame: a re-encode evens an odd crop or source (`editmod.EVEN_FRAME`). A
# GIF's is in its header (ffprobe reports no stream size for an image format).
_, _, out_w, out_h, _ = probe.probe_media(final)
if gif:
out_w, out_h = gifmod.size(final) or (None, None)
poster = _gif_still(rel) if gif else None
# Unsized, a crop's own size stands in, cut from the frame the filters saw.
cut = (
editmod.crop_stored_size(edit_spec["crop"], *_filter_frame(src_path, src_w, src_h))
@@ -940,6 +961,8 @@ def _process_edit(job_id: int, asset_id: int) -> None:
asset.width, asset.height = cut
else:
asset.width, asset.height = (None, None) if crop else (src_w, src_h)
if poster:
asset.poster_path = poster
asset.error = None
asset.last_access_at = datetime.now(timezone.utc)
job = db.get(DownloadJob, job_id)
@@ -1057,6 +1080,19 @@ def _clip_crop(spec: dict, data: dict) -> str:
return crop
def _hold_gif_cap(out: Path) -> None:
"""A GIF over its own size cap is not kept (`gif.MAX_BYTES`): a stated failure that names the
range and the size, the two things that make it smaller."""
if out.stat().st_size > gifmod.MAX_BYTES:
raise StatedFailure(dlerrors.GIF_TOO_BIG_MESSAGE)
def _gif_still(rel: str) -> str | None:
"""The placed GIF's still (`gif.ensure_still`), as the poster's rel path beside it."""
still = gifmod.ensure_still(storage.abs_path(settings.files_root, rel))
return str(Path(rel).with_suffix(".jpg")) if still else None
def _process_clip(job_id: int, asset_id: int) -> None:
"""Cut an ad-hoc clip (downloads/clip): fetch or open its source, ONE re-encode to the clip
shape, then into the user's library beside their edits."""
@@ -1086,27 +1122,39 @@ def _process_clip(job_id: int, asset_id: int) -> None:
raise StatedFailure("The chosen audio track is not in the file.")
crop = _clip_crop(spec, data)
total_s = clipmod.duration(spec)
out = staging / "clip.mp4"
gif = spec.get("gif")
hdr = clipmod.is_hdr(data)
out = staging / ("clip.gif" if gif else "clip.mp4")
_set_job(job_id, phase="editing", progress=0, speed_bps=None, eta_s=None)
editmod.run_ffmpeg(
clipmod.build_cmd(
cmd = (
gifmod.build_cmd(
src, out, start, total_s, pre=clipmod.gif_pre(crop, hdr), side=gif["side"]
)
if gif
else clipmod.build_cmd(
src,
out,
start,
total_s,
audio_track=audio_track,
hdr=clipmod.is_hdr(data),
hdr=hdr,
threads=editmod.encode_thread_cap(),
crop=crop,
),
)
)
editmod.run_ffmpeg(
cmd,
total_s,
on_progress=_ffmpeg_progress_writer(job_id, "editing"),
should_cancel=_cancel_poll(job_id),
)
if not out.exists():
raise StatedFailure("ffmpeg produced no output file")
# The phone-safe shape by construction; still held to the rule every ready file meets.
out = _ensure_phone_safe(job_id, out, staging, "editing", round(total_s))
if gif:
_hold_gif_cap(out)
else:
# The phone-safe shape by construction; still held to the rule every ready file meets.
out = _ensure_phone_safe(job_id, out, staging, "editing", round(total_s))
# Held to the cap by its real size: a range fetch passes yt-dlp's `max_filesize` to its
# ffmpeg downloader, which never reads it, and a Plex clip fetches nothing at all. Read
# again, since other jobs of this owner may have landed during the encode.
@@ -1118,6 +1166,8 @@ def _process_clip(job_id: int, asset_id: int) -> None:
storage.place_file(out, settings.files_root, rel)
final = storage.abs_path(settings.files_root, rel)
vcodec, acodec, width, height, _ = probe.probe_media(final)
if gif:
width, height = gifmod.size(final) or (None, None)
with SessionLocal() as db:
asset = db.get(MediaAsset, asset_id)
@@ -1135,8 +1185,10 @@ def _process_clip(job_id: int, asset_id: int) -> None:
asset.duration_s = round(total_s)
asset.media_kind = mediakind.derive(vcodec, acodec)
# The clip's own frame as its poster: the link preview shows the moment, and a Plex
# item has no public thumbnail at all.
asset.poster_path = editmod.ensure_poster(asset, settings.files_root)
# item has no public thumbnail at all. A GIF's is its first frame, cut from the GIF.
asset.poster_path = (
_gif_still(rel) if gif else editmod.ensure_poster(asset, settings.files_root)
)
asset.error = None
asset.last_access_at = datetime.now(timezone.utc)
fields: dict = {"status": JobStatus.DONE, "progress": 100, "phase": None}