This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
ffmpeg.go
243 lines (216 loc) · 5.96 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
package thumbnailer
// #cgo pkg-config: libavcodec libavutil libavformat libswscale
// #cgo CFLAGS: -std=c11 -g
// #include "ffmpeg.h"
import "C"
import (
"errors"
"fmt"
"io"
"sync"
"time"
"unsafe"
)
// FFMediaType correspond to the AVMediaType enum in ffmpeg
type FFMediaType int8
// Correspond to the AVMediaType enum in ffmpeg
const (
FFUnknown FFMediaType = iota - 1
FFVideo
FFAudio
)
var (
// Global map of AVIOHandlers. One handlers struct per format context.
// Using AVFormatContext pointer address as a key.
handlersMap = handlerMap{
m: make(map[uintptr]io.ReadSeeker),
}
// Input format specifiers for FFmpeg. These save FFmpeg some overhead on
// format detection and also prevent failure to open input on format
// detection failure.
inputFormats = map[string]*C.char{
"image/jpeg": C.CString("mjpeg"),
"image/png": C.CString("image2"),
"image/gif": C.CString("gif"),
"image/webp": C.CString("webp"),
"application/ogg": C.CString("ogg"),
"video/webm": C.CString("webm"),
"video/x-matroska": C.CString("matroska"),
"video/mp4": C.CString("mp4"),
"video/avi": C.CString("avi"),
"video/quicktime": C.CString("mp4"),
"video/x-flv": C.CString("flv"),
"audio/mpeg": C.CString("mp3"),
"audio/aac": C.CString("aac"),
"audio/wave": C.CString("wav"),
"audio/x-flac": C.CString("flac"),
}
)
// C can not retain any pointers to Go memory after the cgo call returns. We
// still need a way to bind AVFormatContext instances to Go I/O functions. To do
// that we convert the AVFormatContext pointer to a uintptr and use it as a key
// to look up the respective handlers on each call.
type handlerMap struct {
sync.RWMutex
m map[uintptr]io.ReadSeeker
}
func (h *handlerMap) Set(k uintptr, rs io.ReadSeeker) {
h.Lock()
h.m[k] = rs
h.Unlock()
}
func (h *handlerMap) Delete(k uintptr) {
h.Lock()
delete(h.m, k)
h.Unlock()
}
func (h *handlerMap) Get(k unsafe.Pointer) io.ReadSeeker {
h.RLock()
handlers, ok := h.m[uintptr(k)]
h.RUnlock()
if !ok {
panic(fmt.Errorf("no handler instance found for pointer: %v", k))
}
return handlers
}
// Container for allocated codecs, so we can reuse them
type codecInfo struct {
stream C.int
ctx *C.AVCodecContext
}
// FFContext is a wrapper for passing Go I/O interfaces to C
type FFContext struct {
avFormatCtx *C.struct_AVFormatContext
handlerKey uintptr
codecs map[FFMediaType]codecInfo
}
// NewFFContext constructs a new AVIOContext and AVFormatContext.
// It is the responsibility of the caller to call Close() after finishing
// using the context.
func NewFFContext(rs io.ReadSeeker) (*FFContext, error) {
return newFFContextWithFormat(rs, nil)
}
// Like NewFFContext, but optionally specifies the passed input format explicitly.
// inputFormat can be NULL.
func newFFContextWithFormat(rs io.ReadSeeker, inputFormat *C.char,
) (*FFContext, error) {
ctx := C.avformat_alloc_context()
this := &FFContext{
avFormatCtx: ctx,
codecs: make(map[FFMediaType]codecInfo),
}
this.handlerKey = uintptr(unsafe.Pointer(ctx))
handlersMap.Set(this.handlerKey, rs)
err := C.create_context(&this.avFormatCtx, inputFormat)
if err < 0 {
this.Close()
return nil, castError(err)
}
if this.avFormatCtx == nil {
this.Close()
return nil, errors.New("unknown context creation error")
}
return this, nil
}
// Close closes and frees memory allocated for c. c should not be used after
// this point.
func (c *FFContext) Close() {
for _, ci := range c.codecs {
C.avcodec_free_context(&ci.ctx)
}
if c.avFormatCtx != nil {
C.av_free(unsafe.Pointer(c.avFormatCtx.pb.buffer))
c.avFormatCtx.pb.buffer = nil
C.av_free(unsafe.Pointer(c.avFormatCtx.pb))
C.av_free(unsafe.Pointer(c.avFormatCtx))
}
handlersMap.Delete(c.handlerKey)
}
// Allocate a codec context for the best stream of the passed FFMediaType, if
// not allocated already
func (c *FFContext) codecContext(typ FFMediaType) (codecInfo, error) {
if ci, ok := c.codecs[typ]; ok {
return ci, nil
}
var (
ctx *C.struct_AVCodecContext
stream C.int
)
err := C.codec_context(&ctx, &stream, c.avFormatCtx, int32(typ))
switch {
case err == C.AVERROR_STREAM_NOT_FOUND:
return codecInfo{}, ErrStreamNotFound
case err < 0:
return codecInfo{}, castError(err)
}
ci := codecInfo{
stream: stream,
ctx: ctx,
}
c.codecs[typ] = ci
return ci, nil
}
// CodecName returns the codec name of the best stream of type typ
func (c *FFContext) CodecName(typ FFMediaType) (codec string, err error) {
ci, err := c.codecContext(typ)
if err != nil {
return
}
return C.GoString(ci.ctx.codec.name), nil
}
// HasStream returns, if the file has a decodeable stream of the passed type
func (c *FFContext) HasStream(typ FFMediaType) (bool, error) {
_, err := c.codecContext(typ)
switch err {
case nil:
return true, nil
case ErrStreamNotFound:
return false, nil
default:
return false, err
}
}
// Length returns the duration of the input
func (c *FFContext) Length() time.Duration {
return time.Duration(c.avFormatCtx.duration * 1000)
}
// Dims returns dimensions of the best video (or image) stream in the media
func (c *FFContext) Dims() (dims Dims, err error) {
ci, err := c.codecContext(FFVideo)
if err != nil {
return
}
dims = Dims{
Width: uint(ci.ctx.width),
Height: uint(ci.ctx.height),
}
return
}
func castIOError(err error) C.int {
// Properly pass EOF to FFmpeg
if err == io.EOF {
return C.AVERROR_EOF
}
return -1
}
//export readCallBack
func readCallBack(opaque unsafe.Pointer, buf *C.uint8_t, bufSize C.int) C.int {
s := (*[1 << 30]byte)(unsafe.Pointer(buf))[:bufSize:bufSize]
n, err := handlersMap.Get(opaque).Read(s)
if err != nil && !(err == io.EOF && n != 0) {
return castIOError(err)
}
return C.int(n)
}
//export seekCallBack
func seekCallBack(
opaque unsafe.Pointer,
offset C.int64_t,
whence C.int,
) C.int64_t {
n, err := handlersMap.Get(opaque).Seek(int64(offset), int(whence))
if err != nil {
return C.int64_t(castIOError(err))
}
return C.int64_t(n)
}