media

package
v0.1.0-alpha.26 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: GPL-3.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package media owns MagicHandy's bounded local video catalog. It discovers files only after an explicit scan and never drives motion or transports.

Index

Constants

View Source
const (
	// MaxMediaFunscriptBytes bounds the paired document read into memory.
	MaxMediaFunscriptBytes int64 = 16 << 20
	// MaxMediaFunscriptActions bounds parsing, API output, and engine content.
	MaxMediaFunscriptActions = motion.MaximumMediaTimelinePoints
)
View Source
const (
	// MaxScanDepth bounds recursion below each registered root.
	MaxScanDepth = 6
	// MaxFilesPerLocation bounds all encountered regular files, not just videos.
	MaxFilesPerLocation = 10_000
)
View Source
const ConvertedExtension = ".mp4"

ConvertedExtension is the only container conversion targets.

View Source
const ConvertedSuffix = "_MHConverted"

ConvertedSuffix marks a file this app produced. It is fixed rather than configurable: changing it would orphan every file already carrying it.

View Source
const (
	// MaxThumbnailBytes bounds an accepted cover. The browser is asked for a
	// small JPEG, so anything approaching this is a client that ignored the
	// contract rather than an unusually detailed frame.
	MaxThumbnailBytes = 2 << 20
)

Variables

View Source
var (
	// ErrVideoNotFound reports an unknown catalog identifier.
	ErrVideoNotFound = errors.New("media video not found")
	// ErrVideoUnavailable reports a catalog row whose file cannot be opened.
	ErrVideoUnavailable = errors.New("media video is unavailable")
	// ErrFunscriptNotFound reports a video without a scanned exact-name pair.
	ErrFunscriptNotFound = errors.New("paired funscript not found")
	// ErrFunscriptUnavailable reports a paired script that can no longer be opened.
	ErrFunscriptUnavailable = errors.New("paired funscript is unavailable")
	// ErrScanBusy reports a second scan or catalog-maintenance overlap.
	ErrScanBusy = errors.New("media scan is already running")
	// ErrNoLocations reports an explicit scan with no configured roots.
	ErrNoLocations = errors.New("no media library locations are configured")
	// ErrClosed reports use after catalog shutdown.
	ErrClosed = errors.New("media catalog is closed")
)
View Source
var (
	// ErrToolsUnavailable reports that no usable FFmpeg is configured. It is a
	// normal state, not a failure: every feature that needs FFmpeg says so and
	// the rest of the app is unaffected.
	ErrToolsUnavailable = errors.New("ffmpeg is not configured")
	// ErrToolInvalid reports a configured path that is not a working FFmpeg.
	ErrToolInvalid = errors.New("configured ffmpeg could not be verified")
)
View Source
var (
	// ErrFunscriptInvalid reports malformed or unusable paired content.
	ErrFunscriptInvalid = errors.New("paired funscript is invalid")
	// ErrFunscriptTooLarge reports a document outside media playback bounds.
	ErrFunscriptTooLarge = errors.New("paired funscript exceeds playback limits")
	// ErrFunscriptComplete reports an anchor at or beyond the final action.
	ErrFunscriptComplete = errors.New("paired funscript has ended")
)
View Source
var (
	// ErrThumbnailInvalid reports a cover payload that is not a usable JPEG.
	ErrThumbnailInvalid = errors.New("thumbnail image is not a supported JPEG")
	// ErrThumbnailNotFound reports a video with no generated cover.
	ErrThumbnailNotFound = errors.New("thumbnail has not been generated")
)
View Source
var ErrJobBusy = errors.New("a media job is already running")

ErrJobBusy reports a second media job while one is running. One at a time, like scans: two long media jobs at once is a way to make the app feel broken.

Functions

func CatalogedExtension

func CatalogedExtension(extension string) bool

CatalogedExtension reports whether the scanner indexes this extension at all. Unplayable containers are indexed too, because a file the app hides is a file the user cannot ask it to repair.

func ContainerType

func ContainerType(path string) string

ContainerType returns the MIME type for a path, or empty when unknown.

