-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
443 lines (410 loc) · 12.4 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
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
436
437
438
439
440
441
442
443
package main
import (
"context"
"fmt"
"github.com/ai-mastering/aimastering-go"
"github.com/urfave/cli"
"io"
"log"
"net/http"
"os"
"sort"
"time"
"github.com/theckman/go-securerandom"
)
var (
gitTag string
gitHash string
buildTime string
goVersion string
goos string
goarch string
)
func uploadAudio(client *aimastering.APIClient, auth context.Context, audioPath string) (int32) {
// upload input audio
if audioPath == "-" {
audio, _, err := client.AudioApi.CreateAudio(auth, map[string]interface{}{
"file": os.Stdin,
})
if err != nil {
log.Fatal(err)
}
return audio.Id
} else {
audioFile, err := os.Open(audioPath)
if err != nil {
log.Fatal(err)
}
defer audioFile.Close()
audio, _, err := client.AudioApi.CreateAudio(auth, map[string]interface{}{
"file": audioFile,
})
if err != nil {
log.Fatal(err)
}
return audio.Id
}
}
func main() {
app := cli.NewApp()
app.Name = "aimastering"
app.EnableBashCompletion = true
app.Version = gitTag + " " + gitHash + " " + goos + "/" + goarch + " " + buildTime + " " + goVersion
app.HelpName = "aimastering"
app.Copyright = "(c) 2019 Bakuage Co., Ltd."
app.Usage = "AI Mastering API CLI client"
randomStr, _ := securerandom.Base64InBytes(32)
accessToken := "guest_" + randomStr
var input string
var output string
var userAgent string
userAgentFlag := cli.StringFlag{
Name: "user-agent",
Usage: "User agent text used for API request",
Hidden: false,
Value: "aimastering-cli",
Destination: &userAgent,
}
//accessTokenFlag := cli.StringFlag{
// Name: "access-token",
// Usage: "AI Mastering API Access Token (retrieved from https://aimastering.com/app/developer)",
// EnvVar: "AIMASTERING_ACCESS_TOKEN",
// Hidden: false,
// Value: "",
// Destination: &accessToken,
//}
inputFlag := cli.StringFlag{
Name: "input, i",
Usage: "Input audio file path. If - is specified, stdin is used.",
Hidden: false,
Value: "",
Destination: &input,
}
outputFlag := cli.StringFlag{
Name: "output, o",
Usage: "Output audio file path. If - is specified, stdout is used.",
Hidden: false,
Value: "",
Destination: &output,
}
app.Commands = []cli.Command{
{
Name: "master",
Usage: "master an audio",
UsageText: "aimastering master --input input.wav --output output.wav [command options]",
HideHelp: false,
Action: func(c *cli.Context) error {
//if accessToken == "" {
// log.Fatal("--access-token required")
//}
if input == "" {
log.Fatal("--input required")
}
if output == "" {
log.Fatal("--output required")
}
cfg := aimastering.NewConfiguration()
cfg.UserAgent = userAgent
log.Printf("User agent:%s\n", userAgent)
client := aimastering.NewAPIClient(cfg)
auth := context.WithValue(context.Background(), aimastering.ContextAPIKey, aimastering.APIKey{
Key: accessToken,
})
// upload input audio
inputAudioId := uploadAudio(client, auth, input)
log.Printf("The input audio was uploaded id %d\n", inputAudioId)
// start the mastering
masteringOptions := map[string]interface{}{
"mode": "custom",
"targetLoudness": float32(c.Float64("target-loudness")),
"targetLoudnessMode": c.String("target-loudness-mode"),
"mastering": float32(c.Float64("mastering-level")) > 0,
"masteringMatchingLevel": float32(c.Float64("mastering-level")),
"masteringAlgorithm": c.String("mastering-algorithm"),
"ceilingMode": c.String("ceiling-mode"),
"ceiling": float32(c.Float64("ceiling")),
"bassPreservation": c.Bool("bass-preservation"),
"preset": c.String("preset"),
"noiseReduction": c.Bool("noise-reduction"),
"lowCutFreq": float32(c.Float64("low-cut-freq")),
"highCutFreq": float32(c.Float64("high-cut-freq")),
"sampleRate": int32(c.Int("sample-rate")),
"bitDepth": int32(c.Int("bit-depth")),
"outputFormat": c.String("output-format"),
"oversample": int32(c.Int("oversample")),
}
if c.String("reference") != "" {
referenceAudioId := uploadAudio(client, auth, input)
log.Printf("The reference audio was uploaded id %d\n", referenceAudioId)
masteringOptions["reference_audio_id"] = referenceAudioId
}
var masteringOptionKeys []string
for k := range masteringOptions {
masteringOptionKeys = append(masteringOptionKeys, k)
}
sort.Strings(masteringOptionKeys)
log.Printf("Mastering options\n")
for _, k := range masteringOptionKeys {
log.Printf("%s:%s\n", k, fmt.Sprint(masteringOptions[k]))
}
mastering, _, err := client.MasteringApi.CreateMastering(auth, inputAudioId, masteringOptions)
if err != nil {
log.Fatal(err)
}
log.Printf("The mastering started id %d\n", mastering.Id)
// wait for the mastering completion
for mastering.Status == "processing" || mastering.Status == "waiting" {
mastering, _, err = client.MasteringApi.GetMastering(auth, mastering.Id)
if err != nil {
log.Fatal(err)
}
log.Printf("waiting for the mastering completion %d%%\n", int(100 * mastering.Progression))
time.Sleep(5 * time.Second)
}
if mastering.Status != "succeeded" {
additionalReason := ""
if mastering.FailureReason == "failed_to_prepare" {
inputAudio, _, err := client.AudioApi.GetAudio(auth, mastering.InputAudioId)
if err != nil {
log.Fatal(err)
}
if inputAudio.Status != "prepared" {
additionalReason += fmt.Sprintf("Input audio preparation failed with status %s because %s", inputAudio.Status, inputAudio.FailureReason)
}
if c.String("reference") != "" {
referenceAudio, _, err := client.AudioApi.GetAudio(auth, mastering.ReferenceAudioId)
if err != nil {
log.Fatal(err)
}
if referenceAudio.Status != "prepared" {
additionalReason += fmt.Sprintf("Reference audio preparation failed with status %s because %s", referenceAudio.Status, referenceAudio.FailureReason)
}
}
}
log.Fatalf("Mastering failed with status %s because %s, %s", mastering.Status, mastering.FailureReason, additionalReason)
}
// download output audio
// notes
// - client.AudioApi.DownloadAudio cannot be used because swagger-codegen doesn't support binary string response in golang
// - instead use GetAudioDownloadToken (to get signed url) + HTTP Get
audioDownloadToken, _, err := client.AudioApi.GetAudioDownloadToken(auth, mastering.OutputAudioId)
// http get signed url
resp, err := http.Get(audioDownloadToken.DownloadUrl)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if output == "-" {
// write output
_, err = io.Copy(os.Stdout, resp.Body)
if err != nil {
log.Fatal(err)
}
log.Print("The Output audio was saved to stdout\n")
} else {
outputAudioFile, err := os.Create(output)
if err != nil {
log.Fatal(err)
}
defer outputAudioFile.Close()
// write output
_, err = io.Copy(outputAudioFile, resp.Body)
if err != nil {
log.Fatal(err)
}
log.Printf("The Output audio was saved to %s\n", output)
}
outputVideo := c.String("output-video")
if outputVideo != "" {
// wait for the video encode completion
for mastering.VideoStatus == "waiting" {
mastering, _, err = client.MasteringApi.GetMastering(auth, mastering.Id)
if err != nil {
log.Fatal(err)
}
log.Print("waiting for the video encode completion\n")
time.Sleep(5 * time.Second)
}
if mastering.VideoStatus != "succeeded" {
log.Fatalf("Video encode failed with status %s", mastering.VideoStatus)
}
// download output video
videoDownloadToken, _, err := client.VideoApi.GetVideoDownloadToken(auth, mastering.OutputVideoId)
// http get signed url
resp, err := http.Get(videoDownloadToken.DownloadUrl)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
outputVideoFile, err := os.Create(outputVideo)
if err != nil {
log.Fatal(err)
}
defer outputVideoFile.Close()
// write output
_, err = io.Copy(outputVideoFile, resp.Body)
if err != nil {
log.Fatal(err)
}
log.Printf("The Output video was saved to %s\n", outputVideo)
}
if c.Bool("remove") {
client.MasteringApi.DeleteMastering(auth, mastering.Id)
}
return nil
},
Flags: []cli.Flag{
//accessTokenFlag,
inputFlag,
outputFlag,
userAgentFlag,
cli.StringFlag{
Name: "reference",
Usage: "Reference audio file path",
Hidden: true,
Value: "",
},
cli.StringFlag{
Name: "output-video",
Usage: "Output video file path. Save video only when specified.",
Hidden: false,
Value: "",
},
cli.Float64Flag{
Name: "target-loudness",
Usage: "Target loudness in dB",
Hidden: false,
Value: -9,
},
cli.StringFlag{
Name: "target-loudness-mode",
Usage: "Target loudness mode loudness/rms/peak/youtube_loudness",
Hidden: false,
Value: "loudness",
},
cli.Float64Flag{
Name: "mastering-level",
Usage: "Mastering level in [0, 1]. 0 means disabled",
Hidden: false,
Value: 0.5,
},
cli.StringFlag{
Name: "mastering-algorithm",
Usage: "Mastering algorithm v1/v2",
Hidden: false,
Value: "v2",
},
cli.Float64Flag{
Name: "ceiling",
Usage: "Output ceiling in dB",
Hidden: false,
Value: -0.5,
},
cli.StringFlag{
Name: "ceiling-mode",
Usage: "Output ceiling mode peak/true_peak/lowpass_true_peak",
Hidden: false,
Value: "true_peak",
},
cli.BoolTFlag{
Name: "bass-preservation",
Usage: "Bass preservation",
Hidden: true,
},
cli.StringFlag{
Name: "preset",
Usage: "Mastering preset",
Hidden: false,
Value: "generic",
},
cli.BoolFlag{
Name: "noise-reduction",
Usage: "Noise reduction",
Hidden: true,
},
cli.Float64Flag{
Name: "low-cut-freq",
Usage: "Low cut frequency in Hz",
Hidden: false,
Value: 20,
},
cli.Float64Flag{
Name: "high-cut-freq",
Usage: "High cut frequency in Hz",
Hidden: false,
Value: 20000,
},
cli.IntFlag{
Name: "sample-rate",
Usage: "Sample rate of output. 0 means same as the input.",
Hidden: false,
Value: 0,
},
cli.IntFlag{
Name: "bit-depth",
Usage: "Bit depth of output. This is used only when output format is wav. 16/24/32",
Hidden: false,
Value: 24,
},
cli.StringFlag{
Name: "output-format",
Usage: "Output format of output. wav/mp3",
Hidden: false,
Value: "wav",
},
cli.IntFlag{
Name: "oversample",
Usage: "Oversample factor 1/2",
Hidden: false,
Value: 2,
},
cli.BoolTFlag{
Name: "remove",
Usage: "Remove the created mastering after finish.",
Hidden: false,
},
},
},
{
Name: "autocomplete",
Usage: "Print commands to initialize autocompletion",
UsageText: "aimastering autocomplete --shell bash",
HideHelp: false,
Action: func(c *cli.Context) error {
switch c.String("shell") {
case "bash":
fmt.Print(`_cli_bash_autocomplete() {
local cur opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _cli_bash_autocomplete aimastering`)
case "zsh":
fmt.Print(`_cli_zsh_autocomplete() {
local -a opts
opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} --generate-bash-completion)}")
_describe 'values' opts
return
}
compdef _cli_zsh_autocomplete aimastering`)
}
return nil
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "shell",
Usage: "Specify shell bash/zsh",
Hidden: false,
Value: "bash",
},
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}