ass

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 14 Imported by: ? 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 ass reads, writes, and styles Advanced SubStation Alpha subtitles.

Index

Constants

View Source
const (
	FontDejaVuSans               = "DejaVu Sans"
	FontDejaVuSerif              = "DejaVu Serif"
	FontDejaVuSansMono           = "DejaVu Sans Mono"
	FontTikTokSans               = "TikTok Sans"
	FontBarlowCondensedExtraBold = "Barlow Condensed ExtraBold"
	FontAnton                    = "Anton"
	FontTheBold                  = "THE BOLD FONT (FREE VERSION)"
)

Built-in preset fonts. Custom presets may name any installed font family.

View Source
const (
	PresetBlackGold = "black-gold"
	// DefaultPreset is the look used when a caller does not choose one.
	DefaultPreset = PresetBlackGold
)

Preset names referenced outside the preset table.

View Source
const (
	EdgeTop    = "top"
	EdgeBottom = "bottom"
	EdgeLeft   = "left"
	EdgeRight  = "right"
)

Edges named in a SafeAreaIssue.

View Source
const (

	// SafeAreaAll is the name of the area that clears every listed platform.
	SafeAreaAll = "all"
)

Platform safe areas on a 1080 x 1920 vertical video, from each platform's own guidance:

  • TikTok: the In-Feed Standard LTR safe zone template on TikTok's In-Feed ads page, measured from the image. The right edge widens below y=840, where the like, comment and share buttons sit.
  • YouTube Shorts: Google's Universal Video Ad Safe Zones, vertical video.
  • Instagram Reels: Meta's Reels ad guide, about 14% top, 35% bottom and 6% on each side.

Variables

View Source
var (
	ErrInvalidDocument = errors.New("invalid ASS document")
	ErrInputTooLarge   = errors.New("ASS input exceeds 64 MiB")
)

Errors specific to ASS documents. Missing entries wrap commerr.ErrNotFound and rejected values wrap commerr.ErrInvalidValue from github.com/psyb0t/ctxerrors/commerr.

Functions

func EscapeText added in v0.2.0

func EscapeText(text string) string

EscapeText makes plain text safe to put in an event: an opening brace would otherwise start an override block and hide the text after it. libass shows the escaped brace; VSFilter shows a backslash followed by the text.

Types

type Alignment

type Alignment int

Alignment represents text positioning using numpad-style layout

const (
	AlignmentBottomLeft   Alignment = 1
	AlignmentBottomCenter Alignment = 2
	AlignmentBottomRight  Alignment = 3
	AlignmentMiddleLeft   Alignment = 4
	AlignmentMiddleCenter Alignment = 5
	AlignmentMiddleRight  Alignment = 6
	AlignmentTopLeft      Alignment = 7
	AlignmentTopCenter    Alignment = 8
	AlignmentTopRight     Alignment = 9
)

func (Alignment) Ptr

func (a Alignment) Ptr() *Alignment

Ptr returns a pointer to a copy of a, for optional fields.

type Alpha

type Alpha string

Alpha holds an ASS transparency value from 00 for opaque to FF for transparent.

const (
	AlphaOpaque      Alpha = "&H00&"
	AlphaTransparent Alpha = "&HFF&"
	AlphaHalf        Alpha = "&H80&"
)

Alpha values for opaque, fully transparent and half transparent.

func (Alpha) Ptr added in v0.1.0

func (a Alpha) Ptr() *Alpha

Ptr returns a pointer to a copy of a, for optional Override fields.

type BoldWeight

type BoldWeight int

BoldWeight represents predefined weights for bold text

const (
	BoldWeightNone   BoldWeight = 0
	BoldWeightNormal BoldWeight = 1
	BoldWeightBold   BoldWeight = 700
	BoldWeightBolder BoldWeight = 900
)

func (BoldWeight) Ptr

func (b BoldWeight) Ptr() *BoldWeight

Ptr returns a pointer to a copy of b, for optional fields.

type BorderStyle

