timing

package
v0.10.0-dev.56 Latest Latest
Warning

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

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

Documentation

Overview

Package timing is subflux's subtitle timing model: a Timing maps each cue's baseline time to the time a media server shows it, and every managed file is its baseline rendered under one Timing.

Index

Constants

View Source
const CodecVersion uint16 = 1

CodecVersion names AppendTiming's and AppendCues' encodings and ParseCues' event rules. Storage folds it into every codec holding them, so a change to any of the three must bump it, or stored baselines re-parse to other events than the ones their timings were fitted to.

View Source
const PreviewSpan = 10 * time.Minute

PreviewSpan is the media one preview window covers from its start.

Variables

View Source
var (
	// ErrTimingInvalid is a Timing outside Validate's rules, or timing bytes
	// DecodeTiming cannot read.
	ErrTimingInvalid = errors.New("invalid timing")
	// ErrFormatUnsupported is a subtitle document no parser here reads.
	ErrFormatUnsupported = errors.New("unsupported subtitle format")
)
View Source
var Codes = []struct {
	Err  error
	Code string
}{
	{ErrTimingInvalid, "timing_invalid"},
	{ErrFormatUnsupported, "format_unsupported"},
}

Codes is every sentinel timing's exported calls return, with the code api answers for it. The element type is unnamed, so timing never imports api's wirespec.

View Source
var Schema = formschema.Schema{Fields: []formschema.Field{
	{
		Key: keySync, Label: "Sync timing", Kind: formschema.Bool, Default: "true",
		Help: "Re-time each downloaded subtitle against a subtitle track inside the video.",
	},
	{
		Key: keyAudioFallback, Label: "Audio fallback", Kind: formschema.Bool, Default: "false",
		Help: "Also try the video's speech when its subtitle tracks cannot verify a download's timing. Slower, and it can spot a different cut only when the video also has a usable subtitle track.",
	},
}}

Schema is the timing section's form. It has no confidence setting: the reference and audio gates sit on different measures, so one number would gate one of them wrongly.

Functions

func AppendCues

func AppendCues(b []byte, c Cues) []byte

AppendCues appends c's encoding to b: a layout byte, the format and encoding bytes, and the document as a uvarint length and its bytes. The zero Cues encodes as bytes DecodeCues refuses.

func AppendTiming

func AppendTiming(b []byte, t Timing) []byte

AppendTiming appends t's encoding to b: a kind byte, then zig-zag varints for every millisecond field, Scale as its big-endian IEEE 754 bits, and a Piecewise's segment count as a uvarint. A t failing Validate encodes as bytes DecodeTiming refuses.

func OffsetMs

func OffsetMs(t Timing) int64

OffsetMs is the offset t applies at the start of the baseline: a Shift's, a Linear's, a Piecewise's first kept segment's; 0 for Identity.

func Render

func Render(c Cues, t Timing) ([]byte, error)

Render writes c's document under t, rewriting only timestamp spans. A cue mapped to end at or before 0, or starting in a Drop segment, is removed with its SRT block or ASS line, and the remaining SRT indexes renumber from 1; one mapped to start before 0 starts at 0. Times round to 1 ms for SRT and 10 ms for ASS and SSA; a stamp the mapping leaves unchanged keeps its bytes. It refuses, as ErrTimingInvalid, a t failing Validate and a time past the format's last stamp (ASS 9:59:59.99), and, as ErrFormatUnsupported, the zero Cues.

func RenderVTT

func RenderVTT(c Cues, t Timing, from time.Duration) ([]byte, error)

RenderVTT renders the events Render would write under t as WebVTT for the preview window [from, from+PreviewSpan): the events meeting it, shifted by -from and clipped to it, since the preview fragment starts at time 0. A player styles SRT's <i>, <b> and <u> and hides other SRT tags, so in SRT those six exact tags pass and other tags are removed; ASS override blocks are removed, every other '&', '<' and '>' is escaped, and "-->" is broken by U+2060. It refuses what Render refuses, and a negative from as ErrTimingInvalid.

func StripHI

func StripHI(text string) string

StripHI removes hearing-impaired annotations from one event's decoded text, its lines separated by "\n": [...], (...) and ♪...♪ spans, speaker labels at a line start (JOHN:, DR. SMITH:), and lines of only notes. It is the one HI rule: Clean's strip_hi and subsync's dialogue filter both call it. Text is read as UTF-8, an invalid sequence as U+FFFD.

