mediawrite

package
v0.10.0-dev.70 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Overview

Package mediawrite is the one writer of subtitle files beside videos. Each media root is its own os.Root keyed by its path; every change is staged behind a storage intent and published without replacing a file subflux cannot account for, so a crash or an outside writer never costs a file or its record.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidRef is a reference the writer cannot act on: an unknown
	// instance, a name that is not one local subtitle element, or a supersede
	// naming another instance.
	ErrInvalidRef = errors.New("mediawrite: invalid file reference")
	// ErrExpectation is a file whose bytes or record moved since the caller
	// listed it, or the zero Expectation of an unmanaged file listed without
	// hashing; nothing changed.
	ErrExpectation = errors.New("mediawrite: file changed since it was listed")
	// ErrPathPending is a name an unsettled write still owns.
	ErrPathPending = errors.New("mediawrite: a write to this file is pending")
	// ErrNameContended is a delivery whose name an outside writer took, or
	// whose numbered names were all taken.
	ErrNameContended = errors.New("mediawrite: no free name for the subtitle")
	// ErrOutsideRoot is a video no configured media root contains.
	ErrOutsideRoot = errors.New("mediawrite: video is outside every media root")
	// ErrRootUnavailable is a video whose root is configured but unmounted,
	// empty, read-only, hung or not yet recovered.
	ErrRootUnavailable = errors.New("mediawrite: media root unavailable")
)
View Source
var Codes = slices.Concat([]struct {
	Err  error
	Code string
}{
	{ErrInvalidRef, "param_invalid"},
	{ErrExpectation, "file_changed"},
	{ErrPathPending, "write_pending"},
	{ErrOutsideRoot, "outside_root"},
	{ErrRootUnavailable, "media_root_unavailable"},
}, timing.Codes)

Codes is every sentinel the api-called exports return (List, Current, Retime, Delete, OpenVideo, DecodeRef, ValidName), timing's passed on, with the code api answers for it. ErrNameContended is absent: only Deliver returns it, and only search calls Deliver.

View Source
var Schema = formschema.Schema{Fields: []formschema.Field{
	{
		Key: fieldStripHI, Label: "Strip hearing-impaired notes", Kind: formschema.Bool, Default: off,
		Help: "Remove notes for deaf and hard-of-hearing viewers, such as [music], (laughs) and speaker labels.",
	},
	{
		Key: fieldStripTags, Label: "Strip formatting tags", Kind: formschema.Bool, Default: on,
		Help: "Remove <i>, <b>, <u>, <s> and <font> tags.",
	},
	{
		Key: fieldNormalizeUTF8, Label: "Convert to UTF-8", Kind: formschema.Bool, Default: on,
		Help: "Convert UTF-16, Windows-1252 and the other encodings subflux recognizes to UTF-8. A file in an encoding it cannot tell keeps its bytes.",
	},
	{
		Key: fieldNormalizeLineEndings, Label: "Standard line endings", Kind: formschema.Bool, Default: on,
		Help: "Convert line endings to CRLF, the SRT standard.",
	},
	{
		Key: fieldCleanWhitespace, Label: "Clean whitespace", Kind: formschema.Bool, Default: on,
		Help: "Trim spaces at either end of each line and remove lines left empty.",
	},
	{
		Key: fieldRemoveEmpty, Label: "Remove empty subtitles", Kind: formschema.Bool, Default: on,
		Help: "Drop subtitle lines left with no text, renumbering the rest.",
	},
}}

Schema is the post_processing section's form: what Deliver does to a downloaded subtitle before it writes it.

Functions

func ValidName

func ValidName(name string) error

ValidName is DecodeRef's syntax check with no instance: one local path element with an extension subtitleext.OnDisk accepts, else ErrInvalidRef.

Types

type Alerts

type Alerts interface {
	Reconcile(source status.AlertSource, active bool, text string)
	RetainAlerts(kind string, live []status.AlertSource)
}

Alerts is declared here, its caller; status.Store implements it.

type Config

type Config struct {
	Clean timing.CleanOptions
}

Config is the post_processing section: the options Deliver cleans a subtitle with before it renders it. ParseConfig fills its defaults.

func ParseConfig

func ParseConfig(n *yaml.Node) (Config, []formschema.FieldError)

ParseConfig decodes the post_processing section, n being its node or nil when absent, reporting each error at post_processing.<key>.

type Delivery