type BorderStyle int

BorderStyle represents the type of border to draw around text

const (
	BorderStyleOutlineDropShadow BorderStyle = 1
	// BorderStyleOpaqueBox draws a box behind each line, colored by OutlineColor.
	BorderStyleOpaqueBox BorderStyle = 3
	// BorderStyleEventBox is a libass extension: one box behind the whole event,
	// colored by ShadowColor and padded by Shadow. VSFilter draws it as style 1.
	BorderStyleEventBox BorderStyle = 4
)

func (BorderStyle) Ptr

func (b BorderStyle) Ptr() *BorderStyle

Ptr returns a pointer to a copy of b, for optional fields.

type CaptionSpec

type CaptionSpec struct {
	Title        string
	Width        int
	Height       int
	Dialogues    []Dialogue
	Uppercase    bool
	WordsPerLine int
}

CaptionSpec supplies timed lines and the visual settings for a new caption script.

type Clip

type Clip struct {
	X1      float64
	Y1      float64
	X2      float64
	Y2      float64
	Inverse bool
}

Clip limits drawing to a rectangle, or to everything outside it when Inverse is set.

type Color

type Color string

Color holds an ASS color in BGR or ABGR format.

const (
	ColorWhite   Color = "&H00FFFFFF"
	ColorBlack   Color = "&H00000000"
	ColorRed     Color = "&H000000FF"
	ColorGreen   Color = "&H0000FF00"
	ColorBlue    Color = "&H00FF0000"
	ColorYellow  Color = "&H0000FFFF"
	ColorMagenta Color = "&H00FF00FF"
	ColorCyan    Color = "&H00FFFF00"

	ColorGray      Color = "&H00808080"
	ColorDarkGray  Color = "&H00404040"
	ColorLightGray Color = "&H00C0C0C0"

	ColorPurple Color = "&H00800080"
	ColorViolet Color = "&H00EE82EE"
	ColorIndigo Color = "&H004B0082"
	ColorPink   Color = "&H00CBC0FF"
	ColorOrange Color = "&H000080FF"
	ColorBrown  Color = "&H002A2AA5"
	ColorMaroon Color = "&H00000080"
	ColorNavy   Color = "&H00800000"
	ColorOlive  Color = "&H00008080"
	ColorTeal   Color = "&H00808000"

	ColorDeepPink       Color = "&H009314FF"
	ColorSkyBlue        Color = "&H00EBCE87"
	ColorLimeGreen      Color = "&H0032CD32"
	ColorGoldenRod      Color = "&H0020A5DA"
	ColorCornflowerBlue Color = "&H00ED9564"
	ColorBlueViolet     Color = "&H00E22B8A"
	ColorTurquoise      Color = "&H00D0E040"
	ColorSeaGreen       Color = "&H00578B2E"
	ColorHotPink        Color = "&H00B469FF"
	ColorDodgerBlue     Color = "&H00FF901E"
)

func ParseRGB

func ParseRGB(value string) (Color, error)

ParseRGB accepts three or six hexadecimal RGB digits, with an optional #.

func (Color) Ptr

func (c Color) Ptr() *Color

Ptr returns a pointer to a copy of c, for optional Override fields.

type Contents

type Contents struct {
	Info   map[string]string
	Styles []map[string]string
	Events []map[string]string
}

Contents contains the parsed fields. All returned maps are independent of the document.

type Dialogue

type Dialogue struct {
	Start time.Duration
	End   time.Duration
	Text  string
}

Dialogue represents a single subtitle event (dialogue line) in the ASS file. This is a helper struct that is used when constructing an event.

type Document

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

Document keeps the original ASS text and locates the fields that can be edited.

func Parse

func Parse(reader io.Reader) (*Document, error)

Parse reads a UTF-8 ASS v4+ file, preserving its original bytes.

func (*Document) Apply

func (d *Document) Apply(edit Edit) (*Document, error)

Apply returns a new document. The original remains available if an edit fails.

