Skip to content

Commit

Permalink
Add bitrate to webrtc/mse/mp4 consumer info (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
dnjooiopa committed Jun 19, 2024
1 parent 6b6c660 commit 862eaa3
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dev:
goreload .
5 changes: 5 additions & 0 deletions pkg/core/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ type Connection struct {
Send int `json:"bytes_send,omitempty"`

Transport any `json:"-"`

stopBitrateWorker chan struct{} `json:"-"`
Bitrate int `json:"bitrate,omitempty"` // bytes per second
}

func (c *Connection) GetMedias() []*Media {
Expand All @@ -67,6 +70,8 @@ func (c *Connection) GetTrack(media *Media, codec *Codec) (*Receiver, error) {
}

func (c *Connection) Stop() error {
c.StopBitrateWorker()

for _, receiver := range c.Receivers {
receiver.Close()
}
Expand Down
29 changes: 29 additions & 0 deletions pkg/core/custom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package core

import (
"time"
)

func (c *Connection) StartBitrateWorker() {
c.stopBitrateWorker = make(chan struct{}, 1)

go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()

prevSendBytes := c.Send
for {
select {
case <-ticker.C:
c.Bitrate = c.Send - prevSendBytes
prevSendBytes = c.Send
case <-c.stopBitrateWorker:
return
}
}
}()
}

func (c *Connection) StopBitrateWorker() {
c.stopBitrateWorker <- struct{}{}
}
4 changes: 3 additions & 1 deletion pkg/mp4/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func NewConsumer(medias []*core.Media) *Consumer {
}

wr := core.NewWriteBuffer(nil)
return &Consumer{
cons := &Consumer{
Connection: core.Connection{
ID: core.NewID(),
FormatName: "mp4",
Expand All @@ -58,6 +58,8 @@ func NewConsumer(medias []*core.Media) *Consumer {
muxer: &Muxer{},
wr: wr,
}
cons.StartBitrateWorker()
return cons
}

func (c *Consumer) AddTrack(media *core.Media, _ *core.Codec, track *core.Receiver) error {
Expand Down
3 changes: 3 additions & 0 deletions pkg/webrtc/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ func NewConn(pc *webrtc.PeerConnection) *Conn {
}
})

c.StartBitrateWorker()

return c
}

Expand All @@ -148,6 +150,7 @@ func (c *Conn) MarshalJSON() ([]byte, error) {

func (c *Conn) Close() error {
c.closed.Done(nil)
c.StopBitrateWorker()
return c.pc.Close()
}

Expand Down

0 comments on commit 862eaa3

Please sign in to comment.