-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
245 lines (228 loc) · 7.07 KB
/
main.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
// eac3to wrapper program.
//
// This program wraps eac3to and fixes long-standing bugs:
// (1) unable to decompress zlib deflated PGS subtitles in mkv.
// It will transparently uses mkvmerge to extract *.sup.
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/AkarinVS/eac3to-wrapper/mkv"
)
const prefix = "eac3to-wrapper"
var (
version string = "unknown" // fill when building, with -ldflags=-X
// path to essential executables
mkvExtractPath string
mkvMergePath string
eac3toPath string
)
// findExe locates the path for executable of given name.
// It will try the executable's directory and then relative paths in altdir.
func findExe(name string, altdir ...string) (path string) {
self, err := os.Executable()
if err != nil {
log.Fatal(err)
}
selfi, err := os.Stat(self)
if err != nil {
log.Fatal(err)
}
dir := filepath.Dir(self)
if runtime.GOOS == "windows" {
name += ".exe"
}
for _, path := range append([]string{"."}, altdir...) {
fn := filepath.Join(dir, path, name)
// XXX: we only determines if the file exists, and not bother to check its FileMode.
fi, err := os.Stat(fn)
if err == nil && !fi.IsDir() {
// also skip ourselves to avoid endless loops.
if os.SameFile(selfi, fi) {
log.Printf("skipped %s while looking for %s", fn, name)
continue
}
return fn
}
}
log.Printf("unable to locate %s from %s", name, dir)
return ""
}
// checkEnv checks if the execution environment is sane.
func checkEnv() {
if os.Getenv("EAC3TO_WRAPPER_DEV") == "" {
logf := fmt.Sprintf("%s_%s_%04X.log", "EAC", time.Now().Format("20060102-1504"), os.Getpid())
for _, dir := range []string{"./log", "../../log"} {
fn := filepath.Join(dir, logf)
fd, err := os.OpenFile(fn, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err == nil {
log.SetOutput(fd)
log.SetFlags(log.Lmicroseconds) // no need to output Ldate to dated log file
fmt.Fprintf(os.Stderr, "log file at %s\n", fn)
redirectStderr(fd)
break
}
}
}
// There are three different places eac3to-wrapper could be placed:
// (1) during development, at the same directory with mkv{extract,merge} and eac3to.
// (2) under tools/eac3to.
mkvExtractPath = findExe("mkvextract", "../mkvtoolnix")
mkvMergePath = findExe("mkvmerge", "../mkvtoolnix")
eac3toPath = findExe("eac3to", "../eac3to", "../eac3to.real")
if mkvExtractPath == "" || mkvMergePath == "" || eac3toPath == "" {
log.Fatal("unable to locate essential programs, abort")
}
log.Printf("located %s %s %s", mkvExtractPath, mkvMergePath, eac3toPath)
}
// getMkvTracks uses `mkvmerge -J` on the given mkvf file and parses the result
// into mkv.Info.
func getMkvTracks(mkvf string) (*mkv.Info, error) {
cmd := exec.Command(mkvMergePath, "-J", mkvf)
log.Printf("running %v", cmd)
out, err := cmd.Output()
if err != nil {
return nil, err
}
info, err := mkv.ParseInfo(out)
if err != nil {
return nil, err
}
return info, nil
}
// getTrackMapping processes mkv.Info and generate a eac3to track to mkvtoolnix
// track mapping table.
//
// mkvtoolnix always uses the 0-based physical track ID, but eac3to's 1-based
// track ID is more complicated:
// 1. video first, then audio, and finally subtitle.
// 2. within each group, sort by the track number property of the track.
func getTrackMapping(info *mkv.Info) []int {
tracks := append([]*mkv.Track(nil), info.Tracks...)
sort.Slice(tracks, func(i, j int) bool {
ti, tj := tracks[i].Type(), tracks[j].Type()
if ti < tj {
return true
} else if ti == tj {
return tracks[i].Number < tracks[j].Number
}
return false
})
mapping := make([]int, len(tracks)+1)
mapping[0] = -1 // poison the invalid eac3to track 0
for i, trk := range tracks {
mapping[i+1] = trk.Id
}
return mapping
}
// run executes the given program with the given arguments.
// If captureStdout is true, then stdout will be redirected to stderr.
func run(prog string, args []string, captureStdout bool) error {
cmd := exec.Command(prog, args...)
log.Printf("running %v", cmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if captureStdout {
cmd.Stdout = os.Stderr
}
return cmd.Run()
}
// fileHasSuffix determines if a filename has a given suffix, taking into
// consideration of platform case (in)sensitivity.
func fileHasSuffix(filename string, suffix string) bool {
if runtime.GOOS == "windows" {
filename = strings.ToLower(filename)
suffix = strings.ToLower(suffix)
}
return filepath.Ext(filename) == suffix
}
// Type Track represents a track extraction with eac3to.
type Track struct {
Id int
Filename string
}
var extractTrackRe = regexp.MustCompile(`^([1-9][0-9]*):(.*)$`)
// parseEac3toArgs approximately parses eac3to args and see if workaround is
// necessary.
// Specially, if it's extracting from mkv, then mkvFile will be the input mkv
// file, and tracks will be all the *.sup subtitle tracks.
// Finally, filtered arguments will be returned as newArgs.
func parseEac3toArgs(args []string) (newArgs []string, mkvFile string, tracks []Track) {
for i := 0; i < len(args); i++ {
arg := args[i]
newArgsPrev := newArgs
newArgs = append(newArgs, arg)
if arg[0] != '-' && arg[0] != '+' {
// check for mkv filename
if fileHasSuffix(arg, ".mkv") && mkvFile == "" {
mkvFile = arg
}
// check for track extraction
if m := extractTrackRe.FindStringSubmatch(arg); len(m) == 3 {
var trk Track
trk.Id, _ = strconv.Atoi(m[1])
trk.Filename = m[2]
if trk.Filename == "" && len(args) > i+1 {
trk.Filename = args[i+1]
newArgs = append(newArgs, trk.Filename)
i++
} else {
// we proactively split the extraction into the canonical
// two argument "TID:" "FILENAME" format to workaround
// Windows' command line issue:
// eac3to implements its own command line argument splitter,
// and it will treat 2:"file name.flac" differently from
// "2:file name.flac".
newArgs = newArgsPrev
newArgs = append(newArgs, fmt.Sprintf("%d:", trk.Id), trk.Filename)
}
// only intercept *.sup extractions from *.mkv
if mkvFile != "" && fileHasSuffix(trk.Filename, ".sup") {
tracks = append(tracks, trk)
newArgs = newArgsPrev // remove this extraction
continue
}
}
}
}
log.Printf("translated %q, mkv %q, tracks %v", newArgs, mkvFile, tracks)
return
}
func main() {
checkEnv()
log.Printf("version %s, command line %q", version, os.Args)
nargs, mkvf, tracks := parseEac3toArgs(os.Args[1:])
if mkvf != "" && len(tracks) > 0 {
info, err := getMkvTracks(mkvf)
if err != nil {
log.Fatal(err)
}
log.Printf("%#v", *info)
mapping := getTrackMapping(info)
log.Printf("track mapping from eac3to to mkvtoolnix: %v", mapping)
// build mkvextract args
extArgs := []string{mkvf, "tracks"}
for _, trk := range tracks {
extArgs = append(extArgs, fmt.Sprintf("%d:%s", mapping[trk.Id], trk.Filename))
}
err = run(mkvExtractPath, extArgs, true)
if err != nil {
log.Fatal(err)
}
log.Printf("mkvextract succeeded.")
}
err := run(eac3toPath, nargs, false)
if err != nil {
log.Fatal(err)
}
log.Printf("%s succeeded.", prefix)
}