Musings and discoveries while navigating life. Mostly python, perl, sql, R, linux, os x, linguistics, cooking, bread, and food.

About Me

My Photo
Jonathan Keane
Chicago, IL, United States

11 December 2010

Using ffmpeg to divide a video into many clips.

Although this seems ludicrously obvious now, a few months ago I was completely unable to come up with a good solution for automatically separating one video into many different clips. After a while I finally stumbled on something suggesting ffmpeg as a solution. And come to find out it's actually relatively easy:

ffmpeg -ss xx.xxx -t xx.xxx -i /foo/bar.in.mpg -sameq /foo/bar.out.mpg

In order to then automate this I wrote a short python script that also used rpy2 to grab data on what times I needed video from out of my data in R. Then I just used something like the following to extract 1.6 seconds around each point of time in the list times that I had grabbed from R

for time in times:
    filename = '/foo/bar.in.mpg'
    dur = "00:00:01.600"
    secs = str(datetime.timedelta(milliseconds=(time-800)))
    cmd = ''.join(['ffmpeg -ss ',secs,' -t ',dur,' -i ',filename,' -sameq ','/foo/bar.out.mpg'])
    os.system(cmd) 

I've seen other places suggest to use the -vcodec copy -acodec copy options, however this made the clip begin not where I had specified after -ss, but rather at the closest key frame. Using -sameq does take longer and is lossy because the clip is reencoded, but it starts the clip exactly where you specify it. 

Although I used python and R, this could have been accomplished entirely within R, or with any other data source and scripting language. Something similar can be done to extract still images. The ffmpeg documentation is a great resource.

No comments: