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

Fix "panic: send on closed channel" #1438

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
16 changes: 12 additions & 4 deletions pkg/core/track.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package core
import (
"encoding/json"
"errors"

"github.com/pion/rtp"
)

Expand Down Expand Up @@ -71,8 +70,9 @@ type Sender struct {
Packets int `json:"packets,omitempty"`
Drops int `json:"drops,omitempty"`

buf chan *Packet
done chan struct{}
buf chan *Packet
done chan struct{}
isClosed bool
}

func NewSender(media *Media, codec *Codec) *Sender {
Expand All @@ -99,6 +99,11 @@ func NewSender(media *Media, codec *Codec) *Sender {
s.Input = func(packet *Packet) {
// writing to nil chan - OK, writing to closed chan - panic
s.mu.Lock()
if s.isClosed {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would recommend to refactor function to use defer s.mu.Unlock(), so it would be closed anyway and the remove all other s.mu.Unlock() instances

s.Drops++
s.mu.Unlock()
return
}
select {
case s.buf <- packet:
s.Bytes += len(packet.Payload)
Expand Down Expand Up @@ -165,10 +170,13 @@ func (s *Sender) State() string {

func (s *Sender) Close() {
// close buffer if exists
if buf := s.buf; buf != nil {
s.mu.Lock()
if buf := s.buf; buf != nil && !s.isClosed {
s.isClosed = true
s.buf = nil
defer close(buf)
}
s.mu.Unlock()

s.Node.Close()
}
Expand Down