From ec16766d4391a1e52902b0b675d67064058b3593 Mon Sep 17 00:00:00 2001 From: ucwong Date: Fri, 14 Feb 2025 02:15:54 +0800 Subject: [PATCH] skip setting flushOffset in read-only mode --- core/rawdb/freezer_table.go | 7 + go.mod | 10 +- go.sum | 20 +- .../charmbracelet/bubbletea/options.go | 17 - .../charmbracelet/bubbletea/screen.go | 44 +- .../github.com/dlclark/regexp2/fastclock.go | 12 + .../github.com/pion/webrtc/v4/.golangci.yml | 47 +- vendor/github.com/pion/webrtc/v4/api.go | 24 +- .../github.com/pion/webrtc/v4/atomicbool.go | 1 + .../github.com/pion/webrtc/v4/bundlepolicy.go | 7 +- .../github.com/pion/webrtc/v4/certificate.go | 38 +- .../pion/webrtc/v4/configuration_common.go | 1 + vendor/github.com/pion/webrtc/v4/constants.go | 21 +- .../github.com/pion/webrtc/v4/datachannel.go | 50 +- .../pion/webrtc/v4/datachannel_js.go | 47 ++ .../pion/webrtc/v4/datachannelstate.go | 7 +- vendor/github.com/pion/webrtc/v4/dtlsrole.go | 4 +- .../pion/webrtc/v4/dtlstransport.go | 70 ++- .../pion/webrtc/v4/dtlstransport_js.go | 5 + .../pion/webrtc/v4/dtlstransportstate.go | 7 +- vendor/github.com/pion/webrtc/v4/errors.go | 144 +++-- .../webrtc/v4/gathering_complete_promise.go | 6 +- .../github.com/pion/webrtc/v4/icecandidate.go | 116 +++- .../pion/webrtc/v4/icecandidateinit.go | 2 +- .../pion/webrtc/v4/icecandidatepair.go | 5 +- .../pion/webrtc/v4/icecandidatetype.go | 6 +- .../github.com/pion/webrtc/v4/icecomponent.go | 2 +- .../pion/webrtc/v4/iceconnectionstate.go | 4 +- .../pion/webrtc/v4/icecredentialtype.go | 5 +- .../github.com/pion/webrtc/v4/icegatherer.go | 26 +- .../pion/webrtc/v4/icegathererstate.go | 2 +- .../pion/webrtc/v4/icegatheringstate.go | 4 +- .../github.com/pion/webrtc/v4/iceprotocol.go | 4 +- vendor/github.com/pion/webrtc/v4/icerole.go | 7 +- vendor/github.com/pion/webrtc/v4/iceserver.go | 22 +- .../github.com/pion/webrtc/v4/icetransport.go | 41 +- .../pion/webrtc/v4/icetransport_js.go | 5 + .../pion/webrtc/v4/icetransportpolicy.go | 9 +- .../pion/webrtc/v4/icetransportstate.go | 7 +- .../github.com/pion/webrtc/v4/interceptor.go | 47 +- .../pion/webrtc/v4/internal/fmtp/av1.go | 1 + .../pion/webrtc/v4/internal/fmtp/fmtp.go | 27 +- .../pion/webrtc/v4/internal/fmtp/h264.go | 8 +- .../pion/webrtc/v4/internal/fmtp/vp9.go | 1 + .../pion/webrtc/v4/internal/mux/endpoint.go | 24 +- .../pion/webrtc/v4/internal/mux/mux.go | 52 +- .../pion/webrtc/v4/internal/mux/muxfunc.go | 16 +- .../pion/webrtc/v4/internal/util/util.go | 4 +- .../github.com/pion/webrtc/v4/mediaengine.go | 146 +++-- .../github.com/pion/webrtc/v4/networktype.go | 6 +- .../pion/webrtc/v4/offeransweroptions.go | 2 +- .../github.com/pion/webrtc/v4/operations.go | 8 +- .../pion/webrtc/v4/peerconnection.go | 584 ++++++++++++------ .../pion/webrtc/v4/peerconnectionstate.go | 2 +- .../pion/webrtc/v4/pkg/media/media.go | 4 +- .../pion/webrtc/v4/rtcpmuxpolicy.go | 7 +- vendor/github.com/pion/webrtc/v4/rtpcodec.go | 20 +- .../pion/webrtc/v4/rtpreceiveparameters.go | 2 +- .../github.com/pion/webrtc/v4/rtpreceiver.go | 124 +++- .../pion/webrtc/v4/rtpreceiver_js.go | 5 + vendor/github.com/pion/webrtc/v4/rtpsender.go | 61 +- .../github.com/pion/webrtc/v4/rtpsender_js.go | 5 + .../pion/webrtc/v4/rtpsendparameters.go | 2 +- .../pion/webrtc/v4/rtptransceiver.go | 59 +- .../pion/webrtc/v4/rtptransceiver_js.go | 5 + .../pion/webrtc/v4/rtptransceiverdirection.go | 10 +- .../pion/webrtc/v4/rtptransceiverinit.go | 3 +- .../pion/webrtc/v4/sctptransport.go | 22 +- .../pion/webrtc/v4/sctptransport_js.go | 5 + .../pion/webrtc/v4/sctptransportstate.go | 2 +- vendor/github.com/pion/webrtc/v4/sdp.go | 281 ++++++--- .../github.com/pion/webrtc/v4/sdpsemantics.go | 9 +- vendor/github.com/pion/webrtc/v4/sdptype.go | 8 +- .../pion/webrtc/v4/sessiondescription.go | 3 +- .../pion/webrtc/v4/settingengine.go | 59 +- .../pion/webrtc/v4/signalingstate.go | 10 +- .../pion/webrtc/v4/srtp_writer_future.go | 5 +- vendor/github.com/pion/webrtc/v4/stats.go | 55 +- vendor/github.com/pion/webrtc/v4/stats_go.go | 18 +- .../github.com/pion/webrtc/v4/track_local.go | 18 +- .../pion/webrtc/v4/track_local_static.go | 90 +-- .../github.com/pion/webrtc/v4/track_remote.go | 48 +- .../supranational/blst/bindings/go/README.md | 16 +- .../supranational/blst/bindings/go/blst.go | 462 +++++++------- .../supranational/blst/bindings/go/blst.tgo | 86 +-- .../blst/bindings/go/blst_minpk.tgo | 36 +- .../blst/bindings/go/blst_misc.tgo | 81 +-- .../blst/bindings/go/blst_px.tgo | 134 ++-- .../blst/bindings/go/generate.py | 1 + vendor/modernc.org/libc/libc_windows.go | 30 +- vendor/modules.txt | 10 +- 91 files changed, 2294 insertions(+), 1286 deletions(-) diff --git a/core/rawdb/freezer_table.go b/core/rawdb/freezer_table.go index 10bf5f9a6e..ec3b4f31c2 100644 --- a/core/rawdb/freezer_table.go +++ b/core/rawdb/freezer_table.go @@ -406,6 +406,13 @@ func (t *freezerTable) repairIndex() error { // If legacy metadata is detected, attempt to recover the offset from the // index file to avoid clearing the entire table. if t.metadata.version == freezerTableV1 { + // Skip truncation if the legacy metadata is opened in read-only mode. + // Since all items in the legacy index file were forcibly synchronized, + // data integrity is guaranteed. Therefore, it's safe to leave any extra + // items untruncated in this special scenario. + if t.readonly { + return nil + } t.logger.Info("Recovering freezer flushOffset for legacy table", "offset", size) return t.metadata.setFlushOffset(size, true) } diff --git a/go.mod b/go.mod index bb3b2f8524..a81f018626 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,7 @@ require ( github.com/aws/aws-sdk-go-v2/credentials v1.17.59 github.com/aws/aws-sdk-go-v2/service/route53 v1.48.7 github.com/cespare/cp v1.1.1 - github.com/charmbracelet/bubbletea v1.3.2 + github.com/charmbracelet/bubbletea v1.3.3 github.com/cloudflare/cloudflare-go v0.115.0 github.com/cockroachdb/pebble v1.1.4 github.com/consensys/gnark-crypto v0.16.0 @@ -140,7 +140,7 @@ require ( github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect github.com/dgraph-io/badger/v4 v4.5.2-0.20250122183558-3ceff587c885 // indirect github.com/dgraph-io/ristretto/v2 v2.1.0 // indirect - github.com/dlclark/regexp2 v1.11.4 // indirect + github.com/dlclark/regexp2 v1.11.5 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/edsrzf/mmap-go v1.2.0 // indirect github.com/elliotchance/orderedmap v1.8.0 // indirect @@ -203,7 +203,7 @@ require ( github.com/pion/transport/v2 v2.2.10 // indirect github.com/pion/transport/v3 v3.0.7 // indirect github.com/pion/turn/v4 v4.0.0 // indirect - github.com/pion/webrtc/v4 v4.0.8 // indirect + github.com/pion/webrtc/v4 v4.0.9 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.20.5 // indirect @@ -219,7 +219,7 @@ require ( github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 // indirect - github.com/supranational/blst v0.3.13 // indirect + github.com/supranational/blst v0.3.14 // indirect github.com/tidwall/btree v1.7.0 // indirect github.com/tidwall/hashmap v1.8.1 // indirect github.com/tklauser/go-sysconf v0.3.14 // indirect @@ -245,7 +245,7 @@ require ( golang.org/x/term v0.29.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect lukechampine.com/blake3 v1.3.0 // indirect - modernc.org/libc v1.61.12 // indirect + modernc.org/libc v1.61.13 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.8.2 // indirect modernc.org/sqlite v1.34.5 // indirect diff --git a/go.sum b/go.sum index f7e419302c..fabc43be03 100644 --- a/go.sum +++ b/go.sum @@ -337,8 +337,8 @@ github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/bubbletea v1.3.2 h1:nc+gDivH0P8ii8CUcf3zCN/PiUz7LKbp3Iz+vYPScNY= -github.com/charmbracelet/bubbletea v1.3.2/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo= +github.com/charmbracelet/bubbletea v1.3.3 h1:WpU6fCY0J2vDWM3zfS3vIDi/ULq3SYphZhkAGGvmEUY= +github.com/charmbracelet/bubbletea v1.3.3/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo= github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg= github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo= github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= @@ -422,8 +422,8 @@ github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WA github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= -github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo= -github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= +github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/docker/docker v1.13.1/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/dop251/goja v0.0.0-20200721192441-a695b0cdd498/go.mod h1:Mw6PkjjMXWbTj+nnj4s3QPXq1jaT0s5pC0iFD4+BOAA= @@ -1032,8 +1032,8 @@ github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM= github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA= github.com/pion/webrtc/v2 v2.2.7/go.mod h1:EfCuvKjzMgX4F/aSryRUC7L9o3u2N8WNUgnzd6wOO+8= github.com/pion/webrtc/v2 v2.2.9/go.mod h1:TcArPDphZIBtZ+mh8J/qOREyY3ca7ihQrenulOIvfPQ= -github.com/pion/webrtc/v4 v4.0.8 h1:T1ZmnT9qxIJIt4d8XoiMOBrTClGHDDXNg9e/fh018Qc= -github.com/pion/webrtc/v4 v4.0.8/go.mod h1:HHBeUVBAC+j4ZFnYhovEFStF02Arb1EyD4G7e7HBTJw= +github.com/pion/webrtc/v4 v4.0.9 h1:PyOYMRKJgfy0dzPcYtFD/4oW9zaw3Ze3oZzzbj2LV9E= +github.com/pion/webrtc/v4 v4.0.9/go.mod h1:ViHLVaNpiuvaH8pdiuQxuA9awuE6KVzAXx3vVWilOck= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= @@ -1223,8 +1223,8 @@ github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXl github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/supranational/blst v0.3.13 h1:AYeSxdOMacwu7FBmpfloBz5pbFXDmJL33RuwnKtmTjk= -github.com/supranational/blst v0.3.13/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= +github.com/supranational/blst v0.3.14 h1:xNMoHRJOTwMn63ip6qoWJ2Ymgvj7E2b9jY2FAwY+qRo= +github.com/supranational/blst v0.3.14/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= github.com/syncthing/syncthing v0.14.48-rc.4/go.mod h1:nw3siZwHPA6M8iSfjDCWQ402eqvEIasMQOE8nFOxy7M= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= @@ -1813,8 +1813,8 @@ modernc.org/libc v1.19.0/go.mod h1:ZRfIaEkgrYgZDl6pa4W39HgN5G/yDW+NRmNKZBDFrk0= modernc.org/libc v1.20.3/go.mod h1:ZRfIaEkgrYgZDl6pa4W39HgN5G/yDW+NRmNKZBDFrk0= modernc.org/libc v1.21.4/go.mod h1:przBsL5RDOZajTVslkugzLBj1evTue36jEomFQOoYuI= modernc.org/libc v1.21.5/go.mod h1:przBsL5RDOZajTVslkugzLBj1evTue36jEomFQOoYuI= -modernc.org/libc v1.61.12 h1:Fsnh0A7XLXylYNwIOJmKux9PhnfrIvMaMnjuyJ1t/f4= -modernc.org/libc v1.61.12/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= +modernc.org/libc v1.61.13 h1:3LRd6ZO1ezsFiX1y+bHd1ipyEHIJKvuprv0sLTBwLW8= +modernc.org/libc v1.61.13/go.mod h1:8F/uJWL/3nNil0Lgt1Dpz+GgkApWh04N3el3hxJcA6E= modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= diff --git a/vendor/github.com/charmbracelet/bubbletea/options.go b/vendor/github.com/charmbracelet/bubbletea/options.go index e1f70ef69b..c509353b18 100644 --- a/vendor/github.com/charmbracelet/bubbletea/options.go +++ b/vendor/github.com/charmbracelet/bubbletea/options.go @@ -106,8 +106,6 @@ func WithoutSignals() ProgramOption { // // To enter the altscreen once the program has already started running use the // EnterAltScreen command. -// -// Deprecated: use the [EnterAltScreen] [Cmd] in your [Model.Init] instead. func WithAltScreen() ProgramOption { return func(p *Program) { p.startupOptions |= withAltScreen @@ -115,9 +113,6 @@ func WithAltScreen() ProgramOption { } // WithoutBracketedPaste starts the program with bracketed paste disabled. -// -// Deprecated: use the [EnableBracketedPaste] [Cmd] in your [Model.Init] -// instead. func WithoutBracketedPaste() ProgramOption { return func(p *Program) { p.startupOptions |= withoutBracketedPaste @@ -139,9 +134,6 @@ func WithoutBracketedPaste() ProgramOption { // running use the DisableMouse command. // // The mouse will be automatically disabled when the program exits. -// -// Deprecated: use the [EnableMouseCellMotion] [Cmd] in your [Model.Init] -// instead. func WithMouseCellMotion() ProgramOption { return func(p *Program) { p.startupOptions |= withMouseCellMotion // set @@ -167,9 +159,6 @@ func WithMouseCellMotion() ProgramOption { // running use the DisableMouse command. // // The mouse will be automatically disabled when the program exits. -// -// Deprecated: use the [EnableMouseAllMotion] [Cmd] in your [Model.Init] -// instead. func WithMouseAllMotion() ProgramOption { return func(p *Program) { p.startupOptions |= withMouseAllMotion // set @@ -199,10 +188,6 @@ func WithoutRenderer() ProgramOption { // // Deprecated: this incurs a noticeable performance hit. A future release will // optimize ANSI automatically without the performance penalty. -// -// Deprecated: this will be removed in a future release. This ANSI compressor -// has major performance implications and we don't recommend using it. In v2, -// rendering bandwidth will be decreased significantly. func WithANSICompressor() ProgramOption { return func(p *Program) { p.startupOptions |= withANSICompressor @@ -260,8 +245,6 @@ func WithFPS(fps int) ProgramOption { // Note that while most terminals and multiplexers support focus reporting, // some do not. Also note that tmux needs to be configured to report focus // events. -// -// Deprecated: use the [EnableReportFocus] [Cmd] in your [Model.Init] instead. func WithReportFocus() ProgramOption { return func(p *Program) { p.startupOptions |= withReportFocus diff --git a/vendor/github.com/charmbracelet/bubbletea/screen.go b/vendor/github.com/charmbracelet/bubbletea/screen.go index daf3360935..dfec48f0b4 100644 --- a/vendor/github.com/charmbracelet/bubbletea/screen.go +++ b/vendor/github.com/charmbracelet/bubbletea/screen.go @@ -24,9 +24,11 @@ func ClearScreen() Msg { type clearScreenMsg struct{} // EnterAltScreen is a special command that tells the Bubble Tea program to -// enter the alternate screen buffer (i.e. the full terminal window). The -// altscreen will be automatically exited when the program quits. To manually -// exit the altscreen while the program is running, use [ExitAltScreen]. +// enter the alternate screen buffer. +// +// Because commands run asynchronously, this command should not be used in your +// model's Init function. To initialize your program with the altscreen enabled +// use the WithAltScreen ProgramOption instead. func EnterAltScreen() Msg { return enterAltScreenMsg{} } @@ -47,13 +49,15 @@ func ExitAltScreen() Msg { } // exitAltScreenMsg in an internal message signals that the program should exit -// alternate screen buffer. You can send a exitAltScreenMsg with -// [ExitAltScreen]. +// alternate screen buffer. You can send a exitAltScreenMsg with ExitAltScreen. type exitAltScreenMsg struct{} // EnableMouseCellMotion is a special command that enables mouse click, // release, and wheel events. Mouse movement events are also captured if // a mouse button is pressed (i.e., drag events). +// +// Because commands run asynchronously, this command should not be used in your +// model's Init function. Use the WithMouseCellMotion ProgramOption instead. func EnableMouseCellMotion() Msg { return enableMouseCellMotionMsg{} } @@ -68,7 +72,10 @@ type enableMouseCellMotionMsg struct{} // button is pressed, effectively enabling support for hover interactions. // // Many modern terminals support this, but not all. If in doubt, use -// [EnableMouseCellMotion] instead. +// EnableMouseCellMotion instead. +// +// Because commands run asynchronously, this command should not be used in your +// model's Init function. Use the WithMouseAllMotion ProgramOption instead. func EnableMouseAllMotion() Msg { return enableMouseAllMotionMsg{} } @@ -101,9 +108,6 @@ type hideCursorMsg struct{} // ShowCursor is a special command for manually instructing Bubble Tea to show // the cursor. -// -// Deprecated: this will be removed in a future release. In v2, the cursor will -// can be manged via a dedicated API. func ShowCursor() Msg { return showCursorMsg{} } @@ -113,10 +117,9 @@ func ShowCursor() Msg { type showCursorMsg struct{} // EnableBracketedPaste is a special command that tells the Bubble Tea program -// to accept bracketed paste input. To disable bracketed paste, use -// [DisableBracketedPaste]. +// to accept bracketed paste input. // -// Also note that bracketed paste will be automatically disabled when the +// Note that bracketed paste will be automatically disabled when the // program quits. func EnableBracketedPaste() Msg { return enableBracketedPasteMsg{} @@ -128,18 +131,17 @@ func EnableBracketedPaste() Msg { type enableBracketedPasteMsg struct{} // DisableBracketedPaste is a special command that tells the Bubble Tea program -// to accept bracketed paste input. To enable bracketed paste, use -// [EnableBracketedPaste]. +// to accept bracketed paste input. // -// Also note that bracketed paste will be automatically disabled when the +// Note that bracketed paste will be automatically disabled when the // program quits. func DisableBracketedPaste() Msg { return disableBracketedPasteMsg{} } -// disableBracketedPasteMsg in an internal message signals that bracketed paste -// should be disabled. You can send an disableBracketedPasteMsg with -// DisableBracketedPaste. +// disableBracketedPasteMsg in an internal message signals that +// bracketed paste should be disabled. You can send an +// disableBracketedPasteMsg with DisableBracketedPaste. type disableBracketedPasteMsg struct{} // enableReportFocusMsg is an internal message that signals to enable focus @@ -165,7 +167,7 @@ func DisableReportFocus() Msg { // EnterAltScreen enters the alternate screen buffer, which consumes the entire // terminal window. ExitAltScreen will return the terminal to its former state. // -// Deprecated: Use the [EnterAltScreen] [Cmd] instead. +// Deprecated: Use the WithAltScreen ProgramOption instead. func (p *Program) EnterAltScreen() { if p.renderer != nil { p.renderer.enterAltScreen() @@ -188,7 +190,7 @@ func (p *Program) ExitAltScreen() { // EnableMouseCellMotion enables mouse click, release, wheel and motion events // if a mouse button is pressed (i.e., drag events). // -// Deprecated: Use the [EnableMouseCellMotion] [Cmd] instead. +// Deprecated: Use the WithMouseCellMotion ProgramOption instead. func (p *Program) EnableMouseCellMotion() { if p.renderer != nil { p.renderer.enableMouseCellMotion() @@ -213,7 +215,7 @@ func (p *Program) DisableMouseCellMotion() { // regardless of whether a mouse button is pressed. Many modern terminals // support this, but not all. // -// Deprecated: Use the [EnableMouseAllMotion] [Cmd] instead. +// Deprecated: Use the WithMouseAllMotion ProgramOption instead. func (p *Program) EnableMouseAllMotion() { if p.renderer != nil { p.renderer.enableMouseAllMotion() diff --git a/vendor/github.com/dlclark/regexp2/fastclock.go b/vendor/github.com/dlclark/regexp2/fastclock.go index caf2c9d882..d256e63c74 100644 --- a/vendor/github.com/dlclark/regexp2/fastclock.go +++ b/vendor/github.com/dlclark/regexp2/fastclock.go @@ -50,8 +50,20 @@ func makeDeadline(d time.Duration) fasttime { // Start or extend clock if necessary. if end > fast.clockEnd.read() { + // If time.Since(last use) > timeout, there's a chance that + // fast.current will no longer be updated, which can lead to + // incorrect 'end' calculations that can trigger a false timeout + fast.mu.Lock() + if !fast.running && !fast.start.IsZero() { + // update fast.current + fast.current.write(durationToTicks(time.Since(fast.start))) + // recalculate our end value + end = fast.current.read() + durationToTicks(d+clockPeriod) + } + fast.mu.Unlock() extendClock(end) } + return end } diff --git a/vendor/github.com/pion/webrtc/v4/.golangci.yml b/vendor/github.com/pion/webrtc/v4/.golangci.yml index a3235bec28..88cb4fbf9e 100644 --- a/vendor/github.com/pion/webrtc/v4/.golangci.yml +++ b/vendor/github.com/pion/webrtc/v4/.golangci.yml @@ -25,17 +25,32 @@ linters-settings: - ^os.Exit$ - ^panic$ - ^print(ln)?$ + varnamelen: + max-distance: 12 + min-name-length: 2 + ignore-type-assert-ok: true + ignore-map-index-ok: true + ignore-chan-recv-ok: true + ignore-decls: + - i int + - n int + - w io.Writer + - r io.Reader + - b []byte linters: enable: - 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 + - containedctx # containedctx is a linter that detects struct contained context.Context field - contextcheck # check the function whether use a non-inherited context + - cyclop # checks function and package cyclomatic complexity - decorder # check declaration order and count of types, constants, variables and functions - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - durationcheck # check for two durations multiplied together + - err113 # Golang linter to check the errors handling expressions - 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`. @@ -46,18 +61,17 @@ linters: - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - - gochecknoinits # Checks that no init functions are present in Go code - gocognit # Computes and checks the cognitive complexity of functions - goconst # Finds repeated strings that could be replaced by a constant - gocritic # The most opinionated Go source code linter + - gocyclo # Computes and checks the cyclomatic complexity of functions + - godot # Check if comments end in a period - godox # Tool for detection of FIXME, TODO and other comment keywords - - err113 # Golang linter to check the errors handling expressions - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - 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. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code @@ -65,9 +79,15 @@ linters: - grouper # An analyzer to analyze expression groups. - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used + - lll # Reports long lines + - maintidx # maintidx measures the maintainability index of each function. + - makezero # Finds slice declarations with non-zero initial length - misspell # Finds commonly misspelled English words in comments + - nakedret # Finds naked returns in functions greater than a specified function length + - nestif # Reports deeply nested if statements - 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. + - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - noctx # noctx finds sending http request without context.Context - predeclared # find code that shadows one of Go's predeclared identifiers - revive # golint replacement, finds style mistakes @@ -75,28 +95,22 @@ linters: - 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 + - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types + - varnamelen # checks that the length of a variable's name matches its scope - wastedassign # wastedassign finds wasted assignment statements - whitespace # Tool for detection of leading and trailing whitespace disable: - depguard # Go linter that checks if package imports are in a list of acceptable packages - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - funlen # Tool for detection of long functions - - gocyclo # Computes and checks the cyclomatic complexity of functions - - godot # Check if comments end in a period - - gomnd # An analyzer to detect magic numbers. + - gochecknoinits # Checks that no init functions are present in Go code + - 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. + - interfacebloat # A linter that checks length of interface. - ireturn # Accept Interfaces, Return Concrete Types - - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - - nakedret # Finds naked returns in functions greater than a specified function length - - nestif # Reports deeply nested if statements - - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity + - mnd # An analyzer to detect magic numbers - 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 @@ -104,8 +118,7 @@ linters: - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - 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 + - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! diff --git a/vendor/github.com/pion/webrtc/v4/api.go b/vendor/github.com/pion/webrtc/v4/api.go index 369b1a9a37..a96ebad401 100644 --- a/vendor/github.com/pion/webrtc/v4/api.go +++ b/vendor/github.com/pion/webrtc/v4/api.go @@ -29,38 +29,38 @@ type API struct { // It uses the default Codecs and Interceptors unless you customize them // using WithMediaEngine and WithInterceptorRegistry respectively. func NewAPI(options ...func(*API)) *API { - a := &API{ + api := &API{ interceptor: &interceptor.NoOp{}, settingEngine: &SettingEngine{}, } for _, o := range options { - o(a) + o(api) } - if a.settingEngine.LoggerFactory == nil { - a.settingEngine.LoggerFactory = logging.NewDefaultLoggerFactory() + if api.settingEngine.LoggerFactory == nil { + api.settingEngine.LoggerFactory = logging.NewDefaultLoggerFactory() } - logger := a.settingEngine.LoggerFactory.NewLogger("api") + logger := api.settingEngine.LoggerFactory.NewLogger("api") - if a.mediaEngine == nil { - a.mediaEngine = &MediaEngine{} - err := a.mediaEngine.RegisterDefaultCodecs() + if api.mediaEngine == nil { + api.mediaEngine = &MediaEngine{} + err := api.mediaEngine.RegisterDefaultCodecs() if err != nil { logger.Errorf("Failed to register default codecs %s", err) } } - if a.interceptorRegistry == nil { - a.interceptorRegistry = &interceptor.Registry{} - err := RegisterDefaultInterceptors(a.mediaEngine, a.interceptorRegistry) + if api.interceptorRegistry == nil { + api.interceptorRegistry = &interceptor.Registry{} + err := RegisterDefaultInterceptors(api.mediaEngine, api.interceptorRegistry) if err != nil { logger.Errorf("Failed to register default interceptors %s", err) } } - return a + return api } // WithMediaEngine allows providing a MediaEngine to the API. diff --git a/vendor/github.com/pion/webrtc/v4/atomicbool.go b/vendor/github.com/pion/webrtc/v4/atomicbool.go index cc6cdc1e84..846289ecad 100644 --- a/vendor/github.com/pion/webrtc/v4/atomicbool.go +++ b/vendor/github.com/pion/webrtc/v4/atomicbool.go @@ -27,5 +27,6 @@ func (b *atomicBool) swap(value bool) bool { if value { i = 1 } + return atomic.SwapInt32(&(b.val), i) != 0 } diff --git a/vendor/github.com/pion/webrtc/v4/bundlepolicy.go b/vendor/github.com/pion/webrtc/v4/bundlepolicy.go index 7e3d6c506f..1750ade38c 100644 --- a/vendor/github.com/pion/webrtc/v4/bundlepolicy.go +++ b/vendor/github.com/pion/webrtc/v4/bundlepolicy.go @@ -14,7 +14,7 @@ import ( type BundlePolicy int const ( - // BundlePolicyUnknown is the enum's zero-value + // BundlePolicyUnknown is the enum's zero-value. BundlePolicyUnknown BundlePolicy = iota // BundlePolicyBalanced indicates to gather ICE candidates for each @@ -67,7 +67,7 @@ func (t BundlePolicy) String() string { } } -// UnmarshalJSON parses the JSON-encoded data and stores the result +// UnmarshalJSON parses the JSON-encoded data and stores the result. func (t *BundlePolicy) UnmarshalJSON(b []byte) error { var val string if err := json.Unmarshal(b, &val); err != nil { @@ -75,10 +75,11 @@ func (t *BundlePolicy) UnmarshalJSON(b []byte) error { } *t = newBundlePolicy(val) + return nil } -// MarshalJSON returns the JSON encoding +// MarshalJSON returns the JSON encoding. func (t BundlePolicy) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } diff --git a/vendor/github.com/pion/webrtc/v4/certificate.go b/vendor/github.com/pion/webrtc/v4/certificate.go index 36d1fb0796..dfceb9b1ca 100644 --- a/vendor/github.com/pion/webrtc/v4/certificate.go +++ b/vendor/github.com/pion/webrtc/v4/certificate.go @@ -62,28 +62,36 @@ func NewCertificate(key crypto.PrivateKey, tpl x509.Certificate) (*Certificate, return nil, &rtcerr.UnknownError{Err: err} } - return &Certificate{privateKey: key, x509Cert: cert, statsID: fmt.Sprintf("certificate-%d", time.Now().UnixNano())}, nil + return &Certificate{ + privateKey: key, + x509Cert: cert, + statsID: fmt.Sprintf("certificate-%d", time.Now().UnixNano()), + }, nil } // Equals determines if two certificates are identical by comparing both the // secretKeys and x509Certificates. -func (c Certificate) Equals(o Certificate) bool { +func (c Certificate) Equals(cert Certificate) bool { switch cSK := c.privateKey.(type) { case *rsa.PrivateKey: - if oSK, ok := o.privateKey.(*rsa.PrivateKey); ok { + if oSK, ok := cert.privateKey.(*rsa.PrivateKey); ok { if cSK.N.Cmp(oSK.N) != 0 { return false } - return c.x509Cert.Equal(o.x509Cert) + + return c.x509Cert.Equal(cert.x509Cert) } + return false case *ecdsa.PrivateKey: - if oSK, ok := o.privateKey.(*ecdsa.PrivateKey); ok { + if oSK, ok := cert.privateKey.(*ecdsa.PrivateKey); ok { if cSK.X.Cmp(oSK.X) != 0 || cSK.Y.Cmp(oSK.Y) != 0 { return false } - return c.x509Cert.Equal(o.x509Cert) + + return c.x509Cert.Equal(cert.x509Cert) } + return false default: return false @@ -95,6 +103,7 @@ func (c Certificate) Expires() time.Time { if c.x509Cert == nil { return time.Time{} } + return c.x509Cert.NotAfter } @@ -150,7 +159,7 @@ func GenerateCertificate(secretKey crypto.PrivateKey) (*Certificate, error) { // CertificateFromX509 creates a new WebRTC Certificate from a given PrivateKey and Certificate // -// This can be used if you want to share a certificate across multiple PeerConnections +// This can be used if you want to share a certificate across multiple PeerConnections. func CertificateFromX509(privateKey crypto.PrivateKey, certificate *x509.Certificate) Certificate { return Certificate{privateKey, certificate, fmt.Sprintf("certificate-%d", time.Now().UnixNano())} } @@ -176,11 +185,12 @@ func (c Certificate) collectStats(report *statsReportCollector) error { } report.Collect(stats.ID, stats) + return nil } // CertificateFromPEM creates a fresh certificate based on a string containing -// pem blocks fort the private key and x509 certificate +// pem blocks fort the private key and x509 certificate. func CertificateFromPEM(pems string) (*Certificate, error) { // decode & parse the certificate block, more := pem.Decode([]byte(pems)) @@ -206,18 +216,19 @@ func CertificateFromPEM(pems string) (*Certificate, error) { return nil, fmt.Errorf("unable to parse private key: %w", err) } x := CertificateFromX509(privateKey, cert) + return &x, nil } // PEM returns the certificate encoded as two pem block: once for the X509 -// certificate and the other for the private key +// certificate and the other for the private key. func (c Certificate) PEM() (string, error) { // First write the X509 certificate - var o strings.Builder + var builder strings.Builder xcertBytes := make( []byte, base64.StdEncoding.EncodedLen(len(c.x509Cert.Raw))) base64.StdEncoding.Encode(xcertBytes, c.x509Cert.Raw) - err := pem.Encode(&o, &pem.Block{Type: "CERTIFICATE", Bytes: xcertBytes}) + err := pem.Encode(&builder, &pem.Block{Type: "CERTIFICATE", Bytes: xcertBytes}) if err != nil { return "", fmt.Errorf("failed to pem encode the X certificate: %w", err) } @@ -226,9 +237,10 @@ func (c Certificate) PEM() (string, error) { if err != nil { return "", fmt.Errorf("failed to marshal private key: %w", err) } - err = pem.Encode(&o, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) + err = pem.Encode(&builder, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}) if err != nil { return "", fmt.Errorf("failed to encode private key: %w", err) } - return o.String(), nil + + return builder.String(), nil } diff --git a/vendor/github.com/pion/webrtc/v4/configuration_common.go b/vendor/github.com/pion/webrtc/v4/configuration_common.go index a3acdf5b81..4fb22fb85b 100644 --- a/vendor/github.com/pion/webrtc/v4/configuration_common.go +++ b/vendor/github.com/pion/webrtc/v4/configuration_common.go @@ -23,5 +23,6 @@ func (c Configuration) getICEServers() []ICEServer { iceServers[iceServersIndex].URLs[urlsIndex] = rawURL } } + return iceServers } diff --git a/vendor/github.com/pion/webrtc/v4/constants.go b/vendor/github.com/pion/webrtc/v4/constants.go index 5a22e339fd..afcf5bfa95 100644 --- a/vendor/github.com/pion/webrtc/v4/constants.go +++ b/vendor/github.com/pion/webrtc/v4/constants.go @@ -7,16 +7,16 @@ import "github.com/pion/dtls/v3" const ( // default as the standard ethernet MTU - // can be overwritten with SettingEngine.SetReceiveMTU() + // can be overwritten with SettingEngine.SetReceiveMTU(). receiveMTU = 1500 // simulcastProbeCount is the amount of RTP Packets // that handleUndeclaredSSRC will read and try to dispatch from - // mid and rid values + // mid and rid values. simulcastProbeCount = 10 // simulcastMaxProbeRoutines is how many active routines can be used to probe - // If the total amount of incoming SSRCes exceeds this new requests will be ignored + // If the total amount of incoming SSRCes exceeds this new requests will be ignored. simulcastMaxProbeRoutines = 25 mediaSectionApplication = "application" @@ -33,14 +33,21 @@ const ( generatedCertificateOrigin = "WebRTC" - // AttributeRtxPayloadType is the interceptor attribute added when Read() returns an RTX packet containing the RTX stream payload type + // AttributeRtxPayloadType is the interceptor attribute added when Read() + // returns an RTX packet containing the RTX stream payload type. AttributeRtxPayloadType = "rtx_payload_type" - // AttributeRtxSsrc is the interceptor attribute added when Read() returns an RTX packet containing the RTX stream SSRC + // AttributeRtxSsrc is the interceptor attribute added when Read() + // returns an RTX packet containing the RTX stream SSRC. AttributeRtxSsrc = "rtx_ssrc" - // AttributeRtxSequenceNumber is the interceptor attribute added when Read() returns an RTX packet containing the RTX stream sequence number + // AttributeRtxSequenceNumber is the interceptor attribute added when + // Read() returns an RTX packet containing the RTX stream sequence number. AttributeRtxSequenceNumber = "rtx_sequence_number" ) func defaultSrtpProtectionProfiles() []dtls.SRTPProtectionProfile { - return []dtls.SRTPProtectionProfile{dtls.SRTP_AEAD_AES_256_GCM, dtls.SRTP_AEAD_AES_128_GCM, dtls.SRTP_AES128_CM_HMAC_SHA1_80} + return []dtls.SRTPProtectionProfile{ + dtls.SRTP_AEAD_AES_256_GCM, + dtls.SRTP_AEAD_AES_128_GCM, + dtls.SRTP_AES128_CM_HMAC_SHA1_80, + } } diff --git a/vendor/github.com/pion/webrtc/v4/datachannel.go b/vendor/github.com/pion/webrtc/v4/datachannel.go index ea50a031fe..4c3d63f7c6 100644 --- a/vendor/github.com/pion/webrtc/v4/datachannel.go +++ b/vendor/github.com/pion/webrtc/v4/datachannel.go @@ -25,7 +25,7 @@ var errSCTPNotEstablished = errors.New("SCTP not established") // DataChannel represents a WebRTC DataChannel // The DataChannel interface represents a network channel -// which can be used for bidirectional peer-to-peer transfers of arbitrary data +// which can be used for bidirectional peer-to-peer transfers of arbitrary data. type DataChannel struct { mu sync.RWMutex @@ -87,13 +87,17 @@ func (api *API) NewDataChannel(transport *SCTPTransport, params *DataChannelPara // newDataChannel is an internal constructor for the data channel used to // create the DataChannel object before the networking is set up. -func (api *API) newDataChannel(params *DataChannelParameters, sctpTransport *SCTPTransport, log logging.LeveledLogger) (*DataChannel, error) { +func (api *API) newDataChannel( + params *DataChannelParameters, + sctpTransport *SCTPTransport, + log logging.LeveledLogger, +) (*DataChannel, error) { // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #5) if len(params.Label) > 65535 { return nil, &rtcerr.TypeError{Err: ErrStringSizeLimit} } - d := &DataChannel{ + dataChannel := &DataChannel{ sctpTransport: sctpTransport, statsID: fmt.Sprintf("DataChannel-%d", time.Now().UnixNano()), label: params.Label, @@ -107,12 +111,13 @@ func (api *API) newDataChannel(params *DataChannelParameters, sctpTransport *SCT log: log, } - d.setReadyState(DataChannelStateConnecting) - return d, nil + dataChannel.setReadyState(DataChannelStateConnecting) + + return dataChannel, nil } -// open opens the datachannel over the sctp transport -func (d *DataChannel) open(sctpTransport *SCTPTransport) error { +// open opens the datachannel over the sctp transport. +func (d *DataChannel) open(sctpTransport *SCTPTransport) error { //nolint:cyclop association := sctpTransport.association() if association == nil { return errSCTPNotEstablished @@ -121,6 +126,7 @@ func (d *DataChannel) open(sctpTransport *SCTPTransport) error { d.mu.Lock() if d.sctpTransport != nil { // already open d.mu.Unlock() + return nil } d.sctpTransport = sctpTransport @@ -175,6 +181,7 @@ func (d *DataChannel) open(sctpTransport *SCTPTransport) error { dc, err := datachannel.Dial(association, *d.id, cfg) if err != nil { d.mu.Unlock() + return err } @@ -185,6 +192,7 @@ func (d *DataChannel) open(sctpTransport *SCTPTransport) error { d.onDial() d.handleOpen(dc, false, d.negotiated) + return nil } @@ -197,7 +205,7 @@ func (d *DataChannel) Transport() *SCTPTransport { } // After onOpen is complete check that the user called detach -// and provide an error message if the call was missed +// and provide an error message if the call was missed. func (d *DataChannel) checkDetachAfterOpen() { d.mu.RLock() defer d.mu.RUnlock() @@ -229,6 +237,7 @@ func (d *DataChannel) onOpen() { handler := d.onOpenHandler if d.isGracefulClosed { d.mu.RUnlock() + return } d.mu.RUnlock() @@ -242,7 +251,7 @@ func (d *DataChannel) onOpen() { } // OnDial sets an event handler which is invoked when the -// peer has been dialed, but before said peer has responded +// peer has been dialed, but before said peer has responded. func (d *DataChannel) OnDial(f func()) { d.mu.Lock() d.dialHandlerOnce = sync.Once{} @@ -260,6 +269,7 @@ func (d *DataChannel) onDial() { handler := d.onDialHandler if d.isGracefulClosed { d.mu.RUnlock() + return } d.mu.RUnlock() @@ -308,6 +318,7 @@ func (d *DataChannel) onMessage(msg DataChannelMessage) { handler := d.onMessageHandler if d.isGracefulClosed { d.mu.RUnlock() + return } d.mu.RUnlock() @@ -376,6 +387,7 @@ func (d *DataChannel) onError(err error) { handler := d.onErrorHandler if d.isGracefulClosed { d.mu.RUnlock() + return } d.mu.RUnlock() @@ -401,18 +413,19 @@ func (d *DataChannel) readLoop() { d.onError(err) } d.onClose() + return } - m := DataChannelMessage{Data: make([]byte, n), IsString: isString} - copy(m.Data, buffer[:n]) + msg := DataChannelMessage{Data: make([]byte, n), IsString: isString} + copy(msg.Data, buffer[:n]) // NB: Why was DataChannelMessage not passed as a pointer value? - d.onMessage(m) // nolint:staticcheck + d.onMessage(msg) // nolint:staticcheck } } -// Send sends the binary message to the DataChannel peer +// Send sends the binary message to the DataChannel peer. func (d *DataChannel) Send(data []byte) error { err := d.ensureOpen() if err != nil { @@ -420,10 +433,11 @@ func (d *DataChannel) Send(data []byte) error { } _, err = d.dataChannel.WriteDataChannel(data, false) + return err } -// SendText sends the text message to the DataChannel peer +// SendText sends the text message to the DataChannel peer. func (d *DataChannel) SendText(s string) error { err := d.ensureOpen() if err != nil { @@ -431,6 +445,7 @@ func (d *DataChannel) SendText(s string) error { } _, err = d.dataChannel.WriteDataChannel([]byte(s), true) + return err } @@ -440,6 +455,7 @@ func (d *DataChannel) ensureOpen() error { if d.ReadyState() != DataChannelStateOpen { return io.ErrClosedPipe } + return nil } @@ -465,11 +481,13 @@ func (d *DataChannel) DetachWithDeadline() (datachannel.ReadWriteCloserDeadliner if !d.api.settingEngine.detach.DataChannels { d.mu.Unlock() + return nil, errDetachNotEnabled } if d.dataChannel == nil { d.mu.Unlock() + return nil, errDetachBeforeOpened } @@ -616,6 +634,7 @@ func (d *DataChannel) ReadyState() DataChannelState { if v, ok := d.readyState.Load().(DataChannelState); ok { return v } + return DataChannelState(0) } @@ -636,6 +655,7 @@ func (d *DataChannel) BufferedAmount() uint64 { if d.dataChannel == nil { return 0 } + return d.dataChannel.BufferedAmount() } @@ -652,6 +672,7 @@ func (d *DataChannel) BufferedAmountLowThreshold() uint64 { if d.dataChannel == nil { return d.bufferedAmountLowThreshold } + return d.dataChannel.BufferedAmountLowThreshold() } @@ -684,6 +705,7 @@ func (d *DataChannel) OnBufferedAmountLow(f func()) { func (d *DataChannel) getStatsID() string { d.mu.Lock() defer d.mu.Unlock() + return d.statsID } diff --git a/vendor/github.com/pion/webrtc/v4/datachannel_js.go b/vendor/github.com/pion/webrtc/v4/datachannel_js.go index 5e5fc4b0cd..add07b697a 100644 --- a/vendor/github.com/pion/webrtc/v4/datachannel_js.go +++ b/vendor/github.com/pion/webrtc/v4/datachannel_js.go @@ -7,6 +7,7 @@ package webrtc import ( + "errors" "fmt" "syscall/js" @@ -26,13 +27,20 @@ type DataChannel struct { // syscall/js API. Initially nil. onOpenHandler *js.Func onCloseHandler *js.Func + onClosingHandler *js.Func onMessageHandler *js.Func onBufferedAmountLow *js.Func + onErrorHandler *js.Func // A reference to the associated api object used by this datachannel api *API } +// JSValue returns the underlying RTCDataChannel +func (d *DataChannel) JSValue() js.Value { + return d.underlying +} + // OnOpen sets an event handler which is invoked when // the underlying data transport has been established (or re-established). func (d *DataChannel) OnOpen(f func()) { @@ -63,6 +71,39 @@ func (d *DataChannel) OnClose(f func()) { d.underlying.Set("onclose", onCloseHandler) } +// FYI `OnClosing` is not implemented in the non-JS version of Pion. + +func (d *DataChannel) OnClosing(f func()) { + if d.onClosingHandler != nil { + oldHandler := d.onClosingHandler + defer oldHandler.Release() + } + onClosingHandler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + go f() + return js.Undefined() + }) + d.onClosingHandler = &onClosingHandler + d.underlying.Set("onclosing", onClosingHandler) +} + +func (d *DataChannel) OnError(f func(err error)) { + if d.onErrorHandler != nil { + oldHandler := d.onErrorHandler + defer oldHandler.Release() + } + onErrorHandler := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + event := args[0] + errorObj := event.Get("error") + // FYI RTCError has some extra properties, e.g. `errorDetail`: + // https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/error_event + errorMessage := errorObj.Get("message").String() + go f(errors.New(errorMessage)) + return js.Undefined() + }) + d.onErrorHandler = &onErrorHandler + d.underlying.Set("onerror", onErrorHandler) +} + // OnMessage sets an event handler which is invoked on a binary message arrival // from a remote peer. Note that browsers may place limitations on message size. func (d *DataChannel) OnMessage(f func(msg DataChannelMessage)) { @@ -145,12 +186,18 @@ func (d *DataChannel) Close() (err error) { if d.onCloseHandler != nil { d.onCloseHandler.Release() } + if d.onClosingHandler != nil { + d.onClosingHandler.Release() + } if d.onMessageHandler != nil { d.onMessageHandler.Release() } if d.onBufferedAmountLow != nil { d.onBufferedAmountLow.Release() } + if d.onErrorHandler != nil { + d.onErrorHandler.Release() + } return nil } diff --git a/vendor/github.com/pion/webrtc/v4/datachannelstate.go b/vendor/github.com/pion/webrtc/v4/datachannelstate.go index 848d94ca89..ad275c5db9 100644 --- a/vendor/github.com/pion/webrtc/v4/datachannelstate.go +++ b/vendor/github.com/pion/webrtc/v4/datachannelstate.go @@ -7,7 +7,7 @@ package webrtc type DataChannelState int const ( - // DataChannelStateUnknown is the enum's zero-value + // DataChannelStateUnknown is the enum's zero-value. DataChannelStateUnknown DataChannelState = iota // DataChannelStateConnecting indicates that the data channel is being @@ -66,13 +66,14 @@ func (t DataChannelState) String() string { } } -// MarshalText implements encoding.TextMarshaler +// MarshalText implements encoding.TextMarshaler. func (t DataChannelState) MarshalText() ([]byte, error) { return []byte(t.String()), nil } -// UnmarshalText implements encoding.TextUnmarshaler +// UnmarshalText implements encoding.TextUnmarshaler. func (t *DataChannelState) UnmarshalText(b []byte) error { *t = newDataChannelState(string(b)) + return nil } diff --git a/vendor/github.com/pion/webrtc/v4/dtlsrole.go b/vendor/github.com/pion/webrtc/v4/dtlsrole.go index 40a14e8721..94cbac9617 100644 --- a/vendor/github.com/pion/webrtc/v4/dtlsrole.go +++ b/vendor/github.com/pion/webrtc/v4/dtlsrole.go @@ -11,7 +11,7 @@ import ( type DTLSRole byte const ( - // DTLSRoleUnknown is the enum's zero-value + // DTLSRoleUnknown is the enum's zero-value. DTLSRoleUnknown DTLSRole = iota // DTLSRoleAuto defines the DTLS role is determined based on @@ -60,7 +60,7 @@ func (r DTLSRole) String() string { // Iterate a SessionDescription from a remote to determine if an explicit // role can been determined from it. The decision is made from the first role we we parse. -// If no role can be found we return DTLSRoleAuto +// If no role can be found we return DTLSRoleAuto. func dtlsRoleFromRemoteSDP(sessionDescription *sdp.SessionDescription) DTLSRole { if sessionDescription == nil { return DTLSRoleAuto diff --git a/vendor/github.com/pion/webrtc/v4/dtlstransport.go b/vendor/github.com/pion/webrtc/v4/dtlstransport.go index 3e442923b5..e0b575a118 100644 --- a/vendor/github.com/pion/webrtc/v4/dtlstransport.go +++ b/vendor/github.com/pion/webrtc/v4/dtlstransport.go @@ -69,7 +69,7 @@ type simulcastStreamPair struct { // This constructor is part of the ORTC API. It is not // meant to be used together with the basic WebRTC API. func (api *API) NewDTLSTransport(transport *ICETransport, certificates []Certificate) (*DTLSTransport, error) { - t := &DTLSTransport{ + trans := &DTLSTransport{ iceTransport: transport, api: api, state: DTLSTransportStateNew, @@ -84,7 +84,7 @@ func (api *API) NewDTLSTransport(transport *ICETransport, certificates []Certifi if !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) { return nil, &rtcerr.InvalidAccessError{Err: ErrCertificateExpired} } - t.certificates = append(t.certificates, x509Cert) + trans.certificates = append(trans.certificates, x509Cert) } } else { sk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) @@ -95,21 +95,22 @@ func (api *API) NewDTLSTransport(transport *ICETransport, certificates []Certifi if err != nil { return nil, err } - t.certificates = []Certificate{*certificate} + trans.certificates = []Certificate{*certificate} } - return t, nil + return trans, nil } // ICETransport returns the currently-configured *ICETransport or nil -// if one has not been configured +// if one has not been configured. func (t *DTLSTransport) ICETransport() *ICETransport { t.lock.RLock() defer t.lock.RUnlock() + return t.iceTransport } -// onStateChange requires the caller holds the lock +// onStateChange requires the caller holds the lock. func (t *DTLSTransport) onStateChange(state DTLSTransportState) { t.state = state handler := t.onStateChangeHandler @@ -130,6 +131,7 @@ func (t *DTLSTransport) OnStateChange(f func(DTLSTransportState)) { func (t *DTLSTransport) State() DTLSTransportState { t.lock.RLock() defer t.lock.RUnlock() + return t.state } @@ -175,10 +177,11 @@ func (t *DTLSTransport) GetLocalParameters() (DTLSParameters, error) { } // GetRemoteCertificate returns the certificate chain in use by the remote side -// returns an empty list prior to selection of the remote certificate +// returns an empty list prior to selection of the remote certificate. func (t *DTLSTransport) GetRemoteCertificate() []byte { t.lock.RLock() defer t.lock.RUnlock() + return t.remoteCertificate } @@ -243,6 +246,7 @@ func (t *DTLSTransport) startSRTP() error { t.srtpSession.Store(srtpSession) t.srtcpSession.Store(srtcpSession) close(t.srtpReady) + return nil } @@ -285,11 +289,12 @@ func (t *DTLSTransport) role() DTLSRole { if t.iceTransport.Role() == ICERoleControlling { return DTLSRoleServer } + return defaultDtlsRoleAnswer } -// Start DTLS transport negotiation with the parameters of the remote DTLS transport -func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: gocognit +// Start DTLS transport negotiation with the parameters of the remote DTLS transport. +func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint:gocognit,cyclop // Take lock and prepare connection, we must not hold the lock // when connecting prepareTransport := func() (DTLSRole, *dtls.Config, error) { @@ -341,7 +346,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: } if t.api.settingEngine.replayProtection.DTLS != nil { - dtlsConfig.ReplayProtectionWindow = int(*t.api.settingEngine.replayProtection.DTLS) + dtlsConfig.ReplayProtectionWindow = int(*t.api.settingEngine.replayProtection.DTLS) //nolint:gosec // G115 } if t.api.settingEngine.dtls.clientAuth != nil { @@ -382,12 +387,14 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: if err != nil { t.onStateChange(DTLSTransportStateFailed) + return err } srtpProfile, ok := dtlsConn.SelectedSRTPProtectionProfile() if !ok { t.onStateChange(DTLSTransportStateFailed) + return ErrNoSRTPProtectionProfile } @@ -402,6 +409,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: t.srtpProtectionProfile = srtp.ProtectionProfileNullHmacSha1_80 default: t.onStateChange(DTLSTransportStateFailed) + return ErrNoSRTPProtectionProfile } @@ -409,16 +417,18 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: connectionState, ok := dtlsConn.ConnectionState() if !ok { t.onStateChange(DTLSTransportStateFailed) + return errNoRemoteCertificate } if len(connectionState.PeerCertificates) == 0 { t.onStateChange(DTLSTransportStateFailed) + return errNoRemoteCertificate } t.remoteCertificate = connectionState.PeerCertificates[0] - if !t.api.settingEngine.disableCertificateFingerprintVerification { + if !t.api.settingEngine.disableCertificateFingerprintVerification { //nolint:nestif parsedRemoteCert, err := x509.ParseCertificate(t.remoteCertificate) if err != nil { if closeErr := dtlsConn.Close(); closeErr != nil { @@ -426,6 +436,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: } t.onStateChange(DTLSTransportStateFailed) + return err } @@ -435,6 +446,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { //nolint: } t.onStateChange(DTLSTransportStateFailed) + return err } } @@ -473,6 +485,7 @@ func (t *DTLSTransport) Stop() error { } } t.onStateChange(DTLSTransportStateClosed) + return util.FlattenErrs(closeErrs) } @@ -504,14 +517,20 @@ func (t *DTLSTransport) ensureICEConn() error { return nil } -func (t *DTLSTransport) storeSimulcastStream(srtpReadStream *srtp.ReadStreamSRTP, srtcpReadStream *srtp.ReadStreamSRTCP) { +func (t *DTLSTransport) storeSimulcastStream( + srtpReadStream *srtp.ReadStreamSRTP, + srtcpReadStream *srtp.ReadStreamSRTCP, +) { t.lock.Lock() defer t.lock.Unlock() t.simulcastStreams = append(t.simulcastStreams, simulcastStreamPair{srtpReadStream, srtcpReadStream}) } -func (t *DTLSTransport) streamsForSSRC(ssrc SSRC, streamInfo interceptor.StreamInfo) (*srtp.ReadStreamSRTP, interceptor.RTPReader, *srtp.ReadStreamSRTCP, interceptor.RTCPReader, error) { +func (t *DTLSTransport) streamsForSSRC( + ssrc SSRC, + streamInfo interceptor.StreamInfo, +) (*srtp.ReadStreamSRTP, interceptor.RTPReader, *srtp.ReadStreamSRTCP, interceptor.RTCPReader, error) { srtpSession, err := t.getSRTPSession() if err != nil { return nil, nil, nil, nil, err @@ -522,10 +541,16 @@ func (t *DTLSTransport) streamsForSSRC(ssrc SSRC, streamInfo interceptor.StreamI return nil, nil, nil, nil, err } - rtpInterceptor := t.api.interceptor.BindRemoteStream(&streamInfo, interceptor.RTPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { - n, err = rtpReadStream.Read(in) - return n, a, err - })) + rtpInterceptor := t.api.interceptor.BindRemoteStream( + &streamInfo, + interceptor.RTPReaderFunc( + func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { + n, err = rtpReadStream.Read(in) + + return n, a, err + }, + ), + ) srtcpSession, err := t.getSRTCPSession() if err != nil { @@ -537,10 +562,13 @@ func (t *DTLSTransport) streamsForSSRC(ssrc SSRC, streamInfo interceptor.StreamI return nil, nil, nil, nil, err } - rtcpInterceptor := t.api.interceptor.BindRTCPReader(interceptor.RTCPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { - n, err = rtcpReadStream.Read(in) - return n, a, err - })) + rtcpInterceptor := t.api.interceptor.BindRTCPReader(interceptor.RTCPReaderFunc( + func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { + n, err = rtcpReadStream.Read(in) + + return n, a, err + }), + ) return rtpReadStream, rtpInterceptor, rtcpReadStream, rtcpInterceptor, nil } diff --git a/vendor/github.com/pion/webrtc/v4/dtlstransport_js.go b/vendor/github.com/pion/webrtc/v4/dtlstransport_js.go index bc3444e568..846cfb7127 100644 --- a/vendor/github.com/pion/webrtc/v4/dtlstransport_js.go +++ b/vendor/github.com/pion/webrtc/v4/dtlstransport_js.go @@ -17,6 +17,11 @@ type DTLSTransport struct { underlying js.Value } +// JSValue returns the underlying RTCDtlsTransport +func (r *DTLSTransport) JSValue() js.Value { + return r.underlying +} + // ICETransport returns the currently-configured *ICETransport or nil // if one has not been configured func (r *DTLSTransport) ICETransport() *ICETransport { diff --git a/vendor/github.com/pion/webrtc/v4/dtlstransportstate.go b/vendor/github.com/pion/webrtc/v4/dtlstransportstate.go index c938ae2c0f..933e38dca6 100644 --- a/vendor/github.com/pion/webrtc/v4/dtlstransportstate.go +++ b/vendor/github.com/pion/webrtc/v4/dtlstransportstate.go @@ -7,7 +7,7 @@ package webrtc type DTLSTransportState int const ( - // DTLSTransportStateUnknown is the enum's zero-value + // DTLSTransportStateUnknown is the enum's zero-value. DTLSTransportStateUnknown DTLSTransportState = iota // DTLSTransportStateNew indicates that DTLS has not started negotiating @@ -76,13 +76,14 @@ func (t DTLSTransportState) String() string { } } -// MarshalText implements encoding.TextMarshaler +// MarshalText implements encoding.TextMarshaler. func (t DTLSTransportState) MarshalText() ([]byte, error) { return []byte(t.String()), nil } -// UnmarshalText implements encoding.TextUnmarshaler +// UnmarshalText implements encoding.TextUnmarshaler. func (t *DTLSTransportState) UnmarshalText(b []byte) error { *t = newDTLSTransportState(string(b)) + return nil } diff --git a/vendor/github.com/pion/webrtc/v4/errors.go b/vendor/github.com/pion/webrtc/v4/errors.go index 8c460d1444..908f948c6f 100644 --- a/vendor/github.com/pion/webrtc/v4/errors.go +++ b/vendor/github.com/pion/webrtc/v4/errors.go @@ -76,88 +76,100 @@ var ( // and is mutually exclusive. ErrRetransmitsOrPacketLifeTime = errors.New("both MaxPacketLifeTime and MaxRetransmits was set") - // ErrCodecNotFound is returned when a codec search to the Media Engine fails + // ErrCodecNotFound is returned when a codec search to the Media Engine fails. ErrCodecNotFound = errors.New("codec not found") // ErrNoRemoteDescription indicates that an operation was rejected because - // the remote description is not set + // the remote description is not set. ErrNoRemoteDescription = errors.New("remote description is not set") // ErrIncorrectSDPSemantics indicates that the PeerConnection was configured to - // generate SDP Answers with different SDP Semantics than the received Offer + // generate SDP Answers with different SDP Semantics than the received Offer. ErrIncorrectSDPSemantics = errors.New("remote SessionDescription semantics does not match configuration") - // ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct + // ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct. ErrIncorrectSignalingState = errors.New("operation can not be run in current signaling state") // ErrProtocolTooLarge indicates that value given for a DataChannelInit protocol is - // longer then 65535 bytes + // longer then 65535 bytes. ErrProtocolTooLarge = errors.New("protocol is larger then 65535 bytes") // ErrSenderNotCreatedByConnection indicates RemoveTrack was called with a RtpSender not created - // by this PeerConnection + // by this PeerConnection. ErrSenderNotCreatedByConnection = errors.New("RtpSender not created by this PeerConnection") // ErrSessionDescriptionNoFingerprint indicates SetRemoteDescription was called with a SessionDescription that has no - // fingerprint + // fingerprint. ErrSessionDescriptionNoFingerprint = errors.New("SetRemoteDescription called with no fingerprint") // ErrSessionDescriptionInvalidFingerprint indicates SetRemoteDescription was called with a SessionDescription that - // has an invalid fingerprint + // has an invalid fingerprint. ErrSessionDescriptionInvalidFingerprint = errors.New("SetRemoteDescription called with an invalid fingerprint") - // ErrSessionDescriptionConflictingFingerprints indicates SetRemoteDescription was called with a SessionDescription that - // has an conflicting fingerprints - ErrSessionDescriptionConflictingFingerprints = errors.New("SetRemoteDescription called with multiple conflicting fingerprint") + // ErrSessionDescriptionConflictingFingerprints indicates SetRemoteDescription was called with a SessionDescription + // that has an conflicting fingerprints. + ErrSessionDescriptionConflictingFingerprints = errors.New( + "SetRemoteDescription called with multiple conflicting fingerprint", + ) // ErrSessionDescriptionMissingIceUfrag indicates SetRemoteDescription was called with a SessionDescription that - // is missing an ice-ufrag value + // is missing an ice-ufrag value. ErrSessionDescriptionMissingIceUfrag = errors.New("SetRemoteDescription called with no ice-ufrag") // ErrSessionDescriptionMissingIcePwd indicates SetRemoteDescription was called with a SessionDescription that - // is missing an ice-pwd value + // is missing an ice-pwd value. ErrSessionDescriptionMissingIcePwd = errors.New("SetRemoteDescription called with no ice-pwd") - // ErrSessionDescriptionConflictingIceUfrag indicates SetRemoteDescription was called with a SessionDescription that - // contains multiple conflicting ice-ufrag values - ErrSessionDescriptionConflictingIceUfrag = errors.New("SetRemoteDescription called with multiple conflicting ice-ufrag values") + // ErrSessionDescriptionConflictingIceUfrag indicates SetRemoteDescription was called with a SessionDescription + // that contains multiple conflicting ice-ufrag values. + ErrSessionDescriptionConflictingIceUfrag = errors.New( + "SetRemoteDescription called with multiple conflicting ice-ufrag values", + ) - // ErrSessionDescriptionConflictingIcePwd indicates SetRemoteDescription was called with a SessionDescription that - // contains multiple conflicting ice-pwd values - ErrSessionDescriptionConflictingIcePwd = errors.New("SetRemoteDescription called with multiple conflicting ice-pwd values") + // ErrSessionDescriptionConflictingIcePwd indicates SetRemoteDescription was called with a SessionDescription + // that contains multiple conflicting ice-pwd values. + ErrSessionDescriptionConflictingIcePwd = errors.New( + "SetRemoteDescription called with multiple conflicting ice-pwd values", + ) - // ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen + // ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen. ErrNoSRTPProtectionProfile = errors.New("DTLS Handshake completed and no SRTP Protection Profile was chosen") - // ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint used for comparing certificates + // ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint + // used for comparing certificates. ErrFailedToGenerateCertificateFingerprint = errors.New("failed to generate certificate fingerprint") - // ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available + // ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available. ErrNoCodecsAvailable = errors.New("operation failed no codecs are available") - // ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec + // ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec. ErrUnsupportedCodec = errors.New("unable to start track, codec is not supported by remote") - // ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine needs at - // least one configured codec. + // ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine + // needs at least one configured codec. ErrSenderWithNoCodecs = errors.New("unable to populate media section, RTPSender created with no codecs") - // ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original + // ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original. ErrRTPSenderNewTrackHasIncorrectKind = errors.New("new track must be of the same kind as previous") - // ErrRTPSenderNewTrackHasIncorrectEnvelope indicates that the new track has a different envelope than the previous/original + // ErrRTPSenderNewTrackHasIncorrectEnvelope indicates that the new track has a different envelope + // than the previous/original. ErrRTPSenderNewTrackHasIncorrectEnvelope = errors.New("new track must have the same envelope as previous") - // ErrUnbindFailed indicates that a TrackLocal was not able to be unbind + // ErrUnbindFailed indicates that a TrackLocal was not able to be unbind. ErrUnbindFailed = errors.New("failed to unbind TrackLocal from PeerConnection") - // ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader + // ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader. ErrNoPayloaderForCodec = errors.New("the requested codec does not have a payloader") - // ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was registered with a direction besides `sendonly` or `recvonly` - ErrRegisterHeaderExtensionInvalidDirection = errors.New("a header extension must be registered as 'recvonly', 'sendonly' or both") + // ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was + // registered with a direction besides `sendonly` or `recvonly`. + ErrRegisterHeaderExtensionInvalidDirection = errors.New( + "a header extension must be registered as 'recvonly', 'sendonly' or both", + ) - // ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight and the requested SSRC was ignored + // ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight + // and the requested SSRC was ignored. ErrSimulcastProbeOverflow = errors.New("simulcast probe limit has been reached, new SSRC has been discarded") errDetachNotEnabled = errors.New("enable detaching by calling webrtc.DetachDataChannels()") @@ -173,35 +185,49 @@ var ( errICEConnectionNotStarted = errors.New("ICE connection not started") errICECandidateTypeUnknown = errors.New("unknown candidate type") - errICEInvalidConvertCandidateType = errors.New("cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type") - errICEAgentNotExist = errors.New("ICEAgent does not exist") - errICECandiatesCoversionFailed = errors.New("unable to convert ICE candidates to ICECandidates") - errICERoleUnknown = errors.New("unknown ICE Role") - errICEProtocolUnknown = errors.New("unknown protocol") - errICEGathererNotStarted = errors.New("gatherer not started") + errICEInvalidConvertCandidateType = errors.New( + "cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type", + ) + errICEAgentNotExist = errors.New("ICEAgent does not exist") + errICECandiatesCoversionFailed = errors.New("unable to convert ICE candidates to ICECandidates") + errICERoleUnknown = errors.New("unknown ICE Role") + errICEProtocolUnknown = errors.New("unknown protocol") + errICEGathererNotStarted = errors.New("gatherer not started") errNetworkTypeUnknown = errors.New("unknown network type") - errSDPDoesNotMatchOffer = errors.New("new sdp does not match previous offer") - errSDPDoesNotMatchAnswer = errors.New("new sdp does not match previous answer") - errPeerConnSDPTypeInvalidValue = errors.New("provided value is not a valid enum value of type SDPType") + errSDPDoesNotMatchOffer = errors.New("new sdp does not match previous offer") + errSDPDoesNotMatchAnswer = errors.New("new sdp does not match previous answer") + errPeerConnSDPTypeInvalidValue = errors.New( + "provided value is not a valid enum value of type SDPType", + ) errPeerConnStateChangeInvalid = errors.New("invalid state change op") errPeerConnStateChangeUnhandled = errors.New("unhandled state change op") errPeerConnSDPTypeInvalidValueSetLocalDescription = errors.New("invalid SDP type supplied to SetLocalDescription()") - errPeerConnRemoteDescriptionWithoutMidValue = errors.New("remoteDescription contained media section without mid value") - errPeerConnRemoteDescriptionNil = errors.New("remoteDescription has not been set yet") - errPeerConnSingleMediaSectionHasExplicitSSRC = errors.New("single media section has an explicit SSRC") - errPeerConnRemoteSSRCAddTransceiver = errors.New("could not add transceiver for remote SSRC") - errPeerConnSimulcastMidRTPExtensionRequired = errors.New("mid RTP Extensions required for Simulcast") - errPeerConnSimulcastStreamIDRTPExtensionRequired = errors.New("stream id RTP Extensions required for Simulcast") - errPeerConnSimulcastIncomingSSRCFailed = errors.New("incoming SSRC failed Simulcast probing") - errPeerConnAddTransceiverFromKindOnlyAcceptsOne = errors.New("AddTransceiverFromKind only accepts one RTPTransceiverInit") - errPeerConnAddTransceiverFromTrackOnlyAcceptsOne = errors.New("AddTransceiverFromTrack only accepts one RTPTransceiverInit") - errPeerConnAddTransceiverFromKindSupport = errors.New("AddTransceiverFromKind currently only supports recvonly") - errPeerConnAddTransceiverFromTrackSupport = errors.New("AddTransceiverFromTrack currently only supports sendonly and sendrecv") - errPeerConnSetIdentityProviderNotImplemented = errors.New("TODO SetIdentityProvider") - errPeerConnWriteRTCPOpenWriteStream = errors.New("WriteRTCP failed to open WriteStream") - errPeerConnTranscieverMidNil = errors.New("cannot find transceiver with mid") + errPeerConnRemoteDescriptionWithoutMidValue = errors.New( + "remoteDescription contained media section without mid value", + ) + errPeerConnRemoteDescriptionNil = errors.New("remoteDescription has not been set yet") + errPeerConnSingleMediaSectionHasExplicitSSRC = errors.New("single media section has an explicit SSRC") + errPeerConnRemoteSSRCAddTransceiver = errors.New("could not add transceiver for remote SSRC") + errPeerConnSimulcastMidRTPExtensionRequired = errors.New("mid RTP Extensions required for Simulcast") + errPeerConnSimulcastStreamIDRTPExtensionRequired = errors.New("stream id RTP Extensions required for Simulcast") + errPeerConnSimulcastIncomingSSRCFailed = errors.New("incoming SSRC failed Simulcast probing") + errPeerConnAddTransceiverFromKindOnlyAcceptsOne = errors.New( + "AddTransceiverFromKind only accepts one RTPTransceiverInit", + ) + errPeerConnAddTransceiverFromTrackOnlyAcceptsOne = errors.New( + "AddTransceiverFromTrack only accepts one RTPTransceiverInit", + ) + errPeerConnAddTransceiverFromKindSupport = errors.New( + "AddTransceiverFromKind currently only supports recvonly", + ) + errPeerConnAddTransceiverFromTrackSupport = errors.New( + "AddTransceiverFromTrack currently only supports sendonly and sendrecv", + ) + errPeerConnSetIdentityProviderNotImplemented = errors.New("TODO SetIdentityProvider") + errPeerConnWriteRTCPOpenWriteStream = errors.New("WriteRTCP failed to open WriteStream") + errPeerConnTranscieverMidNil = errors.New("cannot find transceiver with mid") errRTPReceiverDTLSTransportNil = errors.New("DTLSTransport must not be nil") errRTPReceiverReceiveAlreadyCalled = errors.New("Receive has already been called") @@ -227,14 +253,18 @@ var ( errSDPZeroTransceivers = errors.New("addTransceiverSDP() called with 0 transceivers") errSDPMediaSectionMediaDataChanInvalid = errors.New("invalid Media Section. Media + DataChannel both enabled") - errSDPMediaSectionMultipleTrackInvalid = errors.New("invalid Media Section. Can not have multiple tracks in one MediaSection in UnifiedPlan") + errSDPMediaSectionMultipleTrackInvalid = errors.New( + "invalid Media Section. Can not have multiple tracks in one MediaSection in UnifiedPlan", + ) errSettingEngineSetAnsweringDTLSRole = errors.New("SetAnsweringDTLSRole must DTLSRoleClient or DTLSRoleServer") errSignalingStateCannotRollback = errors.New("can't rollback from stable state") errSignalingStateProposedTransitionInvalid = errors.New("invalid proposed signaling state transition") - errStatsICECandidateStateInvalid = errors.New("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state") + errStatsICECandidateStateInvalid = errors.New( + "cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state", + ) errInvalidICECredentialTypeString = errors.New("invalid ICECredentialType") errInvalidICEServer = errors.New("invalid ICEServer") diff --git a/vendor/github.com/pion/webrtc/v4/gathering_complete_promise.go b/vendor/github.com/pion/webrtc/v4/gathering_complete_promise.go index 12d3170d68..d51a99363e 100644 --- a/vendor/github.com/pion/webrtc/v4/gathering_complete_promise.go +++ b/vendor/github.com/pion/webrtc/v4/gathering_complete_promise.go @@ -7,10 +7,12 @@ import ( "context" ) -// GatheringCompletePromise is a Pion specific helper function that returns a channel that is closed when gathering is complete. +// GatheringCompletePromise is a Pion specific helper function that returns a channel that is closed +// when gathering is complete. // This function may be helpful in cases where you are unable to trickle your ICE Candidates. // -// It is better to not use this function, and instead trickle candidates. If you use this function you will see longer connection startup times. +// It is better to not use this function, and instead trickle candidates. +// If you use this function you will see longer connection startup times. // When the call is connected you will see no impact however. func GatheringCompletePromise(pc *PeerConnection) (gatherComplete <-chan struct{}) { gatheringComplete, done := context.WithCancel(context.Background()) diff --git a/vendor/github.com/pion/webrtc/v4/icecandidate.go b/vendor/github.com/pion/webrtc/v4/icecandidate.go index 7080272575..fb40f33db3 100644 --- a/vendor/github.com/pion/webrtc/v4/icecandidate.go +++ b/vendor/github.com/pion/webrtc/v4/icecandidate.go @@ -9,7 +9,7 @@ import ( "github.com/pion/ice/v4" ) -// ICECandidate represents a ice candidate +// ICECandidate represents a ice candidate. type ICECandidate struct { statsID string Foundation string `json:"foundation"` @@ -24,11 +24,15 @@ type ICECandidate struct { TCPType string `json:"tcpType"` SDPMid string `json:"sdpMid"` SDPMLineIndex uint16 `json:"sdpMLineIndex"` + extensions string } -// Conversion for package ice - -func newICECandidatesFromICE(iceCandidates []ice.Candidate, sdpMid string, sdpMLineIndex uint16) ([]ICECandidate, error) { +// Conversion for package ice. +func newICECandidatesFromICE( + iceCandidates []ice.Candidate, + sdpMid string, + sdpMLineIndex uint16, +) ([]ICECandidate, error) { candidates := []ICECandidate{} for _, i := range iceCandidates { @@ -42,39 +46,41 @@ func newICECandidatesFromICE(iceCandidates []ice.Candidate, sdpMid string, sdpML return candidates, nil } -func newICECandidateFromICE(i ice.Candidate, sdpMid string, sdpMLineIndex uint16) (ICECandidate, error) { - typ, err := convertTypeFromICE(i.Type()) +func newICECandidateFromICE(candidate ice.Candidate, sdpMid string, sdpMLineIndex uint16) (ICECandidate, error) { + typ, err := convertTypeFromICE(candidate.Type()) if err != nil { return ICECandidate{}, err } - protocol, err := NewICEProtocol(i.NetworkType().NetworkShort()) + protocol, err := NewICEProtocol(candidate.NetworkType().NetworkShort()) if err != nil { return ICECandidate{}, err } - c := ICECandidate{ - statsID: i.ID(), - Foundation: i.Foundation(), - Priority: i.Priority(), - Address: i.Address(), + newCandidate := ICECandidate{ + statsID: candidate.ID(), + Foundation: candidate.Foundation(), + Priority: candidate.Priority(), + Address: candidate.Address(), Protocol: protocol, - Port: uint16(i.Port()), - Component: i.Component(), + Port: uint16(candidate.Port()), //nolint:gosec // G115 + Component: candidate.Component(), Typ: typ, - TCPType: i.TCPType().String(), + TCPType: candidate.TCPType().String(), SDPMid: sdpMid, SDPMLineIndex: sdpMLineIndex, } - if i.RelatedAddress() != nil { - c.RelatedAddress = i.RelatedAddress().Address - c.RelatedPort = uint16(i.RelatedAddress().Port) + newCandidate.setExtensions(candidate.Extensions()) + + if candidate.RelatedAddress() != nil { + newCandidate.RelatedAddress = candidate.RelatedAddress().Address + newCandidate.RelatedPort = uint16(candidate.RelatedAddress().Port) //nolint:gosec // G115 } - return c, nil + return newCandidate, nil } -func (c ICECandidate) toICE() (ice.Candidate, error) { +func (c ICECandidate) toICE() (cand ice.Candidate, err error) { candidateID := c.statsID switch c.Typ { case ICECandidateTypeHost: @@ -88,7 +94,8 @@ func (c ICECandidate) toICE() (ice.Candidate, error) { Foundation: c.Foundation, Priority: c.Priority, } - return ice.NewCandidateHost(&config) + + cand, err = ice.NewCandidateHost(&config) case ICECandidateTypeSrflx: config := ice.CandidateServerReflexiveConfig{ CandidateID: candidateID, @@ -101,7 +108,8 @@ func (c ICECandidate) toICE() (ice.Candidate, error) { RelAddr: c.RelatedAddress, RelPort: int(c.RelatedPort), } - return ice.NewCandidateServerReflexive(&config) + + cand, err = ice.NewCandidateServerReflexive(&config) case ICECandidateTypePrflx: config := ice.CandidatePeerReflexiveConfig{ CandidateID: candidateID, @@ -114,7 +122,8 @@ func (c ICECandidate) toICE() (ice.Candidate, error) { RelAddr: c.RelatedAddress, RelPort: int(c.RelatedPort), } - return ice.NewCandidatePeerReflexive(&config) + + cand, err = ice.NewCandidatePeerReflexive(&config) case ICECandidateTypeRelay: config := ice.CandidateRelayConfig{ CandidateID: candidateID, @@ -127,10 +136,68 @@ func (c ICECandidate) toICE() (ice.Candidate, error) { RelAddr: c.RelatedAddress, RelPort: int(c.RelatedPort), } - return ice.NewCandidateRelay(&config) + + cand, err = ice.NewCandidateRelay(&config) default: return nil, fmt.Errorf("%w: %s", errICECandidateTypeUnknown, c.Typ) } + + if cand != nil && err == nil { + err = c.exportExtensions(cand) + } + + return cand, err +} + +func (c *ICECandidate) setExtensions(ext []ice.CandidateExtension) { + var extensions string + + for i := range ext { + if i > 0 { + extensions += " " + } + + extensions += ext[i].Key + " " + ext[i].Value + } + + c.extensions = extensions +} + +func (c *ICECandidate) exportExtensions(cand ice.Candidate) error { + extensions := c.extensions + var ext ice.CandidateExtension + var field string + + for i, start := 0, 0; i < len(extensions); i++ { + switch { + case extensions[i] == ' ': + field = extensions[start:i] + start = i + 1 + case i == len(extensions)-1: + field = extensions[start:] + default: + continue + } + + // Extension keys can't be empty + hasKey := ext.Key != "" + if !hasKey { + ext.Key = field + } else { + ext.Value = field + } + + // Extension value can be empty + if hasKey || i == len(extensions)-1 { + if err := cand.AddExtension(ext); err != nil { + return err + } + + ext = ice.CandidateExtension{} + } + } + + return nil } func convertTypeFromICE(t ice.CandidateType) (ICECandidateType, error) { @@ -153,6 +220,7 @@ func (c ICECandidate) String() string { if err != nil { return fmt.Sprintf("%#v failed to convert to ICE: %s", c, err) } + return ic.String() } diff --git a/vendor/github.com/pion/webrtc/v4/icecandidateinit.go b/vendor/github.com/pion/webrtc/v4/icecandidateinit.go index 30ad93c0bb..bd9df800d4 100644 --- a/vendor/github.com/pion/webrtc/v4/icecandidateinit.go +++ b/vendor/github.com/pion/webrtc/v4/icecandidateinit.go @@ -3,7 +3,7 @@ package webrtc -// ICECandidateInit is used to serialize ice candidates +// ICECandidateInit is used to serialize ice candidates. type ICECandidateInit struct { Candidate string `json:"candidate"` SDPMid *string `json:"sdpMid"` diff --git a/vendor/github.com/pion/webrtc/v4/icecandidatepair.go b/vendor/github.com/pion/webrtc/v4/icecandidatepair.go index b87884bce4..2ae2efe54e 100644 --- a/vendor/github.com/pion/webrtc/v4/icecandidatepair.go +++ b/vendor/github.com/pion/webrtc/v4/icecandidatepair.go @@ -5,7 +5,7 @@ package webrtc import "fmt" -// ICECandidatePair represents an ICE Candidate pair +// ICECandidatePair represents an ICE Candidate pair. type ICECandidatePair struct { statsID string Local *ICECandidate @@ -21,9 +21,10 @@ func (p *ICECandidatePair) String() string { } // NewICECandidatePair returns an initialized *ICECandidatePair -// for the given pair of ICECandidate instances +// for the given pair of ICECandidate instances. func NewICECandidatePair(local, remote *ICECandidate) *ICECandidatePair { statsID := newICECandidatePairStatsID(local.statsID, remote.statsID) + return &ICECandidatePair{ statsID: statsID, Local: local, diff --git a/vendor/github.com/pion/webrtc/v4/icecandidatetype.go b/vendor/github.com/pion/webrtc/v4/icecandidatetype.go index 27d7a1422f..7ac62db119 100644 --- a/vendor/github.com/pion/webrtc/v4/icecandidatetype.go +++ b/vendor/github.com/pion/webrtc/v4/icecandidatetype.go @@ -13,7 +13,7 @@ import ( type ICECandidateType int const ( - // ICECandidateTypeUnknown is the enum's zero-value + // ICECandidateTypeUnknown is the enum's zero-value. ICECandidateTypeUnknown ICECandidateType = iota // ICECandidateTypeHost indicates that the candidate is of Host type as @@ -51,7 +51,7 @@ const ( iceCandidateTypeRelayStr = "relay" ) -// NewICECandidateType takes a string and converts it into ICECandidateType +// NewICECandidateType takes a string and converts it into ICECandidateType. func NewICECandidateType(raw string) (ICECandidateType, error) { switch raw { case iceCandidateTypeHostStr: @@ -95,6 +95,7 @@ func getCandidateType(candidateType ice.CandidateType) (ICECandidateType, error) default: // NOTE: this should never happen[tm] err := fmt.Errorf("%w: %s", errICEInvalidConvertCandidateType, candidateType.String()) + return ICECandidateTypeUnknown, err } } @@ -108,5 +109,6 @@ func (t ICECandidateType) MarshalText() ([]byte, error) { func (t *ICECandidateType) UnmarshalText(b []byte) error { var err error *t, err = NewICECandidateType(string(b)) + return err } diff --git a/vendor/github.com/pion/webrtc/v4/icecomponent.go b/vendor/github.com/pion/webrtc/v4/icecomponent.go index ae8f230fbf..ea13f98591 100644 --- a/vendor/github.com/pion/webrtc/v4/icecomponent.go +++ b/vendor/github.com/pion/webrtc/v4/icecomponent.go @@ -8,7 +8,7 @@ package webrtc type ICEComponent int const ( - // ICEComponentUnknown is the enum's zero-value + // ICEComponentUnknown is the enum's zero-value. ICEComponentUnknown ICEComponent = iota // ICEComponentRTP indicates that the ICE Transport is used for RTP (or diff --git a/vendor/github.com/pion/webrtc/v4/iceconnectionstate.go b/vendor/github.com/pion/webrtc/v4/iceconnectionstate.go index 4b7deb802f..488b882ab8 100644 --- a/vendor/github.com/pion/webrtc/v4/iceconnectionstate.go +++ b/vendor/github.com/pion/webrtc/v4/iceconnectionstate.go @@ -7,7 +7,7 @@ package webrtc type ICEConnectionState int const ( - // ICEConnectionStateUnknown is the enum's zero-value + // ICEConnectionStateUnknown is the enum's zero-value. ICEConnectionStateUnknown ICEConnectionState = iota // ICEConnectionStateNew indicates that any of the ICETransports are @@ -56,7 +56,7 @@ const ( iceConnectionStateClosedStr = "closed" ) -// NewICEConnectionState takes a string and converts it to ICEConnectionState +// NewICEConnectionState takes a string and converts it to ICEConnectionState. func NewICEConnectionState(raw string) ICEConnectionState { switch raw { case iceConnectionStateNewStr: diff --git a/vendor/github.com/pion/webrtc/v4/icecredentialtype.go b/vendor/github.com/pion/webrtc/v4/icecredentialtype.go index 5d704a9bd9..ae30d1d66b 100644 --- a/vendor/github.com/pion/webrtc/v4/icecredentialtype.go +++ b/vendor/github.com/pion/webrtc/v4/icecredentialtype.go @@ -50,7 +50,7 @@ func (t ICECredentialType) String() string { } } -// UnmarshalJSON parses the JSON-encoded data and stores the result +// UnmarshalJSON parses the JSON-encoded data and stores the result. func (t *ICECredentialType) UnmarshalJSON(b []byte) error { var val string if err := json.Unmarshal(b, &val); err != nil { @@ -63,10 +63,11 @@ func (t *ICECredentialType) UnmarshalJSON(b []byte) error { } *t = tmp + return nil } -// MarshalJSON returns the JSON encoding +// MarshalJSON returns the JSON encoding. func (t ICECredentialType) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } diff --git a/vendor/github.com/pion/webrtc/v4/icegatherer.go b/vendor/github.com/pion/webrtc/v4/icegatherer.go index 9cb4acac46..d1a6df6d2d 100644 --- a/vendor/github.com/pion/webrtc/v4/icegatherer.go +++ b/vendor/github.com/pion/webrtc/v4/icegatherer.go @@ -70,7 +70,7 @@ func (api *API) NewICEGatherer(opts ICEGatherOptions) (*ICEGatherer, error) { }, nil } -func (g *ICEGatherer) createAgent() error { +func (g *ICEGatherer) createAgent() error { //nolint:cyclop g.lock.Lock() defer g.lock.Unlock() @@ -149,11 +149,12 @@ func (g *ICEGatherer) createAgent() error { } g.agent = agent + return nil } // Gather ICE candidates. -func (g *ICEGatherer) Gather() error { +func (g *ICEGatherer) Gather() error { //nolint:cyclop if err := g.createAgent(); err != nil { return err } @@ -182,12 +183,13 @@ func (g *ICEGatherer) Gather() error { sdpMid = mid } - sdpMLineIndex := uint16(g.sdpMLineIndex.Load()) + sdpMLineIndex := uint16(g.sdpMLineIndex.Load()) //nolint:gosec // G115 if candidate != nil { c, err := newICECandidateFromICE(candidate, sdpMid, sdpMLineIndex) if err != nil { g.log.Warnf("Failed to convert ice.Candidate: %s", err) + return } onLocalCandidateHandler(&c) @@ -200,10 +202,11 @@ func (g *ICEGatherer) Gather() error { }); err != nil { return err } + return agent.GatherCandidates() } -// set media stream identification tag and media description index for this gatherer +// set media stream identification tag and media description index for this gatherer. func (g *ICEGatherer) setMediaStreamIdentification(mid string, mLineIndex uint16) { g.sdpMid.Store(mid) g.sdpMLineIndex.Store(uint32(mLineIndex)) @@ -290,7 +293,7 @@ func (g *ICEGatherer) GetLocalCandidates() ([]ICECandidate, error) { sdpMid = mid } - sdpMLineIndex := uint16(g.sdpMLineIndex.Load()) + sdpMLineIndex := uint16(g.sdpMLineIndex.Load()) //nolint:gosec // G115 return newICECandidatesFromICE(iceCandidates, sdpMid, sdpMLineIndex) } @@ -301,7 +304,7 @@ func (g *ICEGatherer) OnLocalCandidate(f func(*ICECandidate)) { g.onLocalCandidateHandler.Store(f) } -// OnStateChange fires any time the ICEGatherer changes +// OnStateChange fires any time the ICEGatherer changes. func (g *ICEGatherer) OnStateChange(f func(ICEGathererState)) { g.onStateChangeHandler.Store(f) } @@ -322,6 +325,7 @@ func (g *ICEGatherer) setState(s ICEGathererState) { func (g *ICEGatherer) getAgent() *ice.Agent { g.lock.RLock() defer g.lock.RUnlock() + return g.agent } @@ -339,6 +343,7 @@ func (g *ICEGatherer) collectStats(collector *statsReportCollector) { stats, err := toICECandidatePairStats(candidatePairStats) if err != nil { g.log.Error(err.Error()) + continue } @@ -363,10 +368,10 @@ func (g *ICEGatherer) collectStats(collector *statsReportCollector) { ID: candidateStats.ID, Type: StatsTypeLocalCandidate, IP: candidateStats.IP, - Port: int32(candidateStats.Port), + Port: int32(candidateStats.Port), //nolint:gosec // G115, no overflow, port Protocol: networkType.Protocol(), CandidateType: candidateType, - Priority: int32(candidateStats.Priority), + Priority: int32(candidateStats.Priority), //nolint:gosec URL: candidateStats.URL, RelayProtocol: candidateStats.RelayProtocol, Deleted: candidateStats.Deleted, @@ -391,10 +396,10 @@ func (g *ICEGatherer) collectStats(collector *statsReportCollector) { ID: candidateStats.ID, Type: StatsTypeRemoteCandidate, IP: candidateStats.IP, - Port: int32(candidateStats.Port), + Port: int32(candidateStats.Port), //nolint:gosec // G115, no overflow, port Protocol: networkType.Protocol(), CandidateType: candidateType, - Priority: int32(candidateStats.Priority), + Priority: int32(candidateStats.Priority), //nolint:gosec // G115 URL: candidateStats.URL, RelayProtocol: candidateStats.RelayProtocol, } @@ -418,6 +423,7 @@ func (g *ICEGatherer) getSelectedCandidatePairStats() (ICECandidatePairStats, bo stats, err := toICECandidatePairStats(selectedCandidatePairStats) if err != nil { g.log.Error(err.Error()) + return ICECandidatePairStats{}, false } diff --git a/vendor/github.com/pion/webrtc/v4/icegathererstate.go b/vendor/github.com/pion/webrtc/v4/icegathererstate.go index b78df5fc5f..26966dd8ae 100644 --- a/vendor/github.com/pion/webrtc/v4/icegathererstate.go +++ b/vendor/github.com/pion/webrtc/v4/icegathererstate.go @@ -11,7 +11,7 @@ import ( type ICEGathererState uint32 const ( - // ICEGathererStateUnknown is the enum's zero-value + // ICEGathererStateUnknown is the enum's zero-value. ICEGathererStateUnknown ICEGathererState = iota // ICEGathererStateNew indicates object has been created but diff --git a/vendor/github.com/pion/webrtc/v4/icegatheringstate.go b/vendor/github.com/pion/webrtc/v4/icegatheringstate.go index 13ea2f73d4..2878277b12 100644 --- a/vendor/github.com/pion/webrtc/v4/icegatheringstate.go +++ b/vendor/github.com/pion/webrtc/v4/icegatheringstate.go @@ -7,7 +7,7 @@ package webrtc type ICEGatheringState int const ( - // ICEGatheringStateUnknown is the enum's zero-value + // ICEGatheringStateUnknown is the enum's zero-value. ICEGatheringStateUnknown ICEGatheringState = iota // ICEGatheringStateNew indicates that any of the ICETransports are @@ -31,7 +31,7 @@ const ( iceGatheringStateCompleteStr = "complete" ) -// NewICEGatheringState takes a string and converts it to ICEGatheringState +// NewICEGatheringState takes a string and converts it to ICEGatheringState. func NewICEGatheringState(raw string) ICEGatheringState { switch raw { case iceGatheringStateNewStr: diff --git a/vendor/github.com/pion/webrtc/v4/iceprotocol.go b/vendor/github.com/pion/webrtc/v4/iceprotocol.go index 67254f7d2f..8362e93d4b 100644 --- a/vendor/github.com/pion/webrtc/v4/iceprotocol.go +++ b/vendor/github.com/pion/webrtc/v4/iceprotocol.go @@ -13,7 +13,7 @@ import ( type ICEProtocol int const ( - // ICEProtocolUnknown is the enum's zero-value + // ICEProtocolUnknown is the enum's zero-value. ICEProtocolUnknown ICEProtocol = iota // ICEProtocolUDP indicates the URL uses a UDP transport. @@ -29,7 +29,7 @@ const ( iceProtocolTCPStr = "tcp" ) -// NewICEProtocol takes a string and converts it to ICEProtocol +// NewICEProtocol takes a string and converts it to ICEProtocol. func NewICEProtocol(raw string) (ICEProtocol, error) { switch { case strings.EqualFold(iceProtocolUDPStr, raw): diff --git a/vendor/github.com/pion/webrtc/v4/icerole.go b/vendor/github.com/pion/webrtc/v4/icerole.go index dce6336e9f..59ac9af54b 100644 --- a/vendor/github.com/pion/webrtc/v4/icerole.go +++ b/vendor/github.com/pion/webrtc/v4/icerole.go @@ -8,7 +8,7 @@ package webrtc type ICERole int const ( - // ICERoleUnknown is the enum's zero-value + // ICERoleUnknown is the enum's zero-value. ICERoleUnknown ICERole = iota // ICERoleControlling indicates that the ICE agent that is responsible @@ -50,13 +50,14 @@ func (t ICERole) String() string { } } -// MarshalText implements encoding.TextMarshaler +// MarshalText implements encoding.TextMarshaler. func (t ICERole) MarshalText() ([]byte, error) { return []byte(t.String()), nil } -// UnmarshalText implements encoding.TextUnmarshaler +// UnmarshalText implements encoding.TextUnmarshaler. func (t *ICERole) UnmarshalText(b []byte) error { *t = newICERole(string(b)) + return nil } diff --git a/vendor/github.com/pion/webrtc/v4/iceserver.go b/vendor/github.com/pion/webrtc/v4/iceserver.go index a28e727eb4..32a3685410 100644 --- a/vendor/github.com/pion/webrtc/v4/iceserver.go +++ b/vendor/github.com/pion/webrtc/v4/iceserver.go @@ -28,10 +28,11 @@ func (s ICEServer) parseURL(i int) (*stun.URI, error) { func (s ICEServer) validate() error { _, err := s.urls() + return err } -func (s ICEServer) urls() ([]*stun.URI, error) { +func (s ICEServer) urls() ([]*stun.URI, error) { //nolint:cyclop urls := []*stun.URI{} for i := range s.URLs { @@ -85,6 +86,7 @@ func iceserverUnmarshalUrls(val interface{}) (*[]string, error) { return nil, errInvalidICEServer } } + return &out, nil } @@ -101,14 +103,15 @@ func iceserverUnmarshalOauth(val interface{}) (*OAuthCredential, error) { if !ok { return nil, errInvalidICEServer } + return &OAuthCredential{ MACKey: MACKey, AccessToken: AccessToken, }, nil } -func (s *ICEServer) iceserverUnmarshalFields(m map[string]interface{}) error { - if val, ok := m["urls"]; ok { +func (s *ICEServer) iceserverUnmarshalFields(fields map[string]interface{}) error { //nolint:cyclop + if val, ok := fields["urls"]; ok { u, err := iceserverUnmarshalUrls(val) if err != nil { return err @@ -118,13 +121,13 @@ func (s *ICEServer) iceserverUnmarshalFields(m map[string]interface{}) error { s.URLs = []string{} } - if val, ok := m["username"]; ok { + if val, ok := fields["username"]; ok { s.Username, ok = val.(string) if !ok { return errInvalidICEServer } } - if val, ok := m["credentialType"]; ok { + if val, ok := fields["credentialType"]; ok { ct, ok := val.(string) if !ok { return errInvalidICEServer @@ -137,7 +140,7 @@ func (s *ICEServer) iceserverUnmarshalFields(m map[string]interface{}) error { } else { s.CredentialType = ICECredentialTypePassword } - if val, ok := m["credential"]; ok { + if val, ok := fields["credential"]; ok { switch s.CredentialType { case ICECredentialTypePassword: s.Credential = val @@ -151,10 +154,11 @@ func (s *ICEServer) iceserverUnmarshalFields(m map[string]interface{}) error { return errInvalidICECredentialTypeString } } + return nil } -// UnmarshalJSON parses the JSON-encoded data and stores the result +// UnmarshalJSON parses the JSON-encoded data and stores the result. func (s *ICEServer) UnmarshalJSON(b []byte) error { var tmp interface{} err := json.Unmarshal(b, &tmp) @@ -164,10 +168,11 @@ func (s *ICEServer) UnmarshalJSON(b []byte) error { if m, ok := tmp.(map[string]interface{}); ok { return s.iceserverUnmarshalFields(m) } + return errInvalidICEServer } -// MarshalJSON returns the JSON encoding +// MarshalJSON returns the JSON encoding. func (s ICEServer) MarshalJSON() ([]byte, error) { m := make(map[string]interface{}) m["urls"] = s.URLs @@ -178,5 +183,6 @@ func (s ICEServer) MarshalJSON() ([]byte, error) { m["credential"] = s.Credential } m["credentialType"] = s.CredentialType + return json.Marshal(m) } diff --git a/vendor/github.com/pion/webrtc/v4/icetransport.go b/vendor/github.com/pion/webrtc/v4/icetransport.go index a78f8b76a6..e060349768 100644 --- a/vendor/github.com/pion/webrtc/v4/icetransport.go +++ b/vendor/github.com/pion/webrtc/v4/icetransport.go @@ -36,7 +36,6 @@ type ICETransport struct { conn *ice.Conn mux *mux.Mux - ctx context.Context ctxCancel func() loggerFactory logging.LoggerFactory @@ -45,7 +44,7 @@ type ICETransport struct { } // GetSelectedCandidatePair returns the selected candidate pair on which packets are sent -// if there is no selected pair nil is returned +// if there is no selected pair nil is returned. func (t *ICETransport) GetSelectedCandidatePair() (*ICECandidatePair, error) { agent := t.gatherer.getAgent() if agent == nil { @@ -71,7 +70,7 @@ func (t *ICETransport) GetSelectedCandidatePair() (*ICECandidatePair, error) { } // GetSelectedCandidatePairStats returns the selected candidate pair stats on which packets are sent -// if there is no selected pair empty stats, false is returned to indicate stats not available +// if there is no selected pair empty stats, false is returned to indicate stats not available. func (t *ICETransport) GetSelectedCandidatePairStats() (ICECandidatePairStats, bool) { return t.gatherer.getSelectedCandidatePairStats() } @@ -84,11 +83,12 @@ func NewICETransport(gatherer *ICEGatherer, loggerFactory logging.LoggerFactory) log: loggerFactory.NewLogger("ortc"), } iceTransport.setState(ICETransportStateNew) + return iceTransport } // Start incoming connectivity checks based on its configured role. -func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role *ICERole) error { +func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role *ICERole) error { //nolint:cyclop t.lock.Lock() defer t.lock.Unlock() @@ -121,6 +121,7 @@ func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role * candidates, err := newICECandidatesFromICE([]ice.Candidate{local, remote}, "", 0) if err != nil { t.log.Warnf("%w: %s", errICECandiatesCoversionFailed, err) + return } t.onSelectedCandidatePairChange(NewICECandidatePair(&candidates[0], &candidates[1])) @@ -134,7 +135,8 @@ func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role * } t.role = *role - t.ctx, t.ctxCancel = context.WithCancel(context.Background()) + ctx, ctxCancel := context.WithCancel(context.Background()) + t.ctxCancel = ctxCancel // Drop the lock here to allow ICE candidates to be // added so that the agent can complete a connection @@ -144,12 +146,12 @@ func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role * var err error switch *role { case ICERoleControlling: - iceConn, err = agent.Dial(t.ctx, + iceConn, err = agent.Dial(ctx, params.UsernameFragment, params.Password) case ICERoleControlled: - iceConn, err = agent.Accept(t.ctx, + iceConn, err = agent.Accept(ctx, params.UsernameFragment, params.Password) @@ -171,7 +173,7 @@ func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role * config := mux.Config{ Conn: t.conn, - BufferSize: int(t.gatherer.api.settingEngine.getReceiveMTU()), + BufferSize: int(t.gatherer.api.settingEngine.getReceiveMTU()), //nolint:gosec // G115 LoggerFactory: t.loggerFactory, } t.mux = mux.NewMux(config) @@ -180,7 +182,7 @@ func (t *ICETransport) Start(gatherer *ICEGatherer, params ICEParameters, role * } // restart is not exposed currently because ORTC has users create a whole new ICETransport -// so for now lets keep it private so we don't cause ORTC users to depend on non-standard APIs +// so for now lets keep it private so we don't cause ORTC users to depend on non-standard APIs. func (t *ICETransport) restart() error { t.lock.Lock() defer t.lock.Unlock() @@ -190,9 +192,13 @@ func (t *ICETransport) restart() error { return fmt.Errorf("%w: unable to restart ICETransport", errICEAgentNotExist) } - if err := agent.Restart(t.gatherer.api.settingEngine.candidates.UsernameFragment, t.gatherer.api.settingEngine.candidates.Password); err != nil { + if err := agent.Restart( + t.gatherer.api.settingEngine.candidates.UsernameFragment, + t.gatherer.api.settingEngine.candidates.Password, + ); err != nil { return err } + return t.gatherer.Gather() } @@ -229,18 +235,21 @@ func (t *ICETransport) stop(shouldGracefullyClose bool) error { closeErrs = append(closeErrs, gatherer.GracefulClose()) } closeErrs = append(closeErrs, mux.Close()) + return util.FlattenErrs(closeErrs) } else if gatherer != nil { if shouldGracefullyClose { return gatherer.GracefulClose() } + return gatherer.Close() } + return nil } // OnSelectedCandidatePairChange sets a handler that is invoked when a new -// ICE candidate pair is selected +// ICE candidate pair is selected. func (t *ICETransport) OnSelectedCandidatePairChange(f func(*ICECandidatePair)) { t.onSelectedCandidatePairChangeHandler.Store(f) } @@ -308,8 +317,8 @@ func (t *ICETransport) AddRemoteCandidate(remoteCandidate *ICECandidate) error { defer t.lock.RUnlock() var ( - c ice.Candidate - err error + candidate ice.Candidate + err error ) if err = t.ensureGatherer(); err != nil { @@ -317,7 +326,7 @@ func (t *ICETransport) AddRemoteCandidate(remoteCandidate *ICECandidate) error { } if remoteCandidate != nil { - if c, err = remoteCandidate.toICE(); err != nil { + if candidate, err = remoteCandidate.toICE(); err != nil { return err } } @@ -327,7 +336,7 @@ func (t *ICETransport) AddRemoteCandidate(remoteCandidate *ICECandidate) error { return fmt.Errorf("%w: unable to add remote candidates", errICEAgentNotExist) } - return agent.AddRemoteCandidate(c) + return agent.AddRemoteCandidate(candidate) } // State returns the current ice transport state. @@ -335,6 +344,7 @@ func (t *ICETransport) State() ICETransportState { if v, ok := t.state.Load().(ICETransportState); ok { return v } + return ICETransportState(0) } @@ -355,6 +365,7 @@ func (t *ICETransport) setState(i ICETransportState) { func (t *ICETransport) newEndpoint(f mux.MatchFunc) *mux.Endpoint { t.lock.Lock() defer t.lock.Unlock() + return t.mux.NewEndpoint(f) } diff --git a/vendor/github.com/pion/webrtc/v4/icetransport_js.go b/vendor/github.com/pion/webrtc/v4/icetransport_js.go index 3ca577b10a..29c69ad7a4 100644 --- a/vendor/github.com/pion/webrtc/v4/icetransport_js.go +++ b/vendor/github.com/pion/webrtc/v4/icetransport_js.go @@ -15,6 +15,11 @@ type ICETransport struct { underlying js.Value } +// JSValue returns the underlying RTCIceTransport +func (t *ICETransport) JSValue() js.Value { + return t.underlying +} + // GetSelectedCandidatePair returns the selected candidate pair on which packets are sent // if there is no selected pair nil is returned func (t *ICETransport) GetSelectedCandidatePair() (*ICECandidatePair, error) { diff --git a/vendor/github.com/pion/webrtc/v4/icetransportpolicy.go b/vendor/github.com/pion/webrtc/v4/icetransportpolicy.go index d9a41637a0..39a1fa364a 100644 --- a/vendor/github.com/pion/webrtc/v4/icetransportpolicy.go +++ b/vendor/github.com/pion/webrtc/v4/icetransportpolicy.go @@ -11,7 +11,7 @@ import ( // permitted candidates. Only these candidates are used for connectivity checks. type ICETransportPolicy int -// ICEGatherPolicy is the ORTC equivalent of ICETransportPolicy +// ICEGatherPolicy is the ORTC equivalent of ICETransportPolicy. type ICEGatherPolicy = ICETransportPolicy const ( @@ -29,7 +29,7 @@ const ( iceTransportPolicyAllStr = "all" ) -// NewICETransportPolicy takes a string and converts it to ICETransportPolicy +// NewICETransportPolicy takes a string and converts it to ICETransportPolicy. func NewICETransportPolicy(raw string) ICETransportPolicy { switch raw { case iceTransportPolicyRelayStr: @@ -50,17 +50,18 @@ func (t ICETransportPolicy) String() string { } } -// UnmarshalJSON parses the JSON-encoded data and stores the result +// UnmarshalJSON parses the JSON-encoded data and stores the result. func (t *ICETransportPolicy) UnmarshalJSON(b []byte) error { var val string if err := json.Unmarshal(b, &val); err != nil { return err } *t = NewICETransportPolicy(val) + return nil } -// MarshalJSON returns the JSON encoding +// MarshalJSON returns the JSON encoding. func (t ICETransportPolicy) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } diff --git a/vendor/github.com/pion/webrtc/v4/icetransportstate.go b/vendor/github.com/pion/webrtc/v4/icetransportstate.go index 645c5c7746..714d5fe61d 100644 --- a/vendor/github.com/pion/webrtc/v4/icetransportstate.go +++ b/vendor/github.com/pion/webrtc/v4/icetransportstate.go @@ -9,7 +9,7 @@ import "github.com/pion/ice/v4" type ICETransportState int const ( - // ICETransportStateUnknown is the enum's zero-value + // ICETransportStateUnknown is the enum's zero-value. ICETransportStateUnknown ICETransportState = iota // ICETransportStateNew indicates the ICETransport is waiting @@ -143,13 +143,14 @@ func (c ICETransportState) toICE() ice.ConnectionState { } } -// MarshalText implements encoding.TextMarshaler +// MarshalText implements encoding.TextMarshaler. func (c ICETransportState) MarshalText() ([]byte, error) { return []byte(c.String()), nil } -// UnmarshalText implements encoding.TextUnmarshaler +// UnmarshalText implements encoding.TextUnmarshaler. func (c *ICETransportState) UnmarshalText(b []byte) error { *c = newICETransportState(string(b)) + return nil } diff --git a/vendor/github.com/pion/webrtc/v4/interceptor.go b/vendor/github.com/pion/webrtc/v4/interceptor.go index b9e7f40d7a..d2df622f96 100644 --- a/vendor/github.com/pion/webrtc/v4/interceptor.go +++ b/vendor/github.com/pion/webrtc/v4/interceptor.go @@ -37,7 +37,7 @@ func RegisterDefaultInterceptors(mediaEngine *MediaEngine, interceptorRegistry * return ConfigureTWCCSender(mediaEngine, interceptorRegistry) } -// ConfigureRTCPReports will setup everything necessary for generating Sender and Receiver Reports +// ConfigureRTCPReports will setup everything necessary for generating Sender and Receiver Reports. func ConfigureRTCPReports(interceptorRegistry *interceptor.Registry) error { reciver, err := report.NewReceiverInterceptor() if err != nil { @@ -51,6 +51,7 @@ func ConfigureRTCPReports(interceptorRegistry *interceptor.Registry) error { interceptorRegistry.Add(reciver) interceptorRegistry.Add(sender) + return nil } @@ -70,17 +71,22 @@ func ConfigureNack(mediaEngine *MediaEngine, interceptorRegistry *interceptor.Re mediaEngine.RegisterFeedback(RTCPFeedback{Type: "nack", Parameter: "pli"}, RTPCodecTypeVideo) interceptorRegistry.Add(responder) interceptorRegistry.Add(generator) + return nil } // ConfigureTWCCHeaderExtensionSender will setup everything necessary for adding // a TWCC header extension to outgoing RTP packets. This will allow the remote peer to generate TWCC reports. func ConfigureTWCCHeaderExtensionSender(mediaEngine *MediaEngine, interceptorRegistry *interceptor.Registry) error { - if err := mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeVideo); err != nil { + if err := mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeVideo, + ); err != nil { return err } - if err := mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeAudio); err != nil { + if err := mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeAudio, + ); err != nil { return err } @@ -90,6 +96,7 @@ func ConfigureTWCCHeaderExtensionSender(mediaEngine *MediaEngine, interceptorReg } interceptorRegistry.Add(i) + return nil } @@ -97,12 +104,16 @@ func ConfigureTWCCHeaderExtensionSender(mediaEngine *MediaEngine, interceptorReg // This must be called after registering codecs with the MediaEngine. func ConfigureTWCCSender(mediaEngine *MediaEngine, interceptorRegistry *interceptor.Registry) error { mediaEngine.RegisterFeedback(RTCPFeedback{Type: TypeRTCPFBTransportCC}, RTPCodecTypeVideo) - if err := mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeVideo); err != nil { + if err := mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeVideo, + ); err != nil { return err } mediaEngine.RegisterFeedback(RTCPFeedback{Type: TypeRTCPFBTransportCC}, RTPCodecTypeAudio) - if err := mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeAudio); err != nil { + if err := mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.TransportCCURI}, RTPCodecTypeAudio, + ); err != nil { return err } @@ -112,6 +123,7 @@ func ConfigureTWCCSender(mediaEngine *MediaEngine, interceptorRegistry *intercep } interceptorRegistry.Add(generator) + return nil } @@ -125,20 +137,27 @@ func ConfigureCongestionControlFeedback(mediaEngine *MediaEngine, interceptorReg return err } interceptorRegistry.Add(generator) + return nil } -// ConfigureSimulcastExtensionHeaders enables the RTP Extension Headers needed for Simulcast +// ConfigureSimulcastExtensionHeaders enables the RTP Extension Headers needed for Simulcast. func ConfigureSimulcastExtensionHeaders(mediaEngine *MediaEngine) error { - if err := mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.SDESMidURI}, RTPCodecTypeVideo); err != nil { + if err := mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.SDESMidURI}, RTPCodecTypeVideo, + ); err != nil { return err } - if err := mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.SDESRTPStreamIDURI}, RTPCodecTypeVideo); err != nil { + if err := mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.SDESRTPStreamIDURI}, RTPCodecTypeVideo, + ); err != nil { return err } - return mediaEngine.RegisterHeaderExtension(RTPHeaderExtensionCapability{URI: sdp.SDESRepairRTPStreamIDURI}, RTPCodecTypeVideo) + return mediaEngine.RegisterHeaderExtension( + RTPHeaderExtensionCapability{URI: sdp.SDESRepairRTPStreamIDURI}, RTPCodecTypeVideo, + ) } type interceptorToTrackLocalWriter struct{ interceptor atomic.Value } // interceptor.RTPWriter } @@ -160,8 +179,14 @@ func (i *interceptorToTrackLocalWriter) Write(b []byte) (int, error) { return i.WriteRTP(&packet.Header, packet.Payload) } -// nolint: unparam -func createStreamInfo(id string, ssrc, ssrcRTX, ssrcFEC SSRC, payloadType, payloadTypeRTX, payloadTypeFEC PayloadType, codec RTPCodecCapability, webrtcHeaderExtensions []RTPHeaderExtensionParameter) *interceptor.StreamInfo { +//nolint:unparam +func createStreamInfo( + id string, + ssrc, ssrcRTX, ssrcFEC SSRC, + payloadType, payloadTypeRTX, payloadTypeFEC PayloadType, + codec RTPCodecCapability, + webrtcHeaderExtensions []RTPHeaderExtensionParameter, +) *interceptor.StreamInfo { headerExtensions := make([]interceptor.RTPHeaderExtension, 0, len(webrtcHeaderExtensions)) for _, h := range webrtcHeaderExtensions { headerExtensions = append(headerExtensions, interceptor.RTPHeaderExtension{ID: h.ID, URI: h.URI}) diff --git a/vendor/github.com/pion/webrtc/v4/internal/fmtp/av1.go b/vendor/github.com/pion/webrtc/v4/internal/fmtp/av1.go index 29eccd114d..d7eab4d297 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/fmtp/av1.go +++ b/vendor/github.com/pion/webrtc/v4/internal/fmtp/av1.go @@ -37,5 +37,6 @@ func (h *av1FMTP) Match(b FMTP) bool { func (h *av1FMTP) Parameter(key string) (string, bool) { v, ok := h.parameters[key] + return v, ok } diff --git a/vendor/github.com/pion/webrtc/v4/internal/fmtp/fmtp.go b/vendor/github.com/pion/webrtc/v4/internal/fmtp/fmtp.go index f515a648d0..95a3243dea 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/fmtp/fmtp.go +++ b/vendor/github.com/pion/webrtc/v4/internal/fmtp/fmtp.go @@ -25,7 +25,7 @@ func parseParameters(line string) map[string]string { } // FMTP interface for implementing custom -// FMTP parsers based on MimeType +// FMTP parsers based on MimeType. type FMTP interface { // MimeType returns the MimeType associated with // the fmtp @@ -38,36 +38,36 @@ type FMTP interface { Parameter(key string) (string, bool) } -// Parse parses an fmtp string based on the MimeType +// Parse parses an fmtp string based on the MimeType. func Parse(mimeType, line string) FMTP { - var f FMTP + var fmtp FMTP parameters := parseParameters(line) switch { case strings.EqualFold(mimeType, "video/h264"): - f = &h264FMTP{ + fmtp = &h264FMTP{ parameters: parameters, } case strings.EqualFold(mimeType, "video/vp9"): - f = &vp9FMTP{ + fmtp = &vp9FMTP{ parameters: parameters, } case strings.EqualFold(mimeType, "video/av1"): - f = &av1FMTP{ + fmtp = &av1FMTP{ parameters: parameters, } default: - f = &genericFMTP{ + fmtp = &genericFMTP{ mimeType: mimeType, parameters: parameters, } } - return f + return fmtp } type genericFMTP struct { @@ -80,24 +80,24 @@ func (g *genericFMTP) MimeType() string { } // Match returns true if g and b are compatible fmtp descriptions -// The generic implementation is used for MimeTypes that are not defined +// The generic implementation is used for MimeTypes that are not defined. func (g *genericFMTP) Match(b FMTP) bool { - c, ok := b.(*genericFMTP) + fmtp, ok := b.(*genericFMTP) if !ok { return false } - if !strings.EqualFold(g.mimeType, c.MimeType()) { + if !strings.EqualFold(g.mimeType, fmtp.MimeType()) { return false } for k, v := range g.parameters { - if vb, ok := c.parameters[k]; ok && !strings.EqualFold(vb, v) { + if vb, ok := fmtp.parameters[k]; ok && !strings.EqualFold(vb, v) { return false } } - for k, v := range c.parameters { + for k, v := range fmtp.parameters { if va, ok := g.parameters[k]; ok && !strings.EqualFold(va, v) { return false } @@ -108,5 +108,6 @@ func (g *genericFMTP) Match(b FMTP) bool { func (g *genericFMTP) Parameter(key string) (string, bool) { v, ok := g.parameters[key] + return v, ok } diff --git a/vendor/github.com/pion/webrtc/v4/internal/fmtp/h264.go b/vendor/github.com/pion/webrtc/v4/internal/fmtp/h264.go index b89b97aa22..0fdaea5591 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/fmtp/h264.go +++ b/vendor/github.com/pion/webrtc/v4/internal/fmtp/h264.go @@ -16,6 +16,7 @@ func profileLevelIDMatches(a, b string) bool { if err != nil || len(bb) < 2 { return false } + return aa[0] == bb[0] && aa[1] == bb[1] } @@ -41,7 +42,7 @@ func (h *h264FMTP) MimeType() string { // apply for the level part of profile-level-id and does not apply // for the other stream properties and capability parameters. func (h *h264FMTP) Match(b FMTP) bool { - c, ok := b.(*h264FMTP) + fmtp, ok := b.(*h264FMTP) if !ok { return false } @@ -51,7 +52,7 @@ func (h *h264FMTP) Match(b FMTP) bool { if !hok { return false } - cpmode, cok := c.parameters["packetization-mode"] + cpmode, cok := fmtp.parameters["packetization-mode"] if !cok { return false } @@ -66,7 +67,7 @@ func (h *h264FMTP) Match(b FMTP) bool { return false } - cplid, cok := c.parameters["profile-level-id"] + cplid, cok := fmtp.parameters["profile-level-id"] if !cok { return false } @@ -80,5 +81,6 @@ func (h *h264FMTP) Match(b FMTP) bool { func (h *h264FMTP) Parameter(key string) (string, bool) { v, ok := h.parameters[key] + return v, ok } diff --git a/vendor/github.com/pion/webrtc/v4/internal/fmtp/vp9.go b/vendor/github.com/pion/webrtc/v4/internal/fmtp/vp9.go index 7fc618bccd..bbbd7f29ae 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/fmtp/vp9.go +++ b/vendor/github.com/pion/webrtc/v4/internal/fmtp/vp9.go @@ -37,5 +37,6 @@ func (h *vp9FMTP) Match(b FMTP) bool { func (h *vp9FMTP) Parameter(key string) (string, bool) { v, ok := h.parameters[key] + return v, ok } diff --git a/vendor/github.com/pion/webrtc/v4/internal/mux/endpoint.go b/vendor/github.com/pion/webrtc/v4/internal/mux/endpoint.go index 2a3d03571f..d1a24c0b67 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/mux/endpoint.go +++ b/vendor/github.com/pion/webrtc/v4/internal/mux/endpoint.go @@ -20,7 +20,7 @@ type Endpoint struct { onClose func() } -// Close unregisters the endpoint from the Mux +// Close unregisters the endpoint from the Mux. func (e *Endpoint) Close() (err error) { if e.onClose != nil { e.onClose() @@ -31,6 +31,7 @@ func (e *Endpoint) Close() (err error) { } e.mux.RemoveEndpoint(e) + return nil } @@ -39,19 +40,20 @@ func (e *Endpoint) close() error { } // Read reads a packet of len(p) bytes from the underlying conn -// that are matched by the associated MuxFunc +// that are matched by the associated MuxFunc. func (e *Endpoint) Read(p []byte) (int, error) { return e.buffer.Read(p) } // ReadFrom reads a packet of len(p) bytes from the underlying conn -// that are matched by the associated MuxFunc +// that are matched by the associated MuxFunc. func (e *Endpoint) ReadFrom(p []byte) (int, net.Addr, error) { i, err := e.Read(p) + return i, nil, err } -// Write writes len(p) bytes to the underlying conn +// Write writes len(p) bytes to the underlying conn. func (e *Endpoint) Write(p []byte) (int, error) { n, err := e.mux.nextConn.Write(p) if errors.Is(err, ice.ErrNoCandidatePairs) { @@ -63,38 +65,38 @@ func (e *Endpoint) Write(p []byte) (int, error) { return n, err } -// WriteTo writes len(p) bytes to the underlying conn +// WriteTo writes len(p) bytes to the underlying conn. func (e *Endpoint) WriteTo(p []byte, _ net.Addr) (int, error) { return e.Write(p) } -// LocalAddr is a stub +// LocalAddr is a stub. func (e *Endpoint) LocalAddr() net.Addr { return e.mux.nextConn.LocalAddr() } -// RemoteAddr is a stub +// RemoteAddr is a stub. func (e *Endpoint) RemoteAddr() net.Addr { return e.mux.nextConn.RemoteAddr() } -// SetDeadline is a stub +// SetDeadline is a stub. func (e *Endpoint) SetDeadline(time.Time) error { return nil } -// SetReadDeadline is a stub +// SetReadDeadline is a stub. func (e *Endpoint) SetReadDeadline(time.Time) error { return nil } -// SetWriteDeadline is a stub +// SetWriteDeadline is a stub. func (e *Endpoint) SetWriteDeadline(time.Time) error { return nil } // SetOnClose is a user set callback that -// will be executed when `Close` is called +// will be executed when `Close` is called. func (e *Endpoint) SetOnClose(onClose func()) { e.onClose = onClose } diff --git a/vendor/github.com/pion/webrtc/v4/internal/mux/mux.go b/vendor/github.com/pion/webrtc/v4/internal/mux/mux.go index 02e3acae93..942476897e 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/mux/mux.go +++ b/vendor/github.com/pion/webrtc/v4/internal/mux/mux.go @@ -19,19 +19,19 @@ const ( // The maximum amount of data that can be buffered before returning errors. maxBufferSize = 1000 * 1000 // 1MB - // How many total pending packets can be cached + // How many total pending packets can be cached. maxPendingPackets = 15 ) // Config collects the arguments to mux.Mux construction into -// a single structure +// a single structure. type Config struct { Conn net.Conn BufferSize int LoggerFactory logging.LoggerFactory } -// Mux allows multiplexing +// Mux allows multiplexing. type Mux struct { nextConn net.Conn bufferSize int @@ -45,9 +45,9 @@ type Mux struct { log logging.LeveledLogger } -// NewMux creates a new Mux +// NewMux creates a new Mux. func NewMux(config Config) *Mux { - m := &Mux{ + mux := &Mux{ nextConn: config.Conn, endpoints: make(map[*Endpoint]MatchFunc), bufferSize: config.BufferSize, @@ -55,31 +55,31 @@ func NewMux(config Config) *Mux { log: config.LoggerFactory.NewLogger("mux"), } - go m.readLoop() + go mux.readLoop() - return m + return mux } -// NewEndpoint creates a new Endpoint -func (m *Mux) NewEndpoint(f MatchFunc) *Endpoint { - e := &Endpoint{ +// NewEndpoint creates a new Endpoint. +func (m *Mux) NewEndpoint(matchFunc MatchFunc) *Endpoint { + endpoint := &Endpoint{ mux: m, buffer: packetio.NewBuffer(), } // Set a maximum size of the buffer in bytes. - e.buffer.SetLimitSize(maxBufferSize) + endpoint.buffer.SetLimitSize(maxBufferSize) m.lock.Lock() - m.endpoints[e] = f + m.endpoints[endpoint] = matchFunc m.lock.Unlock() - go m.handlePendingPackets(e, f) + go m.handlePendingPackets(endpoint, matchFunc) - return e + return endpoint } -// RemoveEndpoint removes an endpoint from the Mux +// RemoveEndpoint removes an endpoint from the Mux. func (m *Mux) RemoveEndpoint(e *Endpoint) { m.lock.Lock() defer m.lock.Unlock() @@ -92,6 +92,7 @@ func (m *Mux) Close() error { for e := range m.endpoints { if err := e.close(); err != nil { m.lock.Unlock() + return err } @@ -124,9 +125,11 @@ func (m *Mux) readLoop() { return case errors.Is(err, io.ErrShortBuffer), errors.Is(err, packetio.ErrTimeout): m.log.Errorf("mux: failed to read from packetio.Buffer %s", err.Error()) + continue case err != nil: m.log.Errorf("mux: ending readLoop packetio.Buffer error %s", err.Error()) + return } @@ -136,6 +139,7 @@ func (m *Mux) readLoop() { return } m.log.Errorf("mux: ending readLoop dispatch error %s", err.Error()) + return } } @@ -144,6 +148,7 @@ func (m *Mux) readLoop() { func (m *Mux) dispatch(buf []byte) error { if len(buf) == 0 { m.log.Warnf("Warning: mux: unable to dispatch zero length packet") + return nil } @@ -153,6 +158,7 @@ func (m *Mux) dispatch(buf []byte) error { for e, f := range m.endpoints { if f(buf) { endpoint = e + break } } @@ -161,12 +167,21 @@ func (m *Mux) dispatch(buf []byte) error { if !m.isClosed { if len(m.pendingPackets) >= maxPendingPackets { - m.log.Warnf("Warning: mux: no endpoint for packet starting with %d, not adding to queue size(%d)", buf[0], len(m.pendingPackets)) + m.log.Warnf( + "Warning: mux: no endpoint for packet starting with %d, not adding to queue size(%d)", + buf[0], //nolint:gosec // G602, false positive? + len(m.pendingPackets), + ) } else { - m.log.Warnf("Warning: mux: no endpoint for packet starting with %d, adding to queue size(%d)", buf[0], len(m.pendingPackets)) + m.log.Warnf( + "Warning: mux: no endpoint for packet starting with %d, adding to queue size(%d)", + buf[0], //nolint:gosec // G602, false positive? + len(m.pendingPackets), + ) m.pendingPackets = append(m.pendingPackets, append([]byte{}, buf...)) } } + return nil } @@ -176,6 +191,7 @@ func (m *Mux) dispatch(buf []byte) error { // Expected when bytes are received faster than the endpoint can process them (#2152, #2180) if errors.Is(err, packetio.ErrFull) { m.log.Infof("mux: endpoint buffer is full, dropping packet") + return nil } @@ -193,7 +209,7 @@ func (m *Mux) handlePendingPackets(endpoint *Endpoint, matchFunc MatchFunc) { m.log.Warnf("Warning: mux: error writing packet to endpoint from pending queue: %s", err) } } else { - pendingPackets = append(pendingPackets, buf) + pendingPackets = append(pendingPackets, buf) //nolint:makezero // todo fix } } m.pendingPackets = pendingPackets diff --git a/vendor/github.com/pion/webrtc/v4/internal/mux/muxfunc.go b/vendor/github.com/pion/webrtc/v4/internal/mux/muxfunc.go index 69c3d14cdf..3f3e42928c 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/mux/muxfunc.go +++ b/vendor/github.com/pion/webrtc/v4/internal/mux/muxfunc.go @@ -3,20 +3,21 @@ package mux -// MatchFunc allows custom logic for mapping packets to an Endpoint +// MatchFunc allows custom logic for mapping packets to an Endpoint. type MatchFunc func([]byte) bool -// MatchAll always returns true +// MatchAll always returns true. func MatchAll([]byte) bool { return true } -// MatchRange returns true if the first byte of buf is in [lower..upper] +// MatchRange returns true if the first byte of buf is in [lower..upper]. func MatchRange(lower, upper byte, buf []byte) bool { if len(buf) < 1 { return false } b := buf[0] + return b >= lower && b <= upper } @@ -35,13 +36,13 @@ func MatchRange(lower, upper byte, buf []byte) bool { // +----------------+ // MatchDTLS is a MatchFunc that accepts packets with the first byte in [20..63] -// as defied in RFC7983 +// as defied in RFC7983. func MatchDTLS(b []byte) bool { return MatchRange(20, 63, b) } // MatchSRTPOrSRTCP is a MatchFunc that accepts packets with the first byte in [128..191] -// as defied in RFC7983 +// as defied in RFC7983. func MatchSRTPOrSRTCP(b []byte) bool { return MatchRange(128, 191, b) } @@ -51,15 +52,16 @@ func isRTCP(buf []byte) bool { if len(buf) < 4 { return false } + return buf[1] >= 192 && buf[1] <= 223 } -// MatchSRTP is a MatchFunc that only matches SRTP and not SRTCP +// MatchSRTP is a MatchFunc that only matches SRTP and not SRTCP. func MatchSRTP(buf []byte) bool { return MatchSRTPOrSRTCP(buf) && !isRTCP(buf) } -// MatchSRTCP is a MatchFunc that only matches SRTCP and not SRTP +// MatchSRTCP is a MatchFunc that only matches SRTCP and not SRTP. func MatchSRTCP(buf []byte) bool { return MatchSRTPOrSRTCP(buf) && isRTCP(buf) } diff --git a/vendor/github.com/pion/webrtc/v4/internal/util/util.go b/vendor/github.com/pion/webrtc/v4/internal/util/util.go index 966a6230a6..46703ef4d7 100644 --- a/vendor/github.com/pion/webrtc/v4/internal/util/util.go +++ b/vendor/github.com/pion/webrtc/v4/internal/util/util.go @@ -28,7 +28,7 @@ func RandUint32() uint32 { return globalMathRandomGenerator.Uint32() } -// FlattenErrs flattens multiple errors into one +// FlattenErrs flattens multiple errors into one. func FlattenErrs(errs []error) error { errs2 := []error{} for _, e := range errs { @@ -39,6 +39,7 @@ func FlattenErrs(errs []error) error { if len(errs2) == 0 { return nil } + return multiError(errs2) } @@ -71,5 +72,6 @@ func (me multiError) Is(err error) bool { } } } + return false } diff --git a/vendor/github.com/pion/webrtc/v4/mediaengine.go b/vendor/github.com/pion/webrtc/v4/mediaengine.go index 7a76917a76..885da9e27a 100644 --- a/vendor/github.com/pion/webrtc/v4/mediaengine.go +++ b/vendor/github.com/pion/webrtc/v4/mediaengine.go @@ -117,8 +117,12 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f", videoRTCPFeedback}, - PayloadType: 102, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f", + videoRTCPFeedback, + }, + PayloadType: 102, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=102", nil}, @@ -126,8 +130,12 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f", videoRTCPFeedback}, - PayloadType: 104, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f", + videoRTCPFeedback, + }, + PayloadType: 104, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=104", nil}, @@ -135,8 +143,12 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", videoRTCPFeedback}, - PayloadType: 106, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f", + videoRTCPFeedback, + }, + PayloadType: 106, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=106", nil}, @@ -144,8 +156,12 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f", videoRTCPFeedback}, - PayloadType: 108, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f", + videoRTCPFeedback, + }, + PayloadType: 108, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=108", nil}, @@ -153,8 +169,12 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f", videoRTCPFeedback}, - PayloadType: 127, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f", + videoRTCPFeedback, + }, + PayloadType: 127, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=127", nil}, @@ -162,8 +182,13 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f", videoRTCPFeedback}, - PayloadType: 39, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, + 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=4d001f", + videoRTCPFeedback, + }, + PayloadType: 39, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=39", nil}, @@ -198,8 +223,12 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { }, { - RTPCodecCapability: RTPCodecCapability{MimeTypeH264, 90000, 0, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f", videoRTCPFeedback}, - PayloadType: 112, + RTPCodecCapability: RTPCodecCapability{ + MimeTypeH264, 90000, 0, + "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f", + videoRTCPFeedback, + }, + PayloadType: 112, }, { RTPCodecCapability: RTPCodecCapability{MimeTypeRTX, 90000, 0, "apt=112", nil}, @@ -214,19 +243,19 @@ func (m *MediaEngine) RegisterDefaultCodecs() error { return nil } -// addCodec will append codec if it not exists +// addCodec will append codec if it not exists. func (m *MediaEngine) addCodec(codecs []RTPCodecParameters, codec RTPCodecParameters) []RTPCodecParameters { for _, c := range codecs { if c.MimeType == codec.MimeType && c.PayloadType == codec.PayloadType { return codecs } } + return append(codecs, codec) } // RegisterCodec adds codec to the MediaEngine // These are the list of codecs supported by this PeerConnection. -// RegisterCodec is not safe for concurrent use. func (m *MediaEngine) RegisterCodec(codec RTPCodecParameters, typ RTPCodecType) error { m.mu.Lock() defer m.mu.Unlock() @@ -240,12 +269,19 @@ func (m *MediaEngine) RegisterCodec(codec RTPCodecParameters, typ RTPCodecType) default: return ErrUnknownType } + return nil } // RegisterHeaderExtension adds a header extension to the MediaEngine -// To determine the negotiated value use `GetHeaderExtensionID` after signaling is complete -func (m *MediaEngine) RegisterHeaderExtension(extension RTPHeaderExtensionCapability, typ RTPCodecType, allowedDirections ...RTPTransceiverDirection) error { +// To determine the negotiated value use `GetHeaderExtensionID` after signaling is complete. +// +//nolint:cyclop +func (m *MediaEngine) RegisterHeaderExtension( + extension RTPHeaderExtensionCapability, + typ RTPCodecType, + allowedDirections ...RTPTransceiverDirection, +) error { m.mu.Lock() defer m.mu.Unlock() @@ -306,8 +342,11 @@ func (m *MediaEngine) RegisterFeedback(feedback RTCPFeedback, typ RTPCodecType) } // getHeaderExtensionID returns the negotiated ID for a header extension. -// If the Header Extension isn't enabled ok will be false -func (m *MediaEngine) getHeaderExtensionID(extension RTPHeaderExtensionCapability) (val int, audioNegotiated, videoNegotiated bool) { +// If the Header Extension isn't enabled ok will be false. +func (m *MediaEngine) getHeaderExtensionID(extension RTPHeaderExtensionCapability) ( + val int, + audioNegotiated, videoNegotiated bool, +) { m.mu.RLock() defer m.mu.RUnlock() @@ -325,7 +364,7 @@ func (m *MediaEngine) getHeaderExtensionID(extension RTPHeaderExtensionCapabilit } // copy copies any user modifiable state of the MediaEngine -// all internal state is reset +// all internal state is reset. func (m *MediaEngine) copy() *MediaEngine { m.mu.Lock() defer m.mu.Unlock() @@ -337,6 +376,7 @@ func (m *MediaEngine) copy() *MediaEngine { if len(m.headerExtensions) > 0 { cloned.negotiatedHeaderExtensions = map[int]mediaEngineHeaderExtension{} } + return cloned } @@ -346,6 +386,7 @@ func findCodecByPayload(codecs []RTPCodecParameters, payloadType PayloadType) *R return &codec } } + return nil } @@ -393,7 +434,7 @@ func (m *MediaEngine) collectStats(collector *statsReportCollector) { PayloadType: codec.PayloadType, MimeType: codec.MimeType, ClockRate: codec.ClockRate, - Channels: uint8(codec.Channels), + Channels: uint8(codec.Channels), //nolint:gosec // G115 SDPFmtpLine: codec.SDPFmtpLine, } @@ -405,15 +446,21 @@ func (m *MediaEngine) collectStats(collector *statsReportCollector) { statsLoop(m.audioCodecs) } -// Look up a codec and enable if it exists -func (m *MediaEngine) matchRemoteCodec(remoteCodec RTPCodecParameters, typ RTPCodecType, exactMatches, partialMatches []RTPCodecParameters) (RTPCodecParameters, codecMatchType, error) { +// Look up a codec and enable if it exists. +// +//nolint:cyclop +func (m *MediaEngine) matchRemoteCodec( + remoteCodec RTPCodecParameters, + typ RTPCodecType, + exactMatches, partialMatches []RTPCodecParameters, +) (RTPCodecParameters, codecMatchType, error) { codecs := m.videoCodecs if typ == RTPCodecTypeAudio { codecs = m.audioCodecs } remoteFmtp := fmtp.Parse(remoteCodec.RTPCodecCapability.MimeType, remoteCodec.RTPCodecCapability.SDPFmtpLine) - if apt, hasApt := remoteFmtp.Parameter("apt"); hasApt { + if apt, hasApt := remoteFmtp.Parameter("apt"); hasApt { //nolint:nestif payloadType, err := strconv.ParseUint(apt, 10, 8) if err != nil { return RTPCodecParameters{}, codecMatchNone, err @@ -425,6 +472,7 @@ func (m *MediaEngine) matchRemoteCodec(remoteCodec RTPCodecParameters, typ RTPCo if codec.PayloadType == PayloadType(payloadType) { aptMatch = codecMatchExact aptCodec = codec + break } } @@ -434,6 +482,7 @@ func (m *MediaEngine) matchRemoteCodec(remoteCodec RTPCodecParameters, typ RTPCo if codec.PayloadType == PayloadType(payloadType) { aptMatch = codecMatchPartial aptCodec = codec + break } } @@ -446,22 +495,29 @@ func (m *MediaEngine) matchRemoteCodec(remoteCodec RTPCodecParameters, typ RTPCo // replace the apt value with the original codec's payload type toMatchCodec := remoteCodec if aptMatched, mt := codecParametersFuzzySearch(aptCodec, codecs); mt == aptMatch { - toMatchCodec.SDPFmtpLine = strings.Replace(toMatchCodec.SDPFmtpLine, fmt.Sprintf("apt=%d", payloadType), fmt.Sprintf("apt=%d", aptMatched.PayloadType), 1) + toMatchCodec.SDPFmtpLine = strings.Replace( + toMatchCodec.SDPFmtpLine, + fmt.Sprintf("apt=%d", payloadType), + fmt.Sprintf("apt=%d", aptMatched.PayloadType), + 1, + ) } - // if apt's media codec is partial match, then apt codec must be partial match too + // if apt's media codec is partial match, then apt codec must be partial match too. localCodec, matchType := codecParametersFuzzySearch(toMatchCodec, codecs) if matchType == codecMatchExact && aptMatch == codecMatchPartial { matchType = codecMatchPartial } + return localCodec, matchType, nil } localCodec, matchType := codecParametersFuzzySearch(remoteCodec, codecs) + return localCodec, matchType, nil } -// Update header extensions from a remote media section +// Update header extensions from a remote media section. func (m *MediaEngine) updateHeaderExtensionFromMediaSection(media *sdp.MediaDescription) error { var typ RTPCodecType switch { @@ -482,10 +538,11 @@ func (m *MediaEngine) updateHeaderExtensionFromMediaSection(media *sdp.MediaDesc return err } } + return nil } -// Look up a header extension and enable if it exists +// Look up a header extension and enable if it exists. func (m *MediaEngine) updateHeaderExtension(id int, extension string, typ RTPCodecType) error { if m.negotiatedHeaderExtensions == nil { return nil @@ -508,6 +565,7 @@ func (m *MediaEngine) updateHeaderExtension(id int, extension string, typ RTPCod m.negotiatedHeaderExtensions[id] = h } } + return nil } @@ -521,8 +579,8 @@ func (m *MediaEngine) pushCodecs(codecs []RTPCodecParameters, typ RTPCodecType) } } -// Update the MediaEngine from a remote description -func (m *MediaEngine) updateFromRemoteDescription(desc sdp.SessionDescription) error { +// Update the MediaEngine from a remote description. +func (m *MediaEngine) updateFromRemoteDescription(desc sdp.SessionDescription) error { //nolint:cyclop m.mu.Lock() defer m.mu.Unlock() @@ -549,6 +607,7 @@ func (m *MediaEngine) updateFromRemoteDescription(desc sdp.SessionDescription) e if err := m.updateHeaderExtensionFromMediaSection(media); err != nil { return err } + continue } @@ -590,6 +649,7 @@ func (m *MediaEngine) updateFromRemoteDescription(desc sdp.SessionDescription) e return err } } + return nil } @@ -614,7 +674,8 @@ func (m *MediaEngine) getCodecsByKind(typ RTPCodecType) []RTPCodecParameters { return nil } -func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPTransceiverDirection) RTPParameters { //nolint:gocognit +//nolint:gocognit,cyclop +func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPTransceiverDirection) RTPParameters { headerExtensions := make([]RTPHeaderExtensionParameter, 0) // perform before locking to prevent recursive RLocks @@ -622,21 +683,24 @@ func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPT m.mu.RLock() defer m.mu.RUnlock() - if m.negotiatedVideo && typ == RTPCodecTypeVideo || - m.negotiatedAudio && typ == RTPCodecTypeAudio { + + //nolint:nestif + if (m.negotiatedVideo && typ == RTPCodecTypeVideo) || (m.negotiatedAudio && typ == RTPCodecTypeAudio) { for id, e := range m.negotiatedHeaderExtensions { - if haveRTPTransceiverDirectionIntersection(e.allowedDirections, directions) && (e.isAudio && typ == RTPCodecTypeAudio || e.isVideo && typ == RTPCodecTypeVideo) { + if haveRTPTransceiverDirectionIntersection(e.allowedDirections, directions) && + (e.isAudio && typ == RTPCodecTypeAudio || e.isVideo && typ == RTPCodecTypeVideo) { headerExtensions = append(headerExtensions, RTPHeaderExtensionParameter{ID: id, URI: e.uri}) } } } else { mediaHeaderExtensions := make(map[int]mediaEngineHeaderExtension) - for _, e := range m.headerExtensions { + for _, ext := range m.headerExtensions { usingNegotiatedID := false for id := range m.negotiatedHeaderExtensions { - if m.negotiatedHeaderExtensions[id].uri == e.uri { + if m.negotiatedHeaderExtensions[id].uri == ext.uri { usingNegotiatedID = true - mediaHeaderExtensions[id] = e + mediaHeaderExtensions[id] = ext + break } } @@ -647,7 +711,8 @@ func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPT idAvailable = false } if _, taken := m.negotiatedHeaderExtensions[id]; idAvailable && !taken { - mediaHeaderExtensions[id] = e + mediaHeaderExtensions[id] = ext + break } } @@ -655,7 +720,8 @@ func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPT } for id, e := range mediaHeaderExtensions { - if haveRTPTransceiverDirectionIntersection(e.allowedDirections, directions) && (e.isAudio && typ == RTPCodecTypeAudio || e.isVideo && typ == RTPCodecTypeVideo) { + if haveRTPTransceiverDirectionIntersection(e.allowedDirections, directions) && + (e.isAudio && typ == RTPCodecTypeAudio || e.isVideo && typ == RTPCodecTypeVideo) { headerExtensions = append(headerExtensions, RTPHeaderExtensionParameter{ID: id, URI: e.uri}) } } diff --git a/vendor/github.com/pion/webrtc/v4/networktype.go b/vendor/github.com/pion/webrtc/v4/networktype.go index 7bf4862327..a7ee773c12 100644 --- a/vendor/github.com/pion/webrtc/v4/networktype.go +++ b/vendor/github.com/pion/webrtc/v4/networktype.go @@ -18,11 +18,11 @@ func supportedNetworkTypes() []NetworkType { } } -// NetworkType represents the type of network +// NetworkType represents the type of network. type NetworkType int const ( - // NetworkTypeUnknown is the enum's zero-value + // NetworkTypeUnknown is the enum's zero-value. NetworkTypeUnknown NetworkType = iota // NetworkTypeUDP4 indicates UDP over IPv4. @@ -61,7 +61,7 @@ func (t NetworkType) String() string { } } -// Protocol returns udp or tcp +// Protocol returns udp or tcp. func (t NetworkType) Protocol() string { switch t { case NetworkTypeUDP4: diff --git a/vendor/github.com/pion/webrtc/v4/offeransweroptions.go b/vendor/github.com/pion/webrtc/v4/offeransweroptions.go index 5286889755..17435566a2 100644 --- a/vendor/github.com/pion/webrtc/v4/offeransweroptions.go +++ b/vendor/github.com/pion/webrtc/v4/offeransweroptions.go @@ -18,7 +18,7 @@ type AnswerOptions struct { } // OfferOptions structure describes the options used to control the offer -// creation process +// creation process. type OfferOptions struct { OfferAnswerOptions diff --git a/vendor/github.com/pion/webrtc/v4/operations.go b/vendor/github.com/pion/webrtc/v4/operations.go index 67d24eebec..3e65f13578 100644 --- a/vendor/github.com/pion/webrtc/v4/operations.go +++ b/vendor/github.com/pion/webrtc/v4/operations.go @@ -8,7 +8,7 @@ import ( "sync" ) -// Operation is a function +// Operation is a function. type operation func() // Operations is a task executor. @@ -64,10 +64,11 @@ func (o *operations) tryEnqueue(op operation) bool { return true } -// IsEmpty checks if there are tasks in the queue +// IsEmpty checks if there are tasks in the queue. func (o *operations) IsEmpty() bool { o.mu.Lock() defer o.mu.Unlock() + return o.ops.Len() == 0 } @@ -93,6 +94,7 @@ func (o *operations) GracefulClose() { o.mu.Lock() if o.isClosed { o.mu.Unlock() + return } // do not enqueue anymore ops from here on @@ -120,6 +122,7 @@ func (o *operations) pop() func() { if op, ok := e.Value.(operation); ok { return op } + return nil } @@ -132,6 +135,7 @@ func (o *operations) start() { if o.ops.Len() == 0 || o.isClosed { o.busyCh = nil + return } diff --git a/vendor/github.com/pion/webrtc/v4/peerconnection.go b/vendor/github.com/pion/webrtc/v4/peerconnection.go index 5e613c224c..07b188b71b 100644 --- a/vendor/github.com/pion/webrtc/v4/peerconnection.go +++ b/vendor/github.com/pion/webrtc/v4/peerconnection.go @@ -100,6 +100,7 @@ type PeerConnection struct { // then call [(*API).NewPeerConnection] instead of this function. func NewPeerConnection(configuration Configuration) (*PeerConnection, error) { api := NewAPI() + return api.NewPeerConnection(configuration) } @@ -200,7 +201,7 @@ func (api *API) NewPeerConnection(configuration Configuration) (*PeerConnection, // from its SetConfiguration counterpart because most of the checks do not // include verification statements related to the existing state. Thus the // function describes only minor verification of some the struct variables. -func (pc *PeerConnection) initConfiguration(configuration Configuration) error { +func (pc *PeerConnection) initConfiguration(configuration Configuration) error { //nolint:cyclop if configuration.PeerIdentity != "" { pc.configuration.PeerIdentity = configuration.PeerIdentity } @@ -255,7 +256,7 @@ func (pc *PeerConnection) initConfiguration(configuration Configuration) error { } // OnSignalingStateChange sets an event handler which is invoked when the -// peer connection's signaling state changes +// peer connection's signaling state changes. func (pc *PeerConnection) OnSignalingStateChange(f func(SignalingState)) { pc.mu.Lock() defer pc.mu.Unlock() @@ -282,7 +283,7 @@ func (pc *PeerConnection) OnDataChannel(f func(*DataChannel)) { } // OnNegotiationNeeded sets an event handler which is invoked when -// a change has occurred which requires session negotiation +// a change has occurred which requires session negotiation. func (pc *PeerConnection) OnNegotiationNeeded(f func()) { pc.onNegotiationNeededHandler.Store(f) } @@ -295,6 +296,7 @@ func (pc *PeerConnection) onNegotiationNeeded() { // connection.[[UpdateNegotiationNeededFlagOnEmptyChain]] to true, and abort these steps. if !pc.ops.IsEmpty() { pc.updateNegotiationNeededFlagOnEmptyChain.set(true) + return } pc.ops.Enqueue(pc.negotiationNeededOp) @@ -312,6 +314,7 @@ func (pc *PeerConnection) negotiationNeededOp() { // true, and abort these steps. if !pc.ops.IsEmpty() { pc.updateNegotiationNeededFlagOnEmptyChain.set(true) + return } @@ -325,6 +328,7 @@ func (pc *PeerConnection) negotiationNeededOp() { // to false, and abort these steps. if !pc.checkNegotiationNeeded() { pc.isNegotiationNeeded.set(false) + return } @@ -342,7 +346,7 @@ func (pc *PeerConnection) negotiationNeededOp() { } } -func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit +func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit,cyclop // To check if negotiation is needed for connection, perform the following checks: // Skip 1, 2 steps // Step 3 @@ -364,23 +368,24 @@ func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit return true } - for _, t := range pc.rtpTransceivers { + for _, transceiver := range pc.rtpTransceivers { // https://www.w3.org/TR/webrtc/#dfn-update-the-negotiation-needed-flag // Step 5.1 // if t.stopping && !t.stopped { // return true // } - m := getByMid(t.Mid(), localDesc) + mid := getByMid(transceiver.Mid(), localDesc) // Step 5.2 - if m == nil { + if mid == nil { return true } // Step 5.3.1 - if t.Direction() == RTPTransceiverDirectionSendrecv || t.Direction() == RTPTransceiverDirectionSendonly { - descMsid, okMsid := m.Attribute(sdp.AttrKeyMsid) - sender := t.Sender() + if transceiver.Direction() == RTPTransceiverDirectionSendrecv || + transceiver.Direction() == RTPTransceiverDirectionSendonly { + descMsid, okMsid := mid.Attribute(sdp.AttrKeyMsid) + sender := transceiver.Sender() if sender == nil { return true } @@ -400,17 +405,17 @@ func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit switch localDesc.Type { case SDPTypeOffer: // Step 5.3.2 - rm := getByMid(t.Mid(), remoteDesc) + rm := getByMid(transceiver.Mid(), remoteDesc) if rm == nil { return true } - if getPeerDirection(m) != t.Direction() && getPeerDirection(rm) != t.Direction().Revers() { + if getPeerDirection(mid) != transceiver.Direction() && getPeerDirection(rm) != transceiver.Direction().Revers() { return true } case SDPTypeAnswer: // Step 5.3.3 - if _, ok := m.Attribute(t.Direction().String()); !ok { + if _, ok := mid.Attribute(transceiver.Direction().String()); !ok { return true } default: @@ -491,7 +496,7 @@ func (pc *PeerConnection) onICEConnectionStateChange(cs ICEConnectionState) { } // OnConnectionStateChange sets an event handler which is called -// when the PeerConnectionState has changed +// when the PeerConnectionState has changed. func (pc *PeerConnection) OnConnectionStateChange(f func(PeerConnectionState)) { pc.onConnectionStateChangeHandler.Store(f) } @@ -505,7 +510,7 @@ func (pc *PeerConnection) onConnectionStateChange(cs PeerConnectionState) { } // SetConfiguration updates the configuration of this PeerConnection object. -func (pc *PeerConnection) SetConfiguration(configuration Configuration) error { //nolint:gocognit +func (pc *PeerConnection) SetConfiguration(configuration Configuration) error { //nolint:gocognit,cyclop // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2) if pc.isClosed.get() { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} @@ -571,6 +576,7 @@ func (pc *PeerConnection) SetConfiguration(configuration Configuration) error { } pc.configuration.ICEServers = configuration.ICEServers } + return nil } @@ -586,11 +592,12 @@ func (pc *PeerConnection) GetConfiguration() Configuration { func (pc *PeerConnection) getStatsID() string { pc.mu.RLock() defer pc.mu.RUnlock() + return pc.statsID } // hasLocalDescriptionChanged returns whether local media (rtpTransceivers) has changed -// caller of this method should hold `pc.mu` lock +// caller of this method should hold `pc.mu` lock. func (pc *PeerConnection) hasLocalDescriptionChanged(desc *SessionDescription) bool { for _, t := range pc.rtpTransceivers { m := getByMid(t.Mid(), desc) @@ -602,12 +609,15 @@ func (pc *PeerConnection) hasLocalDescriptionChanged(desc *SessionDescription) b return true } } + return false } // CreateOffer starts the PeerConnection and generates the localDescription // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-createoffer -func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription, error) { //nolint:gocognit +// +//nolint:gocognit,cyclop +func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription, error) { useIdentity := pc.idpLoginURL != nil switch { case useIdentity: @@ -623,7 +633,7 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription } var ( - d *sdp.SessionDescription + descr *sdp.SessionDescription offer SessionDescription err error ) @@ -649,7 +659,7 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription } // include unmatched local transceivers - if !isPlanB { + if !isPlanB { //nolint:nestif // update the greater mid if the remote description provides a greater one if pc.currentRemoteDescription != nil { var numericMid int @@ -675,6 +685,7 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription pc.greaterMid = numericMid } } + continue } pc.greaterMid++ @@ -686,17 +697,22 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription } if pc.currentRemoteDescription == nil { - d, err = pc.generateUnmatchedSDP(currentTransceivers, useIdentity) + descr, err = pc.generateUnmatchedSDP(currentTransceivers, useIdentity) } else { - d, err = pc.generateMatchedSDP(currentTransceivers, useIdentity, true /*includeUnmatched */, connectionRoleFromDtlsRole(defaultDtlsRoleOffer)) + descr, err = pc.generateMatchedSDP( + currentTransceivers, + useIdentity, + true, /*includeUnmatched */ + connectionRoleFromDtlsRole(defaultDtlsRoleOffer), + ) } if err != nil { return SessionDescription{}, err } - updateSDPOrigin(&pc.sdpOrigin, d) - sdpBytes, err := d.Marshal() + updateSDPOrigin(&pc.sdpOrigin, descr) + sdpBytes, err := descr.Marshal() if err != nil { return SessionDescription{}, err } @@ -704,7 +720,7 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription offer = SessionDescription{ Type: SDPTypeOffer, SDP: string(sdpBytes), - parsed: d, + parsed: descr, } // Verify local media hasn't changed during offer @@ -719,6 +735,7 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription } pc.lastOffer = offer.SDP + return offer, nil } @@ -736,7 +753,12 @@ func (pc *PeerConnection) createICEGatherer() (*ICEGatherer, error) { // Update the PeerConnectionState given the state of relevant transports // https://www.w3.org/TR/webrtc/#rtcpeerconnectionstate-enum -func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnectionState, dtlsTransportState DTLSTransportState) { +// +//nolint:cyclop +func (pc *PeerConnection) updateConnectionState( + iceConnectionState ICEConnectionState, + dtlsTransportState DTLSTransportState, +) { connectionState := PeerConnectionStateNew switch { // The RTCPeerConnection object's [[IsClosed]] slot is true. @@ -766,7 +788,8 @@ func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnection // All RTCIceTransports and RTCDtlsTransports are in the "connected", "completed" or "closed" // state and all RTCDtlsTransports are in the "connected" or "closed" state. - case (iceConnectionState == ICEConnectionStateConnected || iceConnectionState == ICEConnectionStateCompleted || iceConnectionState == ICEConnectionStateClosed) && + case (iceConnectionState == ICEConnectionStateConnected || + iceConnectionState == ICEConnectionStateCompleted || iceConnectionState == ICEConnectionStateClosed) && (dtlsTransportState == DTLSTransportStateConnected || dtlsTransportState == DTLSTransportStateClosed): connectionState = PeerConnectionStateConnected } @@ -779,8 +802,8 @@ func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnection } func (pc *PeerConnection) createICETransport() *ICETransport { - t := pc.api.NewICETransport(pc.iceGatherer) - t.internalOnConnectionStateChangeHandler.Store(func(state ICETransportState) { + transport := pc.api.NewICETransport(pc.iceGatherer) + transport.internalOnConnectionStateChangeHandler.Store(func(state ICETransportState) { var cs ICEConnectionState switch state { case ICETransportStateNew: @@ -799,16 +822,19 @@ func (pc *PeerConnection) createICETransport() *ICETransport { cs = ICEConnectionStateClosed default: pc.log.Warnf("OnConnectionStateChange: unhandled ICE state: %s", state) + return } pc.onICEConnectionStateChange(cs) pc.updateConnectionState(cs, pc.dtlsTransport.State()) }) - return t + return transport } -// CreateAnswer starts the PeerConnection and generates the localDescription +// CreateAnswer starts the PeerConnection and generates the localDescription. +// +//nolint:cyclop func (pc *PeerConnection) CreateAnswer(*AnswerOptions) (SessionDescription, error) { useIdentity := pc.idpLoginURL != nil remoteDesc := pc.RemoteDescription() @@ -819,7 +845,8 @@ func (pc *PeerConnection) CreateAnswer(*AnswerOptions) (SessionDescription, erro return SessionDescription{}, errIdentityProviderNotImplemented case pc.isClosed.get(): return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} - case pc.signalingState.Get() != SignalingStateHaveRemoteOffer && pc.signalingState.Get() != SignalingStateHaveLocalPranswer: + case pc.signalingState.Get() != SignalingStateHaveRemoteOffer && + pc.signalingState.Get() != SignalingStateHaveLocalPranswer: return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrIncorrectSignalingState} } @@ -837,13 +864,13 @@ func (pc *PeerConnection) CreateAnswer(*AnswerOptions) (SessionDescription, erro pc.mu.Lock() defer pc.mu.Unlock() - d, err := pc.generateMatchedSDP(pc.rtpTransceivers, useIdentity, false /*includeUnmatched */, connectionRole) + descr, err := pc.generateMatchedSDP(pc.rtpTransceivers, useIdentity, false /*includeUnmatched */, connectionRole) if err != nil { return SessionDescription{}, err } - updateSDPOrigin(&pc.sdpOrigin, d) - sdpBytes, err := d.Marshal() + updateSDPOrigin(&pc.sdpOrigin, descr) + sdpBytes, err := descr.Marshal() if err != nil { return SessionDescription{}, err } @@ -851,19 +878,24 @@ func (pc *PeerConnection) CreateAnswer(*AnswerOptions) (SessionDescription, erro desc := SessionDescription{ Type: SDPTypeAnswer, SDP: string(sdpBytes), - parsed: d, + parsed: descr, } pc.lastAnswer = desc.SDP + return desc, nil } // 4.4.1.6 Set the SessionDescription -func (pc *PeerConnection) setDescription(sd *SessionDescription, op stateChangeOp) error { //nolint:gocognit +// +//nolint:gocognit,cyclop +func (pc *PeerConnection) setDescription(sd *SessionDescription, op stateChangeOp) error { switch { case pc.isClosed.get(): return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} case NewSDPType(sd.Type.String()) == SDPTypeUnknown: - return &rtcerr.TypeError{Err: fmt.Errorf("%w: '%d' is not a valid enum value of type SDPType", errPeerConnSDPTypeInvalidValue, sd.Type)} + return &rtcerr.TypeError{ + Err: fmt.Errorf("%w: '%d' is not a valid enum value of type SDPType", errPeerConnSDPTypeInvalidValue, sd.Type), + } } nextState, err := func() (SignalingState, error) { @@ -969,10 +1001,13 @@ func (pc *PeerConnection) setDescription(sd *SessionDescription, op stateChangeO } pc.onSignalingStateChange(nextState) } + return err } // SetLocalDescription sets the SessionDescription of the local peer +// +//nolint:cyclop func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error { if pc.isClosed.get() { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} @@ -1025,6 +1060,7 @@ func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error { if pc.iceGatherer.State() == ICEGathererStateNew { return pc.iceGatherer.Gather() } + return nil } @@ -1036,11 +1072,14 @@ func (pc *PeerConnection) LocalDescription() *SessionDescription { if pendingLocalDescription := pc.PendingLocalDescription(); pendingLocalDescription != nil { return pendingLocalDescription } + return pc.CurrentLocalDescription() } // SetRemoteDescription sets the SessionDescription of the remote peer -func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { //nolint:gocognit,gocyclo +// +//nolint:gocognit,gocyclo,cyclop,maintidx +func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { if pc.isClosed.get() { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } @@ -1063,7 +1102,7 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { sender.configureRTXAndFEC() } - var t *RTPTransceiver + var transceiver *RTPTransceiver localTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...) detectedPlanB := descriptionIsPlanB(pc.RemoteDescription(), pc.log) if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan { @@ -1072,7 +1111,7 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { weOffer := desc.Type == SDPTypeAnswer - if !weOffer && !detectedPlanB { + if !weOffer && !detectedPlanB { //nolint:nestif for _, media := range pc.RemoteDescription().parsed.MediaDescriptions { midValue := getMidValue(media) if midValue == "" { @@ -1089,17 +1128,17 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { continue } - t, localTransceivers = findByMid(midValue, localTransceivers) - if t == nil { - t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers) + transceiver, localTransceivers = findByMid(midValue, localTransceivers) + if transceiver == nil { + transceiver, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers) } else if direction == RTPTransceiverDirectionInactive { - if err := t.Stop(); err != nil { + if err := transceiver.Stop(); err != nil { return err } } switch { - case t == nil: + case transceiver == nil: receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport) if err != nil { return err @@ -1112,44 +1151,47 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { localDirection = RTPTransceiverDirectionInactive } - t = newRTPTransceiver(receiver, nil, localDirection, kind, pc.api) + transceiver = newRTPTransceiver(receiver, nil, localDirection, kind, pc.api) pc.mu.Lock() - pc.addRTPTransceiver(t) + pc.addRTPTransceiver(transceiver) pc.mu.Unlock() // if transceiver is create by remote sdp, set prefer codec same as remote peer if codecs, err := codecsFromMediaDescription(media); err == nil { filteredCodecs := []RTPCodecParameters{} for _, codec := range codecs { - if c, matchType := codecParametersFuzzySearch(codec, pc.api.mediaEngine.getCodecsByKind(kind)); matchType == codecMatchExact { + if c, matchType := codecParametersFuzzySearch( + codec, + pc.api.mediaEngine.getCodecsByKind(kind), + ); matchType == codecMatchExact { // if codec match exact, use payloadtype register to mediaengine codec.PayloadType = c.PayloadType filteredCodecs = append(filteredCodecs, codec) } } - _ = t.SetCodecPreferences(filteredCodecs) + _ = transceiver.SetCodecPreferences(filteredCodecs) } case direction == RTPTransceiverDirectionRecvonly: - if t.Direction() == RTPTransceiverDirectionSendrecv { - t.setDirection(RTPTransceiverDirectionSendonly) - } else if t.Direction() == RTPTransceiverDirectionRecvonly { - t.setDirection(RTPTransceiverDirectionInactive) + if transceiver.Direction() == RTPTransceiverDirectionSendrecv { + transceiver.setDirection(RTPTransceiverDirectionSendonly) + } else if transceiver.Direction() == RTPTransceiverDirectionRecvonly { + transceiver.setDirection(RTPTransceiverDirectionInactive) } case direction == RTPTransceiverDirectionSendrecv: - if t.Direction() == RTPTransceiverDirectionSendonly { - t.setDirection(RTPTransceiverDirectionSendrecv) - } else if t.Direction() == RTPTransceiverDirectionInactive { - t.setDirection(RTPTransceiverDirectionRecvonly) + if transceiver.Direction() == RTPTransceiverDirectionSendonly { + transceiver.setDirection(RTPTransceiverDirectionSendrecv) + } else if transceiver.Direction() == RTPTransceiverDirectionInactive { + transceiver.setDirection(RTPTransceiverDirectionRecvonly) } case direction == RTPTransceiverDirectionSendonly: - if t.Direction() == RTPTransceiverDirectionInactive { - t.setDirection(RTPTransceiverDirectionRecvonly) + if transceiver.Direction() == RTPTransceiverDirectionInactive { + transceiver.setDirection(RTPTransceiverDirectionRecvonly) } } - if t.Mid() == "" { - if err := t.SetMid(midValue); err != nil { + if transceiver.Mid() == "" { + if err := transceiver.SetMid(midValue); err != nil { return err } } @@ -1193,6 +1235,7 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { pc.startRTP(true, &desc, currentTransceivers) }) } + return nil } @@ -1207,7 +1250,8 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { // If one of the agents is lite and the other one is not, the lite agent must be the controlled agent. // If both or neither agents are lite the offering agent is controlling. // RFC 8445 S6.1.1 - if (weOffer && remoteIsLite == pc.api.settingEngine.candidates.ICELite) || (remoteIsLite && !pc.api.settingEngine.candidates.ICELite) { + if (weOffer && remoteIsLite == pc.api.settingEngine.candidates.ICELite) || + (remoteIsLite && !pc.api.settingEngine.candidates.ICELite) { iceRole = ICERoleControlling } @@ -1223,11 +1267,19 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { } pc.ops.Enqueue(func() { - pc.startTransports(iceRole, dtlsRoleFromRemoteSDP(desc.parsed), iceDetails.Ufrag, iceDetails.Password, fingerprint, fingerprintHash) + pc.startTransports( + iceRole, + dtlsRoleFromRemoteSDP(desc.parsed), + iceDetails.Ufrag, + iceDetails.Password, + fingerprint, + fingerprintHash, + ) if weOffer { pc.startRTP(false, &desc, currentTransceivers) } }) + return nil } @@ -1247,16 +1299,18 @@ func (pc *PeerConnection) configureReceiver(incoming trackDetails, receiver *RTP func (pc *PeerConnection) startReceiver(incoming trackDetails, receiver *RTPReceiver) { if err := receiver.startReceive(trackDetailsToRTPReceiveParameters(&incoming)); err != nil { pc.log.Warnf("RTPReceiver Receive failed %s", err) + return } - for _, t := range receiver.Tracks() { - if t.SSRC() == 0 || t.RID() != "" { + for _, track := range receiver.Tracks() { + if track.SSRC() == 0 || track.RID() != "" { return } if pc.api.settingEngine.fireOnTrackBeforeFirstRTP { - pc.onTrack(t, receiver) + pc.onTrack(track, receiver) + return } go func(track *TrackRemote) { @@ -1264,20 +1318,27 @@ func (pc *PeerConnection) startReceiver(incoming trackDetails, receiver *RTPRece n, _, err := track.peek(b) if err != nil { pc.log.Warnf("Could not determine PayloadType for SSRC %d (%s)", track.SSRC(), err) + return } if err = track.checkAndUpdateTrack(b[:n]); err != nil { pc.log.Warnf("Failed to set codec settings for track SSRC %d (%s)", track.SSRC(), err) + return } pc.onTrack(track, receiver) - }(t) + }(track) } } -func setRTPTransceiverCurrentDirection(answer *SessionDescription, currentTransceivers []*RTPTransceiver, weOffer bool) error { +//nolint:cyclop +func setRTPTransceiverCurrentDirection( + answer *SessionDescription, + currentTransceivers []*RTPTransceiver, + weOffer bool, +) error { currentTransceivers = append([]*RTPTransceiver{}, currentTransceivers...) for _, media := range answer.parsed.MediaDescriptions { midValue := getMidValue(media) @@ -1289,10 +1350,10 @@ func setRTPTransceiverCurrentDirection(answer *SessionDescription, currentTransc continue } - var t *RTPTransceiver - t, currentTransceivers = findByMid(midValue, currentTransceivers) + var transceiver *RTPTransceiver + transceiver, currentTransceivers = findByMid(midValue, currentTransceivers) - if t == nil { + if transceiver == nil { return fmt.Errorf("%w: %q", errPeerConnTranscieverMidNil, midValue) } @@ -1315,19 +1376,20 @@ func setRTPTransceiverCurrentDirection(answer *SessionDescription, currentTransc // If a transceiver is created by applying a remote description that has recvonly transceiver, // it will have no sender. In this case, the transceiver's current direction is set to inactive so // that the transceiver can be reused by next AddTrack. - if !weOffer && direction == RTPTransceiverDirectionSendonly && t.Sender() == nil { + if !weOffer && direction == RTPTransceiverDirectionSendonly && transceiver.Sender() == nil { direction = RTPTransceiverDirectionInactive } - t.setCurrentDirection(direction) + transceiver.setCurrentDirection(direction) } + return nil } func runIfNewReceiver( incomingTrack trackDetails, transceivers []*RTPTransceiver, - f func(incomingTrack trackDetails, receiver *RTPReceiver), + callbackFunc func(incomingTrack trackDetails, receiver *RTPReceiver), ) bool { for _, t := range transceivers { if t.Mid() != incomingTrack.mid { @@ -1342,52 +1404,61 @@ func runIfNewReceiver( continue } - f(incomingTrack, receiver) + callbackFunc(incomingTrack, receiver) + return true } return false } -// configureRTPReceivers opens knows inbound SRTP streams from the RemoteDescription -func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) { //nolint:gocognit +// configureRTPReceivers opens knows inbound SRTP streams from the RemoteDescription. +// +//nolint:gocognit,cyclop +func (pc *PeerConnection) configureRTPReceivers( + isRenegotiation bool, + remoteDesc *SessionDescription, + currentTransceivers []*RTPTransceiver, +) { incomingTracks := trackDetailsFromSDP(pc.log, remoteDesc.parsed) - if isRenegotiation { - for _, t := range currentTransceivers { - receiver := t.Receiver() + if isRenegotiation { //nolint:nestif + for _, transceiver := range currentTransceivers { + receiver := transceiver.Receiver() if receiver == nil { continue } - tracks := t.Receiver().Tracks() + tracks := transceiver.Receiver().Tracks() if len(tracks) == 0 { continue } - mid := t.Mid() + mid := transceiver.Mid() receiverNeedsStopped := false - for _, track := range tracks { - func(t *TrackRemote) { - t.mu.Lock() - defer t.mu.Unlock() - - if t.rid != "" { - if details := trackDetailsForRID(incomingTracks, mid, t.rid); details != nil { - t.id = details.id - t.streamID = details.streamID + for _, trackRemote := range tracks { + func(track *TrackRemote) { + track.mu.Lock() + defer track.mu.Unlock() + + if track.rid != "" { + if details := trackDetailsForRID(incomingTracks, mid, track.rid); details != nil { + track.id = details.id + track.streamID = details.streamID + return } - } else if t.ssrc != 0 { - if details := trackDetailsForSSRC(incomingTracks, t.ssrc); details != nil { - t.id = details.id - t.streamID = details.streamID + } else if track.ssrc != 0 { + if details := trackDetailsForSSRC(incomingTracks, track.ssrc); details != nil { + track.id = details.id + track.streamID = details.streamID + return } } receiverNeedsStopped = true - }(track) + }(trackRemote) } if !receiverNeedsStopped { @@ -1396,15 +1467,17 @@ func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc if err := receiver.Stop(); err != nil { pc.log.Warnf("Failed to stop RtpReceiver: %s", err) + continue } receiver, err := pc.api.NewRTPReceiver(receiver.kind, pc.dtlsTransport) if err != nil { pc.log.Warnf("Failed to create new RtpReceiver: %s", err) + continue } - t.setReceiver(receiver) + transceiver.setReceiver(receiver) } } @@ -1432,7 +1505,7 @@ func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc } } -// startRTPReceivers opens knows inbound SRTP streams from the RemoteDescription +// startRTPReceivers opens knows inbound SRTP streams from the RemoteDescription. func (pc *PeerConnection) startRTPReceivers(remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) { incomingTracks := trackDetailsFromSDP(pc.log, remoteDesc.parsed) if len(incomingTracks) == 0 { @@ -1466,6 +1539,7 @@ func (pc *PeerConnection) startRTPReceivers(remoteDesc *SessionDescription, curr }) if err != nil { pc.log.Warnf("Could not add transceiver for remote SSRC %d: %s", incomingTrack.ssrcs[0], err) + continue } pc.configureReceiver(incomingTrack, t.Receiver()) @@ -1474,7 +1548,7 @@ func (pc *PeerConnection) startRTPReceivers(remoteDesc *SessionDescription, curr } } -// startRTPSenders starts all outbound RTP streams +// startRTPSenders starts all outbound RTP streams. func (pc *PeerConnection) startRTPSenders(currentTransceivers []*RTPTransceiver) error { for _, transceiver := range currentTransceivers { if sender := transceiver.Sender(); sender != nil && sender.isNegotiated() && !sender.hasSent() { @@ -1488,7 +1562,7 @@ func (pc *PeerConnection) startRTPSenders(currentTransceivers []*RTPTransceiver) return nil } -// Start SCTP subsystem +// Start SCTP subsystem. func (pc *PeerConnection) startSCTP() { // Start sctp if err := pc.sctpTransport.Start(SCTPCapabilities{ @@ -1503,7 +1577,11 @@ func (pc *PeerConnection) startSCTP() { } } -func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *SessionDescription) (handled bool, err error) { +//nolint:cyclop +func (pc *PeerConnection) handleUndeclaredSSRC( + ssrc SSRC, + remoteDescription *SessionDescription, +) (handled bool, err error) { if len(remoteDescription.parsed.MediaDescriptions) != 1 { return false, nil } @@ -1554,15 +1632,17 @@ func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *Ses pc.configureReceiver(incoming, t.Receiver()) pc.startReceiver(incoming, t.Receiver()) + return true, nil } // Chrome sends probing traffic on SSRC 0. This reads the packets to ensure that we properly -// generate TWCC reports for it. Since this isn't actually media we don't pass this to the user +// generate TWCC reports for it. Since this isn't actually media we don't pass this to the user. func (pc *PeerConnection) handleNonMediaBandwidthProbe() { nonMediaBandwidthProbe, err := pc.api.NewRTPReceiver(RTPCodecTypeVideo, pc.dtlsTransport) if err != nil { pc.log.Errorf("handleNonMediaBandwidthProbe failed to create RTPReceiver: %v", err) + return } @@ -1570,6 +1650,7 @@ func (pc *PeerConnection) handleNonMediaBandwidthProbe() { Encodings: []RTPDecodingParameters{{RTPCodingParameters: RTPCodingParameters{}}}, }); err != nil { pc.log.Errorf("handleNonMediaBandwidthProbe failed to start RTPReceiver: %v", err) + return } @@ -1578,12 +1659,13 @@ func (pc *PeerConnection) handleNonMediaBandwidthProbe() { for { if _, _, err = nonMediaBandwidthProbe.readRTP(b, nonMediaBandwidthProbe.Track()); err != nil { pc.log.Tracef("handleNonMediaBandwidthProbe read exiting: %v", err) + return } } } -func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) error { //nolint:gocognit +func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) error { //nolint:gocognit,cyclop remoteDescription := pc.RemoteDescription() if remoteDescription == nil { return errPeerConnRemoteDescriptionNil @@ -1606,17 +1688,23 @@ func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) err return err } - midExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESMidURI}) + midExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID( + RTPHeaderExtensionCapability{sdp.SDESMidURI}, + ) if !audioSupported && !videoSupported { return errPeerConnSimulcastMidRTPExtensionRequired } - streamIDExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESRTPStreamIDURI}) + streamIDExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID( + RTPHeaderExtensionCapability{sdp.SDESRTPStreamIDURI}, + ) if !audioSupported && !videoSupported { return errPeerConnSimulcastStreamIDRTPExtensionRequired } - repairStreamIDExtensionID, _, _ := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESRepairRTPStreamIDURI}) + repairStreamIDExtensionID, _, _ := pc.api.mediaEngine.getHeaderExtensionID( + RTPHeaderExtensionCapability{sdp.SDESRepairRTPStreamIDURI}, + ) b := make([]byte, pc.api.settingEngine.getReceiveMTU()) @@ -1635,7 +1723,15 @@ func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) err return err } - streamInfo := createStreamInfo("", ssrc, 0, 0, params.Codecs[0].PayloadType, 0, 0, params.Codecs[0].RTPCodecCapability, params.HeaderExtensions) + streamInfo := createStreamInfo( + "", + ssrc, + 0, 0, + params.Codecs[0].PayloadType, + 0, 0, + params.Codecs[0].RTPCodecCapability, + params.HeaderExtensions, + ) readStream, interceptor, rtcpReadStream, rtcpInterceptor, err := pc.dtlsTransport.streamsForSSRC(ssrc, *streamInfo) if err != nil { return err @@ -1655,7 +1751,14 @@ func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) err return err } - if _, paddingOnly, err = handleUnknownRTPPacket(b[:i], uint8(midExtensionID), uint8(streamIDExtensionID), uint8(repairStreamIDExtensionID), &mid, &rid, &rsid); err != nil { + if _, paddingOnly, err = handleUnknownRTPPacket( + b[:i], uint8(midExtensionID), //nolint:gosec // G115 + uint8(streamIDExtensionID), //nolint:gosec // G115 + uint8(repairStreamIDExtensionID), //nolint:gosec // G115 + &mid, + &rid, + &rsid, + ); err != nil { return err } @@ -1671,46 +1774,60 @@ func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) err if rsid != "" { receiver.mu.Lock() defer receiver.mu.Unlock() + return receiver.receiveForRtx(SSRC(0), rsid, streamInfo, readStream, interceptor, rtcpReadStream, rtcpInterceptor) } - track, err := receiver.receiveForRid(rid, params, streamInfo, readStream, interceptor, rtcpReadStream, rtcpInterceptor) + track, err := receiver.receiveForRid( + rid, + params, + streamInfo, + readStream, + interceptor, + rtcpReadStream, + rtcpInterceptor, + ) if err != nil { return err } pc.onTrack(track, receiver) + return nil } } pc.api.interceptor.UnbindRemoteStream(streamInfo) + return errPeerConnSimulcastIncomingSSRCFailed } -// undeclaredMediaProcessor handles RTP/RTCP packets that don't match any a:ssrc lines +// undeclaredMediaProcessor handles RTP/RTCP packets that don't match any a:ssrc lines. func (pc *PeerConnection) undeclaredMediaProcessor() { go pc.undeclaredRTPMediaProcessor() go pc.undeclaredRTCPMediaProcessor() } -func (pc *PeerConnection) undeclaredRTPMediaProcessor() { +func (pc *PeerConnection) undeclaredRTPMediaProcessor() { //nolint:cyclop var simulcastRoutineCount uint64 for { srtpSession, err := pc.dtlsTransport.getSRTPSession() if err != nil { pc.log.Warnf("undeclaredMediaProcessor failed to open SrtpSession: %v", err) + return } srtcpSession, err := pc.dtlsTransport.getSRTCPSession() if err != nil { pc.log.Warnf("undeclaredMediaProcessor failed to open SrtcpSession: %v", err) + return } srtpReadStream, ssrc, err := srtpSession.AcceptStream() if err != nil { pc.log.Warnf("Failed to accept RTP %v", err) + return } @@ -1718,6 +1835,7 @@ func (pc *PeerConnection) undeclaredRTPMediaProcessor() { srtcpReadStream, err := srtcpSession.OpenReadStream(ssrc) if err != nil { pc.log.Warnf("Failed to open RTCP stream for %d: %v", ssrc, err) + return } @@ -1728,6 +1846,7 @@ func (pc *PeerConnection) undeclaredRTPMediaProcessor() { if err = srtcpReadStream.Close(); err != nil { pc.log.Warnf("Failed to close RTCP stream %v", err) } + continue } @@ -1735,12 +1854,14 @@ func (pc *PeerConnection) undeclaredRTPMediaProcessor() { if ssrc == 0 { go pc.handleNonMediaBandwidthProbe() + continue } if atomic.AddUint64(&simulcastRoutineCount, 1) >= simulcastMaxProbeRoutines { atomic.AddUint64(&simulcastRoutineCount, ^uint64(0)) pc.log.Warn(ErrSimulcastProbeOverflow.Error()) + continue } @@ -1764,12 +1885,14 @@ func (pc *PeerConnection) undeclaredRTCPMediaProcessor() { srtcpSession, err := pc.dtlsTransport.getSRTCPSession() if err != nil { pc.log.Warnf("undeclaredMediaProcessor failed to open SrtcpSession: %v", err) + return } stream, ssrc, err := srtcpSession.AcceptStream() if err != nil { pc.log.Warnf("Failed to accept RTCP %v", err) + return } pc.log.Warnf("Incoming unhandled RTCP ssrc(%d), OnTrack will not be fired", ssrc) @@ -1788,6 +1911,7 @@ func (pc *PeerConnection) RemoteDescription() *SessionDescription { if pc.pendingRemoteDescription != nil { return pc.pendingRemoteDescription } + return pc.currentRemoteDescription } @@ -1806,8 +1930,10 @@ func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error { if err != nil { if errors.Is(err, ice.ErrUnknownCandidateTyp) || errors.Is(err, ice.ErrDetermineNetworkType) { pc.log.Warnf("Discarding remote candidate: %s", err) + return nil } + return err } @@ -1827,10 +1953,11 @@ func (pc *PeerConnection) ICEConnectionState() 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. func (pc *PeerConnection) GetSenders() (result []*RTPSender) { pc.mu.Lock() defer pc.mu.Unlock() @@ -1840,10 +1967,11 @@ func (pc *PeerConnection) GetSenders() (result []*RTPSender) { result = append(result, sender) } } + return result } -// GetReceivers returns the RTPReceivers that are currently attached to this PeerConnection +// GetReceivers returns the RTPReceivers that are currently attached to this PeerConnection. func (pc *PeerConnection) GetReceivers() (receivers []*RTPReceiver) { pc.mu.Lock() defer pc.mu.Unlock() @@ -1853,10 +1981,11 @@ func (pc *PeerConnection) GetReceivers() (receivers []*RTPReceiver) { receivers = append(receivers, receiver) } } + return } -// GetTransceivers returns the RtpTransceiver that are currently attached to this PeerConnection +// GetTransceivers returns the RtpTransceiver that are currently attached to this PeerConnection. func (pc *PeerConnection) GetTransceivers() []*RTPTransceiver { pc.mu.Lock() defer pc.mu.Unlock() @@ -1864,7 +1993,9 @@ func (pc *PeerConnection) GetTransceivers() []*RTPTransceiver { return pc.rtpTransceivers } -// AddTrack adds a Track to the PeerConnection +// AddTrack adds a Track to the PeerConnection. +// +//nolint:cyclop func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error) { if pc.isClosed.get() { return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} @@ -1872,26 +2003,27 @@ func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error) { pc.mu.Lock() defer pc.mu.Unlock() - for _, t := range pc.rtpTransceivers { - currentDirection := t.getCurrentDirection() + for _, transceiver := range pc.rtpTransceivers { + currentDirection := transceiver.getCurrentDirection() // According to https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtrack, if the // transceiver can be reused only if it's currentDirection never be sendrecv or sendonly. // But that will cause sdp inflate. So we only check currentDirection's current value, // that's worked for all browsers. - if t.kind == track.Kind() && t.Sender() == nil && + if transceiver.kind == track.Kind() && transceiver.Sender() == nil && !(currentDirection == RTPTransceiverDirectionSendrecv || currentDirection == RTPTransceiverDirectionSendonly) { sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport) if err == nil { - err = t.SetSender(sender, track) + err = transceiver.SetSender(sender, track) if err != nil { _ = sender.Stop() - t.setSender(nil) + transceiver.setSender(nil) } } if err != nil { return nil, err } pc.onNegotiationNeeded() + return sender, nil } } @@ -1901,10 +2033,11 @@ func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error) { return nil, err } pc.addRTPTransceiver(transceiver) + return transceiver.Sender(), nil } -// RemoveTrack removes a Track from the PeerConnection +// RemoveTrack removes a Track from the PeerConnection. func (pc *PeerConnection) RemoveTrack(sender *RTPSender) (err error) { if pc.isClosed.get() { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} @@ -1916,6 +2049,7 @@ func (pc *PeerConnection) RemoveTrack(sender *RTPSender) (err error) { for _, t := range pc.rtpTransceivers { if t.Sender() == sender { transceiver = t + break } } @@ -1927,41 +2061,52 @@ func (pc *PeerConnection) RemoveTrack(sender *RTPSender) (err error) { pc.onNegotiationNeeded() } } + return } -func (pc *PeerConnection) newTransceiverFromTrack(direction RTPTransceiverDirection, track TrackLocal, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) { +//nolint:cyclop +func (pc *PeerConnection) newTransceiverFromTrack( + direction RTPTransceiverDirection, + track TrackLocal, + init ...RTPTransceiverInit, +) (t *RTPTransceiver, err error) { var ( - r *RTPReceiver - s *RTPSender + receiver *RTPReceiver + sender *RTPSender ) switch direction { case RTPTransceiverDirectionSendrecv: - r, err = pc.api.NewRTPReceiver(track.Kind(), pc.dtlsTransport) + receiver, err = pc.api.NewRTPReceiver(track.Kind(), pc.dtlsTransport) if err != nil { - return + return t, err } - s, err = pc.api.NewRTPSender(track, pc.dtlsTransport) + sender, err = pc.api.NewRTPSender(track, pc.dtlsTransport) case RTPTransceiverDirectionSendonly: - s, err = pc.api.NewRTPSender(track, pc.dtlsTransport) + sender, err = pc.api.NewRTPSender(track, pc.dtlsTransport) default: err = errPeerConnAddTransceiverFromTrackSupport } if err != nil { - return + return t, err } // Allow RTPTransceiverInit to override SSRC - if s != nil && len(s.trackEncodings) == 1 && + if sender != nil && len(sender.trackEncodings) == 1 && len(init) == 1 && len(init[0].SendEncodings) == 1 && init[0].SendEncodings[0].SSRC != 0 { - s.trackEncodings[0].ssrc = init[0].SendEncodings[0].SSRC + sender.trackEncodings[0].ssrc = init[0].SendEncodings[0].SSRC } - return newRTPTransceiver(r, s, direction, track.Kind(), pc.api), nil + return newRTPTransceiver(receiver, sender, direction, track.Kind(), pc.api), nil } // AddTransceiverFromKind Create a new RtpTransceiver and adds it to the set of transceivers. -func (pc *PeerConnection) AddTransceiverFromKind(kind RTPCodecType, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) { +// +//nolint:cyclop +func (pc *PeerConnection) AddTransceiverFromKind( + kind RTPCodecType, + init ...RTPTransceiverInit, +) (t *RTPTransceiver, err error) { if pc.isClosed.get() { return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } @@ -1998,11 +2143,15 @@ func (pc *PeerConnection) AddTransceiverFromKind(kind RTPCodecType, init ...RTPT pc.mu.Lock() pc.addRTPTransceiver(t) pc.mu.Unlock() + return t, nil } // AddTransceiverFromTrack Create a new RtpTransceiver(SendRecv or SendOnly) and add it to the set of transceivers. -func (pc *PeerConnection) AddTransceiverFromTrack(track TrackLocal, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) { +func (pc *PeerConnection) AddTransceiverFromTrack( + track TrackLocal, + init ...RTPTransceiverInit, +) (t *RTPTransceiver, err error) { if pc.isClosed.get() { return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } @@ -2020,12 +2169,15 @@ func (pc *PeerConnection) AddTransceiverFromTrack(track TrackLocal, init ...RTPT pc.addRTPTransceiver(t) pc.mu.Unlock() } + return } // CreateDataChannel creates a new DataChannel object with the given label // and optional DataChannelInit used to configure properties of the // underlying channel such as data reliability. +// +//nolint:cyclop func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelInit) (*DataChannel, error) { // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #2) if pc.isClosed.get() { @@ -2042,7 +2194,7 @@ func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelIn params.ID = options.ID } - if options != nil { + if options != nil { //nolint:nestif // Ordered indicates if data is allowed to be delivered out of order. The // default value of true, guarantees that data will be delivered in order. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #9) @@ -2076,27 +2228,27 @@ func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelIn } } - d, err := pc.api.newDataChannel(params, nil, pc.log) + dataChannel, err := pc.api.newDataChannel(params, nil, pc.log) if err != nil { return nil, err } // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #16) - if d.maxPacketLifeTime != nil && d.maxRetransmits != nil { + if dataChannel.maxPacketLifeTime != nil && dataChannel.maxRetransmits != nil { return nil, &rtcerr.TypeError{Err: ErrRetransmitsOrPacketLifeTime} } pc.sctpTransport.lock.Lock() - pc.sctpTransport.dataChannels = append(pc.sctpTransport.dataChannels, d) - if d.ID() != nil { - pc.sctpTransport.dataChannelIDsUsed[*d.ID()] = struct{}{} + pc.sctpTransport.dataChannels = append(pc.sctpTransport.dataChannels, dataChannel) + if dataChannel.ID() != nil { + pc.sctpTransport.dataChannelIDsUsed[*dataChannel.ID()] = struct{}{} } pc.sctpTransport.dataChannelsRequested++ pc.sctpTransport.lock.Unlock() // If SCTP already connected open all the channels if pc.sctpTransport.State() == SCTPTransportStateConnected { - if err = d.open(pc.sctpTransport); err != nil { + if err = dataChannel.open(pc.sctpTransport); err != nil { return nil, err } } @@ -2105,10 +2257,10 @@ func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelIn pc.onNegotiationNeeded() pc.mu.Unlock() - return d, nil + return dataChannel, nil } -// SetIdentityProvider is used to configure an identity provider to generate identity assertions +// SetIdentityProvider is used to configure an identity provider to generate identity assertions. func (pc *PeerConnection) SetIdentityProvider(string) error { return errPeerConnSetIdentityProviderNotImplemented } @@ -2117,6 +2269,7 @@ func (pc *PeerConnection) SetIdentityProvider(string) error { // packet is discarded. It also runs any configured interceptors. func (pc *PeerConnection) WriteRTCP(pkts []rtcp.Packet) error { _, err := pc.interceptorRTCPWriter.Write(pkts, make(interceptor.Attributes)) + return err } @@ -2136,7 +2289,7 @@ func (pc *PeerConnection) GracefulClose() error { return pc.close(true /* shouldGracefullyClose */) } -func (pc *PeerConnection) close(shouldGracefullyClose bool) error { +func (pc *PeerConnection) close(shouldGracefullyClose bool) error { //nolint:cyclop // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #1) // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #2) @@ -2164,6 +2317,7 @@ func (pc *PeerConnection) close(shouldGracefullyClose bool) error { // to happen and then return. if isAlreadyGracefullyClosingOrClosed { <-pc.isGracefulCloseDone + return nil } // Otherwise we need to go through the graceful closure flow once the @@ -2204,6 +2358,7 @@ func (pc *PeerConnection) close(shouldGracefullyClose bool) error { gracefulCloseErrors = append(gracefulCloseErrors, d.GracefulClose()) } pc.sctpTransport.lock.Unlock() + return gracefulCloseErrors } @@ -2217,10 +2372,10 @@ func (pc *PeerConnection) close(shouldGracefullyClose bool) error { // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #4) pc.mu.Lock() for _, t := range pc.rtpTransceivers { - closeErrs = append(closeErrs, t.Stop()) + closeErrs = append(closeErrs, t.Stop()) //nolint:makezero // todo fix } if nonMediaBandwidthProbe, ok := pc.nonMediaBandwidthProbe.Load().(*RTPReceiver); ok { - closeErrs = append(closeErrs, nonMediaBandwidthProbe.Stop()) + closeErrs = append(closeErrs, nonMediaBandwidthProbe.Stop()) //nolint:makezero // todo fix } pc.mu.Unlock() @@ -2233,32 +2388,32 @@ func (pc *PeerConnection) close(shouldGracefullyClose bool) error { // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #6) if pc.sctpTransport != nil { - closeErrs = append(closeErrs, pc.sctpTransport.Stop()) + closeErrs = append(closeErrs, pc.sctpTransport.Stop()) //nolint:makezero // todo fix } // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #7) - closeErrs = append(closeErrs, pc.dtlsTransport.Stop()) + closeErrs = append(closeErrs, pc.dtlsTransport.Stop()) //nolint:makezero // todo fix // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #8, #9, #10) if pc.iceTransport != nil && !shouldGracefullyClose { // we will stop gracefully in doGracefulCloseOps - closeErrs = append(closeErrs, pc.iceTransport.Stop()) + closeErrs = append(closeErrs, pc.iceTransport.Stop()) //nolint:makezero // todo fix } // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #11) pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State()) - closeErrs = append(closeErrs, doGracefulCloseOps()...) + closeErrs = append(closeErrs, doGracefulCloseOps()...) //nolint:makezero // todo fix // Interceptor closes at the end to prevent Bind from being called after interceptor is closed - closeErrs = append(closeErrs, pc.api.interceptor.Close()) + closeErrs = append(closeErrs, pc.api.interceptor.Close()) //nolint:makezero // todo fix return util.FlattenErrs(closeErrs) } // addRTPTransceiver appends t into rtpTransceivers // and fires onNegotiationNeeded; -// caller of this method should hold `pc.mu` lock +// caller of this method should hold `pc.mu` lock. func (pc *PeerConnection) addRTPTransceiver(t *RTPTransceiver) { pc.rtpTransceivers = append(pc.rtpTransceivers, t) pc.onNegotiationNeeded() @@ -2275,6 +2430,7 @@ func (pc *PeerConnection) CurrentLocalDescription() *SessionDescription { localDescription := pc.currentLocalDescription iceGather := pc.iceGatherer iceGatheringState := pc.ICEGatheringState() + return populateLocalCandidates(localDescription, iceGather, iceGatheringState) } @@ -2289,6 +2445,7 @@ func (pc *PeerConnection) PendingLocalDescription() *SessionDescription { localDescription := pc.pendingLocalDescription iceGather := pc.iceGatherer iceGatheringState := pc.ICEGatheringState() + return populateLocalCandidates(localDescription, iceGather, iceGatheringState) } @@ -2344,10 +2501,11 @@ func (pc *PeerConnection) ConnectionState() 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. func (pc *PeerConnection) GetStats() StatsReport { var ( dataChannelsAccepted uint32 @@ -2408,8 +2566,12 @@ func (pc *PeerConnection) GetStats() StatsReport { return statsCollector.Ready() } -// Start all transports. PeerConnection now has enough state -func (pc *PeerConnection) startTransports(iceRole ICERole, dtlsRole DTLSRole, remoteUfrag, remotePwd, fingerprint, fingerprintHash string) { +// Start all transports. PeerConnection now has enough state. +func (pc *PeerConnection) startTransports( + iceRole ICERole, + dtlsRole DTLSRole, + remoteUfrag, remotePwd, fingerprint, fingerprintHash string, +) { // Start the ice transport err := pc.iceTransport.Start( pc.iceGatherer, @@ -2422,6 +2584,7 @@ func (pc *PeerConnection) startTransports(iceRole ICERole, dtlsRole DTLSRole, re ) if err != nil { pc.log.Warnf("Failed to start manager: %s", err) + return } @@ -2446,12 +2609,17 @@ func (pc *PeerConnection) startTransports(iceRole ICERole, dtlsRole DTLSRole, re pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State()) if err != nil { pc.log.Warnf("Failed to start manager: %s", err) + return } } // nolint: gocognit -func (pc *PeerConnection) startRTP(isRenegotiation bool, remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) { +func (pc *PeerConnection) startRTP( + isRenegotiation bool, + remoteDesc *SessionDescription, + currentTransceivers []*RTPTransceiver, +) { if !isRenegotiation { pc.undeclaredMediaProcessor() } @@ -2463,13 +2631,18 @@ func (pc *PeerConnection) startRTP(isRenegotiation bool, remoteDesc *SessionDesc } // generateUnmatchedSDP generates an SDP that doesn't take remote state into account -// This is used for the initial call for CreateOffer -func (pc *PeerConnection) generateUnmatchedSDP(transceivers []*RTPTransceiver, useIdentity bool) (*sdp.SessionDescription, error) { - d, err := sdp.NewJSEPSessionDescription(useIdentity) +// This is used for the initial call for CreateOffer. +// +//nolint:cyclop +func (pc *PeerConnection) generateUnmatchedSDP( + transceivers []*RTPTransceiver, + useIdentity bool, +) (*sdp.SessionDescription, error) { + desc, err := sdp.NewJSEPSessionDescription(useIdentity) if err != nil { return nil, err } - d.Attributes = append(d.Attributes, sdp.Attribute{Key: sdp.AttrKeyMsidSemantic, Value: "WMS*"}) + desc.Attributes = append(desc.Attributes, sdp.Attribute{Key: sdp.AttrKeyMsidSemantic, Value: "WMS*"}) iceParams, err := pc.iceGatherer.GetLocalParameters() if err != nil { @@ -2488,7 +2661,7 @@ func (pc *PeerConnection) generateUnmatchedSDP(transceivers []*RTPTransceiver, u pc.sctpTransport.lock.Lock() defer pc.sctpTransport.lock.Unlock() - if isPlanB { + if isPlanB { //nolint:nestif video := make([]*RTPTransceiver, 0) audio := make([]*RTPTransceiver, 0) @@ -2531,18 +2704,37 @@ func (pc *PeerConnection) generateUnmatchedSDP(transceivers []*RTPTransceiver, u return nil, err } - return populateSDP(d, isPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, true, pc.api.mediaEngine, connectionRoleFromDtlsRole(defaultDtlsRoleOffer), candidates, iceParams, mediaSections, pc.ICEGatheringState(), nil) + return populateSDP( + desc, + isPlanB, + dtlsFingerprints, + pc.api.settingEngine.sdpMediaLevelFingerprints, + pc.api.settingEngine.candidates.ICELite, + true, + pc.api.mediaEngine, + connectionRoleFromDtlsRole(defaultDtlsRoleOffer), + candidates, + iceParams, + mediaSections, + pc.ICEGatheringState(), + nil, + ) } // generateMatchedSDP generates a SDP and takes the remote state into account // this is used everytime we have a RemoteDescription -// nolint: gocyclo -func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, useIdentity bool, includeUnmatched bool, connectionRole sdp.ConnectionRole) (*sdp.SessionDescription, error) { //nolint:gocognit - d, err := sdp.NewJSEPSessionDescription(useIdentity) +// +//nolint:gocognit,gocyclo,cyclop +func (pc *PeerConnection) generateMatchedSDP( + transceivers []*RTPTransceiver, + useIdentity, includeUnmatched bool, + connectionRole sdp.ConnectionRole, +) (*sdp.SessionDescription, error) { + desc, err := sdp.NewJSEPSessionDescription(useIdentity) if err != nil { return nil, err } - d.Attributes = append(d.Attributes, sdp.Attribute{Key: sdp.AttrKeyMsidSemantic, Value: "WMS*"}) + desc.Attributes = append(desc.Attributes, sdp.Attribute{Key: sdp.AttrKeyMsidSemantic, Value: "WMS*"}) iceParams, err := pc.iceGatherer.GetLocalParameters() if err != nil { @@ -2554,7 +2746,7 @@ func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, use return nil, err } - var t *RTPTransceiver + var transceiver *RTPTransceiver remoteDescription := pc.currentRemoteDescription if pc.pendingRemoteDescription != nil { remoteDescription = pc.pendingRemoteDescription @@ -2578,6 +2770,7 @@ func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, use if media.MediaName.Media == mediaSectionApplication { mediaSections = append(mediaSections, mediaSection{id: midValue, data: true}) alreadyHaveApplicationMediaSection = true + continue } @@ -2592,49 +2785,60 @@ func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, use switch { case sdpSemantics == SDPSemanticsPlanB || sdpSemantics == SDPSemanticsUnifiedPlanWithFallback && detectedPlanB: if !detectedPlanB { - return nil, &rtcerr.TypeError{Err: fmt.Errorf("%w: Expected PlanB, but RemoteDescription is UnifiedPlan", ErrIncorrectSDPSemantics)} + return nil, &rtcerr.TypeError{ + Err: fmt.Errorf("%w: Expected PlanB, but RemoteDescription is UnifiedPlan", ErrIncorrectSDPSemantics), + } } // If we're responding to a plan-b offer, then we should try to fill up this // media entry with all matching local transceivers mediaTransceivers := []*RTPTransceiver{} for { // keep going until we can't get any more - t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers) - if t == nil { + transceiver, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers) + if transceiver == nil { if len(mediaTransceivers) == 0 { - t = &RTPTransceiver{kind: kind, api: pc.api, codecs: pc.api.mediaEngine.getCodecsByKind(kind)} - t.setDirection(RTPTransceiverDirectionInactive) - mediaTransceivers = append(mediaTransceivers, t) + transceiver = &RTPTransceiver{kind: kind, api: pc.api, codecs: pc.api.mediaEngine.getCodecsByKind(kind)} + transceiver.setDirection(RTPTransceiverDirectionInactive) + mediaTransceivers = append(mediaTransceivers, transceiver) } + break } - if sender := t.Sender(); sender != nil { + if sender := transceiver.Sender(); sender != nil { sender.setNegotiated() } - mediaTransceivers = append(mediaTransceivers, t) + mediaTransceivers = append(mediaTransceivers, transceiver) } mediaSections = append(mediaSections, mediaSection{id: midValue, transceivers: mediaTransceivers}) case sdpSemantics == SDPSemanticsUnifiedPlan || sdpSemantics == SDPSemanticsUnifiedPlanWithFallback: if detectedPlanB { - return nil, &rtcerr.TypeError{Err: fmt.Errorf("%w: Expected UnifiedPlan, but RemoteDescription is PlanB", ErrIncorrectSDPSemantics)} + return nil, &rtcerr.TypeError{ + Err: fmt.Errorf( + "%w: Expected UnifiedPlan, but RemoteDescription is PlanB", + ErrIncorrectSDPSemantics, + ), + } } - t, localTransceivers = findByMid(midValue, localTransceivers) - if t == nil { + transceiver, localTransceivers = findByMid(midValue, localTransceivers) + if transceiver == nil { return nil, fmt.Errorf("%w: %q", errPeerConnTranscieverMidNil, midValue) } - if sender := t.Sender(); sender != nil { + if sender := transceiver.Sender(); sender != nil { sender.setNegotiated() } - mediaTransceivers := []*RTPTransceiver{t} + mediaTransceivers := []*RTPTransceiver{transceiver} extensions, _ := rtpExtensionsFromMediaDescription(media) - mediaSections = append(mediaSections, mediaSection{id: midValue, transceivers: mediaTransceivers, matchExtensions: extensions, rids: getRids(media)}) + mediaSections = append( + mediaSections, + mediaSection{id: midValue, transceivers: mediaTransceivers, matchExtensions: extensions, rids: getRids(media)}, + ) } } var bundleGroup *string // If we are offering also include unmatched local transceivers - if includeUnmatched { + if includeUnmatched { //nolint:nestif if !detectedPlanB { for _, t := range localTransceivers { if sender := t.Sender(); sender != nil { @@ -2666,7 +2870,21 @@ func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, use return nil, err } - return populateSDP(d, detectedPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, isExtmapAllowMixed, pc.api.mediaEngine, connectionRole, candidates, iceParams, mediaSections, pc.ICEGatheringState(), bundleGroup) + return populateSDP( + desc, + detectedPlanB, + dtlsFingerprints, + pc.api.settingEngine.sdpMediaLevelFingerprints, + pc.api.settingEngine.candidates.ICELite, + isExtmapAllowMixed, + pc.api.mediaEngine, + connectionRole, + candidates, + iceParams, + mediaSections, + pc.ICEGatheringState(), + bundleGroup, + ) } func (pc *PeerConnection) setGatherCompleteHandler(handler func()) { diff --git a/vendor/github.com/pion/webrtc/v4/peerconnectionstate.go b/vendor/github.com/pion/webrtc/v4/peerconnectionstate.go index 0ff24afca0..677cfa95ce 100644 --- a/vendor/github.com/pion/webrtc/v4/peerconnectionstate.go +++ b/vendor/github.com/pion/webrtc/v4/peerconnectionstate.go @@ -7,7 +7,7 @@ package webrtc type PeerConnectionState int const ( - // PeerConnectionStateUnknown is the enum's zero-value + // PeerConnectionStateUnknown is the enum's zero-value. PeerConnectionStateUnknown PeerConnectionState = iota // PeerConnectionStateNew indicates that any of the ICETransports or diff --git a/vendor/github.com/pion/webrtc/v4/pkg/media/media.go b/vendor/github.com/pion/webrtc/v4/pkg/media/media.go index ab07e31897..f8ee5e3829 100644 --- a/vendor/github.com/pion/webrtc/v4/pkg/media/media.go +++ b/vendor/github.com/pion/webrtc/v4/pkg/media/media.go @@ -10,7 +10,7 @@ import ( "github.com/pion/rtp" ) -// A Sample contains encoded media and timing information +// A Sample contains encoded media and timing information. type Sample struct { Data []byte Timestamp time.Time @@ -25,7 +25,7 @@ type Sample struct { } // Writer defines an interface to handle -// the creation of media files +// the creation of media files. type Writer interface { // Add the content of an RTP packet to the media WriteRTP(packet *rtp.Packet) error diff --git a/vendor/github.com/pion/webrtc/v4/rtcpmuxpolicy.go b/vendor/github.com/pion/webrtc/v4/rtcpmuxpolicy.go index ec84ea9132..d4f7f476d4 100644 --- a/vendor/github.com/pion/webrtc/v4/rtcpmuxpolicy.go +++ b/vendor/github.com/pion/webrtc/v4/rtcpmuxpolicy.go @@ -12,7 +12,7 @@ import ( type RTCPMuxPolicy int const ( - // RTCPMuxPolicyUnknown is the enum's zero-value + // RTCPMuxPolicyUnknown is the enum's zero-value. RTCPMuxPolicyUnknown RTCPMuxPolicy = iota // RTCPMuxPolicyNegotiate indicates to gather ICE candidates for both @@ -55,7 +55,7 @@ func (t RTCPMuxPolicy) String() string { } } -// UnmarshalJSON parses the JSON-encoded data and stores the result +// UnmarshalJSON parses the JSON-encoded data and stores the result. func (t *RTCPMuxPolicy) UnmarshalJSON(b []byte) error { var val string if err := json.Unmarshal(b, &val); err != nil { @@ -63,10 +63,11 @@ func (t *RTCPMuxPolicy) UnmarshalJSON(b []byte) error { } *t = newRTCPMuxPolicy(val) + return nil } -// MarshalJSON returns the JSON encoding +// MarshalJSON returns the JSON encoding. func (t RTCPMuxPolicy) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } diff --git a/vendor/github.com/pion/webrtc/v4/rtpcodec.go b/vendor/github.com/pion/webrtc/v4/rtpcodec.go index a414d51050..cc079280ec 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpcodec.go +++ b/vendor/github.com/pion/webrtc/v4/rtpcodec.go @@ -10,17 +10,17 @@ import ( "github.com/pion/webrtc/v4/internal/fmtp" ) -// RTPCodecType determines the type of a codec +// RTPCodecType determines the type of a codec. type RTPCodecType int const ( - // RTPCodecTypeUnknown is the enum's zero-value + // RTPCodecTypeUnknown is the enum's zero-value. RTPCodecTypeUnknown RTPCodecType = iota - // RTPCodecTypeAudio indicates this is an audio codec + // RTPCodecTypeAudio indicates this is an audio codec. RTPCodecTypeAudio - // RTPCodecTypeVideo indicates this is a video codec + // RTPCodecTypeVideo indicates this is a video codec. RTPCodecTypeVideo ) @@ -35,7 +35,7 @@ func (t RTPCodecType) String() string { } } -// NewRTPCodecType creates a RTPCodecType from a string +// NewRTPCodecType creates a RTPCodecType from a string. func NewRTPCodecType(r string) RTPCodecType { switch { case strings.EqualFold(r, RTPCodecTypeAudio.String()): @@ -103,8 +103,11 @@ const ( // Do a fuzzy find for a codec in the list of codecs // Used for lookup up a codec in an existing list to find a match -// Returns codecMatchExact, codecMatchPartial, or codecMatchNone -func codecParametersFuzzySearch(needle RTPCodecParameters, haystack []RTPCodecParameters) (RTPCodecParameters, codecMatchType) { +// Returns codecMatchExact, codecMatchPartial, or codecMatchNone. +func codecParametersFuzzySearch( + needle RTPCodecParameters, + haystack []RTPCodecParameters, +) (RTPCodecParameters, codecMatchType) { needleFmtp := fmtp.Parse(needle.RTPCodecCapability.MimeType, needle.RTPCodecCapability.SDPFmtpLine) // First attempt to match on MimeType + SDPFmtpLine @@ -125,7 +128,7 @@ func codecParametersFuzzySearch(needle RTPCodecParameters, haystack []RTPCodecPa return RTPCodecParameters{}, codecMatchNone } -// Given a CodecParameters find the RTX CodecParameters if one exists +// Given a CodecParameters find the RTX CodecParameters if one exists. func findRTXPayloadType(needle PayloadType, haystack []RTPCodecParameters) PayloadType { aptStr := fmt.Sprintf("apt=%d", needle) for _, c := range haystack { @@ -142,6 +145,7 @@ func rtcpFeedbackIntersection(a, b []RTCPFeedback) (out []RTCPFeedback) { for _, bFeeback := range b { if aFeedback.Type == bFeeback.Type && aFeedback.Parameter == bFeeback.Parameter { out = append(out, aFeedback) + break } } diff --git a/vendor/github.com/pion/webrtc/v4/rtpreceiveparameters.go b/vendor/github.com/pion/webrtc/v4/rtpreceiveparameters.go index 26a667616b..a07bbc6c9e 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpreceiveparameters.go +++ b/vendor/github.com/pion/webrtc/v4/rtpreceiveparameters.go @@ -3,7 +3,7 @@ package webrtc -// RTPReceiveParameters contains the RTP stack settings used by receivers +// RTPReceiveParameters contains the RTP stack settings used by receivers. type RTPReceiveParameters struct { Encodings []RTPDecodingParameters } diff --git a/vendor/github.com/pion/webrtc/v4/rtpreceiver.go b/vendor/github.com/pion/webrtc/v4/rtpreceiver.go index ba1afb5517..b4757636f7 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpreceiver.go +++ b/vendor/github.com/pion/webrtc/v4/rtpreceiver.go @@ -20,7 +20,7 @@ import ( ) // trackStreams maintains a mapping of RTP/RTCP streams to a specific track -// a RTPReceiver may contain multiple streams if we are dealing with Simulcast +// a RTPReceiver may contain multiple streams if we are dealing with Simulcast. type trackStreams struct { track *TrackRemote @@ -54,7 +54,7 @@ func (p *rtxPacketWithAttributes) release() { } } -// RTPReceiver allows an application to inspect the receipt of a TrackRemote +// RTPReceiver allows an application to inspect the receipt of a TrackRemote. type RTPReceiver struct { kind RTPCodecType transport *DTLSTransport @@ -72,7 +72,7 @@ type RTPReceiver struct { rtxPool sync.Pool } -// NewRTPReceiver constructs a new RTPReceiver +// NewRTPReceiver constructs a new RTPReceiver. func (api *API) NewRTPReceiver(kind RTPCodecType, transport *DTLSTransport) (*RTPReceiver, error) { if transport == nil { return nil, errRTPReceiverDTLSTransportNil @@ -100,18 +100,23 @@ func (r *RTPReceiver) setRTPTransceiver(tr *RTPTransceiver) { } // Transport returns the currently-configured *DTLSTransport or nil -// if one has not yet been configured +// if one has not yet been configured. func (r *RTPReceiver) Transport() *DTLSTransport { r.mu.RLock() defer r.mu.RUnlock() + return r.transport } func (r *RTPReceiver) getParameters() RTPParameters { - parameters := r.api.mediaEngine.getRTPParametersByKind(r.kind, []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly}) + parameters := r.api.mediaEngine.getRTPParametersByKind( + r.kind, + []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly}, + ) if r.tr != nil { parameters.Codecs = r.tr.getCodecs() } + return parameters } @@ -120,10 +125,11 @@ func (r *RTPReceiver) getParameters() RTPParameters { func (r *RTPReceiver) GetParameters() RTPParameters { r.mu.RLock() defer r.mu.RUnlock() + return r.getParameters() } -// Track returns the RtpTransceiver TrackRemote +// Track returns the RtpTransceiver TrackRemote. func (r *RTPReceiver) Track() *TrackRemote { r.mu.RLock() defer r.mu.RUnlock() @@ -131,11 +137,12 @@ func (r *RTPReceiver) Track() *TrackRemote { if len(r.tracks) != 1 { return nil } + return r.tracks[0].track } // Tracks returns the RtpTransceiver tracks -// A RTPReceiver to support Simulcast may now have multiple tracks +// A RTPReceiver to support Simulcast may now have multiple tracks. func (r *RTPReceiver) Tracks() []*TrackRemote { r.mu.RLock() defer r.mu.RUnlock() @@ -144,11 +151,12 @@ func (r *RTPReceiver) Tracks() []*TrackRemote { for i := range r.tracks { tracks = append(tracks, r.tracks[i].track) } + return tracks } // RTPTransceiver returns the RTPTransceiver this -// RTPReceiver belongs too, or nil if none +// RTPReceiver belongs too, or nil if none. func (r *RTPReceiver) RTPTransceiver() *RTPTransceiver { r.mu.Lock() defer r.mu.Unlock() @@ -156,7 +164,7 @@ func (r *RTPReceiver) RTPTransceiver() *RTPTransceiver { return r.tr } -// configureReceive initialize the track +// configureReceive initialize the track. func (r *RTPReceiver) configureReceive(parameters RTPReceiveParameters) { r.mu.Lock() defer r.mu.Unlock() @@ -176,8 +184,8 @@ func (r *RTPReceiver) configureReceive(parameters RTPReceiveParameters) { } } -// startReceive starts all the transports -func (r *RTPReceiver) startReceive(parameters RTPReceiveParameters) error { +// startReceive starts all the transports. +func (r *RTPReceiver) startReceive(parameters RTPReceiveParameters) error { //nolint:cyclop r.mu.Lock() defer r.mu.Unlock() select { @@ -199,31 +207,51 @@ func (r *RTPReceiver) startReceive(parameters RTPReceiveParameters) error { continue } - var t *trackStreams + var streams *trackStreams for idx, ts := range r.tracks { if ts.track != nil && ts.track.SSRC() == parameters.Encodings[i].SSRC { - t = &r.tracks[idx] + streams = &r.tracks[idx] + break } } - if t == nil { + if streams == nil { return fmt.Errorf("%w: %d", errRTPReceiverWithSSRCTrackStreamNotFound, parameters.Encodings[i].SSRC) } - t.streamInfo = createStreamInfo("", parameters.Encodings[i].SSRC, 0, 0, 0, 0, 0, codec, globalParams.HeaderExtensions) + streams.streamInfo = createStreamInfo( + "", + parameters.Encodings[i].SSRC, + 0, 0, 0, 0, 0, + codec, + globalParams.HeaderExtensions, + ) var err error - if t.rtpReadStream, t.rtpInterceptor, t.rtcpReadStream, t.rtcpInterceptor, err = r.transport.streamsForSSRC(parameters.Encodings[i].SSRC, *t.streamInfo); err != nil { + + //nolint:lll // # TODO refactor + if streams.rtpReadStream, streams.rtpInterceptor, streams.rtcpReadStream, streams.rtcpInterceptor, err = r.transport.streamsForSSRC(parameters.Encodings[i].SSRC, *streams.streamInfo); err != nil { return err } if rtxSsrc := parameters.Encodings[i].RTX.SSRC; rtxSsrc != 0 { streamInfo := createStreamInfo("", rtxSsrc, 0, 0, 0, 0, 0, codec, globalParams.HeaderExtensions) - rtpReadStream, rtpInterceptor, rtcpReadStream, rtcpInterceptor, err := r.transport.streamsForSSRC(rtxSsrc, *streamInfo) + rtpReadStream, rtpInterceptor, rtcpReadStream, rtcpInterceptor, err := r.transport.streamsForSSRC( + rtxSsrc, + *streamInfo, + ) if err != nil { return err } - if err = r.receiveForRtx(rtxSsrc, "", streamInfo, rtpReadStream, rtpInterceptor, rtcpReadStream, rtcpInterceptor); err != nil { + if err = r.receiveForRtx( + rtxSsrc, + "", + streamInfo, + rtpReadStream, + rtpInterceptor, + rtcpReadStream, + rtcpInterceptor, + ); err != nil { return err } } @@ -232,13 +260,14 @@ func (r *RTPReceiver) startReceive(parameters RTPReceiveParameters) error { return nil } -// Receive initialize the track and starts all the transports +// Receive initialize the track and starts all the transports. func (r *RTPReceiver) Receive(parameters RTPReceiveParameters) error { r.configureReceive(parameters) + return r.startReceive(parameters) } -// Read reads incoming RTCP for this RTPReceiver +// Read reads incoming RTCP for this RTPReceiver. func (r *RTPReceiver) Read(b []byte) (n int, a interceptor.Attributes, err error) { select { case <-r.received: @@ -248,7 +277,7 @@ func (r *RTPReceiver) Read(b []byte) (n int, a interceptor.Attributes, err error } } -// ReadSimulcast reads incoming RTCP for this RTPReceiver for given rid +// ReadSimulcast reads incoming RTCP for this RTPReceiver for given rid. func (r *RTPReceiver) ReadSimulcast(b []byte, rid string) (n int, a interceptor.Attributes, err error) { select { case <-r.received: @@ -265,6 +294,7 @@ func (r *RTPReceiver) ReadSimulcast(b []byte, rid string) (n int, a interceptor. if rtcpInterceptor == nil { return 0, nil, fmt.Errorf("%w: %s", errRTPReceiverForRIDTrackStreamNotFound, rid) } + return rtcpInterceptor.Read(b, a) case <-r.closed: @@ -289,7 +319,7 @@ func (r *RTPReceiver) ReadRTCP() ([]rtcp.Packet, interceptor.Attributes, error) return pkts, attributes, nil } -// ReadSimulcastRTCP is a convenience method that wraps ReadSimulcast and unmarshal for you +// ReadSimulcastRTCP is a convenience method that wraps ReadSimulcast and unmarshal for you. func (r *RTPReceiver) ReadSimulcastRTCP(rid string) ([]rtcp.Packet, interceptor.Attributes, error) { b := make([]byte, r.api.settingEngine.getReceiveMTU()) i, attributes, err := r.ReadSimulcast(b, rid) @@ -298,6 +328,7 @@ func (r *RTPReceiver) ReadSimulcastRTCP(rid string) ([]rtcp.Packet, interceptor. } pkts, err := rtcp.Unmarshal(b[:i]) + return pkts, attributes, err } @@ -310,8 +341,8 @@ func (r *RTPReceiver) haveReceived() bool { } } -// Stop irreversibly stops the RTPReceiver -func (r *RTPReceiver) Stop() error { +// Stop irreversibly stops the RTPReceiver. +func (r *RTPReceiver) Stop() error { //nolint:cyclop r.mu.Lock() defer r.mu.Unlock() var err error @@ -357,6 +388,7 @@ func (r *RTPReceiver) Stop() error { } close(r.closed) + return err } @@ -366,10 +398,11 @@ func (r *RTPReceiver) streamsForTrack(t *TrackRemote) *trackStreams { return &r.tracks[i] } } + return nil } -// readRTP should only be called by a track, this only exists so we can keep state in one place +// readRTP should only be called by a track, this only exists so we can keep state in one place. func (r *RTPReceiver) readRTP(b []byte, reader *TrackRemote) (n int, a interceptor.Attributes, err error) { <-r.received if t := r.streamsForTrack(reader); t != nil { @@ -380,8 +413,16 @@ func (r *RTPReceiver) readRTP(b []byte, reader *TrackRemote) (n int, a intercept } // receiveForRid is the sibling of Receive expect for RIDs instead of SSRCs -// It populates all the internal state for the given RID -func (r *RTPReceiver) receiveForRid(rid string, params RTPParameters, streamInfo *interceptor.StreamInfo, rtpReadStream *srtp.ReadStreamSRTP, rtpInterceptor interceptor.RTPReader, rtcpReadStream *srtp.ReadStreamSRTCP, rtcpInterceptor interceptor.RTCPReader) (*TrackRemote, error) { +// It populates all the internal state for the given RID. +func (r *RTPReceiver) receiveForRid( + rid string, + params RTPParameters, + streamInfo *interceptor.StreamInfo, + rtpReadStream *srtp.ReadStreamSRTP, + rtpInterceptor interceptor.RTPReader, + rtcpReadStream *srtp.ReadStreamSRTCP, + rtcpInterceptor interceptor.RTCPReader, +) (*TrackRemote, error) { r.mu.Lock() defer r.mu.Unlock() @@ -407,8 +448,18 @@ func (r *RTPReceiver) receiveForRid(rid string, params RTPParameters, streamInfo return nil, fmt.Errorf("%w: %s", errRTPReceiverForRIDTrackStreamNotFound, rid) } -// receiveForRtx starts a routine that processes the repair stream -func (r *RTPReceiver) receiveForRtx(ssrc SSRC, rsid string, streamInfo *interceptor.StreamInfo, rtpReadStream *srtp.ReadStreamSRTP, rtpInterceptor interceptor.RTPReader, rtcpReadStream *srtp.ReadStreamSRTCP, rtcpInterceptor interceptor.RTCPReader) error { +// receiveForRtx starts a routine that processes the repair stream. +// +//nolint:cyclop +func (r *RTPReceiver) receiveForRtx( + ssrc SSRC, + rsid string, + streamInfo *interceptor.StreamInfo, + rtpReadStream *srtp.ReadStreamSRTP, + rtpInterceptor interceptor.RTPReader, + rtcpReadStream *srtp.ReadStreamSRTCP, + rtcpInterceptor interceptor.RTCPReader, +) error { var track *trackStreams if ssrc != 0 && len(r.tracks) == 1 { track = &r.tracks[0] @@ -419,6 +470,7 @@ func (r *RTPReceiver) receiveForRtx(ssrc SSRC, rsid string, streamInfo *intercep if track.track.RtxSSRC() == 0 { track.track.setRtxSSRC(SSRC(streamInfo.SSRC)) } + break } } @@ -441,6 +493,7 @@ func (r *RTPReceiver) receiveForRtx(ssrc SSRC, rsid string, streamInfo *intercep i, attributes, err := track.repairInterceptor.Read(b, nil) if err != nil { r.rtxPool.Put(b) // nolint:staticcheck + return } @@ -462,6 +515,7 @@ func (r *RTPReceiver) receiveForRtx(ssrc SSRC, rsid string, streamInfo *intercep if i-int(headerLength)-paddingLength < 2 { // BWE probe packet, ignore r.rtxPool.Put(b) // nolint:staticcheck + continue } @@ -481,6 +535,7 @@ func (r *RTPReceiver) receiveForRtx(ssrc SSRC, rsid string, streamInfo *intercep select { case <-r.closed: r.rtxPool.Put(b) // nolint:staticcheck + return case track.repairStreamChannel <- rtxPacketWithAttributes{pkt: b[:i-2], attributes: attributes, pool: &r.rtxPool}: default: @@ -488,6 +543,7 @@ func (r *RTPReceiver) receiveForRtx(ssrc SSRC, rsid string, streamInfo *intercep } } }() + return nil } @@ -499,7 +555,8 @@ func (r *RTPReceiver) SetReadDeadline(t time.Time) error { return r.tracks[0].rtcpReadStream.SetReadDeadline(t) } -// SetReadDeadlineSimulcast sets the max amount of time the RTCP stream for a given rid will block before returning. 0 is forever. +// SetReadDeadlineSimulcast sets the max amount of time the RTCP stream for a given rid will block before returning. +// 0 is forever. func (r *RTPReceiver) SetReadDeadlineSimulcast(deadline time.Time, rid string) error { r.mu.RLock() defer r.mu.RUnlock() @@ -509,11 +566,12 @@ func (r *RTPReceiver) SetReadDeadlineSimulcast(deadline time.Time, rid string) e return t.rtcpReadStream.SetReadDeadline(deadline) } } + return fmt.Errorf("%w: %s", errRTPReceiverForRIDTrackStreamNotFound, rid) } // setRTPReadDeadline sets the max amount of time the RTP stream will block before returning. 0 is forever. -// This should be fired by calling SetReadDeadline on the TrackRemote +// This should be fired by calling SetReadDeadline on the TrackRemote. func (r *RTPReceiver) setRTPReadDeadline(deadline time.Time, reader *TrackRemote) error { r.mu.RLock() defer r.mu.RUnlock() @@ -521,10 +579,11 @@ func (r *RTPReceiver) setRTPReadDeadline(deadline time.Time, reader *TrackRemote if t := r.streamsForTrack(reader); t != nil { return t.rtpReadStream.SetReadDeadline(deadline) } + return fmt.Errorf("%w: %d", errRTPReceiverWithSSRCTrackStreamNotFound, reader.SSRC()) } -// readRTX returns an RTX packet if one is available on the RTX track, otherwise returns nil +// readRTX returns an RTX packet if one is available on the RTX track, otherwise returns nil. func (r *RTPReceiver) readRTX(reader *TrackRemote) *rtxPacketWithAttributes { if !reader.HasRTX() { return nil @@ -543,5 +602,6 @@ func (r *RTPReceiver) readRTX(reader *TrackRemote) *rtxPacketWithAttributes { default: } } + return nil } diff --git a/vendor/github.com/pion/webrtc/v4/rtpreceiver_js.go b/vendor/github.com/pion/webrtc/v4/rtpreceiver_js.go index 44cef72d14..af82a6cb3a 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpreceiver_js.go +++ b/vendor/github.com/pion/webrtc/v4/rtpreceiver_js.go @@ -13,3 +13,8 @@ type RTPReceiver struct { // Pointer to the underlying JavaScript RTCRTPReceiver object. underlying js.Value } + +// JSValue returns the underlying RTCRtpReceiver +func (r *RTPReceiver) JSValue() js.Value { + return r.underlying +} \ No newline at end of file diff --git a/vendor/github.com/pion/webrtc/v4/rtpsender.go b/vendor/github.com/pion/webrtc/v4/rtpsender.go index 3a59761921..2052274149 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpsender.go +++ b/vendor/github.com/pion/webrtc/v4/rtpsender.go @@ -32,7 +32,7 @@ type trackEncoding struct { ssrc, ssrcRTX, ssrcFEC SSRC } -// RTPSender allows an application to control how a given Track is encoded and transmitted to a remote peer +// RTPSender allows an application to control how a given Track is encoded and transmitted to a remote peer. type RTPSender struct { trackEncodings []*trackEncoding @@ -57,7 +57,7 @@ type RTPSender struct { sendCalled, stopCalled chan struct{} } -// NewRTPSender constructs a new RTPSender +// NewRTPSender constructs a new RTPSender. func (api *API) NewRTPSender(track TrackLocal, transport *DTLSTransport) (*RTPSender, error) { if track == nil { return nil, errRTPSenderTrackNil @@ -87,6 +87,7 @@ func (api *API) NewRTPSender(track TrackLocal, transport *DTLSTransport) (*RTPSe func (r *RTPSender) isNegotiated() bool { r.mu.RLock() defer r.mu.RUnlock() + return r.negotiated } @@ -103,10 +104,11 @@ func (r *RTPSender) setRTPTransceiver(rtpTransceiver *RTPTransceiver) { } // Transport returns the currently-configured *DTLSTransport or nil -// if one has not yet been configured +// if one has not yet been configured. func (r *RTPSender) Transport() *DTLSTransport { r.mu.RLock() defer r.mu.RUnlock() + return r.transport } @@ -144,11 +146,12 @@ func (r *RTPSender) GetParameters() RTPSendParameters { } else { sendParameters.Codecs = r.api.mediaEngine.getCodecsByKind(r.kind) } + return sendParameters } // AddEncoding adds an encoding to RTPSender. Used by simulcast senders. -func (r *RTPSender) AddEncoding(track TrackLocal) error { +func (r *RTPSender) AddEncoding(track TrackLocal) error { //nolint:cyclop r.mu.Lock() defer r.mu.Unlock() @@ -191,6 +194,7 @@ func (r *RTPSender) AddEncoding(track TrackLocal) error { } r.addEncoding(track) + return nil } @@ -211,7 +215,7 @@ func (r *RTPSender) addEncoding(track TrackLocal) { r.trackEncodings = append(r.trackEncodings, trackEncoding) } -// Track returns the RTCRtpTransceiver track, or nil +// Track returns the RTCRtpTransceiver track, or nil. func (r *RTPSender) Track() TrackLocal { r.mu.RLock() defer r.mu.RUnlock() @@ -226,7 +230,7 @@ func (r *RTPSender) Track() TrackLocal { // ReplaceTrack replaces the track currently being used as the sender's source with a new TrackLocal. // The new track must be of the same media kind (audio, video, etc) and switching the track should not // require negotiation. -func (r *RTPSender) ReplaceTrack(track TrackLocal) error { +func (r *RTPSender) ReplaceTrack(track TrackLocal) error { //nolint:cyclop r.mu.Lock() defer r.mu.Unlock() @@ -260,10 +264,15 @@ func (r *RTPSender) ReplaceTrack(track TrackLocal) error { return nil } + params := r.api.mediaEngine.getRTPParametersByKind( + track.Kind(), + []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}, + ) + // If we reach this point in the routine, there is only 1 track encoding codec, err := track.Bind(&baseTrackLocalContext{ id: context.ID(), - params: r.api.mediaEngine.getRTPParametersByKind(track.Kind(), []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}), + params: params, ssrc: context.SSRC(), ssrcRTX: context.SSRCRetransmission(), ssrcFEC: context.SSRCForwardErrorCorrection(), @@ -305,17 +314,23 @@ func (r *RTPSender) Send(parameters RTPSendParameters) error { trackEncoding := r.trackEncodings[idx] srtpStream := &srtpWriterFuture{ssrc: parameters.Encodings[idx].SSRC, rtpSender: r} writeStream := &interceptorToTrackLocalWriter{} - rtpParameters := r.api.mediaEngine.getRTPParametersByKind(trackEncoding.track.Kind(), []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}) + rtpParameters := r.api.mediaEngine.getRTPParametersByKind( + trackEncoding.track.Kind(), + []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}, + ) trackEncoding.srtpStream = srtpStream trackEncoding.ssrc = parameters.Encodings[idx].SSRC trackEncoding.ssrcRTX = parameters.Encodings[idx].RTX.SSRC trackEncoding.ssrcFEC = parameters.Encodings[idx].FEC.SSRC trackEncoding.rtcpInterceptor = r.api.interceptor.BindRTCPReader( - interceptor.RTCPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { - n, err = trackEncoding.srtpStream.Read(in) - return n, a, err - }), + interceptor.RTCPReaderFunc( + func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { + n, err = trackEncoding.srtpStream.Read(in) + + return n, a, err + }, + ), ) trackEncoding.context = &baseTrackLocalContext{ id: r.id, @@ -356,15 +371,17 @@ func (r *RTPSender) Send(parameters RTPSendParameters) error { } close(r.sendCalled) + return nil } -// Stop irreversibly stops the RTPSender +// Stop irreversibly stops the RTPSender. func (r *RTPSender) Stop() error { r.mu.Lock() if stopped := r.hasStopped(); stopped { r.mu.Unlock() + return nil } @@ -390,7 +407,7 @@ func (r *RTPSender) Stop() error { return util.FlattenErrs(errs) } -// Read reads incoming RTCP for this RTPSender +// Read reads incoming RTCP for this RTPSender. func (r *RTPSender) Read(b []byte) (n int, a interceptor.Attributes, err error) { select { case <-r.sendCalled: @@ -416,7 +433,7 @@ func (r *RTPSender) ReadRTCP() ([]rtcp.Packet, interceptor.Attributes, error) { return pkts, attributes, nil } -// ReadSimulcast reads incoming RTCP for this RTPSender for given rid +// ReadSimulcast reads incoming RTCP for this RTPSender for given rid. func (r *RTPSender) ReadSimulcast(b []byte, rid string) (n int, a interceptor.Attributes, err error) { select { case <-r.sendCalled: @@ -425,13 +442,14 @@ func (r *RTPSender) ReadSimulcast(b []byte, rid string) (n int, a interceptor.At return t.rtcpInterceptor.Read(b, a) } } + return 0, nil, fmt.Errorf("%w: %s", errRTPSenderNoTrackForRID, rid) case <-r.stopCalled: return 0, nil, io.ErrClosedPipe } } -// ReadSimulcastRTCP is a convenience method that wraps ReadSimulcast and unmarshal for you +// ReadSimulcastRTCP is a convenience method that wraps ReadSimulcast and unmarshal for you. func (r *RTPSender) ReadSimulcastRTCP(rid string) ([]rtcp.Packet, interceptor.Attributes, error) { b := make([]byte, r.api.settingEngine.getReceiveMTU()) i, attributes, err := r.ReadSimulcast(b, rid) @@ -440,6 +458,7 @@ func (r *RTPSender) ReadSimulcastRTCP(rid string) ([]rtcp.Packet, interceptor.At } pkts, err := rtcp.Unmarshal(b[:i]) + return pkts, attributes, err } @@ -449,7 +468,8 @@ func (r *RTPSender) SetReadDeadline(t time.Time) error { return r.trackEncodings[0].srtpStream.SetReadDeadline(t) } -// SetReadDeadlineSimulcast sets the max amount of time the RTCP stream for a given rid will block before returning. 0 is forever. +// SetReadDeadlineSimulcast sets the max amount of time the RTCP stream for a given rid +// will block before returning. 0 is forever. func (r *RTPSender) SetReadDeadlineSimulcast(deadline time.Time, rid string) error { r.mu.RLock() defer r.mu.RUnlock() @@ -459,10 +479,11 @@ func (r *RTPSender) SetReadDeadlineSimulcast(deadline time.Time, rid string) err return t.srtpStream.SetReadDeadline(deadline) } } + return fmt.Errorf("%w: %s", errRTPSenderNoTrackForRID, rid) } -// hasSent tells if data has been ever sent for this instance +// hasSent tells if data has been ever sent for this instance. func (r *RTPSender) hasSent() bool { select { case <-r.sendCalled: @@ -472,7 +493,7 @@ func (r *RTPSender) hasSent() bool { } } -// hasStopped tells if stop has been called +// hasStopped tells if stop has been called. func (r *RTPSender) hasStopped() bool { select { case <-r.stopCalled: @@ -483,7 +504,7 @@ func (r *RTPSender) hasStopped() bool { } // Set a SSRC for FEC and RTX if MediaEngine has them enabled -// If the remote doesn't support FEC or RTX we disable locally +// If the remote doesn't support FEC or RTX we disable locally. func (r *RTPSender) configureRTXAndFEC() { r.mu.RLock() defer r.mu.RUnlock() diff --git a/vendor/github.com/pion/webrtc/v4/rtpsender_js.go b/vendor/github.com/pion/webrtc/v4/rtpsender_js.go index 46ea599f7c..42a574320f 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpsender_js.go +++ b/vendor/github.com/pion/webrtc/v4/rtpsender_js.go @@ -13,3 +13,8 @@ type RTPSender struct { // Pointer to the underlying JavaScript RTCRTPSender object. underlying js.Value } + +// JSValue returns the underlying RTCRtpSender +func (s *RTPSender) JSValue() js.Value { + return s.underlying +} diff --git a/vendor/github.com/pion/webrtc/v4/rtpsendparameters.go b/vendor/github.com/pion/webrtc/v4/rtpsendparameters.go index b955c61ce5..6857291937 100644 --- a/vendor/github.com/pion/webrtc/v4/rtpsendparameters.go +++ b/vendor/github.com/pion/webrtc/v4/rtpsendparameters.go @@ -3,7 +3,7 @@ package webrtc -// RTPSendParameters contains the RTP stack settings used by receivers +// RTPSendParameters contains the RTP stack settings used by receivers. type RTPSendParameters struct { RTPParameters Encodings []RTPEncodingParameters diff --git a/vendor/github.com/pion/webrtc/v4/rtptransceiver.go b/vendor/github.com/pion/webrtc/v4/rtptransceiver.go index 74acd66415..5ce0f2d481 100644 --- a/vendor/github.com/pion/webrtc/v4/rtptransceiver.go +++ b/vendor/github.com/pion/webrtc/v4/rtptransceiver.go @@ -42,26 +42,30 @@ func newRTPTransceiver( t.setSender(sender) t.setDirection(direction) t.setCurrentDirection(RTPTransceiverDirectionUnknown) + return t } // SetCodecPreferences sets preferred list of supported codecs -// if codecs is empty or nil we reset to default from MediaEngine +// if codecs is empty or nil we reset to default from MediaEngine. func (t *RTPTransceiver) SetCodecPreferences(codecs []RTPCodecParameters) error { t.mu.Lock() defer t.mu.Unlock() for _, codec := range codecs { - if _, matchType := codecParametersFuzzySearch(codec, t.api.mediaEngine.getCodecsByKind(t.kind)); matchType == codecMatchNone { + if _, matchType := codecParametersFuzzySearch( + codec, t.api.mediaEngine.getCodecsByKind(t.kind), + ); matchType == codecMatchNone { return fmt.Errorf("%w %s", errRTPTransceiverCodecUnsupported, codec.MimeType) } } t.codecs = codecs + return nil } -// Codecs returns list of supported codecs +// Codecs returns list of supported codecs. func (t *RTPTransceiver) getCodecs() []RTPCodecParameters { t.mu.RLock() defer t.mu.RUnlock() @@ -85,7 +89,7 @@ func (t *RTPTransceiver) getCodecs() []RTPCodecParameters { return filteredCodecs } -// 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 { if v, ok := t.sender.Load().(*RTPSender); ok { return v @@ -94,9 +98,10 @@ func (t *RTPTransceiver) Sender() *RTPSender { return nil } -// SetSender sets the RTPSender and Track to current transceiver +// SetSender sets the RTPSender and Track to current transceiver. func (t *RTPTransceiver) SetSender(s *RTPSender, track TrackLocal) error { t.setSender(s) + return t.setSendingTrack(track) } @@ -112,7 +117,7 @@ func (t *RTPTransceiver) setSender(s *RTPSender) { t.sender.Store(s) } -// 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 { if v, ok := t.receiver.Load().(*RTPReceiver); ok { return v @@ -127,6 +132,7 @@ func (t *RTPTransceiver) SetMid(mid string) error { return fmt.Errorf("%w: %s to %s", errRTPTransceiverCannotChangeMid, currentMid, mid) } t.mid.Store(mid) + return nil } @@ -135,6 +141,7 @@ func (t *RTPTransceiver) Mid() string { if v, ok := t.mid.Load().(string); ok { return v } + return "" } @@ -143,15 +150,16 @@ func (t *RTPTransceiver) Kind() RTPCodecType { return t.kind } -// Direction returns the RTPTransceiver's current direction +// Direction returns the RTPTransceiver's current direction. func (t *RTPTransceiver) Direction() RTPTransceiverDirection { if direction, ok := t.direction.Load().(RTPTransceiverDirection); ok { return direction } + return RTPTransceiverDirection(0) } -// Stop irreversibly stops the RTPTransceiver +// Stop irreversibly stops the RTPTransceiver. func (t *RTPTransceiver) Stop() error { if sender := t.Sender(); sender != nil { if err := sender.Stop(); err != nil { @@ -166,6 +174,7 @@ func (t *RTPTransceiver) Stop() error { t.setDirection(RTPTransceiverDirectionInactive) t.setCurrentDirection(RTPTransceiverDirectionInactive) + return nil } @@ -193,10 +202,11 @@ func (t *RTPTransceiver) getCurrentDirection() RTPTransceiverDirection { if v, ok := t.currentDirection.Load().(RTPTransceiverDirection); ok { return v } + return RTPTransceiverDirectionUnknown } -func (t *RTPTransceiver) setSendingTrack(track TrackLocal) error { +func (t *RTPTransceiver) setSendingTrack(track TrackLocal) error { //nolint:cyclop if err := t.Sender().ReplaceTrack(track); err != nil { return err } @@ -222,6 +232,7 @@ func (t *RTPTransceiver) setSendingTrack(track TrackLocal) error { default: return errRTPTransceiverSetSendingInvalidState } + return nil } @@ -236,13 +247,21 @@ func findByMid(mid string, localTransceivers []*RTPTransceiver) (*RTPTransceiver } // Given a direction+type pluck a transceiver from the passed list -// if no entry satisfies the requested type+direction return a inactive Transceiver -func satisfyTypeAndDirection(remoteKind RTPCodecType, remoteDirection RTPTransceiverDirection, localTransceivers []*RTPTransceiver) (*RTPTransceiver, []*RTPTransceiver) { +// if no entry satisfies the requested type+direction return a inactive Transceiver. +func satisfyTypeAndDirection( + remoteKind RTPCodecType, + remoteDirection RTPTransceiverDirection, + localTransceivers []*RTPTransceiver, +) (*RTPTransceiver, []*RTPTransceiver) { // Get direction order from most preferred to least getPreferredDirections := func() []RTPTransceiverDirection { switch remoteDirection { case RTPTransceiverDirectionSendrecv: - return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly, RTPTransceiverDirectionSendrecv, RTPTransceiverDirectionSendonly} + return []RTPTransceiverDirection{ + RTPTransceiverDirectionRecvonly, + RTPTransceiverDirectionSendrecv, + RTPTransceiverDirectionSendonly, + } case RTPTransceiverDirectionSendonly: return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly, RTPTransceiverDirectionSendrecv} case RTPTransceiverDirectionRecvonly: @@ -265,11 +284,17 @@ func satisfyTypeAndDirection(remoteKind RTPCodecType, remoteDirection RTPTransce } // handleUnknownRTPPacket consumes a single RTP Packet and returns information that is helpful -// for demuxing and handling an unknown SSRC (usually for Simulcast) -func handleUnknownRTPPacket(buf []byte, midExtensionID, streamIDExtensionID, repairStreamIDExtensionID uint8, mid, rid, rsid *string) (payloadType PayloadType, paddingOnly bool, err error) { +// for demuxing and handling an unknown SSRC (usually for Simulcast). +func handleUnknownRTPPacket( + buf []byte, + midExtensionID, + streamIDExtensionID, + repairStreamIDExtensionID uint8, + mid, rid, rsid *string, +) (payloadType PayloadType, paddingOnly bool, err error) { rp := &rtp.Packet{} if err = rp.Unmarshal(buf); err != nil { - return + return 0, false, err } if rp.Padding && len(rp.Payload) == 0 { @@ -277,7 +302,7 @@ func handleUnknownRTPPacket(buf []byte, midExtensionID, streamIDExtensionID, rep } if !rp.Header.Extension { - return + return payloadType, paddingOnly, nil } payloadType = PayloadType(rp.PayloadType) @@ -293,5 +318,5 @@ func handleUnknownRTPPacket(buf []byte, midExtensionID, streamIDExtensionID, rep *rsid = string(payload) } - return + return payloadType, paddingOnly, nil } diff --git a/vendor/github.com/pion/webrtc/v4/rtptransceiver_js.go b/vendor/github.com/pion/webrtc/v4/rtptransceiver_js.go index 43e129af38..14ff92a714 100644 --- a/vendor/github.com/pion/webrtc/v4/rtptransceiver_js.go +++ b/vendor/github.com/pion/webrtc/v4/rtptransceiver_js.go @@ -16,6 +16,11 @@ type RTPTransceiver struct { underlying js.Value } +// JSValue returns the underlying RTCRtpTransceiver +func (r *RTPTransceiver) JSValue() js.Value { + return r.underlying +} + // Direction returns the RTPTransceiver's current direction func (r *RTPTransceiver) Direction() RTPTransceiverDirection { return NewRTPTransceiverDirection(r.underlying.Get("direction").String()) diff --git a/vendor/github.com/pion/webrtc/v4/rtptransceiverdirection.go b/vendor/github.com/pion/webrtc/v4/rtptransceiverdirection.go index 5e1a5be1bc..b360ce4d54 100644 --- a/vendor/github.com/pion/webrtc/v4/rtptransceiverdirection.go +++ b/vendor/github.com/pion/webrtc/v4/rtptransceiverdirection.go @@ -7,7 +7,7 @@ package webrtc type RTPTransceiverDirection int const ( - // RTPTransceiverDirectionUnknown is the enum's zero-value + // RTPTransceiverDirectionUnknown is the enum's zero-value. RTPTransceiverDirectionUnknown RTPTransceiverDirection = iota // RTPTransceiverDirectionSendrecv indicates the RTPSender will offer @@ -67,7 +67,7 @@ func (t RTPTransceiverDirection) String() string { } } -// Revers indicate the opposite direction +// Revers indicate the opposite direction. func (t RTPTransceiverDirection) Revers() RTPTransceiverDirection { switch t { case RTPTransceiverDirectionSendonly: @@ -79,7 +79,10 @@ func (t RTPTransceiverDirection) Revers() RTPTransceiverDirection { } } -func haveRTPTransceiverDirectionIntersection(haystack []RTPTransceiverDirection, needle []RTPTransceiverDirection) bool { +func haveRTPTransceiverDirectionIntersection( + haystack []RTPTransceiverDirection, + needle []RTPTransceiverDirection, +) bool { for _, n := range needle { for _, h := range haystack { if n == h { @@ -87,5 +90,6 @@ func haveRTPTransceiverDirectionIntersection(haystack []RTPTransceiverDirection, } } } + return false } diff --git a/vendor/github.com/pion/webrtc/v4/rtptransceiverinit.go b/vendor/github.com/pion/webrtc/v4/rtptransceiverinit.go index 1ad9bb606d..e4dd8fe248 100644 --- a/vendor/github.com/pion/webrtc/v4/rtptransceiverinit.go +++ b/vendor/github.com/pion/webrtc/v4/rtptransceiverinit.go @@ -3,7 +3,8 @@ package webrtc -// RTPTransceiverInit dictionary is used when calling the WebRTC function addTransceiver() to provide configuration options for the new transceiver. +// RTPTransceiverInit dictionary is used when calling the WebRTC function addTransceiver() +// to provide configuration options for the new transceiver. type RTPTransceiverInit struct { Direction RTPTransceiverDirection SendEncodings []RTPEncodingParameters diff --git a/vendor/github.com/pion/webrtc/v4/sctptransport.go b/vendor/github.com/pion/webrtc/v4/sctptransport.go index 6f03d1c0f0..c54bf39a09 100644 --- a/vendor/github.com/pion/webrtc/v4/sctptransport.go +++ b/vendor/github.com/pion/webrtc/v4/sctptransport.go @@ -132,6 +132,7 @@ func (r *SCTPTransport) Start(_ SCTPCapabilities) error { err := d.open(r) if err != nil { r.log.Warnf("failed to open data channel: %s", err) + continue } openedDCCount++ @@ -147,7 +148,7 @@ func (r *SCTPTransport) Start(_ SCTPCapabilities) error { return nil } -// Stop stops the SCTPTransport +// Stop stops the SCTPTransport. func (r *SCTPTransport) Stop() error { r.lock.Lock() defer r.lock.Unlock() @@ -163,7 +164,11 @@ func (r *SCTPTransport) Stop() error { return nil } -func (r *SCTPTransport) acceptDataChannels(a *sctp.Association, existingDataChannels []*DataChannel) { +//nolint:cyclop +func (r *SCTPTransport) acceptDataChannels( + assoc *sctp.Association, + existingDataChannels []*DataChannel, +) { dataChannels := make([]*datachannel.DataChannel, 0, len(existingDataChannels)) for _, dc := range existingDataChannels { dc.mu.Lock() @@ -176,7 +181,7 @@ func (r *SCTPTransport) acceptDataChannels(a *sctp.Association, existingDataChan } ACCEPT: for { - dc, err := datachannel.Accept(a, &datachannel.Config{ + dc, err := datachannel.Accept(assoc, &datachannel.Config{ LoggerFactory: r.api.settingEngine.LoggerFactory, }, dataChannels...) if err != nil { @@ -187,6 +192,7 @@ ACCEPT: } else { r.onClose(nil) } + return } for _, ch := range dataChannels { @@ -199,7 +205,7 @@ ACCEPT: maxRetransmits *uint16 maxPacketLifeTime *uint16 ) - val := uint16(dc.Config.ReliabilityParameter) + val := uint16(dc.Config.ReliabilityParameter) //nolint:gosec //G115 ordered := true switch dc.Config.ChannelType { @@ -300,7 +306,7 @@ func (r *SCTPTransport) OnDataChannel(f func(*DataChannel)) { } // OnDataChannelOpened sets an event handler which is invoked when a data -// channel is opened +// channel is opened. func (r *SCTPTransport) OnDataChannelOpened(f func(*DataChannel)) { r.lock.Lock() defer r.lock.Unlock() @@ -324,6 +330,7 @@ func (r *SCTPTransport) onDataChannel(dc *DataChannel) (done chan struct{}) { done = make(chan struct{}) if handler == nil || dc == nil { close(done) + return } @@ -384,10 +391,11 @@ func (r *SCTPTransport) MaxChannels() uint16 { return *r.maxChannels } -// State returns the current state of the SCTPTransport +// State returns the current state of the SCTPTransport. func (r *SCTPTransport) State() SCTPTransportState { r.lock.RLock() defer r.lock.RUnlock() + return r.state } @@ -430,6 +438,7 @@ func (r *SCTPTransport) generateAndSetDataChannelID(dtlsRole DTLSRole, idOut **u } *idOut = &id r.dataChannelIDsUsed[id] = struct{}{} + return nil } @@ -443,5 +452,6 @@ func (r *SCTPTransport) association() *sctp.Association { r.lock.RLock() association := r.sctpAssociation r.lock.RUnlock() + return association } diff --git a/vendor/github.com/pion/webrtc/v4/sctptransport_js.go b/vendor/github.com/pion/webrtc/v4/sctptransport_js.go index 7ab6c39008..701b7f7365 100644 --- a/vendor/github.com/pion/webrtc/v4/sctptransport_js.go +++ b/vendor/github.com/pion/webrtc/v4/sctptransport_js.go @@ -14,6 +14,11 @@ type SCTPTransport struct { underlying js.Value } +// JSValue returns the underlying RTCSctpTransport +func (r *SCTPTransport) JSValue() js.Value { + return r.underlying +} + // Transport returns the DTLSTransport instance the SCTPTransport is sending over. func (r *SCTPTransport) Transport() *DTLSTransport { underlying := r.underlying.Get("transport") diff --git a/vendor/github.com/pion/webrtc/v4/sctptransportstate.go b/vendor/github.com/pion/webrtc/v4/sctptransportstate.go index 9deb73813e..1103305fc9 100644 --- a/vendor/github.com/pion/webrtc/v4/sctptransportstate.go +++ b/vendor/github.com/pion/webrtc/v4/sctptransportstate.go @@ -7,7 +7,7 @@ package webrtc type SCTPTransportState int const ( - // SCTPTransportStateUnknown is the enum's zero-value + // SCTPTransportStateUnknown is the enum's zero-value. SCTPTransportStateUnknown SCTPTransportState = iota // SCTPTransportStateConnecting indicates the SCTPTransport is in the diff --git a/vendor/github.com/pion/webrtc/v4/sdp.go b/vendor/github.com/pion/webrtc/v4/sdp.go index b07a55326c..d0ff51eb5c 100644 --- a/vendor/github.com/pion/webrtc/v4/sdp.go +++ b/vendor/github.com/pion/webrtc/v4/sdp.go @@ -21,7 +21,7 @@ import ( ) // trackDetails represents any media source that can be represented in a SDP -// This isn't keyed by SSRC because it also needs to support rid based sources +// This isn't keyed by SSRC because it also needs to support rid based sources. type trackDetails struct { mid string kind RTPCodecType @@ -40,6 +40,7 @@ func trackDetailsForSSRC(trackDetails []trackDetails, ssrc SSRC) *trackDetails { } } } + return nil } @@ -55,6 +56,7 @@ func trackDetailsForRID(trackDetails []trackDetails, mid, rid string) *trackDeta } } } + return nil } @@ -80,7 +82,12 @@ func filterTrackWithSSRC(incomingTracks []trackDetails, ssrc SSRC) []trackDetail } // extract all trackDetails from an SDP. -func trackDetailsFromSDP(log logging.LeveledLogger, s *sdp.SessionDescription) (incomingTracks []trackDetails) { // nolint:gocognit +// +//nolint:gocognit,gocyclo,cyclop +func trackDetailsFromSDP( + log logging.LeveledLogger, + s *sdp.SessionDescription, +) (incomingTracks []trackDetails) { for _, media := range s.MediaDescriptions { tracksInMediaSection := []trackDetails{} rtxRepairFlows := map[uint64]uint64{} @@ -110,7 +117,7 @@ func trackDetailsFromSDP(log logging.LeveledLogger, s *sdp.SessionDescription) ( switch attr.Key { case sdp.AttrKeySSRCGroup: split := strings.Split(attr.Value, " ") - if split[0] == sdp.SemanticTokenFlowIdentification { + if split[0] == sdp.SemanticTokenFlowIdentification { //nolint:nestif // Add rtx ssrcs to blacklist, to avoid adding them as tracks // Essentially lines like `a=ssrc-group:FID 2231627014 632943048` are processed by this section // as this declares that the second SSRC (632943048) is a rtx repair flow (RFC4588) for the first @@ -119,15 +126,20 @@ func trackDetailsFromSDP(log logging.LeveledLogger, s *sdp.SessionDescription) ( baseSsrc, err := strconv.ParseUint(split[1], 10, 32) if err != nil { log.Warnf("Failed to parse SSRC: %v", err) + continue } rtxRepairFlow, err := strconv.ParseUint(split[2], 10, 32) if err != nil { log.Warnf("Failed to parse SSRC: %v", err) + continue } rtxRepairFlows[rtxRepairFlow] = baseSsrc - tracksInMediaSection = filterTrackWithSSRC(tracksInMediaSection, SSRC(rtxRepairFlow)) // Remove if rtx was added as track before + tracksInMediaSection = filterTrackWithSSRC( + tracksInMediaSection, + SSRC(rtxRepairFlow), + ) // Remove if rtx was added as track before for i := range tracksInMediaSection { if tracksInMediaSection[i].ssrcs[0] == SSRC(baseSsrc) { repairSsrc := SSRC(rtxRepairFlow) @@ -152,6 +164,7 @@ func trackDetailsFromSDP(log logging.LeveledLogger, s *sdp.SessionDescription) ( ssrc, err := strconv.ParseUint(split[0], 10, 32) if err != nil { log.Warnf("Failed to parse SSRC: %v", err) + continue } @@ -183,7 +196,7 @@ func trackDetailsFromSDP(log logging.LeveledLogger, s *sdp.SessionDescription) ( for r, baseSsrc := range rtxRepairFlows { if baseSsrc == ssrc { - repairSsrc := SSRC(r) + repairSsrc := SSRC(r) //nolint:gosec // G115 trackDetails.repairSsrc = &repairSsrc } } @@ -215,23 +228,23 @@ func trackDetailsFromSDP(log logging.LeveledLogger, s *sdp.SessionDescription) ( return incomingTracks } -func trackDetailsToRTPReceiveParameters(t *trackDetails) RTPReceiveParameters { - encodingSize := len(t.ssrcs) - if len(t.rids) >= encodingSize { - encodingSize = len(t.rids) +func trackDetailsToRTPReceiveParameters(trackDetails *trackDetails) RTPReceiveParameters { + encodingSize := len(trackDetails.ssrcs) + if len(trackDetails.rids) >= encodingSize { + encodingSize = len(trackDetails.rids) } encodings := make([]RTPDecodingParameters, encodingSize) for i := range encodings { - if len(t.rids) > i { - encodings[i].RID = t.rids[i] + if len(trackDetails.rids) > i { + encodings[i].RID = trackDetails.rids[i] } - if len(t.ssrcs) > i { - encodings[i].SSRC = t.ssrcs[i] + if len(trackDetails.ssrcs) > i { + encodings[i].SSRC = trackDetails.ssrcs[i] } - if t.repairSsrc != nil { - encodings[i].RTX.SSRC = *t.repairSsrc + if trackDetails.repairSsrc != nil { + encodings[i].RTX.SSRC = *trackDetails.repairSsrc } } @@ -261,16 +274,22 @@ func getRids(media *sdp.MediaDescription) []*simulcastRid { for _, rid := range rids { if rid.id == ridID { rid.paused = true + break } } } } } + return rids } -func addCandidatesToMediaDescriptions(candidates []ICECandidate, m *sdp.MediaDescription, iceGatheringState ICEGatheringState) error { +func addCandidatesToMediaDescriptions( + candidates []ICECandidate, + mediaDescr *sdp.MediaDescription, + iceGatheringState ICEGatheringState, +) error { appendCandidateIfNew := func(c ice.Candidate, attributes []sdp.Attribute) { marshaled := c.Marshal() for _, a := range attributes { @@ -279,7 +298,7 @@ func addCandidatesToMediaDescriptions(candidates []ICECandidate, m *sdp.MediaDes } } - m.WithValueAttribute("candidate", marshaled) + mediaDescr.WithValueAttribute("candidate", marshaled) } for _, c := range candidates { @@ -289,26 +308,36 @@ func addCandidatesToMediaDescriptions(candidates []ICECandidate, m *sdp.MediaDes } candidate.SetComponent(1) - appendCandidateIfNew(candidate, m.Attributes) + appendCandidateIfNew(candidate, mediaDescr.Attributes) candidate.SetComponent(2) - appendCandidateIfNew(candidate, m.Attributes) + appendCandidateIfNew(candidate, mediaDescr.Attributes) } if iceGatheringState != ICEGatheringStateComplete { return nil } - for _, a := range m.Attributes { + for _, a := range mediaDescr.Attributes { if a.Key == "end-of-candidates" { return nil } } - m.WithPropertyAttribute("end-of-candidates") + mediaDescr.WithPropertyAttribute("end-of-candidates") + return nil } -func addDataMediaSection(d *sdp.SessionDescription, shouldAddCandidates bool, dtlsFingerprints []DTLSFingerprint, midValue string, iceParams ICEParameters, candidates []ICECandidate, dtlsRole sdp.ConnectionRole, iceGatheringState ICEGatheringState) error { +func addDataMediaSection( + descr *sdp.SessionDescription, + shouldAddCandidates bool, + dtlsFingerprints []DTLSFingerprint, + midValue string, + iceParams ICEParameters, + candidates []ICECandidate, + dtlsRole sdp.ConnectionRole, + iceGatheringState ICEGatheringState, +) error { media := (&sdp.MediaDescription{ MediaName: sdp.MediaName{ Media: mediaSectionApplication, @@ -340,11 +369,16 @@ func addDataMediaSection(d *sdp.SessionDescription, shouldAddCandidates bool, dt } } - d.WithMedia(media) + descr.WithMedia(media) + return nil } -func populateLocalCandidates(sessionDescription *SessionDescription, i *ICEGatherer, iceGatheringState ICEGatheringState) *SessionDescription { +func populateLocalCandidates( + sessionDescription *SessionDescription, + i *ICEGatherer, + iceGatheringState ICEGatheringState, +) *SessionDescription { if sessionDescription == nil || i == nil { return sessionDescription } @@ -356,8 +390,8 @@ func populateLocalCandidates(sessionDescription *SessionDescription, i *ICEGathe parsed := sessionDescription.parsed if len(parsed.MediaDescriptions) > 0 { - m := parsed.MediaDescriptions[0] - if err = addCandidatesToMediaDescriptions(candidates, m, iceGatheringState); err != nil { + mediaDescr := parsed.MediaDescriptions[0] + if err = addCandidatesToMediaDescriptions(candidates, mediaDescr, iceGatheringState); err != nil { return sessionDescription } } @@ -374,7 +408,7 @@ func populateLocalCandidates(sessionDescription *SessionDescription, i *ICEGathe } } -// nolint: gocognit +//nolint:gocognit,cyclop func addSenderSDP( mediaSection mediaSection, isPlanB bool, @@ -400,14 +434,29 @@ func addSenderSDP( media = media.WithValueAttribute("ssrc-group", fmt.Sprintf("FEC-FR %d %d", encoding.SSRC, encoding.FEC.SSRC)) } - media = media.WithMediaSource(uint32(encoding.SSRC), track.StreamID() /* cname */, track.StreamID() /* streamLabel */, track.ID()) + media = media.WithMediaSource( + uint32(encoding.SSRC), + track.StreamID(), /* cname */ + track.StreamID(), /* streamLabel */ + track.ID(), + ) if !isPlanB { if encoding.RTX.SSRC != 0 { - media = media.WithMediaSource(uint32(encoding.RTX.SSRC), track.StreamID() /* cname */, track.StreamID() /* streamLabel */, track.ID()) + media = media.WithMediaSource( + uint32(encoding.RTX.SSRC), + track.StreamID(), /* cname */ + track.StreamID(), /* streamLabel */ + track.ID(), + ) } if encoding.FEC.SSRC != 0 { - media = media.WithMediaSource(uint32(encoding.FEC.SSRC), track.StreamID() /* cname */, track.StreamID() /* streamLabel */, track.ID()) + media = media.WithMediaSource( + uint32(encoding.FEC.SSRC), + track.StreamID(), /* cname */ + track.StreamID(), /* streamLabel */ + track.ID(), + ) } media = media.WithPropertyAttribute("msid:" + track.StreamID() + " " + track.ID()) @@ -431,8 +480,9 @@ func addSenderSDP( } } +//nolint:cyclop func addTransceiverSDP( - d *sdp.SessionDescription, + descr *sdp.SessionDescription, isPlanB bool, shouldAddCandidates bool, dtlsFingerprints []DTLSFingerprint, @@ -449,15 +499,15 @@ func addTransceiverSDP( return false, errSDPZeroTransceivers } // Use the first transceiver to generate the section attributes - t := transceivers[0] - media := sdp.NewJSEPMediaDescription(t.kind.String(), []string{}). + transceiver := transceivers[0] + media := sdp.NewJSEPMediaDescription(transceiver.kind.String(), []string{}). WithValueAttribute(sdp.AttrKeyConnectionSetup, dtlsRole.String()). WithValueAttribute(sdp.AttrKeyMID, midValue). WithICECredentials(iceParams.UsernameFragment, iceParams.Password). WithPropertyAttribute(sdp.AttrKeyRTCPMux). WithPropertyAttribute(sdp.AttrKeyRTCPRsize) - codecs := t.getCodecs() + codecs := transceiver.getCodecs() for _, codec := range codecs { name := strings.TrimPrefix(codec.MimeType, "audio/") name = strings.TrimPrefix(name, "video/") @@ -469,18 +519,20 @@ func addTransceiverSDP( } if len(codecs) == 0 { // If we are sender and we have no codecs throw an error early - if t.Sender() != nil { + if transceiver.Sender() != nil { return false, ErrSenderWithNoCodecs } // Explicitly reject track if we don't have the codec // We need to include connection information even if we're rejecting a track, otherwise Firefox will fail to // parse the SDP with an error like: - // SIPCC Failed to parse SDP: SDP Parse Error on line 50: c= connection line not specified for every media level, validation failed. - // In addition this makes our SDP compliant with RFC 4566 Section 5.7: https://datatracker.ietf.org/doc/html/rfc4566#section-5.7 - d.WithMedia(&sdp.MediaDescription{ + // SIPCC Failed to parse SDP: SDP Parse Error on line 50: c= connection line not specified for every media level, + // validation failed. + // In addition this makes our SDP compliant with RFC 4566 Section 5.7: + // https://datatracker.ietf.org/doc/html/rfc4566#section-5.7 + descr.WithMedia(&sdp.MediaDescription{ MediaName: sdp.MediaName{ - Media: t.kind.String(), + Media: transceiver.kind.String(), Port: sdp.RangedPort{Value: 0}, Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, Formats: []string{"0"}, @@ -493,18 +545,19 @@ func addTransceiverSDP( }, }, }) + return false, nil } directions := []RTPTransceiverDirection{} - if t.Sender() != nil { + if transceiver.Sender() != nil { directions = append(directions, RTPTransceiverDirectionSendonly) } - if t.Receiver() != nil { + if transceiver.Receiver() != nil { directions = append(directions, RTPTransceiverDirectionRecvonly) } - parameters := mediaEngine.getRTPParametersByKind(t.kind, directions) + parameters := mediaEngine.getRTPParametersByKind(transceiver.kind, directions) for _, rtpExtension := range parameters.HeaderExtensions { if mediaSection.matchExtensions != nil { if _, enabled := mediaSection.matchExtensions[rtpExtension.URI]; !enabled { @@ -535,7 +588,7 @@ func addTransceiverSDP( addSenderSDP(mediaSection, isPlanB, media) - media = media.WithPropertyAttribute(t.Direction().String()) + media = media.WithPropertyAttribute(transceiver.Direction().String()) for _, fingerprint := range dtlsFingerprints { media = media.WithFingerprint(fingerprint.Algorithm, strings.ToUpper(fingerprint.Value)) @@ -547,7 +600,7 @@ func addTransceiverSDP( } } - d.WithMedia(media) + descr.WithMedia(media) return true, nil } @@ -573,19 +626,23 @@ func bundleMatchFromRemote(matchBundleGroup *string) func(mid string) bool { } } bundleTags := strings.Split(*matchBundleGroup, " ") + return func(midValue string) bool { for _, tag := range bundleTags { if tag == midValue { return true } } + return false } } -// populateSDP serializes a PeerConnections state into an SDP +// populateSDP serializes a PeerConnections state into an SDP. +// +//nolint:cyclop func populateSDP( - d *sdp.SessionDescription, + descr *sdp.SessionDescription, isPlanB bool, dtlsFingerprints []DTLSFingerprint, mediaDescriptionFingerprint bool, @@ -615,54 +672,76 @@ func populateSDP( bundleCount++ } - for i, m := range mediaSections { - if m.data && len(m.transceivers) != 0 { + for i, section := range mediaSections { + if section.data && len(section.transceivers) != 0 { return nil, errSDPMediaSectionMediaDataChanInvalid - } else if !isPlanB && len(m.transceivers) > 1 { + } else if !isPlanB && len(section.transceivers) > 1 { return nil, errSDPMediaSectionMultipleTrackInvalid } shouldAddID := true shouldAddCandidates := i == 0 - if m.data { - if err = addDataMediaSection(d, shouldAddCandidates, mediaDtlsFingerprints, m.id, iceParams, candidates, connectionRole, iceGatheringState); err != nil { + if section.data { + if err = addDataMediaSection( + descr, + shouldAddCandidates, + mediaDtlsFingerprints, + section.id, + iceParams, + candidates, + connectionRole, + iceGatheringState, + ); err != nil { return nil, err } } else { - shouldAddID, err = addTransceiverSDP(d, isPlanB, shouldAddCandidates, mediaDtlsFingerprints, mediaEngine, m.id, iceParams, candidates, connectionRole, iceGatheringState, m) + shouldAddID, err = addTransceiverSDP( + descr, + isPlanB, + shouldAddCandidates, + mediaDtlsFingerprints, + mediaEngine, + section.id, + iceParams, + candidates, + connectionRole, + iceGatheringState, + section, + ) if err != nil { return nil, err } } if shouldAddID { - if bundleMatch(m.id) { - appendBundle(m.id) + if bundleMatch(section.id) { + appendBundle(section.id) } else { - d.MediaDescriptions[len(d.MediaDescriptions)-1].MediaName.Port = sdp.RangedPort{Value: 0} + descr.MediaDescriptions[len(descr.MediaDescriptions)-1].MediaName.Port = sdp.RangedPort{Value: 0} } } } if !mediaDescriptionFingerprint { for _, fingerprint := range dtlsFingerprints { - d.WithFingerprint(fingerprint.Algorithm, strings.ToUpper(fingerprint.Value)) + descr.WithFingerprint(fingerprint.Algorithm, strings.ToUpper(fingerprint.Value)) } } if isICELite { // RFC 5245 S15.3 - d = d.WithValueAttribute(sdp.AttrKeyICELite, "") + descr = descr.WithValueAttribute(sdp.AttrKeyICELite, "") } if isExtmapAllowMixed { - d = d.WithPropertyAttribute(sdp.AttrKeyExtMapAllowMixed) + descr = descr.WithPropertyAttribute(sdp.AttrKeyExtMapAllowMixed) } if bundleCount > 0 { - d = d.WithValueAttribute(sdp.AttrKeyGroup, bundleValue) + descr = descr.WithValueAttribute(sdp.AttrKeyGroup, bundleValue) } - return d, nil + + return descr, nil } func getMidValue(media *sdp.MediaDescription) string { @@ -671,10 +750,11 @@ func getMidValue(media *sdp.MediaDescription) string { return attr.Value } } + return "" } -// SessionDescription contains a MediaSection with Multiple SSRCs, it is Plan-B +// SessionDescription contains a MediaSection with Multiple SSRCs, it is Plan-B. func descriptionIsPlanB(desc *SessionDescription, log logging.LeveledLogger) bool { if desc == nil || desc.parsed == nil { return false @@ -695,7 +775,7 @@ func descriptionIsPlanB(desc *SessionDescription, log logging.LeveledLogger) boo // SessionDescription contains a MediaSection with name `audio`, `video` or `data` // If only one SSRC is set we can't know if it is Plan-B or Unified. If users have -// set fallback mode assume it is Plan-B +// set fallback mode assume it is Plan-B. func descriptionPossiblyPlanB(desc *SessionDescription) bool { if desc == nil || desc.parsed == nil { return false @@ -707,6 +787,7 @@ func descriptionPossiblyPlanB(desc *SessionDescription) bool { return true } } + return false } @@ -716,6 +797,7 @@ func getPeerDirection(media *sdp.MediaDescription) RTPTransceiverDirection { return direction } } + return RTPTransceiverDirectionUnknown } @@ -737,7 +819,7 @@ func extractBundleID(desc *sdp.SessionDescription) string { return bundleIDs[1] } -func extractFingerprint(desc *sdp.SessionDescription) (string, string, error) { //nolint: gocognit +func extractFingerprint(desc *sdp.SessionDescription) (string, string, error) { //nolint:gocognit,cyclop fingerprint := "" // Fingerprint on session level has highest priority @@ -745,14 +827,14 @@ func extractFingerprint(desc *sdp.SessionDescription) (string, string, error) { fingerprint = sessionFingerprint } - if fingerprint == "" { + if fingerprint == "" { //nolint:nestif bundleID := extractBundleID(desc) if bundleID != "" { // Locate the fingerprint of the bundled media section - for _, m := range desc.MediaDescriptions { - if mid, haveMid := m.Attribute("mid"); haveMid { + for _, mediaDescr := range desc.MediaDescriptions { + if mid, haveMid := mediaDescr.Attribute("mid"); haveMid { if mid == bundleID && fingerprint == "" { - if mediaFingerprint, haveFingerprint := m.Attribute("fingerprint"); haveFingerprint { + if mediaFingerprint, haveFingerprint := mediaDescr.Attribute("fingerprint"); haveFingerprint { fingerprint = mediaFingerprint } } @@ -762,8 +844,8 @@ func extractFingerprint(desc *sdp.SessionDescription) (string, string, error) { // Take the fingerprint from the first media section which has one. // Note: According to Bundle spec each media section would have it's own transport // with it's own cert and fingerprint each, so we would need to return a list. - for _, m := range desc.MediaDescriptions { - mediaFingerprint, haveFingerprint := m.Attribute("fingerprint") + for _, mediaDescr := range desc.MediaDescriptions { + mediaFingerprint, haveFingerprint := mediaDescr.Attribute("fingerprint") if haveFingerprint && fingerprint == "" { fingerprint = mediaFingerprint } @@ -779,17 +861,21 @@ func extractFingerprint(desc *sdp.SessionDescription) (string, string, error) { if len(parts) != 2 { return "", "", ErrSessionDescriptionInvalidFingerprint } + return parts[1], parts[0], nil } -// identifiedMediaDescription contains a MediaDescription with sdpMid and sdpMLineIndex +// identifiedMediaDescription contains a MediaDescription with sdpMid and sdpMLineIndex. type identifiedMediaDescription struct { MediaDescription *sdp.MediaDescription SDPMid string SDPMLineIndex uint16 } -func extractICEDetailsFromMedia(media *identifiedMediaDescription, log logging.LeveledLogger) (string, string, []ICECandidate, error) { +func extractICEDetailsFromMedia( + media *identifiedMediaDescription, + log logging.LeveledLogger, +) (string, string, []ICECandidate, error) { remoteUfrag := "" remotePwd := "" candidates := []ICECandidate{} @@ -807,8 +893,10 @@ func extractICEDetailsFromMedia(media *identifiedMediaDescription, log logging.L if err != nil { if errors.Is(err, ice.ErrUnknownCandidateTyp) || errors.Is(err, ice.ErrDetermineNetworkType) { log.Warnf("Discarding remote candidate: %s", err) + continue } + return "", "", nil, err } @@ -830,7 +918,10 @@ type sdpICEDetails struct { Candidates []ICECandidate } -func extractICEDetails(desc *sdp.SessionDescription, log logging.LeveledLogger) (*sdpICEDetails, error) { // nolint:gocognit +func extractICEDetails( + desc *sdp.SessionDescription, + log logging.LeveledLogger, +) (*sdpICEDetails, error) { // nolint:gocognit details := &sdpICEDetails{ Candidates: []ICECandidate{}, } @@ -870,7 +961,10 @@ func extractICEDetails(desc *sdp.SessionDescription, log logging.LeveledLogger) // Select the first media section or the first bundle section // Currently Pion uses the first media section to gather candidates. // https://github.com/pion/webrtc/pull/2950 -func selectCandidateMediaSection(sessionDescription *sdp.SessionDescription) (descr *identifiedMediaDescription, ok bool) { +func selectCandidateMediaSection(sessionDescription *sdp.SessionDescription) ( + descr *identifiedMediaDescription, + ok bool, +) { bundleID := extractBundleID(sessionDescription) for mLineIndex, mediaDescr := range sessionDescription.MediaDescriptions { @@ -881,7 +975,7 @@ func selectCandidateMediaSection(sessionDescription *sdp.SessionDescription) (de return &identifiedMediaDescription{ MediaDescription: mediaDescr, SDPMid: mid, - SDPMLineIndex: uint16(mLineIndex), + SDPMLineIndex: uint16(mLineIndex), //nolint:gosec // G115 }, true } } else { @@ -889,7 +983,7 @@ func selectCandidateMediaSection(sessionDescription *sdp.SessionDescription) (de return &identifiedMediaDescription{ MediaDescription: mediaDescr, SDPMid: mid, - SDPMLineIndex: uint16(mLineIndex), + SDPMLineIndex: uint16(mLineIndex), //nolint:gosec // G115 }, true } } @@ -898,8 +992,8 @@ func selectCandidateMediaSection(sessionDescription *sdp.SessionDescription) (de } func haveApplicationMediaSection(desc *sdp.SessionDescription) bool { - for _, m := range desc.MediaDescriptions { - if m.MediaName.Media == mediaSectionApplication { + for _, mediaDescr := range desc.MediaDescriptions { + if mediaDescr.MediaName.Media == mediaSectionApplication { return true } } @@ -913,25 +1007,27 @@ func getByMid(searchMid string, desc *SessionDescription) *sdp.MediaDescription return m } } + return nil } -// haveDataChannel return MediaDescription with MediaName equal application +// haveDataChannel return MediaDescription with MediaName equal application. func haveDataChannel(desc *SessionDescription) *sdp.MediaDescription { for _, d := range desc.parsed.MediaDescriptions { if d.MediaName.Media == mediaSectionApplication { return d } } + return nil } -func codecsFromMediaDescription(m *sdp.MediaDescription) (out []RTPCodecParameters, err error) { +func codecsFromMediaDescription(mediaDescr *sdp.MediaDescription) (out []RTPCodecParameters, err error) { s := &sdp.SessionDescription{ - MediaDescriptions: []*sdp.MediaDescription{m}, + MediaDescriptions: []*sdp.MediaDescription{mediaDescr}, } - for _, payloadStr := range m.MediaName.Formats { + for _, payloadStr := range mediaDescr.MediaName.Formats { payloadType, err := strconv.ParseUint(payloadStr, 10, 8) if err != nil { return nil, err @@ -942,6 +1038,7 @@ func codecsFromMediaDescription(m *sdp.MediaDescription) (out []RTPCodecParamete if payloadType == 0 { continue } + return nil, err } @@ -963,8 +1060,14 @@ func codecsFromMediaDescription(m *sdp.MediaDescription) (out []RTPCodecParamete } out = append(out, RTPCodecParameters{ - RTPCodecCapability: RTPCodecCapability{m.MediaName.Media + "/" + codec.Name, codec.ClockRate, channels, codec.Fmtp, feedback}, - PayloadType: PayloadType(payloadType), + RTPCodecCapability: RTPCodecCapability{ + mediaDescr.MediaName.Media + "/" + codec.Name, + codec.ClockRate, + channels, + codec.Fmtp, + feedback, + }, + PayloadType: PayloadType(payloadType), }) } @@ -992,17 +1095,17 @@ func rtpExtensionsFromMediaDescription(m *sdp.MediaDescription) (map[string]int, // for subsequent calling, it updates Origin for SessionDescription from saved one // and increments session version by one. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-25#section-5.2.2 -func updateSDPOrigin(origin *sdp.Origin, d *sdp.SessionDescription) { - if atomic.CompareAndSwapUint64(&origin.SessionVersion, 0, d.Origin.SessionVersion) { // store - atomic.StoreUint64(&origin.SessionID, d.Origin.SessionID) +func updateSDPOrigin(origin *sdp.Origin, descr *sdp.SessionDescription) { + if atomic.CompareAndSwapUint64(&origin.SessionVersion, 0, descr.Origin.SessionVersion) { // store + atomic.StoreUint64(&origin.SessionID, descr.Origin.SessionID) } else { // load for { // awaiting for saving session id - d.Origin.SessionID = atomic.LoadUint64(&origin.SessionID) - if d.Origin.SessionID != 0 { + descr.Origin.SessionID = atomic.LoadUint64(&origin.SessionID) + if descr.Origin.SessionID != 0 { break } } - d.Origin.SessionVersion = atomic.AddUint64(&origin.SessionVersion, 1) + descr.Origin.SessionVersion = atomic.AddUint64(&origin.SessionVersion, 1) } } diff --git a/vendor/github.com/pion/webrtc/v4/sdpsemantics.go b/vendor/github.com/pion/webrtc/v4/sdpsemantics.go index 689b4e95bf..c834167a42 100644 --- a/vendor/github.com/pion/webrtc/v4/sdpsemantics.go +++ b/vendor/github.com/pion/webrtc/v4/sdpsemantics.go @@ -8,7 +8,7 @@ import ( ) // SDPSemantics determines which style of SDP offers and answers -// can be used +// can be used. type SDPSemantics int const ( @@ -24,7 +24,7 @@ const ( // SDPSemanticsUnifiedPlanWithFallback prefers unified-plan // offers and answers, but will respond to a plan-b offer - // with a plan-b answer + // with a plan-b answer. SDPSemanticsUnifiedPlanWithFallback ) @@ -58,7 +58,7 @@ func (s SDPSemantics) String() string { } } -// UnmarshalJSON parses the JSON-encoded data and stores the result +// UnmarshalJSON parses the JSON-encoded data and stores the result. func (s *SDPSemantics) UnmarshalJSON(b []byte) error { var val string if err := json.Unmarshal(b, &val); err != nil { @@ -66,10 +66,11 @@ func (s *SDPSemantics) UnmarshalJSON(b []byte) error { } *s = newSDPSemantics(val) + return nil } -// MarshalJSON returns the JSON encoding +// MarshalJSON returns the JSON encoding. func (s SDPSemantics) MarshalJSON() ([]byte, error) { return json.Marshal(s.String()) } diff --git a/vendor/github.com/pion/webrtc/v4/sdptype.go b/vendor/github.com/pion/webrtc/v4/sdptype.go index 5aa3b98611..f265d9d641 100644 --- a/vendor/github.com/pion/webrtc/v4/sdptype.go +++ b/vendor/github.com/pion/webrtc/v4/sdptype.go @@ -12,7 +12,7 @@ import ( type SDPType int const ( - // SDPTypeUnknown is the enum's zero-value + // SDPTypeUnknown is the enum's zero-value. SDPTypeUnknown SDPType = iota // SDPTypeOffer indicates that a description MUST be treated as an SDP offer. @@ -46,7 +46,7 @@ const ( sdpTypeRollbackStr = "rollback" ) -// NewSDPType creates an SDPType from a string +// NewSDPType creates an SDPType from a string. func NewSDPType(raw string) SDPType { switch raw { case sdpTypeOfferStr: @@ -77,12 +77,12 @@ func (t SDPType) String() string { } } -// MarshalJSON enables JSON marshaling of a SDPType +// MarshalJSON enables JSON marshaling of a SDPType. func (t SDPType) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } -// UnmarshalJSON enables JSON unmarshaling of a SDPType +// UnmarshalJSON enables JSON unmarshaling of a SDPType. func (t *SDPType) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { diff --git a/vendor/github.com/pion/webrtc/v4/sessiondescription.go b/vendor/github.com/pion/webrtc/v4/sessiondescription.go index 91e22a9118..186f858371 100644 --- a/vendor/github.com/pion/webrtc/v4/sessiondescription.go +++ b/vendor/github.com/pion/webrtc/v4/sessiondescription.go @@ -16,9 +16,10 @@ type SessionDescription struct { parsed *sdp.SessionDescription } -// Unmarshal is a helper to deserialize the sdp +// Unmarshal is a helper to deserialize the sdp. func (sd *SessionDescription) Unmarshal() (*sdp.SessionDescription, error) { sd.parsed = &sdp.SessionDescription{} err := sd.parsed.UnmarshalString(sd.SDP) + return sd.parsed, err } diff --git a/vendor/github.com/pion/webrtc/v4/settingengine.go b/vendor/github.com/pion/webrtc/v4/settingengine.go index edfb1549bc..c5f481b0d6 100644 --- a/vendor/github.com/pion/webrtc/v4/settingengine.go +++ b/vendor/github.com/pion/webrtc/v4/settingengine.go @@ -96,7 +96,7 @@ type SettingEngine struct { iceUDPMux ice.UDPMux iceProxyDialer proxy.Dialer iceDisableActiveTCP bool - iceBindingRequestHandler func(m *stun.Message, local, remote ice.Candidate, pair *ice.CandidatePair) bool + iceBindingRequestHandler func(m *stun.Message, local, remote ice.Candidate, pair *ice.CandidatePair) bool //nolint:lll disableMediaEngineCopy bool srtpProtectionProfiles []dtls.SRTPProtectionProfile receiveMTU uint @@ -106,7 +106,7 @@ type SettingEngine struct { dataChannelBlockWrite bool } -// getReceiveMTU returns the configured MTU. If SettingEngine's MTU is configured to 0 it returns the default +// getReceiveMTU returns the configured MTU. If SettingEngine's MTU is configured to 0 it returns the default. func (e *SettingEngine) getReceiveMTU() uint { if e.receiveMTU != 0 { return e.receiveMTU @@ -123,13 +123,13 @@ func (e *SettingEngine) DetachDataChannels() { } // EnableDataChannelBlockWrite allows data channels to block on write, -// it only works if DetachDataChannels is enabled +// it only works if DetachDataChannels is enabled. func (e *SettingEngine) EnableDataChannelBlockWrite(nonblockWrite bool) { e.dataChannelBlockWrite = nonblockWrite } // SetSRTPProtectionProfiles allows the user to override the default SRTP Protection Profiles -// The default srtp protection profiles are provided by the function `defaultSrtpProtectionProfiles` +// The default srtp protection profiles are provided by the function `defaultSrtpProtectionProfiles`. func (e *SettingEngine) SetSRTPProtectionProfiles(profiles ...dtls.SRTPProtectionProfile) { e.srtpProtectionProfiles = profiles } @@ -146,34 +146,36 @@ func (e *SettingEngine) SetSRTPProtectionProfiles(profiles ...dtls.SRTPProtectio // // keepAliveInterval: // -// How often the ICE Agent sends extra traffic if there is no activity, if media is flowing no traffic will be sent. Default is 2 seconds +// How often the ICE Agent sends extra traffic if there is no activity, if media is flowing no traffic will be sent. +// +// Default is 2 seconds. func (e *SettingEngine) SetICETimeouts(disconnectedTimeout, failedTimeout, keepAliveInterval time.Duration) { e.timeout.ICEDisconnectedTimeout = &disconnectedTimeout e.timeout.ICEFailedTimeout = &failedTimeout e.timeout.ICEKeepaliveInterval = &keepAliveInterval } -// SetHostAcceptanceMinWait sets the ICEHostAcceptanceMinWait +// SetHostAcceptanceMinWait sets the ICEHostAcceptanceMinWait. func (e *SettingEngine) SetHostAcceptanceMinWait(t time.Duration) { e.timeout.ICEHostAcceptanceMinWait = &t } -// SetSrflxAcceptanceMinWait sets the ICESrflxAcceptanceMinWait +// SetSrflxAcceptanceMinWait sets the ICESrflxAcceptanceMinWait. func (e *SettingEngine) SetSrflxAcceptanceMinWait(t time.Duration) { e.timeout.ICESrflxAcceptanceMinWait = &t } -// SetPrflxAcceptanceMinWait sets the ICEPrflxAcceptanceMinWait +// SetPrflxAcceptanceMinWait sets the ICEPrflxAcceptanceMinWait. func (e *SettingEngine) SetPrflxAcceptanceMinWait(t time.Duration) { e.timeout.ICEPrflxAcceptanceMinWait = &t } -// SetRelayAcceptanceMinWait sets the ICERelayAcceptanceMinWait +// SetRelayAcceptanceMinWait sets the ICERelayAcceptanceMinWait. func (e *SettingEngine) SetRelayAcceptanceMinWait(t time.Duration) { e.timeout.ICERelayAcceptanceMinWait = &t } -// SetSTUNGatherTimeout sets the ICESTUNGatherTimeout +// SetSTUNGatherTimeout sets the ICESTUNGatherTimeout. func (e *SettingEngine) SetSTUNGatherTimeout(t time.Duration) { e.timeout.ICESTUNGatherTimeout = &t } @@ -191,10 +193,11 @@ func (e *SettingEngine) SetEphemeralUDPPortRange(portMin, portMax uint16) error e.ephemeralUDP.PortMin = portMin e.ephemeralUDP.PortMax = portMax + return nil } -// SetLite configures whether or not the ice agent should be a lite agent +// SetLite configures whether or not the ice agent should be a lite agent. func (e *SettingEngine) SetLite(lite bool) { e.candidates.ICELite = lite } @@ -208,7 +211,7 @@ func (e *SettingEngine) SetNetworkTypes(candidateTypes []NetworkType) { // SetInterfaceFilter sets the filtering functions when gathering ICE candidates // This can be used to exclude certain network interfaces from ICE. Which may be // useful if you know a certain interface will never succeed, or if you wish to reduce -// the amount of information you wish to expose to the remote peer +// the amount of information you wish to expose to the remote peer. func (e *SettingEngine) SetInterfaceFilter(filter func(string) (keep bool)) { e.candidates.InterfaceFilter = filter } @@ -216,7 +219,7 @@ func (e *SettingEngine) SetInterfaceFilter(filter func(string) (keep bool)) { // SetIPFilter sets the filtering functions when gathering ICE candidates // This can be used to exclude certain ip from ICE. Which may be // useful if you know a certain ip will never succeed, or if you wish to reduce -// the amount of information you wish to expose to the remote peer +// the amount of information you wish to expose to the remote peer. func (e *SettingEngine) SetIPFilter(filter func(net.IP) (keep bool)) { e.candidates.IPFilter = filter } @@ -252,7 +255,7 @@ func (e *SettingEngine) SetNAT1To1IPs(ips []string, candidateType ICECandidateTy } // SetIncludeLoopbackCandidate enable pion to gather loopback candidates, it is useful -// for some VM have public IP mapped to loopback interface +// for some VM have public IP mapped to loopback interface. func (e *SettingEngine) SetIncludeLoopbackCandidate(include bool) { e.candidates.IncludeLoopbackCandidate = include } @@ -274,6 +277,7 @@ func (e *SettingEngine) SetAnsweringDTLSRole(role DTLSRole) error { } e.answeringDTLSRole = role + return nil } @@ -285,28 +289,29 @@ func (e *SettingEngine) SetNet(net transport.Net) { e.net = net } -// SetICEMulticastDNSMode controls if pion/ice queries and generates mDNS ICE Candidates +// SetICEMulticastDNSMode controls if pion/ice queries and generates mDNS ICE Candidates. func (e *SettingEngine) SetICEMulticastDNSMode(multicastDNSMode ice.MulticastDNSMode) { e.candidates.MulticastDNSMode = multicastDNSMode } // SetMulticastDNSHostName sets a static HostName to be used by pion/ice instead of generating one on startup // -// This should only be used for a single PeerConnection. Having multiple PeerConnections with the same HostName will cause -// undefined behavior +// This should only be used for a single PeerConnection. +// Having multiple PeerConnections with the same HostName will cause undefined behavior. func (e *SettingEngine) SetMulticastDNSHostName(hostName string) { e.candidates.MulticastDNSHostName = hostName } // SetICECredentials sets a staic uFrag/uPwd to be used by pion/ice // -// This is useful if you want to do signalless WebRTC session, or having a reproducible environment with static credentials +// This is useful if you want to do signalless WebRTC session, +// or having a reproducible environment with static credentials. func (e *SettingEngine) SetICECredentials(usernameFragment, password string) { e.candidates.UsernameFragment = usernameFragment e.candidates.Password = password } -// DisableCertificateFingerprintVerification disables fingerprint verification after DTLS Handshake has finished +// DisableCertificateFingerprintVerification disables fingerprint verification after DTLS Handshake has finished. func (e *SettingEngine) DisableCertificateFingerprintVerification(isDisabled bool) { e.disableCertificateFingerprintVerification = isDisabled } @@ -370,7 +375,7 @@ func (e *SettingEngine) SetICEMaxBindingRequests(d uint16) { e.iceMaxBindingRequests = &d } -// DisableActiveTCP disables using active TCP for ICE. Active TCP is enabled by default +// DisableActiveTCP disables using active TCP for ICE. Active TCP is enabled by default. func (e *SettingEngine) DisableActiveTCP(isDisabled bool) { e.iceDisableActiveTCP = isDisabled } @@ -383,7 +388,7 @@ func (e *SettingEngine) DisableMediaEngineCopy(isDisabled bool) { } // SetReceiveMTU sets the size of read buffer that copies incoming packets. This is optional. -// Leave this 0 for the default receiveMTU +// Leave this 0 for the default receiveMTU. func (e *SettingEngine) SetReceiveMTU(receiveMTU uint) { e.receiveMTU = receiveMTU } @@ -457,7 +462,7 @@ func (e *SettingEngine) SetSCTPMaxReceiveBufferSize(maxReceiveBufferSize uint32) // EnableSCTPZeroChecksum controls the zero checksum feature in SCTP. // This removes the need to checksum every incoming/outgoing packet and will reduce -// latency and CPU usage. This feature is not backwards compatible so is disabled by default +// latency and CPU usage. This feature is not backwards compatible so is disabled by default. func (e *SettingEngine) EnableSCTPZeroChecksum(isEnabled bool) { e.sctp.enableZeroChecksum = isEnabled } @@ -482,7 +487,9 @@ func (e *SettingEngine) SetDTLSServerHelloMessageHook(hook func(handshake.Messag // SetDTLSCertificateRequestMessageHook if not nil, is called when a DTLS Certificate Request message is sent // from a client. The returned handshake message replaces the original message. -func (e *SettingEngine) SetDTLSCertificateRequestMessageHook(hook func(handshake.MessageCertificateRequest) handshake.Message) { +func (e *SettingEngine) SetDTLSCertificateRequestMessageHook( + hook func(handshake.MessageCertificateRequest) handshake.Message, +) { e.dtls.certificateRequestMessageHook = hook } @@ -496,8 +503,10 @@ func (e *SettingEngine) SetSCTPRTOMax(rtoMax time.Duration) { // This allows users to do things like // - Log incoming Binding Requests for debugging // - Implement draft-thatcher-ice-renomination -// - Implement custom CandidatePair switching logic -func (e *SettingEngine) SetICEBindingRequestHandler(bindingRequestHandler func(m *stun.Message, local, remote ice.Candidate, pair *ice.CandidatePair) bool) { +// - Implement custom CandidatePair switching logic. +func (e *SettingEngine) SetICEBindingRequestHandler( + bindingRequestHandler func(m *stun.Message, local, remote ice.Candidate, pair *ice.CandidatePair) bool, +) { e.iceBindingRequestHandler = bindingRequestHandler } diff --git a/vendor/github.com/pion/webrtc/v4/signalingstate.go b/vendor/github.com/pion/webrtc/v4/signalingstate.go index 9d60afd260..03b8fb239a 100644 --- a/vendor/github.com/pion/webrtc/v4/signalingstate.go +++ b/vendor/github.com/pion/webrtc/v4/signalingstate.go @@ -32,7 +32,7 @@ func (op stateChangeOp) String() string { type SignalingState int32 const ( - // SignalingStateUnknown is the enum's zero-value + // SignalingStateUnknown is the enum's zero-value. SignalingStateUnknown SignalingState = iota // SignalingStateStable indicates there is no offer/answer exchange in @@ -110,17 +110,18 @@ func (t SignalingState) String() string { } } -// Get thread safe read value +// Get thread safe read value. func (t *SignalingState) Get() SignalingState { return SignalingState(atomic.LoadInt32((*int32)(t))) } -// Set thread safe write value +// Set thread safe write value. func (t *SignalingState) Set(state SignalingState) { atomic.StoreInt32((*int32)(t), int32(state)) } -func checkNextSignalingState(cur, next SignalingState, op stateChangeOp, sdpType SDPType) (SignalingState, error) { // nolint:gocognit +//nolint:gocognit,cyclop +func checkNextSignalingState(cur, next SignalingState, op stateChangeOp, sdpType SDPType) (SignalingState, error) { // Special case for rollbacks if sdpType == SDPTypeRollback && cur == SignalingStateStable { return cur, &rtcerr.InvalidModificationError{ @@ -188,6 +189,7 @@ func checkNextSignalingState(cur, next SignalingState, op stateChangeOp, sdpType } } } + return cur, &rtcerr.InvalidModificationError{ Err: fmt.Errorf("%w: %s->%s(%s)->%s", errSignalingStateProposedTransitionInvalid, cur, op, sdpType, next), } diff --git a/vendor/github.com/pion/webrtc/v4/srtp_writer_future.go b/vendor/github.com/pion/webrtc/v4/srtp_writer_future.go index fe090858b2..31afb2d135 100644 --- a/vendor/github.com/pion/webrtc/v4/srtp_writer_future.go +++ b/vendor/github.com/pion/webrtc/v4/srtp_writer_future.go @@ -17,7 +17,7 @@ import ( ) // srtpWriterFuture blocks Read/Write calls until -// the SRTP Session is available +// the SRTP Session is available. type srtpWriterFuture struct { ssrc SSRC rtpSender *RTPSender @@ -27,7 +27,7 @@ type srtpWriterFuture struct { closed bool } -func (s *srtpWriterFuture) init(returnWhenNoSRTP bool) error { +func (s *srtpWriterFuture) init(returnWhenNoSRTP bool) error { //nolint:cyclop if returnWhenNoSRTP { select { case <-s.rtpSender.stopCalled: @@ -73,6 +73,7 @@ func (s *srtpWriterFuture) init(returnWhenNoSRTP bool) error { s.rtcpReadStream.Store(rtcpReadStream) s.rtpWriteStream.Store(rtpWriteStream) + return nil } diff --git a/vendor/github.com/pion/webrtc/v4/stats.go b/vendor/github.com/pion/webrtc/v4/stats.go index 4dfa3bad8a..0d73394b97 100644 --- a/vendor/github.com/pion/webrtc/v4/stats.go +++ b/vendor/github.com/pion/webrtc/v4/stats.go @@ -18,8 +18,8 @@ type Stats interface { statsMarker() } -// UnmarshalStatsJSON unmarshals a Stats object from JSON -func UnmarshalStatsJSON(b []byte) (Stats, error) { +// UnmarshalStatsJSON unmarshals a Stats object from JSON. +func UnmarshalStatsJSON(b []byte) (Stats, error) { //nolint:cyclop type typeJSON struct { Type StatsType `json:"type"` } @@ -135,17 +135,17 @@ const ( // StatsTypeCertificate is used by CertificateStats. StatsTypeCertificate StatsType = "certificate" - // StatsTypeSCTPTransport is used by SCTPTransportStats + // StatsTypeSCTPTransport is used by SCTPTransportStats. StatsTypeSCTPTransport StatsType = "sctp-transport" ) -// MediaKind indicates the kind of media (audio or video) +// MediaKind indicates the kind of media (audio or video). type MediaKind string const ( - // MediaKindAudio indicates this is audio stats + // MediaKindAudio indicates this is audio stats. MediaKindAudio MediaKind = "audio" - // MediaKindVideo indicates this is video stats + // MediaKindVideo indicates this is video stats. MediaKindVideo MediaKind = "video" ) @@ -202,11 +202,12 @@ func (src *statsReportCollector) Ready() StatsReport { src.collectingGroup.Wait() src.mux.Lock() defer src.mux.Unlock() + return src.report } // CodecType specifies whether a CodecStats objects represents a media format -// that is being encoded or decoded +// that is being encoded or decoded. type CodecType string const ( @@ -269,6 +270,7 @@ func unmarshalCodecStats(b []byte) (CodecStats, error) { if err != nil { return CodecStats{}, fmt.Errorf("unmarshal codec stats: %w", err) } + return codecStats, nil } @@ -605,6 +607,7 @@ func unmarshalInboundRTPStreamStats(b []byte) (InboundRTPStreamStats, error) { if err != nil { return InboundRTPStreamStats{}, fmt.Errorf("unmarshal inbound rtp stream stats: %w", err) } + return inboundRTPStreamStats, nil } @@ -619,10 +622,14 @@ const ( // QualityLimitationReasonCPU means the resolution and/or framerate is primarily limited due to CPU load. QualityLimitationReasonCPU QualityLimitationReason = "cpu" - // QualityLimitationReasonBandwidth means the resolution and/or framerate is primarily limited due to congestion cues during bandwidth estimation. Typical, congestion control algorithms use inter-arrival time, round-trip time, packet or other congestion cues to perform bandwidth estimation. + // QualityLimitationReasonBandwidth means the resolution and/or framerate is primarily limited + // due to congestion cues during bandwidth estimation. + // Typical, congestion control algorithms use inter-arrival time, round-trip time, + // packet or other congestion cues to perform bandwidth estimation. QualityLimitationReasonBandwidth QualityLimitationReason = "bandwidth" - // QualityLimitationReasonOther means the resolution and/or framerate is primarily limited for a reason other than the above. + // QualityLimitationReasonOther means the resolution and/or framerate is primarily limited + // for a reason other than the above. QualityLimitationReasonOther QualityLimitationReason = "other" ) @@ -855,6 +862,7 @@ func unmarshalOutboundRTPStreamStats(b []byte) (OutboundRTPStreamStats, error) { if err != nil { return OutboundRTPStreamStats{}, fmt.Errorf("unmarshal outbound rtp stream stats: %w", err) } + return outboundRTPStreamStats, nil } @@ -986,6 +994,7 @@ func unmarshalRemoteInboundRTPStreamStats(b []byte) (RemoteInboundRTPStreamStats if err != nil { return RemoteInboundRTPStreamStats{}, fmt.Errorf("unmarshal remote inbound rtp stream stats: %w", err) } + return remoteInboundRTPStreamStats, nil } @@ -1105,6 +1114,7 @@ func unmarshalRemoteOutboundRTPStreamStats(b []byte) (RemoteOutboundRTPStreamSta if err != nil { return RemoteOutboundRTPStreamStats{}, fmt.Errorf("unmarshal remote outbound rtp stream stats: %w", err) } + return remoteOutboundRTPStreamStats, nil } @@ -1152,6 +1162,7 @@ func unmarshalCSRCStats(b []byte) (RTPContributingSourceStats, error) { if err != nil { return RTPContributingSourceStats{}, fmt.Errorf("unmarshal csrc stats: %w", err) } + return csrcStats, nil } @@ -1215,7 +1226,8 @@ type AudioSourceStats struct { // TotalCaptureDelay is the total delay, in seconds, for each audio sample between the time the sample was emitted // by the capture device and the sample reaching the source. This can be used together with totalSamplesCaptured to - // calculate the average capture delay per sample. Only applicable if the audio source represents an audio capture device. + // calculate the average capture delay per sample. + // Only applicable if the audio source represents an audio capture device. TotalCaptureDelay float64 `json:"totalCaptureDelay"` // TotalSamplesCaptured is the total number of captured samples reaching the audio source, i.e. that were not dropped @@ -1278,6 +1290,7 @@ func unmarshalMediaSourceStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal audio source stats: %w", err) } + return mediaSourceStats, nil case MediaKindVideo: var mediaSourceStats VideoSourceStats @@ -1285,6 +1298,7 @@ func unmarshalMediaSourceStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal video source stats: %w", err) } + return mediaSourceStats, nil default: return nil, fmt.Errorf("kind: %w", ErrUnknownType) @@ -1346,6 +1360,7 @@ func unmarshalMediaPlayoutStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal audio playout stats: %w", err) } + return audioPlayoutStats, nil } @@ -1391,6 +1406,7 @@ func unmarshalPeerConnectionStats(b []byte) (PeerConnectionStats, error) { if err != nil { return PeerConnectionStats{}, fmt.Errorf("unmarshal pc stats: %w", err) } + return pcStats, nil } @@ -1445,6 +1461,7 @@ func unmarshalDataChannelStats(b []byte) (DataChannelStats, error) { if err != nil { return DataChannelStats{}, fmt.Errorf("unmarshal data channel stats: %w", err) } + return dataChannelStats, nil } @@ -1477,6 +1494,7 @@ func unmarshalStreamStats(b []byte) (MediaStreamStats, error) { if err != nil { return MediaStreamStats{}, fmt.Errorf("unmarshal stream stats: %w", err) } + return streamStats, nil } @@ -1658,6 +1676,7 @@ func unmarshalSenderStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal audio sender stats: %w", err) } + return senderStats, nil case MediaKindVideo: var senderStats VideoSenderStats @@ -1665,6 +1684,7 @@ func unmarshalSenderStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal video sender stats: %w", err) } + return senderStats, nil default: return nil, fmt.Errorf("kind: %w", ErrUnknownType) @@ -1689,6 +1709,7 @@ func unmarshalTrackStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal audio track stats: %w", err) } + return trackStats, nil case MediaKindVideo: var trackStats SenderVideoTrackAttachmentStats @@ -1696,6 +1717,7 @@ func unmarshalTrackStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal video track stats: %w", err) } + return trackStats, nil default: return nil, fmt.Errorf("kind: %w", ErrUnknownType) @@ -1894,6 +1916,7 @@ func unmarshalReceiverStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal audio receiver stats: %w", err) } + return receiverStats, nil case MediaKindVideo: var receiverStats VideoReceiverStats @@ -1901,6 +1924,7 @@ func unmarshalReceiverStats(b []byte) (Stats, error) { if err != nil { return nil, fmt.Errorf("unmarshal video receiver stats: %w", err) } + return receiverStats, nil default: return nil, fmt.Errorf("kind: %w", ErrUnknownType) @@ -1980,6 +2004,7 @@ func unmarshalTransportStats(b []byte) (TransportStats, error) { if err != nil { return TransportStats{}, fmt.Errorf("unmarshal transport stats: %w", err) } + return transportStats, nil } @@ -2000,6 +2025,7 @@ func toStatsICECandidatePairState(state ice.CandidatePairState) (StatsICECandida default: // NOTE: this should never happen[tm] err := fmt.Errorf("%w: %s", errStatsICECandidateStateInvalid, state.String()) + return StatsICECandidatePairState("Unknown"), err } } @@ -2228,6 +2254,7 @@ func unmarshalICECandidatePairStats(b []byte) (ICECandidatePairStats, error) { if err != nil { return ICECandidatePairStats{}, fmt.Errorf("unmarshal ice candidate pair stats: %w", err) } + return iceCandidatePairStats, nil } @@ -2305,6 +2332,7 @@ func unmarshalICECandidateStats(b []byte) (ICECandidateStats, error) { if err != nil { return ICECandidateStats{}, fmt.Errorf("unmarshal ice candidate stats: %w", err) } + return iceCandidateStats, nil } @@ -2344,6 +2372,7 @@ func unmarshalCertificateStats(b []byte) (CertificateStats, error) { if err != nil { return CertificateStats{}, fmt.Errorf("unmarshal certificate stats: %w", err) } + return certificateStats, nil } @@ -2364,8 +2393,9 @@ type SCTPTransportStats struct { // RTCTransportStats for the DTLSTransport and ICETransport supporting the SCTP transport. TransportID string `json:"transportId"` - // SmoothedRoundTripTime is the latest smoothed round-trip time value, corresponding to spinfo_srtt defined in [RFC6458] - // but converted to seconds. If there has been no round-trip time measurements yet, this value is undefined. + // SmoothedRoundTripTime is the latest smoothed round-trip time value, + // corresponding to spinfo_srtt defined in [RFC6458] but converted to seconds. + // If there has been no round-trip time measurements yet, this value is undefined. SmoothedRoundTripTime float64 `json:"smoothedRoundTripTime"` // CongestionWindow is the latest congestion window, corresponding to spinfo_cwnd defined in [RFC6458]. @@ -2394,5 +2424,6 @@ func unmarshalSCTPTransportStats(b []byte) (SCTPTransportStats, error) { if err := json.Unmarshal(b, &sctpTransportStats); err != nil { return SCTPTransportStats{}, fmt.Errorf("unmarshal sctp transport stats: %w", err) } + return sctpTransportStats, nil } diff --git a/vendor/github.com/pion/webrtc/v4/stats_go.go b/vendor/github.com/pion/webrtc/v4/stats_go.go index a9a8e21562..58722c1818 100644 --- a/vendor/github.com/pion/webrtc/v4/stats_go.go +++ b/vendor/github.com/pion/webrtc/v4/stats_go.go @@ -6,7 +6,7 @@ package webrtc -// GetConnectionStats is a helper method to return the associated stats for a given PeerConnection +// GetConnectionStats is a helper method to return the associated stats for a given PeerConnection. func (r StatsReport) GetConnectionStats(conn *PeerConnection) (PeerConnectionStats, bool) { statsID := conn.getStatsID() stats, ok := r[statsID] @@ -18,10 +18,11 @@ func (r StatsReport) GetConnectionStats(conn *PeerConnection) (PeerConnectionSta if !ok { return PeerConnectionStats{}, false } + return pcStats, true } -// GetDataChannelStats is a helper method to return the associated stats for a given DataChannel +// GetDataChannelStats is a helper method to return the associated stats for a given DataChannel. func (r StatsReport) GetDataChannelStats(dc *DataChannel) (DataChannelStats, bool) { statsID := dc.getStatsID() stats, ok := r[statsID] @@ -33,10 +34,11 @@ func (r StatsReport) GetDataChannelStats(dc *DataChannel) (DataChannelStats, boo if !ok { return DataChannelStats{}, false } + return dcStats, true } -// GetICECandidateStats is a helper method to return the associated stats for a given ICECandidate +// GetICECandidateStats is a helper method to return the associated stats for a given ICECandidate. func (r StatsReport) GetICECandidateStats(c *ICECandidate) (ICECandidateStats, bool) { statsID := c.statsID stats, ok := r[statsID] @@ -48,10 +50,11 @@ func (r StatsReport) GetICECandidateStats(c *ICECandidate) (ICECandidateStats, b if !ok { return ICECandidateStats{}, false } + return candidateStats, true } -// GetICECandidatePairStats is a helper method to return the associated stats for a given ICECandidatePair +// GetICECandidatePairStats is a helper method to return the associated stats for a given ICECandidatePair. func (r StatsReport) GetICECandidatePairStats(c *ICECandidatePair) (ICECandidatePairStats, bool) { statsID := c.statsID stats, ok := r[statsID] @@ -63,10 +66,11 @@ func (r StatsReport) GetICECandidatePairStats(c *ICECandidatePair) (ICECandidate if !ok { return ICECandidatePairStats{}, false } + return candidateStats, true } -// GetCertificateStats is a helper method to return the associated stats for a given Certificate +// GetCertificateStats is a helper method to return the associated stats for a given Certificate. func (r StatsReport) GetCertificateStats(c *Certificate) (CertificateStats, bool) { statsID := c.statsID stats, ok := r[statsID] @@ -78,10 +82,11 @@ func (r StatsReport) GetCertificateStats(c *Certificate) (CertificateStats, bool if !ok { return CertificateStats{}, false } + return certificateStats, true } -// GetCodecStats is a helper method to return the associated stats for a given Codec +// GetCodecStats is a helper method to return the associated stats for a given Codec. func (r StatsReport) GetCodecStats(c *RTPCodecParameters) (CodecStats, bool) { statsID := c.statsID stats, ok := r[statsID] @@ -93,5 +98,6 @@ func (r StatsReport) GetCodecStats(c *RTPCodecParameters) (CodecStats, bool) { if !ok { return CodecStats{}, false } + return codecStats, true } diff --git a/vendor/github.com/pion/webrtc/v4/track_local.go b/vendor/github.com/pion/webrtc/v4/track_local.go index 86a6b7f837..448b98af28 100644 --- a/vendor/github.com/pion/webrtc/v4/track_local.go +++ b/vendor/github.com/pion/webrtc/v4/track_local.go @@ -8,7 +8,7 @@ import ( "github.com/pion/rtp" ) -// TrackLocalWriter is the Writer for outbound RTP Packets +// TrackLocalWriter is the Writer for outbound RTP Packets. type TrackLocalWriter interface { // WriteRTP encrypts a RTP packet and writes to the connection WriteRTP(header *rtp.Header, payload []byte) (int, error) @@ -57,39 +57,39 @@ type baseTrackLocalContext struct { } // CodecParameters returns the negotiated RTPCodecParameters. These are the codecs supported by both -// PeerConnections and the SSRC/PayloadTypes +// PeerConnections and the SSRC/PayloadTypes. func (t *baseTrackLocalContext) CodecParameters() []RTPCodecParameters { return t.params.Codecs } // HeaderExtensions returns the negotiated RTPHeaderExtensionParameters. These are the header extensions supported by -// both PeerConnections and the SSRC/PayloadTypes +// both PeerConnections and the SSRC/PayloadTypes. func (t *baseTrackLocalContext) HeaderExtensions() []RTPHeaderExtensionParameter { return t.params.HeaderExtensions } -// SSRC requires the negotiated SSRC of this track +// SSRC requires the negotiated SSRC of this track. func (t *baseTrackLocalContext) SSRC() SSRC { return t.ssrc } -// SSRCRetransmission returns the negotiated SSRC used to send retransmissions for this track +// SSRCRetransmission returns the negotiated SSRC used to send retransmissions for this track. func (t *baseTrackLocalContext) SSRCRetransmission() SSRC { return t.ssrcRTX } -// SSRCForwardErrorCorrection returns the negotiated SSRC to send forward error correction for this track +// SSRCForwardErrorCorrection returns the negotiated SSRC to send forward error correction for this track. func (t *baseTrackLocalContext) SSRCForwardErrorCorrection() SSRC { return t.ssrcFEC } // WriteStream returns the WriteStream for this TrackLocal. The implementer writes the outbound -// media packets to it +// media packets to it. func (t *baseTrackLocalContext) WriteStream() TrackLocalWriter { return t.writeStream } -// ID is a unique identifier that is used for both Bind/Unbind +// ID is a unique identifier that is used for both Bind/Unbind. func (t *baseTrackLocalContext) ID() string { return t.id } @@ -101,7 +101,7 @@ func (t *baseTrackLocalContext) RTCPReader() interceptor.RTCPReader { // TrackLocal is an interface that controls how the user can send media // The user can provide their own TrackLocal implementations, or use -// the implementations in pkg/media +// the implementations in pkg/media. type TrackLocal interface { // Bind should implement the way how the media data flows from the Track to the PeerConnection // This will be called internally after signaling is complete and the list of available diff --git a/vendor/github.com/pion/webrtc/v4/track_local_static.go b/vendor/github.com/pion/webrtc/v4/track_local_static.go index 2dd665cd24..7512599f1f 100644 --- a/vendor/github.com/pion/webrtc/v4/track_local_static.go +++ b/vendor/github.com/pion/webrtc/v4/track_local_static.go @@ -17,7 +17,7 @@ import ( // trackBinding is a single bind for a Track // Bind can be called multiple times, this stores the -// result for a single bind call so that it can be used when writing +// result for a single bind call so that it can be used when writing. type trackBinding struct { id string ssrc, ssrcRTX, ssrcFEC SSRC @@ -26,7 +26,7 @@ type trackBinding struct { } // TrackLocalStaticRTP is a TrackLocal that has a pre-set codec and accepts RTP Packets. -// If you wish to send a media.Sample use TrackLocalStaticSample +// If you wish to send a media.Sample use TrackLocalStaticSample. type TrackLocalStaticRTP struct { mu sync.RWMutex bindings []trackBinding @@ -36,7 +36,11 @@ type TrackLocalStaticRTP struct { } // NewTrackLocalStaticRTP returns a TrackLocalStaticRTP. -func NewTrackLocalStaticRTP(c RTPCodecCapability, id, streamID string, options ...func(*TrackLocalStaticRTP)) (*TrackLocalStaticRTP, error) { +func NewTrackLocalStaticRTP( + c RTPCodecCapability, + id, streamID string, + options ...func(*TrackLocalStaticRTP), +) (*TrackLocalStaticRTP, error) { t := &TrackLocalStaticRTP{ codec: c, bindings: []trackBinding{}, @@ -58,7 +62,7 @@ func WithRTPStreamID(rid string) func(*TrackLocalStaticRTP) { } } -// WithPayloader allows the user to override the Payloader +// WithPayloader allows the user to override the Payloader. func WithPayloader(h func(RTPCodecCapability) (rtp.Payloader, error)) func(*TrackLocalStaticRTP) { return func(s *TrackLocalStaticRTP) { s.payloader = h @@ -67,21 +71,24 @@ func WithPayloader(h func(RTPCodecCapability) (rtp.Payloader, error)) func(*Trac // Bind is called by the PeerConnection after negotiation is complete // This asserts that the code requested is supported by the remote peer. -// If so it sets up all the state (SSRC and PayloadType) to have a call -func (s *TrackLocalStaticRTP) Bind(t TrackLocalContext) (RTPCodecParameters, error) { +// If so it sets up all the state (SSRC and PayloadType) to have a call. +func (s *TrackLocalStaticRTP) Bind(trackContext TrackLocalContext) (RTPCodecParameters, error) { s.mu.Lock() defer s.mu.Unlock() parameters := RTPCodecParameters{RTPCodecCapability: s.codec} - if codec, matchType := codecParametersFuzzySearch(parameters, t.CodecParameters()); matchType != codecMatchNone { + if codec, matchType := codecParametersFuzzySearch( + parameters, + trackContext.CodecParameters(), + ); matchType != codecMatchNone { s.bindings = append(s.bindings, trackBinding{ - ssrc: t.SSRC(), - ssrcRTX: t.SSRCRetransmission(), - ssrcFEC: t.SSRCForwardErrorCorrection(), + ssrc: trackContext.SSRC(), + ssrcRTX: trackContext.SSRCRetransmission(), + ssrcFEC: trackContext.SSRCForwardErrorCorrection(), payloadType: codec.PayloadType, - payloadTypeRTX: findRTXPayloadType(codec.PayloadType, t.CodecParameters()), - writeStream: t.WriteStream(), - id: t.ID(), + payloadTypeRTX: findRTXPayloadType(codec.PayloadType, trackContext.CodecParameters()), + writeStream: trackContext.WriteStream(), + id: trackContext.ID(), }) return codec, nil @@ -100,6 +107,7 @@ func (s *TrackLocalStaticRTP) Unbind(t TrackLocalContext) error { if s.bindings[i].id == t.ID() { s.bindings[i] = s.bindings[len(s.bindings)-1] s.bindings = s.bindings[:len(s.bindings)-1] + return nil } } @@ -109,16 +117,16 @@ func (s *TrackLocalStaticRTP) Unbind(t TrackLocalContext) error { // ID is the unique identifier for this Track. This should be unique for the // stream, but doesn't have to globally unique. A common example would be 'audio' or 'video' -// and StreamID would be 'desktop' or 'webcam' +// and StreamID would be 'desktop' or 'webcam'. func (s *TrackLocalStaticRTP) ID() string { return s.id } -// StreamID is the group this track belongs too. This must be unique +// StreamID is the group this track belongs too. This must be unique. func (s *TrackLocalStaticRTP) StreamID() string { return s.streamID } // RID is the RTP stream identifier. func (s *TrackLocalStaticRTP) RID() string { return s.rid } -// Kind controls if this TrackLocal is audio or video +// Kind controls if this TrackLocal is audio or video. func (s *TrackLocalStaticRTP) Kind() RTPCodecType { switch { case strings.HasPrefix(s.codec.MimeType, "audio/"): @@ -130,7 +138,7 @@ func (s *TrackLocalStaticRTP) Kind() RTPCodecType { } } -// Codec gets the Codec of the track +// Codec gets the Codec of the track. func (s *TrackLocalStaticRTP) Codec() RTPCodecCapability { return s.codec } @@ -150,13 +158,14 @@ func resetPacketPoolAllocation(localPacket *rtp.Packet) { func getPacketAllocationFromPool() *rtp.Packet { ipacket := rtpPacketPool.Get() + return ipacket.(*rtp.Packet) //nolint:forcetypeassert } // WriteRTP writes a RTP Packet to the TrackLocalStaticRTP // If one PeerConnection fails the packets will still be sent to // all PeerConnections. The error message will contain the ID of the failed -// PeerConnections so you can remove them +// PeerConnections so you can remove them. func (s *TrackLocalStaticRTP) WriteRTP(p *rtp.Packet) error { packet := getPacketAllocationFromPool() @@ -167,17 +176,17 @@ func (s *TrackLocalStaticRTP) WriteRTP(p *rtp.Packet) error { return s.writeRTP(packet) } -// writeRTP is like WriteRTP, except that it may modify the packet p -func (s *TrackLocalStaticRTP) writeRTP(p *rtp.Packet) error { +// writeRTP is like WriteRTP, except that it may modify the packet p. +func (s *TrackLocalStaticRTP) writeRTP(packet *rtp.Packet) error { s.mu.RLock() defer s.mu.RUnlock() writeErrs := []error{} for _, b := range s.bindings { - p.Header.SSRC = uint32(b.ssrc) - p.Header.PayloadType = uint8(b.payloadType) - if _, err := b.writeStream.WriteRTP(&p.Header, p.Payload); err != nil { + packet.Header.SSRC = uint32(b.ssrc) + packet.Header.PayloadType = uint8(b.payloadType) + if _, err := b.writeStream.WriteRTP(&packet.Header, packet.Payload); err != nil { writeErrs = append(writeErrs, err) } } @@ -188,7 +197,7 @@ func (s *TrackLocalStaticRTP) writeRTP(p *rtp.Packet) error { // Write writes a RTP Packet as a buffer to the TrackLocalStaticRTP // If one PeerConnection fails the packets will still be sent to // all PeerConnections. The error message will contain the ID of the failed -// PeerConnections so you can remove them +// PeerConnections so you can remove them. func (s *TrackLocalStaticRTP) Write(b []byte) (n int, err error) { packet := getPacketAllocationFromPool() @@ -202,7 +211,7 @@ func (s *TrackLocalStaticRTP) Write(b []byte) (n int, err error) { } // TrackLocalStaticSample is a TrackLocal that has a pre-set codec and accepts Samples. -// If you wish to send a RTP Packet use TrackLocalStaticRTP +// If you wish to send a RTP Packet use TrackLocalStaticRTP. type TrackLocalStaticSample struct { packetizer rtp.Packetizer sequencer rtp.Sequencer @@ -210,8 +219,12 @@ type TrackLocalStaticSample struct { clockRate float64 } -// NewTrackLocalStaticSample returns a TrackLocalStaticSample -func NewTrackLocalStaticSample(c RTPCodecCapability, id, streamID string, options ...func(*TrackLocalStaticRTP)) (*TrackLocalStaticSample, error) { +// NewTrackLocalStaticSample returns a TrackLocalStaticSample. +func NewTrackLocalStaticSample( + c RTPCodecCapability, + id, streamID string, + options ...func(*TrackLocalStaticRTP), +) (*TrackLocalStaticSample, error) { rtpTrack, err := NewTrackLocalStaticRTP(c, id, streamID, options...) if err != nil { return nil, err @@ -224,26 +237,26 @@ func NewTrackLocalStaticSample(c RTPCodecCapability, id, streamID string, option // ID is the unique identifier for this Track. This should be unique for the // stream, but doesn't have to globally unique. A common example would be 'audio' or 'video' -// and StreamID would be 'desktop' or 'webcam' +// and StreamID would be 'desktop' or 'webcam'. func (s *TrackLocalStaticSample) ID() string { return s.rtpTrack.ID() } -// StreamID is the group this track belongs too. This must be unique +// StreamID is the group this track belongs too. This must be unique. func (s *TrackLocalStaticSample) StreamID() string { return s.rtpTrack.StreamID() } // RID is the RTP stream identifier. func (s *TrackLocalStaticSample) RID() string { return s.rtpTrack.RID() } -// Kind controls if this TrackLocal is audio or video +// Kind controls if this TrackLocal is audio or video. func (s *TrackLocalStaticSample) Kind() RTPCodecType { return s.rtpTrack.Kind() } -// Codec gets the Codec of the track +// Codec gets the Codec of the track. func (s *TrackLocalStaticSample) Codec() RTPCodecCapability { return s.rtpTrack.Codec() } // Bind is called by the PeerConnection after negotiation is complete // This asserts that the code requested is supported by the remote peer. -// If so it setups all the state (SSRC and PayloadType) to have a call +// If so it setups all the state (SSRC and PayloadType) to have a call. func (s *TrackLocalStaticSample) Bind(t TrackLocalContext) (RTPCodecParameters, error) { codec, err := s.rtpTrack.Bind(t) if err != nil { @@ -278,6 +291,7 @@ func (s *TrackLocalStaticSample) Bind(t TrackLocalContext) (RTPCodecParameters, codec.ClockRate, ) s.clockRate = float64(codec.RTPCodecCapability.ClockRate) + return codec, nil } @@ -290,14 +304,14 @@ func (s *TrackLocalStaticSample) Unbind(t TrackLocalContext) error { // WriteSample writes a Sample to the TrackLocalStaticSample // If one PeerConnection fails the packets will still be sent to // all PeerConnections. The error message will contain the ID of the failed -// PeerConnections so you can remove them +// PeerConnections so you can remove them. func (s *TrackLocalStaticSample) WriteSample(sample media.Sample) error { s.rtpTrack.mu.RLock() - p := s.packetizer + packetizer := s.packetizer clockRate := s.clockRate s.rtpTrack.mu.RUnlock() - if p == nil { + if packetizer == nil { return nil } @@ -308,9 +322,9 @@ func (s *TrackLocalStaticSample) WriteSample(sample media.Sample) error { samples := uint32(sample.Duration.Seconds() * clockRate) if sample.PrevDroppedPackets > 0 { - p.SkipSamples(samples * uint32(sample.PrevDroppedPackets)) + packetizer.SkipSamples(samples * uint32(sample.PrevDroppedPackets)) } - packets := p.Packetize(sample.Data, samples) + packets := packetizer.Packetize(sample.Data, samples) writeErrs := []error{} for _, p := range packets { @@ -325,7 +339,7 @@ func (s *TrackLocalStaticSample) WriteSample(sample media.Sample) error { // GeneratePadding writes padding-only samples to the TrackLocalStaticSample // If one PeerConnection fails the packets will still be sent to // all PeerConnections. The error message will contain the ID of the failed -// PeerConnections so you can remove them +// PeerConnections so you can remove them. func (s *TrackLocalStaticSample) GeneratePadding(samples uint32) error { s.rtpTrack.mu.RLock() p := s.packetizer diff --git a/vendor/github.com/pion/webrtc/v4/track_remote.go b/vendor/github.com/pion/webrtc/v4/track_remote.go index 7e448dd989..1b037e7162 100644 --- a/vendor/github.com/pion/webrtc/v4/track_remote.go +++ b/vendor/github.com/pion/webrtc/v4/track_remote.go @@ -14,7 +14,7 @@ import ( "github.com/pion/rtp" ) -// TrackRemote represents a single inbound source of media +// TrackRemote represents a single inbound source of media. type TrackRemote struct { mu sync.RWMutex @@ -46,16 +46,17 @@ func newTrackRemote(kind RTPCodecType, ssrc, rtxSsrc SSRC, rid string, receiver // ID is the unique identifier for this Track. This should be unique for the // stream, but doesn't have to globally unique. A common example would be 'audio' or 'video' -// and StreamID would be 'desktop' or 'webcam' +// and StreamID would be 'desktop' or 'webcam'. func (t *TrackRemote) ID() string { t.mu.RLock() defer t.mu.RUnlock() + return t.id } // RID gets the RTP Stream ID of this Track // With Simulcast you will have multiple tracks with the same ID, but different RID values. -// In many cases a TrackRemote will not have an RID, so it is important to assert it is non-zero +// In many cases a TrackRemote will not have an RID, so it is important to assert it is non-zero. func (t *TrackRemote) RID() string { t.mu.RLock() defer t.mu.RUnlock() @@ -63,50 +64,55 @@ func (t *TrackRemote) RID() string { return t.rid } -// PayloadType gets the PayloadType of the track +// PayloadType gets the PayloadType of the track. func (t *TrackRemote) PayloadType() PayloadType { t.mu.RLock() defer t.mu.RUnlock() + return t.payloadType } -// Kind gets the Kind of the track +// Kind gets the Kind of the track. func (t *TrackRemote) Kind() RTPCodecType { t.mu.RLock() defer t.mu.RUnlock() + return t.kind } -// StreamID is the group this track belongs too. This must be unique +// StreamID is the group this track belongs too. This must be unique. func (t *TrackRemote) StreamID() string { t.mu.RLock() defer t.mu.RUnlock() + return t.streamID } -// SSRC gets the SSRC of the track +// SSRC gets the SSRC of the track. func (t *TrackRemote) SSRC() SSRC { t.mu.RLock() defer t.mu.RUnlock() + return t.ssrc } -// Msid gets the Msid of the track +// Msid gets the Msid of the track. func (t *TrackRemote) Msid() string { return t.StreamID() + " " + t.ID() } -// Codec gets the Codec of the track +// Codec gets the Codec of the track. func (t *TrackRemote) Codec() RTPCodecParameters { t.mu.RLock() defer t.mu.RUnlock() + return t.codec } // Read reads data from the track. func (t *TrackRemote) Read(b []byte) (n int, attributes interceptor.Attributes, err error) { t.mu.RLock() - r := t.receiver + receiver := t.receiver peeked := t.peeked != nil t.mu.RUnlock() @@ -123,12 +129,13 @@ func (t *TrackRemote) Read(b []byte) (n int, attributes interceptor.Attributes, if data != nil { n = copy(b, data) err = t.checkAndUpdateTrack(b) - return + + return n, attributes, err } } // If there's a separate RTX track and an RTX packet is available, return that - if rtxPacketReceived := r.readRTX(t); rtxPacketReceived != nil { + if rtxPacketReceived := receiver.readRTX(t); rtxPacketReceived != nil { n = copy(b, rtxPacketReceived.pkt) attributes = rtxPacketReceived.attributes rtxPacketReceived.release() @@ -136,10 +143,11 @@ func (t *TrackRemote) Read(b []byte) (n int, attributes interceptor.Attributes, } else { // If there's no separate RTX track (or there's a separate RTX track but no RTX packet waiting), wait for and return // a packet from the main track - n, attributes, err = r.readRTP(b, t) + n, attributes, err = receiver.readRTP(b, t) if err != nil { - return + return n, attributes, err } + err = t.checkAndUpdateTrack(b) } @@ -147,7 +155,7 @@ func (t *TrackRemote) Read(b []byte) (n int, attributes interceptor.Attributes, } // checkAndUpdateTrack checks payloadType for every incoming packet -// once a different payloadType is detected the track will be updated +// once a different payloadType is detected the track will be updated. func (t *TrackRemote) checkAndUpdateTrack(b []byte) error { if len(b) < 2 { return errRTPTooShort @@ -184,10 +192,11 @@ func (t *TrackRemote) ReadRTP() (*rtp.Packet, interceptor.Attributes, error) { if err := r.Unmarshal(b[:i]); err != nil { return nil, nil, err } + return r, attributes, nil } -// peek is like Read, but it doesn't discard the packet read +// peek is like Read, but it doesn't discard the packet read. func (t *TrackRemote) peek(b []byte) (n int, a interceptor.Attributes, err error) { n, a, err = t.Read(b) if err != nil { @@ -203,6 +212,7 @@ func (t *TrackRemote) peek(b []byte) (n int, a interceptor.Attributes, err error t.peeked = data t.peekedAttributes = a t.mu.Unlock() + return } @@ -211,17 +221,19 @@ func (t *TrackRemote) SetReadDeadline(deadline time.Time) error { return t.receiver.setRTPReadDeadline(deadline, t) } -// RtxSSRC returns the RTX SSRC for a track, or 0 if track does not have a separate RTX stream +// RtxSSRC returns the RTX SSRC for a track, or 0 if track does not have a separate RTX stream. func (t *TrackRemote) RtxSSRC() SSRC { t.mu.RLock() defer t.mu.RUnlock() + return t.rtxSsrc } -// HasRTX returns true if the track has a separate RTX stream +// HasRTX returns true if the track has a separate RTX stream. func (t *TrackRemote) HasRTX() bool { t.mu.RLock() defer t.mu.RUnlock() + return t.rtxSsrc != 0 } diff --git a/vendor/github.com/supranational/blst/bindings/go/README.md b/vendor/github.com/supranational/blst/bindings/go/README.md index 961853ed69..7bd6599d8d 100644 --- a/vendor/github.com/supranational/blst/bindings/go/README.md +++ b/vendor/github.com/supranational/blst/bindings/go/README.md @@ -13,10 +13,19 @@ go test The generate.py script is used to generate both min-pk and min-sig variants of the binding from a common code base. It consumes the `*.tgo` files along with `blst_minpk_test.go` and produces `blst.go` and `blst_minsig_test.go`. The .tgo files can treated as if they were .go files, including the use of gofmt and goimports. The generate script will filter out extra imports while processing and automatically run goimports on the final blst.go file. -After running generate.py, `go build` and `go test` can be run as usual. Cgo will compile `cgo_server.c`, which includes the required C implementation files, and `cgo_assembly.S`, which includes appropriate pre-generated assembly code for the platform. To compile on Windows one has to have MinGW gcc on the `%PATH%`. +After running generate.py, `go build` and `go test` can be run as usual. Cgo will compile `cgo_server.c`, which includes the required C implementation files, and `cgo_assembly.S`, which includes appropriate pre-generated assembly code for the platform. + +#### Caveats If the test or target application crashes with an "illegal instruction" exception [after copying to an older system], rebuild with `CGO_CFLAGS` environment variable set to `-O2 -D__BLST_PORTABLE__`. Don't forget `-O2`! +On Windows the C compiler invoked by cgo, one denoted in `go env CC` output, has to target [MinGW](https://www.mingw-w64.org/). Verify with ` -dM -E -x c nul: | findstr "MINGW64"`. + +If you're cross-compiling, you have to set `CC` environment variable to the target C cross-compiler and `CGO_ENABLED` to 1. For example, to compile the test program for ARM: +``` +env GOARCH=arm CC=arm-linux-gnueabi-gcc CGO_ENABLED=1 go test -c +``` + ## Usage There are two primary modes of operation that can be chosen based on type definitions in the application. @@ -73,8 +82,3 @@ func main() { ``` See the tests for further examples of usage. - -If you're cross-compiling, you have to set `CC` environment variable to the target C cross-compiler and `CGO_ENABLED` to 1. For example, to compile the test program for ARM: -``` -env GOARCH=arm CC=arm-linux-gnueabi-gcc CGO_ENABLED=1 go test -c -``` diff --git a/vendor/github.com/supranational/blst/bindings/go/blst.go b/vendor/github.com/supranational/blst/bindings/go/blst.go index 77f2241934..6fe6b31841 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst.go +++ b/vendor/github.com/supranational/blst/bindings/go/blst.go @@ -159,6 +159,7 @@ import ( "runtime" "sync" "sync/atomic" + "unsafe" ) const BLST_SCALAR_BYTES = 256 / 8 @@ -168,15 +169,15 @@ const BLST_P1_SERIALIZE_BYTES = BLST_FP_BYTES * 2 const BLST_P2_COMPRESS_BYTES = BLST_FP_BYTES * 2 const BLST_P2_SERIALIZE_BYTES = BLST_FP_BYTES * 4 -type Scalar = C.blst_scalar -type Fp = C.blst_fp -type Fp2 = C.blst_fp2 +type Scalar struct{ cgo C.blst_scalar } +type Fp struct{ cgo C.blst_fp } +type Fp2 struct{ cgo C.blst_fp2 } type Fp6 = C.blst_fp6 -type Fp12 = C.blst_fp12 -type P1 = C.blst_p1 -type P2 = C.blst_p2 -type P1Affine = C.blst_p1_affine -type P2Affine = C.blst_p2_affine +type Fp12 struct{ cgo C.blst_fp12 } +type P1 struct{ cgo C.blst_p1 } +type P2 struct{ cgo C.blst_p2 } +type P1Affine struct{ cgo C.blst_p1_affine } +type P2Affine struct{ cgo C.blst_p2_affine } type Message = []byte type Pairing = []C.blst_pairing type SecretKey = Scalar @@ -205,11 +206,11 @@ func initMaxProcs() int { return maxProcs } -func SetMaxProcs(max int) { - if max <= 0 { - max = 1 +func SetMaxProcs(procs int) { + if procs <= 0 { + procs = 1 } - maxProcs = max + maxProcs = procs } func numThreads(maxThreads int) int { @@ -229,9 +230,9 @@ func numThreads(maxThreads int) int { } var cgo_pairingSizeOf = C.blst_pairing_sizeof() -var cgo_p1Generator = *C.blst_p1_generator() -var cgo_p2Generator = *C.blst_p2_generator() -var cgo_fp12One = *C.blst_fp12_one() +var cgo_p1Generator = P1{*C.blst_p1_generator()} +var cgo_p2Generator = P2{*C.blst_p2_generator()} +var cgo_fp12One = Fp12{*C.blst_fp12_one()} // Secret key func (sk *SecretKey) Zeroize() { @@ -248,7 +249,7 @@ func KeyGen(ikm []byte, optional ...[]byte) *SecretKey { if len(ikm) < 32 { return nil } - C.blst_keygen(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... @@ -265,7 +266,7 @@ func KeyGenV3(ikm []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v3(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen_v3(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... @@ -282,7 +283,7 @@ func KeyGenV45(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v4_5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen_v4_5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), (*C.byte)(&salt[0]), C.size_t(len(salt)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too @@ -300,7 +301,7 @@ func KeyGenV5(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + C.blst_keygen_v5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), (*C.byte)(&salt[0]), C.size_t(len(salt)), ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too @@ -314,7 +315,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { return nil } var sk SecretKey - C.blst_derive_master_eip2333(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) + C.blst_derive_master_eip2333(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -323,7 +324,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { func (master *SecretKey) DeriveChildEip2333(child_index uint32) *SecretKey { var sk SecretKey - C.blst_derive_child_eip2333(&sk, master, C.uint(child_index)) + C.blst_derive_child_eip2333(&sk.cgo, &master.cgo, C.uint(child_index)) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -356,30 +357,38 @@ func PairingFinalVerify(ctx Pairing, optional ...*Fp12) bool { if len(optional) > 0 { gtsig = optional[0] } - return bool(C.blst_pairing_finalverify(&ctx[0], gtsig)) + return bool(C.blst_pairing_finalverify(&ctx[0], gtsig.asPtr())) } func PairingRawAggregate(ctx Pairing, q *P2Affine, p *P1Affine) { - C.blst_pairing_raw_aggregate(&ctx[0], q, p) + C.blst_pairing_raw_aggregate(&ctx[0], &q.cgo, &p.cgo) } func PairingAsFp12(ctx Pairing) *Fp12 { var pt Fp12 - C.go_pairing_as_fp12(&pt, &ctx[0]) + C.go_pairing_as_fp12(&pt.cgo, &ctx[0]) return &pt } +func (pt *Fp12) asPtr() *C.blst_fp12 { + if pt != nil { + return &pt.cgo + } + + return nil +} + func Fp12One() Fp12 { return cgo_fp12One } func Fp12FinalVerify(pt1 *Fp12, pt2 *Fp12) bool { - return bool(C.blst_fp12_finalverify(pt1, pt2)) + return bool(C.blst_fp12_finalverify(&pt1.cgo, &pt2.cgo)) } func Fp12MillerLoop(q *P2Affine, p *P1Affine) *Fp12 { var pt Fp12 - C.blst_miller_loop(&pt, q, p) + C.blst_miller_loop(&pt.cgo, &q.cgo, &p.cgo) return &pt } @@ -393,7 +402,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if nThreads == 1 || nElems == 1 { var pt Fp12 - C.go_miller_loop_n(&pt, &qs[0], &ps[0], C.size_t(nElems), false) + C.go_miller_loop_n(&pt.cgo, &qs[0].cgo, &ps[0].cgo, C.size_t(nElems), false) return &pt } @@ -423,7 +432,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if n > stride { n = stride } - C.go_miller_loop_n(&acc, &qs[work], &ps[work], C.size_t(n), + C.go_miller_loop_n(&acc.cgo, &qs[work].cgo, &ps[work].cgo, C.size_t(n), C.bool(!first)) first = false } @@ -437,25 +446,25 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { } var pt Fp12 - C.go_fp12slice_mul(&pt, &ret[0], C.size_t(nThreads)) + C.go_fp12slice_mul(&pt.cgo, &ret[0].cgo, C.size_t(nThreads)) return &pt } func (pt *Fp12) MulAssign(p *Fp12) { - C.blst_fp12_mul(pt, pt, p) + C.blst_fp12_mul(&pt.cgo, &pt.cgo, &p.cgo) } func (pt *Fp12) FinalExp() { - C.blst_final_exp(pt, pt) + C.blst_final_exp(&pt.cgo, &pt.cgo) } func (pt *Fp12) InGroup() bool { - return bool(C.blst_fp12_in_group(pt)) + return bool(C.blst_fp12_in_group(&pt.cgo)) } func (pt *Fp12) ToBendian() []byte { var out [BLST_FP_BYTES * 12]byte - C.blst_bendian_from_fp12((*C.byte)(&out[0]), pt) + C.blst_bendian_from_fp12((*C.byte)(&out[0]), &pt.cgo) return out[:] } @@ -479,13 +488,21 @@ func ptrOrNil(bytes []byte) *C.byte { // PublicKey // +func (pt *P1Affine) asPtr() *C.blst_p1_affine { + if pt != nil { + return &pt.cgo + } + + return nil +} + func (pk *P1Affine) From(s *Scalar) *P1Affine { - C.blst_sk_to_pk2_in_g1(nil, pk, s) + C.blst_sk_to_pk2_in_g1(nil, &pk.cgo, &s.cgo) return pk } func (pk *P1Affine) KeyValidate() bool { - return bool(C.go_p1_affine_validate(pk, true)) + return bool(C.go_p1_affine_validate(&pk.cgo, true)) } // sigInfcheck, check for infinity, is a way to avoid going @@ -493,7 +510,7 @@ func (pk *P1Affine) KeyValidate() bool { // always cryptographically safe, but application might want // to guard against obviously bogus individual[!] signatures. func (sig *P2Affine) SigValidate(sigInfcheck bool) bool { - return bool(C.go_p2_affine_validate(sig, C.bool(sigInfcheck))) + return bool(C.go_p2_affine_validate(&sig.cgo, C.bool(sigInfcheck))) } // @@ -513,7 +530,7 @@ func (sig *P2Affine) Sign(sk *SecretKey, msg []byte, dst []byte, } else { q = EncodeToG2(msg, dst, augSingle) } - C.blst_sign_pk2_in_g1(nil, sig, q, sk) + C.blst_sign_pk2_in_g1(nil, &sig.cgo, &q.cgo, &sk.cgo) return sig } @@ -717,7 +734,7 @@ func coreAggregateVerifyPkInG1(sigFn sigGetterP2, sigGroupcheck bool, atomic.StoreInt32(&valid, 0) } if atomic.LoadInt32(&valid) > 0 { - C.blst_aggregated_in_g2(>sig, sig) + C.blst_aggregated_in_g2(>sig.cgo, &sig.cgo) } mutex.Unlock() @@ -765,7 +782,7 @@ func CoreVerifyPkInG1(pk *P1Affine, sig *P2Affine, hash_or_encode bool, return C.BLST_SUCCESS } - return int(C.blst_core_verify_pk_in_g1(pk, sig, C.bool(hash_or_encode), + return int(C.blst_core_verify_pk_in_g1(&pk.cgo, &sig.cgo, C.bool(hash_or_encode), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug)))) @@ -959,19 +976,19 @@ func (agg *P2Aggregate) AddAggregate(other *P2Aggregate) { } else if agg.v == nil { agg.v = other.v } else { - C.blst_p2_add_or_double(agg.v, agg.v, other.v) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &other.v.cgo) } } func (agg *P2Aggregate) Add(elmt *P2Affine, groupcheck bool) bool { - if groupcheck && !bool(C.blst_p2_affine_in_g2(elmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&elmt.cgo)) { return false } if agg.v == nil { agg.v = new(P2) - C.blst_p2_from_affine(agg.v, elmt) + C.blst_p2_from_affine(&agg.v.cgo, &elmt.cgo) } else { - C.blst_p2_add_or_double_affine(agg.v, agg.v, elmt) + C.blst_p2_add_or_double_affine(&agg.v.cgo, &agg.v.cgo, &elmt.cgo) } return true } @@ -1021,15 +1038,15 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, atomic.StoreInt32(&valid, 0) break } - if groupcheck && !bool(C.blst_p2_affine_in_g2(curElmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&curElmt.cgo)) { atomic.StoreInt32(&valid, 0) break } if first { - C.blst_p2_from_affine(&agg, curElmt) + C.blst_p2_from_affine(&agg.cgo, &curElmt.cgo) first = false } else { - C.blst_p2_add_or_double_affine(&agg, &agg, curElmt) + C.blst_p2_add_or_double_affine(&agg.cgo, &agg.cgo, &curElmt.cgo) } // application might have some async work to do runtime.Gosched() @@ -1060,7 +1077,7 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, agg.v = msg.agg first = false } else { - C.blst_p2_add_or_double(agg.v, agg.v, msg.agg) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &msg.agg.cgo) } } } @@ -1079,13 +1096,21 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, // PublicKey // +func (pt *P2Affine) asPtr() *C.blst_p2_affine { + if pt != nil { + return &pt.cgo + } + + return nil +} + func (pk *P2Affine) From(s *Scalar) *P2Affine { - C.blst_sk_to_pk2_in_g2(nil, pk, s) + C.blst_sk_to_pk2_in_g2(nil, &pk.cgo, &s.cgo) return pk } func (pk *P2Affine) KeyValidate() bool { - return bool(C.go_p2_affine_validate(pk, true)) + return bool(C.go_p2_affine_validate(&pk.cgo, true)) } // sigInfcheck, check for infinity, is a way to avoid going @@ -1093,7 +1118,7 @@ func (pk *P2Affine) KeyValidate() bool { // always cryptographically safe, but application might want // to guard against obviously bogus individual[!] signatures. func (sig *P1Affine) SigValidate(sigInfcheck bool) bool { - return bool(C.go_p1_affine_validate(sig, C.bool(sigInfcheck))) + return bool(C.go_p1_affine_validate(&sig.cgo, C.bool(sigInfcheck))) } // @@ -1113,7 +1138,7 @@ func (sig *P1Affine) Sign(sk *SecretKey, msg []byte, dst []byte, } else { q = EncodeToG1(msg, dst, augSingle) } - C.blst_sign_pk2_in_g2(nil, sig, q, sk) + C.blst_sign_pk2_in_g2(nil, &sig.cgo, &q.cgo, &sk.cgo) return sig } @@ -1317,7 +1342,7 @@ func coreAggregateVerifyPkInG2(sigFn sigGetterP1, sigGroupcheck bool, atomic.StoreInt32(&valid, 0) } if atomic.LoadInt32(&valid) > 0 { - C.blst_aggregated_in_g1(>sig, sig) + C.blst_aggregated_in_g1(>sig.cgo, &sig.cgo) } mutex.Unlock() @@ -1365,7 +1390,7 @@ func CoreVerifyPkInG2(pk *P2Affine, sig *P1Affine, hash_or_encode bool, return C.BLST_SUCCESS } - return int(C.blst_core_verify_pk_in_g2(pk, sig, C.bool(hash_or_encode), + return int(C.blst_core_verify_pk_in_g2(&pk.cgo, &sig.cgo, C.bool(hash_or_encode), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug)))) @@ -1559,19 +1584,19 @@ func (agg *P1Aggregate) AddAggregate(other *P1Aggregate) { } else if agg.v == nil { agg.v = other.v } else { - C.blst_p1_add_or_double(agg.v, agg.v, other.v) + C.blst_p1_add_or_double(&agg.v.cgo, &agg.v.cgo, &other.v.cgo) } } func (agg *P1Aggregate) Add(elmt *P1Affine, groupcheck bool) bool { - if groupcheck && !bool(C.blst_p1_affine_in_g1(elmt)) { + if groupcheck && !bool(C.blst_p1_affine_in_g1(&elmt.cgo)) { return false } if agg.v == nil { agg.v = new(P1) - C.blst_p1_from_affine(agg.v, elmt) + C.blst_p1_from_affine(&agg.v.cgo, &elmt.cgo) } else { - C.blst_p1_add_or_double_affine(agg.v, agg.v, elmt) + C.blst_p1_add_or_double_affine(&agg.v.cgo, &agg.v.cgo, &elmt.cgo) } return true } @@ -1621,15 +1646,15 @@ func (agg *P1Aggregate) coreAggregate(getter aggGetterP1, groupcheck bool, atomic.StoreInt32(&valid, 0) break } - if groupcheck && !bool(C.blst_p1_affine_in_g1(curElmt)) { + if groupcheck && !bool(C.blst_p1_affine_in_g1(&curElmt.cgo)) { atomic.StoreInt32(&valid, 0) break } if first { - C.blst_p1_from_affine(&agg, curElmt) + C.blst_p1_from_affine(&agg.cgo, &curElmt.cgo) first = false } else { - C.blst_p1_add_or_double_affine(&agg, &agg, curElmt) + C.blst_p1_add_or_double_affine(&agg.cgo, &agg.cgo, &curElmt.cgo) } // application might have some async work to do runtime.Gosched() @@ -1660,7 +1685,7 @@ func (agg *P1Aggregate) coreAggregate(getter aggGetterP1, groupcheck bool, agg.v = msg.agg first = false } else { - C.blst_p1_add_or_double(agg.v, agg.v, msg.agg) + C.blst_p1_add_or_double(&agg.v.cgo, &agg.v.cgo, &msg.agg.cgo) } } } @@ -1679,8 +1704,8 @@ func PairingAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -1697,9 +1722,9 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_mul_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), - &rand.b[0], C.size_t(randBits), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), + &rand.cgo.b[0], C.size_t(randBits), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -1713,7 +1738,7 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, // P1 Serdes func (p1 *P1Affine) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_affine_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_affine_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -1721,14 +1746,14 @@ func (p1 *P1Affine) Deserialize(in []byte) *P1Affine { if len(in) != BLST_P1_SERIALIZE_BYTES { return nil } - if C.blst_p1_deserialize(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_deserialize(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_affine_compress((*C.byte)(&out[0]), p1) + C.blst_p1_affine_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -1736,14 +1761,14 @@ func (p1 *P1Affine) Uncompress(in []byte) *P1Affine { if len(in) != BLST_P1_COMPRESS_BYTES { return nil } - if C.blst_p1_uncompress(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_uncompress(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) InG1() bool { - return bool(C.blst_p1_affine_in_g1(p1)) + return bool(C.blst_p1_affine_in_g1(&p1.cgo)) } func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { @@ -1800,12 +1825,12 @@ func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { func (p1 *P1) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } func (p1 *P1) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_compress((*C.byte)(&out[0]), p1) + C.blst_p1_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -1817,7 +1842,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -1825,7 +1850,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { if len(optional) > 0 { nbits = optional[0] } - C.blst_p1_mult(p1, p1, scalar, C.size_t(nbits)) + C.blst_p1_mult(&p1.cgo, &p1.cgo, scalar, C.size_t(nbits)) return p1 } @@ -1837,9 +1862,9 @@ func (p1 *P1) Mult(scalarIf interface{}, optional ...int) *P1 { func (p1 *P1) AddAssign(pointIf interface{}) *P1 { switch val := pointIf.(type) { case *P1: - C.blst_p1_add_or_double(p1, p1, val) + C.blst_p1_add_or_double(&p1.cgo, &p1.cgo, &val.cgo) case *P1Affine: - C.blst_p1_add_or_double_affine(p1, p1, val) + C.blst_p1_add_or_double_affine(&p1.cgo, &p1.cgo, &val.cgo) default: panic(fmt.Sprintf("unsupported type %T", val)) } @@ -1852,19 +1877,19 @@ func (p1 *P1) Add(pointIf interface{}) *P1 { } func (p1 *P1) SubAssign(pointIf interface{}) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) } - C.go_p1_sub_assign(p1, x, affine) + C.go_p1_sub_assign(&p1.cgo, x, affine) return p1 } @@ -1882,15 +1907,15 @@ func P1Generator() *P1 { // group generator point" func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, optional ...int) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool if pointIf != nil { switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -1903,7 +1928,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -1911,7 +1936,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, if len(optional) > 0 { nbits = optional[0] } - C.go_p1_mult_n_acc(acc, x, affine, scalar, C.size_t(nbits)) + C.go_p1_mult_n_acc(&acc.cgo, x, affine, scalar, C.size_t(nbits)) return acc } @@ -1921,12 +1946,12 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, func (p *P1) ToAffine() *P1Affine { var pa P1Affine - C.blst_p1_to_affine(&pa, p) + C.blst_p1_to_affine(&pa.cgo, &p.cgo) return &pa } func (p *P1) FromAffine(pa *P1Affine) { - C.blst_p1_from_affine(p, pa) + C.blst_p1_from_affine(&p.cgo, &pa.cgo) } // Hash @@ -1939,7 +1964,7 @@ func HashToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_hash_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_hash_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -1954,7 +1979,7 @@ func EncodeToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_encode_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_encode_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -1973,7 +1998,8 @@ func P1sToAffine(points []*P1, optional ...int) P1Affines { } ret := make([]P1Affine, npoints) _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.blst_p1s_to_affine(&ret[0].cgo, (**C.blst_p1)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return ret } @@ -1991,7 +2017,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } if maxProcs < 2 || npoints < 768 { - C.go_p1slice_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.go_p1slice_to_affine(&ret[0].cgo, &points[0].cgo, C.size_t(npoints)) return ret } @@ -2009,7 +2035,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } rem -= 1 go func(out *P1Affine, inp *P1, delta int) { - C.go_p1slice_to_affine(out, inp, C.size_t(delta)) + C.go_p1slice_to_affine(&out.cgo, &inp.cgo, C.size_t(delta)) wg.Done() }(&ret[x], &points[x], delta) } @@ -2031,7 +2057,8 @@ func P1AffinesAdd(points []*P1Affine, optional ...int) *P1 { } var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_add(&ret, &points[0], C.size_t(npoints)) + C.blst_p1s_add(&ret.cgo, (**C.blst_p1_affine)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return &ret } @@ -2039,7 +2066,7 @@ func (points P1Affines) Add() *P1 { npoints := len(points) if maxProcs < 2 || npoints < 768 { var ret P1 - C.go_p1slice_add(&ret, &points[0], C.size_t(npoints)) + C.go_p1slice_add(&ret.cgo, &points[0].cgo, C.size_t(npoints)) return &ret } @@ -2057,7 +2084,7 @@ func (points P1Affines) Add() *P1 { rem -= 1 go func(points *P1Affine, delta int) { var ret P1 - C.go_p1slice_add(&ret, points, C.size_t(delta)) + C.go_p1slice_add(&ret.cgo, &points.cgo, C.size_t(delta)) msgs <- ret }(&points[x], delta) } @@ -2065,7 +2092,7 @@ func (points P1Affines) Add() *P1 { ret := <-msgs for i := 1; i < nslices; i++ { msg := <-msgs - C.blst_p1_add_or_double(&ret, &ret, &msg) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &msg.cgo) } return &ret } @@ -2113,7 +2140,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { if nbits <= 248 { scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } } case []*Scalar: @@ -2122,7 +2149,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { } scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2134,16 +2161,16 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { sz := int(C.blst_p1s_mult_pippenger_scratch_sizeof(C.size_t(npoints))) / 8 scratch := make([]uint64, sz) - pointsBySlice := [2]*P1Affine{nil, nil} - var p_points **P1Affine + pointsBySlice := [2]*C.blst_p1_affine{nil, nil} + var p_points **C.blst_p1_affine switch val := pointsIf.(type) { case []*P1Affine: - p_points = &val[0] + p_points = (**C.blst_p1_affine)(unsafe.Pointer(&val[0])) case []P1Affine: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] case P1Affines: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] } @@ -2157,7 +2184,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[0] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[0].b[0] + scalarsBySlice[0] = &val[0].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[0] @@ -2168,7 +2195,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_mult_pippenger(&ret, p_points, C.size_t(npoints), + C.blst_p1s_mult_pippenger(&ret.cgo, p_points, C.size_t(npoints), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0])) @@ -2215,7 +2242,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] case []Scalar: if nbits > 248 { - scalar = &val[workItem].b[0] + scalar = &val[workItem].cgo.b[0] } else { scalar = scalars[workItem] } @@ -2223,7 +2250,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] } - C.go_p1_mult_n_acc(&acc, &point.x, true, + C.go_p1_mult_n_acc(&acc.cgo, &point.cgo.x, true, scalar, C.size_t(nbits)) } @@ -2234,7 +2261,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { ret := <-msgs for tid := 1; tid < numThreads; tid++ { point := <-msgs - C.blst_p1_add_or_double(&ret, &ret, &point) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &point.cgo) } for i := range scalars { @@ -2288,7 +2315,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { for tid := 0; tid < numThreads; tid++ { go func() { scratch := make([]uint64, sz< 248 { - scalarsBySlice[0] = &val[x].b[0] + scalarsBySlice[0] = &val[x].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[x] @@ -2331,7 +2358,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[x] } - C.blst_p1s_tile_pippenger(&grid[workItem].point, + C.blst_p1s_tile_pippenger(&grid[workItem].point.cgo, p_points, C.size_t(grid[workItem].dx), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0]), @@ -2357,14 +2384,14 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { rows[y/window] = true // mark the "row" for grid[row].y == y { // if it's current "row", process it for row < total && grid[row].y == y { - C.blst_p1_add_or_double(&ret, &ret, &grid[row].point) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &grid[row].point.cgo) row++ } if y == 0 { break // one can as well 'return &ret' here } for j := 0; j < window; j++ { - C.blst_p1_double(&ret, &ret) + C.blst_p1_double(&ret.cgo, &ret.cgo) } y -= window if !rows[y/window] { // see if next "row" was marked already @@ -2422,7 +2449,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { return false } } @@ -2457,7 +2484,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { atomic.StoreInt32(&valid, 0) break } @@ -2484,8 +2511,8 @@ func PairingAggregatePkInG2(ctx Pairing, PK *P2Affine, pkValidate bool, } r := C.blst_pairing_chk_n_aggr_pk_in_g2(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -2502,9 +2529,9 @@ func PairingMulNAggregatePkInG2(ctx Pairing, PK *P2Affine, pkValidate bool, } r := C.blst_pairing_chk_n_mul_n_aggr_pk_in_g2(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), - &rand.b[0], C.size_t(randBits), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), + &rand.cgo.b[0], C.size_t(randBits), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -2518,7 +2545,7 @@ func PairingMulNAggregatePkInG2(ctx Pairing, PK *P2Affine, pkValidate bool, // P2 Serdes func (p2 *P2Affine) Serialize() []byte { var out [BLST_P2_SERIALIZE_BYTES]byte - C.blst_p2_affine_serialize((*C.byte)(&out[0]), p2) + C.blst_p2_affine_serialize((*C.byte)(&out[0]), &p2.cgo) return out[:] } @@ -2526,14 +2553,14 @@ func (p2 *P2Affine) Deserialize(in []byte) *P2Affine { if len(in) != BLST_P2_SERIALIZE_BYTES { return nil } - if C.blst_p2_deserialize(p2, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p2_deserialize(&p2.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p2 } func (p2 *P2Affine) Compress() []byte { var out [BLST_P2_COMPRESS_BYTES]byte - C.blst_p2_affine_compress((*C.byte)(&out[0]), p2) + C.blst_p2_affine_compress((*C.byte)(&out[0]), &p2.cgo) return out[:] } @@ -2541,14 +2568,14 @@ func (p2 *P2Affine) Uncompress(in []byte) *P2Affine { if len(in) != BLST_P2_COMPRESS_BYTES { return nil } - if C.blst_p2_uncompress(p2, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p2_uncompress(&p2.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p2 } func (p2 *P2Affine) InG2() bool { - return bool(C.blst_p2_affine_in_g2(p2)) + return bool(C.blst_p2_affine_in_g2(&p2.cgo)) } func (_ *P2Affine) BatchUncompress(in [][]byte) []*P2Affine { @@ -2605,12 +2632,12 @@ func (_ *P2Affine) BatchUncompress(in [][]byte) []*P2Affine { func (p2 *P2) Serialize() []byte { var out [BLST_P2_SERIALIZE_BYTES]byte - C.blst_p2_serialize((*C.byte)(&out[0]), p2) + C.blst_p2_serialize((*C.byte)(&out[0]), &p2.cgo) return out[:] } func (p2 *P2) Compress() []byte { var out [BLST_P2_COMPRESS_BYTES]byte - C.blst_p2_compress((*C.byte)(&out[0]), p2) + C.blst_p2_compress((*C.byte)(&out[0]), &p2.cgo) return out[:] } @@ -2622,7 +2649,7 @@ func (p2 *P2) MultAssign(scalarIf interface{}, optional ...int) *P2 { scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2630,7 +2657,7 @@ func (p2 *P2) MultAssign(scalarIf interface{}, optional ...int) *P2 { if len(optional) > 0 { nbits = optional[0] } - C.blst_p2_mult(p2, p2, scalar, C.size_t(nbits)) + C.blst_p2_mult(&p2.cgo, &p2.cgo, scalar, C.size_t(nbits)) return p2 } @@ -2642,9 +2669,9 @@ func (p2 *P2) Mult(scalarIf interface{}, optional ...int) *P2 { func (p2 *P2) AddAssign(pointIf interface{}) *P2 { switch val := pointIf.(type) { case *P2: - C.blst_p2_add_or_double(p2, p2, val) + C.blst_p2_add_or_double(&p2.cgo, &p2.cgo, &val.cgo) case *P2Affine: - C.blst_p2_add_or_double_affine(p2, p2, val) + C.blst_p2_add_or_double_affine(&p2.cgo, &p2.cgo, &val.cgo) default: panic(fmt.Sprintf("unsupported type %T", val)) } @@ -2657,19 +2684,19 @@ func (p2 *P2) Add(pointIf interface{}) *P2 { } func (p2 *P2) SubAssign(pointIf interface{}) *P2 { - var x *Fp2 + var x *C.blst_fp2 var affine C.bool switch val := pointIf.(type) { case *P2: - x = &val.x + x = &val.cgo.x affine = false case *P2Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) } - C.go_p2_sub_assign(p2, x, affine) + C.go_p2_sub_assign(&p2.cgo, x, affine) return p2 } @@ -2687,15 +2714,15 @@ func P2Generator() *P2 { // group generator point" func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, optional ...int) *P2 { - var x *Fp2 + var x *C.blst_fp2 var affine C.bool if pointIf != nil { switch val := pointIf.(type) { case *P2: - x = &val.x + x = &val.cgo.x affine = false case *P2Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2708,7 +2735,7 @@ func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, scalar = (*C.byte)(&val[0]) nbits = len(val) * 8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2716,7 +2743,7 @@ func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, if len(optional) > 0 { nbits = optional[0] } - C.go_p2_mult_n_acc(acc, x, affine, scalar, C.size_t(nbits)) + C.go_p2_mult_n_acc(&acc.cgo, x, affine, scalar, C.size_t(nbits)) return acc } @@ -2726,12 +2753,12 @@ func (acc *P2) MultNAccumulate(pointIf interface{}, scalarIf interface{}, func (p *P2) ToAffine() *P2Affine { var pa P2Affine - C.blst_p2_to_affine(&pa, p) + C.blst_p2_to_affine(&pa.cgo, &p.cgo) return &pa } func (p *P2) FromAffine(pa *P2Affine) { - C.blst_p2_from_affine(p, pa) + C.blst_p2_from_affine(&p.cgo, &pa.cgo) } // Hash @@ -2744,7 +2771,7 @@ func HashToG2(msg []byte, dst []byte, aug = optional[0] } - C.blst_hash_to_g2(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_hash_to_g2(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -2759,7 +2786,7 @@ func EncodeToG2(msg []byte, dst []byte, aug = optional[0] } - C.blst_encode_to_g2(&q, ptrOrNil(msg), C.size_t(len(msg)), + C.blst_encode_to_g2(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug))) return &q @@ -2778,7 +2805,8 @@ func P2sToAffine(points []*P2, optional ...int) P2Affines { } ret := make([]P2Affine, npoints) _cgoCheckPointer := func(...interface{}) {} - C.blst_p2s_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.blst_p2s_to_affine(&ret[0].cgo, (**C.blst_p2)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return ret } @@ -2796,7 +2824,7 @@ func (points P2s) ToAffine(optional ...P2Affines) P2Affines { } if maxProcs < 2 || npoints < 768 { - C.go_p2slice_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.go_p2slice_to_affine(&ret[0].cgo, &points[0].cgo, C.size_t(npoints)) return ret } @@ -2814,7 +2842,7 @@ func (points P2s) ToAffine(optional ...P2Affines) P2Affines { } rem -= 1 go func(out *P2Affine, inp *P2, delta int) { - C.go_p2slice_to_affine(out, inp, C.size_t(delta)) + C.go_p2slice_to_affine(&out.cgo, &inp.cgo, C.size_t(delta)) wg.Done() }(&ret[x], &points[x], delta) } @@ -2836,7 +2864,8 @@ func P2AffinesAdd(points []*P2Affine, optional ...int) *P2 { } var ret P2 _cgoCheckPointer := func(...interface{}) {} - C.blst_p2s_add(&ret, &points[0], C.size_t(npoints)) + C.blst_p2s_add(&ret.cgo, (**C.blst_p2_affine)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return &ret } @@ -2844,7 +2873,7 @@ func (points P2Affines) Add() *P2 { npoints := len(points) if maxProcs < 2 || npoints < 768 { var ret P2 - C.go_p2slice_add(&ret, &points[0], C.size_t(npoints)) + C.go_p2slice_add(&ret.cgo, &points[0].cgo, C.size_t(npoints)) return &ret } @@ -2862,7 +2891,7 @@ func (points P2Affines) Add() *P2 { rem -= 1 go func(points *P2Affine, delta int) { var ret P2 - C.go_p2slice_add(&ret, points, C.size_t(delta)) + C.go_p2slice_add(&ret.cgo, &points.cgo, C.size_t(delta)) msgs <- ret }(&points[x], delta) } @@ -2870,7 +2899,7 @@ func (points P2Affines) Add() *P2 { ret := <-msgs for i := 1; i < nslices; i++ { msg := <-msgs - C.blst_p2_add_or_double(&ret, &ret, &msg) + C.blst_p2_add_or_double(&ret.cgo, &ret.cgo, &msg.cgo) } return &ret } @@ -2918,7 +2947,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { if nbits <= 248 { scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } } case []*Scalar: @@ -2927,7 +2956,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { } scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -2939,16 +2968,16 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { sz := int(C.blst_p2s_mult_pippenger_scratch_sizeof(C.size_t(npoints))) / 8 scratch := make([]uint64, sz) - pointsBySlice := [2]*P2Affine{nil, nil} - var p_points **P2Affine + pointsBySlice := [2]*C.blst_p2_affine{nil, nil} + var p_points **C.blst_p2_affine switch val := pointsIf.(type) { case []*P2Affine: - p_points = &val[0] + p_points = (**C.blst_p2_affine)(unsafe.Pointer(&val[0])) case []P2Affine: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] case P2Affines: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] } @@ -2962,7 +2991,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { p_scalars = &scalars[0] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[0].b[0] + scalarsBySlice[0] = &val[0].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[0] @@ -2973,7 +3002,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { var ret P2 _cgoCheckPointer := func(...interface{}) {} - C.blst_p2s_mult_pippenger(&ret, p_points, C.size_t(npoints), + C.blst_p2s_mult_pippenger(&ret.cgo, p_points, C.size_t(npoints), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0])) @@ -3020,7 +3049,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { scalar = scalars[workItem] case []Scalar: if nbits > 248 { - scalar = &val[workItem].b[0] + scalar = &val[workItem].cgo.b[0] } else { scalar = scalars[workItem] } @@ -3028,7 +3057,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { scalar = scalars[workItem] } - C.go_p2_mult_n_acc(&acc, &point.x, true, + C.go_p2_mult_n_acc(&acc.cgo, &point.cgo.x, true, scalar, C.size_t(nbits)) } @@ -3039,7 +3068,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { ret := <-msgs for tid := 1; tid < numThreads; tid++ { point := <-msgs - C.blst_p2_add_or_double(&ret, &ret, &point) + C.blst_p2_add_or_double(&ret.cgo, &ret.cgo, &point.cgo) } for i := range scalars { @@ -3093,7 +3122,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { for tid := 0; tid < numThreads; tid++ { go func() { scratch := make([]uint64, sz< 248 { - scalarsBySlice[0] = &val[x].b[0] + scalarsBySlice[0] = &val[x].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[x] @@ -3136,7 +3165,7 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { p_scalars = &scalars[x] } - C.blst_p2s_tile_pippenger(&grid[workItem].point, + C.blst_p2s_tile_pippenger(&grid[workItem].point.cgo, p_points, C.size_t(grid[workItem].dx), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0]), @@ -3162,14 +3191,14 @@ func P2AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P2 { rows[y/window] = true // mark the "row" for grid[row].y == y { // if it's current "row", process it for row < total && grid[row].y == y { - C.blst_p2_add_or_double(&ret, &ret, &grid[row].point) + C.blst_p2_add_or_double(&ret.cgo, &ret.cgo, &grid[row].point.cgo) row++ } if y == 0 { break // one can as well 'return &ret' here } for j := 0; j < window; j++ { - C.blst_p2_double(&ret, &ret) + C.blst_p2_double(&ret.cgo, &ret.cgo) } y -= window if !rows[y/window] { // see if next "row" was marked already @@ -3227,7 +3256,7 @@ func P2AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p2_affine_validate(point, true) { + if !C.go_p2_affine_validate(&point.cgo, true) { return false } } @@ -3262,7 +3291,7 @@ func P2AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p2_affine_validate(point, true) { + if !C.go_p2_affine_validate(&point.cgo, true) { atomic.StoreInt32(&valid, 0) break } @@ -3281,10 +3310,10 @@ func (points P2Affines) Validate() bool { return P2AffinesValidate(points) } -func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { - var aug [][]byte // For aggregate verify - var augSingle []byte // For signing - useHash := true // hash (true), encode (false) +// aug [][]byte - augmentation bytes for signing (default: nil) +func parseOpts(optional ...interface{}) (augSingle []byte, aug [][]byte, + useHash bool, ok bool) { + useHash = true // hash (true), encode (false) for _, arg := range optional { switch v := arg.(type) { @@ -3305,35 +3334,35 @@ func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { // reason they should be used primarily for prototyping with a goal to // formulate interfaces that would process multiple scalars per cgo call. func (a *Scalar) MulAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_mul_n_check(a, a, b)) + return a, bool(C.blst_sk_mul_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Mul(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_mul_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_mul_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) AddAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_add_n_check(a, a, b)) + return a, bool(C.blst_sk_add_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Add(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_add_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_add_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) SubAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_sub_n_check(a, a, b)) + return a, bool(C.blst_sk_sub_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Sub(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_sub_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_sub_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Inverse() *Scalar { var ret Scalar - C.blst_sk_inverse(&ret, a) + C.blst_sk_inverse(&ret.cgo, &a.cgo) return &ret } @@ -3344,20 +3373,20 @@ func (a *Scalar) Inverse() *Scalar { // Scalar serdes func (s *Scalar) Serialize() []byte { var out [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&out[0]), s) + C.blst_bendian_from_scalar((*C.byte)(&out[0]), &s.cgo) return out[:] } func (s *Scalar) Deserialize(in []byte) *Scalar { if len(in) != BLST_SCALAR_BYTES || - !C.go_scalar_from_bendian(s, (*C.byte)(&in[0])) { + !C.go_scalar_from_bendian(&s.cgo, (*C.byte)(&in[0])) { return nil } return s } func (s *Scalar) Valid() bool { - return bool(C.blst_sk_check(s)) + return bool(C.blst_sk_check(&s.cgo)) } func (s *Scalar) HashTo(msg []byte, dst []byte) bool { @@ -3372,7 +3401,7 @@ func (s *Scalar) HashTo(msg []byte, dst []byte) bool { func HashToScalar(msg []byte, dst []byte) *Scalar { var ret Scalar - if C.go_hash_to_scalar(&ret, ptrOrNil(msg), C.size_t(len(msg)), + if C.go_hash_to_scalar(&ret.cgo, ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst))) { return &ret } @@ -3386,20 +3415,20 @@ func HashToScalar(msg []byte, dst []byte) *Scalar { func (fr *Scalar) ToLEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_lendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_lendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToLEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_lendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_lendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromLEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_le_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_le_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -3409,7 +3438,7 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_lendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_lendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -3419,20 +3448,20 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { func (fr *Scalar) ToBEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_bendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToBEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_bendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromBEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_be_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_be_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -3442,7 +3471,7 @@ func (fp *Fp) FromBEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_bendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_bendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -3461,9 +3490,11 @@ func (s *Scalar) Print(name string) { func (p *P1Affine) Print(name string) { fmt.Printf("%s:\n", name) - arr := p.x.ToBEndian() + x := Fp{p.cgo.x} + arr := x.ToBEndian() PrintBytes(arr, " x") - arr = p.y.ToBEndian() + y := Fp{p.cgo.y} + arr = y.ToBEndian() PrintBytes(arr, " y") } @@ -3475,16 +3506,19 @@ func (p *P1) Print(name string) { func (f *Fp2) Print(name string) { fmt.Printf("%s:\n", name) - arr := f.fp[0].ToBEndian() - PrintBytes(arr, " 0") - arr = f.fp[1].ToBEndian() - PrintBytes(arr, " 1") + var arr [BLST_FP_BYTES]byte + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[0]) + PrintBytes(arr[:], " 0") + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[1]) + PrintBytes(arr[:], " 1") } func (p *P2Affine) Print(name string) { fmt.Printf("%s:\n", name) - p.x.Print(" x") - p.y.Print(" y") + x := Fp2{p.cgo.x} + x.Print(" x") + y := Fp2{p.cgo.y} + y.Print(" y") } func (p *P2) Print(name string) { @@ -3510,19 +3544,19 @@ func (e1 *Fp2) Equals(e2 *Fp2) bool { } func (e1 *P1Affine) Equals(e2 *P1Affine) bool { - return bool(C.blst_p1_affine_is_equal(e1, e2)) + return bool(C.blst_p1_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P1) Equals(e2 *P1) bool { - return bool(C.blst_p1_is_equal(e1, e2)) + return bool(C.blst_p1_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2Affine) Equals(e2 *P2Affine) bool { - return bool(C.blst_p2_affine_is_equal(e1, e2)) + return bool(C.blst_p2_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2) Equals(e2 *P2) bool { - return bool(C.blst_p2_is_equal(e1, e2)) + return bool(C.blst_p2_is_equal(&e1.cgo, &e2.cgo)) } // private thunk for testing diff --git a/vendor/github.com/supranational/blst/bindings/go/blst.tgo b/vendor/github.com/supranational/blst/bindings/go/blst.tgo index 947089c34f..bcfd735a09 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst.tgo @@ -158,15 +158,15 @@ const BLST_P1_SERIALIZE_BYTES = BLST_FP_BYTES * 2 const BLST_P2_COMPRESS_BYTES = BLST_FP_BYTES * 2 const BLST_P2_SERIALIZE_BYTES = BLST_FP_BYTES * 4 -type Scalar = C.blst_scalar -type Fp = C.blst_fp -type Fp2 = C.blst_fp2 +type Scalar struct{ cgo C.blst_scalar } +type Fp struct{ cgo C.blst_fp } +type Fp2 struct{ cgo C.blst_fp2 } type Fp6 = C.blst_fp6 -type Fp12 = C.blst_fp12 -type P1 = C.blst_p1 -type P2 = C.blst_p2 -type P1Affine = C.blst_p1_affine -type P2Affine = C.blst_p2_affine +type Fp12 struct{ cgo C.blst_fp12 } +type P1 struct{ cgo C.blst_p1 } +type P2 struct{ cgo C.blst_p2 } +type P1Affine struct{ cgo C.blst_p1_affine } +type P2Affine struct{ cgo C.blst_p2_affine } type Message = []byte type Pairing = []C.blst_pairing type SecretKey = Scalar @@ -195,11 +195,11 @@ func initMaxProcs() int { return maxProcs } -func SetMaxProcs(max int) { - if max <= 0 { - max = 1 +func SetMaxProcs(procs int) { + if procs <= 0 { + procs = 1 } - maxProcs = max + maxProcs = procs } func numThreads(maxThreads int) int { @@ -219,9 +219,9 @@ func numThreads(maxThreads int) int { } var cgo_pairingSizeOf = C.blst_pairing_sizeof() -var cgo_p1Generator = *C.blst_p1_generator() -var cgo_p2Generator = *C.blst_p2_generator() -var cgo_fp12One = *C.blst_fp12_one() +var cgo_p1Generator = P1{*C.blst_p1_generator()} +var cgo_p2Generator = P2{*C.blst_p2_generator()} +var cgo_fp12One = Fp12{*C.blst_fp12_one()} // // Secret key @@ -240,8 +240,8 @@ func KeyGen(ikm []byte, optional ...[]byte) *SecretKey { if len(ikm) < 32 { return nil } - C.blst_keygen(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -257,8 +257,8 @@ func KeyGenV3(ikm []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v3(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen_v3(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -274,9 +274,9 @@ func KeyGenV45(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v4_5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - (*C.byte)(&salt[0]), C.size_t(len(salt)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen_v4_5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + (*C.byte)(&salt[0]), C.size_t(len(salt)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -292,9 +292,9 @@ func KeyGenV5(ikm []byte, salt []byte, optional ...[]byte) *SecretKey { if len(optional) > 0 { info = optional[0] } - C.blst_keygen_v5(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), - (*C.byte)(&salt[0]), C.size_t(len(salt)), - ptrOrNil(info), C.size_t(len(info))) + C.blst_keygen_v5(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm)), + (*C.byte)(&salt[0]), C.size_t(len(salt)), + ptrOrNil(info), C.size_t(len(info))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -306,7 +306,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { return nil } var sk SecretKey - C.blst_derive_master_eip2333(&sk, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) + C.blst_derive_master_eip2333(&sk.cgo, (*C.byte)(&ikm[0]), C.size_t(len(ikm))) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -315,7 +315,7 @@ func DeriveMasterEip2333(ikm []byte) *SecretKey { func (master *SecretKey) DeriveChildEip2333(child_index uint32) *SecretKey { var sk SecretKey - C.blst_derive_child_eip2333(&sk, master, C.uint(child_index)) + C.blst_derive_child_eip2333(&sk.cgo, &master.cgo, C.uint(child_index)) // Postponing secret key zeroing till garbage collection can be too // late to be effective, but every little bit helps... runtime.SetFinalizer(&sk, func(sk *SecretKey) { sk.Zeroize() }) @@ -350,30 +350,38 @@ func PairingFinalVerify(ctx Pairing, optional ...*Fp12) bool { if len(optional) > 0 { gtsig = optional[0] } - return bool(C.blst_pairing_finalverify(&ctx[0], gtsig)) + return bool(C.blst_pairing_finalverify(&ctx[0], gtsig.asPtr())) } func PairingRawAggregate(ctx Pairing, q *P2Affine, p *P1Affine) { - C.blst_pairing_raw_aggregate(&ctx[0], q, p) + C.blst_pairing_raw_aggregate(&ctx[0], &q.cgo, &p.cgo) } func PairingAsFp12(ctx Pairing) *Fp12 { var pt Fp12 - C.go_pairing_as_fp12(&pt, &ctx[0]) + C.go_pairing_as_fp12(&pt.cgo, &ctx[0]) return &pt } +func (pt *Fp12) asPtr() *C.blst_fp12 { + if (pt != nil) { + return &pt.cgo + } + + return nil +} + func Fp12One() Fp12 { return cgo_fp12One } func Fp12FinalVerify(pt1 *Fp12, pt2 *Fp12) bool { - return bool(C.blst_fp12_finalverify(pt1, pt2)) + return bool(C.blst_fp12_finalverify(&pt1.cgo, &pt2.cgo)) } func Fp12MillerLoop(q *P2Affine, p *P1Affine) *Fp12 { var pt Fp12 - C.blst_miller_loop(&pt, q, p) + C.blst_miller_loop(&pt.cgo, &q.cgo, &p.cgo) return &pt } @@ -387,7 +395,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if nThreads == 1 || nElems == 1 { var pt Fp12 - C.go_miller_loop_n(&pt, &qs[0], &ps[0], C.size_t(nElems), false) + C.go_miller_loop_n(&pt.cgo, &qs[0].cgo, &ps[0].cgo, C.size_t(nElems), false) return &pt } @@ -417,7 +425,7 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { if n > stride { n = stride } - C.go_miller_loop_n(&acc, &qs[work], &ps[work], C.size_t(n), + C.go_miller_loop_n(&acc.cgo, &qs[work].cgo, &ps[work].cgo, C.size_t(n), C.bool(!first)) first = false } @@ -431,25 +439,25 @@ func Fp12MillerLoopN(qs []P2Affine, ps []P1Affine) *Fp12 { } var pt Fp12 - C.go_fp12slice_mul(&pt, &ret[0], C.size_t(nThreads)) + C.go_fp12slice_mul(&pt.cgo, &ret[0].cgo, C.size_t(nThreads)) return &pt } func (pt *Fp12) MulAssign(p *Fp12) { - C.blst_fp12_mul(pt, pt, p) + C.blst_fp12_mul(&pt.cgo, &pt.cgo, &p.cgo) } func (pt *Fp12) FinalExp() { - C.blst_final_exp(pt, pt) + C.blst_final_exp(&pt.cgo, &pt.cgo) } func (pt *Fp12) InGroup() bool { - return bool(C.blst_fp12_in_group(pt)) + return bool(C.blst_fp12_in_group(&pt.cgo)) } func (pt *Fp12) ToBendian() []byte { var out [BLST_FP_BYTES*12]byte - C.blst_bendian_from_fp12((*C.byte)(&out[0]), pt) + C.blst_bendian_from_fp12((*C.byte)(&out[0]), &pt.cgo) return out[:] } diff --git a/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo b/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo index 7d329bbc23..2615ae4a78 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst_minpk.tgo @@ -9,13 +9,21 @@ import ( // PublicKey // +func (pt *P1Affine) asPtr() *C.blst_p1_affine { + if (pt != nil) { + return &pt.cgo + } + + return nil +} + func (pk *P1Affine) From(s *Scalar) *P1Affine { - C.blst_sk_to_pk2_in_g1(nil, pk, s) + C.blst_sk_to_pk2_in_g1(nil, &pk.cgo, &s.cgo) return pk } func (pk *P1Affine) KeyValidate() bool { - return bool(C.go_p1_affine_validate(pk, true)) + return bool(C.go_p1_affine_validate(&pk.cgo, true)) } // sigInfcheck, check for infinity, is a way to avoid going @@ -23,7 +31,7 @@ func (pk *P1Affine) KeyValidate() bool { // always cryptographically safe, but application might want // to guard against obviously bogus individual[!] signatures. func (sig *P2Affine) SigValidate(sigInfcheck bool) bool { - return bool(C.go_p2_affine_validate(sig, C.bool(sigInfcheck))) + return bool(C.go_p2_affine_validate(&sig.cgo, C.bool(sigInfcheck))) } // @@ -43,7 +51,7 @@ func (sig *P2Affine) Sign(sk *SecretKey, msg []byte, dst []byte, } else { q = EncodeToG2(msg, dst, augSingle) } - C.blst_sign_pk2_in_g1(nil, sig, q, sk) + C.blst_sign_pk2_in_g1(nil, &sig.cgo, &q.cgo, &sk.cgo) return sig } @@ -247,7 +255,7 @@ func coreAggregateVerifyPkInG1(sigFn sigGetterP2, sigGroupcheck bool, atomic.StoreInt32(&valid, 0) } if atomic.LoadInt32(&valid) > 0 { - C.blst_aggregated_in_g2(>sig, sig) + C.blst_aggregated_in_g2(>sig.cgo, &sig.cgo) } mutex.Unlock() @@ -295,7 +303,7 @@ func CoreVerifyPkInG1(pk *P1Affine, sig *P2Affine, hash_or_encode bool, return C.BLST_SUCCESS } - return int(C.blst_core_verify_pk_in_g1(pk, sig, C.bool(hash_or_encode), + return int(C.blst_core_verify_pk_in_g1(&pk.cgo, &sig.cgo, C.bool(hash_or_encode), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(dst), C.size_t(len(dst)), ptrOrNil(aug), C.size_t(len(aug)))) @@ -489,19 +497,19 @@ func (agg *P2Aggregate) AddAggregate(other *P2Aggregate) { } else if agg.v == nil { agg.v = other.v } else { - C.blst_p2_add_or_double(agg.v, agg.v, other.v) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &other.v.cgo) } } func (agg *P2Aggregate) Add(elmt *P2Affine, groupcheck bool) bool { - if groupcheck && !bool(C.blst_p2_affine_in_g2(elmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&elmt.cgo)) { return false } if agg.v == nil { agg.v = new(P2) - C.blst_p2_from_affine(agg.v, elmt) + C.blst_p2_from_affine(&agg.v.cgo, &elmt.cgo) } else { - C.blst_p2_add_or_double_affine(agg.v, agg.v, elmt) + C.blst_p2_add_or_double_affine(&agg.v.cgo, &agg.v.cgo, &elmt.cgo) } return true } @@ -551,15 +559,15 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, atomic.StoreInt32(&valid, 0) break } - if groupcheck && !bool(C.blst_p2_affine_in_g2(curElmt)) { + if groupcheck && !bool(C.blst_p2_affine_in_g2(&curElmt.cgo)) { atomic.StoreInt32(&valid, 0) break } if first { - C.blst_p2_from_affine(&agg, curElmt) + C.blst_p2_from_affine(&agg.cgo, &curElmt.cgo) first = false } else { - C.blst_p2_add_or_double_affine(&agg, &agg, curElmt) + C.blst_p2_add_or_double_affine(&agg.cgo, &agg.cgo, &curElmt.cgo) } // application might have some async work to do runtime.Gosched() @@ -590,7 +598,7 @@ func (agg *P2Aggregate) coreAggregate(getter aggGetterP2, groupcheck bool, agg.v = msg.agg first = false } else { - C.blst_p2_add_or_double(agg.v, agg.v, msg.agg) + C.blst_p2_add_or_double(&agg.v.cgo, &agg.v.cgo, &msg.agg.cgo) } } } diff --git a/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo b/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo index a6e5d90d9b..b629d1ee5a 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst_misc.tgo @@ -1,12 +1,14 @@ import "fmt" +// // Parse out optional arguments for sign and verify. -// aug []byte - augmentation bytes (default: nil) -func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { - var aug [][]byte // For aggregate verify - var augSingle []byte // For signing - useHash := true // hash (true), encode (false) +// augSingle []byte - augmentation bytes for aggregate verify (default: nil) +// aug [][]byte - augmentation bytes for signing (default: nil) +// +func parseOpts(optional ...interface{}) (augSingle []byte, aug [][]byte, + useHash bool, ok bool) { + useHash = true // hash (true), encode (false) for _, arg := range optional { switch v := arg.(type) { @@ -29,35 +31,35 @@ func parseOpts(optional ...interface{}) ([]byte, [][]byte, bool, bool) { // formulate interfaces that would process multiple scalars per cgo call. // func (a *Scalar) MulAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_mul_n_check(a, a, b)) + return a, bool(C.blst_sk_mul_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Mul(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_mul_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_mul_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) AddAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_add_n_check(a, a, b)) + return a, bool(C.blst_sk_add_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Add(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_add_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_add_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) SubAssign(b *Scalar) (*Scalar, bool) { - return a, bool(C.blst_sk_sub_n_check(a, a, b)) + return a, bool(C.blst_sk_sub_n_check(&a.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Sub(b *Scalar) (*Scalar, bool) { var ret Scalar - return &ret, bool(C.blst_sk_sub_n_check(&ret, a, b)) + return &ret, bool(C.blst_sk_sub_n_check(&ret.cgo, &a.cgo, &b.cgo)) } func (a *Scalar) Inverse() *Scalar { var ret Scalar - C.blst_sk_inverse(&ret, a) + C.blst_sk_inverse(&ret.cgo, &a.cgo) return &ret } @@ -68,20 +70,20 @@ func (a *Scalar) Inverse() *Scalar { // Scalar serdes func (s *Scalar) Serialize() []byte { var out [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&out[0]), s) + C.blst_bendian_from_scalar((*C.byte)(&out[0]), &s.cgo) return out[:] } func (s *Scalar) Deserialize(in []byte) *Scalar { if len(in) != BLST_SCALAR_BYTES || - !C.go_scalar_from_bendian(s, (*C.byte)(&in[0])) { + !C.go_scalar_from_bendian(&s.cgo, (*C.byte)(&in[0])) { return nil } return s } func (s *Scalar) Valid() bool { - return bool(C.blst_sk_check(s)) + return bool(C.blst_sk_check(&s.cgo)) } func (s *Scalar) HashTo(msg []byte, dst []byte) bool { @@ -96,8 +98,8 @@ func (s *Scalar) HashTo(msg []byte, dst []byte) bool { func HashToScalar(msg []byte, dst []byte) *Scalar { var ret Scalar - if C.go_hash_to_scalar(&ret, ptrOrNil(msg), C.size_t(len(msg)), - ptrOrNil(dst), C.size_t(len(dst))) { + if C.go_hash_to_scalar(&ret.cgo, ptrOrNil(msg), C.size_t(len(msg)), + ptrOrNil(dst), C.size_t(len(dst))) { return &ret } @@ -110,20 +112,20 @@ func HashToScalar(msg []byte, dst []byte) *Scalar { func (fr *Scalar) ToLEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_lendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_lendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToLEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_lendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_lendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromLEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_le_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_le_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -133,7 +135,7 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_lendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_lendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -143,20 +145,20 @@ func (fp *Fp) FromLEndian(arr []byte) *Fp { func (fr *Scalar) ToBEndian() []byte { var arr [BLST_SCALAR_BYTES]byte - C.blst_bendian_from_scalar((*C.byte)(&arr[0]), fr) + C.blst_bendian_from_scalar((*C.byte)(&arr[0]), &fr.cgo) return arr[:] } func (fp *Fp) ToBEndian() []byte { var arr [BLST_FP_BYTES]byte - C.blst_bendian_from_fp((*C.byte)(&arr[0]), fp) + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &fp.cgo) return arr[:] } func (fr *Scalar) FromBEndian(arr []byte) *Scalar { nbytes := len(arr) if nbytes < BLST_SCALAR_BYTES || - !C.blst_scalar_from_be_bytes(fr, (*C.byte)(&arr[0]), C.size_t(nbytes)) { + !C.blst_scalar_from_be_bytes(&fr.cgo, (*C.byte)(&arr[0]), C.size_t(nbytes)) { return nil } return fr @@ -166,7 +168,7 @@ func (fp *Fp) FromBEndian(arr []byte) *Fp { if len(arr) != BLST_FP_BYTES { return nil } - C.blst_fp_from_bendian(fp, (*C.byte)(&arr[0])) + C.blst_fp_from_bendian(&fp.cgo, (*C.byte)(&arr[0])) return fp } @@ -185,9 +187,11 @@ func (s *Scalar) Print(name string) { func (p *P1Affine) Print(name string) { fmt.Printf("%s:\n", name) - arr := p.x.ToBEndian() + x := Fp{p.cgo.x} + arr := x.ToBEndian() PrintBytes(arr, " x") - arr = p.y.ToBEndian() + y := Fp{p.cgo.y} + arr = y.ToBEndian() PrintBytes(arr, " y") } @@ -199,16 +203,19 @@ func (p *P1) Print(name string) { func (f *Fp2) Print(name string) { fmt.Printf("%s:\n", name) - arr := f.fp[0].ToBEndian() - PrintBytes(arr, " 0") - arr = f.fp[1].ToBEndian() - PrintBytes(arr, " 1") + var arr [BLST_FP_BYTES]byte + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[0]) + PrintBytes(arr[:], " 0") + C.blst_bendian_from_fp((*C.byte)(&arr[0]), &f.cgo.fp[1]) + PrintBytes(arr[:], " 1") } func (p *P2Affine) Print(name string) { fmt.Printf("%s:\n", name) - p.x.Print(" x") - p.y.Print(" y") + x := Fp2{p.cgo.x} + x.Print(" x") + y := Fp2{p.cgo.y} + y.Print(" y") } func (p *P2) Print(name string) { @@ -234,19 +241,19 @@ func (e1 *Fp2) Equals(e2 *Fp2) bool { } func (e1 *P1Affine) Equals(e2 *P1Affine) bool { - return bool(C.blst_p1_affine_is_equal(e1, e2)) + return bool(C.blst_p1_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P1) Equals(e2 *P1) bool { - return bool(C.blst_p1_is_equal(e1, e2)) + return bool(C.blst_p1_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2Affine) Equals(e2 *P2Affine) bool { - return bool(C.blst_p2_affine_is_equal(e1, e2)) + return bool(C.blst_p2_affine_is_equal(&e1.cgo, &e2.cgo)) } func (e1 *P2) Equals(e2 *P2) bool { - return bool(C.blst_p2_is_equal(e1, e2)) + return bool(C.blst_p2_is_equal(&e1.cgo, &e2.cgo)) } // private thunk for testing diff --git a/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo b/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo index ebe2ac3c28..6873c500c9 100644 --- a/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo +++ b/vendor/github.com/supranational/blst/bindings/go/blst_px.tgo @@ -7,8 +7,8 @@ func PairingAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -25,9 +25,9 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, } r := C.blst_pairing_chk_n_mul_n_aggr_pk_in_g1(&ctx[0], - PK, C.bool(pkValidate), - sig, C.bool(sigGroupcheck), - &rand.b[0], C.size_t(randBits), + PK.asPtr(), C.bool(pkValidate), + sig.asPtr(), C.bool(sigGroupcheck), + &rand.cgo.b[0], C.size_t(randBits), ptrOrNil(msg), C.size_t(len(msg)), ptrOrNil(aug), C.size_t(len(aug))) @@ -41,7 +41,7 @@ func PairingMulNAggregatePkInG1(ctx Pairing, PK *P1Affine, pkValidate bool, // P1 Serdes func (p1 *P1Affine) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_affine_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_affine_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -49,14 +49,14 @@ func (p1 *P1Affine) Deserialize(in []byte) *P1Affine { if len(in) != BLST_P1_SERIALIZE_BYTES { return nil } - if C.blst_p1_deserialize(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_deserialize(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_affine_compress((*C.byte)(&out[0]), p1) + C.blst_p1_affine_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -64,14 +64,14 @@ func (p1 *P1Affine) Uncompress(in []byte) *P1Affine { if len(in) != BLST_P1_COMPRESS_BYTES { return nil } - if C.blst_p1_uncompress(p1, (*C.byte)(&in[0])) != C.BLST_SUCCESS { + if C.blst_p1_uncompress(&p1.cgo, (*C.byte)(&in[0])) != C.BLST_SUCCESS { return nil } return p1 } func (p1 *P1Affine) InG1() bool { - return bool(C.blst_p1_affine_in_g1(p1)) + return bool(C.blst_p1_affine_in_g1(&p1.cgo)) } func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { @@ -128,12 +128,12 @@ func (_ *P1Affine) BatchUncompress(in [][]byte) []*P1Affine { func (p1 *P1) Serialize() []byte { var out [BLST_P1_SERIALIZE_BYTES]byte - C.blst_p1_serialize((*C.byte)(&out[0]), p1) + C.blst_p1_serialize((*C.byte)(&out[0]), &p1.cgo) return out[:] } func (p1 *P1) Compress() []byte { var out [BLST_P1_COMPRESS_BYTES]byte - C.blst_p1_compress((*C.byte)(&out[0]), p1) + C.blst_p1_compress((*C.byte)(&out[0]), &p1.cgo) return out[:] } @@ -145,7 +145,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { scalar = (*C.byte)(&val[0]) nbits = len(val)*8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -153,7 +153,7 @@ func (p1 *P1) MultAssign(scalarIf interface{}, optional ...int) *P1 { if len(optional) > 0 { nbits = optional[0] } - C.blst_p1_mult(p1, p1, scalar, C.size_t(nbits)) + C.blst_p1_mult(&p1.cgo, &p1.cgo, scalar, C.size_t(nbits)) return p1 } @@ -165,9 +165,9 @@ func (p1 *P1) Mult(scalarIf interface{}, optional ...int) *P1 { func (p1 *P1) AddAssign(pointIf interface{}) *P1 { switch val := pointIf.(type) { case *P1: - C.blst_p1_add_or_double(p1, p1, val) + C.blst_p1_add_or_double(&p1.cgo, &p1.cgo, &val.cgo) case *P1Affine: - C.blst_p1_add_or_double_affine(p1, p1, val) + C.blst_p1_add_or_double_affine(&p1.cgo, &p1.cgo, &val.cgo) default: panic(fmt.Sprintf("unsupported type %T", val)) } @@ -180,19 +180,19 @@ func (p1 *P1) Add(pointIf interface{}) *P1 { } func (p1 *P1) SubAssign(pointIf interface{}) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) } - C.go_p1_sub_assign(p1, x, affine) + C.go_p1_sub_assign(&p1.cgo, x, affine) return p1 } @@ -209,15 +209,15 @@ func P1Generator() *P1 { // group generator point" func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, optional ...int) *P1 { - var x *Fp + var x *C.blst_fp var affine C.bool if pointIf != nil { switch val := pointIf.(type) { case *P1: - x = &val.x + x = &val.cgo.x affine = false case *P1Affine: - x = &val.x + x = &val.cgo.x affine = true default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -230,7 +230,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, scalar = (*C.byte)(&val[0]) nbits = len(val)*8 case *Scalar: - scalar = &val.b[0] + scalar = &val.cgo.b[0] nbits = 255 default: panic(fmt.Sprintf("unsupported type %T", val)) @@ -238,7 +238,7 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, if len(optional) > 0 { nbits = optional[0] } - C.go_p1_mult_n_acc(acc, x, affine, scalar, C.size_t(nbits)) + C.go_p1_mult_n_acc(&acc.cgo, x, affine, scalar, C.size_t(nbits)) return acc } @@ -248,12 +248,12 @@ func (acc *P1) MultNAccumulate(pointIf interface{}, scalarIf interface{}, func (p *P1) ToAffine() *P1Affine { var pa P1Affine - C.blst_p1_to_affine(&pa, p) + C.blst_p1_to_affine(&pa.cgo, &p.cgo) return &pa } func (p *P1) FromAffine(pa *P1Affine) { - C.blst_p1_from_affine(p, pa) + C.blst_p1_from_affine(&p.cgo, &pa.cgo) } // @@ -268,9 +268,9 @@ func HashToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_hash_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), - ptrOrNil(dst), C.size_t(len(dst)), - ptrOrNil(aug), C.size_t(len(aug))) + C.blst_hash_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), + ptrOrNil(dst), C.size_t(len(dst)), + ptrOrNil(aug), C.size_t(len(aug))) return &q } @@ -283,9 +283,9 @@ func EncodeToG1(msg []byte, dst []byte, aug = optional[0] } - C.blst_encode_to_g1(&q, ptrOrNil(msg), C.size_t(len(msg)), - ptrOrNil(dst), C.size_t(len(dst)), - ptrOrNil(aug), C.size_t(len(aug))) + C.blst_encode_to_g1(&q.cgo, ptrOrNil(msg), C.size_t(len(msg)), + ptrOrNil(dst), C.size_t(len(dst)), + ptrOrNil(aug), C.size_t(len(aug))) return &q } @@ -302,7 +302,8 @@ func P1sToAffine(points []*P1, optional ...int) P1Affines { } ret := make([]P1Affine, npoints) _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.blst_p1s_to_affine(&ret[0].cgo, (**C.blst_p1)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return ret } @@ -320,7 +321,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } if maxProcs < 2 || npoints < 768 { - C.go_p1slice_to_affine(&ret[0], &points[0], C.size_t(npoints)) + C.go_p1slice_to_affine(&ret[0].cgo, &points[0].cgo, C.size_t(npoints)) return ret } @@ -338,7 +339,7 @@ func (points P1s) ToAffine(optional ...P1Affines) P1Affines { } rem -= 1 go func(out *P1Affine, inp *P1, delta int) { - C.go_p1slice_to_affine(out, inp, C.size_t(delta)) + C.go_p1slice_to_affine(&out.cgo, &inp.cgo, C.size_t(delta)) wg.Done() }(&ret[x], &points[x], delta) } @@ -360,7 +361,8 @@ func P1AffinesAdd(points []*P1Affine, optional ...int) *P1 { } var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_add(&ret, &points[0], C.size_t(npoints)) + C.blst_p1s_add(&ret.cgo, (**C.blst_p1_affine)(unsafe.Pointer(&points[0])), + C.size_t(npoints)) return &ret } @@ -368,7 +370,7 @@ func (points P1Affines) Add() *P1 { npoints := len(points) if maxProcs < 2 || npoints < 768 { var ret P1 - C.go_p1slice_add(&ret, &points[0], C.size_t(npoints)) + C.go_p1slice_add(&ret.cgo, &points[0].cgo, C.size_t(npoints)) return &ret } @@ -386,7 +388,7 @@ func (points P1Affines) Add() *P1 { rem -= 1 go func(points *P1Affine, delta int) { var ret P1 - C.go_p1slice_add(&ret, points, C.size_t(delta)) + C.go_p1slice_add(&ret.cgo, &points.cgo, C.size_t(delta)) msgs <- ret }(&points[x], delta) } @@ -394,7 +396,7 @@ func (points P1Affines) Add() *P1 { ret := <- msgs for i := 1; i < nslices; i++ { msg := <- msgs - C.blst_p1_add_or_double(&ret, &ret, &msg) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &msg.cgo) } return &ret } @@ -442,7 +444,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { if nbits <= 248 { scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } } case []*Scalar: @@ -451,7 +453,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { } scalars = make([]*C.byte, npoints) for i := range scalars { - scalars[i] = &val[i].b[0] + scalars[i] = &val[i].cgo.b[0] } default: panic(fmt.Sprintf("unsupported type %T",val)) @@ -463,16 +465,16 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { sz := int(C.blst_p1s_mult_pippenger_scratch_sizeof(C.size_t(npoints)))/8 scratch := make([]uint64, sz) - pointsBySlice := [2]*P1Affine{nil, nil} - var p_points **P1Affine + pointsBySlice := [2]*C.blst_p1_affine{nil, nil} + var p_points **C.blst_p1_affine switch val := pointsIf.(type) { case []*P1Affine: - p_points = &val[0] + p_points = (**C.blst_p1_affine)(unsafe.Pointer(&val[0])) case []P1Affine: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] case P1Affines: - pointsBySlice[0] = &val[0] + pointsBySlice[0] = &val[0].cgo p_points = &pointsBySlice[0] } @@ -486,7 +488,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[0] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[0].b[0] + scalarsBySlice[0] = &val[0].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[0] @@ -497,9 +499,9 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { var ret P1 _cgoCheckPointer := func(...interface{}) {} - C.blst_p1s_mult_pippenger(&ret, p_points, C.size_t(npoints), - p_scalars, C.size_t(nbits), - (*C.limb_t)(&scratch[0])) + C.blst_p1s_mult_pippenger(&ret.cgo, p_points, C.size_t(npoints), + p_scalars, C.size_t(nbits), + (*C.limb_t)(&scratch[0])) for i := range(scalars) { scalars[i] = nil @@ -544,7 +546,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] case []Scalar: if nbits > 248 { - scalar = &val[workItem].b[0] + scalar = &val[workItem].cgo.b[0] } else { scalar = scalars[workItem] } @@ -552,8 +554,8 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { scalar = scalars[workItem] } - C.go_p1_mult_n_acc(&acc, &point.x, true, - scalar, C.size_t(nbits)) + C.go_p1_mult_n_acc(&acc.cgo, &point.cgo.x, true, + scalar, C.size_t(nbits)) } msgs <- acc @@ -563,7 +565,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { ret := <-msgs for tid := 1; tid < numThreads; tid++ { point := <- msgs - C.blst_p1_add_or_double(&ret, &ret, &point); + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &point.cgo); } for i := range(scalars) { @@ -615,7 +617,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { for tid := 0; tid < numThreads; tid++ { go func() { scratch := make([]uint64, sz << uint(window-1)) - pointsBySlice := [2]*P1Affine{nil, nil} + pointsBySlice := [2]*C.blst_p1_affine{nil, nil} scalarsBySlice := [2]*C.byte{nil, nil} _cgoCheckPointer := func(...interface{}) {} @@ -628,15 +630,15 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { x := grid[workItem].x y := grid[workItem].y - var p_points **P1Affine + var p_points **C.blst_p1_affine switch val := pointsIf.(type) { case []*P1Affine: - p_points = &val[x] + p_points = (**C.blst_p1_affine)(unsafe.Pointer(&val[x])) case []P1Affine: - pointsBySlice[0] = &val[x] + pointsBySlice[0] = &val[x].cgo p_points = &pointsBySlice[0] case P1Affines: - pointsBySlice[0] = &val[x] + pointsBySlice[0] = &val[x].cgo p_points = &pointsBySlice[0] } @@ -649,7 +651,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[x] case []Scalar: if nbits > 248 { - scalarsBySlice[0] = &val[x].b[0] + scalarsBySlice[0] = &val[x].cgo.b[0] p_scalars = &scalarsBySlice[0] } else { p_scalars = &scalars[x] @@ -658,7 +660,7 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { p_scalars = &scalars[x] } - C.blst_p1s_tile_pippenger(&grid[workItem].point, + C.blst_p1s_tile_pippenger(&grid[workItem].point.cgo, p_points, C.size_t(grid[workItem].dx), p_scalars, C.size_t(nbits), (*C.limb_t)(&scratch[0]), @@ -684,14 +686,14 @@ func P1AffinesMult(pointsIf interface{}, scalarsIf interface{}, nbits int) *P1 { rows[y/window] = true // mark the "row" for grid[row].y == y { // if it's current "row", process it for row < total && grid[row].y == y { - C.blst_p1_add_or_double(&ret, &ret, &grid[row].point) + C.blst_p1_add_or_double(&ret.cgo, &ret.cgo, &grid[row].point.cgo) row++ } if y == 0 { break // one can as well 'return &ret' here } for j := 0; j < window; j++ { - C.blst_p1_double(&ret, &ret) + C.blst_p1_double(&ret.cgo, &ret.cgo) } y -= window if !rows[y/window] { // see if next "row" was marked already @@ -749,7 +751,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { return false } } @@ -784,7 +786,7 @@ func P1AffinesValidate(pointsIf interface{}) bool { panic(fmt.Sprintf("unsupported type %T", val)) } - if !C.go_p1_affine_validate(point, true) { + if !C.go_p1_affine_validate(&point.cgo, true) { atomic.StoreInt32(&valid, 0) break } diff --git a/vendor/github.com/supranational/blst/bindings/go/generate.py b/vendor/github.com/supranational/blst/bindings/go/generate.py index d40fad2109..0285119148 100644 --- a/vendor/github.com/supranational/blst/bindings/go/generate.py +++ b/vendor/github.com/supranational/blst/bindings/go/generate.py @@ -87,6 +87,7 @@ def remap(fout, fin, mapping, dont_touch, removeImports): mapping = [('P1', 'P2'), ('p1', 'p2'), ('Fp', 'Fp2'), + ('C.blst_fp', 'C.blst_fp2'), ('G1', 'G2'), ('g1', 'g2') ] diff --git a/vendor/modernc.org/libc/libc_windows.go b/vendor/modernc.org/libc/libc_windows.go index 19776f7120..79bd88fc1f 100644 --- a/vendor/modernc.org/libc/libc_windows.go +++ b/vendor/modernc.org/libc/libc_windows.go @@ -226,25 +226,25 @@ var ( userenvapi = windows.NewLazySystemDLL("userenv.dll") procGetProfilesDirectoryW = userenvapi.NewProc("GetProfilesDirectoryW") - modcrt = windows.NewLazySystemDLL("msvcrt.dll") - procAccess = modcrt.NewProc("_access") - procChmod = modcrt.NewProc("_chmod") - procCtime64 = modcrt.NewProc("ctime64") - procGmtime = modcrt.NewProc("gmtime") - procGmtime32 = modcrt.NewProc("_gmtime32") - procGmtime64 = modcrt.NewProc("_gmtime64") - procStat64i32 = modcrt.NewProc("_stat64i32") - procStati64 = modcrt.NewProc("_stati64") - procStrftime = modcrt.NewProc("strftime") - procStrnicmp = modcrt.NewProc("_strnicmp") - procStrtod = modcrt.NewProc("strtod") - procTime64 = modcrt.NewProc("time64") - procWcsncpy = modcrt.NewProc("wcsncpy") - procWcsrchr = modcrt.NewProc("wcsrchr") + modcrt = windows.NewLazySystemDLL("msvcrt.dll") + procAccess = modcrt.NewProc("_access") + procChmod = modcrt.NewProc("_chmod") + procCtime64 = modcrt.NewProc("ctime64") + procGmtime = modcrt.NewProc("gmtime") + procGmtime32 = modcrt.NewProc("_gmtime32") + procGmtime64 = modcrt.NewProc("_gmtime64") + procStati64 = modcrt.NewProc("_stati64") + procStrftime = modcrt.NewProc("strftime") + procStrnicmp = modcrt.NewProc("_strnicmp") + procStrtod = modcrt.NewProc("strtod") + procTime64 = modcrt.NewProc("time64") + procWcsncpy = modcrt.NewProc("wcsncpy") + procWcsrchr = modcrt.NewProc("wcsrchr") moducrt = windows.NewLazySystemDLL("ucrtbase.dll") procFindfirst32 = moducrt.NewProc("_findfirst32") procFindnext32 = moducrt.NewProc("_findnext32") + procStat64i32 = moducrt.NewProc("_stat64i32") ) var ( diff --git a/vendor/modules.txt b/vendor/modules.txt index 0f3bcfb0a7..4ed893e639 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -344,7 +344,7 @@ github.com/cespare/xxhash # github.com/cespare/xxhash/v2 v2.3.0 ## explicit; go 1.11 github.com/cespare/xxhash/v2 -# github.com/charmbracelet/bubbletea v1.3.2 +# github.com/charmbracelet/bubbletea v1.3.3 ## explicit; go 1.18 github.com/charmbracelet/bubbletea # github.com/charmbracelet/lipgloss v1.0.0 @@ -508,7 +508,7 @@ github.com/dgraph-io/badger/v4/y github.com/dgraph-io/ristretto/v2 github.com/dgraph-io/ristretto/v2/z github.com/dgraph-io/ristretto/v2/z/simd -# github.com/dlclark/regexp2 v1.11.4 +# github.com/dlclark/regexp2 v1.11.5 ## explicit; go 1.13 github.com/dlclark/regexp2 github.com/dlclark/regexp2/syntax @@ -955,7 +955,7 @@ github.com/pion/turn/v4/internal/client github.com/pion/turn/v4/internal/ipnet github.com/pion/turn/v4/internal/proto github.com/pion/turn/v4/internal/server -# github.com/pion/webrtc/v4 v4.0.8 +# github.com/pion/webrtc/v4 v4.0.9 ## explicit; go 1.20 github.com/pion/webrtc/v4 github.com/pion/webrtc/v4/internal/fmtp @@ -1032,7 +1032,7 @@ github.com/steakknife/hamming github.com/stretchr/testify/assert github.com/stretchr/testify/assert/yaml github.com/stretchr/testify/require -# github.com/supranational/blst v0.3.13 +# github.com/supranational/blst v0.3.14 ## explicit; go 1.11 github.com/supranational/blst/bindings/go # github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d @@ -1327,7 +1327,7 @@ gopkg.in/yaml.v3 lukechampine.com/blake3 lukechampine.com/blake3/bao lukechampine.com/blake3/guts -# modernc.org/libc v1.61.12 +# modernc.org/libc v1.61.13 ## explicit; go 1.21 modernc.org/libc modernc.org/libc/errno