Module: DTAS::Player::ClientHandler

Includes:
DTAS::ParseTime, XS
Included in:
DTAS::Player
Defined in:
lib/dtas/player/client_handler.rb

Overview

client protocol handling for -player

Instance Method Summary collapse

Methods included from DTAS::ParseTime

#parse_time

Methods included from XS

#xs

Instance Method Details

#__bp_prev_next(io, msg, cur, bp) ⇒ Object



718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# File 'lib/dtas/player/client_handler.rb', line 718

def __bp_prev_next(io, msg, cur, bp)
  case type = msg[1]
  when nil, "track"
    bp.keep_if(&:track?)
  when "pregap"
    bp.keep_if(&:pregap?)
  when "subindex" # any subindex
    bp.keep_if(&:subindex?)
  when /\A\d+\z/ # exact subindex match
    si = type.to_i
    bp.keep_if { |ci| ci.index == si }
  when "any" # anything goes
  else
    return io.emit("INVALID TYPE")
  end
  fmt = cur.format
  case msg[0]
  when "next"
    ds = __current_decoded_samples
    bp.each do |ci|
      next if ci.offset_samples(fmt) < ds
      seek_internal(cur, ci.offset)
      return io.emit("OK")
    end
    # go to the next (real) track if not found
    __current_drop
  when "prev"
    os = cur.offset_samples # where we currently started
    bp.reverse_each do |ci|
      next if ci.offset_samples(fmt) >= os
      seek_internal(cur, ci.offset)
      return io.emit("OK")
    end
    # offset may be nil/zero if we couldn't find a previous breakpoint
    seek_internal(cur, '0')
  end
  io.emit("OK")
end

#__buf_reset(buf) ⇒ Object

buf is always @sink_buf for now



323
324
325
326
327
# File 'lib/dtas/player/client_handler.rb', line 323

def __buf_reset(buf) # buf is always @sink_buf for now
  @srv.wait_ctl(buf, :ignore)
  buf.buf_reset
  @srv.wait_ctl(buf, :wait_readable)
end

#__current_decoded_samplesObject



201
202
203
204
205
206
# File 'lib/dtas/player/client_handler.rb', line 201

def __current_decoded_samples
  initial = @current.offset_samples
  decoded = @format.bytes_to_samples(bytes_decoded)
  decoded = out_samples(decoded, @format, @current.format)
  initial + decoded
end

#__current_requeueObject



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/dtas/player/client_handler.rb', line 208

def __current_requeue
  return unless @current

  # no need to requeue if we're already due to die
  return if @current.requeued
  @current.requeued = true

  dst = @current.dst
  # prepare to seek to the desired point based on the number of bytes which
  # passed through dst buffer we want the offset for the @current file,
  # which may have a different rate than our internal @format
  if @current.respond_to?(:infile)
    # this offset in the @current.format (not player @format)
    @queue.unshift([ @current.infile, "#{__current_decoded_samples}s" ])
  else
    # DTAS::Source::Cmd (hash), just rerun it
    @queue.unshift(@current.to_hsh)
  end
  # We also want to hard drop the buffer so we do not get repeated audio.
  __buf_reset(dst)
end

#__seek_offset_adj(dir, offset) ⇒ Object

returns seek offset as an Integer in sample count



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

def __seek_offset_adj(dir, offset)
  if offset.sub!(/s\z/, '')
    offset = offset.to_i
  else # time
    offset = @current.format.hhmmss_to_samples(offset)
  end
  n = __current_decoded_samples + (dir * offset)
  n = 0 if n < 0
  "#{n}s"
end

#__sink_activate(sink) ⇒ Object



75
76
77
78
79
# File 'lib/dtas/player/client_handler.rb', line 75

def __sink_activate(sink)
  return if sink.pid
  @targets.concat(sink.sink_spawn(@format))
  @targets.sort_by! { |t| t.sink.prio }
end

#__sink_snapshot(sink) ⇒ Object



116
117
118
# File 'lib/dtas/player/client_handler.rb', line 116

def __sink_snapshot(sink)
  [ sink.command, sink.env, sink.pipe_size ].inspect
end

#__sink_switch(sink) ⇒ Object

called to activate/deactivate a sink



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/dtas/player/client_handler.rb', line 93