func (*Document) CheckSafeArea added in v0.2.0

func (d *Document) CheckSafeArea(area SafeArea) ([]SafeAreaIssue, error)

CheckSafeArea reports every style, and every event with its own margins, whose margins let text reach into the area's unsafe edges. It reads margins and alignment only; inline \pos and \move tags are not checked.

func (*Document) Contents

func (d *Document) Contents() Contents

Contents returns the script settings, styles, and events in file order.

func (*Document) EmbedFonts added in v0.2.0

func (d *Document) EmbedFonts(fonts []EmbeddedFont) (*Document, error)

EmbedFonts returns a document with fonts added to its [Fonts] section. The section is created at the end of the file when it is missing. Every other line keeps its bytes. A font whose name is already embedded is rejected.

func (*Document) String

func (d *Document) String() string

String returns the document text, including every untouched byte of the original.

func (*Document) Theme

func (d *Document) Theme(preset Preset, name string) (*Document, error)

Theme replaces the selected style fields. A blank name applies the preset to every style.

func (*Document) Validate

func (d *Document) Validate() error

Validate checks style names, references, and ASS dialogue timestamps.

func (*Document) WithTextPosition added in v0.1.0

func (d *Document) WithTextPosition(position TextPosition, name string) (*Document, error)

WithTextPosition changes style defaults, preserving all event fields and inline tags. An empty style name selects every style.

type Edit

type Edit struct {
	Info   map[string]string
	Styles []StyleEdit
	Events []EventEdit
}

Edit contains changes to script settings, named styles, and numbered events.

type Effect

type Effect string

Effect is an event transition. Build one with BannerEffect or ScrollEffect. An empty Effect has no transition.

func BannerEffect added in v0.2.0

func BannerEffect(delay int, leftToRight bool, fadeWidth int) (Effect, error)

BannerEffect scrolls the event horizontally across the screen, one script pixel every delay milliseconds. The event is drawn on one line. fadeWidth is kept in the effect for other renderers; libass ignores it.

func ScrollEffect added in v0.2.0

func ScrollEffect(direction ScrollDirection, top, bottom, delay, fadeHeight int) (Effect, error)

ScrollEffect scrolls the event vertically between the script rows top and bottom, one pixel every delay milliseconds. fadeHeight is kept for other renderers; libass ignores it.

func (Effect) Ptr

func (e Effect) Ptr() *Effect

Ptr returns a pointer to a copy of e, for optional fields.

type EmbeddedFont added in v0.2.0

type EmbeddedFont struct {
	Name string
	Data []byte
}

EmbeddedFont is a font file stored inside the script. Name is the file name, such as "DejaVuSans.ttf".

type Encoding

type Encoding int

Encoding represents character encoding options

const (
	// EncodingAuto is a libass extension that detects the text direction, for
	// right-to-left and mixed text. VSFilter rejects it.
	EncodingAuto       Encoding = -1
	EncodingANSI       Encoding = 0
	EncodingDefault    Encoding = 1
	EncodingSymbol     Encoding = 2
	EncodingShiftJIS   Encoding = 128
	EncodingHangeul    Encoding = 129
	EncodingGB2312     Encoding = 134
	EncodingChineseBig Encoding = 136
	EncodingMac        Encoding = 77
	EncodingKorean     Encoding = 129
	EncodingJohab      Encoding = 130
	EncodingOEM        Encoding = 255
)

func (Encoding) Ptr

func (e Encoding) Ptr() *Encoding

Ptr returns a pointer to a copy of e, for optional fields.

type Event

type Event struct {
	Comment  bool          // Emit a Comment event instead of Dialogue.
	Layer    int           // Layer number (higher layers are drawn on top)
	Start    time.Duration // Start time of the subtitle
	End      time.Duration // End time of the subtitle
	Style    string        // Name of the style to use
	Name     string        // Name of the event (actor/character name)
	MarginL  int           // Left margin override in pixels
	MarginR  int           // Right margin override in pixels
	MarginV  int           // Vertical margin override in pixels
	Effect   Effect        // Special effect name
	Text     string        // The actual subtitle text
	Override *Override     // Optional override tags for custom formatting
}

