media

package
v0.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package media stores host content files in per-item folders of one private bucket: library-built keys, the generic manifest with conditional-write edits, and the Store port. See media/s3 for the S3 implementation and media/token for access tokens.

Index

Constants

View Source
const (
	HLSContentType = "application/vnd.apple.mpegurl"
	VTTContentType = "text/vtt; charset=utf-8"
)

Playlist content types.

View Source
const (
	IngestPartSize    = 32 << 20
	IngestConcurrency = 3
)

Ingest defaults: parts are buffered in memory, so memory is about (IngestConcurrency+1) × IngestPartSize.

View Source
const (
	AreaManifest  = layout.AreaManifest
	AreaOriginals = layout.AreaOriginals
	AreaBlobs     = layout.AreaBlobs
	AreaPublic    = layout.AreaPublic
)

Folder areas.

View Source
const (
	DefaultMinAspect = 1 / 2.4
	DefaultMaxAspect = 2.4
)

Default aspect bounds: 1:2.4 vertical to 2.4:1 wide, which admits "21:9" content (2560×1080 at 2.37, 2.39:1 cinema) and its vertical equivalents.

View Source
const (
	AccessFull    = "full"    // every file; downloads
	AccessPreview = "preview" // files [0, preview_limit) plus teasers
	AccessNone    = "none"    // teasers only
)

Access levels in ReadResult.

View Source
const (
	MaxSinglePut = 64 << 20
	MinPartSize  = 8 << 20
	MaxPartSize  = 16 << 20
)

Upload size rules. Files up to MaxSinglePut are one checksum-bound PUT to originals/sha256-{hex}; larger ones are multipart to originals/u-{uuid} with parts of MinPartSize growing up to MaxPartSize (the last part may be smaller).

View Source
const (
	OpInsert  = "insert"  // add Name at Index (default: append); a retry with the same Original is a no-op
	OpReplace = "replace" // swap Name's original; variants are regenerated, a stale hls plays until re-encoded
	OpMove    = "move"    // move Name to Index
	OpRename  = "rename"  // rename Name to To
	OpRemove  = "remove"  // drop Name
	OpEdit    = "edit"    // set Name's Edit (an image); nil clears it. Its variants are regenerated
)

Commit operations. Insert and Replace take an uploaded Original.

View Source
const (
	CodeInvalid      = "invalid_request"   // 400
	CodeForbidden    = "forbidden"         // 403
	CodeNotFound     = "not_found"         // 404: unknown kind, file or upload
	CodeConflict     = "conflict"          // 409: file name taken
	CodeIncomplete   = "incomplete"        // 409: multipart parts missing
	CodeNotUploaded  = "not_uploaded"      // 409: commit before the object landed
	CodeTooManyFiles = "too_many_files"    // 409: the commit would exceed the kind's file caps
	CodeTooLarge     = "too_large"         // 413: over the kind's cap
	CodeQuota        = "quota_exceeded"    // 413: owner quota
	CodeType         = "type_not_allowed"  // 415
	CodeChecksum     = "checksum_mismatch" // 422: stored bytes differ from the declared hash
	CodeRate         = "rate_limited"      // 429
)

Stable upload error codes: clients (the browser SDK) branch on Code.

View Source
const (
	PosterSlot   = "poster"
	HoverPreview = "hover_preview"
)

Video kinds carry two public images besides the HLS sprite: the poster slot and a hover preview, a short silent loop. Both are item-level.

View Source
const (
	HoverPreviewDefault = 3.0
	HoverPreviewMin     = 1.0
	HoverPreviewMax     = 6.0
)

Hover preview bounds (seconds) and output widths. The smallest width is always rendered, so listings can link it without a read; wider ones only when the video is at least that wide.

View Source
const (
	FrameDefaultWidth = 320
	FrameMaxWidth     = 1280
)

Frame endpoint bounds.

View Source
const (
	PosterSourceFrame  = "frame"
	PosterSourceUpload = "upload"
	PosterSourceAuto   = "auto"
)

Poster sources.

View Source
const CookieName = token.CookieName

CookieName is the access worker's cookie.

View Source
const DefaultQueue = "contentkit_media"

DefaultQueue is JobsConfig.Queue's default.

View Source
const SlotVersionParam = layout.VersionParam

SlotVersionParam is the query parameter carrying an output's version.

View Source
const UserKind = "user"

UserKind is the kind of per-user folders ({tenant}/user/{id}/), erased by EraseUserTx.

Variables

View Source
var (
	ErrUnknownKind = errors.New("media: unknown kind")
	ErrType        = errors.New("media: content type not allowed")
	ErrTooLarge    = errors.New("media: file too large")
)
View Source
var (
	// ErrNotVisible hides an item the viewer may not see, or that does not exist.
	ErrNotVisible = errors.New("media: not found")
	// ErrResolve wraps a resolver failure; it always denies.
	ErrResolve = errors.New("media: resolve failed")
	// ErrInvalidRequest is a malformed read request.
	ErrInvalidRequest = errors.New("media: invalid request")
)
View Source
var (
	ErrNotFound           = errors.New("media: object not found")
	ErrPreconditionFailed = errors.New("media: precondition failed")
	ErrNotModified        = errors.New("media: not modified")
)
View Source
var DefaultLadder = []int{2160, 1440, 1080, 720, 480}

DefaultLadder is the default H.264 ladder by short side.

View Source
var ErrJobsNotBound = errors.New("media: River jobs are not composed into a client")
View Source
var ErrManifestConflict = errors.New("media: manifest edit kept conflicting")
View Source
var ErrNotAllowed = errors.New("media: not allowed")

ErrNotAllowed is a URL request for a file the viewer may not have, or a blob that file does not reference.

View Source
var ErrSuperseded = errors.New("media: record changed")

ErrSuperseded reports a record that changed while a job worked from it; the job for the newer record does the work instead.

View Source
var HoverPreviewWidths = []int{320, 640}
View Source
var VideoPoster = Slot{Aspect: 16.0 / 9, Widths: []int{480, 960, 1920}}

VideoPoster is the poster slot every video kind gets. Its original is an uploaded image or a frame the video worker grabbed; the image job encodes either through the slot's Edit.

Functions

func AutoHoverPreview added in v0.26.0

func AutoHoverPreview(duration float64) (start, length float64)

AutoHoverPreview is the default section: HoverPreviewDefault seconds from a quarter in, inside the video.

func Encoded added in v0.26.0

func Encoded(f File) bool

Encoded reports a video file whose current source has an HLS ladder.

func HoverPreviewVersion added in v0.26.0

func HoverPreviewVersion(key, source, recipe string) string

HoverPreviewVersion is the URL version of a render.

func NewInlineName added in v0.17.0

func NewInlineName() string

NewInlineName names a new inline image: "i-{uuid}".

func NewUploadName

func NewUploadName() string

NewUploadName names a multipart upload whose hash is unknown: "u-{uuid}".

func SHA256Name

func SHA256Name(sum []byte) string

SHA256Name names content-addressed files: "sha256-{hex}".

func SlotOutput added in v0.20.0

func SlotOutput(slot string, width int) string

SlotOutput names a slot's output of one width: "{slot}_{width}".

func UploadHandler

func UploadHandler(u *Uploads, o UploadHandlerOptions) http.Handler

UploadHandler serves the upload API the browser SDK calls. All routes are POST with JSON bodies; SHA-256 values are lowercase hex. Errors are ErrorReply with the status of its code (Retry-After on 429).

POST /presign      PresignBody  -> PresignReply
POST /parts        PartsBody    -> PartsReply     presign multipart parts
POST /parts/list   TicketBody   -> PartsReply     parts that landed (resume)
POST /complete     TicketBody   -> CompleteReply
POST /abort        TicketBody   -> 204
POST /commit       CommitBody   -> CommitReply
POST /commit-slot            SlotBody         -> SlotManifest (204 for an inline image)
POST /commit-slot-from-file  SlotFromFileBody -> SlotManifest
POST /edit-slot              SlotEditBody     -> SlotManifest   re-edit the committed original
POST /slot                   SlotRefBody      -> SlotManifest
POST /slot-original          SlotRefBody      -> the committed original's bytes (editor)
POST /video-images   VideoImagesBody  -> VideoImages   poster + hover preview, with selections
POST /video-poster   VideoPosterBody  -> VideoImages
POST /video-preview  VideoPreviewBody -> VideoImages
GET  /frame?kind=&id=&version=&file=&t=&w= -> image/jpeg   poster picker frame (UploadOptions.Frames)

Types

type AudioTrack

type AudioTrack struct {
	ID        string    `json:"id"`
	Lang      string    `json:"lang,omitempty"`
	Label     string    `json:"label,omitempty"`
	Default   bool      `json:"default,omitempty"`
	Bandwidth int       `json:"bandwidth,omitempty"`
	Codecs    string    `json:"codecs,omitempty"`
	Blob      string    `json:"blob"`
	Segments  []Segment `json:"segments"`
}

type Capabilities

type Capabilities struct {
	ConditionalPut bool // If-Match / If-None-Match on PUT
	ChecksumSHA256 bool // x-amz-checksum-sha256 enforced on PUT
}

Capabilities are backend features the library depends on, established by Probe.

func Probe

func Probe(ctx context.Context, s Store, prefix string) (Capabilities, error)

Probe measures the backend's capabilities with scratch objects under prefix, which it removes. Results depend on the backend release (RGW vs MinIO).

type CommitBody

type CommitBody struct {
	Ref RefBody `json:"ref"`
	Ops []Op    `json:"ops"`
}

type CommitFile

type CommitFile struct {
	Name     string         `json:"name"`
	Original string         `json:"original"`
	Type     string         `json:"type,omitempty"`
	Size     int64          `json:"size,omitempty"`
	Edit     *Edit          `json:"edit,omitempty"`
	Meta     map[string]any `json:"meta,omitempty"`
}