def __sink_switch(sink)
  if sink.active
    if @current
      # maybe it's still alive for now, but it's just being killed
      # do not reactivate it until we've reaped it
      if sink.pid
        drop_sink(sink)

        # we must restart @current if there's a moment we're target-less:
        __current_requeue unless @targets[0]
      else
        __sink_activate(sink)
      end
    end
  else
    drop_sink(sink)
  end
  # if we change any sinks, make sure the event loop watches it for
  # readability again, since we new sinks should be writable, and
  # we've stopped waiting on killed sinks
  @srv.wait_ctl(@sink_buf, :wait_readable)
end

#_dpc_tl_add(io, msg) ⇒ Object



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/dtas/player/client_handler.rb', line 580

def _dpc_tl_add(io, msg)
  path = msg.shift
  after_track_id = msg.shift
  after_track_id = after_track_id.to_i if after_track_id
  case set_as_current = msg.shift
  when 'true' then set_as_current = true
  when 'false', nil then set_as_current = false
  else
    return io.emit('ERR tl add PATH [after_track_id] [true|false]')
  end
  begin
    track_id = @tl.add_track(path, after_track_id, set_as_current)
    return io.emit('ERR FULL') unless track_id
  rescue ArgumentError => e
    return io.emit("ERR #{e.message}")
  end

  _tl_skip if set_as_current # if @current is playing, it will restart soon

  # start playing if we're currently idle
  next_source(_next) unless need_to_queue
  io.emit(track_id.to_s)
end

#_dpc_tl_clear(io, msg) ⇒ Object



704
705
706
707
708
# File 'lib/dtas/player/client_handler.rb', line 704

def _dpc_tl_clear(io, msg)
  @tl.clear
  _tl_skip
  io.emit('OK')
end

#_dpc_tl_current(io, msg) ⇒ Object



683
684
685
686
# File 'lib/dtas/player/client_handler.rb', line 683

def _dpc_tl_current(io, msg)
  track = @tl.cur_track
  io.emit(track ? track.to_path : 'NONE')
end

#_dpc_tl_current_id(io, msg) ⇒ Object



688
689
690
691
# File 'lib/dtas/player/client_handler.rb', line 688

def _dpc_tl_current_id(io, msg)
  track = @tl.cur_track
  io.emit(track ? track.track_id.to_s : 'NONE')
end

#_dpc_tl_get(io, msg) ⇒ Object



660
661
662
663
664
# File 'lib/dtas/player/client_handler.rb', line 660

def _dpc_tl_get(io, msg)
  res = @tl.get_tracks(msg.map!(&:to_i))
  res.map! { |tid, file| "#{tid}=#{file ? Shellwords.escape(file) : ''}" }
  io.emit("#{res.size} #{res.join(' ')}")
end

#_dpc_tl_goto(io, msg) ⇒ Object



671
672
673
674
675
676
677
678
679
680
681
# File 'lib/dtas/player/client_handler.rb', line 671

def _dpc_tl_goto(io, msg)
  track_id = msg.shift or return io.emit('ERR track_id not specified')
  offset = msg.shift # may be nil
  if @tl.go_to(track_id.to_i, offset)
    _tl_skip
    next_source(_next) unless need_to_queue
    io.emit('OK')
  else
    io.emit('MISSING')
  end
end

#_dpc_tl_max(io, msg) ⇒ Object



633
634
635
636
637
638
639
640
641
642
# File 'lib/dtas/player/client_handler.rb', line 633

def _dpc_tl_max(io, msg)
  prev = @tl.max
  case msg.shift
  when nil
  when %r{\A(\d[\d_]*)\z} then @tl.max = $1.to_i
  else
    return io.emit('ERR tl max must a non-negative integer')
  end
  io.emit("tl max #{prev}")
end

#_dpc_tl_next(io, msg) ⇒ Object



693
694
695
696
# File 'lib/dtas/player/client_handler.rb', line 693

def _dpc_tl_next(io, msg)
  _tl_skip
  io.emit('OK')
end

#_dpc_tl_prev(io, msg) ⇒ Object



698
699
700
701
702
# File 'lib/dtas/player/client_handler.rb', line 698

def _dpc_tl_prev(io, msg)
  @tl.previous!
  _tl_skip
  io.emit('OK')
end

