DEV Community

loading...
Cover image for Debugging with GIFs!

Debugging with GIFs!

joshnuss profile image Joshua Nussbaum ใƒป2 min read

Have you ever wished you could see a video or animation of your program running? Either to help debug an issue or to explain how it works?

There is an easy way to do this - it's a bit of a hack - but it works well and is easy to setup.

All you need to do is generate an SVG file for each animation frame and then stitch them together into an single playable file.

Generating the graphics

For each state you want to visualize, write a serially named .svg file with padded zeros. For example: frames/00001.svg, frames/00002.svg ... etc.

Here's an example that generates a line series. It is written in Elixir, but this technique works with any language.

defmodule SVG do 
  def export(frame_index, data) do
    # filename is padded with zeros
    filename = frame_index |> to_string |> String.pad_leading(5, "0")
    path = "frames/#{filename}.svg"

    data = """
    <svg
      xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink"
      viewBox="0 0 200 200">

      #{points(data)}

    </svg>
    """

    # write to disk
    File.write(path, data)
  end

  # outputs a list of points
  defp points(data) do
    data |> Enum.map(&point/1) |> Enum.join("\n")    
  end

  # outputs a circle for each point
  defp point({x, y}) do
    ~s|<circle cx="#{x}" cy="#{y}" r="1" fill="blue"/>| 
  end
end

Now you can call SVG.export() from the code you want to diagnose, just supply a frame_index and series of points:

frame_index = 1
series = [{0, 1}, {1, 10}]

# writes SVG to "frames/00001.svg"
SVG.export(frame_index, series)

Stitching the graphics together

Now that you have bunch of frames, let's turn them into an animation.

GIF format

To generate a .gif, simply use convert:

convert -delay 2 -loop 0 frames/*.svg animated.gif

Video format

For .mp4 and other video formats, use the indispensable ffmpeg utility.

Note that ffmpeg doesn't understand .svg files, so you'll need to convert them to .png first:

mogrify -format png frames/*.svg
ffmpeg -r 10 -i frames/%05d.png -pix_fmt yuv420p video.mp4

Summary

Generate animations and video from any data is easy. It's a useful technique for debugging programs or helping others visualize your programs at work.

All you need are .svg files and the utilities convert & ffmpeg.

Happy visualizing!

You can find a fully working example here: https://gist.github.com/joshnuss/353abbd564167e69eecdadd9d590f9e6

Discussion (0)

pic
Editor guide