func ConvertedName

func ConvertedName(relativePath string) string

ConvertedName returns the output name for a source path: the basename gains the reserved suffix and the extension becomes .mp4.

func HasConvertedSuffix

func HasConvertedSuffix(relativePath string) bool

HasConvertedSuffix reports whether a path is app output. Such a file is never converted again, so NAME_MHConverted_MHConverted.mp4 cannot exist.

Types

type Catalog

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

Catalog borrows the process datastore and owns the explicit scanner lifecycle. It has no startup scan and no timer.

func Open

func Open(dataDir string, logger *slog.Logger) (*Catalog, error)

Open opens a standalone catalog for tools and tests.

func OpenWithDatabase

func OpenWithDatabase(database *dbstore.DB, logger *slog.Logger) (*Catalog, error)

OpenWithDatabase borrows the process-owned datastore.

func (*Catalog) CancelJob

func (c *Catalog) CancelJob() JobState

CancelJob requests cancellation. State stays running until the worker has stopped touching the filesystem and database.

func (*Catalog) CancelScan

func (c *Catalog) CancelScan() ScanState

CancelScan requests cancellation. State remains running until the worker has stopped touching the filesystem and database.

func (*Catalog) ClearThumbnails

func (c *Catalog) ClearThumbnails(ctx context.Context) (int, error)

ClearThumbnails removes every generated cover and forgets that any existed, making the whole storage cost recoverable in one step.

func (*Catalog) Close

func (c *Catalog) Close() error

Close cancels and drains scanning before releasing an owned datastore.

func (*Catalog) FunscriptSourceIdentity

func (c *Catalog) FunscriptSourceIdentity(ctx context.Context, id string) (string, error)

FunscriptSourceIdentity returns a private cache key for the current paired file without parsing it. The path remains server-only and never enters API payloads or diagnostics.

func (*Catalog) JobState

func (c *Catalog) JobState() JobState

JobState returns a race-safe progress snapshot.

func (*Catalog) List

func (c *Catalog) List(ctx context.Context) ([]Video, error)

List returns the bounded catalog, available entries first.

func (*Catalog) LoadFunscript

func (c *Catalog) LoadFunscript(ctx context.Context, id string) (Funscript, error)

LoadFunscript opens and parses the exact-basename pair for one video.

func (*Catalog) OpenFunscript

func (c *Catalog) OpenFunscript(ctx context.Context, id string) (*os.File, Video, error)

OpenFunscript revalidates and opens the exact-basename script recorded by the scanner. Like video streaming, callers provide only the opaque video ID.

func (*Catalog) OpenThumbnail

func (c *Catalog) OpenThumbnail(ctx context.Context, id string) (*os.File, error)

OpenThumbnail opens a stored cover for serving.

func (*Catalog) OpenVideo

func (c *Catalog) OpenVideo(ctx context.Context, id string) (*os.File, Video, error)

OpenVideo revalidates the catalog jail and opens a regular file for http.ServeContent. No HTTP endpoint accepts a filesystem path.

func (*Catalog) RetainLocations

func (c *Catalog) RetainLocations(ctx context.Context, locations []string) (int64, error)

RetainLocations removes rows for roots deleted from settings. It first drains a scan so an obsolete root cannot be reinserted after the delete.

func (*Catalog) SaveThumbnail

func (c *Catalog) SaveThumbnail(ctx context.Context, id string, image []byte) error

SaveThumbnail stores a cover the browser captured and marks the row. The payload is validated as a JPEG rather than trusted: this endpoint writes a file to disk, so "the client said it was an image" is not enough.

func (*Catalog) ScanState

func (c *Catalog) ScanState() ScanState

ScanState returns a race-safe progress snapshot.

func (*Catalog) SetCompatibility

func (c *Catalog) SetCompatibility(ctx context.Context, id string, state Compatibility) error

SetCompatibility records what playback actually revealed.

This is the signal extension checks cannot produce. An .mp4 holding HEVC is indexed as an ordinary video and then refused by a browser without an HEVC decoder — Firefox, on most platforms — and only the failure event says so. It is stored so the verdict survives a reload, and it is deliberately reversible: a later successful play in a browser that does have the decoder writes "playable" straight back over it.

