-
Notifications
You must be signed in to change notification settings - Fork 46
/
main.go
295 lines (251 loc) · 7.86 KB
/
main.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"errors"
"flag"
"fmt"
"log"
"strings"
"github.com/asticode/go-astiav"
)
var (
input = flag.String("i", "", "the input path")
)
var (
af *astiav.AudioFifo
decodedFrame *astiav.Frame
finalFrame *astiav.Frame
resampledFrame *astiav.Frame
src *astiav.SoftwareResampleContext
)
func main() {
// Handle ffmpeg logs
astiav.SetLogLevel(astiav.LogLevelDebug)
astiav.SetLogCallback(func(c astiav.Classer, l astiav.LogLevel, fmt, msg string) {
var cs string
if c != nil {
if cl := c.Class(); cl != nil {
cs = " - class: " + cl.String()
}
}
log.Printf("ffmpeg log: %s%s - level: %d\n", strings.TrimSpace(msg), cs, l)
})
// Parse flags
flag.Parse()
// Usage
if *input == "" {
log.Println("Usage: <binary path> -i <input path>")
return
}
// Allocate input format context
inputFormatContext := astiav.AllocFormatContext()
if inputFormatContext == nil {
log.Fatal(errors.New("main: input format context is nil"))
}
defer inputFormatContext.Free()
// Open input
if err := inputFormatContext.OpenInput(*input, nil, nil); err != nil {
log.Fatal(fmt.Errorf("main: opening input failed: %w", err))
}
defer inputFormatContext.CloseInput()
// Find stream info
if err := inputFormatContext.FindStreamInfo(nil); err != nil {
log.Fatal(fmt.Errorf("main: finding stream info failed: %w", err))
}
// Loop through streams
var s *astiav.Stream
var cc *astiav.CodecContext
for _, is := range inputFormatContext.Streams() {
// Only process audio
if is.CodecParameters().MediaType() != astiav.MediaTypeAudio {
continue
}
// Store stream
s = is
// Find decoder
c := astiav.FindDecoder(is.CodecParameters().CodecID())
if c == nil {
log.Fatal(errors.New("main: codec is nil"))
}
// Allocate codec context
if cc = astiav.AllocCodecContext(c); cc == nil {
log.Fatal(errors.New("main: codec context is nil"))
}
defer cc.Free()
// Update codec context
if err := is.CodecParameters().ToCodecContext(cc); err != nil {
log.Fatal(fmt.Errorf("main: updating codec context failed: %w", err))
}
// Open codec context
if err := cc.Open(c, nil); err != nil {
log.Fatal(fmt.Errorf("main: opening codec context failed: %w", err))
}
break
}
// No stream
if s == nil {
log.Fatal("main: no audio stream found")
}
// Alloc resample context
src = astiav.AllocSoftwareResampleContext()
defer src.Free()
// Allocate packet
pkt := astiav.AllocPacket()
defer pkt.Free()
// Allocate decoded frame
decodedFrame = astiav.AllocFrame()
defer decodedFrame.Free()
// Allocate resampled frame
resampledFrame = astiav.AllocFrame()
defer resampledFrame.Free()
// For the resampled frame we need to setup mandatory information
resampledFrame.SetChannelLayout(astiav.ChannelLayoutStereo)
resampledFrame.SetSampleFormat(astiav.SampleFormatFltp)
resampledFrame.SetSampleRate(24000)
// Do this only if you want to make sure the resampled frame's number of samples doesn't get
// bigger than a custom value ("200" in our case)
resampledFrame.SetNbSamples(200)
const align = 0
if err := resampledFrame.AllocBuffer(align); err != nil {
log.Fatal(fmt.Errorf("main: allocating buffer failed: %w", err))
}
if err := resampledFrame.AllocSamples(align); err != nil {
log.Fatal(fmt.Errorf("main: allocating samples failed: %w", err))
}
// For the sake of the example we use an audio FIFO to ensure final frames have an exact constant
// number of samples except for the last one. However this is optional and it depends on your use case
finalFrame = astiav.AllocFrame()
defer finalFrame.Free()
finalFrame.SetChannelLayout(resampledFrame.ChannelLayout())
finalFrame.SetNbSamples(resampledFrame.NbSamples())
finalFrame.SetSampleFormat(resampledFrame.SampleFormat())
finalFrame.SetSampleRate(resampledFrame.SampleRate())
if err := finalFrame.AllocBuffer(align); err != nil {
log.Fatal(fmt.Errorf("main: allocating buffer failed: %w", err))
}
if err := finalFrame.AllocSamples(align); err != nil {
log.Fatal(fmt.Errorf("main: allocating samples failed: %w", err))
}
af = astiav.AllocAudioFifo(finalFrame.SampleFormat(), finalFrame.ChannelLayout().Channels(), finalFrame.NbSamples())
defer af.Free()
// Loop
for {
// We use a closure to ease unreferencing the packet
if stop := func() bool {
// Read frame
if err := inputFormatContext.ReadFrame(pkt); err != nil {
if errors.Is(err, astiav.ErrEof) {
return true
}
log.Fatal(fmt.Errorf("main: reading frame failed: %w", err))
}
// Make sure to unreference the packet
defer pkt.Unref()
// Invalid stream
if pkt.StreamIndex() != s.Index() {
return false
}
// Send packet
if err := cc.SendPacket(pkt); err != nil {
log.Fatal(fmt.Errorf("main: sending packet failed: %w", err))
}
// Loop
for {
// We use a closure to ease unreferencing the frame
if stop := func() bool {
// Receive frame
if err := cc.ReceiveFrame(decodedFrame); err != nil {
if errors.Is(err, astiav.ErrEof) || errors.Is(err, astiav.ErrEagain) {
return true
}
log.Fatal(fmt.Errorf("main: receiving frame failed: %w", err))
}
// Make sure to unreference the frame
defer decodedFrame.Unref()
// Log
log.Printf("new decoded frame: nb samples: %d", decodedFrame.NbSamples())
// Resample decoded frame
if err := src.ConvertFrame(decodedFrame, resampledFrame); err != nil {
log.Fatal(fmt.Errorf("main: resampling decoded frame failed: %w", err))
}
// Something was resampled
if nbSamples := resampledFrame.NbSamples(); nbSamples > 0 {
// Log
log.Printf("new resampled frame: nb samples: %d", nbSamples)
// Add resampled frame to audio fifo
if err := addResampledFrameToAudioFIFO(false); err != nil {
log.Fatal(fmt.Errorf("main: adding resampled frame to audio fifo failed: %w", err))
}
// Flush software resample context
if err := flushSoftwareResampleContext(false); err != nil {
log.Fatal(fmt.Errorf("main: flushing software resample context failed: %w", err))
}
}
return false
}(); stop {
break
}
}
return false
}(); stop {
break
}
}
// Flush software resample context
if err := flushSoftwareResampleContext(true); err != nil {
log.Fatal(fmt.Errorf("main: flushing software resample context failed: %w", err))
}
// Success
log.Println("success")
}
func flushSoftwareResampleContext(finalFlush bool) error {
// Loop
for {
// We're making the final flush or there's enough data to flush the resampler
if finalFlush || src.Delay(int64(resampledFrame.SampleRate())) >= int64(resampledFrame.NbSamples()) {
// Flush resampler
if err := src.ConvertFrame(nil, resampledFrame); err != nil {
log.Fatal(fmt.Errorf("main: flushing resampler failed: %w", err))
}
// Log
if resampledFrame.NbSamples() > 0 {
log.Printf("new resampled frame: nb samples: %d", resampledFrame.NbSamples())
}
// Add resampled frame to audio fifo
if err := addResampledFrameToAudioFIFO(finalFlush); err != nil {
log.Fatal(fmt.Errorf("main: adding resampled frame to audio fifo failed: %w", err))
}
// Final flush is done
if finalFlush && resampledFrame.NbSamples() == 0 {
break
}
continue
}
break
}
return nil
}
func addResampledFrameToAudioFIFO(flush bool) error {
// Write
if resampledFrame.NbSamples() > 0 {
if _, err := af.Write(resampledFrame); err != nil {
return fmt.Errorf("main: writing failed: %w", err)
}
}
// Loop
for {
// We're flushing or there's enough data to read
if (flush && af.Size() > 0) || (!flush && af.Size() >= finalFrame.NbSamples()) {
// Read
n, err := af.Read(finalFrame)
if err != nil {
return fmt.Errorf("main: reading failed: %w", err)
}
finalFrame.SetNbSamples(n)
// Log
log.Printf("new final frame: nb samples: %d", finalFrame.NbSamples())
continue
}
break
}
return nil
}