|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "os" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/bluenviron/gortsplib/v4" |
| 12 | + "github.com/bluenviron/gortsplib/v4/pkg/base" |
| 13 | + "github.com/bluenviron/gortsplib/v4/pkg/description" |
| 14 | + "github.com/bluenviron/gortsplib/v4/pkg/format" |
| 15 | + "github.com/bluenviron/mediacommon/v2/pkg/formats/mpegts" |
| 16 | +) |
| 17 | + |
| 18 | +// This example shows how to |
| 19 | +// 1. create a RTSP server which accepts plain connections |
| 20 | +// 2. read from disk a MPEG-TS file which contains a H264 track |
| 21 | +// 3. serve the content of the file to connected readers |
| 22 | + |
| 23 | +func findTrack(r *mpegts.Reader) (*mpegts.Track, error) { |
| 24 | + for _, track := range r.Tracks() { |
| 25 | + if _, ok := track.Codec.(*mpegts.CodecH264); ok { |
| 26 | + return track, nil |
| 27 | + } |
| 28 | + } |
| 29 | + return nil, fmt.Errorf("H264 track not found") |
| 30 | +} |
| 31 | + |
| 32 | +func randUint32() (uint32, error) { |
| 33 | + var b [4]byte |
| 34 | + _, err := rand.Read(b[:]) |
| 35 | + if err != nil { |
| 36 | + return 0, err |
| 37 | + } |
| 38 | + return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3]), nil |
| 39 | +} |
| 40 | + |
| 41 | +type serverHandler struct { |
| 42 | + server *gortsplib.Server |
| 43 | + stream *gortsplib.ServerStream |
| 44 | + mutex sync.RWMutex |
| 45 | +} |
| 46 | + |
| 47 | +// called when a connection is opened. |
| 48 | +func (sh *serverHandler) OnConnOpen(ctx *gortsplib.ServerHandlerOnConnOpenCtx) { |
| 49 | + log.Printf("conn opened") |
| 50 | +} |
| 51 | + |
| 52 | +// called when a connection is closed. |
| 53 | +func (sh *serverHandler) OnConnClose(ctx *gortsplib.ServerHandlerOnConnCloseCtx) { |
| 54 | + log.Printf("conn closed (%v)", ctx.Error) |
| 55 | +} |
| 56 | + |
| 57 | +// called when a session is opened. |
| 58 | +func (sh *serverHandler) OnSessionOpen(ctx *gortsplib.ServerHandlerOnSessionOpenCtx) { |
| 59 | + log.Printf("session opened") |
| 60 | +} |
| 61 | + |
| 62 | +// called when a session is closed. |
| 63 | +func (sh *serverHandler) OnSessionClose(ctx *gortsplib.ServerHandlerOnSessionCloseCtx) { |
| 64 | + log.Printf("session closed") |
| 65 | +} |
| 66 | + |
| 67 | +// called when receiving a DESCRIBE request. |
| 68 | +func (sh *serverHandler) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error) { |
| 69 | + log.Printf("describe request") |
| 70 | + |
| 71 | + sh.mutex.RLock() |
| 72 | + defer sh.mutex.RUnlock() |
| 73 | + |
| 74 | + return &base.Response{ |
| 75 | + StatusCode: base.StatusOK, |
| 76 | + }, sh.stream, nil |
| 77 | +} |
| 78 | + |
| 79 | +// called when receiving a SETUP request. |
| 80 | +func (sh *serverHandler) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) { |
| 81 | + log.Printf("setup request") |
| 82 | + |
| 83 | + sh.mutex.RLock() |
| 84 | + defer sh.mutex.RUnlock() |
| 85 | + |
| 86 | + return &base.Response{ |
| 87 | + StatusCode: base.StatusOK, |
| 88 | + }, sh.stream, nil |
| 89 | +} |
| 90 | + |
| 91 | +// called when receiving a PLAY request. |
| 92 | +func (sh *serverHandler) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) { |
| 93 | + log.Printf("play request") |
| 94 | + |
| 95 | + return &base.Response{ |
| 96 | + StatusCode: base.StatusOK, |
| 97 | + }, nil |
| 98 | +} |
| 99 | + |
| 100 | +func readVideoFile(stream *gortsplib.ServerStream, media *description.Media, forma *format.H264) { |
| 101 | + // open a file in MPEG-TS format |
| 102 | + f, err := os.Open("myvideo.ts") |
| 103 | + if err != nil { |
| 104 | + panic(err) |
| 105 | + } |
| 106 | + defer f.Close() |
| 107 | + |
| 108 | + // setup MPEG-TS parser |
| 109 | + r := &mpegts.Reader{R: f} |
| 110 | + err = r.Initialize() |
| 111 | + if err != nil { |
| 112 | + panic(err) |
| 113 | + } |
| 114 | + |
| 115 | + // find the H264 track inside the file |
| 116 | + track, err := findTrack(r) |
| 117 | + if err != nil { |
| 118 | + panic(err) |
| 119 | + } |
| 120 | + |
| 121 | + // setup H264 -> RTP encoder |
| 122 | + rtpEnc, err := forma.CreateEncoder() |
| 123 | + if err != nil { |
| 124 | + panic(err) |
| 125 | + } |
| 126 | + |
| 127 | + randomStart, err := randUint32() |
| 128 | + if err != nil { |
| 129 | + panic(err) |
| 130 | + } |
| 131 | + |
| 132 | + timeDecoder := mpegts.TimeDecoder{} |
| 133 | + timeDecoder.Initialize() |
| 134 | + |
| 135 | + var firstDTS *int64 |
| 136 | + var startTime time.Time |
| 137 | + |
| 138 | + // setup a callback that is called whenever a H264 access unit is read from the file |
| 139 | + r.OnDataH264(track, func(pts, dts int64, au [][]byte) error { |
| 140 | + dts = timeDecoder.Decode(dts) |
| 141 | + pts = timeDecoder.Decode(pts) |
| 142 | + |
| 143 | + // sleep between access units |
| 144 | + if firstDTS != nil { |
| 145 | + timeDrift := time.Duration(dts-*firstDTS)*time.Second/90000 - time.Since(startTime) |
| 146 | + if timeDrift > 0 { |
| 147 | + time.Sleep(timeDrift) |
| 148 | + } |
| 149 | + } else { |
| 150 | + startTime = time.Now() |
| 151 | + firstDTS = &dts |
| 152 | + } |
| 153 | + |
| 154 | + log.Printf("writing access unit with pts=%d dts=%d", pts, dts) |
| 155 | + |
| 156 | + // wrap the access unit into RTP packets |
| 157 | + packets, err := rtpEnc.Encode(au) |
| 158 | + if err != nil { |
| 159 | + return err |
| 160 | + } |
| 161 | + |
| 162 | + // set packet timestamp |
| 163 | + // we don't have to perform any conversion |
| 164 | + // since H264 clock rate is the same in both MPEG-TS and RTSP |
| 165 | + for _, packet := range packets { |
| 166 | + packet.Timestamp = uint32(int64(randomStart) + pts) |
| 167 | + } |
| 168 | + |
| 169 | + // write RTP packets to the server |
| 170 | + for _, packet := range packets { |
| 171 | + err := stream.WritePacketRTP(media, packet) |
| 172 | + if err != nil { |
| 173 | + return err |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + return nil |
| 178 | + }) |
| 179 | + |
| 180 | + for { |
| 181 | + err := r.Read() |
| 182 | + if err != nil { |
| 183 | + panic(err) |
| 184 | + } |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +func main() { |
| 189 | + h := &serverHandler{} |
| 190 | + |
| 191 | + // prevent clients from connecting to the server until the stream is properly set up |
| 192 | + h.mutex.Lock() |
| 193 | + |
| 194 | + // create the server |
| 195 | + h.server = &gortsplib.Server{ |
| 196 | + Handler: h, |
| 197 | + RTSPAddress: ":8554", |
| 198 | + UDPRTPAddress: ":8000", |
| 199 | + UDPRTCPAddress: ":8001", |
| 200 | + MulticastIPRange: "224.1.0.0/16", |
| 201 | + MulticastRTPPort: 8002, |
| 202 | + MulticastRTCPPort: 8003, |
| 203 | + } |
| 204 | + |
| 205 | + // start the server |
| 206 | + err := h.server.Start() |
| 207 | + if err != nil { |
| 208 | + panic(err) |
| 209 | + } |
| 210 | + |
| 211 | + // create a RTSP description that contains a H264 format |
| 212 | + forma := &format.H264{ |
| 213 | + PayloadTyp: 96, |
| 214 | + PacketizationMode: 1, |
| 215 | + } |
| 216 | + desc := &description.Session{ |
| 217 | + Medias: []*description.Media{{ |
| 218 | + Type: description.MediaTypeVideo, |
| 219 | + Formats: []format.Format{forma}, |
| 220 | + }}, |
| 221 | + } |
| 222 | + |
| 223 | + // create a server stream |
| 224 | + h.stream = &gortsplib.ServerStream{ |
| 225 | + Server: h.server, |
| 226 | + Desc: desc, |
| 227 | + } |
| 228 | + err = h.stream.Initialize() |
| 229 | + if err != nil { |
| 230 | + panic(err) |
| 231 | + } |
| 232 | + |
| 233 | + // in a separate routine, read the MPEG-TS file |
| 234 | + go readVideoFile(h.stream, desc.Medias[0], forma) |
| 235 | + |
| 236 | + // allow clients to connect |
| 237 | + h.mutex.Unlock() |
| 238 | + |
| 239 | + // wait until a fatal error |
| 240 | + log.Printf("server is ready on %s", h.server.RTSPAddress) |
| 241 | + panic(h.server.Wait()) |
| 242 | +} |
0 commit comments