func (*Catalog) SetDuration

func (c *Catalog) SetDuration(ctx context.Context, id string, durationMillis int64) error

SetDuration stores browser-decoded metadata without probing media in Go.

func (*Catalog) SetScriptOffset

func (c *Catalog) SetScriptOffset(ctx context.Context, id string, offsetMillis int) error

SetScriptOffset stores this pairing's calibration. Bounds are the caller's to enforce; the catalog only refuses a value it could not have produced.

func (*Catalog) StartConversionJob

func (c *Catalog) StartConversionJob(
	ctx context.Context, tools Tools, settings config.MediaSettings, ids []string,
) (JobState, error)

StartConversionJob repairs files that cannot play. Passing no identifiers sweeps the library.

Both entry points gate on the same NeedsConversion test rather than re-deriving it, because a sweep that re-encoded a playable library would be the single worst thing this feature could do.

func (*Catalog) StartScan

func (c *Catalog) StartScan(locations []string) (ScanState, error)

StartScan snapshots configured roots and starts one cancellable scan.

func (*Catalog) StartScanThen

func (c *Catalog) StartScanThen(locations []string, after func(ScanState)) (ScanState, error)

StartScanThen starts a scan and runs after() once it has finished, which is how the opt-in generate-and-convert options ride a scan. The callback receives the final state so it can decline: a cancelled or failed scan should not silently launch an hour of encoding.

func (*Catalog) StartScanThenWithOptions

func (c *Catalog) StartScanThenWithOptions(
	locations []string,
	options ScanOptions,
	after func(ScanState),
) (ScanState, error)

StartScanThenWithOptions starts a scan with explicit policy and follow-up.

func (*Catalog) StartScanWithOptions

func (c *Catalog) StartScanWithOptions(locations []string, options ScanOptions) (ScanState, error)

StartScanWithOptions starts a scan with an explicit missing-file policy.

func (*Catalog) StartThumbnailJob

func (c *Catalog) StartThumbnailJob(ctx context.Context, tools Tools, redo bool) (JobState, error)

StartThumbnailJob generates covers for videos the browser cannot reach: those never opened, and those it cannot decode at all.

func (*Catalog) Summary

func (c *Catalog) Summary(ctx context.Context) (Summary, error)

Summary returns indexed catalog counts without loading media rows.

func (*Catalog) ThumbnailDir

func (c *Catalog) ThumbnailDir() string

ThumbnailDir is where generated covers live: under the app data directory, never beside the user's media. Writing into someone's video folders is a surprise, and it makes the whole feature impossible to cleanly undo.

func (*Catalog) Video

func (c *Catalog) Video(ctx context.Context, id string) (Video, error)

Video returns one catalog row by opaque ID.

func (*Catalog) WaitForJob

func (c *Catalog) WaitForJob()

WaitForJob blocks until the running job finishes, or returns immediately when none is running. It exists for the scan follow-up, which has to let the thumbnail pass finish before asking for the single job slot again.

type Compatibility

type Compatibility string

Compatibility records what is known about whether a file plays in the browser that is actually running the UI.

Playability is a codec question at least as much as a container one, and that distinction is the whole reason this type exists. An .mp4 is a container every browser opens; an .mp4 holding HEVC does not play in Firefox, which ships no HEVC decoder on most platforms. Classifying by extension alone would call that file supported and never offer to fix it.

So the extension set below is a lower bound on what cannot play, never a claim about what can. Only CompatibilityPlayable is a positive statement, and only the browser can produce it.

