Files
privatestudio/privatestudio/studio/routers/transcode.py
T
Shaun KrugerandClaude Opus 5.5 73b549cb18
Build and publish / cleanup (pull_request) Successful in 17s
Build and publish / test (pull_request) Skipped
Build and publish / build (pull_request) Skipped
Build and publish / pypi (pull_request) Skipped
Add transcode/packaging worker, job slugs, deletes and zip downloads
Worker:
- manage.py run_worker polls the database for pending transcode jobs (ffmpeg)
  and packaging jobs (Bento4 mp4fragment + mp4hls). Jobs are claimed with a
  conditional UPDATE, a heartbeat thread marks progress, stale jobs are failed,
  and SIGTERM returns an interrupted job to the queue.
- SQLite runs in WAL mode with IMMEDIATE transactions and a busy timeout so the
  web server and worker can share the database.
- transcode.py exposes a reusable transcode() and the HW->CPU fallback works.
- Docker image includes ffmpeg and a checksum-verified Bento4 SDK.

Jobs and storage:
- TranscodeJob and PackagingJob have slugs, set explicitly on creation; outputs
  go to transcodes/<slug>/ and packages/<slug>/hls/. Migrations regenerated.
- Uploads into transcodes/ and packages/ are refused; the uploader defaults to
  the videos/raw folder.

UI:
- New packaging job button on transcode jobs.
- Delete views for packaging jobs, transcode jobs, uploaded files and content
  entries, each removing files before records and refusing while referenced.
  TranscodeJob.asset is now SET_NULL so deleting a source keeps its jobs.
- Streamed zip downloads for completed transcode jobs and packages, rooted at
  the job slug; the content page lists packages with download buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 16:34:44 -07:00

108 lines
3.8 KiB
Python

"""YAML-based transcode job request endpoints (scoped to a studio)."""
from typing import Optional
import yaml
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from ninja import Router, Schema
from ninja.errors import HttpError
from privatestudio.studio.models import JobStatus, TranscodeJob, TranscodeProfile, UploadedAsset
from privatestudio.studio.profiles import validate_profile_definition
from privatestudio.studio.routers.common import get_studio_for_user, parse_yaml_body
router = Router()
class TranscodeJobResponse(Schema):
id: int
asset_id: Optional[int]
profile_id: Optional[int]
status: str
requested_at: str
def _job_response(job: TranscodeJob) -> dict:
return {
"id": job.id,
"asset_id": job.asset_id,
"profile_id": job.profile_id,
"status": job.status,
"requested_at": job.requested_at.isoformat(),
}
@router.post("/studios/{bucket}/transcode", response=TranscodeJobResponse)
def request_transcode(request, bucket: str):
"""
Request a transcode job with a YAML definition in the request body.
```yaml
asset: "video.mp4" # Asset key, filename or ID
profile: "hd-profile" # Profile name, or an inline profile definition
```
"""
studio = get_studio_for_user(request.auth, bucket)
request_data = parse_yaml_body(request)
asset_ref = request_data.get("asset")
if not asset_ref:
raise HttpError(400, "Request must specify 'asset'")
assets = UploadedAsset.objects.filter(studio=studio)
if isinstance(asset_ref, int):
asset = assets.filter(pk=asset_ref).first()
else:
asset_ref = str(asset_ref)
asset = assets.filter(s3_path=asset_ref).first() or assets.filter(filename=asset_ref).first()
if asset is None:
raise HttpError(404, f"Asset '{asset_ref}' not found")
profile_ref = request_data.get("profile")
if not profile_ref:
raise HttpError(400, "Request must specify 'profile'")
profile = None
if isinstance(profile_ref, str):
profile = TranscodeProfile.objects.filter(studio=studio, name=profile_ref).first()
if profile is None:
raise HttpError(404, f"Profile '{profile_ref}' not found")
profile_definition = profile.profile_definition
elif isinstance(profile_ref, dict):
profile_definition = yaml.safe_dump(profile_ref)
try:
validate_profile_definition(profile_definition)
except ValidationError as e:
raise HttpError(400, "Invalid inline profile: " + " ".join(e.messages))
else:
raise HttpError(400, "Profile must be a string (name) or object (definition)")
job = TranscodeJob.objects.create(
slug=TranscodeJob.get_random_slug(),
studio=studio,
requested_by=request.auth,
asset=asset,
profile=profile,
profile_definition=profile_definition,
# API requests are submitted directly; drafts are only made in the web UI.
status=JobStatus.PENDING,
)
return _job_response(job)
@router.get("/studios/{bucket}/transcode/{job_id}", response=TranscodeJobResponse)
def get_transcode_job(request, bucket: str, job_id: int):
"""Get the status of a transcode job."""
studio = get_studio_for_user(request.auth, bucket)
return _job_response(get_object_or_404(TranscodeJob, pk=job_id, studio=studio))
@router.get("/studios/{bucket}/transcode", response=list[TranscodeJobResponse])
def list_transcode_jobs(request, bucket: str, status: Optional[str] = None):
"""List transcode jobs for the studio."""
studio = get_studio_for_user(request.auth, bucket)
jobs = studio.transcode_jobs.order_by("id")
if status:
jobs = jobs.filter(status=status)
return [_job_response(job) for job in jobs]