type CommitReply

type CommitReply struct {
	Files []CommitFile `json:"files"`
}

CommitReply is the committed file order.

type CompleteReply

type CompleteReply struct {
	Name string `json:"name"`
	Type string `json:"type"`
	Size int64  `json:"size"`
}

type Crop added in v0.17.0

type Crop struct {
	X int `json:"x"`
	Y int `json:"y"`
	W int `json:"w"`
	H int `json:"h"`
}

Crop is a rectangle in source pixels.

type Deletion

type Deletion struct {
	Ref   contentref.ContentRef
	Owner string
}

Deletion is one item to delete. Owner is its quota owner (UploadGrant.Owner), "" for none; with a Limiter configured the owner's usage is released.

type Delivery

type Delivery struct {
	Mode DeliveryMode
	// BaseURL is the access worker origin for this site, e.g.
	// "https://media.doujins.com".
	BaseURL string
	// CookieDomain is the site's registrable domain, e.g. "doujins.com";
	// required in cookie mode, because a host-only cookie never reaches media.
	CookieDomain string
	// SigningKey is the current key of the ring the access worker verifies.
	SigningKey token.Key
	// TTL is the minimum token lifetime (default 1h); expiries round up to
	// Window (default token.DefaultWindow).
	TTL    time.Duration
	Window time.Duration
}

Delivery is the host's per-site delivery configuration.

type DeliveryMode

type DeliveryMode string

DeliveryMode is how viewers with full access present their token.

const (
	// DeliverCookie (default) returns plain URLs plus a folder cookie scoped to
	// the item's blobs/, so browsers cache immutable blobs normally.
	DeliverCookie DeliveryMode = "cookie"
	// DeliverURL appends ?t= to every URL: apps and clients without cookies.
	DeliverURL DeliveryMode = "url"
)

type Dims added in v0.17.0

type Dims struct {
	W int `json:"w"`
	H int `json:"h"`
}

Dims is a source's size with EXIF orientation applied.

func HoverPreviewSizes added in v0.26.0

func HoverPreviewSizes(w, h int) []Dims

HoverPreviewSizes are the output sizes for a w×h video: the centred 16:9 crop, never upscaled beyond the smallest width.

func PosterFrameSize added in v0.26.0

func PosterFrameSize(w, h int) Dims

PosterFrameSize is the size of a grabbed poster frame from a w×h rendition: as is, or upscaled until its centred 16:9 crop reaches VideoPoster.Min(), so every poster has its smallest width. Poster edits are in these pixels.

type Download

type Download struct {
	Blob   string `json:"blob"`
	Type   string `json:"type,omitempty"`
	Size   int64  `json:"size,omitempty"`
	Spec   string `json:"spec,omitempty"`
	Inputs string `json:"inputs,omitempty"` // hash of the ordered input blobs
}

type DownloadInfo

type DownloadInfo struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	Type string `json:"type,omitempty"`
	Size int64  `json:"size,omitempty"`
	URL  string `json:"url"`
}

type Edit added in v0.17.0

type Edit struct {
	Crop   *Crop `json:"crop,omitempty"`
	Rotate int   `json:"rotate,omitempty"` // clockwise degrees: 0, 90, 180 or 270
}

Edit is a non-destructive image edit: Crop, in the source's pixels (EXIF orientation applied), then a clockwise Rotate. Variants derive from the source through it; the source is never modified.

func (*Edit) Check added in v0.17.0

func (e *Edit) Check(w, h int) error

Check validates the edit's shape and, with a known size (w, h > 0), that the crop lies inside it.

func (*Edit) Hash added in v0.17.0

func (e *Edit) Hash() string

Hash is the edit's stable identity; "" for no edit.

func (*Edit) Normalize added in v0.17.0

func (e *Edit) Normalize() *Edit

Normalize returns nil for an identity edit, else a copy.

func (*Edit) Size added in v0.17.0

func (e *Edit) Size(w, h int) (int, int)

Size is the edited size of a w×h source.

type ErrorReply

type ErrorReply struct {
	Error      string   `json:"error"`
	Code       string   `json:"code"`
	RetryAfter int      `json:"retry_after,omitempty"` // seconds, with 429
	Originals  []string `json:"originals,omitempty"`   // not_uploaded at commit: the originals to upload again
}

ErrorReply is the error body; Code is one of the media Code* constants, "unauthorized" or "internal_error".

type File

type File struct {
	Name     string             `json:"name"`
	Original string             `json:"original"`
	Master   string             `json:"master,omitempty"`
	Type     string             `json:"type,omitempty"`
	Size     int64              `json:"size,omitempty"`
	Edit     *Edit              `json:"edit,omitempty"`
	Dims     *Dims              `json:"dims,omitempty"`
	Meta     map[string]any     `json:"meta,omitempty"`
	Variants map[string]Variant `json:"variants,omitempty"`
	HLS      *HLS               `json:"hls,omitempty"`
}

File is one manifest entry. Original and Master live in originals/; variants, HLS and downloads in blobs/. Image variants derive from Source() through Edit; Dims is Source()'s size, recorded by processing, and edits are validated against it. meta w/h is the edited size.

func VideoFile added in v0.26.0

func VideoFile(m *Manifest, name string) (File, bool)

VideoFile is the named file when it is a video, or with name "" the first video file.

func (File) Source

func (f File) Source() string

Source is the file variants derive from: Master when present, else Original.

func (File) Teaser

func (f File) Teaser() bool

Teaser reports meta.teaser, a file served to any viewer who can see the item.

type FileInfo

type FileInfo struct {
	Index    int     `json:"index"`
	Name     string  `json:"name,omitempty"`
	Type     string  `json:"type,omitempty"`
	Width    int     `json:"w,omitempty"`
	Height   int     `json:"h,omitempty"`
	Duration float64 `json:"duration,omitempty"`
	Edit     *Edit   `json:"edit,omitempty"` // editors only: with Dims, what re-cropping needs
	Dims     *Dims   `json:"dims,omitempty"` // editors only: the source's size; w/h is the edited size
	Teaser   bool    `json:"teaser,omitempty"`
	Locked   bool    `json:"locked,omitempty"`
	HLS      bool    `json:"hls,omitempty"`
	Failed   string  `json:"failed,omitempty"` // editors only: why the video cannot be encoded
	Variant  string  `json:"variant,omitempty"`
	URL      string  `json:"url,omitempty"`
}

type Fit

type Fit string

Fit is how an image spec fits its box.

const (
	FitInside Fit = "inside"
	FitCover  Fit = "cover"
)

type FrameGrabber added in v0.26.0

type FrameGrabber interface {
	Frame(ctx context.Context, item Item, f File, t float64, width int) ([]byte, error)
}

FrameGrabber renders a small JPEG of an encoded video file's frame for the poster picker (media/video.Frames).

type GetOptions

type GetOptions struct {
	IfNoneMatch string
	Range       string
}

GetOptions: IfNoneMatch returns ErrNotModified on a match; Range is an HTTP Range value.

type Grant

type Grant struct {
	Item       Item
	Resolution access.Resolution
	Manifest   *Manifest
	Expires    time.Time
	// contains filtered or unexported fields
}

Grant is one viewer's resolved access to one item or version: the read API and HLS playlists sign every URL through it.

func (*Grant) Allowed

func (g *Grant) Allowed(i int) bool

Allowed reports whether file i is served to this viewer: within the preview cut, or a teaser of a visible item.

func (*Grant) AudioPlaylist

func (g *Grant) AudioPlaylist(file, id string) ([]byte, error)

AudioPlaylist is the byte-range media playlist of one audio track.

func (*Grant) Cookie

func (g *Grant) Cookie() *http.Cookie

Cookie is the folder cookie to set in cookie mode with full access, else nil.

func (*Grant) DownloadURL

func (g *Grant) DownloadURL(ctx context.Context, key string) (name, u string, err error)

DownloadURL signs a manifest download under its display name; full access only, and always a URL token because the worker must see the signed dl=.

func (*Grant) Editor added in v0.19.0

func (g *Grant) Editor() bool

Editor reports an editor's grant: EditorOnly variants are signed.

func (*Grant) Full

func (g *Grant) Full() bool

Full reports full access: one folder token covers every blob.

func (*Grant) MasterPlaylist

func (g *Grant) MasterPlaylist(file string, o MasterOptions) ([]byte, error)

MasterPlaylist is the multivariant playlist of file: one variant per video rendition, with alternative audio and subtitle groups.

func (*Grant) SpriteVTT

func (g *Grant) SpriteVTT(file string) ([]byte, error)

SpriteVTT is the seek-preview track: one cue per sprite tile, each pointing at its tile with a #xywh fragment.

func (*Grant) SubtitlePlaylist

func (g *Grant) SubtitlePlaylist(file, id string) ([]byte, error)

SubtitlePlaylist is a one-segment playlist over the whole WebVTT blob.

func (*Grant) URL

func (g *Grant) URL(i int, blob string) (string, error)

URL signs blob of file i: plain in cookie mode with full access, the folder token in URL mode, else a token for exactly that key.

func (*Grant) VideoPlaylist

func (g *Grant) VideoPlaylist(file string, rung int) ([]byte, error)

VideoPlaylist is the byte-range media playlist of one video rung.

type HLS

type HLS struct {
	Source string       `json:"source"`
	Spec   string       `json:"spec,omitempty"`
	Error  string       `json:"error,omitempty"`
	Video  []Rendition  `json:"video,omitempty"`
	Audio  []AudioTrack `json:"audio,omitempty"`
	Subs   []Subtitle   `json:"subs,omitempty"`
	Sprite *Sprite      `json:"sprite,omitempty"`
}

