-
Notifications
You must be signed in to change notification settings - Fork 17
/
opus.go
238 lines (206 loc) · 5.81 KB
/
opus.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
package opus
import (
"bytes"
"crypto/rand"
"encoding/binary"
"fmt"
"math"
"math/big"
"github.com/digital-dream-labs/opus-go/ogg"
opus "gopkg.in/hraban/opus.v2"
)
// FrameSizes is a list of valid frame sizes for Opus encoding
var FrameSizes = []float32{60, 40, 20, 10, 5, 2.5}
// OggStream is an encoder that takes audio samples and encodes them
// using the Opus audio codec into an Ogg container, using the given
// settings.
type OggStream struct {
SampleRate uint
Channels uint
Bitrate uint
FrameSize float32
Complexity uint
stream ogg.Stream
encoder *opus.Encoder
encbuf []byte
decoder *opus.Decoder
}
// EncodeBytes takes a byte array of little-endian int16 PCM
// samples and encodes them into the Ogg container, returning
// any bytes generated by doing so (could be zero if a page
// flush is not triggered by the encode).
func (s *OggStream) EncodeBytes(audio []byte) ([]byte, error) {
samples := bytesToSamples(audio)
return s.Encode(samples)
}
// Encode takes an array of int16 PCM samples and encodes
// them into the Ogg container, returning any bytes
// generated by doing so (could be zero if a page flush
// is not triggered by the encode).
func (s *OggStream) Encode(audio []int16) ([]byte, error) {
if s.SampleRate == 0 || s.Channels == 0 {
return nil, fmt.Errorf("Invalid sample rate/channels combo, need non-zero: %d/%d", s.SampleRate, s.Channels)
}
if s.FrameSize == 0 {
s.FrameSize = 20
}
out := bytes.Buffer{}
// to be safe, make encoder buffer 2x the needed size for a frame size's worth of
// samples @ target bitrate
if s.encbuf == nil {
bufBits := uint(2*s.FrameSize) * s.Bitrate / 1000
s.encbuf = make([]byte, bufBits/8)
}
for len(audio) > 0 {
nSamples := len(audio)
i, err := s.getFrameSamples(uint(nSamples))
if err != nil {
return nil, err
}
buf, err := s.encodeFrame(audio[:i])
if err != nil {
return nil, err
}
audio = audio[i:]
if n, err := out.Write(buf); n != len(buf) || err != nil {
return nil, getWriteError(err, n, "Invalid output write size")
}
}
return out.Bytes(), nil
}
func (s *OggStream) Decode(oggBytes []byte) ([]byte, error) {
toReturn := make([]byte, 0)
err := s.stream.SubmitDecodeBytes(oggBytes)
if err != nil {
return nil, err
}
if s.decoder == nil {
channels, sampleRate, suberr := s.stream.ReadInfoFromHeaders()
if suberr != nil {
return nil, suberr
}
dec, suberr := opus.NewDecoder(sampleRate, channels)
if suberr != nil {
return nil, suberr
}
s.decoder = dec
}
for {
buf, err := s.stream.DecodeBytesOut()
if err != nil {
return nil, err
} else if buf == nil {
break
}
sampleBuf := make([]int16, 4096)
nDecoded, err := s.decoder.Decode(buf, sampleBuf)
if err != nil {
return nil, err
}
trimmedBuf := sampleBuf[:nDecoded]
bytesOut := samplesToBytes(trimmedBuf)
toReturn = append(toReturn, bytesOut...)
}
return toReturn, nil
}
// Flush attempts to flush any possible completed pages from the Ogg container
// if data was submitted that didn't generate new page output.
func (s *OggStream) Flush() []byte {
return s.stream.Flush()
}
func (s *OggStream) encodeFrame(samples []int16) ([]byte, error) {
frameSize := len(samples)
frameSizeMs := float32(frameSize) / float32(s.Channels) * 1000 / float32(s.SampleRate)
switch frameSizeMs {
case 2.5, 5, 10, 20, 40, 60:
default:
return nil, fmt.Errorf("Illegal frame size: %d samples (%f ms)", frameSize, frameSizeMs)
}
buf := bytes.Buffer{}
if s.encoder == nil {
// this is the first stream; initialize
randomID, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt32))
if err != nil {
return nil, err
}
s.stream.Init(int32(randomID.Int64()))
enc, err := opus.NewEncoder(int(s.SampleRate), int(s.Channels), opus.AppVoIP)
if err != nil {
return nil, err
}
s.encoder = enc
// defaults
if s.Bitrate == 0 {
s.Bitrate = 40000
}
_ = s.encoder.SetBitrate(int(s.Bitrate))
_ = s.encoder.SetComplexity(int(s.Complexity))
// get header
if err := s.writeHeader(&buf); err != nil {
return nil, err
}
}
n, err := s.encoder.Encode(samples, s.encbuf)
if err != nil {
return nil, err
}
// opus is encoded at 48khz, so the number of samples we put in the packet
// must assume that
opusSamples := frameSizeMs * 48000 / 1000
packet := s.stream.NewSeqPacket(s.encbuf[:n], int64(opusSamples))
pagebuf, _, err := s.stream.SubmitPacket(packet, false)
if err != nil {
return nil, err
}
if len(pagebuf) > 0 {
wn, err := buf.Write(pagebuf)
if err != nil {
return nil, err
}
if wn != len(pagebuf) {
return nil, fmt.Errorf("Failed to write full buffer size %d: %d", n, wn)
}
}
return buf.Bytes(), nil
}
func bytesToSamples(buf []byte) []int16 {
samples := make([]int16, len(buf)/2)
for i := 0; i < len(buf)/2; i++ {
samples[i] = int16(binary.LittleEndian.Uint16(buf[i*2:]))
}
return samples
}
func samplesToBytes(buf []int16) []byte {
output := make([]byte, len(buf)*2)
for i := 0; i < len(buf); i++ {
binary.LittleEndian.PutUint16(output[2*i:2*(i+1)], uint16(buf[i]))
}
return output
}
func (s *OggStream) getFrameSamples(samples uint) (int, error) {
nSamples := func(fs float32) uint {
return uint(fs * float32(s.Channels*s.SampleRate/1000))
}
ideal := nSamples(s.FrameSize)
if ideal <= samples {
return int(ideal), nil
}
// loop over valid frame sizes until we find one small enough to encode this
for _, val := range FrameSizes {
// if this is bigger than our frame size we already know it won't work
if val >= s.FrameSize {
continue
}
i := nSamples(val)
if i <= samples {
return int(i), nil
}
}
return 0, fmt.Errorf("Could not find valid frame size for %d samples @ %d/%d sample rate/channels", samples, s.Channels, s.SampleRate)
}
func getWriteError(err error, n int, desc string) error {
if err != nil {
return err
}
return fmt.Errorf("%s: %d", desc, n)
}