-
Notifications
You must be signed in to change notification settings - Fork 46
/
encoder.go
279 lines (249 loc) · 7.13 KB
/
encoder.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
package wav
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"time"
"github.com/go-audio/audio"
"github.com/go-audio/riff"
)
// Encoder encodes LPCM data into a wav containter.
type Encoder struct {
w io.WriteSeeker
buf *bytes.Buffer
SampleRate int
BitDepth int
NumChans int
// A number indicating the WAVE format category of the file. The content of
// the <format-specific-fields> portion of the ‘fmt’ chunk, and the
// interpretation of the waveform data, depend on this value. PCM = 1 (i.e.
// Linear quantization) Values other than 1 indicate some form of
// compression.
WavAudioFormat int
// Metadata contains metadata to inject in the file.
Metadata *Metadata
WrittenBytes int
frames int
pcmChunkStarted bool
pcmChunkSizePos int
wroteHeader bool // true if we've written the header out
}
// NewEncoder creates a new encoder to create a new wav file.
// Don't forget to add Frames to the encoder before writing.
func NewEncoder(w io.WriteSeeker, sampleRate, bitDepth, numChans, audioFormat int) *Encoder {
return &Encoder{
w: w,
buf: bytes.NewBuffer(make([]byte, 0, bytesNumFromDuration(time.Minute, sampleRate, bitDepth)*numChans)),
SampleRate: sampleRate,
BitDepth: bitDepth,
NumChans: numChans,
WavAudioFormat: audioFormat,
}
}
// AddLE serializes and adds the passed value using little endian
func (e *Encoder) AddLE(src interface{}) error {
e.WrittenBytes += binary.Size(src)
return binary.Write(e.w, binary.LittleEndian, src)
}
// AddBE serializes and adds the passed value using big endian
func (e *Encoder) AddBE(src interface{}) error {
e.WrittenBytes += binary.Size(src)
return binary.Write(e.w, binary.BigEndian, src)
}
func (e *Encoder) addBuffer(buf *audio.IntBuffer) error {
if buf == nil {
return fmt.Errorf("can't add a nil buffer")
}
frameCount := buf.NumFrames()
// performance tweak: setup a buffer so we don't do too many writes
var err error
for i := 0; i < frameCount; i++ {
for j := 0; j < buf.Format.NumChannels; j++ {
v := buf.Data[i*buf.Format.NumChannels+j]
switch e.BitDepth {
case 8:
if err = binary.Write(e.buf, binary.LittleEndian, uint8(v)); err != nil {
return err
}
case 16:
if err = binary.Write(e.buf, binary.LittleEndian, int16(v)); err != nil {
return err
}
case 24:
if err = binary.Write(e.buf, binary.LittleEndian, audio.Int32toInt24LEBytes(int32(v))); err != nil {
return err
}
case 32:
if err = binary.Write(e.buf, binary.LittleEndian, int32(v)); err != nil {
return err
}
default:
return fmt.Errorf("can't add frames of bit size %d", e.BitDepth)
}
}
e.frames++
}
if n, err := e.w.Write(e.buf.Bytes()); err != nil {
e.WrittenBytes += n
return err
}
e.WrittenBytes += e.buf.Len()
e.buf.Reset()
return nil
}
func (e *Encoder) writeHeader() error {
if e.wroteHeader {
return errors.New("already wrote header")
}
e.wroteHeader = true
if e == nil {
return fmt.Errorf("can't write a nil encoder")
}
if e.w == nil {
return fmt.Errorf("can't write to a nil writer")
}
if e.WrittenBytes > 0 {
return nil
}
// riff ID
if err := e.AddLE(riff.RiffID); err != nil {
return err
}
// file size uint32, to update later on.
if err := e.AddLE(uint32(4294967295)); err != nil {
return err
}
// wave headers
if err := e.AddLE(riff.WavFormatID); err != nil {
return err
}
// form
if err := e.AddLE(riff.FmtID); err != nil {
return err
}
// chunk size
if err := e.AddLE(uint32(16)); err != nil {
return err
}
// wave format
if err := e.AddLE(uint16(e.WavAudioFormat)); err != nil {
return err
}
// num channels
if err := e.AddLE(uint16(e.NumChans)); err != nil {
return fmt.Errorf("error encoding the number of channels - %w", err)
}
// samplerate
if err := e.AddLE(uint32(e.SampleRate)); err != nil {
return fmt.Errorf("error encoding the sample rate - %w", err)
}
blockAlign := e.NumChans * e.BitDepth / 8
// avg bytes per sec
if err := e.AddLE(uint32(e.SampleRate * blockAlign)); err != nil {
return fmt.Errorf("error encoding the avg bytes per sec - %w", err)
}
// block align
if err := e.AddLE(uint16(blockAlign)); err != nil {
return err
}
// bits per sample
if err := e.AddLE(uint16(e.BitDepth)); err != nil {
return fmt.Errorf("error encoding bits per sample - %w", err)
}
return nil
}
// Write encodes and writes the passed buffer to the underlying writer.
// Don't forget to Close() the encoder or the file won't be valid.
func (e *Encoder) Write(buf *audio.IntBuffer) error {
if !e.wroteHeader {
if err := e.writeHeader(); err != nil {
return err
}
}
if !e.pcmChunkStarted {
// sound header
if err := e.AddLE(riff.DataFormatID); err != nil {
return fmt.Errorf("error encoding sound header %w", err)
}
e.pcmChunkStarted = true
// write a temporary chunksize
e.pcmChunkSizePos = e.WrittenBytes
if err := e.AddLE(uint32(4294967295)); err != nil {
return fmt.Errorf("%w when writing wav data chunk size header", err)
}
}
return e.addBuffer(buf)
}
// WriteFrame writes a single frame of data to the underlying writer.
func (e *Encoder) WriteFrame(value interface{}) error {
if !e.wroteHeader {
e.writeHeader()
}
if !e.pcmChunkStarted {
// sound header
if err := e.AddLE(riff.DataFormatID); err != nil {
return fmt.Errorf("error encoding sound header %w", err)
}
e.pcmChunkStarted = true
// write a temporary chunksize
e.pcmChunkSizePos = e.WrittenBytes
if err := e.AddLE(uint32(4294967295)); err != nil {
return fmt.Errorf("%w when writing wav data chunk size header", err)
}
}
e.frames++
return e.AddLE(value)
}
func (e *Encoder) writeMetadata() error {
chunkData := encodeInfoChunk(e)
if err := e.AddBE(CIDList); err != nil {
return fmt.Errorf("failed to write the LIST chunk ID: %w", err)
}
if err := e.AddLE(uint32(len(chunkData))); err != nil {
return fmt.Errorf("failed to write the LIST chunk size: %w", err)
}
return e.AddBE(chunkData)
}
// Close flushes the content to disk, make sure the headers are up to date
// Note that the underlying writer is NOT being closed.
func (e *Encoder) Close() error {
if e == nil || e.w == nil {
return nil
}
// inject metadata at the end to not trip implementation not supporting
// metadata chunks
if e.Metadata != nil {
if err := e.writeMetadata(); err != nil {
return fmt.Errorf("failed to write metadata - %w", err)
}
}
// go back and write total size in header
if _, err := e.w.Seek(4, 0); err != nil {
return err
}
if err := e.AddLE(uint32(e.WrittenBytes) - 8); err != nil {
return fmt.Errorf("%w when writing the total written bytes", err)
}
// rewrite the audio chunk length header
if e.pcmChunkSizePos > 0 {
if _, err := e.w.Seek(int64(e.pcmChunkSizePos), 0); err != nil {
return err
}
chunksize := uint32((int(e.BitDepth) / 8) * int(e.NumChans) * e.frames)
if err := e.AddLE(uint32(chunksize)); err != nil {
return fmt.Errorf("%w when writing wav data chunk size header", err)
}
}
// jump back to the end of the file.
if _, err := e.w.Seek(0, 2); err != nil {
return err
}
switch e.w.(type) {
case *os.File:
return e.w.(*os.File).Sync()
}
return nil
}