refactor(dvrip): simplify broadcast loop structure

- replace traditional for loop with range-based for loop for clarity

refactor(ffmpeg): simplify cut function loop
- utilize range-based for loop instead of traditional for loop

refactor(ring): update API response mapping type
- change map type from `interface{}` to `any` for better type safety

refactor(stream): handle nil source in NewStream
- add nil check for source elements before processing

refactor(webrtc): unify payload handling in GetToken
- change map type from `interface{}` to `any` for consistency

refactor(ascii): optimize nested loops in Write function
- replace traditional for loops with range-based for loops for readability

refactor(bits): enhance readability in Reader methods
- replace traditional for loops with range-based for loops in Read functions

refactor(h264): modernize loop structures in DecodeConfig
- switch to range-based for loops for cleaner code

refactor(h265): streamline profile_tier_level loops
- utilize range-based for loops instead of traditional for loops

chore(core): remove commented-out test function for clarity

refactor(core): simplify RandString function loop
- change traditional for loop to range-based for loop

refactor(flvt): optimize timestamp handling in TestTimeToRTP
- switch to range-based for loop for iterating frames

refactor(nest): improve error handling in ExchangeSDP
- format error message with printf-style formatting for clarity

refactor(tapo): enhance securityEncode function
- change traditional for loop to range-based for loop for readability

fix(tcp): correct masking in websocket Write method
- replace traditional for loop with range-based for loop

refactor(tutk): modernize encoding loops in crypto functions
- utilize range-based for loops for better readability

refactor(tuya): unify data types in MQTT message struct
- change map type from `interface{}` to `any` for consistency

refactor(webrtc): standardize codec registration
- change map type from `interface{}` to `any` for type safety

