Class: DTAS::Player

Inherits:
Object
  • Object
show all
Includes:
ClientHandler, XS
Defined in:
lib/dtas/player.rb

Overview

the core of dtas-player(1)

Defined Under Namespace

Modules: ClientHandler

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClientHandler

#__bp_goto, #__bp_prev_next, #__bp_seek, #__buf_reset, #__current_decoded_samples, #__current_requeue, #__goto_offset_samples, #__offset_direction, #__offset_to_i, #__offset_to_samples, #__seek_offset_adj, #__sink_activate, #__sink_snapshot, #__sink_switch, #_dpc_tl_add, #_dpc_tl_clear, #_dpc_tl_consume, #_dpc_tl_current, #_dpc_tl_current_id, #_dpc_tl_get, #_dpc_tl_goto, #_dpc_tl_max, #_dpc_tl_next, #_dpc_tl_prev, #_dpc_tl_remove, #_dpc_tl_repeat, #_dpc_tl_shuffle, #_dpc_tl_swap, #_dpc_tl_tracks, #_tl_skip, #active_sinks, #adjust_numeric, #bytes_decoded, #current_expect_samples, #do_pause, #do_play, #do_play_pause, #dpc_cd, #dpc_cue, #dpc_current, #dpc_env, #dpc_format, #dpc_restart, #dpc_rg, #dpc_seek, #dpc_sink, #dpc_skip, #dpc_source, #dpc_state, #dpc_tl, #dpc_trim, #drop_sink, #out_samples, #play_pause_handler, #restart_pipeline, #seek_internal, #set_bool, #set_int, #set_uint, #state_file_dump_async

Methods included from ParseTime

#parse_time

Methods included from XS

#xs

Constructor Details

#initializePlayer

Returns a new instance of Player.



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
# File 'lib/dtas/player.rb', line 31

def initialize
  @tl = DTAS::Tracklist.new
  @state_file = nil
  @socket = nil
  @srv = nil
  @queue = [] # files for sources, or commands
  @paused = false
  @format = DTAS::Format.new
  @bypass = [] # %w(rate bits channels) (not worth Hash overhead)
  @bypass_next = nil # source_spec

  @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 = {}
  @trim = nil
  @source_map = {
    "sox" => (sox = DTAS::Source::Sox.new),
    "av" => DTAS::Source::Av.new,
    "ff" => DTAS::Source::Ff.new,
    "splitfx" => DTAS::Source::SplitFX.new(sox),
  }
  source_map_reload
end

Instance Attribute Details

#sinksObject (readonly)

Returns the value of attribute sinks.



29
30
31
# File 'lib/dtas/player.rb', line 29

def sinks
  @sinks
end

#socketObject

Returns the value of attribute socket.



28
29
30
# File 'lib/dtas/player.rb', line 28

def socket
  @socket
end

#state_fileObject

Returns the value of attribute state_file.



27
28
29
# File 'lib/dtas/player.rb', line 27

def state_file
  @state_file
end

Class Method Details

.load(hash) ⇒ Object



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
# File 'lib/dtas/player.rb', line 127

def self.load(hash)
  rv = new
  rv.instance_eval do
    if v = hash["tracklist"]
      @tl = DTAS::Tracklist.load(v)
    end
    @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 bypass trim).each do |k|
      v = hash[k] or next
      instance_variable_set("@#{k}", v)
    end
    if v = hash["source"]
      # compatibility with 0.0.0, which was sox-only
      # we'll drop this after 1.0.0, or when we support a source decoder
      # named "command" or "env" :P
      sox_cmd, sox_env = v["command"], v["env"]
      if sox_cmd || sox_env
        sox = @source_map["sox"]
        sox.command = sox_cmd if sox_cmd
        sox.env = sox_env if sox_env
      end

      # new style: name = "av" or "sox" or whatever else we may support
      @source_map.each do |name, src|
        src_hsh = v[name] or next
        src.load!(src_hsh)
      end
      source_map_reload
    end

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

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

Instance Method Details

#__current_drop(src = @current) ⇒ Object

only call on unrecoverable errors (or “skip”)



446
447
448
# File 'lib/dtas/player.rb', line 446

def __current_drop(src = @current)
  __buf_reset(src.dst) if src && src.pid
end

#__wall(msg) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/dtas/player.rb', line 68

