implemented audio streaming to browser, but it didnt work

This commit is contained in:
tdv
2025-10-16 18:49:02 +03:00
parent af7c659bef
commit f59883315d
9 changed files with 378 additions and 113 deletions

View File

@@ -32,7 +32,7 @@ type PublishTokenReq struct {
}
type PublishTokenResp struct {
WHIP string `json:"whipUrl"` // http://mediamtx:8889/whip/live/<guid>?token=...
HLS string `json:"hlsUrl"` // https://<public>/hls/live/<guid>/index.m3u8?token=...
}
type ReadTokenReq struct {

View File

@@ -126,15 +126,46 @@ func (h *MediaMTXHandler) canPublish(sub, path string) bool {
// --- 3.2 Mint publish token (device flow) -> returns WHIP URL
// POST /mediamtx/token/publish {guid}
func (h *MediaMTXHandler) MintPublish(c *gin.Context) {
user, ok := GetUserContext(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
var req dto.PublishTokenReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
return
}
// Permission check (admin or assigned)
if user.Role != models.RoleAdmin {
var count int64
_ = h.db.Table("user_devices").
Where("user_id = ? AND device_guid = ?", user.ID, req.GUID).
Count(&count).Error
if count == 0 {
c.JSON(http.StatusForbidden, gin.H{"error": "not allowed for this device"})
return
}
}
path := "live/" + req.GUID
tok, _ := h.jwtMgr.GenerateMediaToken(0, "publish", path, h.cfg.TokenTTL) // sub=0 (device)
whip := fmt.Sprintf("%s/whip/%s?token=%s", strings.TrimRight(h.cfg.WebRTCBaseURL, "/"), path, url.QueryEscape(tok))
c.JSON(http.StatusCreated, dto.PublishTokenResp{WHIP: whip})
// We mint a *read* token for the browser to consume HLS.
tok, err := h.jwtMgr.GenerateMediaToken(user.ID, "read", path, h.cfg.TokenTTL)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "token error"})
return
}
pub := strings.TrimRight(h.cfg.PublicBaseURL, "/")
hls := fmt.Sprintf("%s/hls/%s/index.m3u8?token=%s",
pub,
path,
url.QueryEscape(tok),
)
c.JSON(http.StatusCreated, dto.PublishTokenResp{HLS: hls})
}
// --- 3.3 Mint read token (user flow) -> returns HLS + WHEP URLs

View File

@@ -81,7 +81,7 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
r.POST("/mediamtx/auth", mediamtxH.Auth)
// Token minting for device/user flows
r.POST("/mediamtx/token/publish", mediamtxH.MintPublish)
r.POST("/mediamtx/token/read", authMW, mediamtxH.MintRead)
r.POST("/mediamtx/token/read", authMW, middleware.DeviceAccessFilter(), mediamtxH.MintRead)
// Admin controls
r.GET("/mediamtx/paths", authMW, adminOnly, mediamtxH.ListPaths)
r.POST("/mediamtx/webrtc/kick/:id", authMW, adminOnly, mediamtxH.KickWebRTC)