HLS is a byte-range ladder: each rendition is one fMP4 blob. Source is the original it was encoded from; when it differs from the file's, the ladder is stale but still served until its replacement is promoted. Error, with no renditions, records why Source can never be encoded.

type HandlerOptions

type HandlerOptions struct {
	Tenant   string
	Identity Identity
	Logger   *slog.Logger
}

HandlerOptions scope the read API to one tenant.

type Hooks

type Hooks struct {
	// DownloadName returns the display name a download is saved under, e.g.
	// "[Artist] Title (English).zip". Default: "{content_id}-{key}{ext}".
	DownloadName func(ctx context.Context, ref contentref.ContentRef, key string, d Download) (string, error)
	// Failed reports a file a processor cannot derive (an undecodable image,
	// say); file is the manifest file name, or the slot name. The job does not
	// retry it; a new commit does.
	Failed func(ctx context.Context, ref contentref.ContentRef, file string, err error)
	// SlotEncoded reports a slot's new outputs as the stamp a host stores
	// (one value per slot) and passes to Reader.SlotOutputs for listings.
	SlotEncoded func(ctx context.Context, ref contentref.ContentRef, slot string, stamp SlotStamp)
}

Hooks are optional host callbacks.

type HoverPreviewManifest added in v0.26.0

type HoverPreviewManifest struct {
	Selection *HoverPreviewSelection `json:"selection,omitempty"`
	Version   string                 `json:"version,omitempty"`
	MP4       []PreviewImage         `json:"mp4"`
	WebP      []PreviewImage         `json:"webp"`
	Pending   bool                   `json:"pending"`
}

HoverPreviewManifest lists the rendered loops by ascending width, at URLs versioned like slot outputs: MP4 (H.264, 2-3× smaller) and animated WebP.

type HoverPreviewRecord added in v0.26.0

type HoverPreviewRecord struct {
	Version  string              `json:"version,omitempty"`
	File     string              `json:"file"`
	Start    float64             `json:"start"`
	Duration float64             `json:"duration"`
	Auto     bool                `json:"auto,omitempty"`
	Result   *HoverPreviewResult `json:"result,omitempty"`
}

HoverPreviewRecord is originals/hover_preview.json: the selected section and the last render.

func (HoverPreviewRecord) Key added in v0.26.0

func (r HoverPreviewRecord) Key() string

Key identifies the selection a result was rendered for.

type HoverPreviewResult added in v0.26.0

type HoverPreviewResult struct {
	Of      string `json:"of"`      // HoverPreviewRecord.Key
	Source  string `json:"source"`  // the file's original
	Recipe  string `json:"recipe"`  // the renderer's identity
	Version string `json:"version"` // URL version (?v=) the outputs carry
	Outputs []Dims `json:"outputs"`
}

HoverPreviewResult is what the served outputs were rendered from.

type HoverPreviewSelection added in v0.26.0

type HoverPreviewSelection struct {
	Version  string  `json:"version,omitempty"`
	File     string  `json:"file"`
	Start    float64 `json:"start"`
	Duration float64 `json:"duration"`
	Auto     bool    `json:"auto,omitempty"`
}

type Identity

type Identity interface {
	Actor(ctx context.Context) (access.Actor, bool)
}

Identity reads the authenticated actor the host's middleware put in the context; the same shape as content.Identity.

type IngestRequest added in v0.18.0

type IngestRequest struct {
	Ref  contentref.ContentRef
	Name string
	Type string
	Body io.Reader // read once, sequentially
	Size int64     // expected size, checked when > 0; required when the actor is rate- or quota-limited
	Op   string    // OpInsert (default) or OpReplace
	Meta map[string]any

	// Resume continues a multipart upload a previous Ingest left behind:
	// parts already stored with the same bytes are not uploaded again (the
	// body is still read and hashed). An unknown upload starts afresh.
	Resume *IngestUpload
	// OnUpload receives the multipart upload once created, for the host to
	// persist for Resume. With it set a failed Ingest keeps the upload (the
	// bucket's abort-incomplete rule removes it after a day); without it the
	// upload is aborted.
	OnUpload func(IngestUpload) error

	PartSize    int64 // default IngestPartSize; at least 5 MiB
	Concurrency int   // parallel part uploads; default IngestConcurrency
}

IngestRequest streams one file of unknown or huge size from the host (a server-side import, not a browser upload) into Ref's originals and commits it as Name.

type IngestResult added in v0.18.0

type IngestResult struct {
	Original string
	Size     int64
	SHA256   []byte // of the whole file
	Manifest *Manifest
}

IngestResult is the committed original.

type IngestUpload added in v0.18.0

type IngestUpload struct {
	Original string `json:"original"` // u-{uuid}
	UploadID string `json:"upload_id"`
}

IngestUpload identifies an in-progress multipart ingest.

type Item

type Item struct {
	// contains filtered or unexported fields
}

Item is a validated content item and the keys of its folder:

{tenant}/{kind}/{content_id}/manifest.json | manifests/{version}.json
                            /originals/{sha256-hex | u-uuid | slot | slot.json | i-uuid}
                            /blobs/{sha256-hex | u-uuid}
                            /public/{output}.webp

func (Item) Blob

func (i Item) Blob(name string) (string, error)

Blob is the key of a served, immutable derivative.

func (Item) BlobsPrefix

func (i Item) BlobsPrefix() string

func (Item) HoverPreviewOutput added in v0.26.0

func (i Item) HoverPreviewOutput(width int, mp4 bool) string

HoverPreviewOutput is public/hover_preview_{width}.webp or .mp4.

func (Item) HoverPreviewRecord added in v0.26.0

func (i Item) HoverPreviewRecord() string

HoverPreviewRecord is originals/hover_preview.json.

func (Item) Inline added in v0.20.0

func (i Item) Inline(name string) bool

Inline reports whether name is an inline image id the kind accepts.

func (Item) Kind

func (i Item) Kind() Kind

func (Item) ManifestKey

func (i Item) ManifestKey() (string, error)

ManifestKey is manifest.json, or manifests/{version}.json for versioned kinds.

func (Item) ManifestsPrefix

func (i Item) ManifestsPrefix() string

ManifestsPrefix lists every manifest of a versioned kind.

func (Item) Original

func (i Item) Original(name string) (string, error)

Original is the key of an uploaded file or master (never served).

func (Item) OriginalsPrefix

func (i Item) OriginalsPrefix() string

func (Item) Prefix

func (i Item) Prefix() string

Prefix is the folder, "{tenant}/{kind}/{id}/"; versions share it.

func (Item) Public

func (i Item) Public(name string) (string, error)

Public is public/{name}.webp: a slot output or a host-chosen inline image id.

func (Item) PublicPrefix

func (i Item) PublicPrefix() string

func (Item) Ref

func (i Item) Ref() contentref.ContentRef

func (Item) SlotOriginal

func (i Item) SlotOriginal(slot string) (string, error)

SlotOriginal is the original of a registered public slot, overwritten in place, or of an inline image.

func (Item) SlotOutput added in v0.20.0

func (i Item) SlotOutput(slot string, width int) (string, error)

SlotOutput is public/{slot}_{width}.webp.

func (Item) SlotRecord added in v0.20.0

func (i Item) SlotRecord(slot string) (string, error)

SlotRecord is originals/{slot}.json, a registered slot's record (SlotRecord).

type Jobs

type Jobs struct {
	// contains filtered or unexported fields
}

Jobs is media's River contribution: sweep, folder deletion, and the workers other media packages register. Compose RiverJobs once into the host client.

func NewJobs

func NewJobs(cfg JobsConfig) (*Jobs, error)

func (*Jobs) AddProcessor

func (j *Jobs) AddProcessor(p Processor) error

AddProcessor registers a processor for Enqueue'd jobs, before composition.

func (*Jobs) DeleteItemsTx

func (j *Jobs) DeleteItemsTx(ctx context.Context, tx pgx.Tx, items ...Deletion) error

DeleteItemsTx deletes each item's whole folder (every version) through a job enqueued in the host's delete transaction. A second pass after LateUploadWindow removes uploads that land after the first. The quota to release is measured here from the item's manifests, so a retried job settles it once.

func (*Jobs) Enqueue

func (j *Jobs) Enqueue(ctx context.Context, job ProcessJob) error

Enqueue implements ProcessQueue: one pending job per ref and slot, run by every registered processor.

func (*Jobs) EraseUserTx

func (j *Jobs) EraseUserTx(ctx context.Context, tx pgx.Tx, tenant, userID string, items ...Deletion) error

EraseUserTx erases a user's media: the items the host maps to them plus their user folder, {tenant}/user/{id}/.

func (*Jobs) Insert

Insert enqueues a job on the bound client; an empty queue means Queue().

func (*Jobs) InsertTx

func (j *Jobs) InsertTx(ctx context.Context, tx pgx.Tx, args river.JobArgs, o *river.InsertOpts) (*rivertype.JobInsertResult, error)

InsertTx enqueues a job in the host's transaction.

func (*Jobs) Queue

func (j *Jobs) Queue() string

Queue is the shared media queue; registered workers may use it or add their own.

func (*Jobs) Register

func (j *Jobs) Register(fn func(*river.Config) error) error

Register adds workers, queues or periodic jobs to the contribution. Media packages (image variants, video) call it before RiverJobs is composed.

func (*Jobs) RiverJobs

func (j *Jobs) RiverJobs() riverhelpers.Contribution

RiverJobs contributes media's workers, queue and periodic sweep to the host's helpers/river composition. It composes once.

func (*Jobs) ScheduleSweep

func (j *Jobs) ScheduleSweep(ctx context.Context, ref contentref.ContentRef) error