const (
	// CompatibilityUnknown is a file in an openable container that has not been
	// played yet. Most rows sit here, and it is not a problem: the app makes no
	// claim it cannot support, and the first playback settles the question.
	CompatibilityUnknown Compatibility = "unknown"
	// CompatibilityPlayable is a file this browser has actually decoded. It is
	// the only compatibility value the app does not infer.
	CompatibilityPlayable Compatibility = "playable"
	// CompatibilityUnsupportedContainer is an extension the <video> element
	// will not open regardless of what is inside it.
	CompatibilityUnsupportedContainer Compatibility = "unsupported_container"
	// CompatibilityUnsupportedCodec is a file the browser opened and then
	// refused to decode. This is the case extension checks cannot reach.
	CompatibilityUnsupportedCodec Compatibility = "unsupported_codec"
)

func ContainerCompatibility

func ContainerCompatibility(path string) Compatibility

ContainerCompatibility classifies a path by extension alone. It returns unknown rather than playable for openable containers, because opening a container is not decoding its contents.

func (Compatibility) NeedsConversion

func (c Compatibility) NeedsConversion() bool

NeedsConversion reports whether repair would help. Conversion is repair only, so a file that plays is never a candidate no matter what else is true of it.

func (Compatibility) Valid

func (c Compatibility) Valid() bool

Valid reports whether a stored value is one this binary understands. A row written by a newer build is treated as unknown rather than trusted.

type ConversionAction

type ConversionAction string

ConversionAction is what repairing a file actually requires.

const (
	// ActionRemux copies both streams into MP4. Seconds, and lossless.
	ActionRemux ConversionAction = "remux"
	// ActionEncodeAudio keeps the video stream and re-encodes only audio.
	ActionEncodeAudio ConversionAction = "encode_audio"
	// ActionEncodeVideo re-encodes video, and audio only if it needs it.
	ActionEncodeVideo ConversionAction = "encode_video"
)

type ConversionPlan

type ConversionPlan struct {
	Action        ConversionAction `json:"action"`
	VideoCodec    string           `json:"video_codec"`
	AudioCodec    string           `json:"audio_codec"`
	TargetCodec   string           `json:"target_codec,omitempty"`
	DurationMilli int64            `json:"duration_ms"`
	// Lossless is true when no stream is re-encoded, which is worth saying in
	// the UI: it is the difference between ten seconds and an hour.
	Lossless bool `json:"lossless"`
}

ConversionPlan is the decision made from a probe, before any work starts.

func PlanConversion

func PlanConversion(info StreamInfo, settings config.MediaSettings) ConversionPlan

PlanConversion decides what a file needs. Remux is tried first rather than treated as an optimization: skipping it would turn a ten-second job into an hour-long one and degrade quality for no reason.

type ConversionProgress

type ConversionProgress struct {
	ProcessedMillis int64
	TotalMillis     int64
}

ConversionProgress reports how far a running conversion has reached.

type Effect

type Effect struct {
	// ActionsRemoved counts authored actions dropped by smoothing.
	ActionsRemoved int `json:"actions_removed,omitempty"`
	// PeakReductionPercent is the largest distance any rounded corner moved
	// away from its authored extreme.
	PeakReductionPercent float64 `json:"peak_reduction_percent,omitempty"`
}

Effect reports what the active filters actually changed, so the cost is visible rather than argued.

type Filters

type Filters struct {
	// SmoothingPercent removes extrema whose prominence is below it. Zero is off.
	SmoothingPercent int
	// PeakRoundingMillis rounds each direction change over this window on both
	// sides. Zero is off.
	PeakRoundingMillis int
}

Filters are opt-in playback transforms over a paired script. The zero value plays the script exactly as authored, which is the default everywhere: a media amplitude transform shipped once and collapsed subtle strokes toward the device's resolution floor (docs/motion-pathway-review-2026-07-20.md, 2026-07-22), so a filter that quietly changes motion has to be asked for.

type Funscript

type Funscript struct {
	VideoID        string            `json:"video_id"`
	Name           string            `json:"name"`
	DurationMillis int64             `json:"duration_ms"`
	ActionCount    int               `json:"action_count"`
	Actions        []FunscriptAction `json:"actions"`
	SourceIdentity string            `json:"-"`
}

Funscript is the bounded document returned to the browser and used to build the engine's clock-locked timeline. Filesystem paths never leave Catalog.

func (Funscript) TimelineFrom

