FLV Duration in Ruby
There is a lack of decent open source FLV manipulation software out there. There is Yamdi which is a seriously awesome metadata injector, written in C, and then there is FLVTool2, which is a ruby based injector tool. FLVTool2 is really awesome, but it is a serious memory hog and 90% of the files I work with are >1gb size.
I am doing some house cleaning on one project and I have a need to quickly get the duration of an flv video file, but without loading the whole thing into memory, or even reading in the whole file. As an advantage to me, all the files in question have already been injected by yamdi, so the duration is already calculated and inserted into the files. I just need to read it, and be on my merry way.
Here it is:
def duration(filename)
f = File.open(filename, 'r')
raise "Could not open File!" unless f
#check for flv text
unless f.read(3) === 'FLV'
raise "This does not seem to be an FLV file."
end
#check to make sure we are a video
f.seek(3)
is_video = f.read(1).unpack("H*").first.hex
unless is_video == 1
raise "This FLV file does not contain video."
end
#seek to end, get size
f.seek(0, IO::SEEK_END)
length = f.tell
#calculate tag length
f.seek(-4, IO::SEEK_END)
taglen = f.read(4).unpack("H*").first.hex
#finally get duration
f.seek(length - taglen, IO::SEEK_SET)
duration = f.read(3).unpack("H*").first.hex.to_f/1000
f.close()
#duration returns in seconds
duration
end
I ripped this out of another one of my classes that is already dealing with the flv file in other ways, so there is more validation in place than you see here. This has only been tested with files injected with yamdi 1.3 and 1.4, I have not tested with anything else, but if anyone does please let me know!
If you are interested in doing this in php there is similar scripts here which helped me greatly.
Comments:
| Thank you! It's really helpful. I'd never thought this kind of approach instead of using ffmpeg or so. |
| Posted By: James Lee, 2 years ago |
Add Comment:
Back