ScheduleSweep sweeps the item's folder after the grace period; a sweep already waiting for the folder absorbs it. Manifests calls it on every edit.

func (*Jobs) Sweep

func (j *Jobs) Sweep(ctx context.Context, ref contentref.ContentRef) (SweepResult, error)

Sweep deletes the item folder's blobs/ and hash-named originals/ that no manifest in the folder references, once every manifest is older than the grace period, and only objects past abandonedAt. Slot originals, public/ and manifests are never swept.

Invariant: the sweep deletes only objects that no manifest references and that no in-flight commit can newly reference. Uploads keeps the second half: presign reuses an existing original, and a commit accepts one, only while it is referenced or well before abandonedAt (see protected).

func (*Jobs) SweepAll

func (j *Jobs) SweepAll(ctx context.Context) error

SweepAll sweeps every folder of the configured tenants whose kind is registered: the periodic backstop for missed schedules and abandoned uploads.

type JobsConfig

type JobsConfig struct {
	Store Store
	Kinds *Registry
	// Tenants are the folders the periodic sweep pass covers; folders of
	// kinds missing from Kinds are skipped.
	Tenants []string
	// Grace protects in-flight uploads, jobs and mid-stream viewers: a folder
	// is swept only when its manifests are this old, and only objects this old
	// are deleted. Default 24 h.
	Grace time.Duration
	// SweepInterval is the periodic pass interval. Default 24 h.
	SweepInterval time.Duration
	// LateUploadWindow delays the second pass of a folder deletion, which
	// removes PUTs and multipart completions that land after the first. It
	// must exceed the longest upload presign TTL and the 1-day multipart
	// abort rule. Default 25 h.
	LateUploadWindow time.Duration
	Limiter          UploadLimiter // releases a deleted item's quota; optional
	Queue            string        // default "contentkit_media"
	MaxWorkers       int           // default 2
	Logger           *slog.Logger
	Now              func() time.Time // clock for grace decisions; default time.Now
}

JobsConfig configures media's River jobs.

type Kind

type Kind struct {
	Name      string
	Versioned bool // manifests live at manifests/{version_id}.json
	// Types are the accepted content types (empty: any); image processing
	// also requires the bytes to be the declared format.
	Types    []string
	MaxBytes int64
	// MaxFiles caps a manifest's files; 0 is unlimited.
	MaxFiles int
	// TypeLimits are caps per top-level type ("image", "video"): a set
	// MaxBytes replaces the kind's for that type, and MaxFiles caps that
	// type's files. A kind may mix images (Specs) and videos (Video).
	TypeLimits map[string]Limit
	Specs      map[string]Spec // variant name → spec
	Slots      map[string]Slot // public slot name → outputs
	// Inline enables inline images: write-once public images with random ids
	// ("i-{uuid}", from NewInlineName), each re-encoded with this spec from
	// originals/{id} to public/{id}.webp. Post bodies and poll options use them.
	Inline *Spec
	Video  *Video // nil: no video encoding
	// Zip names the variant packed, in file order, into downloads["zip"];
	// "" offers no zip.
	Zip string
}

Kind is a host's per-kind rule set, registered once at startup.

func (Kind) Allows

func (k Kind) Allows(contentType string, size int64) error

Allows checks a file against the kind's types and size cap.

type Limit added in v0.17.0

type Limit struct {
	MaxBytes int64
	MaxFiles int
}

Limit is a per-type cap; zero values are unlimited.

type Locker

type Locker interface {
	Lock(ctx context.Context, key string) (unlock func(), err error)
}

Locker serializes manifest edits on backends without conditional PUT.

func PGLocker

func PGLocker(pool *pgxpool.Pool) Locker

PGLocker serializes manifest edits with a per-manifest session advisory lock in the host database: the fallback for backends without conditional PUT.

type Manifest

type Manifest struct {
	Files     []File              `json:"files"`
	Meta      map[string]any      `json:"meta,omitempty"`
	Downloads map[string]Download `json:"downloads,omitempty"`
}

Manifest is the ordered file list of an item or version. List order is display order. Blob references are names within the item's folder.

func (*Manifest) Blobs

func (m *Manifest) Blobs() []string

Blobs returns every blobs/ name the manifest references.

func (*Manifest) File

func (m *Manifest) File(name string) int

File returns the index of the named file, or -1.

func (*Manifest) OriginalBytes

func (m *Manifest) OriginalBytes() int64

OriginalBytes is the storage charged for a manifest: the sizes of its distinct originals. Deleting or erasing an item releases it.

func (*Manifest) Originals

func (m *Manifest) Originals() []string

Originals returns every originals/ name the manifest references.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate requires unique, non-empty file names and well-formed references.

type ManifestOptions

type ManifestOptions struct {
	// Locker is required when the store lacks ConditionalPut; edits then run
	// under it and write unconditionally. See PGLocker.
	Locker     Locker
	CacheSize  int // manifests kept in process, revalidated by ETag; default 4096
	MaxRetries int // CAS attempts per edit; default 16
	// Jobs, when set, schedules the folder's sweep after every written edit.
	// Scheduling is best-effort (logged); the periodic sweep pass backs it up.
	Jobs *Jobs
}

ManifestOptions configure Manifests.

type Manifests

type Manifests struct {
	// contains filtered or unexported fields
}

Manifests reads and edits item manifests.

func NewManifests

func NewManifests(store Store, kinds *Registry, opts ManifestOptions) (*Manifests, error)

func (*Manifests) Edit

func (m *Manifests) Edit(ctx context.Context, ref contentref.ContentRef, fn func(*Manifest) error) (*Manifest, error)

Edit applies fn to the current manifest (empty if none) and writes it with If-Match on the ETag it read (If-None-Match for a new one), re-reading and re-applying fn on conflict. fn must be safe to run more than once; an error from fn aborts the edit. An unchanged manifest is not written.

func (*Manifests) Get

Get returns the manifest and its ETag, or ErrNotFound. Cached copies are revalidated with a conditional GET, so a read is never stale.

func (*Manifests) HoverPreview added in v0.26.0

func (m *Manifests) HoverPreview(ctx context.Context, ref contentref.ContentRef) (*HoverPreviewRecord, error)

HoverPreview returns an item's hover-preview record, or ErrNotFound.

func (*Manifests) Slot added in v0.20.0

func (m *Manifests) Slot(ctx context.Context, ref contentref.ContentRef, slot string) (*SlotRecord, error)

Slot returns a slot's record, or ErrNotFound before its first commit.

func (*Manifests) SlotManifest added in v0.20.0

func (m *Manifests) SlotManifest(ctx context.Context, baseURL string, ref contentref.ContentRef, slot string) (SlotManifest, error)

SlotManifest reads a slot's manifest (one object), building output URLs on baseURL, the access worker origin. A slot never committed has no outputs.

func (*Manifests) UpdateHoverPreview added in v0.26.0

func (m *Manifests) UpdateHoverPreview(ctx context.Context, ref contentref.ContentRef, fn func(*HoverPreviewRecord) (*HoverPreviewRecord, error)) error

UpdateHoverPreview applies fn to the record (nil before the first write) like UpdateSlot. fn returns the record to write, or nil to leave it alone.

func (*Manifests) UpdateSlot added in v0.20.0

func (m *Manifests) UpdateSlot(ctx context.Context, ref contentref.ContentRef, slot string, fn func(*SlotRecord) error) error

UpdateSlot applies fn to the slot record (zero before the first commit) and writes it like Edit: conditionally, re-running fn on conflict, and only when changed.

func (*Manifests) VideoImages added in v0.26.0

func (m *Manifests) VideoImages(ctx context.Context, baseURL string, ref contentref.ContentRef, uploader bool, file string) (VideoImages, error)

VideoImages builds output URLs on baseURL (the access worker origin). With uploader set it adds the selections and, when ref addresses a manifest, the video file (file "" is the first).

type MasterOptions

type MasterOptions struct {
	Audio, Subs []string
}

MasterOptions filter a master playlist's renditions by id or BCP 47 tag; nil keeps every track, an empty non-nil slice none.

type Multipart

type Multipart struct {
	Ticket      string
	MinPartSize int64
	MaxPartSize int64
	MaxParts    int
}

Multipart carries the opaque ticket for PresignParts, ListParts, Complete and Abort, and the part-size bounds the client adapts within.

type MultipartReply

type MultipartReply struct {
	Ticket      string `json:"ticket"`
	MinPartSize int64  `json:"min_part_size"`
	MaxPartSize int64  `json:"max_part_size"`
	MaxParts    int    `json:"max_parts"`
}

type Object

type Object struct {
	Key            string
	Size           int64
	ETag           string
	ContentType    string
	CacheControl   string
	ContentRange   string
	LastModified   time.Time
	ChecksumSHA256 []byte            // set when the backend stored a full-object SHA-256
	Metadata       map[string]string // user metadata (x-amz-meta-*), lower-case keys; Head and Get
}

Object is object metadata. For a ranged Get, Size is the body length and ContentRange is set.

type Op

type Op struct {
	Op       string         `json:"op"`
	Name     string         `json:"name"`
	Original string         `json:"original,omitempty"`
	Index    *int           `json:"index,omitempty"`
	To       string         `json:"to,omitempty"`
	Meta     map[string]any `json:"meta,omitempty"` // insert, replace: the file's meta
	Edit     *Edit          `json:"edit,omitempty"` // edit, insert, replace: the image's edit (replace drops the old one)
}

Op is one manifest edit.

type PGLimiter

type PGLimiter struct {
	// contains filtered or unexported fields
}

PGLimiter is the default UploadLimiter over ContentKit's Postgres schema: hourly counters per uploader (bytes/day sums the last 24), one usage total per owner and short-lived pending reservations. There are no rows per file.

func NewPGLimiter

