Class: Minicap::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/minicap/stream.rb

Constant Summary collapse

DEFAULT_BUFFER_SIZE =
1024 * 1024
DEFAULT_SLEEP_SECS =
0.001

Instance Method Summary collapse

Constructor Details

#initialize(host, port, options = {}) ⇒ Stream

Returns a new instance of Stream.



7
8
9
10
11
# File 'lib/minicap/stream.rb', line 7

def initialize(host, port, options={})
  @host = host
  @port = port
  @options = options
end

Instance Method Details

#eachObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/minicap/stream.rb', line 13

def each
  return enum_for(:each) unless block_given?

  buffer_size = @options[:buffer_size] || DEFAULT_BUFFER_SIZE
  sleep_secs = @options[:sleep_secs] || DEFAULT_SLEEP_SECS
  debug = @options[:debug]

  soc = nil
  begin
    soc = TCPSocket.open(@host, @port)

    buf = soc.recv(buffer_size).unpack('C*')
    fail 'unknown version' if buf[0] != 1
    header_size = buf[1]
    header = buf[0...header_size]
    data = buf[header_size..-1]

    in_frame = false
    n = 0
    loop do
      if !in_frame && data.size >= 4
        n = uint32le(data)
        in_frame = true
        STDERR.puts 'new frame with size %d' % n if debug
      end

      if in_frame && data.size >= 4 + n
        jpg_blob = data[4...4+n]
        yield jpg_blob
        data = data[4+n..-1]
        in_frame = false
      end

      sleep sleep_secs

      if in_frame
        fetch_size = [buffer_size, 4 + n - data.size].min
      else
        fetch_size = buffer_size
      end

      buf = soc.recv(fetch_size).unpack('C*')
      data += buf
    end
  ensure
    soc.close unless soc
  end
end