-
Notifications
You must be signed in to change notification settings - Fork 0
/
audiocc.go
353 lines (289 loc) · 7.78 KB
/
audiocc.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
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
package main
import (
"os"
"fmt"
"log"
"image"
"regexp"
"strings"
"runtime"
"io/ioutil"
"path/filepath"
"github.com/JamTools/goff/ffmpeg"
"github.com/JamTools/goff/ffprobe"
"github.com/JamTools/goff/fsutil"
)
type audiocc struct {
DirEntry string
Image string
Ffmpeg ffmpeg.Ffmpeger
Ffprobe ffprobe.Ffprober
Files []string
Workers int
Workdir string
}
func main() {
args, cont := processFlags()
if !cont {
os.Exit(0)
}
ffm, err := ffmpeg.New()
if err != nil {
log.Fatal(err)
}
ffp, err := ffprobe.New()
if err != nil {
log.Fatal(err)
}
// process files using multiple cores
var workers = runtime.NumCPU()
//workers = 1 // DEBUG in single-threaded mode
a := &audiocc{ Ffmpeg: ffm, Ffprobe: ffp, Workers: workers,
DirEntry: filepath.Clean(args[0]) }
err = a.process()
if err != nil {
log.Fatal(err)
}
}
// true if --collection & artist path contains " - "
func skipArtistOnCollection(p string) bool {
if flags.Collection {
pa := strings.Split(p, fsutil.PathSep)
// first folder is artist
if strings.Index(pa[0], " - ") != -1 {
return true
}
}
return false
}
// skip if album folder name contains year (--fast)
func skipFast(p string) bool {
if flags.Fast {
pa := strings.Split(p, fsutil.PathSep)
// last folder is album
t := &info{}
t.fromAlbum(pa[len(pa)-1])
if len(t.Year) > 0 && len(t.Album) > 0 {
return true
}
}
return false
}
// process album art once per folder of files
func (a *audiocc) processArtwork(file string) error {
art := &artwork{ Ffmpeg: a.Ffmpeg, Ffprobe: a.Ffprobe,
ImgDecode: image.DecodeConfig,
PathInfo: getPathInfo(a.DirEntry, file) }
if flags.Write {
var err error
// probe to determine if has embedded artwork
_, err = a.Ffprobe.GetData(art.PathInfo.Fullpath)
if err != nil {
return err
}
a.Image, err = art.processWithParentDir()
if err != nil {
return err
}
}
return nil
}
func (a *audiocc) process() error {
if !flags.Write {
fmt.Printf("\n* To write changes to disk, please provide flag: --write\n")
}
// ensure path is is valid directory
_, err := checkDir(a.DirEntry)
if err != nil {
return err
}
// obtain audio file list
a.Files = fsutil.FilesAudio(a.DirEntry)
// group files by parent directory
err = bundleFiles(a.DirEntry, a.Files, func(indexes []int) error {
pi := getPathInfo(a.DirEntry, a.Files[indexes[0]])
// skip if possible
if skipArtistOnCollection(pi.Dir) || skipFast(pi.Dir) {
return nil
}
fmt.Printf("\nProcessing: %v ...\n", pi.Fulldir)
// process artwork once per folder
err = a.processArtwork(a.Files[indexes[0]])
if err != nil {
return err
}
// create new random workdir within current path
a.Workdir, err = ioutil.TempDir(pi.Fulldir, "")
if err != nil {
return err
}
// TODO: threaded error handling
path := a.processThreaded(indexes)
dir := onlyDir(path)
// remove workDir
os.RemoveAll(a.Workdir)
// if not same dir, rename directory to target dir
if pi.Fulldir != dir {
_, err = mergeFolder(pi.Fulldir, dir)
if err != nil {
return err
}
}
// remove parent folder if no longer contains audio files
parentDir := filepath.Dir(pi.Fulldir)
if len(fsutil.FilesAudio(parentDir)) == 0 {
err = os.RemoveAll(parentDir)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
fmt.Printf("\naudiocc finished.\n")
return nil
}
func (a *audiocc) processThreaded(indexes []int) string {
jobs := make(chan int)
done := make(chan string, a.Workers)
// iterate through files sending them to worker processes
go func() {
for x := range indexes {
jobs <- indexes[x]
}
close(jobs)
}()
// start worker processes
for i := 0; i < a.Workers; i++ {
go func() {
var dir string
for job := range jobs {
var err error
dir, err = a.processFile(job)
if err != nil {
fmt.Printf("\nError: %s\n", err.Error())
}
}
// when jobs channel is closed
done <- dir
}()
}
// wait for all workers to finish
var saveDir string
for i := 0; i < a.Workers; i++ {
saveDir = <-done
}
return saveDir
}
func (a *audiocc) processFile(index int) (string, error) {
pi := getPathInfo(a.DirEntry, a.Files[index])
// info from path & filename
i := newInfo(pi.Dir, pi.File)
// info from embedded tags within audio file
d, err := a.Ffprobe.GetData(pi.Fullpath)
if err != nil {
return pi.Fullpath, err
}
// set artist
if flags.Artist != "" {
i.Artist = flags.Artist
}
if i.Artist == "" {
i.Artist = d.Format.Tags.Artist
}
// combine info w/ embedded tags
i, match := i.matchProbeTags(d.Format.Tags)
// skip if sources match (unless --force)
if match && !flags.Force {
return pi.Fullpath, nil
}
// override artist for consistency
if len(flags.Artist) > 0 {
// force artist which was specified
i.Artist = flags.Artist
} else if flags.Collection {
// artist comes from parent folder name
i.Artist = strings.Split(pi.Dir, fsutil.PathSep)[0]
}
// build resulting path
var path string
if flags.Collection {
// build from DirEntry; include artist then year
path = filepath.Join(a.DirEntry, i.Artist, i.Year)
} else {
// remove current dir from fullpath
path = strings.TrimSuffix(pi.Fulldir, pi.Dir)
}
// append directory generated from info
path = filepath.Join(path, i.toAlbum())
// print changes to be made
p := fmt.Sprintf("%v\n", pi.Fullpath)
if !match {
p += fmt.Sprintf(" * update tags: %#v\n", i)
}
// convert audio (if necessary) & update tags
if pi.Ext != ".flac" || regexp.MustCompile(` - FLAC$`).FindString(pi.Dir) == "" {
// convert to mp3 except flac files with " - FLAC" in folder name
f, err := a.processMp3(pi, i)
if err != nil {
return pi.Fullpath, err
}
// add filename to returning path
_, file := filepath.Split(f)
path = filepath.Join(path, file)
if pi.Fullpath != path {
p += fmt.Sprintf(" * rename to: %v\n", path)
}
} else {
// TODO: use metaflac to edit flac metadata & embedd artwork
p += fmt.Sprintf("\n*** Flac processing with 'metaflac' not yet implemented.\n")
}
// print to console all at once
fmt.Printf(p)
return path, nil
}
func (a *audiocc) processMp3(pi *pathInfo, i *info) (string, error) {
// if already mp3, copy stream; do not convert
quality := flags.Bitrate
if pi.Ext == ".mp3" {
quality = "copy"
}
// TODO: specify lower bitrate if source file is of low bitrate
// build metadata from tag info
ffmeta := ffmpeg.Metadata{ Artist: i.Artist, Album: i.toAlbum(),
Disc: i.Disc, Track: i.Track, Title: i.Title, Artwork: a.Image }
// save new file to Workdir subdir within current path
newFile := filepath.Join(a.Workdir, i.toFile() + ".mp3")
// process or convert to mp3
c := &ffmpeg.Mp3Config{ pi.Fullpath, quality, newFile, ffmeta, flags.Fix }
_, err := a.Ffmpeg.ToMp3(c)
if err != nil {
return newFile, err
}
// ensure output file was written
fi, err := os.Stat(newFile)
if err != nil {
return newFile, err
}
// if flagsWrite & resulting file has size
// TODO: ensure resulting file is good by reading & comparing metadata
if fi.Size() > 0 {
file := filepath.Join(pi.Fulldir, i.toFile() + ".mp3")
if flags.Write {
// delete original
err = os.Remove(pi.Fullpath)
if err != nil {
return file, err
}
// move new to original directory
err = os.Rename(newFile, file)
if err != nil {
return file, err
}
}
return file, nil
}
return newFile, fmt.Errorf("File didn't have size")
}