func NewPGLimiter(pool *pgxpool.Pool, schema string, limits PGLimits) (*PGLimiter, error)

func (*PGLimiter) Reserve

func (l *PGLimiter) Reserve(ctx context.Context, r Reservation) error

func (*PGLimiter) Settle

func (l *PGLimiter) Settle(ctx context.Context, s Settlement) error

func (*PGLimiter) Usage

func (l *PGLimiter) Usage(ctx context.Context, tenant, owner string) (used, pending int64, err error)

Usage reports an owner's stored bytes and unexpired pending reservations.

type PGLimits

type PGLimits struct {
	FilesPerHour int
	BytesPerDay  int64
	// Quota is the owner's storage cap in bytes (<= 0 unlimited); nil disables quotas.
	Quota func(ctx context.Context, tenant, owner string) (int64, error)
	// ReservationTTL drops unsettled reservations (commit still enforces the
	// quota); default 24h.
	ReservationTTL time.Duration
}

PGLimits configure PGLimiter. Zero limits are off.

type Part

type Part struct {
	Number int32
	Size   int64
	ETag   string
	SHA256 []byte
}

Part is one uploaded multipart part.

type PartBody

type PartBody struct {
	Number int32  `json:"number"`
	Size   int64  `json:"size"`
	SHA256 string `json:"sha256"`
}

type PartReply

type PartReply struct {
	Number  int32         `json:"number"`
	Size    int64         `json:"size,omitempty"`
	SHA256  string        `json:"sha256,omitempty"`
	Request *RequestReply `json:"request,omitempty"`
}

PartReply is a presigned part (parts) or a landed part (parts/list).

type PartRequest

type PartRequest struct {
	Number int32
	Size   int64
	SHA256 []byte
}

PartRequest is one part to presign: its exact length and SHA-256.

type PartsBody

type PartsBody struct {
	Ticket string     `json:"ticket"`
	Parts  []PartBody `json:"parts"`
}

type PartsReply

type PartsReply struct {
	Parts []PartReply `json:"parts"`
}

type PosterFrame added in v0.26.0

type PosterFrame struct {
	Version string  `json:"version,omitempty"` // manifest holding File, for versioned kinds
	File    string  `json:"file"`
	Time    float64 `json:"time"`
	Auto    bool    `json:"auto,omitempty"`   // chosen by the worker (first non-flat frame)
	Source  string  `json:"source,omitempty"` // original grabbed from; "" until grabbed
}

PosterFrame is a poster grabbed from a video frame (SlotRecord.Frame).

func (PosterFrame) Same added in v0.26.0

func (f PosterFrame) Same(o PosterFrame) bool

Same reports the same selection; an automatic one at any time.

type PosterManifest added in v0.26.0

type PosterManifest struct {
	SlotManifest
	Selection *PosterSelection `json:"selection,omitempty"`
}

PosterManifest is the poster slot's manifest plus its selection.

type PosterRequest added in v0.26.0

type PosterRequest struct {
	Source string
	File   string // default: the first video file
	Time   float64
	SHA256 []byte
	Edit   *Edit
}

PosterRequest selects a video's poster: Source "frame" grabs File at Time (seconds); "upload" commits the image uploaded to the poster slot (SHA256 as presigned); "auto" returns to the worker's choice. Edit is the slot edit, in the grabbed frame's pixels (VideoInfo.W×H) or the upload's; nil centres.

type PosterSelection added in v0.26.0

type PosterSelection struct {
	Source  string   `json:"source"`
	Version string   `json:"version,omitempty"`
	File    string   `json:"file,omitempty"`
	Time    *float64 `json:"time,omitempty"`
}

PosterSelection is the current poster choice; Source is auto, frame or upload.

type PresignBody

type PresignBody struct {
	Ref    RefBody `json:"ref"`
	Type   string  `json:"type"`
	Size   int64   `json:"size"`
	SHA256 string  `json:"sha256,omitempty"` // required up to 64 MiB, for slots and inline images
	Slot   string  `json:"slot,omitempty"`
	Inline bool    `json:"inline,omitempty"` // a new inline image; the reply names it
}

type PresignPut

type PresignPut struct {
	ContentType string
	Size        int64
	SHA256      []byte
	TTL         time.Duration
}

PresignPut binds a direct upload to its exact type, length and SHA-256.

type PresignReply

type PresignReply struct {
	Name      string          `json:"name"`
	Exists    bool            `json:"exists,omitempty"`
	Put       *RequestReply   `json:"put,omitempty"`
	Multipart *MultipartReply `json:"multipart,omitempty"`
}

PresignReply: exists (commit directly), put (one PUT) or multipart.

type PresignRequest

type PresignRequest struct {
	Ref    contentref.ContentRef
	Type   string
	Size   int64
	SHA256 []byte
	Slot   string
	Inline bool
}

PresignRequest declares one file. SHA256 is required up to MaxSinglePut and for slots; Slot targets the kind's fixed slot original, and Inline a new inline image, named in Presigned.Name. Both commit with CommitSlot.

type Presigned

type Presigned struct {
	Name      string
	Exists    bool
	Put       *PresignedRequest
	Multipart *Multipart
}

Presigned is the upload plan: Exists (already in the folder; commit it), a single Put, or a Multipart upload.

type PresignedPart

type PresignedPart struct {
	Number int32
	PresignedRequest
}

PresignedPart is a part URL.

type PresignedRequest

type PresignedRequest struct {
	Method  string
	URL     string
	Header  http.Header
	Expires time.Time
}

PresignedRequest is a request a browser sends as is, with exactly Header.

type PreviewImage added in v0.26.0

type PreviewImage struct {
	W   int    `json:"w"`
	H   int    `json:"h"`
	URL string `json:"url"`
}

type PreviewRequest added in v0.26.0

type PreviewRequest struct {
	File     string
	Start    *float64
	Duration float64
}

PreviewRequest selects the hover-preview section: Start nil is the automatic section; Duration 0 is HoverPreviewDefault.

type ProcessInserter added in v0.26.0

type ProcessInserter struct {
	// contains filtered or unexported fields
}

ProcessInserter enqueues media process jobs into the host's River schema from another process: the video worker hands a grabbed poster frame to the host's image job this way. It inserts only.

func NewProcessInserter added in v0.26.0

func NewProcessInserter(pool *pgxpool.Pool, schema, queue string) (*ProcessInserter, error)

NewProcessInserter targets the host's River schema ("" is the connection's search path) and media queue ("" is DefaultQueue).

func (*ProcessInserter) Enqueue added in v0.26.0

func (p *ProcessInserter) Enqueue(ctx context.Context, job ProcessJob) error

type ProcessJob

type ProcessJob struct {
	Ref  contentref.ContentRef
	Slot string
}

ProcessJob asks for derivatives after a commit: the item's manifest, or one public slot when Slot is set.

type ProcessQueue

type ProcessQueue interface {
	Enqueue(ctx context.Context, job ProcessJob) error
}

ProcessQueue enqueues processing (River in the image and video lanes).

type Processor

type Processor func(ctx context.Context, job ProcessJob) error

Processor derives an item's files after a commit (image variants, video encodes). It must be idempotent. An Enqueue while its job runs queues one rerun after it.

type PutOptions

type PutOptions struct {
	ContentType    string
	CacheControl   string
	ChecksumSHA256 []byte
	IfMatch        string
	IfNoneMatch    string
	Metadata       map[string]string
}

PutOptions are conditions and headers for Put. IfNoneMatch "*" creates only.

type ReadOptions

type ReadOptions struct {
	// Variants in preference order: each file in range gets a URL for the
	// first one it has (EditorOnly ones only for editors). Empty returns
	// metadata only.
	Variants      []string
	Offset, Limit int
}

ReadOptions select the URLs a read returns.

type ReadResult

type ReadResult struct {
	Access       string         `json:"access"`
	Total        int            `json:"total"`
	PreviewLimit int            `json:"preview_limit"`
	Offset       int            `json:"offset"`
	Limit        int            `json:"limit"`
	Expires      int64          `json:"expires"` // unix seconds; URLs and cookie stop working then
	Meta         map[string]any `json:"meta,omitempty"`
	Files        []FileInfo     `json:"files"`
	Downloads    []DownloadInfo `json:"downloads,omitempty"`
	// Cookie must be set on the response (cookie mode, full access).
	Cookie *http.Cookie `json:"-"`
}

ReadResult is the read API response. Files lists every file; only allowed files inside [offset, offset+limit) carry a URL, and files past the cut omit their name.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader answers the read API: one Resolve per item, metadata for every file, and signed URLs for the requested range.

func NewReader

func NewReader(o ReaderOptions) (*Reader, error)

func (*Reader) Grant

func (r *Reader) Grant(ctx context.Context, ref contentref.ContentRef, actor access.Actor) (*Grant, error)

Grant resolves ref for actor exactly once and loads its manifest. A resolver error denies (ErrResolve); an invisible item is ErrNotVisible. A visible item without a manifest yet has no files.

func (*Reader) Handler

func (r *Reader) Handler(o HandlerOptions) http.Handler

Handler serves the read API. The host mounts it under a prefix such as "/media/" after its auth middleware. {id} is "{content_id}" or "{content_id}@{version_id}" for a versioned kind. Errors are JSON {"error", "code"}: 400 invalid_request, 404 not_found (also for hidden items), 500 internal_error (a resolver error denies this way).

GET /{kind}/{id}?variant=high,thumb&offset=0&limit=50 -> ReadResult (+ Set-Cookie mt)
GET /{kind}/{id}/hls/{file}/master.m3u8?audio=ja&subs=en,s2 (filters optional; empty = none)
GET /{kind}/{id}/hls/{file}/video/{height}.m3u8, audio/{track}.m3u8, subs/{track}.m3u8
GET /{kind}/{id}/hls/{file}/sprite.vtt
GET /{kind}/{id}/download/{key} -> 302 to the signed download URL
GET /{kind}/{id}/slots/{slot} -> SlotManifest (public; no resolve, no-cache)
GET /{kind}/{id}/video-images -> VideoImages without selections (public; no resolve, no-cache)

