-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathffmpeg.go
111 lines (96 loc) · 1.92 KB
/
ffmpeg.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
package ffmpeg
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"sync"
"github.com/disgoorg/disgo/voice"
"github.com/jonas747/ogg"
)
const (
// Exec is the default path to the ffmpeg executable
Exec = "ffmpeg"
Channels = 2
SampleRate = 48000
BufferSize = 65307
)
var _ voice.OpusFrameProvider = (*AudioProvider)(nil)
func New(ctx context.Context, r io.Reader, opts ...ConfigOpt) (*AudioProvider, error) {
cfg := DefaultConfig()
cfg.Apply(opts)
cmd := exec.CommandContext(ctx, cfg.Exec,
"-i",
"pipe:0",
"-c:a", "libopus",
"-ac", strconv.Itoa(cfg.Channels),
"-ar", strconv.Itoa(cfg.SampleRate),
"-f", "ogg",
"-b:a",
"96K",
"pipe:1",
)
cmd.Stdin = r
pipe, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err = cmd.Start(); err != nil {
return nil, err
}
done, doneFunc := context.WithCancel(context.Background())
return &AudioProvider{
cmd: cmd,
source: r,
pipe: pipe,
d: ogg.NewPacketDecoder(ogg.NewDecoder(bufio.NewReaderSize(pipe, cfg.BufferSize))),
done: done,
doneFunc: doneFunc,
}, nil
}
type AudioProvider struct {
cmd *exec.Cmd
source io.Reader
pipe io.Closer
d *ogg.PacketDecoder
done context.Context
doneFunc context.CancelFunc
}
func (p *AudioProvider) ProvideOpusFrame() ([]byte, error) {
data, _, err := p.d.Decode()
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, os.ErrClosed) {
p.doneFunc()
return nil, io.EOF
}
return nil, fmt.Errorf("error decoding ogg packet: %w", err)
}
return data, nil
}
func (p *AudioProvider) Close() {
if c, ok := p.source.(io.Closer); ok {
_ = c.Close()
}
_ = p.pipe.Close()
p.doneFunc()
}
func (p *AudioProvider) Wait() error {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
<-p.done.Done()
}()
var err error
wg.Add(1)
go func() {
defer wg.Done()
err = p.cmd.Wait()
}()
wg.Wait()
return err
}