refactor(yaml): simplify Unmarshal function signature
- update parameter type from `interface{}` to `any` for better clarity
This commit is contained in:
Sergey Krashevich
2026-03-10 23:26:45 +03:00
parent 319fc3a154
commit 2b7682cdb3
42 changed files with 120 additions and 133 deletions
+1 -1
View File
@@ -80,7 +80,7 @@ func sendBroadcasts(conn *net.UDPConn) {
IP: net.IP{255, 255, 255, 255}, IP: net.IP{255, 255, 255, 255},
} }
for i := 0; i < 3; i++ { for range 3 {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
_, _ = conn.WriteToUDP(data, addr) _, _ = conn.WriteToUDP(data, addr)
} }
+1 -1
View File
@@ -175,7 +175,7 @@ func runToString(bin string, args string) string {
} }
func cut(s string, sep byte, pos int) string { func cut(s string, sep byte, pos int) string {
for n := 0; n < pos; n++ { for range pos {
if i := strings.IndexByte(s, sep); i > 0 { if i := strings.IndexByte(s, sep); i > 0 {
s = s[i+1:] s = s[i+1:]
} else { } else {
+1 -1
View File
@@ -45,7 +45,7 @@ func apiRing(w http.ResponseWriter, r *http.Request) {
if _, err = ringAPI.GetAuth(code); err != nil { if _, err = ringAPI.GetAuth(code); err != nil {
if ringAPI.Using2FA { if ringAPI.Using2FA {
// Return 2FA prompt // Return 2FA prompt
api.ResponseJSON(w, map[string]interface{}{ api.ResponseJSON(w, map[string]any{
"needs_2fa": true, "needs_2fa": true,
"prompt": ringAPI.PromptFor2FA, "prompt": ringAPI.PromptFor2FA,
}) })
+3
View File
@@ -30,6 +30,9 @@ func NewStream(source any) *Stream {
case []any: case []any:
s := new(Stream) s := new(Stream)
for _, src := range source { for _, src := range source {
if src == nil {
continue
}
str, ok := src.(string) str, ok := src.(string)
if !ok { if !ok {
log.Error().Msgf("[stream] NewStream: Expected string, got %v", src) log.Error().Msgf("[stream] NewStream: Expected string, got %v", src)
+1 -1
View File
@@ -54,7 +54,7 @@ func (m *milestoneAPI) GetToken() error {
return errors.New("milesone: authentication failed: " + res.Status) return errors.New("milesone: authentication failed: " + res.Status)
} }
var payload map[string]interface{} var payload map[string]any
if err = json.NewDecoder(res.Body).Decode(&payload); err != nil { if err = json.NewDecoder(res.Body).Decode(&payload); err != nil {
return err return err
} }
+3 -3
View File
@@ -114,8 +114,8 @@ func (a *writer) Write(p []byte) (n int, err error) {
w := img.Bounds().Dx() w := img.Bounds().Dx()
h := img.Bounds().Dy() h := img.Bounds().Dy()
for y := 0; y < h; y++ { for y := range h {
for x := 0; x < w; x++ { for x := range w {
r, g, b, _ := img.At(x, y).RGBA() r, g, b, _ := img.At(x, y).RGBA()
if a.color != nil { if a.color != nil {
a.color(uint8(r>>8), uint8(g>>8), uint8(b>>8)) a.color(uint8(r>>8), uint8(g>>8), uint8(b>>8))
@@ -155,7 +155,7 @@ const x256b = "\x00\x00\x00\x00\x80\x80\x80\xc0\x80\x00\x00\x00\xff\xff\xff\xff\
func xterm256color(r, g, b uint8, n int) (index uint8) { func xterm256color(r, g, b uint8, n int) (index uint8) {
best := uint16(0xFFFF) best := uint16(0xFFFF)
for i := 0; i < n; i++ { for i := range n {
diff := sqDiff(r, x256r[i]) + sqDiff(g, x256g[i]) + sqDiff(b, x256b[i]) diff := sqDiff(r, x256r[i]) + sqDiff(g, x256g[i]) + sqDiff(b, x256b[i])
if diff < best { if diff < best {
best = diff best = diff
+7 -7
View File
@@ -14,7 +14,7 @@ func NewReader(b []byte) *Reader {
} }
//goland:noinspection GoStandardMethods //goland:noinspection GoStandardMethods
func (r *Reader) ReadByte() byte { func (r *Reader) ReadUint8() byte {
if r.bits != 0 { if r.bits != 0 {
return r.ReadBits8(8) return r.ReadBits8(8)
} }
@@ -33,26 +33,26 @@ func (r *Reader) ReadUint16() uint16 {
if r.bits != 0 { if r.bits != 0 {
return r.ReadBits16(16) return r.ReadBits16(16)
} }
return uint16(r.ReadByte())<<8 | uint16(r.ReadByte()) return uint16(r.ReadUint8())<<8 | uint16(r.ReadUint8())
} }
func (r *Reader) ReadUint24() uint32 { func (r *Reader) ReadUint24() uint32 {
if r.bits != 0 { if r.bits != 0 {
return r.ReadBits(24) return r.ReadBits(24)
} }
return uint32(r.ReadByte())<<16 | uint32(r.ReadByte())<<8 | uint32(r.ReadByte()) return uint32(r.ReadUint8())<<16 | uint32(r.ReadUint8())<<8 | uint32(r.ReadUint8())
} }
func (r *Reader) ReadUint32() uint32 { func (r *Reader) ReadUint32() uint32 {
if r.bits != 0 { if r.bits != 0 {
return r.ReadBits(32) return r.ReadBits(32)
} }
return uint32(r.ReadByte())<<24 | uint32(r.ReadByte())<<16 | uint32(r.ReadByte())<<8 | uint32(r.ReadByte()) return uint32(r.ReadUint8())<<24 | uint32(r.ReadUint8())<<16 | uint32(r.ReadUint8())<<8 | uint32(r.ReadUint8())
} }
func (r *Reader) ReadBit() byte { func (r *Reader) ReadBit() byte {
if r.bits == 0 { if r.bits == 0 {
r.byte = r.ReadByte() r.byte = r.ReadUint8()
r.bits = 7 r.bits = 7
} else { } else {
r.bits-- r.bits--
@@ -106,8 +106,8 @@ func (r *Reader) ReadBytes(n int) (b []byte) {
r.pos += n r.pos += n
} else { } else {
b = make([]byte, n) b = make([]byte, n)
for i := 0; i < n; i++ { for i := range n {
b[i] = r.ReadByte() b[i] = r.ReadUint8()
} }
} }
+3 -3
View File
@@ -11,7 +11,7 @@ func NewWriter(buf []byte) *Writer {
} }
//goland:noinspection GoStandardMethods //goland:noinspection GoStandardMethods
func (w *Writer) WriteByte(b byte) { func (w *Writer) WriteUint8(b byte) {
if w.bits != 0 { if w.bits != 0 {
w.WriteBits8(b, 8) w.WriteBits8(b, 8)
} }
@@ -50,7 +50,7 @@ func (w *Writer) WriteBits8(v, n byte) {
} }
func (w *Writer) WriteAllBits(bit, n byte) { func (w *Writer) WriteAllBits(bit, n byte) {
for i := byte(0); i < n; i++ { for range n {
w.WriteBit(bit) w.WriteBit(bit)
} }
} }
@@ -74,7 +74,7 @@ func (w *Writer) WriteUint16(v uint16) {
func (w *Writer) WriteBytes(bytes ...byte) { func (w *Writer) WriteBytes(bytes ...byte) {
if w.bits != 0 { if w.bits != 0 {
for _, b := range bytes { for _, b := range bytes {
w.WriteByte(b) w.WriteUint8(b)
} }
} }
-14
View File
@@ -118,17 +118,3 @@ func TestName(t *testing.T) {
// stage3 // stage3
_ = prod2.Stop() _ = prod2.Stop()
} }
func TestStripUserinfo(t *testing.T) {
s := `streams:
test:
- ffmpeg:rtsp://username:password@10.1.2.3:554/stream1
- ffmpeg:rtsp://10.1.2.3:554/stream1@#video=copy
`
s = StripUserinfo(s)
require.Equal(t, `streams:
test:
- ffmpeg:rtsp://***@10.1.2.3:554/stream1
- ffmpeg:rtsp://10.1.2.3:554/stream1@#video=copy
`, s)
}
+1 -1
View File
@@ -32,7 +32,7 @@ func RandString(size, base byte) string {
if base == 0 { if base == 0 {
return string(b) return string(b)
} }
for i := byte(0); i < size; i++ { for i := range size {
b[i] = symbols[b[i]%base] b[i] = symbols[b[i]%base]
} }
return string(b) return string(b)
+1 -1
View File
@@ -11,7 +11,7 @@ func TestTimeToRTP(t *testing.T) {
// Video timestamp increases by 50ms, SampleRate 90000, RTP timestamp increases by 4500 // Video timestamp increases by 50ms, SampleRate 90000, RTP timestamp increases by 4500
// Audio timestamp increases by 64ms, SampleRate 16000, RTP timestamp increases by 1024 // Audio timestamp increases by 64ms, SampleRate 16000, RTP timestamp increases by 1024
frameN := 1 frameN := 1
for i := 0; i < 32; i++ { for range 32 {
// 1000ms/(90000/4500) = 50ms // 1000ms/(90000/4500) = 50ms
require.Equal(t, uint32(frameN*4500), TimeToRTP(uint32(frameN*50), 90000)) require.Equal(t, uint32(frameN*4500), TimeToRTP(uint32(frameN*50), 90000))
// 1000ms/(16000/1024) = 64ms // 1000ms/(16000/1024) = 64ms
+2 -2
View File
@@ -20,7 +20,7 @@ func DecodeConfig(conf []byte) (profile []byte, sps []byte, pps []byte) {
count := conf[5] & 0x1F count := conf[5] & 0x1F
conf = conf[6:] conf = conf[6:]
for i := byte(0); i < count; i++ { for range count {
if len(conf) < 2 { if len(conf) < 2 {
return return
} }
@@ -36,7 +36,7 @@ func DecodeConfig(conf []byte) (profile []byte, sps []byte, pps []byte) {
count = conf[0] count = conf[0]
conf = conf[1:] conf = conf[1:]
for i := byte(0); i < count; i++ { for range count {
if len(conf) < 2 { if len(conf) < 2 {
return return
} }
+13 -13
View File
@@ -92,15 +92,15 @@ func DecodeSPS(sps []byte) *SPS {
// ffmpeg -i file.h264 -c copy -bsf:v trace_headers -f null - // ffmpeg -i file.h264 -c copy -bsf:v trace_headers -f null -
r := bits.NewReader(sps) r := bits.NewReader(sps)
hdr := r.ReadByte() hdr := r.ReadUint8()
if hdr&0x1F != NALUTypeSPS { if hdr&0x1F != NALUTypeSPS {
return nil return nil
} }
s := &SPS{ s := &SPS{
profile_idc: r.ReadByte(), profile_idc: r.ReadUint8(),
profile_iop: r.ReadByte(), profile_iop: r.ReadUint8(),
level_idc: r.ReadByte(), level_idc: r.ReadUint8(),
seq_parameter_set_id: r.ReadUEGolomb(), seq_parameter_set_id: r.ReadUEGolomb(),
} }
@@ -120,7 +120,7 @@ func DecodeSPS(sps []byte) *SPS {
s.seq_scaling_matrix_present_flag = r.ReadBit() s.seq_scaling_matrix_present_flag = r.ReadBit()
if s.seq_scaling_matrix_present_flag != 0 { if s.seq_scaling_matrix_present_flag != 0 {
for i := byte(0); i < n; i++ { for i := range n {
//goland:noinspection GoSnakeCaseUsage //goland:noinspection GoSnakeCaseUsage
seq_scaling_list_present_flag := r.ReadBit() seq_scaling_list_present_flag := r.ReadBit()
if seq_scaling_list_present_flag != 0 { if seq_scaling_list_present_flag != 0 {
@@ -176,7 +176,7 @@ func DecodeSPS(sps []byte) *SPS {
if s.vui_parameters_present_flag != 0 { if s.vui_parameters_present_flag != 0 {
s.aspect_ratio_info_present_flag = r.ReadBit() s.aspect_ratio_info_present_flag = r.ReadBit()
if s.aspect_ratio_info_present_flag != 0 { if s.aspect_ratio_info_present_flag != 0 {
s.aspect_ratio_idc = r.ReadByte() s.aspect_ratio_idc = r.ReadUint8()
if s.aspect_ratio_idc == 255 { if s.aspect_ratio_idc == 255 {
s.sar_width = r.ReadUint16() s.sar_width = r.ReadUint16()
s.sar_height = r.ReadUint16() s.sar_height = r.ReadUint16()
@@ -225,7 +225,7 @@ func DecodeSPS(sps []byte) *SPS {
func (s *SPS) scaling_list(r *bits.Reader, sizeOfScalingList int) { func (s *SPS) scaling_list(r *bits.Reader, sizeOfScalingList int) {
lastScale := int32(8) lastScale := int32(8)
nextScale := int32(8) nextScale := int32(8)
for j := 0; j < sizeOfScalingList; j++ { for range sizeOfScalingList {
if nextScale != 0 { if nextScale != 0 {
delta_scale := r.ReadSEGolomb() delta_scale := r.ReadSEGolomb()
nextScale = (lastScale + delta_scale + 256) % 256 nextScale = (lastScale + delta_scale + 256) % 256
@@ -279,11 +279,11 @@ func (s *SPS) String() string {
func FixPixFmt(sps []byte) { func FixPixFmt(sps []byte) {
r := bits.NewReader(sps) r := bits.NewReader(sps)
_ = r.ReadByte() _ = r.ReadUint8()
profile := r.ReadByte() profile := r.ReadUint8()
_ = r.ReadByte() _ = r.ReadUint8()
_ = r.ReadByte() _ = r.ReadUint8()
_ = r.ReadUEGolomb() _ = r.ReadUEGolomb()
switch profile { switch profile {
@@ -300,7 +300,7 @@ func FixPixFmt(sps []byte) {
_ = r.ReadBit() _ = r.ReadBit()
if r.ReadBit() != 0 { if r.ReadBit() != 0 {
for i := byte(0); i < n; i++ { for range n {
if r.ReadBit() != 0 { if r.ReadBit() != 0 {
return // skip return // skip
} }
@@ -345,7 +345,7 @@ func FixPixFmt(sps []byte) {
if r.ReadBit() != 0 { if r.ReadBit() != 0 {
if r.ReadBit() != 0 { if r.ReadBit() != 0 {
if r.ReadByte() == 255 { if r.ReadUint8() == 255 {
_ = r.ReadUint16() _ = r.ReadUint16()
_ = r.ReadUint16() _ = r.ReadUint16()
} }
+2 -2
View File
@@ -92,7 +92,7 @@ func (s *SPS) profile_tier_level(r *bits.Reader) bool {
s.sub_layer_profile_present_flag = make([]byte, s.sps_max_sub_layers_minus1) s.sub_layer_profile_present_flag = make([]byte, s.sps_max_sub_layers_minus1)
s.sub_layer_level_present_flag = make([]byte, s.sps_max_sub_layers_minus1) s.sub_layer_level_present_flag = make([]byte, s.sps_max_sub_layers_minus1)
for i := byte(0); i < s.sps_max_sub_layers_minus1; i++ { for i := range s.sps_max_sub_layers_minus1 {
s.sub_layer_profile_present_flag[i] = r.ReadBit() s.sub_layer_profile_present_flag[i] = r.ReadBit()
s.sub_layer_level_present_flag[i] = r.ReadBit() s.sub_layer_level_present_flag[i] = r.ReadBit()
} }
@@ -103,7 +103,7 @@ func (s *SPS) profile_tier_level(r *bits.Reader) bool {
} }
} }
for i := byte(0); i < s.sps_max_sub_layers_minus1; i++ { for i := range s.sps_max_sub_layers_minus1 {
if s.sub_layer_profile_present_flag[i] != 0 { if s.sub_layer_profile_present_flag[i] != 0 {
_ = r.ReadBits8(2) // sub_layer_profile_space _ = r.ReadBits8(2) // sub_layer_profile_space
_ = r.ReadBit() // sub_layer_tier_flag _ = r.ReadBit() // sub_layer_tier_flag
+1 -1
View File
@@ -10,7 +10,7 @@ import (
) )
func TestNilCharacter(t *testing.T) { func TestNilCharacter(t *testing.T) {
var res SetupEndpoints var res SetupEndpointsRequest
char := &hap.Character{} char := &hap.Character{}
err := char.ReadTLV8(&res) err := char.ReadTLV8(&res)
require.NotNil(t, err) require.NotNil(t, err)
+2 -2
View File
@@ -13,7 +13,7 @@ func TestEncryption(t *testing.T) {
key := []byte(core.RandString(16, 0)) key := []byte(core.RandString(16, 0))
salt := core.RandString(32, 0) salt := core.RandString(32, 0)
c, err := Client(nil, key, salt, true) c, err := NewConn(nil, key, salt, true)
require.NoError(t, err) require.NoError(t, err)
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
@@ -23,7 +23,7 @@ func TestEncryption(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, 4, n) require.Equal(t, 4, n)
c, err = Client(nil, key, salt, false) c, err = NewConn(nil, key, salt, false)
c.rd = bufio.NewReader(buf) c.rd = bufio.NewReader(buf)
require.NoError(t, err) require.NoError(t, err)
+1 -1
View File
@@ -135,7 +135,7 @@ func appendValue(b []byte, tag byte, value reflect.Value) ([]byte, error) {
if value.Type().Elem().Kind() == reflect.Uint8 { if value.Type().Elem().Kind() == reflect.Uint8 {
n := value.Len() n := value.Len()
b = append(b, tag, byte(n)) b = append(b, tag, byte(n))
for i := 0; i < n; i++ { for i := range n {
b = append(b, byte(value.Index(i).Uint())) b = append(b, byte(value.Index(i).Uint()))
} }
return b, nil return b, nil
+1 -1
View File
@@ -41,7 +41,7 @@ func TestMarshal(t *testing.T) {
func TestBytes(t *testing.T) { func TestBytes(t *testing.T) {
bytes := make([]byte, 255) bytes := make([]byte, 255)
for i := 0; i < len(bytes); i++ { for i := range len(bytes) {
bytes[i] = byte(i) bytes[i] = byte(i)
} }
+1 -1
View File
@@ -88,7 +88,7 @@ func (r *reader) RoundTrip(_ *http.Request) (*http.Response, error) {
} }
func (r *reader) getSegment() ([]byte, error) { func (r *reader) getSegment() ([]byte, error) {
for i := 0; i < 10; i++ { for range 10 {
if r.playlist == nil { if r.playlist == nil {
if wait := time.Second - time.Since(r.lastTime); wait > 0 { if wait := time.Second - time.Since(r.lastTime); wait > 0 {
time.Sleep(wait) time.Sleep(wait)
+2 -2
View File
@@ -120,7 +120,7 @@ func DecodeAtom(b []byte) (any, error) {
case MoofTrafTfhd: case MoofTrafTfhd:
rd := bits.NewReader(data) rd := bits.NewReader(data)
_ = rd.ReadByte() // version _ = rd.ReadUint8() // version
flags := rd.ReadUint24() flags := rd.ReadUint24()
atom := &AtomTfhd{ atom := &AtomTfhd{
@@ -145,7 +145,7 @@ func DecodeAtom(b []byte) (any, error) {
case MoofTrafTrun: case MoofTrafTrun:
rd := bits.NewReader(data) rd := bits.NewReader(data)
_ = rd.ReadByte() // version _ = rd.ReadUint8() // version
flags := rd.ReadUint24() flags := rd.ReadUint24()
samples := rd.ReadUint32() samples := rd.ReadUint32()
+1 -1
View File
@@ -78,7 +78,7 @@ func GetLiveStream(id string) (string, error) {
} }
if !v.Success { if !v.Success {
return "", fmt.Errorf("ivideon: can't get live_stream: " + v.Message) return "", fmt.Errorf("ivideon: can't get live_stream: %s", v.Message)
} }
return v.Result.URL, nil return v.Result.URL, nil
+1 -1
View File
@@ -47,7 +47,7 @@ func MakeTables(q byte) (lqt, cqt []byte) {
lqt = make([]byte, 64) lqt = make([]byte, 64)
cqt = make([]byte, 64) cqt = make([]byte, 64)
for i := 0; i < 64; i++ { for i := range 64 {
lq := (int(jpeg_luma_quantizer[i])*factor + 50) / 100 lq := (int(jpeg_luma_quantizer[i])*factor + 50) / 100
cq := (int(jpeg_chroma_quantizer[i])*factor + 50) / 100 cq := (int(jpeg_chroma_quantizer[i])*factor + 50) / 100
+1 -1
View File
@@ -97,7 +97,7 @@ func (d *Demuxer) Demux(data2 []byte) (trackID uint32, packets []*core.Packet) {
n := len(trun.SamplesDuration) n := len(trun.SamplesDuration)
packets = make([]*core.Packet, n) packets = make([]*core.Packet, n)
for i := 0; i < n; i++ { for i := range n {
duration := trun.SamplesDuration[i] duration := trun.SamplesDuration[i]
size := trun.SamplesSize[i] size := trun.SamplesSize[i]
+10 -10
View File
@@ -129,7 +129,7 @@ func (m *Muxer) writePMT(wr *bits.Writer) {
if !ok { if !ok {
break break
} }
wr.WriteByte(pes.StreamType) // Stream type wr.WriteUint8(pes.StreamType) // Stream type
wr.WriteBits8(0b111, 3) // Reserved bits (all to 1) wr.WriteBits8(0b111, 3) // Reserved bits (all to 1)
wr.WriteBits16(pid, 13) // Elementary PID wr.WriteBits16(pid, 13) // Elementary PID
wr.WriteBits8(0b1111, 4) // Reserved bits (all to 1) wr.WriteBits8(0b1111, 4) // Reserved bits (all to 1)
@@ -148,7 +148,7 @@ func (m *Muxer) writePES(wr *bits.Writer, pid uint16, pes *PES) {
const flagAdaptation = 0b00100000 const flagAdaptation = 0b00100000
const flagPayload = 0b00010000 const flagPayload = 0b00010000
wr.WriteByte(SyncByte) wr.WriteUint8(SyncByte)
if pes.Size != 0 { if pes.Size != 0 {
pid |= flagPUSI // Payload unit start indicator (PUSI) pid |= flagPUSI // Payload unit start indicator (PUSI)
@@ -159,17 +159,17 @@ func (m *Muxer) writePES(wr *bits.Writer, pid uint16, pes *PES) {
counter := byte(pes.Sequence) & 0xF counter := byte(pes.Sequence) & 0xF
if size := len(pes.Payload); size < PacketSize-4 { if size := len(pes.Payload); size < PacketSize-4 {
wr.WriteByte(flagAdaptation | flagPayload | counter) // adaptation + payload wr.WriteUint8(flagAdaptation | flagPayload | counter) // adaptation + payload
// for 183 payload will be zero // for 183 payload will be zero
adSize := PacketSize - 4 - 1 - byte(size) adSize := PacketSize - 4 - 1 - byte(size)
wr.WriteByte(adSize) wr.WriteUint8(adSize)
wr.WriteBytes(make([]byte, adSize)...) wr.WriteBytes(make([]byte, adSize)...)
wr.WriteBytes(pes.Payload...) wr.WriteBytes(pes.Payload...)
pes.Payload = nil pes.Payload = nil
} else { } else {
wr.WriteByte(flagPayload | counter) // only payload wr.WriteUint8(flagPayload | counter) // only payload
wr.WriteBytes(pes.Payload[:PacketSize-4]...) wr.WriteBytes(pes.Payload[:PacketSize-4]...)
pes.Payload = pes.Payload[PacketSize-4:] pes.Payload = pes.Payload[PacketSize-4:]
@@ -177,7 +177,7 @@ func (m *Muxer) writePES(wr *bits.Writer, pid uint16, pes *PES) {
} }
func (m *Muxer) writeHeader(wr *bits.Writer, pid uint16) { func (m *Muxer) writeHeader(wr *bits.Writer, pid uint16) {
wr.WriteByte(SyncByte) wr.WriteUint8(SyncByte)
wr.WriteBit(0) // Transport error indicator (TEI) wr.WriteBit(0) // Transport error indicator (TEI)
wr.WriteBit(1) // Payload unit start indicator (PUSI) wr.WriteBit(1) // Payload unit start indicator (PUSI)
@@ -191,9 +191,9 @@ func (m *Muxer) writeHeader(wr *bits.Writer, pid uint16) {
} }
func (m *Muxer) writePSIHeader(wr *bits.Writer, tableID byte, size uint16) { func (m *Muxer) writePSIHeader(wr *bits.Writer, tableID byte, size uint16) {
wr.WriteByte(0) // Pointer field wr.WriteUint8(0) // Pointer field
wr.WriteByte(tableID) // Table ID wr.WriteUint8(tableID) // Table ID
wr.WriteBit(1) // Section syntax indicator wr.WriteBit(1) // Section syntax indicator
wr.WriteBit(0) // Private bit wr.WriteBit(0) // Private bit
@@ -206,8 +206,8 @@ func (m *Muxer) writePSIHeader(wr *bits.Writer, tableID byte, size uint16) {
wr.WriteBits8(0, 5) // Version number wr.WriteBits8(0, 5) // Version number
wr.WriteBit(1) // Current/next indicator wr.WriteBit(1) // Current/next indicator
wr.WriteByte(0) // Section number wr.WriteUint8(0) // Section number
wr.WriteByte(0) // Last section number wr.WriteUint8(0) // Last section number
} }
func (m *Muxer) WriteTail(wr *bits.Writer) { func (m *Muxer) WriteTail(wr *bits.Writer) {
+2 -2
View File
@@ -42,7 +42,7 @@ func opus_control_header(r *bits.Reader) int {
var payload_size int var payload_size int
for { for {
i := r.ReadByte() i := r.ReadUint8()
payload_size += int(i) payload_size += int(i)
if i < 255 { if i < 255 {
break break
@@ -58,7 +58,7 @@ func opus_control_header(r *bits.Reader) int {
_ = r.ReadBits(13) _ = r.ReadBits(13)
} }
if control_extension_flag != 0 { if control_extension_flag != 0 {
control_extension_length := r.ReadByte() control_extension_length := r.ReadUint8()
_ = r.ReadBytes(int(control_extension_length)) // reserved _ = r.ReadBytes(int(control_extension_length)) // reserved
} }
+9 -9
View File
@@ -19,7 +19,7 @@ const (
QOS1 = 0x02 QOS1 = 0x02
) )
func (m *Message) WriteByte(b byte) { func (m *Message) WriteUint8(b byte) {
m.b = append(m.b, b) m.b = append(m.b, b)
} }
@@ -37,7 +37,7 @@ func (m *Message) WriteLen(i int) {
if i /= 128; i > 0 { if i /= 128; i > 0 {
b |= 0x80 b |= 0x80
} }
m.WriteByte(b) m.WriteUint8(b)
} }
} }
@@ -58,12 +58,12 @@ const (
func NewConnect(clientID, username, password string) *Message { func NewConnect(clientID, username, password string) *Message {
m := &Message{} m := &Message{}
m.WriteByte(CONNECT) m.WriteUint8(CONNECT)
m.WriteLen(16 + len(clientID) + len(username) + len(password)) m.WriteLen(16 + len(clientID) + len(username) + len(password))
m.WriteString("MQTT") m.WriteString("MQTT")
m.WriteByte(4) // MQTT version m.WriteUint8(4) // MQTT version
m.WriteByte(flagCleanStart | flagUsername | flagPassword) m.WriteUint8(flagCleanStart | flagUsername | flagPassword)
m.WriteUint16(30) // keepalive m.WriteUint16(30) // keepalive
m.WriteString(clientID) m.WriteString(clientID)
@@ -74,18 +74,18 @@ func NewConnect(clientID, username, password string) *Message {
func NewSubscribe(mid uint16, topic string, qos byte) *Message { func NewSubscribe(mid uint16, topic string, qos byte) *Message {
m := &Message{} m := &Message{}
m.WriteByte(SUBSCRIBE) m.WriteUint8(SUBSCRIBE)
m.WriteLen(5 + len(topic)) m.WriteLen(5 + len(topic))
m.WriteUint16(mid) m.WriteUint16(mid)
m.WriteString(topic) m.WriteString(topic)
m.WriteByte(qos) m.WriteUint8(qos)
return m return m
} }
func NewPublish(topic string, payload []byte) *Message { func NewPublish(topic string, payload []byte) *Message {
m := &Message{} m := &Message{}
m.WriteByte(PUBLISH) m.WriteUint8(PUBLISH)
m.WriteLen(2 + len(topic) + len(payload)) m.WriteLen(2 + len(topic) + len(payload))
m.WriteString(topic) m.WriteString(topic)
@@ -95,7 +95,7 @@ func NewPublish(topic string, payload []byte) *Message {
func NewPublishQOS1(mid uint16, topic string, payload []byte) *Message { func NewPublishQOS1(mid uint16, topic string, payload []byte) *Message {
m := &Message{} m := &Message{}
m.WriteByte(PUBLISH | QOS1) m.WriteUint8(PUBLISH | QOS1)
m.WriteLen(4 + len(topic) + len(payload)) m.WriteLen(4 + len(topic) + len(payload))
m.WriteString(topic) m.WriteString(topic)
+1 -1
View File
@@ -170,7 +170,7 @@ func (a *API) ExchangeSDP(projectID, deviceID, offer string) (string, error) {
maxRetries := 3 maxRetries := 3
retryDelay := time.Second * 30 retryDelay := time.Second * 30
for attempt := 0; attempt < maxRetries; attempt++ { for attempt := range maxRetries {
req, err := http.NewRequest("POST", uri, bytes.NewReader(b)) req, err := http.NewRequest("POST", uri, bytes.NewReader(b))
if err != nil { if err != nil {
return "", err return "", err
+2 -2
View File
@@ -45,7 +45,7 @@ func Dial(rawURL string) (core.Producer, error) {
var nestAPI *API var nestAPI *API
var lastErr error var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ { for attempt := range maxRetries {
nestAPI, err = NewAPI(cliendID, cliendSecret, refreshToken) nestAPI, err = NewAPI(cliendID, cliendSecret, refreshToken)
if err == nil { if err == nil {
break break
@@ -101,7 +101,7 @@ func rtcConn(nestAPI *API, rawURL, projectID, deviceID string) (*WebRTCClient, e
retryDelay := time.Second * 30 retryDelay := time.Second * 30
var lastErr error var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ { for attempt := range maxRetries {
rtcAPI, err := webrtc.NewAPI() rtcAPI, err := webrtc.NewAPI()
if err != nil { if err != nil {
return nil, err return nil, err
+2 -2
View File
@@ -8,7 +8,7 @@ import (
) )
func TestPCMUtoPCM(t *testing.T) { func TestPCMUtoPCM(t *testing.T) {
for pcmu := byte(0); pcmu < 255; pcmu++ { for pcmu := range byte(255) {
pcm1 := MuLawDecompressTable[pcmu] pcm1 := MuLawDecompressTable[pcmu]
pcm2 := v2.PCMUtoPCM(pcmu) pcm2 := v2.PCMUtoPCM(pcmu)
require.Equal(t, pcm1, pcm2) require.Equal(t, pcm1, pcm2)
@@ -16,7 +16,7 @@ func TestPCMUtoPCM(t *testing.T) {
} }
func TestPCMAtoPCM(t *testing.T) { func TestPCMAtoPCM(t *testing.T) {
for pcma := byte(0); pcma < 255; pcma++ { for pcma := range byte(255) {
pcm1 := ALawDecompressTable[pcma] pcm1 := ALawDecompressTable[pcma]
pcm2 := v2.PCMAtoPCM(pcma) pcm2 := v2.PCMAtoPCM(pcma)
require.Equal(t, pcm1, pcm2) require.Equal(t, pcm1, pcm2)
+14 -14
View File
@@ -71,7 +71,7 @@ type RingApi struct {
Using2FA bool Using2FA bool
PromptFor2FA string PromptFor2FA string
RefreshToken string RefreshToken string
auth interface{} // EmailAuth or RefreshTokenAuth auth any // EmailAuth or RefreshTokenAuth
onTokenRefresh func(string) onTokenRefresh func(string)
authMutex sync.Mutex authMutex sync.Mutex
session *SessionResponse session *SessionResponse
@@ -93,12 +93,12 @@ type CameraData struct {
type RingDeviceType string type RingDeviceType string
type RingDevicesResponse struct { type RingDevicesResponse struct {
Doorbots []CameraData `json:"doorbots"` Doorbots []CameraData `json:"doorbots"`
AuthorizedDoorbots []CameraData `json:"authorized_doorbots"` AuthorizedDoorbots []CameraData `json:"authorized_doorbots"`
StickupCams []CameraData `json:"stickup_cams"` StickupCams []CameraData `json:"stickup_cams"`
AllCameras []CameraData `json:"all_cameras"` AllCameras []CameraData `json:"all_cameras"`
Chimes []CameraData `json:"chimes"` Chimes []CameraData `json:"chimes"`
Other []map[string]interface{} `json:"other"` Other []map[string]any `json:"other"`
} }
const ( const (
@@ -153,7 +153,7 @@ const (
sessionValidTime = 12 * time.Hour sessionValidTime = 12 * time.Hour
) )
func NewRestClient(auth interface{}, onTokenRefresh func(string)) (*RingApi, error) { func NewRestClient(auth any, onTokenRefresh func(string)) (*RingApi, error) {
var cacheKey string var cacheKey string
// Create cache key based on auth data // Create cache key based on auth data
@@ -400,7 +400,7 @@ func (c *RingApi) GetSocketTicket() (*SocketTicketResponse, error) {
return &ticket, nil return &ticket, nil
} }
func (c *RingApi) Request(method, url string, body interface{}) ([]byte, error) { func (c *RingApi) Request(method, url string, body any) ([]byte, error) {
// Ensure we have a valid session // Ensure we have a valid session
if err := c.ensureSession(); err != nil { if err := c.ensureSession(); err != nil {
return nil, fmt.Errorf("session validation failed: %w", err) return nil, fmt.Errorf("session validation failed: %w", err)
@@ -476,7 +476,7 @@ func (c *RingApi) Request(method, url string, body interface{}) ([]byte, error)
// Handle 404 error with hardware_id reference - session issue // Handle 404 error with hardware_id reference - session issue
if resp.StatusCode == 404 && strings.Contains(url, clientAPIBaseURL) { if resp.StatusCode == 404 && strings.Contains(url, clientAPIBaseURL) {
var errorBody map[string]interface{} var errorBody map[string]any
if err := json.Unmarshal(responseBody, &errorBody); err == nil { if err := json.Unmarshal(responseBody, &errorBody); err == nil {
if errorStr, ok := errorBody["error"].(string); ok && strings.Contains(errorStr, c.hardwareID) { if errorStr, ok := errorBody["error"].(string); ok && strings.Contains(errorStr, c.hardwareID) {
// Session with hardware_id not found, refresh session // Session with hardware_id not found, refresh session
@@ -523,10 +523,10 @@ func (c *RingApi) ensureSession() error {
return fmt.Errorf("authentication failed while creating session: %w", err) return fmt.Errorf("authentication failed while creating session: %w", err)
} }
sessionPayload := map[string]interface{}{ sessionPayload := map[string]any{
"device": map[string]interface{}{ "device": map[string]any{
"hardware_id": c.hardwareID, "hardware_id": c.hardwareID,
"metadata": map[string]interface{}{ "metadata": map[string]any{
"api_version": apiVersion, "api_version": apiVersion,
"device_model": "ring-client-go", "device_model": "ring-client-go",
}, },
@@ -686,7 +686,7 @@ func generateHardwareID() string {
return hex.EncodeToString(h.Sum(nil)[:16]) return hex.EncodeToString(h.Sum(nil)[:16])
} }
func interfaceSlice(slice interface{}) []CameraData { func interfaceSlice(slice any) []CameraData {
s := reflect.ValueOf(slice) s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice { if s.Kind() != reflect.Slice {
return nil return nil
+3 -3
View File
@@ -140,7 +140,7 @@ func Dial(rawURL string) (*Client, error) {
return return
} }
icePayload := map[string]interface{}{ icePayload := map[string]any{
"ice": iceCandidate.Candidate, "ice": iceCandidate.Candidate,
"mlineindex": iceCandidate.SDPMLineIndex, "mlineindex": iceCandidate.SDPMLineIndex,
} }
@@ -200,7 +200,7 @@ func Dial(rawURL string) (*Client, error) {
} }
// Send offer // Send offer
offerPayload := map[string]interface{}{ offerPayload := map[string]any{
"stream_options": map[string]bool{ "stream_options": map[string]bool{
"audio_enabled": true, "audio_enabled": true,
"video_enabled": true, "video_enabled": true,
@@ -317,7 +317,7 @@ func (c *Client) AddTrack(media *core.Media, codec *core.Codec, track *core.Rece
if webrtcProd, ok := c.prod.(*webrtc.Conn); ok { if webrtcProd, ok := c.prod.(*webrtc.Conn); ok {
if media.Kind == core.KindAudio { if media.Kind == core.KindAudio {
// Enable speaker // Enable speaker
speakerPayload := map[string]interface{}{ speakerPayload := map[string]any{
"stealth_mode": false, "stealth_mode": false,
} }
_ = c.wsClient.sendSessionMessage("camera_options", speakerPayload) _ = c.wsClient.sendSessionMessage("camera_options", speakerPayload)
+6 -6
View File
@@ -142,8 +142,8 @@ func (c *WSClient) Close() error {
close(c.closed) close(c.closed)
} }
closePayload := map[string]interface{}{ closePayload := map[string]any{
"reason": map[string]interface{}{ "reason": map[string]any{
"code": CloseReasonNormalClose, "code": CloseReasonNormalClose,
"text": "", "text": "",
}, },
@@ -198,7 +198,7 @@ func (c *WSClient) activateSession() error {
return err return err
} }
streamPayload := map[string]interface{}{ streamPayload := map[string]any{
"audio_enabled": true, "audio_enabled": true,
"video_enabled": true, "video_enabled": true,
} }
@@ -210,7 +210,7 @@ func (c *WSClient) activateSession() error {
return nil return nil
} }
func (c *WSClient) sendSessionMessage(method string, payload map[string]interface{}) error { func (c *WSClient) sendSessionMessage(method string, payload map[string]any) error {
select { select {
case <-c.closed: case <-c.closed:
return nil return nil
@@ -222,7 +222,7 @@ func (c *WSClient) sendSessionMessage(method string, payload map[string]interfac
defer c.wsMutex.Unlock() defer c.wsMutex.Unlock()
if payload == nil { if payload == nil {
payload = make(map[string]interface{}) payload = make(map[string]any)
} }
payload["doorbot_id"] = c.cameraID payload["doorbot_id"] = c.cameraID
@@ -230,7 +230,7 @@ func (c *WSClient) sendSessionMessage(method string, payload map[string]interfac
payload["session_id"] = c.sessionID payload["session_id"] = c.sessionID
} }
msg := map[string]interface{}{ msg := map[string]any{
"method": method, "method": method,
"dialog_id": c.dialogID, "dialog_id": c.dialogID,
"body": payload, "body": payload,
+1 -1
View File
@@ -68,7 +68,7 @@ func encodeTimestamp(i uint32) string {
func pad(plainText []byte, blockSize int) []byte { func pad(plainText []byte, blockSize int) []byte {
b0 := byte(blockSize - len(plainText)%blockSize) b0 := byte(blockSize - len(plainText)%blockSize)
for i := byte(0); i < b0; i++ { for range b0 {
plainText = append(plainText, b0) plainText = append(plainText, b0)
} }
return plainText return plainText
+1 -1
View File
@@ -419,7 +419,7 @@ func ListenUDPPair() (*net.UDPConn, *net.UDPConn, error) {
listenUDPMu.Lock() listenUDPMu.Lock()
defer listenUDPMu.Unlock() defer listenUDPMu.Unlock()
for i := 0; i < listenUDPAttemps; i++ { for range listenUDPAttemps {
// Get a random even port from the OS // Get a random even port from the OS
ln1, err := net.ListenUDP("udp", &net.UDPAddr{IP: nil, Port: 0}) ln1, err := net.ListenUDP("udp", &net.UDPAddr{IP: nil, Port: 0})
if err != nil { if err != nil {
+1 -1
View File
@@ -389,7 +389,7 @@ func securityEncode(s string) string {
b := make([]byte, n) b := make([]byte, n)
for i := 0; i < n; i++ { for i := range n {
c1 := 187 c1 := 187
c2 := 187 c2 := 187
if i >= size { if i >= size {
+1 -1
View File
@@ -98,7 +98,7 @@ func (w *Client) Write(b []byte) (n int, err error) {
return 0, err return 0, err
} }
for i := 0; i < len(b); i++ { for i := range len(b) {
msg[i] = b[i] ^ mask[i%4] msg[i] = b[i] ^ mask[i%4]
} }
+2 -2
View File
@@ -43,7 +43,7 @@ func ReverseTransCodePartial(dst, src []byte) []byte {
swap(tmp16, src16, n) swap(tmp16, src16, n)
for i := 0; i < n; i++ { for i := range n {
dst16[i] = tmp16[i] ^ charlie[i] dst16[i] = tmp16[i] ^ charlie[i]
} }
@@ -111,7 +111,7 @@ func TransCodePartial(dst, src []byte) []byte {
src16 = src16[16:] src16 = src16[16:]
} }
for i := 0; i < n; i++ { for i := range n {
tmp16[i] = src16[i] ^ charlie[i] tmp16[i] = src16[i] ^ charlie[i]
} }
+2 -2
View File
@@ -208,7 +208,7 @@ func (c *TuyaCloudApiClient) loadWebrtcConfig() (*WebRTCConfig, error) {
} }
if !webRTCConfigResponse.Success { if !webRTCConfigResponse.Success {
return nil, fmt.Errorf(webRTCConfigResponse.Msg) return nil, fmt.Errorf("%s", webRTCConfigResponse.Msg)
} }
err = json.Unmarshal([]byte(webRTCConfigResponse.Result.Skill), &c.skill) err = json.Unmarshal([]byte(webRTCConfigResponse.Result.Skill), &c.skill)
@@ -254,7 +254,7 @@ func (c *TuyaCloudApiClient) loadHubConfig() (config *MQTTConfig, err error) {
} }
if !openIoTHubConfigResponse.Success { if !openIoTHubConfigResponse.Success {
return nil, fmt.Errorf(openIoTHubConfigResponse.Msg) return nil, fmt.Errorf("%s", openIoTHubConfigResponse.Msg)
} }
return &MQTTConfig{ return &MQTTConfig{
+7 -7
View File
@@ -88,12 +88,12 @@ type MqttLowPowerMessage struct {
S int `json:"s,omitempty"` S int `json:"s,omitempty"`
Type string `json:"type,omitempty"` Type string `json:"type,omitempty"`
Data struct { Data struct {
DevID string `json:"devId,omitempty"` DevID string `json:"devId,omitempty"`
Online bool `json:"online,omitempty"` Online bool `json:"online,omitempty"`
LastOnlineChangeTime int64 `json:"lastOnlineChangeTime,omitempty"` LastOnlineChangeTime int64 `json:"lastOnlineChangeTime,omitempty"`
GwID string `json:"gwId,omitempty"` GwID string `json:"gwId,omitempty"`
Cmd string `json:"cmd,omitempty"` Cmd string `json:"cmd,omitempty"`
Dps map[string]interface{} `json:"dps,omitempty"` Dps map[string]any `json:"dps,omitempty"`
} `json:"data"` } `json:"data"`
} }
@@ -395,7 +395,7 @@ func (c *TuyaMqttClient) onError(err error) {
} }
} }
func (c *TuyaMqttClient) sendMqttMessage(messageType string, protocol int, transactionID string, data interface{}) error { func (c *TuyaMqttClient) sendMqttMessage(messageType string, protocol int, transactionID string, data any) error {
if c.closed { if c.closed {
return fmt.Errorf("mqtt client is closed, send mqtt message fail") return fmt.Errorf("mqtt client is closed, send mqtt message fail")
} }
+4 -4
View File
@@ -264,10 +264,10 @@ func RegisterDefaultCodecs(m *webrtc.MediaEngine) error {
} }
videoRTCPFeedback := []webrtc.RTCPFeedback{ videoRTCPFeedback := []webrtc.RTCPFeedback{
{"goog-remb", ""}, {Type: "goog-remb", Parameter: ""},
{"ccm", "fir"}, {Type: "ccm", Parameter: "fir"},
{"nack", ""}, {Type: "nack", Parameter: ""},
{"nack", "pli"}, {Type: "nack", Parameter: "pli"},
} }
for _, codec := range []webrtc.RTPCodecParameters{ for _, codec := range []webrtc.RTPCodecParameters{
{ {
-2
View File
@@ -208,8 +208,6 @@ func (c *Conn) getMediaCodec(remote *webrtc.TrackRemote) (*core.Media, *core.Cod
// sends new codec with new payload type to same media // sends new codec with new payload type to same media
// check GetTrack // check GetTrack
panic(core.Caller()) panic(core.Caller())
return nil, nil
} }
func sanitizeIP6(host string) string { func sanitizeIP6(host string) string {
+2 -2
View File
@@ -7,7 +7,7 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
func Unmarshal(in []byte, out interface{}) (err error) { func Unmarshal(in []byte, out any) (err error) {
return yaml.Unmarshal(in, out) return yaml.Unmarshal(in, out)
} }
@@ -190,7 +190,7 @@ func addPrefix(src, pre []byte) (dst []byte) {
func addIndent(in []byte, indent int) (dst []byte) { func addIndent(in []byte, indent int) (dst []byte) {
pre := make([]byte, indent) pre := make([]byte, indent)
for i := 0; i < indent; i++ { for i := range indent {
pre[i] = ' ' pre[i] = ' '
} }
return addPrefix(in, pre) return addPrefix(in, pre)