Sha256: ff386a543335035bc1d377f588eaa2986ab1fddb5d8b380297a1081ad1f76db5

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

module Ffmprb

  class File

    AUDIO_SAMPLE_MIN = 0.5

    def sample(
      at: 0.01,
      duration: 0,
      video: true,
      audio: true,
      &blk
    )
      audio = File.temp('.wav')  if audio == true
      video = File.temp('.png')  if video == true

      Ffmprb.logger.debug{"Snap shooting files, video: #{video && video.path}, audio: #{audio && audio.path}"}

      fail Error, "Incorrect output extname (must be image)"  unless
        !video || video.channel?(:video) && !video.channel?(:audio)
      fail Error, "Incorrect audio extname (must be sound)"  unless
        !audio || audio.channel?(:audio) && !audio.channel?(:video)
      fail Error, "Can sample either video OR audio UNLESS a block is given"  unless
        block_given? || !!audio != !!video
      fail Error, "Can sample video just for 0 sec (an image snapshot)"  unless
        !video || duration == 0

      cmd = %W[-i #{path}]
      cmd.concat %W[-deinterlace -an -ss #{at} -vframes 1 #{video.path}]  if video
      audio_duration = [AUDIO_SAMPLE_MIN, duration].max
      audio_at = [0, at - audio_duration / 2].max
      cmd.concat %W[-vn -ss #{audio_at} -t #{audio_duration} #{audio.path}]  if audio
      Util.ffmpeg *cmd

      return video || audio  unless block_given?

      begin
        yield *[video || nil, audio || nil].compact
      ensure
        begin
          video.unlink  if video
          audio.unlink  if audio
          Ffmprb.logger.debug{"Removed sample files"}
        rescue
          Ffmprb.logger.warn "#{$!.class.name} removing sample files: #{$!.message}"
        end
      end
    end
    def sample_video(*video, at: 0.01, &blk)
      sample at: at, video: (video.first || true), audio: false, &blk
    end
    def sample_audio(*audio, at: 0.01, &blk)
      sample at: at, video: false, audio: (audio.first || true), &blk
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ffmprb-0.12.3 lib/ffmprb/file/sample.rb