Every request resolves the item once; playlists and redirects are "private, no-store" and carry the folder cookie in cookie mode.

func (*Reader) HoverPreviewURLs added in v0.26.0

func (r *Reader) HoverPreviewURLs(ref contentref.ContentRef, version string) (mp4, webp string, err error)

HoverPreviewURLs are the URLs of the smallest hover-preview loop, which every rendered preview has; it reads nothing, so listings link previews freely (posters: SlotOutputs with PosterSlot). version is HoverPreviewManifest.Version, or "" for URLs revalidated on every view.

func (*Reader) PublicURL

func (r *Reader) PublicURL(ref contentref.ContentRef, name string) (string, error)

PublicURL is the plain URL of a public slot output or inline image; it reads nothing.

func (*Reader) Read

Read resolves ref once and answers the read API.

func (*Reader) Slot added in v0.20.0

func (r *Reader) Slot(ctx context.Context, ref contentref.ContentRef, slot string) (SlotManifest, error)

Slot reads a slot's manifest (no Resolve: outputs are public).

func (*Reader) SlotOutputs added in v0.20.0

func (r *Reader) SlotOutputs(ref contentref.ContentRef, slot string, stamp SlotStamp) ([]SlotImage, error)

SlotOutputs lists, reading nothing, the outputs of a slot encoded as stamp, with immutable ?v= URLs: the SlotManifest.Outputs of that encode. Widths the slot no longer declares are left out. The zero stamp lists the widths up to Min, which every processed slot has, with URLs revalidated on every view (a slot never uploaded answers 404).

func (*Reader) VideoImages added in v0.26.0

func (r *Reader) VideoImages(ctx context.Context, ref contentref.ContentRef) (VideoImages, error)

VideoImages reads a video item's poster and hover preview (two small objects; no Resolve, as both are public).

type ReaderOptions

type ReaderOptions struct {
	Manifests *Manifests
	Kinds     *Registry
	Resolver  access.ContentResolver
	Delivery  Delivery
	Hooks     Hooks
	// MaxLimit caps ReadOptions.Limit (default 200); DefaultLimit is used when
	// Limit is 0 (default 50).
	MaxLimit, DefaultLimit int
	Now                    func() time.Time
}

ReaderOptions configure a Reader.

type RefBody

type RefBody struct {
	Kind    string `json:"kind"`
	ID      string `json:"id"`
	Version string `json:"version,omitempty"`
}

RefBody names an item within the handler's tenant.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is the host's set of kinds.

func NewRegistry

func NewRegistry(kinds ...Kind) (*Registry, error)

NewRegistry validates and registers kinds.

func (*Registry) Item

func (r *Registry) Item(ref contentref.ContentRef) (Item, error)

Item validates ref against the registry. A version is required to address a versioned kind's manifest, and refused for an unversioned kind.

func (*Registry) Kind

func (r *Registry) Kind(name string) (Kind, error)

Kind returns a registered kind.

type Rendition

type Rendition struct {
	Rung      int       `json:"rung"`
	Width     int       `json:"w"`
	Height    int       `json:"h"`
	Bandwidth int       `json:"bandwidth"`
	Average   int       `json:"avg,omitempty"`
	Codecs    string    `json:"codecs"`
	Blob      string    `json:"blob"`
	Segments  []Segment `json:"segments"`
}

Rendition is one video-only fMP4 blob: its init segment is bytes [0, Segments[0].Offset) and the segments follow contiguously. Rung is its ladder label (the short side it was asked for, e.g. 1080 for "1080p"); Width and Height are the encoded frame.

func FrameRendition added in v0.26.0

func FrameRendition(f File) (Rendition, bool)

FrameRendition is the rendition poster frames are grabbed from: the widest.

type RequestReply

type RequestReply struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers"`
	Expires time.Time         `json:"expires"`
}

RequestReply is a presigned request: send exactly these headers (the browser adds Content-Length, which is signed too).

type Reservation

type Reservation struct {
	Tenant   string
	Uploader string
	Owner    string
	Key      string
	Size     int64
}

Reservation is one presigned upload. Uploader is rate-limited; Owner ("" for none) has Size reserved against its quota until the upload is settled or the reservation expires.

type Segment

type Segment struct {
	Offset  int64
	Length  int64
	Seconds float64
}

Segment is one EXT-X-BYTERANGE segment, encoded as [offset, length, seconds].

func (Segment) MarshalJSON

func (s Segment) MarshalJSON() ([]byte, error)

func (*Segment) UnmarshalJSON

func (s *Segment) UnmarshalJSON(b []byte) error

type Settlement

type Settlement struct {
	Tenant  string
	Owner   string
	Keys    []string
	Delta   int64
	Enforce bool
}

Settlement releases reservations and moves an owner's usage. With Enforce, a positive Delta that takes usage over the owner's quota is refused with CodeQuota and changes nothing.

type Slot

type Slot struct {
	Aspect   float64
	Widths   []int
	MinWidth int
	Quality  int // WebP quality; default 80
}

Slot is a fixed public image at Aspect (the edited image's width/height), rendered at each of Widths to public/{slot}_{width}.webp (SlotOutput). Its original is kept at originals/{slot} and its Edit in the slot record. Widths wider than the edited image are skipped, never upscaled; an edit narrower than Min fails, so every width up to Min exists once the slot is processed.

func (Slot) Hash added in v0.20.0

func (s Slot) Hash() string

Hash is the slot spec's stable identity; outputs under another are stale.

func (Slot) Height added in v0.20.0

func (s Slot) Height(width int) int

Height is the output height of a width at Aspect.

func (Slot) Min added in v0.20.0

func (s Slot) Min() int

Min is the narrowest edited width accepted: MinWidth, at least the smallest width.

func (Slot) Resolve added in v0.20.0

func (s Slot) Resolve(e *Edit, w, h int) (*Edit, error)

Resolve is the edit the slot applies to a w×h source (EXIF-oriented): e with its height fitted, or without a crop the largest centred one at Aspect. It must lie inside the source and be at least Min wide once edited.

type SlotBody

type SlotBody struct {
	Ref    RefBody `json:"ref"`
	Slot   string  `json:"slot"`
	SHA256 string  `json:"sha256"`
	Edit   *Edit   `json:"edit,omitempty"`
}

SlotBody commits an uploaded slot (or inline image) original. Edit's crop is in the EXIF-oriented original's pixels, its height derived from its width at the slot's aspect; omitted crops centred at the aspect.

type SlotEditBody added in v0.20.0

type SlotEditBody struct {
	Ref  RefBody `json:"ref"`
	Slot string  `json:"slot"`
	Edit *Edit   `json:"edit,omitempty"`
}

SlotEditBody re-edits the committed original; omitted crops centred.

type SlotFromFile added in v0.19.0

type SlotFromFile struct {
	Ref  contentref.ContentRef // the slot's item; a version ref also names From's manifest
	Slot string
	// From is the manifest holding File when it is not Ref's: another item
	// (or version) of the same tenant, e.g. a post image for a channel avatar.
	From contentref.ContentRef
	File string
	// Edit crops the copy (default: the file's own edit; an empty Edit clears it).
	Edit *Edit
}

SlotFromFile names a slot and the manifest image to fill it from.

type SlotFromFileBody added in v0.17.0

type SlotFromFileBody struct {
	Ref  RefBody  `json:"ref"`
	Slot string   `json:"slot"`
	From *RefBody `json:"from,omitempty"`
	File string   `json:"file"`
	Edit *Edit    `json:"edit,omitempty"`
}

SlotFromFileBody makes File (a manifest image of From, default Ref) the slot's original, through Edit (default: the file's edit; {} clears it).

type SlotImage added in v0.20.0

type SlotImage struct {
	Name string `json:"name"`
	W    int    `json:"w"`
	H    int    `json:"h"`
	URL  string `json:"url"`
}

SlotImage is one produced output.

type SlotManifest added in v0.20.0

type SlotManifest struct {
	Aspect  float64     `json:"aspect"`
	Edit    *Edit       `json:"edit,omitempty"`    // nil: the centred crop at aspect
	Dims    *Dims       `json:"dims,omitempty"`    // the committed original, EXIF-oriented, once measured
	Version string      `json:"version,omitempty"` // of the outputs listed
	Outputs []SlotImage `json:"outputs"`
	Pending bool        `json:"pending"`         // a commit, edit or spec change is not encoded yet
	Error   string      `json:"error,omitempty"` // the latest encode failed; the outputs are older
}

SlotManifest describes a slot for srcset: its produced outputs by ascending width. Output URLs carry ?v={version}; the access worker serves a matching version as immutable, so a re-encode is a new URL.

func (SlotManifest) Stamp added in v0.23.0

func (m SlotManifest) Stamp() SlotStamp

Stamp is the manifest's SlotStamp ("" before the first encode), e.g. to backfill hosts that adopt Hooks.SlotEncoded after slots were set.

type SlotRecord added in v0.20.0

type SlotRecord struct {
	Original string       `json:"original"`        // ETag of originals/{slot} when committed
	Edit     *Edit        `json:"edit,omitempty"`  // nil: the centred crop at the slot's Aspect
	Frame    *PosterFrame `json:"frame,omitempty"` // a video poster grabbed from a frame; nil for uploads
	Result   *SlotResult  `json:"result,omitempty"`
}

SlotRecord is originals/{slot}.json, private like the original. Commits and edits set Original and Edit; the image job sets Result.

