-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconversion.go
More file actions
112 lines (99 loc) · 2.44 KB
/
conversion.go
File metadata and controls
112 lines (99 loc) · 2.44 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
package tinycast
import (
"context"
"fmt"
"io"
"log"
"net/http"
"strconv"
"pipelined.dev/audio/mp3"
"pipelined.dev/pipe"
)
// BitRateMode describes how the MP3 encoder should apply bit rate limits.
type BitRateMode string
// BitRateModes are the modes accepted by the encoder.
var BitRateModes = []BitRateMode{
"ABR",
"CBR",
"VBR",
}
// ParseBitRateMode returns a BitRateMode if it matches the given string or an
// error.
func ParseBitRateMode(in string) (BitRateMode, error) {
for _, m := range BitRateModes {
if in == string(m) {
return m, nil
}
}
return BitRateModes[0], fmt.Errorf("invalid bit rate mode '%s'", in)
}
// ToMp3BitRateMode converts a BitRateMode and BitRate to an mp3.BitRateMode.
func (brm BitRateMode) ToMp3BitRateMode(br BitRate) mp3.BitRateMode {
switch brm {
case BitRateModes[0]:
return mp3.ABR(br)
case BitRateModes[1]:
return mp3.CBR(br)
case BitRateModes[2]:
return mp3.VBR(br)
default:
log.Panicf("Could not find bitrate")
return mp3.ABR(0)
}
}
// BitRate used to encode an audio file.
type BitRate int
// BitRates supported by the MP3 encoder.
var BitRates = []BitRate{
16,
32,
64,
}
// ParseBitRate converts a string version of BitRate.
func ParseBitRate(in string) (BitRate, error) {
for _, m := range BitRates {
if in == m.ToString() {
return m, nil
}
}
return BitRates[0], fmt.Errorf("invalid bit rate '%s'", in)
}
// ToString returns a string version of the BitRate.
func (br BitRate) ToString() string {
return strconv.FormatInt(int64(br), 10)
}
// ChannelModes supported by the MP3 encoder.
var ChannelModes = []mp3.ChannelMode{
mp3.Mono,
mp3.Stereo,
mp3.JointStereo,
}
// ParseChannelMode translates from the string version of a ChannelMode.
func ParseChannelMode(in string) (mp3.ChannelMode, error) {
for _, m := range ChannelModes {
if in == m.String() {
return m, nil
}
}
return ChannelModes[0], fmt.Errorf("invalid channel mode '%s'", in)
}
func transform(c context.Context, cfg ConversionConfig, out io.Writer) error {
resp, err := http.Get(cfg.URL)
if err != nil {
return err
}
defer resp.Body.Close()
bufferSize := 1024 * 1024
p, err := pipe.New(bufferSize, pipe.Line{
Source: mp3.Source(resp.Body),
Sink: mp3.Sink(out, cfg.BitRateMode.ToMp3BitRateMode(cfg.BitRate), cfg.ChannelMode, mp3.DefaultEncodingQuality),
})
if err != nil {
log.Fatalf("failed to bind line: %v", err)
}
err = pipe.Wait(p.Start(c))
if err != nil {
return err
}
return nil
}