I spent most of the day working on a talk for Toastmasters; I want to illustrate it with short clips from a movie. There must be an easy way to mark two points in a MP4 file while you’re watching it and copy what’s between them into a new file, but I couldn’t find one – what I did find was this page which had shell scripts that did some computation, then called
ffmpeg to perform the actual extraction. The scripts worked as advertised, but I wanted to make two improvements.
The first was to be able to supply sub-second timestamps for clipping; Bash can’t do decimal arithmetic, but the
bc command can, and that was an easy change to make.
The other improvement I wanted to make was to avoid having to make a full copy of the source file with “key frames” added at the exact points I wanted to start and end the clip with. The original author was working with short files, but I was working with a full movie that was nearly 2GB in size – making a copy of such a file takes a while, even on a fast machine with an SSD.
I thought about it and came up with a workaround. I extracted a few seconds more than I wanted (without having to add key frames); then I put key frames in at the right points in the extracted video (which required copying it, but only a 10-15MB file, not multiple gigabytes); finally, I extracted the exact part I wanted.
This was easy, but it required multiple calls to
bc to do the calculations. And I needed logic in shell script, which is not my strong suit. But I eventually beat it into submission, and it seems to work.
I realized afterwards that it would have been easy to write a short Python program to do the calculations and write out the exact commands I’d need – and there’d be a much better chance of understanding it if I ever had to modify it. But unless I run into yet another problem, I’m going to leave the code alone.
Having elegant code is nice, but going to sleep is better.