#_dpc_tl_remove(io, msg) ⇒ Object



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/dtas/player/client_handler.rb', line 644

def _dpc_tl_remove(io, msg)
  track_id = msg.shift or return io.emit('ERR track_id not specified')
  track_id = track_id.to_i
  path = @tl.remove_track(track_id) or return io.emit('MISSING')
  rm = path.object_id

  # skip if we're removing the currently playing track
  if @current && @current.respond_to?(:infile) &&
     @current.infile.object_id == rm
    _tl_skip
  end
  # drop it from the queue, too, in case it just got requeued or paused
  @queue.delete_if { |t| Array === t && t[0].object_id == rm }
  io.emit(path)
end

#_dpc_tl_repeat(io, msg) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/dtas/player/client_handler.rb', line 604

def _dpc_tl_repeat(io, msg)
  prev = @tl.repeat.to_s
  do_wall = true
  case msg.shift
  when 'true' then @tl.repeat = true
  when 'false' then @tl.repeat = false
  when '1' then @tl.repeat = 1
  when nil
    do_wall = false
  end
  __wall("tl repeat #{@tl.repeat}") if do_wall
  io.emit("tl repeat #{prev}")
end

#_dpc_tl_shuffle(io, msg) ⇒ Object



618
619
620
621
622
623
624
625
626
627
628
629
630
631
# File 'lib/dtas/player/client_handler.rb', line 618

def _dpc_tl_shuffle(io, msg)
  prev = (!!@tl.shuffle).to_s
  v = msg.shift
  case v
  when 'debug' then return io.emit(@tl.shuffle.to_yaml) # TODO: remove
  when nil
  else
    set_bool(io, 'tl shuffle', v) do |b|
      @tl.shuffle = b
      __wall("tl shuffle #{b}")
    end
  end
  io.emit("tl shuffle #{prev}")
end

#_dpc_tl_swap(io, msg) ⇒ Object



710
711
712
713
714
715
716
# File 'lib/dtas/player/client_handler.rb', line 710

def _dpc_tl_swap(io, msg)
  usage = 'ERR usage: "tl swap TRACK_ID_A TRACK_ID_B"'
  a_id = msg.shift or return io.emit(usage)
  b_id = msg.shift or return io.emit(usage)
  @tl.swap(a_id.to_i, b_id.to_i) or return io.emit('MISSING')
  io.emit('OK')
end

#_dpc_tl_tracks(io, msg) ⇒ Object



666
667
668
669
# File 'lib/dtas/player/client_handler.rb', line 666

def _dpc_tl_tracks(io, msg)
  tracks = @tl.tracks
  io.emit("#{tracks.size} #{tracks.map!(&:to_s).join(' ')}")
end

#_tl_skipObject



569
570
571
572
# File 'lib/dtas/player/client_handler.rb', line 569

def _tl_skip
  @queue.clear
  __current_drop
end

#active_sinksObject



273
274
275
276
277
# File 'lib/dtas/player/client_handler.rb', line 273

def active_sinks
  sinks = @targets.map(&:sink)
  sinks.uniq!
  sinks
end

#adjust_numeric(io, obj, k, v) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dtas/player/client_handler.rb', line 23

def adjust_numeric(io, obj, k, v)
  negate = !!v.sub!(/\A-/, '')
  case v
  when %r{\A\+?\d*\.\d+\z}
    num = v.to_f
  when %r{\A\+?\d+\z}
    num = v.to_i
  else
    return io.emit("ERR #{k}=#{v} must be a float")
  end
  num = -num if negate

  if k.sub!(/\+\z/, '') # increment existing
    num += obj.__send__(k)
  elsif k.sub!(/-\z/, '') # decrement existing
    num = obj.__send__(k) - num
  # else # normal assignment
  end
  obj.__send__("#{k}=", num)
  true
end

#bytes_decoded(src = @current) ⇒ Object



184
185
186
187
# File 'lib/dtas/player/client_handler.rb', line 184

def bytes_decoded(src = @current)
  bytes = src.dst.bytes_xfer - src.dst_zero_byte
  bytes = bytes < 0 ? 0 : bytes # maybe negative in case of sink errors
end

#current_expect_samples(in_samples) ⇒ Object

returns the number of samples we expect from the source this takes into account sample rate differences between the source and internal player format