func (SlotRecord) Fingerprint added in v0.20.0

func (rec SlotRecord) Fingerprint(s Slot) string

Fingerprint identifies the outputs the record yields under slot spec s.

type SlotRefBody added in v0.20.0

type SlotRefBody struct {
	Ref  RefBody `json:"ref"`
	Slot string  `json:"slot"`
}

type SlotResult added in v0.20.0

type SlotResult struct {
	Of      string `json:"of"`              // the Fingerprint last encoded
	Version string `json:"version"`         // the Fingerprint Outputs were encoded under (Of, unless it failed)
	Source  string `json:"source"`          // the original (ETag) Dims measure
	Dims    Dims   `json:"dims"`            // EXIF-oriented; zero when undecodable
	Outputs []Dims `json:"outputs"`         // by ascending width
	Error   string `json:"error,omitempty"` // Of failed; Outputs are older
}

SlotResult is what the served outputs were derived from.

type SlotStamp added in v0.23.0

type SlotStamp string

SlotStamp is the one value a host stores per slot to build its outputs without reads: the encode's version and the widths it produced, "{version}:{w},{w}…". Hooks.SlotEncoded reports it; the zero stamp is a slot the host never saw encoded.

func NewSlotStamp added in v0.23.0

func NewSlotStamp(version string, widths []int) SlotStamp

NewSlotStamp stamps outputs of widths encoded under version.

func (SlotStamp) Parse added in v0.23.0

func (s SlotStamp) Parse() (version string, widths []int, err error)

Parse splits the stamp; the zero stamp is ("", nil).

type Spec

type Spec struct {
	Width   int
	Height  int
	Fit     Fit
	Quality int
	Blur    float64
	// Unedited ignores the file's Edit: an editor's view of the whole source.
	// It must be EditorOnly.
	Unedited bool
	// EditorOnly variants are signed by the read API only for actors whose
	// Resolution is Editor; slots, inline images and zips cannot use them.
	EditorOnly bool
}

Spec describes one derived image. Zero Width and Height keep full resolution.

func (Spec) For added in v0.17.0

func (s Spec) For(e *Edit) string

For is the identity of s derived through e, recorded as Variant.Spec: a variant is stale when its spec or its file's edit changes. Unedited specs ignore the edit.

func (Spec) Hash

func (s Spec) Hash() string

Hash is the spec's stable identity; a variant whose recorded spec differs is stale (see For, which adds the file's edit).

type Sprite

type Sprite struct {
	Blob     string  `json:"blob"`
	Cols     int     `json:"cols"`
	Rows     int     `json:"rows"`
	Width    int     `json:"w"`
	Height   int     `json:"h"`
	Interval float64 `json:"interval"`
}

type Store

type Store interface {
	Put(ctx context.Context, key string, body io.Reader, size int64, opts PutOptions) (Object, error)
	Get(ctx context.Context, key string, opts GetOptions) (io.ReadCloser, Object, error)
	Head(ctx context.Context, key string) (Object, error)
	Delete(ctx context.Context, key string) error
	List(ctx context.Context, prefix string) iter.Seq2[Object, error]

	PresignPut(ctx context.Context, key string, p PresignPut) (PresignedRequest, error)
	CreateMultipart(ctx context.Context, key, contentType string) (uploadID string, err error)
	PresignPart(ctx context.Context, key, uploadID string, number int32, size int64, sha256 []byte, ttl time.Duration) (PresignedRequest, error)
	// PutPart uploads one part from the server, bound to its length and SHA-256.
	PutPart(ctx context.Context, key, uploadID string, number int32, body io.Reader, size int64, sha256 []byte) (Part, error)
	ListParts(ctx context.Context, key, uploadID string) ([]Part, error)
	CompleteMultipart(ctx context.Context, key, uploadID string, parts []Part) (Object, error)
	AbortMultipart(ctx context.Context, key, uploadID string) error

	Capabilities() Capabilities
}

Store is the bucket. Keys are built by Item; implementations do not interpret them.

type Subtitle

type Subtitle struct {
	ID     string `json:"id"`
	Lang   string `json:"lang,omitempty"`
	Label  string `json:"label,omitempty"`
	Forced bool   `json:"forced,omitempty"`
	Blob   string `json:"blob"`
}

type SweepResult

type SweepResult struct {
	Deleted []string
	Wait    time.Duration
}

SweepResult reports one folder sweep. Wait > 0 means a manifest changed within the grace period and nothing was deleted; sweep again after Wait.

type TicketBody

type TicketBody struct {
	Ticket string `json:"ticket"`
}

type UploadAuthorizer

type UploadAuthorizer interface {
	CanUpload(ctx context.Context, actor access.Actor, ref contentref.ContentRef) (UploadGrant, error)
}

UploadAuthorizer is the host's upload permission check (AuthKit), run at presign and commit against the ref whose folder is written: the version for manifest uploads, the work (ref.Content()) for slots and inline images.

type UploadError

type UploadError struct {
	Code       string
	Message    string
	RetryAfter time.Duration // CodeRate: when the window frees
	Originals  []string      // CodeNotUploaded at commit: the originals to upload again
}

UploadError is a refused upload request. UploadLimiter implementations refuse with CodeRate or CodeQuota.

func AsUploadError

func AsUploadError(err error) (*UploadError, bool)

AsUploadError classifies err: an *UploadError, or the kind and registry sentinels. ok is false for internal failures.

func (*UploadError) Error

func (e *UploadError) Error() string

func (*UploadError) Status

func (e *UploadError) Status() int

Status is the HTTP status for Code.

type UploadGrant

type UploadGrant struct {
	Allowed bool
	Exempt  bool
	Owner   string
}

UploadGrant is the host's verdict. Exempt (trusted roles) skips the UploadLimiter checks; Owner is the quota owner (creator, channel), "" for none.

type UploadHandlerOptions

type UploadHandlerOptions struct {
	Tenant string                                   // every ref is scoped to it
	Actor  func(*http.Request) (access.Actor, bool) // the host's authenticated caller; false answers 401
	Logger *slog.Logger                             // 5xx causes; default slog.Default()
	// PublicBaseURL is the access worker origin (Delivery.BaseURL) slot
	// replies build output URLs on; required for slot routes.
	PublicBaseURL string
}

UploadHandlerOptions configure UploadHandler.

type UploadLimiter

type UploadLimiter interface {
	Reserve(ctx context.Context, r Reservation) error
	Settle(ctx context.Context, s Settlement) error
}

UploadLimiter is the optional anti-abuse port. Quota is enforced when bytes are committed: a commit that grows its owner's stored originals past the quota is refused. Reserve runs at presign (skipped for exempt uploaders) and refuses with an *UploadError coded CodeRate or CodeQuota before any bytes move; a reservation is only that early refusal and may expire. Settle runs at commit, abort and item deletion: it drops the reservations of Keys and adds Delta (the change in stored originals, negative on removal) to the owner's usage.

type UploadOptions

type UploadOptions struct {
	Store      Store
	Kinds      *Registry
	Manifests  *Manifests
	Authorizer UploadAuthorizer
	Tickets    *token.Ring   // signs multipart tickets (domain-separated from access tokens); required for files over MaxSinglePut
	Limiter    UploadLimiter // optional
	Queue      ProcessQueue  // optional
	PresignTTL time.Duration // PUT and part URLs; default 15m
	// Grace is the sweep's (JobsConfig.Grace): Queue's when it is *Jobs, else 24h.
	Grace     time.Duration
	TicketTTL time.Duration // multipart ticket; default 24h, the abort-incomplete rule
	// Frames serves the video poster picker's frame grabs (media/video.Frames;
	// needs ffmpeg); nil answers not_found. FrameConcurrency bounds concurrent
	// grabs per process; default 2.
	Frames           FrameGrabber
	FrameConcurrency int
}

UploadOptions configure Uploads.

type UploadedObject

type UploadedObject struct {
	Name string
	Type string
	Size int64
}

UploadedObject is a completed multipart original.

type Uploads

type Uploads struct {
	// contains filtered or unexported fields
}

Uploads presigns direct-to-bucket uploads and commits them into manifests. It keeps no state: a multipart upload is its S3 UploadId, carried in a signed ticket.

func NewUploads

func NewUploads(o UploadOptions) (*Uploads, error)

func (*Uploads) Abort

func (u *Uploads) Abort(ctx context.Context, actor access.Actor, sealed string) error

Abort cancels a multipart upload and drops its reservation.

func (*Uploads) Commit

func (u *Uploads) Commit(ctx context.Context, actor access.Actor, ref contentref.ContentRef, ops []Op) (*Manifest, error)

Commit applies ops to the manifest in one conditional write. Every new original is HEAD-checked against the kind's type and size cap (and re-hashed when the store does not enforce checksums). The owner is charged the change in distinct originals the manifest references; growth past its quota fails with CodeQuota (not for exempt grants). Then processing is enqueued.

func (*Uploads) CommitSlot

func (u *Uploads) CommitSlot(ctx context.Context, actor access.Actor, ref contentref.ContentRef, slot string, sum []byte, edit *Edit) error

