-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathffmpeg.go
404 lines (367 loc) · 9.24 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package thumbnailer
// #cgo pkg-config: libavformat libavutil libavcodec libswscale
// #cgo CFLAGS: -std=c11
// #cgo LDFLAGS: -lm
// #include "ffmpeg.h"
import "C"
import (
"context"
"io"
"strconv"
"sync"
"time"
"unsafe"
"github.com/zRedShift/seekstream"
)
//export readCallback
func readCallback(opaque unsafe.Pointer, buf *C.uint8_t, bufSize C.int) C.int {
ctx, ok := ctxMap.context(opaque)
if !ok {
return C.int(avErrUnknown)
}
p := (*[1 << 30]byte)(unsafe.Pointer(buf))[:bufSize:bufSize]
n, err := ctx.file.Read(p)
if n > 0 || err == nil {
return C.int(n)
}
switch err {
case io.EOF:
return C.int(avErrEOF)
default:
return C.int(avErrUnknown)
}
}
////export writeCallback
//func writeCallback(opaque unsafe.Pointer, buf *C.uint8_t, bufSize C.int) C.int {
// ctx, ok := ctxMap.file(opaque)
// if !ok {
// return C.int(avErrUnknown)
// }
// p := (*[1 << 30]byte)(unsafe.Pointer(buf))[:bufSize:bufSize]
// n, err := ctx.Write(p)
// if err != nil {
// return C.int(avErrUnknown)
// }
// return C.int(n)
//}
//export seekCallback
func seekCallback(opaque unsafe.Pointer, offset C.int64_t, whence C.int) C.int64_t {
ctx, ok := ctxMap.context(opaque)
if !ok {
return C.int64_t(avErrUnknown)
}
if !ctx.file.SeekEnd && whence >= C.SEEK_END {
f, ok := ctx.file.Reader.(*seekstream.File)
if !ok || !f.IsDone() {
return C.int64_t(avErrUnknown)
}
ctx.file.SeekEnd = true
ctx.file.Size = f.Size()
}
if whence == C.AVSEEK_SIZE && ctx.file.Size > 0 {
return C.int64_t(ctx.file.Size)
}
n, err := ctx.file.Seek(int64(offset), int(whence))
if err != nil {
return C.int64_t(avErrUnknown)
}
return C.int64_t(n)
}
//export interruptCallback
func interruptCallback(opaque unsafe.Pointer) C.int {
if ctx, ok := ctxMap.context(opaque); ok {
select {
case <-ctx.context.Done():
return 1
default:
return 0
}
}
return 0
}
// AVLogLevel defines the ffmpeg threshold for dumping information to stderr.
type AVLogLevel int
// Possible values for AVLogLevel.
const (
AVLogQuiet AVLogLevel = (iota - 1) * 8
AVLogPanic
AVLogFatal
AVLogError
AVLogWarning
AVLogInfo
AVLogVerbose
AVLogDebug
AVLogTrace
)
func logLevel() AVLogLevel {
return AVLogLevel(C.av_log_get_level())
}
// SetFFmpegLogLevel allows you to change the log level from the default (AVLogInfo).
func SetFFmpegLogLevel(logLevel AVLogLevel) {
C.av_log_set_level(C.int(logLevel))
}
const (
readCallbackFlag = 1 << iota
//writeCallbackflag
seekCallbackFlag
interruptCallbackFlag
)
const (
hasVideo = 1 << iota
hasAudio
)
type avContext struct {
context context.Context
file *File
formatContext *C.AVFormatContext
stream *C.AVStream
codecContext *C.AVCodecContext
thumbContext *C.ThumbContext
frame *C.AVFrame
durationInFormat bool
}
type avError int
const (
avErrNoMem = avError(-C.ENOMEM)
avErrEOF = avError(C.AVERROR_EOF)
avErrUnknown = avError(C.AVERROR_UNKNOWN)
avErrDecoderNotFound = avError(C.AVERROR_DECODER_NOT_FOUND)
avErrInvalidData = avError(C.AVERROR_INVALIDDATA)
errTooBig = avError(C.ERR_TOO_BIG)
)
func (e avError) errorString() string {
if e == avErrNoMem {
return "cannot allocate memory"
}
if e == errTooBig {
return "video or cover art size exceeds maximum allowed dimensions"
}
errString := (*C.char)(C.av_malloc(C.AV_ERROR_MAX_STRING_SIZE))
if errString == nil {
return "cannot allocate memory for error string, error code: " + strconv.Itoa(int(e))
}
defer C.av_free(unsafe.Pointer(errString))
C.av_make_error_string(errString, C.AV_ERROR_MAX_STRING_SIZE, C.int(e))
return C.GoString(errString)
}
func (e avError) Error() string { return "ffmpeg: " + e.errorString() }
type contextMap struct {
sync.RWMutex
m map[*C.AVFormatContext]*avContext
}
func (m *contextMap) context(opaque unsafe.Pointer) (*avContext, bool) {
m.RLock()
ctx, ok := m.m[(*C.AVFormatContext)(opaque)]
m.RUnlock()
return ctx, ok
}
func (m *contextMap) set(ctx *avContext) {
m.Lock()
m.m[ctx.formatContext] = ctx
m.Unlock()
}
func (m *contextMap) delete(ctx *avContext) {
m.Lock()
delete(m.m, ctx.formatContext)
m.Unlock()
}
var ctxMap = contextMap{m: make(map[*C.AVFormatContext]*avContext)}
func freeFormatContext(ctx *avContext) {
C.free_format_context(ctx.formatContext)
ctxMap.delete(ctx)
}
func createFormatContext(ctx *avContext, callbackFlags C.int) error {
intErr := C.allocate_format_context(&ctx.formatContext)
if intErr < 0 {
return avError(intErr)
}
ctxMap.set(ctx)
intErr = C.create_format_context(ctx.formatContext, callbackFlags)
if intErr < 0 {
ctxMap.delete(ctx)
return avError(intErr)
}
metaData(ctx)
duration(ctx)
err := findStreams(ctx)
if err != nil {
freeFormatContext(ctx)
}
return err
}
func metaData(ctx *avContext) {
var artist, title *C.char
C.get_metadata(ctx.formatContext, &artist, &title)
ctx.file.Artist = C.GoString(artist)
ctx.file.Title = C.GoString(title)
}
func duration(ctx *avContext) {
if ctx.formatContext.duration > 0 {
ctx.durationInFormat = true
ctx.file.Duration = time.Duration(1000 * ctx.formatContext.duration)
}
}
func fullDuration(ctx *avContext) error {
defer freeFormatContext(ctx)
if ctx.durationInFormat {
return nil
}
newDuration := time.Duration(C.find_duration(ctx.formatContext))
if newDuration < 0 {
return avError(newDuration)
}
if newDuration > ctx.file.Duration {
ctx.file.Duration = newDuration
}
return nil
}
func findStreams(ctx *avContext) error {
var orientation C.int
err := C.find_streams(ctx.formatContext, &ctx.stream, &orientation)
if err < 0 {
return avError(err)
}
ctx.file.HasVideo = err&hasVideo != 0
ctx.file.HasAudio = err&hasAudio != 0
if !ctx.file.HasVideo {
ctx.file.Media = "audio"
} else {
ctx.file.Width = int(ctx.stream.codecpar.width)
ctx.file.Height = int(ctx.stream.codecpar.height)
ctx.file.Orientation = int(orientation)
}
return nil
}
func createDecoder(ctx *avContext) error {
err := C.create_codec_context(ctx.stream, &ctx.codecContext)
if err < 0 {
return avError(err)
}
defer C.avcodec_free_context(&ctx.codecContext)
return createThumbContext(ctx)
}
func incrementDuration(ctx *avContext, frame *C.AVFrame) {
if !ctx.durationInFormat && frame.pts != C.AV_NOPTS_VALUE {
ptsToNano := C.int64_t(1000000000 * ctx.stream.time_base.num / ctx.stream.time_base.den)
newDuration := time.Duration(frame.pts * ptsToNano)
if newDuration > ctx.file.Duration {
ctx.file.Duration = newDuration
}
}
}
func populateHistogram(ctx *avContext, frames <-chan *C.AVFrame) <-chan struct{} {
done := make(chan struct{})
go func() {
var n C.int
for frame := range frames {
C.populate_histogram(ctx.thumbContext, n, frame)
n++
}
ctx.thumbContext.n = n
done <- struct{}{}
close(done)
}()
return done
}
func createThumbContext(ctx *avContext) error {
pkt := C.create_packet()
var frame *C.AVFrame
err := C.obtain_next_frame(ctx.formatContext, ctx.codecContext, ctx.stream.index, &pkt, &frame)
if err >= 0 {
incrementDuration(ctx, frame)
ctx.thumbContext = C.create_thumb_context(ctx.stream, frame)
if ctx.thumbContext == nil {
err = C.int(avErrNoMem)
}
}
if err < 0 {
if pkt.buf != nil {
C.av_packet_unref(&pkt)
}
if frame != nil {
C.av_frame_free(&frame)
}
return avError(err)
}
defer C.free_thumb_context(ctx.thumbContext)
frames := make(chan *C.AVFrame, ctx.thumbContext.max_frames)
done := populateHistogram(ctx, frames)
frames <- frame
if pkt.buf != nil {
C.av_packet_unref(&pkt)
}
return populateThumbContext(ctx, frames, done)
}
func populateThumbContext(ctx *avContext, frames chan *C.AVFrame, done <-chan struct{}) error {
pkt := C.create_packet()
var frame *C.AVFrame
var err C.int
for i := C.int(1); i < ctx.thumbContext.max_frames; i++ {
err = C.obtain_next_frame(ctx.formatContext, ctx.codecContext, ctx.stream.index, &pkt, &frame)
if err < 0 {
break
}
incrementDuration(ctx, frame)
frames <- frame
frame = nil
}
close(frames)
if pkt.buf != nil {
C.av_packet_unref(&pkt)
}
if frame != nil {
C.av_frame_free(&frame)
}
<-done
if err != 0 && err != C.int(avErrEOF) {
return avError(err)
}
return convertFrameToRGB(ctx)
}
func convertFrameToRGB(ctx *avContext) error {
outputFrame := C.convert_frame_to_rgb(C.process_frames(ctx.thumbContext), ctx.thumbContext.alpha)
if outputFrame == nil {
return avErrNoMem
}
ctx.frame = outputFrame
ctx.file.HasAlpha = ctx.thumbContext.alpha != 0
return nil
}
func thumbnail(ctx *avContext) <-chan error {
errCh := make(chan error)
go func() {
err := thumbnailFromFFmpeg(ctx.file, ctx.frame.data[0])
C.av_frame_free(&ctx.frame)
errCh <- err
close(errCh)
}()
return errCh
}
func ffmpegThumbnail(context context.Context, file *File) error {
ctx := &avContext{context: context, file: file}
callbackFlags := C.int(readCallbackFlag | interruptCallbackFlag)
if file.Seeker != nil {
callbackFlags |= seekCallbackFlag
}
err := createFormatContext(ctx, callbackFlags)
if err != nil {
return err
}
if !file.HasVideo {
return fullDuration(ctx)
}
if err = createDecoder(ctx); err == errTooBig || err == avErrDecoderNotFound {
return fullDuration(ctx)
}
if err != nil {
freeFormatContext(ctx)
return err
}
errCh := thumbnail(ctx)
err = fullDuration(ctx)
thumbErr := <-errCh
if thumbErr != nil {
return thumbErr
}
return err
}