ffmpeg视频的条件轮换

时间:2014-02-11 18:18:54

标签: ruby-on-rails video ffmpeg carrierwave

我在使用Carrierwave-Video gem上传肖像视频时遇到问题。上传纵向视频(特别是在移动设备上捕获的视频)时,它们会顺时针旋转90度。在Carrierwave-Video文档中,有一个动态配置选项,但我没有找到一种方法来动态传递自定义参数,以便根据视频方向对视频进行转码。我知道如果我运行以下行,我就可以将视频旋转90度CCW:

encode_video(:mp4, custom: "-vf transpose=1")

我需要一种可靠的方法来检测视频是否需要旋转。我想知道是否有某种方法让我使用ffmpeg运行条件参数,只有在视频是肖像时才会运行。

如果它有用,这就是我的视频上传器在我的Rails应用程序中的样子(出于某种原因,转码过程甚至在它检测到视频的方向之前就已经运行了):

require 'carrierwave/processing/mime_types'

class VideoPathUploader < CarrierWave::Uploader::Base

  include CarrierWave::Video
  include CarrierWave::Video::Thumbnailer
  include CarrierWave::MimeTypes

 process :encode

def encode
    Rails.logger.debug "in encode"
    video = FFMPEG::Movie.new(@file.path)
    video_width = video.width
    video_height = video.height
    Rails.logger.debug "video widthxheight: #{video.width}x#{video.height}"
    aspect_ratio = video_width/video_height
    if video_height > video_width
      # rotate video
      Rails.logger.debug "portrait video"
      encode_video(:mp4, custom: "-vf transpose=1", aspect: aspect_ratio)
    else
      encode_video(:mp4, aspect: aspect_ratio)
    end

    instance_variable_set(:@content_type, "video/mp4")
    :set_content_type_mp4
  end
end

2 个答案:

答案 0 :(得分:1)

我能够使用mini_exiftool gem解决问题。在我的计算机上安装exiftool后(使用brew install exiftool),我能够获得上传视频的方向和宽高比,并使用它来确定是否使用ffmpeg将变换应用于视频。这是我的最终上传者:

require 'carrierwave/processing/mime_types'
require 'rubygems'
require 'mini_exiftool'

class VideoPathUploader < CarrierWave::Uploader::Base

 process :encode

 def encode
    video = MiniExiftool.new(@file.path)
    orientation = video.rotation

    if orientation == 90
      # rotate video
      Rails.logger.debug "portrait video"
      aspect_ratio = video.imageheight.to_f / video.imagewidth.to_f
      encode_video(:mp4, custom: "-vf transpose=1", aspect: aspect_ratio)
    else
      aspect_ratio = video.imagewidth.to_f / video.imageheight.to_f
      encode_video(:mp4, resolution: :same, aspect: aspect_ratio)
    end
    instance_variable_set(:@content_type, "video/mp4")
    :set_content_type_mp4
  end

end

另外,如果它有用,我还必须在Heroku上安装exiftool才能将它与我的Rails应用程序一起使用。我是通过使用以下buildpack来完成的:

https://github.com/benalavi/buildpack-exiftool

安装buildpack之后,我仍然需要手动指定exiftool的路径(它应该在安装buildpack时自动执行此操作,但它并没有为我执行此操作)。我通过手动设置路径来完成此操作:

heroku config:set PATH=*all_your_other_paths*:vendor/exiftool-9.40/bin

答案 1 :(得分:1)

我遇到了类似的问题,并使用了基于科学的解决方案的解决方案

您很可能希望清除与视频相关联的轮播元数据。一些玩家(quicktime)将查看旋转元数据并相应地旋转视频。因此,如果您在转码时旋转90,然后视频在播放器中旋转90,它将以180度播放。我还添加了一些标志来提高转码视频的质量。

if orientation == 90
  aspect_ratio = video.imageheight.to_f / video.imagewidth.to_f
  encode_video(:mp4, custom: "-qscale 0 -preset slow -g 30 -vf 'transpose=1' -metadata:s:v:0 rotate=0", aspect: aspect_ratio)
else