CommitSlot validates an uploaded slot or inline original and enqueues the re-encode of its outputs. A registered slot records it with edit (nil: the centred crop at the slot's Aspect); its crop's height follows its width. Inline images take no edit. sum is the SHA-256 the upload was presigned with.

func (*Uploads) Complete

func (u *Uploads) Complete(ctx context.Context, actor access.Actor, sealed string) (UploadedObject, error)

Complete assembles the parts server-side. Missing parts answer CodeIncomplete and keep the upload; parts that cannot add up to the declared size abort it.

func (*Uploads) EditSlot added in v0.20.0

func (u *Uploads) EditSlot(ctx context.Context, actor access.Actor, ref contentref.ContentRef, slot string, edit *Edit) error

EditSlot re-edits the committed original (nil: centred) without a new upload; the job re-encodes every output from it. Once the original's size is known the edit is checked against it here, else by the job.

func (*Uploads) Frame added in v0.26.0

func (u *Uploads) Frame(ctx context.Context, actor access.Actor, ref contentref.ContentRef, file string, t float64, width int) ([]byte, error)

Frame renders a small JPEG of the encoded file's frame at t for the poster picker. t is clamped into the video, width into 64-FrameMaxWidth (0 is FrameDefaultWidth). At most UploadOptions.FrameConcurrency run at once; others wait briefly, then answer CodeRate.

func (*Uploads) Ingest added in v0.18.0

func (u *Uploads) Ingest(ctx context.Context, actor access.Actor, req IngestRequest) (IngestResult, error)

Ingest uploads req.Body into the item's originals (one checksum-bound PUT when it fits in one part, else multipart with per-part SHA-256 and retries) and commits it with Commit, which re-checks the upload and enqueues processing. Every check Commit makes on a browser upload applies.

func (*Uploads) ListParts

func (u *Uploads) ListParts(ctx context.Context, actor access.Actor, sealed string) ([]Part, error)

ListParts reports the parts that landed, for resuming.

func (*Uploads) Presign

func (u *Uploads) Presign(ctx context.Context, actor access.Actor, r PresignRequest) (Presigned, error)

func (*Uploads) PresignParts

func (u *Uploads) PresignParts(ctx context.Context, actor access.Actor, sealed string, parts []PartRequest) ([]PresignedPart, error)

PresignParts signs parts of a multipart upload, each bound to its length and SHA-256. Parts re-signed after a failure replace the earlier attempt.

func (*Uploads) SetHoverPreview added in v0.26.0

func (u *Uploads) SetHoverPreview(ctx context.Context, actor access.Actor, ref contentref.ContentRef, r PreviewRequest) error

SetHoverPreview records a hover-preview selection and enqueues its render.

func (*Uploads) SetSlotFromFile added in v0.17.0

func (u *Uploads) SetSlotFromFile(ctx context.Context, actor access.Actor, r SlotFromFile) error

SetSlotFromFile makes an image file the slot's original: its source is copied to originals/{slot} and recorded with the edit, and the slot's outputs are re-encoded through it. The crop's height follows its width at the slot's Aspect; it is checked against the file's Dims once processing has recorded them, else by the slot job. The actor must be allowed to upload to Ref's work and, when From names another item, to From.

func (*Uploads) SetVideoPoster added in v0.26.0

func (u *Uploads) SetVideoPoster(ctx context.Context, actor access.Actor, ref contentref.ContentRef, r PosterRequest) error

SetVideoPoster records a poster selection and enqueues its work: a frame grab by the video worker (which then hands the frame to the image job), or the upload's encode. Frame selections need the ref's manifest (a version for versioned kinds) and an encoded file.

func (*Uploads) SlotOriginal added in v0.20.0

func (u *Uploads) SlotOriginal(ctx context.Context, actor access.Actor, ref contentref.ContentRef, slot string) (io.ReadCloser, Object, error)

SlotOriginal opens a slot's committed original for its uploaders (the editor); originals are never public.

type Variant

type Variant struct {
	Blob   string `json:"blob"`
	Spec   string `json:"spec,omitempty"`
	Type   string `json:"type,omitempty"`
	Size   int64  `json:"size,omitempty"`
	Editor bool   `json:"editor,omitempty"` // from Spec.EditorOnly: signed for editors only
}

type Video added in v0.19.0

type Video struct {
	// Ladder is the rendition short sides (height of landscape, width of
	// vertical video), largest first; rungs above the source's short side
	// are dropped. Empty is DefaultLadder.
	Ladder []int `json:"ladder,omitempty"`
	// MinAspect and MaxAspect bound a source's display width/height; a
	// source outside fails permanently. Zero is DefaultMinAspect/DefaultMaxAspect.
	MinAspect float64 `json:"min_aspect,omitempty"`
	MaxAspect float64 `json:"max_aspect,omitempty"`
}

Video configures a kind's video encoding (media/video).

func (*Video) Aspects added in v0.22.0

func (v *Video) Aspects() (lo, hi float64)

Aspects are the aspect bounds in effect.

func (*Video) Rungs added in v0.22.0

func (v *Video) Rungs() []int

Rungs is the ladder in effect.

func (Video) Validate added in v0.22.0

func (v Video) Validate() error

Validate requires even rungs of 2–4320, largest first, without repeats, and aspect bounds with MinAspect ≤ 1 ≤ MaxAspect.

type VideoImages added in v0.26.0

type VideoImages struct {
	Poster       PosterManifest       `json:"poster"`
	HoverPreview HoverPreviewManifest `json:"hover_preview"`
	Video        *VideoInfo           `json:"video,omitempty"`
}

VideoImages is a video item's poster and hover preview. Selections and Video are only in the uploader's reply (POST /video-images).

type VideoImagesBody added in v0.26.0

type VideoImagesBody struct {
	Ref  RefBody `json:"ref"`
	File string  `json:"file,omitempty"`
}

VideoImagesBody names a video item; with a version (versioned kinds) the reply describes its file (file, default the first video file).

type VideoInfo added in v0.26.0

type VideoInfo struct {
	Version  string  `json:"version,omitempty"`
	File     string  `json:"file"`
	Duration float64 `json:"duration"`
	W        int     `json:"w"`
	H        int     `json:"h"`
	Encoded  bool    `json:"encoded"`
}

VideoInfo is the picker's video: the selected (or first) file of the ref's manifest. W×H is the grabbed poster frame's size, the space of frame poster edits.

type VideoPosterBody added in v0.26.0

type VideoPosterBody struct {
	Ref    RefBody  `json:"ref"`
	Source string   `json:"source"`
	File   string   `json:"file,omitempty"`
	Time   *float64 `json:"time,omitempty"`
	SHA256 string   `json:"sha256,omitempty"`
	Edit   *Edit    `json:"edit,omitempty"`
}

VideoPosterBody selects the poster. source "frame" needs time (seconds, in the video) and a ref version for versioned kinds, its edit in the grabbed frame's pixels (VideoInfo w×h); "upload" needs the sha256 of the image presigned with slot "poster", its edit in that image's pixels; "auto" returns to the default. Omitted edits centre the 16:9 crop.

type VideoPreviewBody added in v0.26.0

type VideoPreviewBody struct {
	Ref      RefBody  `json:"ref"`
	File     string   `json:"file,omitempty"`
	Start    *float64 `json:"start,omitempty"`
	Duration float64  `json:"duration,omitempty"`
}

VideoPreviewBody selects the hover-preview section: start omitted is the automatic section; duration defaults to 3 and is bounded 1-6 seconds.

Directories

Path Synopsis
Package accessworker is the media access worker's HTTP handler, run by cmd/media-access: it checks the token for a blob path (URL `?t=` or cookie `mt`), serves public/ paths without one (immutable at a current ?v= version), refuses manifests and originals/, and streams the object from the private bucket with its own read-only key.
Package accessworker is the media access worker's HTTP handler, run by cmd/media-access: it checks the token for a blob path (URL `?t=` or cookie `mt`), serves public/ paths without one (immutable at a current ?v= version), refuses manifests and originals/, and streams the object from the private bucket with its own read-only key.
Package image derives WebP variants, public slots and zip downloads with libvips (CGO).
Package image derives WebP variants, public slots and zip downloads with libvips (CGO).
internal
s3test
Package s3test opens the test bucket from the environment:
Package s3test opens the test bucket from the environment:
uploadtestserver command
Command uploadtestserver serves media.UploadHandler over a fresh MinIO/RGW bucket for the browser SDK's integration tests (sdk/upload/test).
Command uploadtestserver serves media.UploadHandler over a fresh MinIO/RGW bucket for the browser SDK's integration tests (sdk/upload/test).
videotest
Package videotest builds synthetic videos whose frames identify their time and orientation, and classifies decoded pixels, for poster and preview tests.
Package videotest builds synthetic videos whose frames identify their time and orientation, and classifies decoded pixels, for poster and preview tests.
wirets
Package wirets renders the upload API wire types as TypeScript for the browser SDK (sdk/upload/src/wire.gen.ts).
Package wirets renders the upload API wire types as TypeScript for the browser SDK (sdk/upload/src/wire.gen.ts).
Package layout defines media object keys, dependency-free so the access worker can classify paths without importing the media runtime:
Package layout defines media object keys, dependency-free so the access worker can classify paths without importing the media runtime:
Package s3 implements media.Store over aws-sdk-go-v2 for Ceph RGW (production) and MinIO (tests).
Package s3 implements media.Store over aws-sdk-go-v2 for Ceph RGW (production) and MinIO (tests).
Package tiered is an optional visibility policy: it maps an item's level to entitlement keys and asks a Checker which ones the actor holds.
Package tiered is an optional visibility policy: it maps an item's level to entitlement keys and asks a Checker which ones the actor holds.
Package token signs and verifies media access tokens, shared by the host signer and the access worker so the format cannot drift:
Package token signs and verifies media access tokens, shared by the host signer and the access worker so the format cannot drift:
Package video encodes an item's video files with ffmpeg into a byte-range HLS ladder (one single-file fMP4 blob per rendition and audio track), WebVTT subtitles, a thumbnail sprite and one muxed MP4 download per quality, and records them in the manifest's hls and downloads.
Package video encodes an item's video files with ffmpeg into a byte-range HLS ladder (one single-file fMP4 blob per rendition and audio track), WebVTT subtitles, a thumbnail sprite and one muxed MP4 download per quality, and records them in the manifest's hls and downloads.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL