-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp3dir.go
226 lines (181 loc) · 4.32 KB
/
mp3dir.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
package main
import (
"flag"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
)
type TransformAction string
const (
ConvertAction = TransformAction("CONVERT")
CopyAction = TransformAction("COPY")
)
type TransformJob struct {
action TransformAction
source string
dest string
}
func (t *TransformJob) String() string {
return fmt.Sprintf("(%v)\n <= %s\n => %s", t.action, t.source, t.dest)
}
func rebasePath(path string, srclib string, dstlib string) (string, error) {
var result string
// get track path relative to source folder
result, err := filepath.Rel(srclib, path)
if err != nil {
return "", err
}
// rebase relative path into destination folder
result = filepath.Join(dstlib, result)
return result, nil
}
func rebasePathWithSuffix(path string, srclib string, dstlib string, suffix string) (string, error) {
var result string
result, err := rebasePath(path, srclib, dstlib)
if err != nil {
return "", err
}
// change suffix
result = strings.TrimSuffix(result, filepath.Ext(result)) + suffix
return result, nil
}
func isAlac(path string) bool {
cmd := exec.Command(
"ffprobe",
"-v", "error",
"-select_streams", "a:0",
"-show_entries", "stream=codec_name",
"-of", "default=noprint_wrappers=1:nokey=1",
path,
)
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
}
codec := strings.TrimSpace(string(out))
return codec == "alac"
}
func transformLibrary(srclib string, dstlib string) []TransformJob {
jobs := make([]TransformJob, 0)
filepath.WalkDir(srclib, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}
/* Let's convert FLAC and ALAC files.
* Since ALAC uses .m4a as an extension - thaaaaaanks, Apple -
* we need to check if there is actually an ALAC stream (as opposed to AAC).
*/
ext := filepath.Ext(path)
if ext == ".flac" || (ext == ".m4a" && isAlac(path)) {
rebasedPath, err := rebasePathWithSuffix(path, srclib, dstlib, ".mp3")
if err != nil {
panic(err)
}
jobs = append(jobs, TransformJob{
action: ConvertAction,
source: path,
dest: rebasedPath,
})
return nil
}
/* Let's copy lossy files. */
if ext == ".mp3" || ext == ".m4a" {
rebasedPath, err := rebasePath(path, srclib, dstlib)
if err != nil {
panic(err)
}
jobs = append(jobs, TransformJob{
action: CopyAction,
source: path,
dest: rebasedPath,
})
return nil
}
// TODO: handle errors
return nil
})
return jobs
}
func runFFmpeg(source string, dest string) error {
cmd := exec.Command("ffmpeg",
"-y",
/* input file */
"-i", source,
/* mp3 v0 */
"-q:a", "0",
/* output file */
dest,
)
err := cmd.Run()
return err
}
func copyFile(source string, dest string) error {
b, err := os.ReadFile(source)
if err != nil {
return err
}
err = os.WriteFile(dest, b, 0644)
return err
}
func runWorker(inbox chan TransformJob, workerID int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("[%d] Spawned job worker!\n", workerID)
for job := range inbox {
fmt.Printf("[%d] New job: %s\n", workerID, job.String())
switch job.action {
case ConvertAction:
err := runFFmpeg(job.source, job.dest)
if err != nil {
fmt.Printf("[%d] ffmpeg error: %v\n", workerID, err)
}
case CopyAction:
err := copyFile(job.source, job.dest)
if err != nil {
fmt.Printf("[%d] copy error: %v\n", workerID, err)
}
default:
panic("runWorker: reached default case! This should never happen.")
}
}
}
func main() {
var srclib string
var dstlib string
var workers int
flag.StringVar(&srclib, "i", "",
"Source folder (aka. your lossless music library)")
flag.StringVar(&dstlib, "o", "",
"Destination folder (aka. the lossy copy)")
flag.IntVar(&workers, "j", 4,
"Number of workers for parallel processing")
flag.Parse()
if srclib == "" {
fmt.Println("Missing: -i")
flag.PrintDefaults()
os.Exit(-1)
}
if dstlib == "" {
fmt.Println("Missing: -o")
flag.PrintDefaults()
os.Exit(-1)
}
jobs := transformLibrary(srclib, dstlib)
jobChannel := make(chan TransformJob, len(jobs))
for _, job := range jobs {
/* Make sure the target directory exists */
os.MkdirAll(filepath.Dir(job.dest), 0755)
jobChannel <- job
}
close(jobChannel)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go runWorker(jobChannel, i, &wg)
}
wg.Wait()
}