Disable h264 for android firefox (#2190)

* Disable H.264 for android firefox

* Fix syntax error for rule

* lower case

* Remove disabled codec from AddTrackRequest

* Consistent handling of enabled codecs

Mainly cleaning up where we are doing codec filtering.

There's also behavior change of how we handle codec compatibility. If a client doesn't support the client's desired codec, we'll pick a backup automatically
instead of rejecting the client's request.

Requires an update on multi-codec simulcast handling.

* fix alternative codec selection

---------

Co-authored-by: David Zhao <dz@livekit.io>
This commit is contained in:
cnderrauber
2023-10-27 14:47:36 +08:00
committed by GitHub
co-authored by David Zhao
parent 1f0ba21854
commit 3633dfe39e
9 changed files with 177 additions and 65 deletions
+2 -1
View File
@@ -33,7 +33,8 @@ var StaticConfigurations = []ConfigurationItem{
// Merge: false,
// },
{
Match: &ScriptMatch{Expr: `c.device_model == "Xiaomi 2201117TI" && c.os == "android"`},
Match: &ScriptMatch{Expr: `(c.device_model == "xiaomi 2201117ti" && c.os == "android") ||
((c.browser == "firefox" || c.browser == "firefox mobile") && (c.os == "linux" || c.os == "android"))`},
Configuration: &livekit.ClientConfiguration{
DisabledCodecs: &livekit.DisabledCodecs{
Publish: []*livekit.Codec{{Mime: "video/h264"}},
+3 -2
View File
@@ -55,7 +55,7 @@ func TestScriptMatchConfiguration(t *testing.T) {
Merge: true,
},
{
Match: &ScriptMatch{Expr: `c.sdk == "ANDROID"`},
Match: &ScriptMatch{Expr: `c.sdk == "android"`},
Configuration: &livekit.ClientConfiguration{
Video: &livekit.VideoConfiguration{
HardwareEncoder: livekit.ClientConfigSetting_DISABLED,
@@ -98,7 +98,8 @@ func TestScriptMatch(t *testing.T) {
{name: "simple match", expr: `c.protocol > 5`, result: true},
{name: "invalid expr", expr: `cc.protocol > 5`, err: true},
{name: "unexist field", expr: `c.protocols > 5`, err: true},
{name: "combined condition", expr: `c.protocol > 5 && (c.sdk=="ANDROID" || c.sdk=="IOS")`, result: true},
{name: "combined condition", expr: `c.protocol > 5 && (c.sdk=="android" || c.sdk=="ios")`, result: true},
{name: "combined condition2", expr: `(c.device_model == "xiaomi 2201117ti" && c.os == "android) || ((c.browser == "firefox" || c.browser == "firefox mobile") && (c.os == "linux" || c.os == "android"))`, result: false},
}
for _, c := range cases {
+5 -4
View File
@@ -17,6 +17,7 @@ package clientconfiguration
import (
"context"
"errors"
"strings"
"github.com/d5/tengo/v2"
@@ -69,19 +70,19 @@ func (c *clientObject) IndexGet(index tengo.Object) (res tengo.Object, err error
switch field.Value {
case "sdk":
return &tengo.String{Value: c.info.Sdk.String()}, nil
return &tengo.String{Value: strings.ToLower(c.info.Sdk.String())}, nil
case "version":
return &tengo.String{Value: c.info.Version}, nil
case "protocol":
return &tengo.Int{Value: int64(c.info.Protocol)}, nil
case "os":
return &tengo.String{Value: c.info.Os}, nil
return &tengo.String{Value: strings.ToLower(c.info.Os)}, nil
case "os_version":
return &tengo.String{Value: c.info.OsVersion}, nil
case "device_model":
return &tengo.String{Value: c.info.DeviceModel}, nil
return &tengo.String{Value: strings.ToLower(c.info.DeviceModel)}, nil
case "browser":
return &tengo.String{Value: c.info.Browser}, nil
return &tengo.String{Value: strings.ToLower(c.info.Browser)}, nil
case "browser_version":
return &tengo.String{Value: c.info.BrowserVersion}, nil
case "address":
@@ -15,8 +15,6 @@
package clientconfiguration
import (
"fmt"
"google.golang.org/protobuf/proto"
"github.com/livekit/protocol/livekit"
@@ -42,7 +40,7 @@ func (s *StaticClientConfigurationManager) GetConfiguration(clientInfo *livekit.
for _, c := range s.confs {
matched, err := c.Match.Match(clientInfo)
if err != nil {
logger.Errorw(fmt.Sprintf("matchrule failed, clientInfo: %s", clientInfo.String()), err)
logger.Errorw("matchrule failed", err, "clientInfo", clientInfo.String())
continue
}
if !matched {
+6 -2
View File
@@ -26,7 +26,7 @@ type ClientInfo struct {
}
func (c ClientInfo) isFirefox() bool {
return c.ClientInfo != nil && strings.EqualFold(c.ClientInfo.Browser, "firefox")
return c.ClientInfo != nil && (strings.EqualFold(c.ClientInfo.Browser, "firefox") || strings.EqualFold(c.ClientInfo.Browser, "firefox mobile"))
}
func (c ClientInfo) isSafari() bool {
@@ -41,6 +41,10 @@ func (c ClientInfo) isLinux() bool {
return c.ClientInfo != nil && strings.EqualFold(c.ClientInfo.Os, "linux")
}
func (c ClientInfo) isAndroid() bool {
return c.ClientInfo != nil && strings.EqualFold(c.ClientInfo.Os, "android")
}
func (c ClientInfo) SupportsAudioRED() bool {
return !c.isFirefox() && !c.isSafari()
}
@@ -85,7 +89,7 @@ func (c ClientInfo) SupportsChangeRTPSenderEncodingActive() bool {
}
func (c ClientInfo) ComplyWithCodecOrderInSDPAnswer() bool {
return !(c.isLinux() && c.isFirefox())
return !((c.isLinux() || c.isAndroid()) && c.isFirefox())
}
// compareVersion compares a semver against the current client SDK version
+20
View File
@@ -18,6 +18,7 @@ import (
"strings"
"github.com/pion/webrtc/v3"
"golang.org/x/exp/slices"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/protocol/livekit"
@@ -132,3 +133,22 @@ func IsCodecEnabled(codecs []*livekit.Codec, cap webrtc.RTPCodecCapability) bool
}
return false
}
func selectAlternativeCodec(enabledCodecs []*livekit.Codec) string {
// sort these by compatibility, since we are looking for backups
if slices.ContainsFunc(enabledCodecs, func(c *livekit.Codec) bool {
return strings.EqualFold(c.Mime, webrtc.MimeTypeVP8)
}) {
return webrtc.MimeTypeVP8
}
if slices.ContainsFunc(enabledCodecs, func(c *livekit.Codec) bool {
return strings.EqualFold(c.Mime, webrtc.MimeTypeH264)
}) {
return webrtc.MimeTypeH264
}
if len(enabledCodecs) > 0 {
return enabledCodecs[0].Mime
}
// uh oh. this should not happen
return ""
}
+71 -19
View File
@@ -88,18 +88,19 @@ func (p participantUpdateInfo) String() string {
// ---------------------------------------------------------------
type ParticipantParams struct {
Identity livekit.ParticipantIdentity
Name livekit.ParticipantName
SID livekit.ParticipantID
Config *WebRTCConfig
Sink routing.MessageSink
AudioConfig config.AudioConfig
VideoConfig config.VideoConfig
ProtocolVersion types.ProtocolVersion
Telemetry telemetry.TelemetryService
Trailer []byte
PLIThrottleConfig config.PLIThrottleConfig
CongestionControlConfig config.CongestionControlConfig
Identity livekit.ParticipantIdentity
Name livekit.ParticipantName
SID livekit.ParticipantID
Config *WebRTCConfig
Sink routing.MessageSink
AudioConfig config.AudioConfig
VideoConfig config.VideoConfig
ProtocolVersion types.ProtocolVersion
Telemetry telemetry.TelemetryService
Trailer []byte
PLIThrottleConfig config.PLIThrottleConfig
CongestionControlConfig config.CongestionControlConfig
// codecs that are enabled for this room
EnabledCodecs []*livekit.Codec
Logger logger.Logger
SimTracks map[uint32]SimulcastTrackInfo
@@ -157,6 +158,10 @@ type ParticipantImpl struct {
// migrated in muted tracks are not fired need close at participant close
mutedTrackNotFired []*MediaTrack
// supported codecs
enabledPublishCodecs []*livekit.Codec
enabledSubscribeCodecs []*livekit.Codec
*TransportManager
*UpTrackManager
*SubscriptionManager
@@ -244,6 +249,7 @@ func NewParticipant(params ParticipantParams) (*ParticipantImpl, error) {
p.state.Store(livekit.ParticipantInfo_JOINING)
p.grants = params.Grants
p.SetResponseSink(params.Sink)
p.setupEnabledCodecs(params.EnabledCodecs, params.ClientConf.GetDisabledCodecs())
p.supervisor.OnPublicationError(p.onPublicationError)
@@ -1109,9 +1115,9 @@ func (p *ParticipantImpl) setupTransportManager() error {
ProtocolVersion: p.params.ProtocolVersion,
Telemetry: p.params.Telemetry,
CongestionControlConfig: p.params.CongestionControlConfig,
EnabledCodecs: p.params.EnabledCodecs,
EnabledPublishCodecs: p.enabledPublishCodecs,
EnabledSubscribeCodecs: p.enabledSubscribeCodecs,
SimTracks: p.params.SimTracks,
ClientConf: p.params.ClientConf,
ClientInfo: p.params.ClientInfo,
Migration: p.params.Migration,
AllowTCPFallback: p.params.AllowTCPFallback,
@@ -1614,19 +1620,33 @@ func (p *ParticipantImpl) addPendingTrackLocked(req *livekit.AddTrackRequest) *l
ti.Stream = StreamFromTrackSource(ti.Source)
}
p.setStableTrackID(req.Cid, ti)
seenCodecs := make(map[string]struct{})
for _, codec := range req.SimulcastCodecs {
mime := codec.Codec
if req.Type == livekit.TrackType_VIDEO && !strings.HasPrefix(mime, "video/") {
mime = "video/" + mime
if !IsCodecEnabled(p.enabledPublishCodecs, webrtc.RTPCodecCapability{MimeType: mime}) {
altCodec := selectAlternativeCodec(p.enabledPublishCodecs)
p.pubLogger.Infow("falling back to alternative codec",
"codec", mime,
"altCodec", altCodec,
"trackID", ti.Sid,
)
// select an alternative MIME type that's generally supported
mime = altCodec
}
} else if req.Type == livekit.TrackType_AUDIO && !strings.HasPrefix(mime, "audio/") {
mime = "audio/" + mime
}
if IsCodecEnabled(p.params.EnabledCodecs, webrtc.RTPCodecCapability{MimeType: mime}) {
ti.Codecs = append(ti.Codecs, &livekit.SimulcastCodecInfo{
MimeType: mime,
Cid: codec.Cid,
})
if _, ok := seenCodecs[mime]; ok {
continue
}
seenCodecs[mime] = struct{}{}
ti.Codecs = append(ti.Codecs, &livekit.SimulcastCodecInfo{
MimeType: mime,
Cid: codec.Cid,
})
}
p.params.Telemetry.TrackPublishRequested(context.Background(), p.ID(), p.Identity(), ti)
@@ -2313,3 +2333,35 @@ func (p *ParticipantImpl) SendDataPacket(dp *livekit.DataPacket, data []byte) er
}
return err
}
func (p *ParticipantImpl) setupEnabledCodecs(codecs []*livekit.Codec, disabledCodecs *livekit.DisabledCodecs) {
subscribeCodecs := make([]*livekit.Codec, 0, len(codecs))
publishCodecs := make([]*livekit.Codec, 0, len(codecs))
shouldDisable := func(c *livekit.Codec, disabled []*livekit.Codec) bool {
for _, disableCodec := range disabled {
// disable codec's fmtp is empty means disable this codec entirely
if strings.EqualFold(c.Mime, disableCodec.Mime) {
return true
}
}
return false
}
for _, c := range codecs {
var publishDisabled bool
var subscribeDisabled bool
if shouldDisable(c, disabledCodecs.GetCodecs()) {
publishDisabled = true
subscribeDisabled = true
} else if shouldDisable(c, disabledCodecs.GetPublish()) {
publishDisabled = true
}
if !publishDisabled {
publishCodecs = append(publishCodecs, c)
}
if !subscribeDisabled {
subscribeCodecs = append(subscribeCodecs, c)
}
}
p.enabledSubscribeCodecs = subscribeCodecs
p.enabledPublishCodecs = publishCodecs
}
+65 -1
View File
@@ -466,6 +466,71 @@ func TestDisableCodecs(t *testing.T) {
require.False(t, found264)
}
func TestDisablePublishCodec(t *testing.T) {
participant := newParticipantForTestWithOpts("123", &participantOpts{
publisher: true,
clientConf: &livekit.ClientConfiguration{
DisabledCodecs: &livekit.DisabledCodecs{
Publish: []*livekit.Codec{
{Mime: "video/h264"},
},
},
},
})
for _, codec := range participant.enabledPublishCodecs {
require.NotEqual(t, strings.ToLower(codec.Mime), "video/h264")
}
sink := &routingfakes.FakeMessageSink{}
participant.SetResponseSink(sink)
var publishReceived atomic.Bool
sink.WriteMessageCalls(func(msg proto.Message) error {
if res, ok := msg.(*livekit.SignalResponse); ok {
if published := res.GetTrackPublished(); published != nil {
publishReceived.Store(true)
require.NotEmpty(t, published.Track.Codecs)
require.Equal(t, "video/vp8", strings.ToLower(published.Track.Codecs[0].MimeType))
}
}
return nil
})
// simulcast codec response should pick an alternative
participant.AddTrack(&livekit.AddTrackRequest{
Cid: "cid1",
Type: livekit.TrackType_VIDEO,
SimulcastCodecs: []*livekit.SimulcastCodec{{
Codec: "h264",
Cid: "cid1",
}},
})
require.Eventually(t, func() bool { return publishReceived.Load() }, 5*time.Second, 10*time.Millisecond)
// publishing a supported codec should not change
publishReceived.Store(false)
sink.WriteMessageCalls(func(msg proto.Message) error {
if res, ok := msg.(*livekit.SignalResponse); ok {
if published := res.GetTrackPublished(); published != nil {
publishReceived.Store(true)
require.NotEmpty(t, published.Track.Codecs)
require.Equal(t, "video/vp8", strings.ToLower(published.Track.Codecs[0].MimeType))
}
}
return nil
})
participant.AddTrack(&livekit.AddTrackRequest{
Cid: "cid2",
Type: livekit.TrackType_VIDEO,
SimulcastCodecs: []*livekit.SimulcastCodec{{
Codec: "vp8",
Cid: "cid2",
}},
})
require.Eventually(t, func() bool { return publishReceived.Load() }, 5*time.Second, 10*time.Millisecond)
}
func TestPreferVideoCodecForPublisher(t *testing.T) {
participant := newParticipantForTestWithOpts("123", &participantOpts{
publisher: true,
@@ -641,7 +706,6 @@ func TestPreferAudioCodecForRed(t *testing.T) {
require.Equalf(t, !disableRed, redPreferred, "offer : \n%s\nanswer sdp: \n%s", sdp, answer.SDP)
})
}
}
type participantOpts struct {
+4 -33
View File
@@ -56,9 +56,9 @@ type TransportManagerParams struct {
ProtocolVersion types.ProtocolVersion
Telemetry telemetry.TelemetryService
CongestionControlConfig config.CongestionControlConfig
EnabledCodecs []*livekit.Codec
EnabledSubscribeCodecs []*livekit.Codec
EnabledPublishCodecs []*livekit.Codec
SimTracks map[uint32]SimulcastTrackInfo
ClientConf *livekit.ClientConfiguration
ClientInfo ClientInfo
Migration bool
AllowTCPFallback bool
@@ -112,35 +112,6 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
}
t.mediaLossProxy.OnMediaLossUpdate(t.onMediaLossUpdate)
subscribeCodecs := make([]*livekit.Codec, 0, len(params.EnabledCodecs))
publishCodecs := make([]*livekit.Codec, 0, len(params.EnabledCodecs))
shouldDisable := func(c *livekit.Codec, disabledCodecs []*livekit.Codec) bool {
for _, disableCodec := range disabledCodecs {
// disable codec's fmtp is empty means disable this codec entirely
if strings.EqualFold(c.Mime, disableCodec.Mime) && (disableCodec.FmtpLine == "" || disableCodec.FmtpLine == c.FmtpLine) {
return true
}
}
return false
}
for _, c := range params.EnabledCodecs {
var publishDisabled bool
var subscribeDisabled bool
if shouldDisable(c, params.ClientConf.GetDisabledCodecs().GetCodecs()) {
publishDisabled = true
subscribeDisabled = true
}
if shouldDisable(c, params.ClientConf.GetDisabledCodecs().GetPublish()) {
publishDisabled = true
}
if !publishDisabled {
publishCodecs = append(publishCodecs, c)
}
if !subscribeDisabled {
subscribeCodecs = append(subscribeCodecs, c)
}
}
publisher, err := NewPCTransport(TransportParams{
ParticipantID: params.SID,
ParticipantIdentity: params.Identity,
@@ -149,7 +120,7 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
DirectionConfig: params.Config.Publisher,
CongestionControlConfig: params.CongestionControlConfig,
Telemetry: params.Telemetry,
EnabledCodecs: publishCodecs,
EnabledCodecs: params.EnabledPublishCodecs,
Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER),
SimTracks: params.SimTracks,
ClientInfo: params.ClientInfo,
@@ -181,7 +152,7 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
DirectionConfig: params.Config.Subscriber,
CongestionControlConfig: params.CongestionControlConfig,
Telemetry: params.Telemetry,
EnabledCodecs: subscribeCodecs,
EnabledCodecs: params.EnabledSubscribeCodecs,
Logger: LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER),
ClientInfo: params.ClientInfo,
IsOfferer: true,