Module: DTAS::Player::ClientHandler

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

Overview

:nodoc:

Instance Method Summary collapse

Methods included from XS

#xs

Instance Method Details

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



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/dtas/player/client_handler.rb', line 618

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



313
314
315
316
317
# File 'lib/dtas/player/client_handler.rb', line 313

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



195
196
197
198
199
200
# File 'lib/dtas/player/client_handler.rb', line 195

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



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/dtas/player/client_handler.rb', line 202

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



184
185
186
187
188
189
190
191
192
193
# File 'lib/dtas/player/client_handler.rb', line 184

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



70
71
72
73
74
# File 'lib/dtas/player/client_handler.rb', line 70

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

#__sink_snapshot(sink) ⇒ Object



111
112
113
# File 'lib/dtas/player/client_handler.rb', line 111

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

#__sink_switch(sink) ⇒ Object

called to activate/deactivate a sink



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/dtas/player/client_handler.rb', line 88

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

#_tl_skipObject



535
536
537
538
# File 'lib/dtas/player/client_handler.rb', line 535

def _tl_skip
  @queue.clear
  __current_drop
end

#active_sinksObject



267
268
269
270
271
# File 'lib/dtas/player/client_handler.rb', line 267

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

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



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/dtas/player/client_handler.rb', line 18

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



179
180
181
182
# File 'lib/dtas/player/client_handler.rb', line 179

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

#chdir_handler(io, msg) ⇒ Object



503
504
505
506
507
508
509
510
511
512
# File 'lib/dtas/player/client_handler.rb', line 503

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

#cue_handler(io, msg) ⇒ Object



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'lib/dtas/player/client_handler.rb', line 657

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

#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



234
235
236
# File 'lib/dtas/player/client_handler.rb', line 234

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

#current_handler(io, msg) ⇒ Object

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



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

def current_handler(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!
  tmp["paused"] = @paused
  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
  io.emit(tmp.to_yaml)
end

#do_pauseObject



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

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

#do_playObject



343
344
345
346
347
348
349
350
351
352
353
# File 'lib/dtas/player/client_handler.rb', line 343

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



355
356
357
# File 'lib/dtas/player/client_handler.rb', line 355

def do_play_pause
  @paused ? do_play : do_pause
end

#do_seek(io, offset) ⇒ Object



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

def do_seek(io, offset)
  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

#drop_sink(sink) ⇒ Object



76
77
78
79
80
81
82
83
84
85
# File 'lib/dtas/player/client_handler.rb', line 76

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

#env_handler(io, msg) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/dtas/player/client_handler.rb', line 441

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

#format_handler(io, msg) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/dtas/player/client_handler.rb', line 406

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

#out_samples(in_samples, infmt, outfmt) ⇒ Object



224
225
226
227
228
229
# File 'lib/dtas/player/client_handler.rb', line 224

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



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

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

#restart_pipelineObject



400
401
402
403
404
# File 'lib/dtas/player/client_handler.rb', line 400

def restart_pipeline
  return if @paused
  __current_requeue
  stop_sinks
end

#rg_handler(io, msg) ⇒ Object



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

def rg_handler(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)[+-]?\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

#seek_internal(cur, offset) ⇒ Object



359
360
361
362
363
364
365
366
367
# File 'lib/dtas/player/client_handler.rb', line 359

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



8
9
10
11
12
13
14
15
16
# File 'lib/dtas/player/client_handler.rb', line 8

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



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/dtas/player/client_handler.rb', line 41

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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/dtas/player/client_handler.rb', line 55

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

#sink_handler(io, msg) ⇒ Object

returns a wait_ctl arg



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

def sink_handler(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, false) { |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_hsh.to_yaml)
  else
    io.emit("ERR unknown sink op #{msg[0]}")
  end
end

#skip_handler(io, msg) ⇒ Object



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

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

#source_handler(io, msg) ⇒ Object



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/dtas/player/client_handler.rb', line 463

def source_handler(io, msg)
  map = @source_map
  op = msg.shift
  if op == "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
    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
    __current_requeue if before != after && @current.class == src.class
    io.emit("OK")
  else
    io.emit("ERR unknown source op")
  end
end

#state_file_handler(io, msg) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/dtas/player/client_handler.rb', line 514

def state_file_handler(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
    begin
      sf.dump(self)
    rescue => e
      return io.emit("ERR dumping to #{xs(Array(dest))} #{e.message}")
    end
  end
  io.emit("OK")
end

#tl_handler(io, msg) ⇒ Object



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# File 'lib/dtas/player/client_handler.rb', line 540

def tl_handler(io, msg)
  case msg.shift
  when "add"
    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)
    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}")
  when "repeat"
    case msg.shift
    when "true" then @tl.repeat = true
    when "false" then @tl.repeat = false
    when "1" then @tl.repeat = 1
    when nil
      return io.emit("repeat #{@tl.repeat.to_s}")
    end
    io.emit("OK")
  when "remove"
    track_id = msg.shift or return io.emit("ERR track_id not specified")
    track_id = track_id.to_i
    @tl.remove_track(track_id) or return io.emit("MISSING")

    # skip if we're removing the currently playing track
    if @current && @current.respond_to?(:infile) &&
       @current.infile.object_id == track_id
      _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 == track_id }
    io.emit("OK")
  when "get"
    res = @tl.get_tracks(msg.map!(&:to_i))
    res.map! { |tid, file| "#{tid}=#{file ? Shellwords.escape(file) : ''}" }
    io.emit("#{res.size} #{res.join(' ')}")
  when "tracks"
    tracks = @tl.tracks
    io.emit("#{tracks.size} " << tracks.map!(&:to_s).join(' '))
  when "goto"
    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
  when "current"
    path = @tl.cur_track
    io.emit(path ? path : "NONE")
  when "current-id"
    path = @tl.cur_track
    io.emit(path ? path.object_id.to_s : "NONE")
  when "next"
    _tl_skip
    io.emit("OK")
  when "prev"
    @tl.previous!
    _tl_skip
    io.emit("OK")
  end
end