Class: Vizcore::Audio::RingBuffer
- Inherits:
-
Object
- Object
- Vizcore::Audio::RingBuffer
- Defined in:
- lib/vizcore/audio/ring_buffer.rb
Overview
Thread-safe circular buffer for recent audio samples.
Instance Attribute Summary collapse
-
#capacity ⇒ Object
readonly
Returns the value of attribute capacity.
Instance Method Summary collapse
- #clear ⇒ void
-
#initialize(capacity) ⇒ RingBuffer
constructor
A new instance of RingBuffer.
-
#latest(count = nil) ⇒ Array<Float>
Newest values first-in-order.
- #push(sample) ⇒ void
- #size ⇒ Integer
- #write(samples) ⇒ void
Constructor Details
#initialize(capacity) ⇒ RingBuffer
Returns a new instance of RingBuffer.
12 13 14 15 16 17 18 19 20 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 12 def initialize(capacity) raise ArgumentError, "capacity must be positive" unless capacity.to_i.positive? @capacity = Integer(capacity) @buffer = Array.new(@capacity, 0.0) @write_index = 0 @size = 0 @mutex = Mutex.new end |
Instance Attribute Details
#capacity ⇒ Object (readonly)
Returns the value of attribute capacity.
9 10 11 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 9 def capacity @capacity end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
65 66 67 68 69 70 71 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 65 def clear @mutex.synchronize do @buffer.fill(0.0) @write_index = 0 @size = 0 end end |
#latest(count = nil) ⇒ Array<Float>
Returns newest values first-in-order.
45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 45 def latest(count = nil) @mutex.synchronize do return [] if @size.zero? requested = count ? Integer(count) : @size return [] if requested <= 0 length = [requested, @size].min start = (@write_index - length) % @capacity extract_range(start, length) end end |
#push(sample) ⇒ void
This method returns an undefined value.
39 40 41 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 39 def push(sample) write([sample]) end |
#size ⇒ Integer
60 61 62 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 60 def size @mutex.synchronize { @size } end |
#write(samples) ⇒ void
This method returns an undefined value.
24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/vizcore/audio/ring_buffer.rb', line 24 def write(samples) normalized = normalize_samples(samples) return if normalized.empty? @mutex.synchronize do normalized.each do |sample| @buffer[@write_index] = sample @write_index = (@write_index + 1) % @capacity @size += 1 if @size < @capacity end end end |