func Validate

func Validate(t Timing) error

Validate is the one Timing check: it refuses, as ErrTimingInvalid, a nil or unknown Timing, an offset past ±6 h, a Scale outside [0.9, 1.1], a Piecewise of fewer than 2 or more than 2,048 segments, whose first FromMs is not 0, whose segments do not chain or end past 24 h, or whose last ToMs is not 0, and any form Canonical would change.

Types

type Action

type Action uint8

Action is what a timing pass does with a subtitle.

const (
	Skip Action = iota + 1
	ActionReference
	ReferenceThenAudio
	// RigidReference syncs by Shift or Linear only and runs no audio: the
	// answer for a flagged different cut.
	RigidReference
)

The actions; the zero Action is none.

func (Action) MarshalText

func (a Action) MarshalText() ([]byte, error)

MarshalText answers the action's snake_case name and refuses the zero Action.

func (*Action) UnmarshalText

func (a *Action) UnmarshalText(b []byte) error

UnmarshalText reads a name MarshalText writes and leaves a on error.

type CleanOptions

type CleanOptions struct {
	StripHI, StripTags, CleanWhitespace, RemoveEmpty bool
	NormalizeUTF8, NormalizeLineEndings              bool
}

CleanOptions is the post_processing section's content; mediawrite owns the section and passes these.

type Config

type Config struct{ Sync, AudioFallback bool }

Config is the timing section. Its zero value turns sync off; an absent section is ParseConfig(nil).

func ParseConfig

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

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

type Cues

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

Cues is a parsed subtitle document: its bytes, Format and encoding, and per event its times and the byte spans of its timestamps, text and block. The zero Cues holds no document.

func Clean

func Clean(c Cues, opts CleanOptions, tag language.Tag) (Cues, error)

Clean applies opts to c once, at delivery, in time linear in the document, and returns the result parsed under the encoding Detect names with tag as the hint. The text options edit event text by textRules, outside ASS and SSA {...} blocks, as deletions of the original bytes; RemoveEmpty removes an event left with no text and renumbers SRT indexes. Other bytes change only by NormalizeUTF8 (an Unknown encoding keeps its bytes) and NormalizeLineEndings (CRLF). A result ParseCues refuses, and the zero Cues, is ErrFormatUnsupported.

func DecodeCues

func DecodeCues(b []byte) (Cues, error)

DecodeCues reads exactly one AppendCues encoding and re-parses the document under the stored encoding. It refuses, as ErrFormatUnsupported, truncated bytes, an encoding byte subtitleenc does not declare, a document over 32 MiB, one that no longer parses, and any bytes AppendCues would not write for the Cues they parse to: another layout, a stored format the document does not parse as, a wrong or overlong length, trailing bytes.

func ParseCues

func ParseCues(b []byte) (Cues, error)

ParseCues decides the format from the bytes, never a name: SRT, ASS, SSA, or WebVTT converted to SRT. Anything else, an empty document, one over 16 MiB or 100,000 events, a WebVTT timestamp past 999:59:59.999, or one in an encoding whose timestamps cannot be found without decoding (ISO-2022-JP), is ErrFormatUnsupported. The error text names what was found where the bytes say: an archive or VobSub container, MicroDVD, binary data. The encoding is detected with no language hint.

func (Cues) Events

func (c Cues) Events() []Event

Events returns every timed event in document order.

func (Cues) Format

func (c Cues) Format() Format

Format is the one answer to the document's format.

type Decision

type Decision struct {
	Action Action
	Skip   SkipReason
}

Decision is a timing pass's plan for one subtitle.

func Plan

func Plan(f rank.Facts, v language.Variant, cfg Config) Decision

Plan decides one subtitle's timing pass from its release facts, the variant it serves and the timing section, in order: sync off is Skip/Disabled, a validated hash Skip/Hash, a forced variant Skip/Forced, the same release Skip/SameRelease; a flagged different cut is RigidReference, whatever AudioFallback holds; otherwise ReferenceThenAudio with AudioFallback on, else ActionReference.

type Event

type Event struct {
	// Text is the decoded view: line breaks as \n, ASS override tags kept.
	Text           string
	Style          string // ASS and SSA only
	StartMs, EndMs int64
}

Event is one cue as the dialogue filter reads it: an SRT cue or an ASS or SSA Dialogue line (Comment lines are kept as bytes and never timed).

