Here is a function for doing this on Linux (and maybe Mac). I've looked around and I haven't seen any previous example of how to do this in MMA. Perhaps the comments will enlighten me as to prior work.
for my case this not only uses far less memory, it's also about 6x faster than Export["foo.mp4",frames,VideoEncoding -> "LIBX264",]
. YMMV.
The function below accepts a (pure/stateless) function f: Any -> Graphics
together withFor my case this method uses a listreasonable amount of values times
memory, even for high-resolution, high-framecount animations. It spawns an ffmpeg
subprocessIt's also significantly faster than using Export (ffmpeg
should be on the path), and then proceeds to loop over the values6x in times
one test case). For each value, it calls f
to generate a frame, which it then rasterizes and feeds to the ffmpeg
process via a fifo/named pipe
How it works
- You make sure the
ffmpeg
executable is available on the path. - You supply
frameGraphicFun
, a frame generator function which accepts a singletime
argument and returns aGraphics[]
object. - You supply
times
, which is a list of time values . - The function
EncodeMyVideo
launchesffmpeg
as a subprocess. It then generates frames one at a time, by callingframeGraphicFun
using the values intimes
. It rasterizes the frameGraphics[]
and feeds it toffmpeg
using a fifo/named pipe (here's where this is *nix-dependent). - When all frames have been sent to
ffmpeg
, it closes the fifo and waits forffmpeg
to return.
.
This way, there's at most one frame in memory at a time.
When all frames have been fed to ffmpeg
,. and the fiforesult is closed, which signals ffmpeg to conclude its businessa video file.
The code currently suffers fromcomes with some caveats:
- It's been testedTested on linux only. It may work as-is on Mac. It almost certainly does not work as-is on windows (though it probably could be made to).
- The encoding parameters are a matter of course debatablepersonal preference. In particular, I preferchoose to force periodic keyframes because,even though it makes the filethat results in a substantially larger, it makes "scrubbing" smoother when using my media player file. I tend to doThe advantage is that a lot with technical animationsthe extra keyframes make seeking much smoother.
- The code isn't particularly elegant Which I find useful when I manually "scrub" through portions of a mathematical animation (and I often do).