forked from go-audio/wav
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
222 lines (198 loc) · 5.57 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
package wav
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"github.com/go-audio/audio"
"github.com/mattetti/audio/riff"
)
// Encoder encodes LPCM data into a wav containter.
type Encoder struct {
w io.WriteSeeker
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
WrittenBytes int
frames int
pcmChunkStarted bool
pcmChunkSizePos int
}
// 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,
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
bb := bytes.NewBuffer(nil)
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(bb, binary.LittleEndian, uint8(v)); err != nil {
return err
}
case 16:
if err = binary.Write(bb, binary.LittleEndian, int16(v)); err != nil {
return err
}
case 24:
if err = binary.Write(bb, binary.LittleEndian, audio.Int32toInt24LEBytes(int32(v))); err != nil {
return err
}
case 32:
if err = binary.Write(bb, 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(bb.Bytes()); err != nil {
e.WrittenBytes += n
return err
}
e.WrittenBytes += bb.Len()
return nil
}
func (e *Encoder) writeHeader() error {
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(42)); 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 - %v", err)
}
// samplerate
if err := e.AddLE(uint32(e.SampleRate)); err != nil {
return fmt.Errorf("error encoding the sample rate - %v", 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 - %v", 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 - %v", err)
}
return nil
}
// Write encodes and writes the passed buffer to the underlying writer.
// Don't forger to Close() the encoder or the file won't be valid.
func (e *Encoder) Write(buf *audio.IntBuffer) error {
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 %v", err)
}
e.pcmChunkStarted = true
// write a temporary chunksize
e.pcmChunkSizePos = e.WrittenBytes
if err := e.AddLE(uint32(42)); err != nil {
return fmt.Errorf("%v when writing wav data chunk size header", err)
}
}
return e.addBuffer(buf)
}
// Close flushes the content to disk, make sure the headers are up to date
// Note that the underlying writter is NOT being closed.
func (e *Encoder) Close() error {
if e == nil || e.w == nil {
return nil
}
// 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("%v 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("%v 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
}