Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jpeg): Add keyframe caching with expiration mechanism to JPEG http handler #1155

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions internal/mjpeg/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"strconv"
"strings"
"sync"
"time"

"github.com/AlexxIT/go2rtc/internal/api"
Expand All @@ -22,6 +23,24 @@ import (
"github.com/rs/zerolog"
)

// CacheEntry represents a cached keyframe with its timestamp
type CacheEntry struct {
frame []byte
timestamp time.Time
}

// Global cache for keyframes with expiration
var keyframeCache = struct {
sync.RWMutex
cache map[string]CacheEntry
}{
cache: make(map[string]CacheEntry),
}

// Cache duration
// TODO: Make it configurable
var cacheDuration = 1 * time.Minute

func Init() {
api.HandleFunc("api/frame.jpeg", handlerKeyframe)
api.HandleFunc("api/stream.mjpeg", handlerStream)
Expand All @@ -30,6 +49,7 @@ func Init() {

ws.HandleFunc("mjpeg", handlerWS)

go cleanupCache()
log = app.GetLogger("mjpeg")
}

Expand All @@ -43,6 +63,15 @@ func handlerKeyframe(w http.ResponseWriter, r *http.Request) {
return
}

keyframeCache.RLock()
cachedEntry, found := keyframeCache.cache[src]
keyframeCache.RUnlock()

if found && time.Since(cachedEntry.timestamp) < cacheDuration {
writeJPEGResponse(w, cachedEntry.frame)
return
}

cons := magic.NewKeyframe()
cons.RemoteAddr = tcp.RemoteAddr(r)
cons.UserAgent = r.UserAgent()
Expand Down Expand Up @@ -71,6 +100,15 @@ func handlerKeyframe(w http.ResponseWriter, r *http.Request) {
b = mjpeg.FixJPEG(b)
}

// Cache the keyframe with timestamp
keyframeCache.Lock()
keyframeCache.cache[src] = CacheEntry{frame: b, timestamp: time.Now()}
keyframeCache.Unlock()

writeJPEGResponse(w, b)
}

func writeJPEGResponse(w http.ResponseWriter, b []byte) {
h := w.Header()
h.Set("Content-Type", "image/jpeg")
h.Set("Content-Length", strconv.Itoa(len(b)))
Expand All @@ -83,6 +121,19 @@ func handlerKeyframe(w http.ResponseWriter, r *http.Request) {
}
}

func cleanupCache() {
for {
time.Sleep(cacheDuration)
keyframeCache.Lock()
for src, entry := range keyframeCache.cache {
if time.Since(entry.timestamp) >= cacheDuration {
delete(keyframeCache.cache, src)
}
}
keyframeCache.Unlock()
}
}

func handlerStream(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
outputMjpeg(w, r)
Expand Down