about summary refs log tree commit homepage
path: root/lib/dtas/player.rb
blob: 99c7400d2c3cd491c16d7e4c38ac2e0f356222a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# -*- encoding: binary -*-
# Copyright (C) 2013, Eric Wong <normalperson@yhbt.net>
# License: GPLv3 or later (https://www.gnu.org/licenses/gpl-3.0.txt)
require 'yaml'
require 'shellwords'
require_relative '../dtas'
require_relative 'source'
require_relative 'source/sox'
require_relative 'source/av'
require_relative 'source/cmd'
require_relative 'sink'
require_relative 'unix_server'
require_relative 'buffer'
require_relative 'sigevent'
require_relative 'rg_state'
require_relative 'state_file'

class DTAS::Player # :nodoc:
  require_relative 'player/client_handler'
  include DTAS::Player::ClientHandler
  attr_accessor :state_file
  attr_accessor :socket
  attr_reader :sinks

  def initialize
    @state_file = nil
    @socket = nil
    @srv = nil
    @queue = [] # sources
    @paused = false
    @format = DTAS::Format.new
    @srccmd = nil
    @srcenv = {}

    @sinks = {} # { user-defined name => sink }
    @targets = [] # order matters
    @rg = DTAS::RGState.new

    # sits in between shared effects (if any) and sinks
    @sink_buf = DTAS::Buffer.new
    @current = nil
    @watchers = {}
  end

  def echo(msg)
    msg = Shellwords.join(msg) if Array === msg
    @watchers.delete_if do |io, _|
      if io.closed?
        true
      else
        case io.emit(msg)
        when :wait_readable, :wait_writable
          false
        else
          true
        end
      end
    end
    $stdout.write(msg << "\n")
  end

  def to_hsh
    rv = {}
    rv["socket"] = @socket
    rv["paused"] = @paused if @paused
    src = rv["source"] = {}
    src["command"] = @srccmd if @srccmd
    src["env"] = @srcenv if @srcenv.size > 0

    # Arrays
    rv["queue"] = @queue

    %w(rg sink_buf format).each do |k|
      rv[k] = instance_variable_get("@#{k}").to_hsh
    end

    # no empty hashes or arrays
    rv.delete_if do |k,v|
      case v
      when Hash, Array
        v.empty?
      else
        false
      end
    end

    unless @sinks.empty?
      sinks = rv["sinks"] = []
      # sort sinks by name for human viewability
      @sinks.keys.sort.each do |name|
        sinks << @sinks[name].to_hsh
      end
    end

    rv
  end

  def self.load(hash)
    rv = new
    rv.instance_eval do
      @rg = DTAS::RGState.load(hash["rg"])
      if v = hash["sink_buf"]
        v = v["buffer_size"]
        @sink_buf.buffer_size = v
      end
      %w(socket queue paused).each do |k|
        v = hash[k] or next
        instance_variable_set("@#{k}", v)
      end
      if v = hash["source"]
        @srccmd = v["command"]
        e = v["env"] and @srcenv = e
      end

      if v = hash["format"]
        @format = DTAS::Format.load(v)
      end

      if sinks = hash["sinks"]
        sinks.each do |sink_hsh|
          sink = DTAS::Sink.load(sink_hsh)
          @sinks[sink.name] = sink
        end
      end
    end
    rv
  end

  def enq_handler(io, msg)
    # check @queue[0] in case we have no sinks
    if @current || @queue[0] || @paused
      @queue << msg
    else
      next_source(msg)
    end
    io.emit("OK")
  end

  def do_enq_head(io, msg)
    # check @queue[0] in case we have no sinks
    if @current || @queue[0] || @paused
      @queue.unshift(msg)
    else
      next_source(msg)
    end
    io.emit("OK")
  end

  # yielded from readable_iter
  def client_iter(io, msg)
    msg = Shellwords.split(msg)
    command = msg.shift
    case command
    when "enq"
      enq_handler(io, msg[0])
    when "enq-head"
      do_enq_head(io, msg)
    when "enq-cmd"
      enq_handler(io, { "command" => msg[0]})
    when "pause", "play", "play_pause"
      play_pause_handler(io, command)
    when "seek"
      do_seek(io, msg[0])
    when "clear"
      @queue.clear
      echo("clear")
      io.emit("OK")
    when "rg"
      rg_handler(io, msg)
    when "skip"
      skip_handler(io, msg)
    when "sink"
      sink_handler(io, msg)
    when "current"
      current_handler(io, msg)
    when "watch"
      @watchers[io] = true
      io.emit("OK")
    when "format"
      format_handler(io, msg)
    when "env"
      env_handler(io, msg)
    when "restart"
      restart_pipeline
      io.emit("OK")
    when "source"
      source_handler(io, msg)
    when "cd"
      chdir_handler(io, msg)
    when "pwd"
      io.emit(Dir.pwd)
    end
  end

  def event_loop_iter
    @srv.run_once do |io, msg| # readability handler, request/response
      case io
      when @sink_buf
        sink_iter
      when DTAS::UNIXAccepted
        client_iter(io, msg)
      when DTAS::Sigevent # signal received
        reap_iter
      else
        raise "BUG: unknown event: #{io.class} #{io.inspect} #{msg.inspect}"
      end
    end
  end

  def reap_iter
    DTAS::Process.reaper do |status, obj|
      warn [ :reap, obj, status ].inspect if $DEBUG
      obj.on_death(status) if obj.respond_to?(:on_death)
      case obj
      when @current
        next_source(@paused ? nil : @queue.shift)
      when DTAS::Sink # on unexpected sink death
        sink_death(obj, status)
      end
    end
    :wait_readable
  end

  def sink_death(sink, status)
    deleted = []
    @targets.delete_if do |t|
      if t.sink == sink
        deleted << t
      else
        false
      end
    end

    if deleted[0]
      warn("#{sink.name} died unexpectedly: #{status.inspect}")
      deleted.each { |t| drop_target(t) }
      __current_drop unless @targets[0]
    end

    return unless sink.active

    if @queue[0] && !@paused
      # we get here if source/sinks are all killed in restart_pipeline
      __sink_activate(sink)
      next_source(@queue.shift)
    end
  ensure
    sink.respawn = false
  end

  # returns a wait_ctl arg for self
  def broadcast_iter(buf, targets)
    case rv = buf.broadcast(targets)
    when Array # array of blocked sinks
      # have sinks wake up the this buffer when they're writable
      trade_ctl = proc { @srv.wait_ctl(buf, :wait_readable) }
      rv.each do |dst|
        dst.on_writable = trade_ctl
        @srv.wait_ctl(dst, :wait_writable)
      end

      # this @sink_buf hibernates until trade_ctl is called
      # via DTAS::Sink#writable_iter
      :ignore
    else # :wait_readable or nil
      rv
    end
  end

  def bind
    @srv = DTAS::UNIXServer.new(@socket)
  end

  # only used on new installations where no sink exists
  def create_default_sink
    return unless @sinks.empty?
    s = DTAS::Sink.new
    s.name = "default"
    s.active = true
    @sinks[s.name] = s
  end

  # called when the player is leaving idle state
  def spawn_sinks(source_spec)
    return true if @targets[0]
    @sinks.each_value do |sink|
      sink.active or next
      next if sink.pid
      @targets.concat(sink.spawn(@format))
    end
    if @targets[0]
      @targets.sort_by! { |t| t.sink.prio }
      true
    else
      # fail, no active sink
      @queue.unshift(source_spec)
      false
    end
  end

  def try_file(*args)
    [ DTAS::Source::Sox, DTAS::Source::Av ].each do |klass|
      rv = klass.try(*args) and return rv
    end

    # keep going down the list until we find something
    while source_spec = @queue.shift
      [ DTAS::Source::Sox, DTAS::Source::Av ].each do |klass|
        rv = klass.try(*source_spec) and return rv
      end
    end
    echo "idle"
    nil
  end

  def next_source(source_spec)
    @current = nil
    if source_spec
      # restart sinks iff we were idle
      spawn_sinks(source_spec) or return

      case source_spec
      when String
        @current = try_file(source_spec)
        echo(%W(file #{@current.infile}))
      when Array
        @current = try_file(*source_spec)
        echo(%W(file #{@current.infile} #{@current.offset_samples}s))
      else
        @current = DTAS::Source::Cmd.new(source_spec["command"])
        echo(%W(command #{@current.command_string}))
      end

      # FIXME, support Av overrides
      if DTAS::Source::Sox === @current
        @current.command = @srccmd if @srccmd
        @current.env = @srcenv.dup unless @srcenv.empty?
      end

      dst = @sink_buf
      @current.dst_assoc(dst)
      @current.spawn(@format, @rg, out: dst.wr, in: "/dev/null")
      @srv.wait_ctl(dst, :wait_readable)
    else
      stop_sinks if @sink_buf.inflight == 0
      echo "idle"
    end
  end

  def drop_target(target)
    @srv.wait_ctl(target, :delete)
    target.close
  end

  def stop_sinks
    @targets.each { |t| drop_target(t) }.clear
  end

  # only call on unrecoverable errors (or "skip")
  def __current_drop(src = @current)
    __buf_reset(src.dst) if src && src.pid
  end

  # pull data from sink_buf into @targets, source feeds into sink_buf
  def sink_iter
    wait_iter = broadcast_iter(@sink_buf, @targets)
    __current_drop if nil == wait_iter # sink error, stop source
    return wait_iter if @current

    # no source left to feed sink_buf, drain the remaining data
    sink_bytes = @sink_buf.inflight
    if sink_bytes > 0
      return wait_iter if @targets[0] # play what is leftover

      # discard the buffer if no sinks
      @sink_buf.discard(sink_bytes)
    end

    # nothing left inflight, stop the sinks until we have a source
    stop_sinks
    :ignore
  end

  # the main loop
  def run
    sev = DTAS::Sigevent.new
    @srv.wait_ctl(sev, :wait_readable)
    old_chld = trap(:CHLD) { sev.signal }
    create_default_sink
    next_source(@paused ? nil : @queue.shift)
    begin
      event_loop_iter
    rescue => e # just in case...
      warn "E: #{e.message} (#{e.class})"
      e.backtrace.each { |l| warn l }
    end while true
  ensure
    __current_requeue
    trap(:CHLD, old_chld)
    sev.close if sev
    # for state file
  end

  def close
    @srv = @srv.close if @srv
    @sink_buf.close!
    @state_file.dump(self, true) if @state_file
  end
end