def __wall(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

#_nextObject



263
264
265
# File 'lib/dtas/player.rb', line 263

def _next
  @queue.shift || @tl.advance_track
end

#_optimize_write_prepare(targets) ⇒ Object



293
294
295
296
297
298
# File 'lib/dtas/player.rb', line 293

def _optimize_write_prepare(targets)
  targets.each do |dst|
    dst.wait_writable_prepare
    @srv.wait_ctl(dst, :wait_writable)
  end
end

#bindObject



320
321
322
# File 'lib/dtas/player.rb', line 320

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

#broadcast_iter(buf, targets) ⇒ Object

returns a wait_ctl arg for self



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/dtas/player.rb', line 301

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, :hot_read) }
    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
    _optimize_write_prepare(targets)
    rv
  end
end

#bypass_match!(dst_fmt, src_fmt) ⇒ Object



499
500
501
502
503
504
# File 'lib/dtas/player.rb', line 499

def bypass_match!(dst_fmt, src_fmt)
  @bypass.each do |k|
    dst_fmt.__send__("#{k}=", src_fmt.__send__(k))
  end
  dst_fmt
end

#client_iter(io, msg) ⇒ Object

yielded from readable_iter



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/dtas/player.rb', line 201

def client_iter(io, msg)
  msg = Shellwords.split(msg)
  command = msg.shift
  case command
  when "enq"
    enq_handler(io, -msg[0])
  when "enq-cmd"
    enq_handler(io, { "command" => -msg[0]})
  when "pause", "play", "play_pause"
    play_pause_handler(io, command)
  when "pwd"
    io.emit(-Dir.pwd)
  else
    m = "dpc_#{command.tr('-', '_')}"
    __send__(m, io, msg) if respond_to?(m)
  end
end

#closeObject



493
494
495
496
497
# File 'lib/dtas/player.rb', line 493

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

#create_default_sinkObject

only used on new installations where no sink exists



325
326
327
328
329
330
331
# File 'lib/dtas/player.rb', line 325

def create_default_sink
  return unless @sinks.empty?
  s = DTAS::Sink.new
  s.name = "default"
  s.active = true
  @sinks[s.name] = s
end

#dpc_clear(io, msg) ⇒ Object



219
220
221
222
223
# File 'lib/dtas/player.rb', line 219

def dpc_clear(io, msg)
  @queue.clear
  wall('clear')
  io.emit('OK')
end

#dpc_enq_head(io, msg) ⇒ Object



190
191
192
193
194
195
196
197
198
# File 'lib/dtas/player.rb', line 190

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

#dpc_queue(io, msg) ⇒ Object



225
226
227
# File 'lib/dtas/player.rb', line 225

def dpc_queue(io, msg)
  'cat' == msg[0] and io.emit(@queue.to_yaml)
end

#dpc_watch(io, _) ⇒ Object



229
230
231
232
# File 'lib/dtas/player.rb', line 229

def dpc_watch(io, _)
  @watchers[io] = true
  io.emit('OK')
end

#drop_target(target) ⇒ Object



435
436
437
438
# File 'lib/dtas/player.rb', line 435

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

#enq_handler(io, msg) ⇒ Object



180
181
182
183
184
185
186
187
188
# File 'lib/dtas/player.rb', line 180

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

#event_loop_iterObject



234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/dtas/player.rb', line 234

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

#format_update!(fmt) ⇒ Object



424
425
426
427
428
# File 'lib/dtas/player.rb', line 424

def format_update!(fmt)
  ary = fmt.to_hash.inject(%w(format)) { |m,(k,v)| v ? m << "#{k}=#{v}" : m }
  @format = fmt
  __wall(ary.join(' ')) # do not escape '='
end

#need_to_queueObject



176
177
178
# File 'lib/dtas/player.rb', line 176

def need_to_queue
  @current || @queue[0] || @paused
end

#next_source(source_spec) ⇒ Object



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
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/dtas/player.rb', line 378