240
241
242
# File 'lib/dtas/player/client_handler.rb', line 240

def current_expect_samples(in_samples) # @current.samples
  out_samples(in_samples, @current.format, @format)
end

#do_pauseObject



346
347
348
349
350
351
# File 'lib/dtas/player/client_handler.rb', line 346

def do_pause
  return if @paused
  wall("pause")
  @paused = true
  __current_requeue
end

#do_playObject



353
354
355
356
357
358
359
360
361
362
363
# File 'lib/dtas/player/client_handler.rb', line 353

def do_play
  # no wall, next_source will wall on new track
  @paused = false
  return if @current
  n = _next
  unless n
    @tl.reset
    n = _next
  end
  next_source(n)
end

#do_play_pauseObject



365
366
367
# File 'lib/dtas/player/client_handler.rb', line 365

def do_play_pause
  @paused ? do_play : do_pause
end

#dpc_cd(io, msg) ⇒ Object



523
524
525
526
527
528
529
530
531
532
# File 'lib/dtas/player/client_handler.rb', line 523

def dpc_cd(io, msg)
  msg.size == 1 or return io.emit("ERR usage: cd DIRNAME")
  begin
    Dir.chdir(msg[0])
  rescue => e
    return io.emit("ERR chdir: #{e.message}")
  end
  # wall(%W(cd msg[0])) # should we broadcast this?
  io.emit("OK")
end

#dpc_cue(io, msg) ⇒ Object



757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/dtas/player/client_handler.rb', line 757

def dpc_cue(io, msg)
  cur = @current
  if cur.respond_to?(:cuebreakpoints)
    bp = cur.cuebreakpoints
    case msg[0]
    when nil
      tmp = { "infile" => cur.infile, "cue" => bp.map(&:to_hash) }
      io.emit(tmp.to_yaml)
    when "next", "prev"
      return __bp_prev_next(io, msg, cur, bp)
    when "goto"
      index = msg[1] or return io.emit("NOINDEX")
      ci = bp[index.to_i] or return io.emit("BADINDEX")
      seek_internal(cur, ci.offset)
      return io.emit("OK")
    end
  else
    io.emit("NOCUE")
  end
end

#dpc_current(io, msg) ⇒ Object

show current info about what’s playing returns non-blocking iterator retval



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

def dpc_current(io, msg)
  tmp = {}
  if @current
    tmp["current"] = s = @current.to_hsh
    s["spawn_at"] = @current.spawn_at
    s["pid"] = @current.pid

    # this offset and samples in the player @format (not @current.format)
    decoded = @format.bytes_to_samples(bytes_decoded)
    if @current.respond_to?(:infile)
      initial = tmp["current_initial"] = @current.offset_samples
      initial = out_samples(initial, @current.format, @format)
      tmp["current_expect"] = current_expect_samples(s["samples"])
      s["format"] = @current.format.to_hash.delete_if { |_,v| v.nil? }
    else
      initial = 0
      tmp["current_expect"] = nil
      s["format"] = @format.to_hash.delete_if { |_,v| v.nil? }
    end
    tmp["current_offset"] = initial + decoded
  end
  tmp["current_inflight"] = @sink_buf.inflight
  tmp["format"] = @format.to_hash.delete_if { |_,v| v.nil? }
  tmp["bypass"] = @bypass.sort!
  t = @trim and tmp['trim'] = t.join(' ')
  if tmp['paused'] = @paused
    first = @queue[0] and tmp['current_paused'] = first
  end
  rg = @rg.to_hsh
  tmp["rg"] = rg unless rg.empty?
  if @targets[0]
    sinks = active_sinks
    tmp["sinks"] = sinks.map! do |sink|
      h = sink.to_hsh
      h["pid"] = sink.pid
      h
    end
  end
  tmp['tracklist'] = @tl.to_hsh(false)
  io.emit(tmp.to_yaml)
end

#dpc_env(io, msg) ⇒ Object



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/dtas/player/client_handler.rb', line 457

