@@ -64,11 +64,47 @@ func Decode(w media.PCM16Writer, targetChannels int, logger logger.Logger) (Writ
6464 }, nil
6565}
6666
67+ // EncodeOptions tunes the Opus encoder. Zero values keep libopus defaults.
68+ type EncodeOptions struct {
69+ // Bitrate is the target encoder bitrate in bits/sec (e.g. 24000). 0 = auto.
70+ Bitrate int
71+ // Complexity is the encoder computational complexity 1-10. 0 = default.
72+ Complexity int
73+ // FEC enables in-band Forward Error Correction.
74+ FEC bool
75+ // PacketLossPercent is the expected packet loss 0-100, used to tune FEC.
76+ PacketLossPercent int
77+ }
78+
6779func Encode (w Writer , channels int , logger logger.Logger ) (media.PCM16Writer , error ) {
80+ return EncodeWith (w , channels , EncodeOptions {}, logger )
81+ }
82+
83+ func EncodeWith (w Writer , channels int , opts EncodeOptions , logger logger.Logger ) (media.PCM16Writer , error ) {
6884 enc , err := opus .NewEncoder (w .SampleRate (), channels , opus .AppVoIP )
6985 if err != nil {
7086 return nil , err
7187 }
88+ if opts .Bitrate > 0 {
89+ if err = enc .SetBitrate (opts .Bitrate ); err != nil {
90+ return nil , fmt .Errorf ("opus set bitrate: %w" , err )
91+ }
92+ }
93+ if opts .Complexity > 0 {
94+ if err = enc .SetComplexity (opts .Complexity ); err != nil {
95+ return nil , fmt .Errorf ("opus set complexity: %w" , err )
96+ }
97+ }
98+ if opts .FEC {
99+ if err = enc .SetInBandFEC (true ); err != nil {
100+ return nil , fmt .Errorf ("opus set fec: %w" , err )
101+ }
102+ if opts .PacketLossPercent > 0 {
103+ if err = enc .SetPacketLossPerc (opts .PacketLossPercent ); err != nil {
104+ return nil , fmt .Errorf ("opus set packet loss: %w" , err )
105+ }
106+ }
107+ }
72108 return & encoder {
73109 w : w ,
74110 enc : enc ,
0 commit comments