forked from bluenviron/gortsplib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (95 loc) · 2.3 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
package main
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"time"
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
)
// This example shows how to
// 1. connect to a RTSP server, announce a M-JPEG format
// 2. generate an image
// 3. encode the image with JPEG
// 4. generate RTP packets from the JPEG image
// 5. write packets to the server
func createRandomImage(i int) *image.RGBA {
img := image.NewRGBA(image.Rect(0, 0, 640, 480))
var cl color.RGBA
switch i {
case 0:
cl = color.RGBA{255, 0, 0, 0}
case 1:
cl = color.RGBA{0, 255, 0, 0}
case 2:
cl = color.RGBA{0, 0, 255, 0}
}
for y := 0; y < img.Rect.Dy(); y++ {
for x := 0; x < img.Rect.Dx(); x++ {
img.SetRGBA(x, y, cl)
}
}
return img
}
func main() {
// create a description that contains a M-JPEG format
forma := &format.MJPEG{}
desc := &description.Session{
Medias: []*description.Media{{
Type: description.MediaTypeVideo,
Formats: []format.Format{forma},
}},
}
// connect to the server, announce the format and start recording
c := gortsplib.Client{}
err := c.StartRecording("rtsp://localhost:8554/mystream", desc)
if err != nil {
panic(err)
}
defer c.Close()
// setup JPEG -> RTP encoder
rtpEnc, err := forma.CreateEncoder()
if err != nil {
panic(err)
}
// setup RTP timestamp generator
rtpTime := &rtptime.Encoder{ClockRate: forma.ClockRate()}
err = rtpTime.Initialize()
if err != nil {
panic(err)
}
start := time.Now()
// setup a ticker to sleep between frames
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
i := 0
for range ticker.C {
// create a random image
img := createRandomImage(i)
i = (i + 1) % 3
// encode the image with JPEG
var buf bytes.Buffer
err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
if err != nil {
panic(err)
}
// generate RTP packets from the JPEG image
pkts, err := rtpEnc.Encode(buf.Bytes())
if err != nil {
panic(err)
}
// get current timestamp
ts := rtpTime.Encode(time.Since(start))
// write packets to the server
for _, pkt := range pkts {
pkt.Timestamp = ts
err = c.WritePacketRTP(desc.Medias[0], pkt)
if err != nil {
panic(err)
}
}
}
}