about summary refs log tree commit homepage
path: root/lib/dtas/trimfx.rb
blob: 5cfac26e243393888536e24e77af236ce58e6124 (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
# Copyright (C) 2013, Eric Wong <normalperson@yhbt.net> and all contributors
# License: GPLv3 or later (https://www.gnu.org/licenses/gpl-3.0.txt)
require_relative '../dtas'
require 'shellwords'

class DTAS::TrimFX
  attr_reader :tbeg
  attr_reader :tlen

  def initialize(args)
    args = args.dup
    case args.shift
    when "trim"
      parse_trim!(args)
    when "all"
      @tbeg = 0
      @tlen = nil
    else
      raise ArgumentError, "#{args.inspect} not understood"
    end
  end

  def to_sox_arg(format)
    if @tbeg && @tlen
      %W(trim #{@tbeg * format.rate}s #{@tlen * format.rate}s)
    else
      []
    end
  end

  def parse_time(tbeg)
    case tbeg
    when /\A\d+\z/
      tbeg.to_i
    when /\A[\d\.]+\z/
      tbeg.to_f
    when /\A[:\d\.]+\z/
      hhmmss = tbeg.dup
      rv = hhmmss.sub!(/\.(\d+)\z/, "") ? "0.#$1".to_f : 0

      # deal with HH:MM:SS
      t = hhmmss.split(/:/)
      raise ArgumentError, "Bad time format: #{hhmmss}" if t.size > 3

      mult = 1
      while part = t.pop
        rv += part.to_i * mult
        mult *= 60
      end
      rv
    else
      raise ArgumentError, "unparseable: #{tbeg.inspect}"
    end
  end

  def parse_trim!(args)
    tbeg = parse_time(args.shift)
    tlen = args.shift
    is_stop_time = tlen.sub!(/\A=/, "") ? true : false
    tlen = parse_time(tlen)
    if is_stop_time
      tlen = tlen - tbeg
    end
    @tbeg = tbeg
    @tlen = tlen
  end
end