Update CI configs to v0.7.2

Update lint scripts and CI configs.
This commit is contained in:
Pion
2022-04-27 03:28:46 +00:00
committed by Sean DuBois
parent dc31439c93
commit c1467e4871
28 changed files with 126 additions and 77 deletions

View File

@@ -47,5 +47,5 @@ jobs:
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v3 uses: golangci/golangci-lint-action@v3
with: with:
version: v1.31 version: v1.45.2
args: $GOLANGCI_LINT_EXRA_ARGS args: $GOLANGCI_LINT_EXRA_ARGS

View File

@@ -15,14 +15,22 @@ linters-settings:
linters: linters:
enable: enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully - bodyclose # checks whether HTTP response body is closed successfully
- contextcheck # check the function whether use a non-inherited context
- deadcode # Finds unused code - deadcode # Finds unused code
- decorder # check declaration order and count of types, constants, variables and functions
- depguard # Go linter that checks if package imports are in a list of acceptable packages - depguard # Go linter that checks if package imports are in a list of acceptable packages
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection - dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements - exhaustive # check exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables - exportloopref # checks for pointers to enclosing loop variables
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic. - gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code - gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code - gochecknoinits # Checks that no init functions are present in Go code
@@ -35,40 +43,62 @@ linters:
- gofumpt # Gofumpt checks whether code was gofumpt-ed. - gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern - goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end - goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems - gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code - gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used - ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments - misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length - nakedret # Finds naked returns in functions greater than a specified function length
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context - noctx # noctx finds sending http request without context.Context
- scopelint # Scopelint checks for unpinned variables in go programs - predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- structcheck # Finds unused struct fields - structcheck # Finds unused struct fields
- stylecheck # Stylecheck is a replacement for golint - stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions - unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters - unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types - unused # Checks Go code for unused constants, variables, functions and types
- varcheck # Finds unused global variables and constants - varcheck # Finds unused global variables and constants
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace - whitespace # Tool for detection of leading and trailing whitespace
disable: disable:
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- exhaustivestruct # Checks if all struct's fields are initialized
- forbidigo # Forbids identifiers
- funlen # Tool for detection of long functions - funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions - gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period - godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers. - gomnd # An analyzer to detect magic numbers.
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines - lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted - maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nestif # Reports deeply nested if statements - nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nolintlint # Reports ill-formed or insufficient nolint directives - nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated - prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully - rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package - testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines! - wsl # Whitespace Linter - Forces you to use empty lines!
issues: issues:

View File

