github.com/cnotch/ipchub@v1.1.0/media/consumptions.go (about)

     1  // Copyright (c) 2019,CAOHONGJU All rights reserved.
     2  // Use of this source code is governed by a MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package media
     6  
     7  import (
     8  	"sort"
     9  	"sync"
    10  	"sync/atomic"
    11  )
    12  
    13  type consumptions struct {
    14  	sync.Map
    15  	count int32
    16  }
    17  
    18  func (m *consumptions) SendToAll(p Pack, keyframe bool) {
    19  	m.Range(func(key, value interface{}) bool {
    20  		c := value.(*consumption)
    21  		c.send(p, keyframe)
    22  		return true
    23  	})
    24  }
    25  
    26  func (m *consumptions) RemoveAndCloseAll() {
    27  	m.Range(func(key, value interface{}) bool {
    28  		c := value.(*consumption)
    29  		m.Delete(key)
    30  		c.Close()
    31  		return true
    32  	})
    33  
    34  	atomic.StoreInt32(&m.count, 0)
    35  }
    36  
    37  func (m *consumptions) Add(c *consumption) {
    38  	m.Store(c.cid, c)
    39  	atomic.AddInt32(&m.count, 1)
    40  }
    41  
    42  func (m *consumptions) Remove(cid CID) *consumption {
    43  	ci, ok := m.Load(cid)
    44  	if ok {
    45  		m.Delete(cid)
    46  		atomic.AddInt32(&m.count, -1)
    47  		return ci.(*consumption)
    48  	}
    49  	return nil
    50  }
    51  
    52  func (m *consumptions) Count() int {
    53  	return int(atomic.LoadInt32(&m.count))
    54  }
    55  
    56  func (m *consumptions) Infos() []ConsumptionInfo {
    57  	cs := make([]ConsumptionInfo, 0, 10)
    58  	m.Range(func(key, value interface{}) bool {
    59  		cs = append(cs, value.(*consumption).Info())
    60  		return true
    61  	})
    62  
    63  	sort.Slice(cs, func(i, j int) bool {
    64  		return cs[i].ID < cs[j].ID
    65  	})
    66  
    67  	return cs
    68  }