-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
435 lines (382 loc) · 9.02 KB
/
Copy pathmain.go
File metadata and controls
435 lines (382 loc) · 9.02 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/integrii/flaggy"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"golang.org/x/text/transform"
)
var supportTypes map[string]subtitle = map[string]subtitle{
".srt": &srtType{},
".ass": &assType{},
}
var (
inputPath string
shift int
gFrom int
gTo int
fromStr string
toStr string
fromRegexp string
toRegexp string
encOverr string
inputEncoding encoding.Encoding
inputEncName string
dry bool
)
var version = "1.0.0"
func init() {
// ponytail: skip CLI parse under go test; upgrade path is TestMain + extracted cmd package
if strings.HasSuffix(os.Args[0], ".test") {
return
}
flaggy.SetName("ass-shifter")
flaggy.SetDescription("ASS subtitle shifter")
flaggy.DefaultParser.ShowHelpOnUnexpected = true
flaggy.DefaultParser.AdditionalHelpPrepend = "https://github.com/Nigh/subtitle-ass-shifter"
flaggy.AddPositionalValue(&inputPath, "path", 1, true, "the subtitle path to shift")
flaggy.Int(&shift, "t", "shift", "shift ms")
flaggy.String(&fromStr, "s", "start", "start from HH:MM:SS")
flaggy.String(&toStr, "e", "end", "end at HH:MM:SS")
flaggy.String(&fromRegexp, "sr", "startRegexp", "start from regular expression")
flaggy.String(&toRegexp, "er", "endRegexp", "end at regular expression")
flaggy.String(&encOverr, "enc", "encoding", "force input encoding (e.g. gbk, shift_jis); skips auto-detection")
flaggy.Bool(&dry, "d", "dry", "dry run")
flaggy.SetVersion(version)
flaggy.Parse()
}
func parseFromTo() error {
re := regexp.MustCompile(`(-?\d+):(\d\d):(\d\d)`)
str2ms := func(str string) (ms int, err error) {
matches := re.FindStringSubmatch(str)
if matches == nil {
return 0, fmt.Errorf("invalid time format, expected HH:MM:SS, example: 0:23:45")
}
hours, _ := strconv.Atoi(matches[1])
minutes, _ := strconv.Atoi(matches[2])
seconds, _ := strconv.Atoi(matches[3])
sign := 1
if hours < 0 {
sign = -1
}
ms = (hours*3600 + minutes*60 + seconds) * 1000 * sign
return
}
if fromStr != "" && fromRegexp != "" {
return fmt.Errorf("multiple start conditions are not allowed")
}
if toStr != "" && toRegexp != "" {
return fmt.Errorf("multiple end conditions are not allowed")
}
if fromStr != "" {
ms, err := str2ms(fromStr)
if err != nil {
return err
} else {
gFrom = ms
}
}
if toStr != "" {
ms, err := str2ms(toStr)
if err != nil {
return err
} else {
gTo = ms
}
}
if gTo != 0 && gFrom != 0 {
if gFrom > gTo {
return fmt.Errorf("end must be greater than start")
}
}
if fromRegexp != "" {
re, err := regexp.Compile(fromRegexp)
if err != nil {
return err
}
fromRegexp = re.String()
}
if toRegexp != "" {
re, err := regexp.Compile(toRegexp)
if err != nil {
return err
}
toRegexp = re.String()
}
return nil
}
func timeInclude(t int, from int, to int) bool {
if from == 0 && to == 0 {
return true
}
if from != 0 && t < from {
return false
}
if to != 0 && t > to {
return false
}
return true
}
var fileUpdated = 0
func main() {
if shift == 0 {
fmt.Println("shift 0ms means nothing to do.")
return
}
if err := parseFromTo(); err != nil {
fmt.Println(err)
return
}
inputPath, _ = filepath.Abs(inputPath)
_, err := os.Stat(inputPath)
if err != nil {
fmt.Println(err)
return
}
if err := initInputEncoding(encOverr); err != nil {
fmt.Println(err)
return
}
if inputEncoding != nil {
fmt.Printf("Using encoding %s (override)\n", inputEncName)
}
filepath.Walk(inputPath, walker)
if dry {
fmt.Println("\n[Info] Dry run, no file changes.")
} else {
fmt.Printf("\n[Info] %d subtitle files updated.\n", fileUpdated)
}
}
func initInputEncoding(label string) error {
if label == "" {
inputEncoding = nil
inputEncName = ""
return nil
}
e, name := charset.Lookup(label)
if e == nil {
return fmt.Errorf("Encoding %s is not recognized", label)
}
inputEncoding = e
inputEncName = name
return nil
}
func walker(realPath string, f os.FileInfo, err error) error {
ext := filepath.Ext(f.Name())
if f.Name()[0] == '.' {
return filepath.SkipDir
}
ext = strings.ToLower(ext)
if subs, ok := supportTypes[ext]; ok {
subFile, err := os.ReadFile(realPath)
fmt.Println("\n" + filepath.Base(realPath))
if err != nil {
fmt.Println(err)
return nil
}
// Detect the encoding
var fileEncoding encoding.Encoding
var name string
var certain bool
if inputEncoding != nil {
fileEncoding = inputEncoding
name = inputEncName
certain = true
} else {
fileEncoding, name, certain = charset.DetermineEncoding(subFile, "")
}
if !certain {
fmt.Printf("Warning: uncertain encoding detected for %s, assuming %s\n", realPath, name)
}
// Transcode to UTF-8
utf8Bytes, _, err := transform.Bytes(fileEncoding.NewDecoder(), subFile)
if err != nil {
fmt.Println(err)
return nil
}
subs.setContent(utf8Bytes)
newLines := subtitleShift(subs, shift)
if !dry {
err = os.WriteFile(realPath, []byte(strings.Join(newLines, "\n")), 0644)
if err != nil {
fmt.Println("[ERROR] "+filepath.Base(realPath), err)
} else {
fileUpdated++
}
}
}
return nil
}
type subtitle interface {
setContent(content []byte)
getContent() []byte
match2Ms(match []string) int
time2Str(totalMs int) string
re() *regexp.Regexp
}
type srtType struct {
content []byte
}
func (s *srtType) setContent(content []byte) {
s.content = content
}
func (s srtType) getContent() []byte {
return s.content
}
func (s srtType) re() *regexp.Regexp {
return regexp.MustCompile(`(-?\d+):(\d\d):(\d\d)\,(\d{1,3})`)
}
func (s srtType) match2Ms(match []string) int {
hours, _ := strconv.Atoi(match[1])
minutes, _ := strconv.Atoi(match[2])
seconds, _ := strconv.Atoi(match[3])
milliseconds, _ := strconv.Atoi(match[4])
for i := 0; i < 3-len(match[4]); i++ {
milliseconds *= 10
}
sign := 1
if hours < 0 {
sign = -1
}
minutes *= sign
seconds *= sign
milliseconds *= sign
totalMs := (hours*3600+minutes*60+seconds)*1000 + milliseconds
return totalMs
}
func (s srtType) time2Str(totalMs int) string {
sign := 1
if totalMs < 0 {
sign = -1
}
totalMs *= sign
return fmt.Sprintf("%02d:%02d:%02d,%03d",
totalMs/3600000*sign,
(totalMs/60000)%60,
(totalMs/1000)%60,
totalMs%1000)
}
type assType struct {
content []byte
}
func (s *assType) setContent(content []byte) {
s.content = content
}
func (s assType) getContent() []byte {
return s.content
}
func (s assType) re() *regexp.Regexp {
return regexp.MustCompile(`(-?\d+):(\d\d):(\d\d)\.(\d{1,3})`)
}
func (s assType) match2Ms(match []string) int {
hours, _ := strconv.Atoi(match[1])
minutes, _ := strconv.Atoi(match[2])
seconds, _ := strconv.Atoi(match[3])
milliseconds, _ := strconv.Atoi(match[4])
for i := 0; i < 3-len(match[4]); i++ {
milliseconds *= 10
}
sign := 1
if hours < 0 {
sign = -1
}
minutes *= sign
seconds *= sign
milliseconds *= sign
totalMs := (hours*3600+minutes*60+seconds)*1000 + milliseconds
return totalMs
}
func (s assType) time2Str(totalMs int) string {
sign := 1
if totalMs < 0 {
sign = -1
}
totalMs *= sign
return fmt.Sprintf("%d:%02d:%02d.%02d",
totalMs/3600000*sign,
(totalMs/60000)%60,
(totalMs/1000)%60,
totalMs%1000/10)
}
func subtitleShift(s subtitle, shift int) (newLines []string) {
lines := strings.Split(string(s.getContent()), "\n")
newLines = make([]string, 0)
timeRe := s.re()
// if regexp is not empty, then use regexp to match time
var reFrom, reTo *regexp.Regexp
if fromRegexp != "" {
reFrom = regexp.MustCompile(fromRegexp)
}
if toRegexp != "" {
reTo = regexp.MustCompile(toRegexp)
}
from := gFrom
to := gTo
if fromRegexp != "" || toRegexp != "" {
for _, v := range lines {
matches := timeRe.FindAllStringSubmatch(v, 2)
if matches != nil {
ms := s.match2Ms(matches[1])
if fromRegexp != "" && from == 0 {
if reFrom.MatchString(v) {
from = ms
}
}
if toRegexp != "" && to == 0 {
if reTo.MatchString(v) {
to = ms
}
}
}
}
}
linesShifted := 0
for _, v := range lines {
matches := timeRe.FindAllStringSubmatchIndex(v, -1)
if len(matches) == 0 {
newLines = append(newLines, v)
continue
}
var builder strings.Builder
lastPos := 0
for _, matchIdx := range matches {
start, end := matchIdx[0], matchIdx[1]
builder.WriteString(v[lastPos:start])
match := timeRe.FindStringSubmatch(v[start:end])
if match == nil {
builder.WriteString(v[start:end])
lastPos = end
continue
}
totalMs := s.match2Ms(match)
if timeInclude(totalMs, from, to) {
builder.WriteString(s.time2Str(totalMs + shift))
linesShifted++
} else {
builder.WriteString(v[start:end])
}
lastPos = end
}
builder.WriteString(v[lastPos:])
newLines = append(newLines, builder.String())
}
var _from string
var _to string
if from != 0 {
_from = s.time2Str(from)
} else {
_from = "start"
}
if to != 0 {
_to = s.time2Str(to)
} else {
_to = "end"
}
fmt.Printf("From %s to %s, %d lines shifted %dms\n", _from, _to, linesShifted, shift)
return
}