@@ -20,7 +20,7 @@ func (b *atomicBool) get() bool {
} }
func (b *atomicBool) swap(value bool) bool { func (b *atomicBool) swap(value bool) bool {
var i int32 = 0 var i int32
if value { if value {
i = 1 i = 1
} }

View File

@@ -321,12 +321,12 @@ var rlBufPool = sync.Pool{New: func() interface{} {
func (d *DataChannel) readLoop() { func (d *DataChannel) readLoop() {
for { for {
buffer := rlBufPool.Get().([]byte) buffer := rlBufPool.Get().([]byte) //nolint:forcetypeassert
n, isString, err := d.dataChannel.ReadDataChannel(buffer) n, isString, err := d.dataChannel.ReadDataChannel(buffer)
if err != nil { if err != nil {
rlBufPool.Put(buffer) // nolint:staticcheck rlBufPool.Put(buffer) // nolint:staticcheck
d.setReadyState(DataChannelStateClosed) d.setReadyState(DataChannelStateClosed)
if err != io.EOF { if !errors.Is(err, io.EOF) {
d.onError(err) d.onError(err)
} }
d.onClose() d.onClose()
@@ -488,8 +488,8 @@ func (d *DataChannel) ID() *uint16 {
// ReadyState represents the state of the DataChannel object. // ReadyState represents the state of the DataChannel object.
func (d *DataChannel) ReadyState() DataChannelState { func (d *DataChannel) ReadyState() DataChannelState {
if v := d.readyState.Load(); v != nil { if v, ok := d.readyState.Load().(DataChannelState); ok {
return v.(DataChannelState) return v
} }
return DataChannelState(0) return DataChannelState(0)
} }

View File

@@ -134,7 +134,7 @@ func (t *DTLSTransport) WriteRTCP(pkts []rtcp.Packet) (int, error) {
srtcpSession, err := t.getSRTCPSession() srtcpSession, err := t.getSRTCPSession()
if err != nil { if err != nil {
return 0, nil return 0, err
} }
writeStream, err := srtcpSession.OpenWriteStream() writeStream, err := srtcpSession.OpenWriteStream()
@@ -232,16 +232,16 @@ func (t *DTLSTransport) startSRTP() error {
} }
func (t *DTLSTransport) getSRTPSession() (*srtp.SessionSRTP, error) { func (t *DTLSTransport) getSRTPSession() (*srtp.SessionSRTP, error) {
if value := t.srtpSession.Load(); value != nil { if value, ok := t.srtpSession.Load().(*srtp.SessionSRTP); ok {
return value.(*srtp.SessionSRTP), nil return value, nil
} }
return nil, errDtlsTransportNotStarted return nil, errDtlsTransportNotStarted
} }
func (t *DTLSTransport) getSRTCPSession() (*srtp.SessionSRTCP, error) { func (t *DTLSTransport) getSRTCPSession() (*srtp.SessionSRTCP, error) {
if value := t.srtcpSession.Load(); value != nil { if value, ok := t.srtcpSession.Load().(*srtp.SessionSRTCP); ok {
return value.(*srtp.SessionSRTCP), nil return value, nil
} }
return nil, errDtlsTransportNotStarted return nil, errDtlsTransportNotStarted
@@ -407,12 +407,12 @@ func (t *DTLSTransport) Stop() error {
// Try closing everything and collect the errors // Try closing everything and collect the errors
var closeErrs []error var closeErrs []error
if srtpSessionValue := t.srtpSession.Load(); srtpSessionValue != nil { if srtpSession, err := t.getSRTPSession(); err == nil && srtpSession != nil {
closeErrs = append(closeErrs, srtpSessionValue.(*srtp.SessionSRTP).Close()) closeErrs = append(closeErrs, srtpSession.Close())
} }
if srtcpSessionValue := t.srtcpSession.Load(); srtcpSessionValue != nil { if srtcpSession, err := t.getSRTCPSession(); err == nil && srtcpSession != nil {
closeErrs = append(closeErrs, srtcpSessionValue.(*srtp.SessionSRTCP).Close()) closeErrs = append(closeErrs, srtcpSession.Close())
} }
for i := range t.simulcastStreams { for i := range t.simulcastStreams {

View File

@@ -1,8 +1,10 @@
//go:build !js
// +build !js // +build !js
package main package main
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@@ -217,16 +219,17 @@ func main() {
frame, _, err = ivf.ParseNextFrame() frame, _, err = ivf.ParseNextFrame()
} }
switch err { switch {
// If we have reached the end of the file start again
case errors.Is(err, io.EOF):
ivf.ResetReader(setReaderFile(qualityLevels[currentQuality].fileName))
// No error write the video frame // No error write the video frame
case nil: case err == nil:
currentTimestamp = frameHeader.Timestamp currentTimestamp = frameHeader.Timestamp
if err = videoTrack.WriteSample(media.Sample{Data: frame, Duration: time.Second}); err != nil { if err = videoTrack.WriteSample(media.Sample{Data: frame, Duration: time.Second}); err != nil {
panic(err) panic(err)
} }
// If we have reached the end of the file start again
case io.EOF:
ivf.ResetReader(setReaderFile(qualityLevels[currentQuality].fileName))
// Error besides io.EOF that we dont know how to handle // Error besides io.EOF that we dont know how to handle
default: default:
panic(err) panic(err)

View File

@@ -5,6 +5,7 @@ package main
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@@ -78,7 +79,7 @@ func main() {
sleepTime := time.Millisecond * time.Duration((float32(header.TimebaseNumerator)/float32(header.TimebaseDenominator))*1000) sleepTime := time.Millisecond * time.Duration((float32(header.TimebaseNumerator)/float32(header.TimebaseDenominator))*1000)
for { for {
frame, _, ivfErr := ivf.ParseNextFrame() frame, _, ivfErr := ivf.ParseNextFrame()
if ivfErr == io.EOF { if errors.Is(ivfErr, io.EOF) {
fmt.Printf("All frames parsed and sent") fmt.Printf("All frames parsed and sent")
os.Exit(0) os.Exit(0)
} }

View File

@@ -5,6 +5,7 @@ package main
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@@ -102,7 +103,7 @@ func main() {
ticker := time.NewTicker(time.Millisecond * time.Duration((float32(header.TimebaseNumerator)/float32(header.TimebaseDenominator))*1000)) ticker := time.NewTicker(time.Millisecond * time.Duration((float32(header.TimebaseNumerator)/float32(header.TimebaseDenominator))*1000))
for ; true; <-ticker.C { for ; true; <-ticker.C {
frame, _, ivfErr := ivf.ParseNextFrame() frame, _, ivfErr := ivf.ParseNextFrame()
if ivfErr == io.EOF { if errors.Is(ivfErr, io.EOF) {
fmt.Printf("All video frames parsed and sent") fmt.Printf("All video frames parsed and sent")
os.Exit(0) os.Exit(0)
} }
@@ -167,7 +168,7 @@ func main() {
ticker := time.NewTicker(oggPageDuration) ticker := time.NewTicker(oggPageDuration)
for ; true; <-ticker.C { for ; true; <-ticker.C {
pageData, pageHeader, oggErr := ogg.ParseNextPage() pageData, pageHeader, oggErr := ogg.ParseNextPage()
if oggErr == io.EOF { if errors.Is(oggErr, io.EOF) {
fmt.Printf("All audio pages parsed and sent") fmt.Printf("All audio pages parsed and sent")
os.Exit(0) os.Exit(0)
} }

View File

@@ -4,6 +4,7 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"net" "net"
"os" "os"
@@ -161,7 +162,8 @@ func main() {
// That's why, for this particular example, the user first needs to provide the answer // That's why, for this particular example, the user first needs to provide the answer
// to the browser then open the third party application. Therefore we must not kill // to the browser then open the third party application. Therefore we must not kill
// the forward on "connection refused" errors // the forward on "connection refused" errors
if opError, ok := err.(*net.OpError); ok && opError.Err.Error() == "write: connection refused" { var opError *net.OpError
if errors.As(err, &opError); ok && opError.Err.Error() == "write: connection refused" {
continue continue
} }
panic(err) panic(err)

View File

@@ -45,7 +45,7 @@ type ICETransport struct {
func (t *ICETransport) GetSelectedCandidatePair() (*ICECandidatePair, error) { func (t *ICETransport) GetSelectedCandidatePair() (*ICECandidatePair, error) {
agent := t.gatherer.getAgent() agent := t.gatherer.getAgent()
if agent == nil { if agent == nil {
return nil, nil return nil, nil //nolint:nilnil
} }
icePair, err := agent.GetSelectedCandidatePair() icePair, err := agent.GetSelectedCandidatePair()
@@ -208,9 +208,8 @@ func (t *ICETransport) OnSelectedCandidatePairChange(f func(*ICECandidatePair))
} }
func (t *ICETransport) onSelectedCandidatePairChange(pair *ICECandidatePair) { func (t *ICETransport) onSelectedCandidatePairChange(pair *ICECandidatePair) {
handler := t.onSelectedCandidatePairChangeHandler.Load() if handler, ok := t.onSelectedCandidatePairChangeHandler.Load().(func(*ICECandidatePair)); ok {
if handler != nil { handler(pair)
handler.(func(*ICECandidatePair))(pair)
} }
} }
@@ -221,11 +220,11 @@ func (t *ICETransport) OnConnectionStateChange(f func(ICETransportState)) {
} }
func (t *ICETransport) onConnectionStateChange(state ICETransportState) { func (t *ICETransport) onConnectionStateChange(state ICETransportState) {
if handler := t.onConnectionStateChangeHandler.Load(); handler != nil { if handler, ok := t.onConnectionStateChangeHandler.Load().(func(ICETransportState)); ok {
handler.(func(ICETransportState))(state) handler(state)
} }
if handler := t.internalOnConnectionStateChangeHandler.Load(); handler != nil { if handler, ok := t.internalOnConnectionStateChangeHandler.Load().(func(ICETransportState)); ok {
handler.(func(ICETransportState))(state) handler(state)
} }
} }
@@ -295,8 +294,8 @@ func (t *ICETransport) AddRemoteCandidate(remoteCandidate *ICECandidate) error {
// State returns the current ice transport state. // State returns the current ice transport state.
func (t *ICETransport) State() ICETransportState { func (t *ICETransport) State() ICETransportState {
if v := t.state.Load(); v != nil { if v, ok := t.state.Load().(ICETransportState); ok {
return v.(ICETransportState) return v
} }
return ICETransportState(0) return ICETransportState(0)
} }

View File

@@ -39,7 +39,7 @@ func FlattenErrs(errs []error) error {
return multiError(errs2) return multiError(errs2)
} }
type multiError []error type multiError []error //nolint:errname
func (me multiError) Error() string { func (me multiError) Error() string {
var errstrings []string var errstrings []string
@@ -62,7 +62,7 @@ func (me multiError) Is(err error) bool {
if errors.Is(e, err) { if errors.Is(e, err) {
return true return true
} }
if me2, ok := e.(multiError); ok { if me2, ok := e.(multiError); ok { //nolint:errorlint
if me2.Is(err) { if me2.Is(err) {
return true return true
} }

View File

@@ -38,7 +38,7 @@ func TestMultiError(t *testing.T) {
t.Errorf("String representation doesn't match, expected: %s, got: %s", errs.Error(), str) t.Errorf("String representation doesn't match, expected: %s, got: %s", errs.Error(), str)
} }
errIs, ok := errs.(multiError) errIs, ok := errs.(multiError) //nolint:errorlint
if !ok { if !ok {
t.Fatal("FlattenErrs returns non-multiError") t.Fatal("FlattenErrs returns non-multiError")
} }

View File

@@ -66,7 +66,10 @@ func (o *operations) pop() func() {
e := o.ops.Front() e := o.ops.Front()
o.ops.Remove(e) o.ops.Remove(e)
return e.Value.(operation) if op, ok := e.Value.(operation); ok {
return op
}
return nil
} }
func (o *operations) start() { func (o *operations) start() {

View File

@@ -1651,7 +1651,10 @@ func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error {
// ICEConnectionState returns the ICE connection state of the // ICEConnectionState returns the ICE connection state of the
// PeerConnection instance. // PeerConnection instance.
func (pc *PeerConnection) ICEConnectionState() ICEConnectionState { func (pc *PeerConnection) ICEConnectionState() ICEConnectionState {
return pc.iceConnectionState.Load().(ICEConnectionState) if state, ok := pc.iceConnectionState.Load().(ICEConnectionState); ok {
return state
}
return ICEConnectionState(0)
} }
// GetSenders returns the RTPSender that are currently attached to this PeerConnection // GetSenders returns the RTPSender that are currently attached to this PeerConnection
@@ -2071,7 +2074,10 @@ func (pc *PeerConnection) ICEGatheringState() ICEGatheringState {
// ConnectionState attribute returns the connection state of the // ConnectionState attribute returns the connection state of the
// PeerConnection instance. // PeerConnection instance.
func (pc *PeerConnection) ConnectionState() PeerConnectionState { func (pc *PeerConnection) ConnectionState() PeerConnectionState {
return pc.connectionState.Load().(PeerConnectionState) if state, ok := pc.connectionState.Load().(PeerConnectionState); ok {
return state
}
return PeerConnectionState(0)
} }
// GetStats return data providing statistics about the overall connection // GetStats return data providing statistics about the overall connection

View File

@@ -1580,7 +1580,7 @@ a=ssrc:1455629982 cname:{61fd3093-0326-4b12-8258-86bdc1fe677a}
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, peerConnection.SetRemoteDescription(SessionDescription{Type: SDPTypeOffer, SDP: remoteSDP})) assert.NoError(t, peerConnection.SetRemoteDescription(SessionDescription{Type: SDPTypeOffer, SDP: remoteSDP}))
assert.Equal(t, RTPTransceiverDirectionInactive, peerConnection.rtpTransceivers[0].direction.Load().(RTPTransceiverDirection)) assert.Equal(t, RTPTransceiverDirectionInactive, peerConnection.rtpTransceivers[0].direction.Load().(RTPTransceiverDirection)) //nolint:forcetypeassert
assert.NoError(t, peerConnection.Close()) assert.NoError(t, peerConnection.Close())
} }

View File

@@ -6,6 +6,7 @@ package webrtc
import ( import (
"bufio" "bufio"
"context" "context"
"errors"
"io" "io"
"strconv" "strconv"
"strings" "strings"
@@ -438,7 +439,7 @@ func TestPeerConnection_Renegotiation_CodecChange(t *testing.T) {
pcAnswer.OnTrack(func(track *TrackRemote, r *RTPReceiver) { pcAnswer.OnTrack(func(track *TrackRemote, r *RTPReceiver) {
tracksCh <- track tracksCh <- track
for { for {
if _, _, readErr := track.ReadRTP(); readErr == io.EOF { if _, _, readErr := track.ReadRTP(); errors.Is(readErr, io.EOF) {
tracksClosed <- struct{}{} tracksClosed <- struct{}{}
return return
} }
@@ -527,7 +528,7 @@ func TestPeerConnection_Renegotiation_RemoveTrack(t *testing.T) {
onTrackFiredFunc() onTrackFiredFunc()
for { for {
if _, _, err := track.ReadRTP(); err == io.EOF { if _, _, err := track.ReadRTP(); errors.Is(err, io.EOF) {
trackClosedFunc() trackClosedFunc()
return return
} }

View File

@@ -26,7 +26,7 @@ type (
// New builds a new H264 writer // New builds a new H264 writer
func New(filename string) (*H264Writer, error) { func New(filename string) (*H264Writer, error) {
f, err := os.Create(filename) f, err := os.Create(filename) //nolint:gosec
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -13,10 +13,10 @@ type writerCloser struct {
bytes.Buffer bytes.Buffer
} }
var errCloseErr = errors.New("close error") var errClose = errors.New("close error")
func (w *writerCloser) Close() error { func (w *writerCloser) Close() error {
return errCloseErr return errClose
} }
func TestNewWith(t *testing.T) { func TestNewWith(t *testing.T) {

View File

@@ -43,7 +43,7 @@ type IVFWriter struct {
// New builds a new IVF writer // New builds a new IVF writer
func New(fileName string, opts ...Option) (*IVFWriter, error) { func New(fileName string, opts ...Option) (*IVFWriter, error) {
f, err := os.Create(fileName) f, err := os.Create(fileName) //nolint:gosec
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -43,7 +43,7 @@ type OggWriter struct {
// New builds a new OGG Opus writer // New builds a new OGG Opus writer
func New(fileName string, sampleRate uint32, channelCount uint16) (*OggWriter, error) { func New(fileName string, sampleRate uint32, channelCount uint16) (*OggWriter, error) {
f, err := os.Create(fileName) f, err := os.Create(fileName) //nolint:gosec
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -23,7 +23,7 @@ func NewReader(r io.Reader) (*Reader, Header, error) {
// Look ahead to see if there's a valid preamble // Look ahead to see if there's a valid preamble
peek, err := bio.Peek(preambleLen) peek, err := bio.Peek(preambleLen)
if err == io.EOF { if errors.Is(err, io.EOF) {
return nil, hdr, errMalformed return nil, hdr, errMalformed
} }
if err != nil { if err != nil {
@@ -38,7 +38,7 @@ func NewReader(r io.Reader) (*Reader, Header, error) {
// consume the preamble // consume the preamble
_, _, err = bio.ReadLine() _, _, err = bio.ReadLine()
if err == io.EOF { if errors.Is(err, io.EOF) {
return nil, hdr, errMalformed return nil, hdr, errMalformed
} }
if err != nil { if err != nil {

View File

@@ -262,7 +262,7 @@ func TestReader(t *testing.T) {
var packets []Packet var packets []Packet
for { for {
pkt, err := r.Next() pkt, err := r.Next()
if err == io.EOF { if errors.Is(err, io.EOF) {
break break
} }
if err != nil { if err != nil {

View File

@@ -100,9 +100,7 @@ func (p Packet) Marshal() ([]byte, error) {
return nil, err return nil, err
} }
data := append(hdrData, p.Payload...) return append(hdrData, p.Payload...), nil
return data, nil
} }
// Unmarshal decodes the Packet from binary. // Unmarshal decodes the Packet from binary.

View File

@@ -2,6 +2,7 @@ package rtpdump
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"net" "net"
"reflect" "reflect"
@@ -91,7 +92,7 @@ func TestRoundTrip(t *testing.T) {
var packets2 []Packet var packets2 []Packet
for { for {
pkt, err := reader.Next() pkt, err := reader.Next()
if err == io.EOF { if errors.Is(err, io.EOF) {
break break
} }
if err != nil { if err != nil {

View File

@@ -82,8 +82,8 @@ func (t *RTPTransceiver) getCodecs() []RTPCodecParameters {
// Sender returns the RTPTransceiver's RTPSender if it has one // Sender returns the RTPTransceiver's RTPSender if it has one
func (t *RTPTransceiver) Sender() *RTPSender { func (t *RTPTransceiver) Sender() *RTPSender {
if v := t.sender.Load(); v != nil { if v, ok := t.sender.Load().(*RTPSender); ok {
return v.(*RTPSender) return v
} }
return nil return nil
@@ -109,8 +109,8 @@ func (t *RTPTransceiver) setSender(s *RTPSender) {
// Receiver returns the RTPTransceiver's RTPReceiver if it has one // Receiver returns the RTPTransceiver's RTPReceiver if it has one
func (t *RTPTransceiver) Receiver() *RTPReceiver { func (t *RTPTransceiver) Receiver() *RTPReceiver {
if v := t.receiver.Load(); v != nil { if v, ok := t.receiver.Load().(*RTPReceiver); ok {
return v.(*RTPReceiver) return v
} }
return nil return nil
@@ -127,8 +127,8 @@ func (t *RTPTransceiver) SetMid(mid string) error {
// Mid gets the Transceiver's mid value. When not already set, this value will be set in CreateOffer or CreateAnswer. // Mid gets the Transceiver's mid value. When not already set, this value will be set in CreateOffer or CreateAnswer.
func (t *RTPTransceiver) Mid() string { func (t *RTPTransceiver) Mid() string {
if v := t.mid.Load(); v != nil { if v, ok := t.mid.Load().(string); ok {
return v.(string) return v
} }
return "" return ""
} }
@@ -140,7 +140,10 @@ func (t *RTPTransceiver) Kind() RTPCodecType {
// Direction returns the RTPTransceiver's current direction // Direction returns the RTPTransceiver's current direction
func (t *RTPTransceiver) Direction() RTPTransceiverDirection { func (t *RTPTransceiver) Direction() RTPTransceiverDirection {
return t.direction.Load().(RTPTransceiverDirection) if direction, ok := t.direction.Load().(RTPTransceiverDirection); ok {
return direction
}
return RTPTransceiverDirection(0)
} }
// Stop irreversibly stops the RTPTransceiver // Stop irreversibly stops the RTPTransceiver

View File

@@ -4,6 +4,7 @@
package webrtc package webrtc
import ( import (
"errors"
"io" "io"
"math" "math"
"sync" "sync"
@@ -175,7 +176,7 @@ ACCEPT:
LoggerFactory: r.api.settingEngine.LoggerFactory, LoggerFactory: r.api.settingEngine.LoggerFactory,
}, dataChannels...) }, dataChannels...)
if err != nil { if err != nil {
if err != io.EOF { if errors.Is(err, io.EOF) {
r.log.Errorf("Failed to accept data channel: %v", err) r.log.Errorf("Failed to accept data channel: %v", err)
r.onError(err) r.onError(err)
} }

View File

@@ -82,16 +82,16 @@ func (s *srtpWriterFuture) Close() error {
} }
s.closed = true s.closed = true
if value := s.rtcpReadStream.Load(); value != nil { if value, ok := s.rtcpReadStream.Load().(*srtp.ReadStreamSRTCP); ok {
return value.(*srtp.ReadStreamSRTCP).Close() return value.Close()
} }
return nil return nil
} }
func (s *srtpWriterFuture) Read(b []byte) (n int, err error) { func (s *srtpWriterFuture) Read(b []byte) (n int, err error) {
if value := s.rtcpReadStream.Load(); value != nil { if value, ok := s.rtcpReadStream.Load().(*srtp.ReadStreamSRTCP); ok {
return value.(*srtp.ReadStreamSRTCP).Read(b) return value.Read(b)
} }
if err := s.init(false); err != nil || s.rtcpReadStream.Load() == nil { if err := s.init(false); err != nil || s.rtcpReadStream.Load() == nil {
@@ -102,8 +102,8 @@ func (s *srtpWriterFuture) Read(b []byte) (n int, err error) {
} }
func (s *srtpWriterFuture) SetReadDeadline(t time.Time) error { func (s *srtpWriterFuture) SetReadDeadline(t time.Time) error {
if value := s.rtcpReadStream.Load(); value != nil { if value, ok := s.rtcpReadStream.Load().(*srtp.ReadStreamSRTCP); ok {
return value.(*srtp.ReadStreamSRTCP).SetReadDeadline(t) return value.SetReadDeadline(t)
} }
if err := s.init(false); err != nil || s.rtcpReadStream.Load() == nil { if err := s.init(false); err != nil || s.rtcpReadStream.Load() == nil {
@@ -114,8 +114,8 @@ func (s *srtpWriterFuture) SetReadDeadline(t time.Time) error {
} }
func (s *srtpWriterFuture) WriteRTP(header *rtp.Header, payload []byte) (int, error) { func (s *srtpWriterFuture) WriteRTP(header *rtp.Header, payload []byte) (int, error) {
if value := s.rtpWriteStream.Load(); value != nil { if value, ok := s.rtpWriteStream.Load().(*srtp.WriteStreamSRTP); ok {
return value.(*srtp.WriteStreamSRTP).WriteRTP(header, payload) return value.WriteRTP(header, payload)
} }
if err := s.init(true); err != nil || s.rtpWriteStream.Load() == nil { if err := s.init(true); err != nil || s.rtpWriteStream.Load() == nil {
@@ -126,8 +126,8 @@ func (s *srtpWriterFuture) WriteRTP(header *rtp.Header, payload []byte) (int, er
} }
func (s *srtpWriterFuture) Write(b []byte) (int, error) { func (s *srtpWriterFuture) Write(b []byte) (int, error) {
if value := s.rtpWriteStream.Load(); value != nil { if value, ok := s.rtpWriteStream.Load().(*srtp.WriteStreamSRTP); ok {
return value.(*srtp.WriteStreamSRTP).Write(b) return value.Write(b)
} }
if err := s.init(true); err != nil || s.rtpWriteStream.Load() == nil { if err := s.init(true); err != nil || s.rtpWriteStream.Load() == nil {

View File

@@ -134,7 +134,7 @@ var rtpPacketPool = sync.Pool{
// PeerConnections so you can remove them // PeerConnections so you can remove them
func (s *TrackLocalStaticRTP) WriteRTP(p *rtp.Packet) error { func (s *TrackLocalStaticRTP) WriteRTP(p *rtp.Packet) error {
ipacket := rtpPacketPool.Get() ipacket := rtpPacketPool.Get()
packet := ipacket.(*rtp.Packet) packet := ipacket.(*rtp.Packet) //nolint:forcetypeassert
defer func() { defer func() {
*packet = rtp.Packet{} *packet = rtp.Packet{}
rtpPacketPool.Put(ipacket) rtpPacketPool.Put(ipacket)
@@ -167,7 +167,7 @@ func (s *TrackLocalStaticRTP) writeRTP(p *rtp.Packet) error {
// PeerConnections so you can remove them // PeerConnections so you can remove them
func (s *TrackLocalStaticRTP) Write(b []byte) (n int, err error) { func (s *TrackLocalStaticRTP) Write(b []byte) (n int, err error) {
ipacket := rtpPacketPool.Get() ipacket := rtpPacketPool.Get()
packet := ipacket.(*rtp.Packet) packet := ipacket.(*rtp.Packet) //nolint:forcetypeassert
defer func() { defer func() {
*packet = rtp.Packet{} *packet = rtp.Packet{}
rtpPacketPool.Put(ipacket) rtpPacketPool.Put(ipacket)