티스토리 뷰

Ruby on Rails - Video Upload with Paperclip & FFmpeg


ffmpeg 를 이용하여 Paperclip 으로 동영상 첨부하는 것을 다루도록 하겠습니다.


요구사항

Paperclip 에서 FFMPEG 나 AVCONV 를 이용해서 동영상을 다루기 때문에 미리 FFMPEG 나 AVCONV 가 설치되있어야 합니다.


which ffmpeg 명령어를 통해 ffmpeg 가 설치 되어 있는지 확인하시고 없으면 아래 링크를 통해 설치하시면 됩니다.


2014/09/07 - [OS/리눅스&우분투] - 우분투에서 ffmpeg 설치


또한 Quicktime/MP4 파일들의 metadata 와 offset 정보들을 제거해 streaming 과 pseudo-streaming 을 가능케 하는 qtfaststart 를 설치되어 있어야 합니다.


qtfaststart 를 여기서 다루도록 하겠습니다.



qtfaststart 설치


1. easy_install 설치

$ sudo apt-get install python-setuptools


2. qtfaststart 설치

$ sudo easy_install qtfaststart


3. paperclip 에서 qtfaststart 를 쓸 수 있게 심볼릭 링크 설정

$ sudo ln -s /usr/local/bin/qtfaststart /usr/local/bin/qt-faststart

(paperclip 에서 qt-faststart 로 접근해서 오류를 뿜어내더라구요..)


qtfaststart 에 대해 좀 더 정보를 알고 싶으시다면

https://github.com/danielgtaylor/qtfaststart



Quick Start

전반적으로 이미지 업로드 paperclip 과 비슷합니다. 좀더 requirements 가 많았다는 것을 빼면..


1. 우선 Gemfile 에 paperclip-ffmpeg 를 추가하고 설치해줍시다.


[Gemfile]

gem "paperclip-ffmpeg"


$ bundle install



2. 동영상을 첨부할 모델에 칼럼 값을 추가해줍시다.


$ rails g paperclip Report video

$ rake db:migrate


여기서 Report 부분은 환경에 맞게 수정해 주시면 됩니다.

그러면 Report 모델에 아래 4가지의 컬럼 값들이 추가되게 됩니다.

video_file_name (string)

video_file_size (int)

video_content_type (string)

video_updated_at (datetime)



3. In app/models/report.rb


report.rb 에 아래와 같이 추가해 줍니다.



has_attached_file :video,
:path => ":rails_root/public/video/:id/:filename",
:url => "/video/:id/:filename",
:styles => {
:medium => { :geometry => "640x480", :format => 'mp4' },
:large => { :geometry => "1024x576", :format => 'mp4' },
},
:processors => [:ffmpeg, :qtfaststart]
validates_attachment_content_type :video, content_type: /\Avideo\/.*\Z/
view raw gistfile1.rb hosted with ❤ by GitHub

4. In app/controllers/reports_controller.rb


이제 생성할 때 다뤄주는 create action 을 작성해주면 됩니다.

이것은 그냥 일반 create 처럼 작성해주시면 됩니다.

예제 코드를 적어놓겠습니다.



# POST /reports
# POST /reports.json
def create
@report = current_user.reports.build(report_params)
respond_to do |format|
if @report.save
format.html { redirect_to @report, notice: 'Report was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
private
def report_params
params.require(:report).permit(:title, :date...) # write params you permit
end
view raw gistfile1.rb hosted with ❤ by GitHub


5. In app/views/reports/form.html.erb


여기선 동영상을 업로드할 폼을 보여주는 뷰 페이지 입니다.





<%= form_for @report, :html => { multipart: true } do |f| %>

<%= f.file_field :video, type: :file %>

<% end %>



6. In app/views/reports/show.html.erb


업로드된 동영상을 보여주는 뷰 페이지 입니다.



<% if @report.video? %>

  <%= video_tag(@report.video.url(:medium), controls: true, size: "543x353") %>

<% end %>






이상 Ruby on Rails 에서 Paperclip & FFmpeg 를 이용한 Video Upload 하는 법이였습니다.


paperclip-ffmpeg github : https://github.com/owahab/paperclip-ffmpeg



댓글