Event represents a single subtitle event (dialogue line) in the ASS file.

type EventEdit

type EventEdit struct {
	Index    int
	Fields   map[string]string
	Override *Override
}

EventEdit updates an event by its one-based index, including comment events.

type Fade

type Fade struct {
	A1 int
	A2 int
	A3 int
	T1 time.Duration
	T2 time.Duration
	T3 time.Duration
	T4 time.Duration
}

Fade is the complex \fade tag: alphas A1, A2 and A3 from 0 to 255 change at times T1 to T4.

type Karaoke added in v0.1.0

type Karaoke struct {
	Mode     KaraokeMode
	Duration time.Duration
}

Karaoke highlights the following syllable for Duration. An empty Mode selects KaraokeInstant.

type KaraokeMode added in v0.1.0

type KaraokeMode string

KaraokeMode selects the karaoke highlight effect.

const (
	KaraokeInstant KaraokeMode = "k"
	KaraokeSweep   KaraokeMode = "kf"
	KaraokeOutline KaraokeMode = "ko"
)

type Movement

type Movement struct {
	X1 float64
	Y1 float64
	X2 float64
	Y2 float64
	T1 *time.Duration
	T2 *time.Duration
}

Movement moves text from (X1, Y1) to (X2, Y2). T1 and T2 bound the movement in event time and must be set together.

type Override

type Override struct {
	ResetStyle      *string // Reset overrides, optionally to another named style.
	Spacing         *float64
	Encoding        *Encoding
	BorderX         *float64
	BorderY         *float64
	ShadowX         *float64
	ShadowY         *float64
	BlurEdges       *int
	DrawingMode     *int
	DrawingBaseline *float64
	Karaoke         *Karaoke
	KaraokeStart    *time.Duration
	SimpleFade      *SimpleFade
	VectorClip      *VectorClip
	Position        *Position   // Absolute positioning
	Movement        *Movement   // Movement animation
	Origin          *Position   // Origin point for rotations
	Alignment       *Alignment  // Text alignment override
	Bold            *bool       // Bold override
	BoldWeight      *BoldWeight // Custom bold weight
	Italic          *bool       // Italic override
	Underline       *bool       // Underline override
	StrikeOut       *bool       // Strikeout override
	FontSize        *float64    // Font size override
	FontName        *string     // Font name override
	PrimaryColor    *Color      // Primary color override
	SecondColor     *Color      // Secondary color override
	OutlineColor    *Color      // Outline color override
	ShadowColor     *Color      // Shadow color override
	GlobalAlpha     *Alpha      // Global alpha override
	PrimaryAlpha    *Alpha      // Primary color alpha
	SecondAlpha     *Alpha      // Secondary color alpha
	OutlineAlpha    *Alpha      // Outline alpha
	ShadowAlpha     *Alpha      // Shadow alpha
	Border          *float64    // Border width override
	Shadow          *float64    // Shadow depth override
	Blur            *float64    // Blur effect
	ScaleX          *float64    // Horizontal scaling override
	ScaleY          *float64    // Vertical scaling override
	RotationZ       *float64    // Z-axis rotation
	RotationX       *float64    // X-axis rotation
	RotationY       *float64    // Y-axis rotation
	ShearX          *float64    // X-axis shearing
	ShearY          *float64    // Y-axis shearing
	Fade            *Fade       // Fade effect
	Transform       []Transform // Transform animations
	Clip            *Clip       // Clipping rectangle
	WrapStyle       *WrapStyle  // Wrap style override
	ResetScale      bool        // \fsc: restore the style's horizontal and vertical scale
}

Override represents text override tags that can be applied to a subtitle event.

func (*Override) Tags

func (o *Override) Tags() (string, error)

Tags encodes the override as a leading ASS tag block.

type Position

type Position struct {
	X float64
	Y float64
}

