forked from asticode/go-astisub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
srt.go
271 lines (237 loc) · 6.07 KB
/
srt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package astisub
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
"strings"
"time"
"golang.org/x/net/html"
)
// Constants
const (
srtTimeBoundariesSeparator = " --> "
)
// Vars
var (
bytesSRTTimeBoundariesSeparator = []byte(srtTimeBoundariesSeparator)
bytesSRTItalicEndTag = []byte("</i>")
bytesSRTItalicStartTag = []byte("<i>")
bytesSRTBoldEndTag = []byte("</b>")
bytesSRTBoldStartTag = []byte("<b>")
bytesSRTUnderlineEndTag = []byte("</u>")
bytesSRTUnderlineStartTag = []byte("<u>")
)
// parseDurationSRT parses an .srt duration
func parseDurationSRT(i string) (time.Duration, error) {
return parseDuration(i, ",", 3)
}
// ReadFromSRT parses an .srt content
func ReadFromSRT(i io.Reader) (o *Subtitles, err error) {
// Init
o = NewSubtitles()
var scanner = bufio.NewScanner(i)
// Scan
var line string
var lineNum int
var s = &Item{}
for scanner.Scan() {
// Fetch line
line = strings.TrimSpace(scanner.Text())
lineNum++
// Remove BOM header
if lineNum == 1 {
line = strings.TrimPrefix(line, string(BytesBOM))
}
// Line contains time boundaries
if strings.Contains(line, srtTimeBoundariesSeparator) {
// Return the wrong number of rows
if len(s.Lines) == 0 {
err = fmt.Errorf("astisub: line %d: no lines", lineNum)
return
}
// Remove last item of previous subtitle since it's the index
index := s.Lines[len(s.Lines)-1]
s.Lines = s.Lines[:len(s.Lines)-1]
// Remove trailing empty lines
if len(s.Lines) > 0 {
for i := len(s.Lines) - 1; i >= 0; i-- {
if len(s.Lines[i].Items) > 0 {
for j := len(s.Lines[i].Items) - 1; j >= 0; j-- {
if len(s.Lines[i].Items[j].Text) == 0 {
s.Lines[i].Items = s.Lines[i].Items[:j]
} else {
break
}
}
if len(s.Lines[i].Items) == 0 {
s.Lines = s.Lines[:i]
}
}
}
}
// Init subtitle
s = &Item{}
// Fetch Index
s.Index, _ = strconv.Atoi(index.String())
// Extract time boundaries
s1 := strings.Split(line, srtTimeBoundariesSeparator)
if l := len(s1); l < 2 {
err = fmt.Errorf("astisub: line %d: time boundaries has only %d element(s)", lineNum, l)
return
}
// We do this to eliminate extra stuff like positions which are not documented anywhere
s2 := strings.Split(s1[1], " ")
// Parse time boundaries
if s.StartAt, err = parseDurationSRT(s1[0]); err != nil {
err = fmt.Errorf("astisub: line %d: parsing srt duration %s failed: %w", lineNum, s1[0], err)
return
}
if s.EndAt, err = parseDurationSRT(s2[0]); err != nil {
err = fmt.Errorf("astisub: line %d: parsing srt duration %s failed: %w", lineNum, s2[0], err)
return
}
// Append subtitle
o.Items = append(o.Items, s)
} else {
// Add text
if l := parseTextSRT(line); len(l.Items) > 0 {
s.Lines = append(s.Lines, l)
}
}
}
return
}
func parseTextSRT(i string) (o Line) {
// Create tokenizer
tr := html.NewTokenizer(strings.NewReader(i))
// Loop
italic := false
bold := false
underline := false
for {
// Get next tag
t := tr.Next()
// Process error
if err := tr.Err(); err != nil {
break
}
switch t {
case html.EndTagToken:
raw := tr.Raw()
if bytes.Equal(raw, bytesSRTItalicEndTag) {
italic = false
} else if bytes.Equal(raw, bytesSRTBoldEndTag) {
bold = false
} else if bytes.Equal(raw, bytesSRTUnderlineEndTag) {
underline = false
}
case html.StartTagToken:
raw := tr.Raw()
if bytes.Equal(raw, bytesSRTItalicStartTag) {
italic = true
} else if bytes.Equal(raw, bytesSRTBoldStartTag) {
bold = true
} else if bytes.Equal(raw, bytesSRTUnderlineStartTag) {
underline = true
}
case html.TextToken:
if s := strings.TrimSpace(string(tr.Raw())); s != "" {
// Get style attribute
var sa *StyleAttributes
if italic || bold || underline {
sa = &StyleAttributes{
SRTItalic: italic,
SRTBold: bold,
SRTUnderline: underline,
}
sa.propagateSRTAttributes()
}
// Append item
o.Items = append(o.Items, LineItem{
InlineStyle: sa,
Text: s,
})
}
}
}
return
}
// formatDurationSRT formats an .srt duration
func formatDurationSRT(i time.Duration) string {
return formatDuration(i, ",", 3)
}
// WriteToSRT writes subtitles in .srt format
func (s Subtitles) WriteToSRT(o io.Writer) (err error) {
// Do not write anything if no subtitles
if len(s.Items) == 0 {
err = ErrNoSubtitlesToWrite
return
}
// Add BOM header
var c []byte
c = append(c, BytesBOM...)
// Loop through subtitles
for k, v := range s.Items {
// Add time boundaries
c = append(c, []byte(strconv.Itoa(k+1))...)
c = append(c, bytesLineSeparator...)
c = append(c, []byte(formatDurationSRT(v.StartAt))...)
c = append(c, bytesSRTTimeBoundariesSeparator...)
c = append(c, []byte(formatDurationSRT(v.EndAt))...)
c = append(c, bytesLineSeparator...)
// Loop through lines
for _, l := range v.Lines {
c = append(c, l.srtBytes()...)
}
// Add new line
c = append(c, bytesLineSeparator...)
}
// Remove last new line
c = c[:len(c)-1]
// Write
if _, err = o.Write(c); err != nil {
err = fmt.Errorf("astisub: writing failed: %w", err)
return
}
return
}
func (l Line) srtBytes() (c []byte) {
for idx, li := range l.Items {
c = append(c, li.srtBytes()...)
// condition to avoid adding space as the last character.
if idx < len(l.Items)-1 {
c = append(c, []byte(" ")...)
}
}
c = append(c, bytesLineSeparator...)
return
}
func (li LineItem) srtBytes() (c []byte) {
// Get styles
i := li.InlineStyle != nil && li.InlineStyle.SRTItalic
b := li.InlineStyle != nil && li.InlineStyle.SRTBold
u := li.InlineStyle != nil && li.InlineStyle.SRTUnderline
// Append
if i {
c = append(c, bytesSRTItalicStartTag...)
}
if b {
c = append(c, bytesSRTBoldStartTag...)
}
if u {
c = append(c, bytesSRTUnderlineStartTag...)
}
c = append(c, []byte(li.Text)...)
if u {
c = append(c, bytesSRTUnderlineEndTag...)
}
if b {
c = append(c, bytesSRTBoldEndTag...)
}
if i {
c = append(c, bytesSRTItalicEndTag...)
}
return
}