Overcoming latency, How we build a Cloud Game service in Go
Gophercon VietNam 2019
giongto35
Agenda
What is cloud gaming?
Future Application
Challenges
Proof of concept!
Tech stack
WebRTC?
The technology behind Cloud Gaming
WebRTC
WebRTC
Video Compression
Audio Compression
Pion, WebRTC library for Go
My project got featured in Pion talk in GopherCon 2019
Pion, WebRTC library for Go Example
// Setup peer connection
api := webrtc.NewAPI(webrtc.WithMediaEngine(mediaEngine))
peerConnection, err := api.NewPeerConnection()
// Create track and add track to connection
videoTrack, err := peerConnection.NewTrack(payloadType, rand.Uint32(), "video", "pion")
peerConnection.AddTrack(videoTrack);
// Write sample to the track
videoTrack.WriteSample(media.Sample{Data: frame, Samples: 90000});
Write Cloud-Gaming in Go
How golang helps my interation is that fast
Architecture
Go channel in action
WebRTC Transmitter (user facing) | Game Emulator | Video Encoder | Audio Encoder | Connection Handler
2. Fan-in, Fan-out
2. Fan-in, Fan-out
func (r *Room) listen() {
for _, webRTC := range r.rtcSessions {
go func(webRTC *){
for input := range webRTC.InputChannel {
r.inputChannel <- input
}
}(webRTC)
}
}
// Other side of r.inputChannel update Game state
func (r *Room) broadcast() {
for image := range r.outputChannel {
for _, webRTC := range r.rtcSessions {
webRTC.ImageChannel <- data
}
}
}
// Other side of webRTC.outputChannel send new copy of media
Fan-in game input
Fan-out media stream
3. Handling concurrency
func (w *webRTC) save() {
w.event <- struct{}
}
func (w *webRTC) update(key int) {
W.input <- key
}
func (e *gameEmulator) gameUpdate() {
for {
select {
case <-e.save:
save(e.snapshotState())
case key := <-e.input:
e.updateState(key)
case <-e.done:
e.close()
return
}
}
}
func (w *webRTC) save() {
w.room.save()
}
func (w *webRTC) update(key int) {
w.room.update(key)
}
func (r *Room) save() {
save(r.gameEmulator.snapshotState())
}
func (r *Room) update(key int) {
r.gameEmulator.updateState(key)
}
Direct call
Over channel
Golang makes it hard
Golang makes it hard
Profiling can cure your headache
Future Improvement