type Format

type Format uint8

Format is a subtitle document format; its file extension is .srt, .ass or .ssa.

const (
	SRT Format = iota + 1
	ASS
	SSA
)

The formats; the zero Format is none.

func (Format) MarshalText

func (f Format) MarshalText() ([]byte, error)

MarshalText answers srt, ass or ssa and refuses the zero Format.

func (*Format) UnmarshalText

func (f *Format) UnmarshalText(b []byte) error

UnmarshalText reads a name MarshalText writes and leaves f on error.

type Identity

type Identity struct{}

Identity leaves every cue where the baseline has it.

type Linear

type Linear struct {
	Scale    float64
	OffsetMs int64
}

Linear maps baseline time t to t*Scale + OffsetMs.

type Method

type Method uint8

Method is what decided a delivered Timing.

const (
	MethodNone Method = iota
	MethodReference
	Audio
)

The methods; MethodNone when the pass was skipped or had no reference.

func (Method) MarshalText

func (m Method) MarshalText() ([]byte, error)

MarshalText answers the method's snake_case name, "none" included.

func (*Method) UnmarshalText

func (m *Method) UnmarshalText(b []byte) error

UnmarshalText reads a name MarshalText writes and leaves m on error.

type Outcome

type Outcome struct {
	Confidence float64
	OffsetMs   int64
	Decision   Decision
	Method     Method
	Verdict    Verdict
}

Outcome records one timing pass. Confidence is finite in [0, 1] and is read per Method, never compared across methods; OffsetMs is within ±6 h.

type Piecewise

type Piecewise struct {
	Segments []Segment
	Scale    float64
}

Piecewise maps a cue at baseline time t in segment s to t*Scale + s.OffsetMs. The last segment's ToMs is 0, meaning open-ended.

type Segment

type Segment struct {
	FromMs, ToMs, OffsetMs int64
	Drop                   bool
}

Segment covers baseline time [FromMs, ToMs); a cue belongs to the segment holding its baseline start. Drop removes the cues starting in it.

type Shift

type Shift struct{ Ms int64 }

Shift maps baseline time t to t + Ms.

type SkipReason

type SkipReason uint8

SkipReason says why a Decision skips; it is SkipReasonNone exactly when the Action is not Skip.

const (
	SkipReasonNone SkipReason = iota
	Hash
	SameRelease
	Forced
	Disabled
)

The skip reasons: a validated hash, the same release, a forced variant, or sync turned off.

func (SkipReason) MarshalText

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

MarshalText answers the reason's snake_case name, "none" included.

func (*SkipReason) UnmarshalText

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

UnmarshalText reads a name MarshalText writes and leaves s on error.

type Timing

type Timing interface {
	// contains filtered or unexported methods
}

Timing is Identity, Shift, Linear or Piecewise. A valid Timing is in its canonical form (see Canonical), so a Timing is applied exactly when it is not Identity{}.

func Canonical

func Canonical(t Timing) Timing

Canonical returns t in its canonical form: a Piecewise with no Drop and one OffsetMs is Linear, a Linear with Scale 1 is Shift, Shift{0} is Identity. Every producer canonicalizes before Validate, which refuses any other form. A t outside Validate's bounds is returned unchanged, so a malformed value never collapses into a valid one.

func DecodeTiming

func DecodeTiming(b []byte) (Timing, error)

DecodeTiming reads exactly one AppendTiming encoding. It refuses, as ErrTimingInvalid, an unknown kind, truncated or trailing bytes, a value failing Validate, and any encoding AppendTiming would not write for the value it holds, so every accepted Timing has one byte form.

type Verdict

type Verdict uint8

Verdict is how far a delivered Timing is trusted.

const (
	Trusted Verdict = iota + 1
	Verified
	Unverified
)

The verdicts: Trusted when the pass was skipped, Verified when a gate passed or a user edited the timing, Unverified otherwise (shown to users as "Timing unverified"). The zero Verdict is none.

func (Verdict) MarshalText

func (v Verdict) MarshalText() ([]byte, error)

MarshalText answers the verdict's snake_case name and refuses the zero Verdict.

func (*Verdict) UnmarshalText

func (v *Verdict) UnmarshalText(b []byte) error

UnmarshalText reads a name MarshalText writes and leaves v on error.

Jump to

Keyboard shortcuts

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