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
- Variables
- func CatalogedExtension(extension string) bool
- func ContainerType(path string) string
- func ConvertedName(relativePath string) string
- func HasConvertedSuffix(relativePath string) bool
- type Catalog
- func (c *Catalog) CancelJob() JobState
- func (c *Catalog) CancelScan() ScanState
- func (c *Catalog) ClearThumbnails(ctx context.Context) (int, error)
- func (c *Catalog) Close() error
- func (c *Catalog) FunscriptSourceIdentity(ctx context.Context, id string) (string, error)
- func (c *Catalog) JobState() JobState
- func (c *Catalog) List(ctx context.Context) ([]Video, error)
- func (c *Catalog) LoadFunscript(ctx context.Context, id string) (Funscript, error)
- func (c *Catalog) OpenFunscript(ctx context.Context, id string) (*os.File, Video, error)
- func (c *Catalog) OpenThumbnail(ctx context.Context, id string) (*os.File, error)
- func (c *Catalog) OpenVideo(ctx context.Context, id string) (*os.File, Video, error)
- func (c *Catalog) RetainLocations(ctx context.Context, locations []string) (int64, error)
- func (c *Catalog) SaveThumbnail(ctx context.Context, id string, image []byte) error
- func (c *Catalog) ScanState() ScanState
- func (c *Catalog) SetCompatibility(ctx context.Context, id string, state Compatibility) error
- func (c *Catalog) SetDuration(ctx context.Context, id string, durationMillis int64) error
- func (c *Catalog) SetScriptOffset(ctx context.Context, id string, offsetMillis int) error
- func (c *Catalog) StartConversionJob(ctx context.Context, tools Tools, settings config.MediaSettings, ids []string) (JobState, error)
- func (c *Catalog) StartScan(locations []string) (ScanState, error)
- func (c *Catalog) StartScanThen(locations []string, after func(ScanState)) (ScanState, error)
- func (c *Catalog) StartScanThenWithOptions(locations []string, options ScanOptions, after func(ScanState)) (ScanState, error)
- func (c *Catalog) StartScanWithOptions(locations []string, options ScanOptions) (ScanState, error)
- func (c *Catalog) StartThumbnailJob(ctx context.Context, tools Tools, redo bool) (JobState, error)
- func (c *Catalog) Summary(ctx context.Context) (Summary, error)
- func (c *Catalog) ThumbnailDir() string
- func (c *Catalog) Video(ctx context.Context, id string) (Video, error)
- func (c *Catalog) WaitForJob()
- type Compatibility
- type ConversionAction
- type ConversionPlan
- type ConversionProgress
- type Effect
- type Filters
- type Funscript
- type FunscriptAction
- type JobIssue
- type JobKind
- type JobState
- type ScanIssue
- type ScanOptions
- type ScanState
- type ScanSummary
- type ScanTrigger
- type StreamInfo
- type Summary
- type ToolStatus
- type Tools
- type Video
Constants ¶
const ( // MaxMediaFunscriptBytes bounds the paired document read into memory. MaxMediaFunscriptBytes int64 = 16 << 20 // MaxMediaFunscriptActions bounds parsing, API output, and engine content. MaxMediaFunscriptActions = motion.MaximumMediaTimelinePoints )
const ( // MaxScanDepth bounds recursion below each registered root. MaxScanDepth = 6 // MaxFilesPerLocation bounds all encountered regular files, not just videos. MaxFilesPerLocation = 10_000 )
const ConvertedExtension = ".mp4"
ConvertedExtension is the only container conversion targets.
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.
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 ¶
var ( // ErrVideoNotFound reports an unknown catalog identifier. ErrVideoNotFound = errors.New("media video not found") 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 = 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") )
var ( // 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") )
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") )
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") )
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 ¶
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 ¶
ContainerType returns the MIME type for a path, or empty when unknown.
func ConvertedName ¶
ConvertedName returns the output name for a source path: the basename gains the reserved suffix and the extension becomes .mp4.
func HasConvertedSuffix ¶
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 OpenWithDatabase ¶
OpenWithDatabase borrows the process-owned datastore.
func (*Catalog) CancelJob ¶
CancelJob requests cancellation. State stays running until the worker has stopped touching the filesystem and database.
func (*Catalog) CancelScan ¶
CancelScan requests cancellation. State remains running until the worker has stopped touching the filesystem and database.
func (*Catalog) ClearThumbnails ¶
ClearThumbnails removes every generated cover and forgets that any existed, making the whole storage cost recoverable in one step.
func (*Catalog) FunscriptSourceIdentity ¶
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) LoadFunscript ¶
LoadFunscript opens and parses the exact-basename pair for one video.
func (*Catalog) OpenFunscript ¶
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 ¶
OpenThumbnail opens a stored cover for serving.
func (*Catalog) OpenVideo ¶
OpenVideo revalidates the catalog jail and opens a regular file for http.ServeContent. No HTTP endpoint accepts a filesystem path.
func (*Catalog) RetainLocations ¶
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 ¶
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) SetCompatibility ¶
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 ¶
SetDuration stores browser-decoded metadata without probing media in Go.
func (*Catalog) SetScriptOffset ¶
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) StartScanThen ¶
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 ¶
StartThumbnailJob generates covers for videos the browser cannot reach: those never opened, and those it cannot decode at all.
func (*Catalog) ThumbnailDir ¶
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) 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 ¶
ConversionProgress reports how far a running conversion has reached.
type Effect ¶
type Effect struct {
ActionsRemoved int `json:"actions_removed,omitempty"`
}
Effect records source actions removed before engine compilation. Continuous rounding measurements come from the resulting engine plan, not a point plot.
type Filters ¶
Filters are opt-in playback transforms. Zero preserves the authored script. Smoothing only removes small, rapid excursions; rounding is compiled by the shared engine after the optional speed cap, with its actual effect reported.
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 ¶
FunscriptAction is one validated timeline action.
type JobIssue ¶
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.
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 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 ¶
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 ¶
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.
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 ¶
NeedsConversion reports whether this row is a repair candidate.