def dpc_env(io, msg)
  if msg.empty?
    # this may fail for large envs due to SEQPACKET size restrictions
    # do we care?
    env = ENV.map do |k,v|
      "#{Shellwords.escape(k)}=#{Shellwords.escape(v)}"
    end.join(' ')
    return io.emit(env)
  end
  msg.each do |kv|
    case kv
    when %r{\A([^=]+)=(.*)\z}
      ENV[$1] = $2
    when %r{\A([^=]+)#}
      ENV.delete($1)
    else
      return io.emit("ERR bad env")
    end
  end
  io.emit("OK")
end

#dpc_format(io, msg) ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/dtas/player/client_handler.rb', line 422

def dpc_format(io, msg)
  new_fmt = @format.dup
  msg.each do |kv|
    k, v = kv.split(/=/, 2)
    case k
    when "type"
      new_fmt.valid_type?(v) or return io.emit("ERR invalid file type")
      new_fmt.type = v
    when "channels", "bits", "rate"
      case v
      when "bypass"
        @bypass << k unless @bypass.include?(k)
      else
        rv = set_uint(io, kv, v, false) { |u| new_fmt.__send__("#{k}=", u) }
        rv == true or return rv
        @bypass.delete(k)
      end
    when "endian"
      new_fmt.valid_endian?(v) or return io.emit("ERR invalid endian")
      new_fmt.endian = v
    end
  end

  bypass_match!(new_fmt, @current.format) if @current

  if new_fmt != @format
    restart_pipeline # calls __current_requeue

    # we must assign this after __current_requeue since __current_requeue
    # relies on the old @format for calculation
    format_update!(new_fmt)
  end
  io.emit("OK")
end

#dpc_restart(io, _) ⇒ Object



417
418
419
420
# File 'lib/dtas/player/client_handler.rb', line 417

def dpc_restart(io, _)
  restart_pipeline
  io.emit('OK')
end

#dpc_rg(io, msg) ⇒ Object



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

def dpc_rg(io, msg)
  return io.emit(@rg.to_hsh.to_yaml) if msg.empty?
  before = @rg.to_hsh
  msg.each do |kv|
    k, v = kv.split('=', 2)
    case k
    when "mode"
      case v
      when "off"
        @rg.mode = nil
      else
        DTAS::RGState::RG_MODE.include?(v) or
          return io.emit("ERR rg mode invalid")
        @rg.mode = v
      end
    when "fallback_track"
      rv = set_bool(io, kv, v) { |b| @rg.fallback_track = b }
      rv == true or return rv
    when %r{(?:gain_threshold|norm_threshold|
            preamp|norm_level|fallback_gain|volume)[+-]?\z}x
      rv = adjust_numeric(io, @rg, k, v)
      rv == true or return rv
    end
  end
  after = @rg.to_hsh
  __current_requeue if before != after
  io.emit("OK")
end

#dpc_seek(io, msg) ⇒ Object



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

def dpc_seek(io, msg)
  offset = msg[0]
  if @current
    if @current.respond_to?(:infile)
      begin
        if offset.sub!(/\A\+/, '')
          offset = __seek_offset_adj(1, offset)
        elsif offset.sub!(/\A-/, '')
          offset = __seek_offset_adj(-1, offset)
        # else: pass to sox directly
        end
      rescue ArgumentError
        return io.emit("ERR bad time format")
      end
      seek_internal(@current, offset)
    else
      return io.emit("ERR unseekable")
    end
  elsif @paused
    case file = @queue[0]
    when String
      @queue[0] = [ file, offset ]
    when Array
      file[1] = offset
    else
      return io.emit("ERR unseekable")
    end
  # unpaused case... what do we do?
  end
  io.emit("OK")
end

#dpc_sink(io, msg) ⇒ Object

returns a wait_ctl arg



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

def dpc_sink(io, msg)
  name = msg[1]
  case msg[0]
  when "ls"
    io.emit(xs(@sinks.keys.sort))
  when "rm"
    sink = @sinks.delete(name) or return io.emit("ERR #{name} not found")
    drop_sink(sink)
    io.emit("OK")
  when "ed"
    sink = @sinks[name] || (new_sink = DTAS::Sink.new)

    # allow things that look like audio device names ("hw:1,0" , "/dev/dsp")
    # or variable names.
    sink.valid_name?(name) or return io.emit("ERR sink name invalid")

    sink.name = name
    active_before = sink.active
    before = __sink_snapshot(sink)

    # multiple changes may be made at once
    msg[2..-1].each do |kv|
      k, v = kv.split('=', 2)
      case k
      when %r{\Aenv\.([^=]+)\z}
        sink.env[$1] = v
      when %r{\Aenv#([^=]+)\z}
        v == nil or return io.emit("ERR unset env has no value")
        sink.env.delete($1)
      when "prio"
        rv = set_int(io, kv, v, false) { |i| sink.prio = i }
        rv == true or return rv
        @targets.sort_by! { |t| t.sink.prio } if sink.active
      when "nonblock", "active"
        rv = set_bool(io, kv, v) { |b| sink.__send__("#{k}=", b) }
        rv == true or return rv
      when "pipe_size"
        rv = set_uint(io, kv, v, true) { |u| sink.pipe_size = u }
        rv == true or return rv
      when "command" # nothing to validate, this could be "rm -rf /" :>
        sink.command = v.empty? ? DTAS::Sink::SINK_DEFAULTS["command"] : v
      end
    end

    @sinks[name] = new_sink if new_sink # no errors? it's a new sink!
    after = __sink_snapshot(sink)

    # start or stop a sink if its active= flag changed.  Additionally,
    # account for a crashed-but-marked-active sink.  The user may have
    # fixed the command to not crash it.
    if (active_before != sink.active) ||
       (sink.active && (!sink.pid || before != after))
      __sink_switch(sink)
    end
    io.emit("OK")
  when "cat"
    sink = @sinks[name] or return io.emit("ERR #{name} not found")
    io.emit(sink.to_hash.to_yaml)
  else
    io.emit("ERR unknown sink op #{msg[0]}")
  end
end

#dpc_skip(io, msg) ⇒ Object



329
330
331
332
333
# File 'lib/dtas/player/client_handler.rb', line 329

def dpc_skip(io, msg)
  __current_drop
  wall("skip")
  io.emit("OK")
end

#dpc_source(io, msg) ⇒ Object



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/dtas/player/client_handler.rb', line 479

def dpc_source(io, msg)
  map = @source_map
  op = msg.shift
  case op
  when "restart"
    __current_requeue
    return io.emit("OK")
  when "ls"
    s = map.keys.sort { |a,b| map[a].tryorder <=> map[b].tryorder }
    return io.emit(s.join(' '))
  end

  name = msg.shift
  src = map[name] or return io.emit("ERR non-existent source name")
  case op
  when "cat"
    io.emit(src.to_source_cat.to_yaml)
  when "ed"
    before = src.to_state_hash.inspect
    sd = src.source_defaults
    msg.each do |kv|
      k, v = kv.split(/=/, 2)
      case k
      when "command"
        src.command = v.empty? ? sd[k] : v
      when %r{\Aenv\.([^=]+)\z}
        src.env[$1] = v
      when %r{\Aenv#([^=]+)\z}
        v == nil or return io.emit("ERR unset env has no value")
        src.env.delete($1)
      when "tryorder"
        rv = set_int(io, kv, v, true) { |i| src.tryorder = i || sd[k] }
        rv == true or return rv
        source_map_reload
      end
    end
    after = src.to_state_hash.inspect
    __current_requeue if before != after && @current.class == src.class
    io.emit("OK")
  else
    io.emit("ERR unknown source op")
  end
end

#dpc_state(io, msg) ⇒ Object



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/dtas/player/client_handler.rb', line 552

def dpc_state(io, msg)
  case msg.shift
  when 'dump'
    dest = msg.shift
    if dest
      sf = DTAS::StateFile.new(dest, false)
    elsif @state_file
      sf = @state_file
      dest = sf.path
    else
      return io.emit("ERR no state file configured")
    end
    state_file_dump_async(io, sf)
    :ignore
  end
end

#dpc_tl(io, msg) ⇒ Object



574
575
576
577
578
# File 'lib/dtas/player/client_handler.rb', line 574

def dpc_tl(io, msg)
  sub = msg.shift
  m = "_dpc_tl_#{sub.tr('-', '_')}"
  __send__(m, io, msg) if respond_to?(m)
end

#dpc_trim(io, msg) ⇒ Object



778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/dtas/player/client_handler.rb', line 778

def dpc_trim(io, msg)
  t = @trim
  case msg.size
  when 0 # OK
  when 1, 2
    case msg[0]
    when 'off'
      @trim = nil
    else
      begin
        tbeg = parse_time(msg[0])
        if tlen = msg[1]
          absolute = tlen.sub!(/\A=/, '') # 44:00 =44:55
          tlen = parse_time(tlen)
          tlen -= tbeg if absolute
        end
        @trim = [ tbeg, tlen ] # seconds as float, since we don't know rate
      rescue => e
        return io.emit("ERR #{e.message}")
      end
    end
    __current_requeue
  else
    return io.emit('ERR usage: trim [off|TBEG [TLEN]]')
  end
  t = t ? t.map(&:to_s).join(' ') : 'off'
  __wall("trim #{t}")
  io.emit(t)
end

#drop_sink(sink) ⇒ Object



81
82
83
84
85
86
87
88
89
90
# File 'lib/dtas/player/client_handler.rb', line 81

def drop_sink(sink)
  @targets.delete_if do |t|
    if t.sink == sink
      drop_target(t)
      true
    else
      false
    end
  end
end

#out_samples(in_samples, infmt, outfmt) ⇒ Object



230
231
232
233
234
235
# File 'lib/dtas/player/client_handler.rb', line 230

def out_samples(in_samples, infmt, outfmt)
  in_rate = infmt.rate
  out_rate = outfmt.rate
  return in_samples if in_rate == out_rate # easy!
  (in_samples * out_rate / in_rate.to_f).round
end

#play_pause_handler(io, command) ⇒ Object



335
336
337
338
339
340
341
342
343
344
# File 'lib/dtas/player/client_handler.rb', line 335

def play_pause_handler(io, command)
  prev = @paused
  __send__("do_#{command}")
  io.emit({
    "paused" => {
      "before" => prev,
      "after" => @paused,
    }
  }.to_yaml)
end

#restart_pipelineObject



411
412
413
414
415
# File 'lib/dtas/player/client_handler.rb', line 411

def restart_pipeline
  return if @paused
  __current_requeue
  stop_sinks
end

#seek_internal(cur, offset) ⇒ Object



369
370
371
372
373
374
375
376
377
# File 'lib/dtas/player/client_handler.rb', line 369

def seek_internal(cur, offset)
  if cur.requeued
    @queue[0][1] = offset
  else
    @queue.unshift([ cur.infile, offset ])
    cur.requeued = true
    __buf_reset(cur.dst) # trigger EPIPE
  end
end

#set_bool(io, kv, v) ⇒ Object

returns true on success, wait_ctl arg on error



13
14
15
16
17
18
19
20
21
# File 'lib/dtas/player/client_handler.rb', line 13

def set_bool(io, kv, v)
  case v
  when "false" then yield(false)
  when "true" then yield(true)
  else
    return io.emit("ERR #{kv} must be true or false")
  end
  true
end

#set_int(io, kv, v, null_ok) ⇒ Object

returns true on success, wait_ctl arg on error



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/dtas/player/client_handler.rb', line 46

def set_int(io, kv, v, null_ok)
  case v
  when %r{\A-?\d+\z}
    yield(v.to_i)
  when ""
    null_ok or return io.emit("ERR #{kv} must be defined")
    yield(nil)
  else
    return io.emit("ERR #{kv} must an integer")
  end
  true
end

#set_uint(io, kv, v, null_ok) ⇒ Object

returns true on success, wait_ctl arg on error



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/dtas/player/client_handler.rb', line 60

def set_uint(io, kv, v, null_ok)
  case v
  when %r{\A\d+\z}
    yield(v.to_i)
  when %r{\A0x[0-9a-fA-F]+\z}i # hex
    yield(v.to_i(16))
  when ""
    null_ok or return io.emit("ERR #{kv} must be defined")
    yield(nil)
  else
    return io.emit("ERR #{kv} must an non-negative integer")
  end
  true
end

#state_file_dump_async(io, sf) ⇒ Object



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/dtas/player/client_handler.rb', line 534

def state_file_dump_async(io, sf)
  on_death = lambda { |_| @srv.wait_ctl(io, :wait_readable) }
  pid = fork do
    begin
      begin
        sf.dump(self)
        res = 'OK'
      rescue => e
        res = "ERR dumping to #{xs(sf.path)} #{e.message}"
      end
      io.to_io.send(res, Socket::MSG_EOR)
    ensure
      exit!(0)
    end
  end
  DTAS::Process::PIDS[pid] = on_death
end