def next_source(source_spec)
  @current.respond_to?(:watch_end) and @current.watch_end(@srv)
  @current = nil
  if source_spec
    case source_spec
    when String
      pending = try_file(source_spec) or return
      msg = %W(file #{pending.infile})
    when Array
      pending = try_file(*source_spec) or return
      msg = %W(file #{pending.infile} #{pending.offset_samples}s)
    else
      pending = DTAS::Source::Cmd.new(source_spec["command"])
      msg = %W(command #{pending.command_string})
    end

    if ! @bypass.empty? && pending.respond_to?(:format)
      new_fmt = bypass_match!(@format.dup, pending.format)
      if new_fmt != @format
        @bypass_next = source_spec
        return if @sink_buf.inflight > 0
        stop_sinks # we may fail to start below
        format_update!(new_fmt)
      end
    end

    # restart sinks iff we were idle
    spawn_sinks(source_spec) or return

    dst = @sink_buf
    pending.dst_assoc(dst)
    pending.src_spawn(@format, @rg, out: dst.wr, in: DTAS.null)

    # watch and restart on modifications
    pending.respond_to?(:watch_begin) and
      @srv.wait_ctl(pending.watch_begin(method(:__current_requeue)),
                    :wait_readable)

    @current = pending
    @srv.wait_ctl(dst, :wait_readable)
    wall(msg)
  else
    player_idle
  end
end

#player_idleObject



430
431
432
433
# File 'lib/dtas/player.rb', line 430

def player_idle
  stop_sinks if @sink_buf.inflight == 0
  wall("idle")
end

#reap_iterObject



249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/dtas/player.rb', line 249

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 : _next)
    when DTAS::Sink # on unexpected sink death
      sink_death(obj, status)
    end
  end
  :wait_readable
end

#runObject

the main loop



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/dtas/player.rb', line 473

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 : _next)
  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
  stop_sinks
  trap(:CHLD, old_chld)
  sev.close if sev
  # for state file
end

#sink_death(sink, status) ⇒ Object



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
# File 'lib/dtas/player.rb', line 267

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) }
    do_pause unless @targets[0]
    return # sink stays dead if it died unexpectedly
  end

  return unless sink.active

  if (@current || @queue[0]) && !@paused
    # we get here if source/sinks are all killed in dpc_restart
    __sink_activate(sink)
    next_source(_next) unless @current
  end
end

#sink_iterObject

pull data from sink_buf into @targets, source feeds into sink_buf



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/dtas/player.rb', line 451

def sink_iter
  wait_iter = broadcast_iter(@sink_buf, @targets)
  do_pause 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
  bn = @bypass_next
  stop_sinks
  next_source(bn) if bn # are we restarting for bypass?
  :ignore
end

#source_map_reloadObject



60
61
62
# File 'lib/dtas/player.rb', line 60

def source_map_reload
  @sources = @source_map.values.sort_by(&:tryorder)
end

#spawn_sinks(source_spec) ⇒ Object

called when the player is leaving idle state



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/dtas/player.rb', line 334

def spawn_sinks(source_spec)
  @bypass_next = nil
  return true if @targets[0]
  @sinks.each_value do |sink|
    sink.active or next
    next if sink.pid
    @targets.concat(sink.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

#stop_sinksObject



440
441
442
443
# File 'lib/dtas/player.rb', line 440

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

#to_hshObject

used for state file



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
# File 'lib/dtas/player.rb', line 85

def to_hsh
  rv = {}
  rv["socket"] = @socket
  rv["paused"] = @paused if @paused
  rv["trim"] = @trim if @trim
  src_map = rv["source"] = {}
  @source_map.each do |name, src|
    src_hsh = src.to_state_hash
    src_map[name] = src_hsh unless src_hsh.empty?
  end

  # Arrays
  rv["queue"] = @queue
  rv["bypass"] = @bypass.sort!

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

  rv["tracklist"] = @tl.to_hsh

  # 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

#try_file(file, offset = nil) ⇒ Object



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
# File 'lib/dtas/player.rb', line 352

def try_file(file, offset = nil)
  @sources.each do |src|
    rv = src.try(file, offset, @trim) and return rv
  end

  # keep going down the list until we find something
  while source_spec = @queue.shift
    path, off = source_spec
    @sources.each do |src|
      rv = src.try(path, off, @trim) and return rv
    end
  end

  # don't get stuck in an infinite loop if @tl.repeat==true and we can't
  # decode anything (FS errors, sox uninstalled, etc...)
  while path_off = @tl.advance_track(false)
    path, off = path_off
    @sources.each do |src|
      rv = src.try(path, off, @trim) and return rv
    end
  end

  player_idle
  nil
end

#wall(msg) ⇒ Object



64
65
66
# File 'lib/dtas/player.rb', line 64

def wall(msg)
  __wall(xs(msg))
end