Position is a point in script coordinates.

type Preset

type Preset struct {
	Name            string
	Font            string
	Text            Color
	Highlight       Color
	Background      Color
	OutlineColor    Color
	BackgroundAlpha Alpha
	FontRatio       float64
	MarginRatio     float64
	SideMarginRatio float64
	// RightMarginRatio replaces SideMarginRatio on the right when it is set.
	RightMarginRatio float64
	Outline          float64
	Shadow           float64
	Padding          float64
	Bold             bool
	Alignment        Alignment
}

Preset sets the complete look of a subtitle style. FontRatio and MarginRatio are fractions of the script height; the side margin ratios are fractions of its width.

func LookupPreset

func LookupPreset(name string) (Preset, error)

LookupPreset returns the requested look, or an error wrapping commerr.ErrNotFound.

func Presets

func Presets() []Preset

Presets returns the built-in looks in display order.

func (Preset) Captions

func (p Preset) Captions(spec CaptionSpec) Script

Captions builds timed captions with separate text and background layers when the preset has a box.

type SafeArea added in v0.2.0

type SafeArea struct {
	Name            string
	TopRatio        float64
	BottomRatio     float64
	LeftRatio       float64
	RightRatio      float64
	LowerRightRatio float64
	LowerFromRatio  float64
}

SafeArea is the part of a vertical video a platform's buttons and captions leave uncovered, as fractions of the script width and height. Text that reaches below LowerFromRatio of the height needs LowerRightRatio on the right instead of RightRatio.

func LookupSafeArea added in v0.2.0

func LookupSafeArea(name string) (SafeArea, error)

LookupSafeArea returns a named safe area, or an error wrapping commerr.ErrNotFound.

func SafeAreas added in v0.2.0

func SafeAreas() []SafeArea

SafeAreas returns the platform safe areas and the combined area that clears all of them.

type SafeAreaIssue added in v0.2.0

type SafeAreaIssue struct {
	Style    string
	Event    int
	Edge     string
	Margin   int
	Required int
}

SafeAreaIssue is a style or event whose placement reaches into the unsafe part of the video. Event is the one-based event number, or zero for a style.

type Script

type Script struct {
	Title      string
	Info       map[string]string // Additional script headers; title, type and resolution use their typed fields.
	Resolution struct {
		Width  int
		Height int
	}
	Styles []Style
	Events []Event
	// Kerning writes the libass Kerning header, which turns on font kerning.
	Kerning bool
	// Language writes the libass Language header, an ISO 639-1 code such as "en",
	// which selects language-specific glyph variants.
	Language string
	// Fonts are embedded in the script's [Fonts] section, so a renderer that
	// reads embedded fonts needs no installed copy.
	Fonts []EmbeddedFont
}

Script represents a complete ASS subtitle script including styles and events.

func NewScript

func NewScript(title string, width, height int) *Script

NewScript starts an empty script at the given coordinate resolution.

func (*Script) AddEvent

func (s *Script) AddEvent(event Event)

AddEvent appends a dialogue event.

func (*Script) AddStyle

func (s *Script) AddStyle(style Style)

AddStyle appends a style definition.

func (Script) Encode

func (s Script) Encode(w io.Writer) error

Encode writes an ASS script to w.

func (Script) MarshalText

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

MarshalText writes a new v4+ ASS script from typed values. Custom Info headers replace the generated defaults of the same name and follow them in sorted order.

func (Script) WithTextPosition added in v0.1.0

func (s Script) WithTextPosition(position TextPosition) (Script, error)

WithTextPosition returns a script with position geometry applied to every style.

func (Script) WriteToFile

func (s Script) WriteToFile(path string) error

WriteToFile writes an ASS script to the requested path.

type ScrollDirection added in v0.2.0

type ScrollDirection string

ScrollDirection selects the vertical scroll effect.

const (
	ScrollUp   ScrollDirection = "Scroll up"
	ScrollDown ScrollDirection = "Scroll down"
)

