-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodec2.go
More file actions
77 lines (65 loc) · 1.67 KB
/
codec2.go
File metadata and controls
77 lines (65 loc) · 1.67 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
package dsd
// #cgo CFLAGS: -Iinclude -I/usr/local/include -L/usr/local/lib
// #cgo LDFLAGS: -lm -lcodec2 -L/usr/local/lib
/*
#include <inttypes.h>
#include <codec2/codec2.h>
typedef struct CODEC2 codec2_t;
*/
import "C"
import (
"fmt"
"unsafe"
)
const (
Codec2Mode3200 uint8 = iota
Codec2Mode2400
Codec2Mode1600
Codec2Mode1400
Codec2Mode1300
Codec2Mode1200
Codec2Mode700
Codec2Mode700B
)
type Codec2 struct {
codec2 *C.codec2_t
samplesPerFrame int
bitsPerFrame int
}
func NewCodec2(mode uint8) *Codec2 {
vs := &Codec2{}
vs.codec2 = C.codec2_create(C.int(mode))
vs.samplesPerFrame = int(C.codec2_samples_per_frame(vs.codec2))
vs.bitsPerFrame = int(C.codec2_bits_per_frame(vs.codec2))
return vs
}
func (vs *Codec2) Close() error {
if vs.codec2 == nil {
return ErrClosed
}
C.codec2_destroy(vs.codec2)
vs.codec2 = nil
return nil
}
func (vs *Codec2) Decode(bits []byte) ([]float32, error) {
if len(bits) != vs.bitsPerFrame {
return nil, fmt.Errorf("dsd: codec2 required %d bits per frame, got %d", vs.bitsPerFrame, len(bits))
}
var (
u = make([]uint16, vs.samplesPerFrame)
)
C.codec2_decode(vs.codec2, (*C.short)(unsafe.Pointer(&u[0])), (*C.uchar)(unsafe.Pointer(&bits[0])))
return u16stof32s(u), nil
}
func (vs *Codec2) Encode(samples []float32) ([]byte, error) {
if len(samples) != vs.samplesPerFrame {
return nil, fmt.Errorf("dsd: codec2 required %d samples per frame, got %d", vs.samplesPerFrame, len(samples))
}
var (
s = f32stou16s(samples)
bits = make([]byte, vs.bitsPerFrame)
)
C.codec2_encode(vs.codec2, (*C.uchar)(unsafe.Pointer(&bits[0])), (*C.short)(unsafe.Pointer(&s[0])))
return bits, nil
}
var _ (VoiceStream) = (*Codec2)(nil)