func (f Funscript) TimelineFrom(
	mediaTimeMillis int64,
	playbackRate float64,
	filters Filters,
) (motion.MediaTimelineDefinition, Effect, error)

TimelineFrom slices and rate-scales the authored timeline at a video-clock anchor. The first point is linearly interpolated at the exact media time. Filters are applied after slicing so they act on what will actually play, and their measured effect is returned rather than estimated.

type FunscriptAction

type FunscriptAction struct {
	AtMillis int64 `json:"at"`
	Position int   `json:"pos"`
}

FunscriptAction is one validated timeline action.

type JobIssue

type JobIssue struct {
	Name    string `json:"name"`
	Message string `json:"message"`
}

JobIssue is one file that could not be processed. A job continues past a failure: one unreadable file should not abandon the other nine hundred.

type JobKind

type JobKind string

JobKind names the long media tasks. Both run through the same runner so progress, cancellation, and the one-at-a-time rule cannot drift apart.

const (
	// JobThumbnails generates covers FFmpeg has to produce.
	JobThumbnails JobKind = "thumbnails"
	// JobConversion repairs files that cannot play.
	JobConversion JobKind = "conversion"
)

type JobState

type JobState struct {
	Kind        JobKind `json:"kind,omitempty"`
	Running     bool    `json:"running"`
	Cancellable bool    `json:"cancellable"`
	Cancelled   bool    `json:"cancelled"`
	StartedAt   string  `json:"started_at,omitempty"`
	CompletedAt string  `json:"completed_at,omitempty"`
	CurrentName string  `json:"current_name,omitempty"`
	Total       int     `json:"total"`
	Processed   int     `json:"processed"`
	Succeeded   int     `json:"succeeded"`
	Failed      int     `json:"failed"`
	// ItemPercent is progress within the current file. Conversion reports it;
	// thumbnail capture is fast enough that it stays at zero.
	ItemPercent int        `json:"item_percent"`
	Issues      []JobIssue `json:"issues"`
	Error       string     `json:"error,omitempty"`
}

JobState is safe to poll while a job runs.

type ScanIssue

type ScanIssue struct {
	Location string `json:"location"`
	Message  string `json:"message"`
}

ScanIssue reports a root that could not be completely enumerated.

type ScanOptions

type ScanOptions struct {
	// RemoveMissing deletes rows absent from a completely enumerated root.
	// Partial and unavailable roots are preserved regardless of this value.
	RemoveMissing bool
	Trigger       ScanTrigger
}

ScanOptions are snapshotted when a scan starts.

func DefaultScanOptions

func DefaultScanOptions() ScanOptions

DefaultScanOptions returns the product defaults for direct callers.

type ScanState

type ScanState struct {
	Running         bool        `json:"running"`
	Trigger         ScanTrigger `json:"trigger,omitempty"`
	Cancellable     bool        `json:"cancellable"`
	Cancelled       bool        `json:"cancelled"`
	StartedAt       string      `json:"started_at,omitempty"`
	CompletedAt     string      `json:"completed_at,omitempty"`
	CurrentLocation string      `json:"current_location,omitempty"`
	FilesVisited    int         `json:"files_visited"`
	VideosFound     int         `json:"videos_found"`
	Summary         ScanSummary `json:"summary"`
	Error           string      `json:"error,omitempty"`
}

ScanState is safe to poll while a scan runs.

type ScanSummary

type ScanSummary struct {
	Locations int         `json:"locations"`
	Added     int         `json:"added"`
	Updated   int         `json:"updated"`
	Missing   int         `json:"missing"`
	Removed   int         `json:"removed"`
	Skipped   int         `json:"skipped"`
	Issues    []ScanIssue `json:"issues"`
}

ScanSummary is the durable-catalog delta from one scan.

type ScanTrigger

type ScanTrigger string

ScanTrigger identifies why a catalog scan started.

const (
	// ScanTriggerManual is a controller-requested scan.
	ScanTriggerManual ScanTrigger = "manual"
	// ScanTriggerStartup is an opted-in background scan during core startup.
	ScanTriggerStartup ScanTrigger = "startup"
)