type Delivery struct {
	Timing     timing.Timing
	Target     language.Tag
	Tag        language.Tag
	Supersedes []Superseded
	Rejected   []statedb.Download
	Cues       timing.Cues
	Provenance statedb.Provenance
	Attempt    int
	Inst       statedb.InstanceID
	Candidate  [32]byte
	Run        statedb.RunID
	Flags      language.Flags
	Variant    language.Variant
	Lock       bool
	Numbered   bool
}

Delivery is one subtitle a search run delivers for an instance. Tag and Flags are the candidate's own, so a substitute says on disk what it is; Target and Variant are what it serves, and Lock locks that pair on every item of the instance. Candidate keys the delivered attempt in the attempt memory; Rejected are the run's other attempts, all undelivered.

type Deps

type Deps struct {
	Store  *statedb.Store
	Roots  Roots
	Alerts Alerts
	Policy func() language.Policy
	Logger *slog.Logger
}

Deps is what New needs; every field but Logger is required. Policy reads the language policy in force, which judges which supersedes are safe.

type Expectation

type Expectation struct {
	Generation uint64
	SHA256     [32]byte
}

Expectation is the state of a file a caller saw: the record's generation (0 for an unmanaged file) and the bytes' SHA-256. The zero value is an unmanaged file listed without hashing, which every write refuses.

type FileRef

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

FileRef names one subtitle file beside an instance's video. Its zero value names nothing; DecodeRef and RefOf build it.

func DecodeRef

func DecodeRef(inst statedb.InstanceID, name string) (FileRef, error)

DecodeRef builds the reference of name beside inst's video from wire input: ErrInvalidRef for the zero instance or a name ValidName refuses.

func RefOf

func RefOf(rec statedb.FileRecord) FileRef

RefOf is the reference of a stored record.

func (FileRef) Inst

func (r FileRef) Inst() statedb.InstanceID

Inst is the instance whose video the file is beside.

func (FileRef) Name

func (r FileRef) Name() string

Name is the file's name in the video's directory.

type FolderState

type FolderState uint8

FolderState is what one check of a reported folder found. Zero is invalid.

const (
	FolderOutside FolderState = iota + 1
	FolderUnavailable
	FolderFound
	FolderMissing
)

The folder states: no configured root contains the folder; its root cannot be opened or the check overran; a directory; absent or not a directory.

func (FolderState) MarshalText

func (s FolderState) MarshalText() ([]byte, error)

MarshalText is outside, unavailable, found or missing, refusing any other value.

func (*FolderState) UnmarshalText

func (s *FolderState) UnmarshalText(b []byte) error

UnmarshalText reads exactly what MarshalText writes, leaving s unchanged on a refusal.

type Found

type Found struct {
	File FileRef
	statedb.LocalFile
	Expect  Expectation
	Ordinal int
	Managed bool
}

Found is one subtitle file of an instance as List read it.

type Inventory

type Inventory struct {
	Files      []Found
	Unparsed   []string
	Unwritable bool
}

Inventory is every subtitle name an instance's video owns: Files the names the grammar reads, Unparsed the owned names it does not (or a name two videos sharing a stem both claim). Unwritable is set while the video directory is remembered as refusing stage creation under a root whose write probe passed.

type ListOptions

type ListOptions struct{ UnmanagedExpect bool }

ListOptions is List's argument. With UnmanagedExpect false an unmanaged Found carries the zero Expectation, which every write refuses, and no unmanaged byte is read; with it set, so does one that cannot be read or is over 16 MiB.

type Roots

type Roots interface {
	MediaRoots(ctx context.Context) []string
}

Roots lists the configured media roots, absolute paths as subflux sees them.

type Superseded

type Superseded struct {
	File   FileRef
	Expect Expectation
}

Superseded is a file a delivery replaces, as the caller listed it.

type Timed

type Timed struct {
	Timing  timing.Timing
	Outcome *timing.Outcome
	Tag     language.Tag
	Cues    timing.Cues
	Flags   language.Flags
	Rigid   bool
}

Timed is a file as Current reads it, all under one confirmed expectation. Flags are the record's, or an unmanaged name's as the grammar reads them; Outcome is the record's timing outcome, nil for an unmanaged or adopted file; Rigid is set when the record's facts say the subtitle is of a different cut, whatever Decision it holds, so no later path gives it a model past Linear or runs audio for it.

type Writer

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