type SimpleFade added in v0.1.0

type SimpleFade struct {
	In  time.Duration
	Out time.Duration
}

SimpleFade fades in over In and out over Out.

type Style

type Style struct {
	Name         string      // Unique identifier for the style
	FontName     string      // Name of the font to use
	FontSize     float64     // Font size in ASS script coordinates.
	PrimaryColor Color       // Primary color in ASS format: &HBBGGRR&
	SecondColor  Color       // Secondary color (for karaoke) in ASS format: &HBBGGRR&
	OutlineColor Color       // Outline color in ASS format: &HBBGGRR&
	ShadowColor  Color       // Shadow color in ASS format: &HBBGGRR&
	PrimaryAlpha Alpha       // Primary color alpha
	SecondAlpha  Alpha       // Secondary color alpha
	OutlineAlpha Alpha       // Outline alpha
	ShadowAlpha  Alpha       // Shadow alpha
	Bold         bool        // Whether text should be bold
	Italic       bool        // Whether text should be italic
	Underline    bool        // Whether text should be underlined
	StrikeOut    bool        // Whether text should be struck through
	ScaleX       float64     // Horizontal scaling as percentage (100 = normal)
	ScaleY       float64     // Vertical scaling as percentage (100 = normal)
	Spacing      float64     // Additional space between letters in pixels
	Angle        float64     // Rotation angle in degrees
	BorderStyle  BorderStyle // Style of border around text
	Outline      float64     // Width of the outline in pixels
	Shadow       float64     // Depth of the shadow in pixels
	Alignment    Alignment   // Text alignment using numpad layout
	MarginL      int         // Left margin in pixels
	MarginR      int         // Right margin in pixels
	MarginV      int         // Vertical margin in pixels
	Encoding     Encoding    // Character encoding number
	WrapStyle    WrapStyle   // Text wrapping style
}

Style represents an ASS style definition that can be applied to multiple subtitle events.

type StyleEdit

type StyleEdit struct {
	Name   string
	Fields map[string]string
}

StyleEdit replaces selected Format columns in a named style.

type TextPosition added in v0.1.0

type TextPosition struct {
	Name             string
	Alignment        Alignment
	MarginRatio      float64
	LeftMarginRatio  float64
	RightMarginRatio float64
}

TextPosition sets style alignment and margins as fractions of the script canvas. Existing event margins and inline positioning retain precedence.

func LookupTextPosition added in v0.1.0

func LookupTextPosition(name string) (TextPosition, error)

LookupTextPosition returns a named placement, or an error wrapping commerr.ErrNotFound.

func TextPositions added in v0.1.0

func TextPositions() []TextPosition

TextPositions returns independent values in display order. Portrait names describe intended use. Every position clears the "all" safe area on a vertical video.

type Transform

type Transform struct {
	Start    time.Duration
	End      time.Duration
	Accel    float64
	Override *Override
}

Transform animates Override from Start to End, relative to the event start. End zero runs it until the event ends. Accel zero selects linear timing.

type VectorClip added in v0.1.0

type VectorClip struct {
	Scale   int
	Drawing string
	Inverse bool
}

VectorClip uses ASS drawing commands. Scale zero selects the default scale of one.

type WrapStyle

type WrapStyle int

WrapStyle represents text wrapping behavior

const (
	// Smart wrapping, top line is wider
	WrapStyleSmartTop WrapStyle = 0
	// End-of-line wrapping, right margin is strictly enforced
	WrapStyleEndOfLine WrapStyle = 1
	// Smart wrapping with a wider bottom line.
	WrapStyleSmartBottom WrapStyle = 3
	// Forced wrapping, only wrap at \n or \N
	WrapStyleForced WrapStyle = 2
	WrapStyleNoWrap WrapStyle = WrapStyleForced
)

func (WrapStyle) Ptr

func (w WrapStyle) Ptr() *WrapStyle

Ptr returns a pointer to a copy of w, for optional fields.

Jump to

Keyboard shortcuts

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