-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
102 lines (77 loc) · 2.08 KB
/
encoding.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
package main
import (
"errors"
"fmt"
"log"
. "github.com/3d0c/gmf"
)
func fatal(err error) {
log.Fatal(err)
}
func main() {
outputfilename := "sample-encoding1.mpg"
dstWidth, dstHeight := 640, 480
codec, err := FindEncoder(AV_CODEC_ID_MPEG1VIDEO)
if err != nil {
fatal(err)
}
videoEncCtx := NewCodecCtx(codec)
if videoEncCtx == nil {
fatal(errors.New("failed to create a new codec context"))
}
defer Release(videoEncCtx)
outputCtx, err := NewOutputCtx(outputfilename)
if err != nil {
fatal(errors.New("failed to create a new output context"))
}
videoEncCtx.
SetBitRate(400000).
SetWidth(dstWidth).
SetHeight(dstHeight).
SetTimeBase(AVR{Num: 1, Den: 25}).
SetPixFmt(AV_PIX_FMT_YUV420P).
SetProfile(FF_PROFILE_MPEG4_SIMPLE).
SetMbDecision(FF_MB_DECISION_RD)
if outputCtx.IsGlobalHeader() {
videoEncCtx.SetFlag(CODEC_FLAG_GLOBAL_HEADER)
}
videoStream := outputCtx.NewStream(codec)
if videoStream == nil {
fatal(errors.New(fmt.Sprintf("Unable to create stream for videoEnc [%s]\n", codec.LongName())))
}
defer Release(videoStream)
if err := videoEncCtx.Open(nil); err != nil {
fatal(err)
}
videoStream.SetCodecCtx(videoEncCtx)
outputCtx.SetStartTime(0)
if err := outputCtx.WriteHeader(); err != nil {
fatal(err)
}
var frame *Frame
i := int64(0)
n := 0
for frame = range GenSyntVideoNewFrame(videoEncCtx.Width(), videoEncCtx.Height(), videoEncCtx.PixFmt()) {
frame.SetPts(i)
if p, err := frame.Encode(videoStream.CodecCtx()); p != nil {
if p.Pts() != AV_NOPTS_VALUE {
p.SetPts(RescaleQ(p.Pts(), videoStream.CodecCtx().TimeBase(), videoStream.TimeBase()))
}
if p.Dts() != AV_NOPTS_VALUE {
p.SetDts(RescaleQ(p.Dts(), videoStream.CodecCtx().TimeBase(), videoStream.TimeBase()))
}
if err := outputCtx.WritePacket(p); err != nil {
fatal(err)
}
n++
log.Printf("Write frame=%d size=%v pts=%v dts=%v\n", frame.Pts(), p.Size(), p.Pts(), p.Dts())
Release(p)
} else if err != nil {
fatal(err)
}
Release(frame)
i++
}
outputCtx.CloseOutputAndRelease()
log.Println(n, "frames written to", outputfilename)
}