Writer serializes every write to the files beside each video and keeps each root's availability. Construct it with New and run Run; every call made before Run's first probe of the call's root waits for it.

func New

func New(d Deps) *Writer

New returns a Writer over d, whose post_processing section is the zero Config until SetConfig. It panics on a missing required dependency.

func (*Writer) Current

func (w *Writer) Current(ctx context.Context, ref FileRef, expect Expectation) (Timed, error)

Current returns, under one confirmation of expect, a record's baseline, timing, outcome, flags and rigidity, or an unmanaged file's parsed bytes at Identity with its name's flags.

func (*Writer) Delete

func (w *Writer) Delete(ctx context.Context, ref FileRef, expect Expectation) error

Delete removes ref's file after confirming expect under the leases, with its record, or for an unmanaged file its place among the local files. A .sub is ErrFormatUnsupported: removing it alone would orphan its .idx.

func (*Writer) Deliver

func (w *Writer) Deliver(ctx context.Context, d Delivery) (statedb.FileRecord, error)

Deliver cleans and renders d under the post_processing section, publishes it beside the instance's video without replacing any file it cannot account for, removes each superseded file still holding its listed bytes that no other configured pair needs, and returns the landed record. It records d's attempt rows exactly once: through RecordAttempts when it fails before staging its intent and d's Run and Attempt are valid, else when the intent settles, here or in recovery. ErrNameContended is a name an outside writer took or eight numbered names all taken.

func (*Writer) FolderState

func (w *Writer) FolderState(ctx context.Context, path string) FolderState

FolderState checks path with one Lstat through the deepest containing root's os.Root (its live handle, else one opened for the call and closed after it) within rootProbeTimeout. Each root runs one check at a time, its open and Lstat included: a call that cannot take the root's slot or finish its check in time answers FolderUnavailable, and an overrun check keeps the slot until its syscall returns.

func (*Writer) List

func (w *Writer) List(ctx context.Context, inst statedb.InstanceID, opts ListOptions) (Inventory, error)

List reads the instance's video directory once under the instance lease and reconciles it: a managed name whose file is gone or changed loses its record and baseline, a changed file becoming the user's; a name with a pending write is skipped. A managed file confirms by size and mtime, else by its hash; one that cannot be read keeps its record and is listed with the record's expectation. A directory that cannot be read or no longer holds the video answers an error and changes nothing.

func (*Writer) OpenVideo

func (w *Writer) OpenVideo(ctx context.Context, inst statedb.InstanceID) (*os.File, error)

OpenVideo opens the instance's video through its root's os.Root, so a symlink can resolve only inside the root, and refuses a non-regular file. The caller closes it. It answers ErrInvalidRef for an unknown instance, ErrOutsideRoot and ErrRootUnavailable as a write does, and any other failure as the path's wrapped error.

func (*Writer) Retime

func (w *Writer) Retime(ctx context.Context, ref FileRef, expect Expectation, tm timing.Timing, outcome *timing.Outcome) (statedb.FileRecord, error)

Retime renders ref's baseline under tm over the file, after confirming expect under the leases, and returns the landed record. An unmanaged file is adopted as a Locked record with no provenance, its bytes the baseline; one whose name has no language is ErrInvalidRef. The record keeps its Decision and Facts; a non-nil outcome (a sync apply) supplies the rest, and nil is a user edit: MethodNone, confidence 0, Verified, tm's offset. Equal bytes update only the record. A result past 16 MiB, or a file timing cannot parse, is ErrFormatUnsupported with nothing changed.

func (*Writer) RootsChanged

func (w *Writer) RootsChanged()

RootsChanged asks Run for a probe pass now, which re-reads Roots; the caller changing what MediaRoots answers calls it after each change. Requests made while one is pending coalesce.

func (*Writer) Run

func (w *Writer) Run(ctx context.Context) error

Run reads the root set and probes every root at once, then every 5 minutes and after each RootsChanged, until ctx ends; it returns nil once the recovery attempts it started have returned. Each probe runs in its own goroutine, one outstanding per root: a probe stuck in a hung mount's syscall outlives Run and is discarded when it returns. After each probe the root's pending writes are recovered, and a call under a root that returned waits for or fails during that recovery.

func (*Writer) SetConfig

func (w *Writer) SetConfig(c Config)

SetConfig replaces the post_processing section, which applies from the next Deliver.

Jump to

Keyboard shortcuts

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