creating a video with dowloaded files using ruby and ffmpeg

The city were I lived has been having some quite troubling air quality issues. And I wanted to document it in a visual way.

I wanted to create a video composed of images taken at around the same time of day and create a video of it as a form of visualization.

Since I don’t have a webcam I had to use images from a known webcam that has a very good view of the city.

The following script downloads images from the webcam and creates an mp4 video using ffmpeg.

require "date"
require "net/http"

DUMP_FOLDER        = "./images/"
BASE_URL           = "http://foo/%{date}/%{hour}.jpg"
STARTING_HOUR      = 1700
DAYS_TO_PROCESS    = 7
FROM_DATE          = Date.today - DAYS_TO_PROCESS # ultimos `DAYS_TO_PROCESS` dias
USER_AGENT         = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'
FIN_HORARIO_VERANO = Date.strptime('2016-10-31')

0.upto(DAYS_TO_PROCESS - 1) do |n|
  curr_date = FROM_DATE + n
  fname     = "#{DUMP_FOLDER}/#{curr_date}.jpg"
  counter   = 0
  hour      = STARTING_HOUR + counter - (curr_date >= FIN_HORARIO_VERANO ? 100 : 0)

  if File.exist?(fname)
    puts "File exists: '#{fname}'."
    next
  end

  begin
    image_uri = URI(format(BASE_URL, date: curr_date, hour: hour + counter))
    puts image_uri
    Net::HTTP.start(image_uri.hostname, image_uri.port) do |http|
      get_req               = Net::HTTP::Get.new(image_uri)
      get_req['User-Agent'] = USER_AGENT
      resp                  = http.request(get_req)

      fail "Not found: '#{resp.code}'" unless '200' == resp.code

      File.open(fname, 'wb'){ |saved_file| saved_file.write(resp.body) }
    end
    sleep(3)
  rescue => e
    puts "Error: #{e}"
    sleep(3)
    counter += 1             # quiza la imagen se grabo con una hora minutos antes o despues
    retry unless counter > 5 # solamente intentamos buscar por 5 minutos despues
  end
end

# creamos video con 1 iamgen por segundo, tomando imagenes del
# directorio de salida
system("ffmpeg -framerate 1 -pattern_type glob -i \"#{DUMP_FOLDER}/*.jpg\" -c:v libx264 -r 30 -pix_fmt yuv420p video.mp4")

NOTE I have not included the URL of the webcam provider to avoid abuse of people running this script without care.