package module
Version: v0.20.0 Latest Latest

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

Go to latest
Published: Jan 15, 2022 License: MIT Imports: 22 Imported by: 24


GoReportCard GoDoc Travis Coveralls

This is a Golang library to manipulate subtitles.

It allows you to manipulate srt, stl, ttml, ssa/ass, webvtt and teletext files for now.

Available operations are parsing, writing, syncing, fragmenting, unfragmenting, merging and optimizing.


To install the library:

go get

To install the CLI:

go install        

Using the library in your code

WARNING: the code below doesn't handle errors for readibility purposes. However you SHOULD!

// Open subtitles
s1, _ := astisub.OpenFile("/path/to/example.ttml")
s2, _ := astisub.ReadFromSRT(bytes.NewReader([]byte("00:01:00.000 --> 00:02:00.000\nCredits")))

// Add a duration to every subtitles (syncing)

// Fragment the subtitles

// Merge subtitles

// Optimize subtitles

// Unfragment the subtitles

// Write subtitles
var buf = &bytes.Buffer{}

Using the CLI

If astisub has been installed properly you can:

  • convert any type of subtitle to any other type of subtitle:

      astisub convert -i -o example.ttml
  • fragment any type of subtitle:

      astisub fragment -i -f 2s -o
  • merge any type of subtitle into any other type of subtitle:

      astisub merge -i -i example.ttml -o
  • optimize any type of subtitle:

      astisub optimize -i -o
  • unfragment any type of subtitle:

      astisub unfragment -i -o
  • sync any type of subtitle:

      astisub sync -i -s "-2s" -o

Features and roadmap

  • parsing
  • writing
  • syncing
  • fragmenting/unfragmenting
  • merging
  • ordering
  • optimizing
  • .srt
  • .ttml
  • .vtt
  • .stl
  • .ssa/.ass
  • .teletext
  • .smi




