forked from zaf/resample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresample.go
More file actions
208 lines (188 loc) · 5.82 KB
/
resample.go
File metadata and controls
208 lines (188 loc) · 5.82 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
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
/*
Copyright (C) 2016 - 2018, Lefteris Zafiris <zaf@fastmail.com>
This program is free software, distributed under the terms of
the BSD 3-Clause License. See the LICENSE file
at the top of the source tree.
*/
/*
Package resample implements resampling of PCM-encoded audio.
It uses the SoX Resampler library `libsoxr'.
To install make sure you have libsoxr installed, then run:
go get -u github.com/zaf/resample
The package warps an io.Reader in a Resampler that resamples and
writes all input data. Input should be RAW PCM encoded audio samples.
For usage details please see the code snippet in the cmd folder.
*/
package resample
/*
#cgo LDFLAGS: -lsoxr
#include <stdlib.h>
#include "soxr.h"
*/
import "C"
import (
"errors"
"io"
"runtime"
"unsafe"
)
const (
// Quality settings
Quick = 0 // Quick cubic interpolation
LowQ = 1 // LowQ 16-bit with larger rolloff
MediumQ = 2 // MediumQ 16-bit with medium rolloff
HighQ = 4 // High quality
VeryHighQ = 6 // Very high quality
// Input formats
F32 = 0 // 32-bit floating point PCM
F64 = 1 // 64-bit floating point PCM
I32 = 2 // 32-bit signed linear PCM
I16 = 3 // 16-bit signed linear PCM
byteLen = 8
)
// Resampler resamples PCM sound data.
type Resampler struct {
resampler C.soxr_t
inRate float64 // input sample rate
outRate float64 // output sample rate
channels int // number of input channels
frameSize int // frame size in bytes
destination io.Writer // output data
}
var threads int
func init() {
threads = runtime.NumCPU()
}
// New returns a pointer to a Resampler that implements an io.WriteCloser.
// It takes as parameters the destination data Writer, the input and output
// sampling rates, the number of channels of the input data, the input format
// and the quality setting.
func New(writer io.Writer, inputRate, outputRate float64, channels, format, quality int) (*Resampler, error) {
var err error
var size int
if writer == nil {
return nil, errors.New("io.Writer is nil")
}
if inputRate <= 0 || outputRate <= 0 {
return nil, errors.New("Invalid input or output sampling rates")
}
if channels == 0 {
return nil, errors.New("Invalid channels number")
}
if quality < 0 || quality > 6 {
return nil, errors.New("Invalid quality setting")
}
switch format {
case F64:
size = 64 / byteLen
case F32, I32:
size = 32 / byteLen
case I16:
size = 16 / byteLen
default:
return nil, errors.New("Invalid format setting")
}
var soxr C.soxr_t
var soxErr C.soxr_error_t
// Setup soxr and create a stream resampler
ioSpec := C.soxr_io_spec(C.soxr_datatype_t(format), C.soxr_datatype_t(format))
qSpec := C.soxr_quality_spec(C.ulong(quality), 0)
runtimeSpec := C.soxr_runtime_spec(C.uint(threads))
soxr = C.soxr_create(C.double(inputRate), C.double(outputRate), C.uint(channels), &soxErr, &ioSpec, &qSpec, &runtimeSpec)
if C.GoString(soxErr) != "" && C.GoString(soxErr) != "0" {
err = errors.New(C.GoString(soxErr))
C.free(unsafe.Pointer(soxErr))
return nil, err
}
r := Resampler{
resampler: soxr,
inRate: inputRate,
outRate: outputRate,
channels: channels,
frameSize: size,
destination: writer,
}
C.free(unsafe.Pointer(soxErr))
return &r, err
}
// Reset permits reusing a Resampler rather than allocating a new one.
func (r *Resampler) Reset(writer io.Writer) (err error) {
if r.resampler == nil {
return errors.New("soxr resampler is nil")
}
r.destination = writer
C.soxr_clear(r.resampler)
return
}
// Close clean-ups and frees memory. Should always be called when
// finished using the resampler.
func (r *Resampler) Close() (err error) {
if r.resampler == nil {
return errors.New("soxr resampler is nil")
}
C.soxr_delete(r.resampler)
r.resampler = nil
return
}
// Write resamples PCM sound data. Writes len(p) bytes from p to
// the underlying data stream, returns the number of bytes written
// from p (0 <= n <= len(p)) and any error encountered that caused
// the write to stop early.
func (r *Resampler) Write(p []byte) (i int, err error) {
if r.resampler == nil {
err = errors.New("soxr resampler is nil")
return
}
if len(p) == 0 {
return
}
if fragment := len(p) % (r.frameSize * r.channels); fragment != 0 {
// Drop fragmented frames from the end of input data
p = p[:len(p)-fragment]
}
framesIn := len(p) / r.frameSize / r.channels
if framesIn == 0 {
err = errors.New("Incomplete input frame data")
return
}
framesOut := int(float64(framesIn) * (r.outRate / r.inRate))
if framesOut == 0 {
err = errors.New("Not enough input to generate output")
return
}
dataIn := C.CBytes(p)
dataOut := C.malloc(C.size_t(framesOut * r.channels * r.frameSize))
var soxErr C.soxr_error_t
var read, done C.size_t = 0, 0
var written int
for int(done) < framesOut {
soxErr = C.soxr_process(r.resampler, C.soxr_in_t(dataIn), C.size_t(framesIn), &read, C.soxr_out_t(dataOut), C.size_t(framesOut), &done)
if C.GoString(soxErr) != "" && C.GoString(soxErr) != "0" {
err = errors.New(C.GoString(soxErr))
goto cleanup
}
if int(read) == framesIn && int(done) < framesOut {
// Indicate end of input to the resampler
var d C.size_t = 0
soxErr = C.soxr_process(r.resampler, C.soxr_in_t(nil), C.size_t(0), nil, C.soxr_out_t(dataOut), C.size_t(framesOut), &d)
if C.GoString(soxErr) != "" && C.GoString(soxErr) != "0" {
err = errors.New(C.GoString(soxErr))
goto cleanup
}
done += d
break
}
}
written, err = r.destination.Write(C.GoBytes(dataOut, C.int(int(done)*r.channels*r.frameSize)))
i = int(float64(written) * (r.inRate / r.outRate))
// If we have read all input and flushed all output, avoid to report short writes due
// to output frames missing because of downsampling or other odd reasons.
if err == nil && framesIn == int(read) && framesOut == int(done) {
i = len(p)
}
cleanup:
C.free(dataIn)
C.free(dataOut)
C.free(unsafe.Pointer(soxErr))
return
}