Guest User

Untitled

a guest
May 20th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. #!/usr/bin/ruby
  2.  
  3. require 'Date'
  4. require 'FileUtils'
  5.  
  6. class JPEG
  7. attr_reader :width, :height, :bits
  8.  
  9. def initialize(file)
  10. if file.kind_of? IO
  11. examine(file)
  12. else
  13. File.open(file, 'rb') { |io| examine(io) }
  14. end
  15. end
  16.  
  17. private
  18. def examine(io)
  19. raise 'malformed JPEG' unless io.getc == 0xFF && io.getc == 0xD8 # SOI
  20.  
  21. class << io
  22. def readint; (readchar << 8) + readchar; end
  23. def readframe; read(readint - 2); end
  24. def readsof; [readint, readchar, readint, readint, readchar]; end
  25. def next
  26. c = readchar while c != 0xFF
  27. c = readchar while c == 0xFF
  28. c
  29. end
  30. end
  31.  
  32. while marker = io.next
  33. case marker
  34. when 0xC0..0xC3, 0xC5..0xC7, 0xC9..0xCB, 0xCD..0xCF # SOF markers
  35. length, @bits, @height, @width, components = io.readsof
  36. raise 'malformed JPEG' unless length == 8 + components * 3
  37. when 0xD9, 0xDA: break # EOI, SOS
  38. when 0xFE: @comment = io.readframe # COM
  39. when 0xE1: io.readframe # APP1, contains EXIF tag
  40. else io.readframe # ignore frame
  41. end
  42. end
  43. end
  44. end
  45.  
  46. def convert_montage_to_video
  47.  
  48. lifestream_root = File.expand_path("~#{ENV['USER']}/lifestream/")
  49. image_files = File.join(lifestream_root, "images", "*.jpeg")
  50. montage_root = File.join(lifestream_root, "montage")
  51. blank_file = File.join(lifestream_root, "blank.jpg")
  52.  
  53. incremental = 0
  54. previous_timestamp = ""
  55.  
  56. # Clean invalid files
  57. Dir.glob(image_files).select{|file| JPEG.new(file).width != 1760}.each{|file| File.unlink file}
  58.  
  59. Dir.glob(image_files).each do |file|
  60.  
  61. timestamp = file[/\d+/]
  62.  
  63. diff = timestamp[0..-3].to_i - previous_timestamp[0..-3].to_i
  64. if previous_timestamp.empty? || diff == 3
  65. FileUtils.mv(file, File.join(montage_root, "#{"%05d" % incremental}.jpg"))
  66. incremental += 1
  67. else
  68. (diff / 3).times do |i|
  69. FileUtils.cp(blank_file, File.join(montage_root, "#{"%05d" % incremental}.jpg"))
  70. incremental += 1
  71. end
  72. end
  73. previous_timestamp = timestamp
  74. end
  75.  
  76. # Convert images into videos using ffmpeg
  77. current_week = Date.today.cweek
  78. output = File.join(lifestream_root, "video/lifestream_#{current_week}.mp4")
  79. `cd #{montage_root}; /opt/local/bin/ffmpeg -r 20 -b 1800 -i %05d.jpg #{output}`
  80.  
  81. # Remove montage files
  82. Dir.glob(File.join(montage_root,"*.jpg")).each{|file| File.unlink file}
  83. Dir.glob(image_files).each{|file| File.unlink file}
  84. end
  85.  
  86. convert_montage_to_video
Add Comment
Please, Sign In to add comment