type StreamInfo

type StreamInfo struct {
	VideoCodec     string
	AudioCodec     string
	DurationMillis int64
	HasVideo       bool
}

StreamInfo is the subset of a container probe that decides what conversion has to do. Everything else ffprobe reports is deliberately discarded.

type Summary

type Summary struct {
	AvailableCount int `json:"available_count"`
	VideoCount     int `json:"video_count"`
	PairedCount    int `json:"paired_count"`
}

Summary is the constant-size media snapshot used by the regular app poll.

type ToolStatus

type ToolStatus struct {
	Configured bool   `json:"configured"`
	Available  bool   `json:"available"`
	FFmpegPath string `json:"ffmpeg_path,omitempty"`
	Version    string `json:"version,omitempty"`
	Error      string `json:"error,omitempty"`
}

ToolStatus is the API view of the dependency, including the absent case.

type Tools

type Tools struct {
	FFmpegPath  string `json:"ffmpeg_path"`
	FFprobePath string `json:"ffprobe_path"`
	Version     string `json:"version"`
}

Tools is a verified pair of external binaries. It is produced only by ResolveTools, so holding one is proof the paths were identified rather than merely configured.

func ResolveTools

func ResolveTools(ctx context.Context, configuredPath string) (Tools, error)

ResolveTools verifies a configured FFmpeg and locates ffprobe beside it.

Identification is not a formality. The path is a user-supplied string that becomes argv[0] of a child process, so it is run once with a harmless argument and required to identify itself before it is ever handed a real input path. A binary that does not print an FFmpeg banner is rejected here rather than discovered mid-conversion.

func (Tools) Inspect

func (t Tools) Inspect(ctx context.Context, path string) (StreamInfo, error)

Inspect reads container metadata. It never decodes frames, so the cost is bounded by header size rather than by the length of the file.

type Video

type Video struct {
	ID                    string  `json:"id"`
	LocationPath          string  `json:"location_path"`
	RelativePath          string  `json:"-"`
	DisplayName           string  `json:"display_name"`
	SizeBytes             int64   `json:"size_bytes"`
	ModifiedAt            string  `json:"modified_at"`
	DurationMillis        *int64  `json:"duration_ms"`
	FunscriptRelativePath *string `json:"-"`
	HasFunscript          bool    `json:"has_funscript"`
	Missing               bool    `json:"missing"`
	ScannedAt             string  `json:"scanned_at"`
	// ScriptOffsetMillis calibrates this pairing alone. It adds to the setup
	// offset in settings rather than replacing it, because the two have
	// different causes: the setup value is the room, this one is the script.
	ScriptOffsetMillis int `json:"script_offset_ms"`
	// ThumbnailGeneratedAt records that a cover exists, so the grid does not
	// stat a file per tile and a missing asset is a knowable state rather than
	// a broken image.
	ThumbnailGeneratedAt *string `json:"thumbnail_generated_at"`
	// Compatibility is what is known about playing this file here. See the
	// Compatibility type: only "playable" is ever a positive claim.
	Compatibility Compatibility `json:"compatibility"`
	// VideoCodec and AudioCodec are filled by an ffprobe inspection and are
	// nil until one has run. They explain a compatibility verdict rather than
	// producing it.
	VideoCodec *string `json:"video_codec"`
	AudioCodec *string `json:"audio_codec"`
	// Superseded marks a row hidden because a converted copy sits beside it.
	Superseded bool `json:"superseded"`
	// ContainerType is the MIME type this file streams as. It is sent so the
	// client can ask its own engine whether it supports the container, which
	// beats any server-side table: MKV plays in Chrome and not in Firefox, and
	// only the browser in front of the user knows which one it is.
	ContainerType string `json:"container_type"`
}

Video is one scan-derived catalog row. Relative paths stay server-side; clients receive only the registered location and display metadata.

func (Video) NeedsConversion

func (v Video) NeedsConversion() bool

NeedsConversion reports whether this row is a repair candidate.

Jump to

Keyboard shortcuts

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