Sha256: 2aca0803811459f2359172e6ce6a0d8015c2f831fceae45f75d0c11d088fa9b4

Contents?: true

Size: 1.94 KB

Versions: 3

Compression:

Stored size: 1.94 KB

Contents

module Subber::Formatter
  class Vtt < Base
    LF_REGEX = /\n/
    CRLF = "\r\n"

    class << self
      # @param subtitles [Array<Subber::Subtitle>]
      # @return [String]
      #
      def format(subtitles)
        cues =
          subtitles.map do |subtitle|
            convert_subtitle_to_cue(subtitle)
          end

        file_content = cues.join
        file_content = add_webvtt_header(file_content)
        file_content = add_window_line_break(file_content)
        file_content
      end

      private

      # @param file_content [String]
      # @return [String]
      #
      def add_webvtt_header(file_content)
        "WEBVTT\n\n#{file_content}"
      end

      # @param file_content [String]
      # @return [String]
      #
      def add_window_line_break(file_content)
        file_content.gsub(LF_REGEX, CRLF)
      end

      # @param subtitle [Subber::Subtitle]
      # @return [String]
      #
      def convert_subtitle_to_cue(subtitle)
        cue = [
          build_counter(subtitle),
          build_time_range(subtitle),
          build_content(subtitle),
        ].join("\n")

        "#{cue}\n\n"
      end

      # @param subtitle [Subber::Subtitle]
      # @return [String]
      #
      def build_counter(subtitle)
        subtitle.counter.to_s
      end

      # @param subtitle [Subber::Subtitle]
      # @return [String]
      #
      def build_time_range(subtitle)
        start_time = convert_ms_to_time(subtitle.start_time)
        end_time = convert_ms_to_time(subtitle.end_time)

        "#{start_time} --> #{end_time}"
      end

      # @param subtitle [Subber::Subtitle]
      # @return [String]
      #
      def build_content(subtitle)
        subtitle.content
      end

      # @param ms_time [Integer] Time in milliseconds
      # @return [String] Formatted time
      #
      def convert_ms_to_time(ms_time)
        seconds = ms_time / 1000.0
        Time.at(seconds).utc.strftime("%H:%M:%S.%L")
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
subber-0.1.9 lib/subber/formatter/vtt.rb
subber-0.1.8 lib/subber/formatter/vtt.rb
subber-0.1.4 lib/subber/formatter/vtt.rb