View Source
const (
	LanguageChinese   = "chinese"
	LanguageEnglish   = "english"
	LanguageFrench    = "french"
	LanguageJapanese  = "japanese"
	LanguageNorwegian = "norwegian"



View Source
var (
	ColorBlack   = &Color{}
	ColorBlue    = &Color{Blue: 255}
	ColorCyan    = &Color{Blue: 255, Green: 255}
	ColorGray    = &Color{Blue: 128, Green: 128, Red: 128}
	ColorGreen   = &Color{Green: 128}
	ColorLime    = &Color{Green: 255}
	ColorMagenta = &Color{Blue: 255, Red: 255}
	ColorMaroon  = &Color{Red: 128}
	ColorNavy    = &Color{Blue: 128}
	ColorOlive   = &Color{Green: 128, Red: 128}
	ColorPurple  = &Color{Blue: 128, Red: 128}
	ColorRed     = &Color{Red: 255}
	ColorSilver  = &Color{Blue: 192, Green: 192, Red: 192}
	ColorTeal    = &Color{Blue: 128, Green: 128}
	ColorYellow  = &Color{Green: 255, Red: 255}
	ColorWhite   = &Color{Blue: 255, Green: 255, Red: 255}


View Source
var (
	ErrInvalidExtension   = errors.New("astisub: invalid extension")
	ErrNoSubtitlesToWrite = errors.New("astisub: no subtitles to write")


View Source
var (
	JustificationUnchanged = Justification(1)
	JustificationLeft      = Justification(2)
	JustificationCentered  = Justification(3)
	JustificationRight     = Justification(4)
View Source
var (
	BytesBOM = []byte{239, 187, 191}


View Source
var (
	ErrNoValidTeletextPID = errors.New("astisub: no valid teletext PID")


View Source
var Now = func() time.Time {
	return time.Now()

Now allows testing functions using it


This section is empty.


type Color

type Color struct {
	Alpha, Blue, Green, Red uint8

Color represents a color

func (*Color) SSAString

func (c *Color) SSAString() string

SSAString expresses the color as an SSA string

func (*Color) TTMLString

func (c *Color) TTMLString() string

TTMLString expresses the color as a TTML string

type Item

type Item struct {
	Comments    []string
	Index       int
	EndAt       time.Duration
	InlineStyle *StyleAttributes
	Lines       []Line
	Region      *Region
	StartAt     time.Duration
	Style       *Style

Item represents a text to show between 2 time boundaries with formatting

func (Item) String

func (i Item) String() string

String implements the Stringer interface

type Justification added in v0.12.0

type Justification int

type Line

type Line struct {
	Items     []LineItem
	VoiceName string

Line represents a set of formatted line items

func (Line) String

func (l Line) String() string

String implement the Stringer interface

type LineItem

type LineItem struct {
	InlineStyle *StyleAttributes
	Style       *Style
	Text        string

LineItem represents a formatted line item

func (LineItem) STLString added in v0.12.0

func (li LineItem) STLString() string

type Metadata

type Metadata struct {
	Comments                                            []string
	Framerate                                           int
	Language                                            string
	SSACollisions                                       string
	SSAOriginalEditing                                  string
	SSAOriginalScript                                   string
	SSAOriginalTiming                                   string
	SSAOriginalTranslation                              string
	SSAPlayDepth                                        *int
	SSAPlayResX, SSAPlayResY                            *int
	SSAScriptType                                       string
	SSAScriptUpdatedBy                                  string
	SSASynchPoint                                       string
	SSATimer                                            *float64
	SSAUpdateDetails                                    string
	SSAWrapStyle                                        string
	STLCountryOfOrigin                                  string
	STLCreationDate                                     *time.Time
	STLDisplayStandardCode                              string
	STLMaximumNumberOfDisplayableCharactersInAnyTextRow *int
	STLMaximumNumberOfDisplayableRows                   *int
	STLPublisher                                        string
	STLRevisionDate                                     *time.Time
	STLSubtitleListReferenceCode                        string
	STLTimecodeStartOfProgramme                         time.Duration
	Title                                               string
	TTMLCopyright                                       string

Metadata represents metadata TODO Merge attributes

type Options

type Options struct {
	Filename string
	Teletext TeletextOptions
	STL      STLOptions

Options represents open or write options

type Region

type Region struct {
	ID          string
	InlineStyle *StyleAttributes
	Style       *Style

Region represents a subtitle's region

type SSAOptions added in v0.20.0

type SSAOptions struct {
	OnUnknownSectionName func(name string)
	OnInvalidLine        func(line string)


type STLOptions added in v0.15.0

type STLOptions struct {
	// IgnoreTimecodeStartOfProgramme - set STLTimecodeStartOfProgramme to zero before parsing
	IgnoreTimecodeStartOfProgramme bool

STLOptions represents STL parsing options

type STLPosition added in v0.12.0

type STLPosition struct {
	VerticalPosition int
	MaxRows          int
	Rows             int

type Style

type Style struct {
	ID          string
	InlineStyle *StyleAttributes
	Style       *Style

Style represents a subtitle's style

type StyleAttributes

type StyleAttributes struct {
	SSAAlignment         *int
	SSAAlphaLevel        *float64
	SSAAngle             *float64 // degrees
	SSABackColour        *Color
	SSABold              *bool
	SSABorderStyle       *int
	SSAEffect            string
	SSAEncoding          *int
	SSAFontName          string
	SSAFontSize          *float64
	SSAItalic            *bool
	SSALayer             *int
	SSAMarginLeft        *int // pixels
	SSAMarginRight       *int // pixels
	SSAMarginVertical    *int // pixels
	SSAMarked            *bool
	SSAOutline           *float64 // pixels
	SSAOutlineColour     *Color
	SSAPrimaryColour     *Color
	SSAScaleX            *float64 // %
	SSAScaleY            *float64 // %
	SSASecondaryColour   *Color
	SSAShadow            *float64 // pixels
	SSASpacing           *float64 // pixels
	SSAStrikeout         *bool
	SSAUnderline         *bool
	STLBoxing            *bool
	STLItalics           *bool
	STLJustification     *Justification
	STLPosition          *STLPosition
	STLUnderline         *bool
	TeletextColor        *Color
	TeletextDoubleHeight *bool
	TeletextDoubleSize   *bool
	TeletextDoubleWidth  *bool
	TeletextSpacesAfter  *int
	TeletextSpacesBefore *int
	// TODO Use pointers with real types below
	TTMLBackgroundColor  *string //
	TTMLColor            *string
	TTMLDirection        *string
	TTMLDisplay          *string
	TTMLDisplayAlign     *string
	TTMLExtent           *string
	TTMLFontFamily       *string
	TTMLFontSize         *string
	TTMLFontStyle        *string
	TTMLFontWeight       *string
	TTMLLineHeight       *string
	TTMLOpacity          *string
	TTMLOrigin           *string
	TTMLOverflow         *string
	TTMLPadding          *string
	TTMLShowBackground   *string
	TTMLTextAlign        *string
	TTMLTextDecoration   *string
	TTMLTextOutline      *string
	TTMLUnicodeBidi      *string
	TTMLVisibility       *string
	TTMLWrapOption       *string
	TTMLWritingMode      *string
	TTMLZIndex           *int
	WebVTTAlign          string
	WebVTTItalics        bool
	WebVTTLine           string
	WebVTTLines          int
	WebVTTPosition       string
	WebVTTRegionAnchor   string
	WebVTTScroll         string
	WebVTTSize           string
	WebVTTVertical       string
	WebVTTViewportAnchor string
	WebVTTWidth          string

StyleAttributes represents style attributes

type Subtitles

type Subtitles struct {
	Items    []*Item
	Metadata *Metadata
	Regions  map[string]*Region
	Styles   map[string]*Style

Subtitles represents an ordered list of items with formatting

func NewSubtitles

func NewSubtitles() *Subtitles

NewSubtitles creates new subtitles

func Open

func Open(o Options) (s *Subtitles, err error)

Open opens a subtitle reader based on options

func OpenFile

func OpenFile(filename string) (*Subtitles, error)

OpenFile opens a file regardless of other options

func ReadFromSRT

func ReadFromSRT(i io.Reader) (o *Subtitles, err error)

ReadFromSRT parses an .srt content

func ReadFromSSA

func ReadFromSSA(i io.Reader) (o *Subtitles, err error)

ReadFromSSA parses an .ssa content

func ReadFromSSAWithOptions added in v0.20.0

func ReadFromSSAWithOptions(i io.Reader, opts SSAOptions) (o *Subtitles, err error)

ReadFromSSAWithOptions parses an .ssa content

func ReadFromSTL

func ReadFromSTL(i io.Reader, opts STLOptions) (o *Subtitles, err error)

ReadFromSTL parses an .stl content

func ReadFromTTML

func ReadFromTTML(i io.Reader) (o *Subtitles, err error)

ReadFromTTML parses a .ttml content

func ReadFromWebVTT

func ReadFromWebVTT(i io.Reader) (o *Subtitles, err error)

ReadFromWebVTT parses a .vtt content TODO Tags (u, i, b) TODO Class

func (*Subtitles) Add

func (s *Subtitles) Add(d time.Duration)

Add adds a duration to each time boundaries. As in the time package, duration can be negative.

func (Subtitles) Duration

func (s Subtitles) Duration() time.Duration

Duration returns the subtitles duration

func (*Subtitles) ForceDuration

func (s *Subtitles) ForceDuration(d time.Duration, addDummyItem bool)

ForceDuration updates the subtitles duration. If requested duration is bigger, then we create a dummy item. If requested duration is smaller, then we remove useless items and we cut the last item or add a dummy item.

func (*Subtitles) Fragment

func (s *Subtitles) Fragment(f time.Duration)

Fragment fragments subtitles with a specific fragment duration

func (Subtitles) IsEmpty

func (s Subtitles) IsEmpty() bool

IsEmpty returns whether the subtitles are empty

func (*Subtitles) Merge

func (s *Subtitles) Merge(i *Subtitles)

Merge merges subtitles i into subtitles

func (*Subtitles) Optimize

func (s *Subtitles) Optimize()

Optimize optimizes subtitles

func (*Subtitles) Order

func (s *Subtitles) Order()

Order orders items

func (*Subtitles) RemoveStyling

func (s *Subtitles) RemoveStyling()

RemoveStyling removes the styling from the subtitles

func (*Subtitles) Unfragment

func (s *Subtitles) Unfragment()

Unfragment unfragments subtitles

func (Subtitles) Write

func (s Subtitles) Write(dst string) (err error)

Write writes subtitles to a file

func (Subtitles) WriteToSRT

func (s Subtitles) WriteToSRT(o io.Writer) (err error)

WriteToSRT writes subtitles in .srt format

func (Subtitles) WriteToSSA

func (s Subtitles) WriteToSSA(o io.Writer) (err error)

WriteToSSA writes subtitles in .ssa format

func (Subtitles) WriteToSTL

func (s Subtitles) WriteToSTL(o io.Writer) (err error)

WriteToSTL writes subtitles in .stl format

func (Subtitles) WriteToTTML

func (s Subtitles) WriteToTTML(o io.Writer) (err error)

WriteToTTML writes subtitles in .ttml format

func (Subtitles) WriteToWebVTT

func (s Subtitles) WriteToWebVTT(o io.Writer) (err error)

WriteToWebVTT writes subtitles in .vtt format

type TTMLIn

type TTMLIn struct {
	Framerate int              `xml:"frameRate,attr"`
	Lang      string           `xml:"lang,attr"`
	Metadata  TTMLInMetadata   `xml:"head>metadata"`
	Regions   []TTMLInRegion   `xml:"head>layout>region"`
	Styles    []TTMLInStyle    `xml:"head>styling>style"`
	Subtitles []TTMLInSubtitle `xml:"body>div>p"`
	Tickrate  int              `xml:"tickRate,attr"`
	XMLName   xml.Name         `xml:"tt"`

TTMLIn represents an input TTML that must be unmarshaled We split it from the output TTML as we can't add strict namespace without breaking retrocompatibility

type TTMLInDuration

type TTMLInDuration struct {
	// contains filtered or unexported fields

TTMLInDuration represents an input TTML duration

func (*TTMLInDuration) UnmarshalText

func (d *TTMLInDuration) UnmarshalText(i []byte) (err error)

UnmarshalText implements the TextUnmarshaler interface Possible formats are: - hh:mm:ss.mmm - hh:mm:ss:fff (fff being frames) - [ticks]t ([ticks] being the tick amount)

type TTMLInHeader

type TTMLInHeader struct {
	ID    string `xml:"id,attr,omitempty"`
	Style string `xml:"style,attr,omitempty"`

TTMLInHeader represents an input TTML header

type TTMLInItem

type TTMLInItem struct {
	Style string `xml:"style,attr,omitempty"`
	Text  string `xml:",chardata"`
	XMLName xml.Name

TTMLInItem represents an input TTML item

type TTMLInItems

type TTMLInItems []TTMLInItem

TTMLInItems represents input TTML items

func (*TTMLInItems) UnmarshalXML

func (i *TTMLInItems) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error)

UnmarshalXML implements the XML unmarshaler interface

type TTMLInMetadata

type TTMLInMetadata struct {
	Copyright string `xml:"copyright"`
	Title     string `xml:"title"`

TTMLInMetadata represents an input TTML Metadata

type TTMLInRegion

type TTMLInRegion struct {
	XMLName xml.Name `xml:"region"`

TTMLInRegion represents an input TTML region

type TTMLInStyle

type TTMLInStyle struct {
	XMLName xml.Name `xml:"style"`

TTMLInStyle represents an input TTML style

type TTMLInStyleAttributes

type TTMLInStyleAttributes struct {
	BackgroundColor *string `xml:"backgroundColor,attr,omitempty"`
	Color           *string `xml:"color,attr,omitempty"`
	Direction       *string `xml:"direction,attr,omitempty"`
	Display         *string `xml:"display,attr,omitempty"`
	DisplayAlign    *string `xml:"displayAlign,attr,omitempty"`
	Extent          *string `xml:"extent,attr,omitempty"`
	FontFamily      *string `xml:"fontFamily,attr,omitempty"`
	FontSize        *string `xml:"fontSize,attr,omitempty"`
	FontStyle       *string `xml:"fontStyle,attr,omitempty"`
	FontWeight      *string `xml:"fontWeight,attr,omitempty"`
	LineHeight      *string `xml:"lineHeight,attr,omitempty"`
	Opacity         *string `xml:"opacity,attr,omitempty"`
	Origin          *string `xml:"origin,attr,omitempty"`
	Overflow        *string `xml:"overflow,attr,omitempty"`
	Padding         *string `xml:"padding,attr,omitempty"`
	ShowBackground  *string `xml:"showBackground,attr,omitempty"`
	TextAlign       *string `xml:"textAlign,attr,omitempty"`
	TextDecoration  *string `xml:"textDecoration,attr,omitempty"`
	TextOutline     *string `xml:"textOutline,attr,omitempty"`
	UnicodeBidi     *string `xml:"unicodeBidi,attr,omitempty"`
	Visibility      *string `xml:"visibility,attr,omitempty"`
	WrapOption      *string `xml:"wrapOption,attr,omitempty"`
	WritingMode     *string `xml:"writingMode,attr,omitempty"`
	ZIndex          *int    `xml:"zIndex,attr,omitempty"`

TTMLInStyleAttributes represents input TTML style attributes

type TTMLInSubtitle

type TTMLInSubtitle struct {
	Begin  *TTMLInDuration `xml:"begin,attr,omitempty"`
	End    *TTMLInDuration `xml:"end,attr,omitempty"`
	ID     string          `xml:"id,attr,omitempty"`
	Items  string          `xml:",innerxml"` // We must store inner XML here since there's no tag to describe both any tag and chardata
	Region string          `xml:"region,attr,omitempty"`
	Style  string          `xml:"style,attr,omitempty"`

TTMLInSubtitle represents an input TTML subtitle

type TTMLOut

type TTMLOut struct {
	Lang            string            `xml:"xml:lang,attr,omitempty"`
	Metadata        *TTMLOutMetadata  `xml:"head>metadata,omitempty"`
	Styles          []TTMLOutStyle    `xml:"head>styling>style,omitempty"` //!\\ Order is important! Keep Styling above Layout
	Regions         []TTMLOutRegion   `xml:"head>layout>region,omitempty"`
	Subtitles       []TTMLOutSubtitle `xml:"body>div>p,omitempty"`
	XMLName         xml.Name          `xml:" tt"`
	XMLNamespaceTTM string            `xml:"xmlns:ttm,attr"`
	XMLNamespaceTTS string            `xml:"xmlns:tts,attr"`

TTMLOut represents an output TTML that must be marshaled We split it from the input TTML as this time we'll add strict namespaces

type TTMLOutDuration

type TTMLOutDuration time.Duration

TTMLOutDuration represents an output TTML duration

func (TTMLOutDuration) MarshalText

func (t TTMLOutDuration) MarshalText() ([]byte, error)

MarshalText implements the TextMarshaler interface

type TTMLOutHeader

type TTMLOutHeader struct {
	ID    string `xml:"xml:id,attr,omitempty"`
	Style string `xml:"style,attr,omitempty"`

TTMLOutHeader represents an output TTML header

type TTMLOutItem

type TTMLOutItem struct {
	Style string `xml:"style,attr,omitempty"`
	Text  string `xml:",chardata"`
	XMLName xml.Name

TTMLOutItem represents an output TTML Item

type TTMLOutMetadata

type TTMLOutMetadata struct {
	Copyright string `xml:"ttm:copyright,omitempty"`
	Title     string `xml:"ttm:title,omitempty"`

TTMLOutMetadata represents an output TTML Metadata

type TTMLOutRegion

type TTMLOutRegion struct {
	XMLName xml.Name `xml:"region"`

TTMLOutRegion represents an output TTML region

type TTMLOutStyle

type TTMLOutStyle struct {
	XMLName xml.Name `xml:"style"`

TTMLOutStyle represents an output TTML style

type TTMLOutStyleAttributes

type TTMLOutStyleAttributes struct {
	BackgroundColor *string `xml:"tts:backgroundColor,attr,omitempty"`
	Color           *string `xml:"tts:color,attr,omitempty"`
	Direction       *string `xml:"tts:direction,attr,omitempty"`
	Display         *string `xml:"tts:display,attr,omitempty"`
	DisplayAlign    *string `xml:"tts:displayAlign,attr,omitempty"`
	Extent          *string `xml:"tts:extent,attr,omitempty"`
	FontFamily      *string `xml:"tts:fontFamily,attr,omitempty"`
	FontSize        *string `xml:"tts:fontSize,attr,omitempty"`
	FontStyle       *string `xml:"tts:fontStyle,attr,omitempty"`
	FontWeight      *string `xml:"tts:fontWeight,attr,omitempty"`
	LineHeight      *string `xml:"tts:lineHeight,attr,omitempty"`
	Opacity         *string `xml:"tts:opacity,attr,omitempty"`
	Origin          *string `xml:"tts:origin,attr,omitempty"`
	Overflow        *string `xml:"tts:overflow,attr,omitempty"`
	Padding         *string `xml:"tts:padding,attr,omitempty"`
	ShowBackground  *string `xml:"tts:showBackground,attr,omitempty"`
	TextAlign       *string `xml:"tts:textAlign,attr,omitempty"`
	TextDecoration  *string `xml:"tts:textDecoration,attr,omitempty"`
	TextOutline     *string `xml:"tts:textOutline,attr,omitempty"`
	UnicodeBidi     *string `xml:"tts:unicodeBidi,attr,omitempty"`
	Visibility      *string `xml:"tts:visibility,attr,omitempty"`
	WrapOption      *string `xml:"tts:wrapOption,attr,omitempty"`
	WritingMode     *string `xml:"tts:writingMode,attr,omitempty"`
	ZIndex          *int    `xml:"tts:zIndex,attr,omitempty"`

TTMLOutStyleAttributes represents output TTML style attributes

type TTMLOutSubtitle

type TTMLOutSubtitle struct {
	Begin  TTMLOutDuration `xml:"begin,attr"`
	End    TTMLOutDuration `xml:"end,attr"`
	ID     string          `xml:"id,attr,omitempty"`
	Items  []TTMLOutItem
	Region string `xml:"region,attr,omitempty"`
	Style  string `xml:"style,attr,omitempty"`

TTMLOutSubtitle represents an output TTML subtitle

type TeletextOptions

type TeletextOptions struct {
	Page int
	PID  int

TeletextOptions represents teletext options


Path Synopsis

Jump to

Keyboard shortcuts

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