Jan 242010

Okay so it’s been a year since my last post, sue me!

So lately I’ve been preoccupied with learning Ruby.  Ruby is a very sweet language, I won’t go into the reasons why, that’s what google is for.  This post is about my first attempt at coding in Ruby. Here’s the scenario, I have an external Hard Drive with around 1TB(1602 files) of AVI files.  These files are in sub directories named by date.  The AVI’s are from my security DVR system and as such are not compressed very well.  Each file takes up between 500mb to 1 gig of space.  I have been transcoding them with FFmpeg manually for the last few days, and knew I could write a simple Bash script to do it for me.  Since I have been bored with doing things the easy way, I thought “Let’s learn a new language just for this task!”.  Stupid, huh?  Anyways,  So I set out to learn Ruby.  Now, I am certainly no expert and I know my coding will probably make Ruby guru’s gag, but it works for me and you are more than welcome to use it at your own risk.  I take no responsibility in you deleting all your files or formatting your system.

GOAL: Recursively find and transcode all files matching the user inputted file extension.

Prerequisites:

Linux (I personally use CentOS 5.4)
FFmpeg compiled with h.264 and libfaac (which is beyond the scope of this post)

Ruby
ProgressBar library for ruby

Now on to the Code:

Okay, so these first four lines are pretty self explanatory. If not, then you need to start learning Ruby or any language for that matter.
Fire up your favorite editor and insert the following:

#!/usr/bin/env ruby
require 'ftools'
require 'progressbar'
require 'find'

Next:
This tells ruby to clear the screen, Let’s start with a blank screen.
system ('clear')

Let’s create some functions:
The first function simply converts a measurement of time in seconds to days, hours, minutes, and seconds are returns a string with these values.
The second one simply defines three variables, start_time, end_time. and elapsed_time. The yield statement basically tells ruby to pause this function after defining the start_time variable, continue processing the main code (which we’ll get to in a second), and come back here once we’re done below.


def secs_to_days (secs)
  days = ((secs / 60) / (60 * 24)).floor
  hours = (((secs / 60) % (60 *24)) / 60).floor
  minutes = (secs / 60) % 60
  seconds = secs % 60
 "Conversion took #{days.to_s} days, 
  #{hours.to_s} hours 
  #{minutes.to_s} minutes 
  and #{seconds.to_s} seconds."
end

def elapsed_time
  start_time = Time.now
  yield
  end_time = Time.now  
  elapsed_time = end_time.to_i - start_time.to_i
end

This function simply presents the user with some questions and gathers the responses into an array and returns the array.


def user_input
  responses = Array.new
  recurse, delete = nil
  print "What type of file are we going to look for? "
  filetype = gets.chomp!
  responses.push filetype
  print "What is the full path where we should begin searching? "
  basedir = gets.chomp!
  responses.push basedir
  print "Should we search recursively? (y/n) "
  recurse = gets.chomp!
  if /y/i =~ recurse
    recurse = true
  else
    recurse = false
  end
  responses.push recurse
  print "Delete the original files after conversion? (y/n) "
  delete = gets.chomp!
  if /y/i =~ delete
    delete = true
  else
    delete = false
  end
  responses.push delete

  return responses
end

Now we’re getting to the meat and bones. The find_files function does exactly that. It is passed our array from the previous function, uses our responses to set our starting directory, the type of file we are looking for and to either search only the current directory or to search recursively.


def find_files(criteria)
  puts "Beginning Filesystem Search for specified files..."
  puts "We will search for all files with an extension of #{criteria[0]}"
  puts "Beginning in the directory named #{criteria[1]} and will"
  if criteria[2] == true
    puts "Search Recursively"
  else
    puts "NOT Search Recursively"
  end

  file_stack = Array.new

  if criteria[2] == true
    Find.find(criteria[1]) do |filename|
      if File.extname(filename) == criteria[0]
        file_stack.push filename
      else
        next
      end
    end
  elsif criteria[2] == false
    puts Dir.glob("*#{criteria[0]}")
    file_stack = Dir.glob("*#{criteria[0]}")

  else
    puts "Oops, I broke!"
  end

  return file_stack
end

Okay, now this is the main function. The first two lines setup our progress bar. Then we start a loop to process our array of found files and transcode each one in turn using FFmpeg into an h.264 video and depending on our responses, will either delete the original file or not. I am also dumping all output from FFmpeg into log files, so if a problem arises, I can see what happened. After each file is transcoded, we tell our progress bar to update. Then, when our loop has reached the end, we tell our progress bar that we are done. One thing to note… my FFmpeg command line is predetermined. Meaning, I already know how many streams my AVI files have and how I want to process them. You will need to modify the FFmpeg command line to suit your needs.


def convert_video(filename, criteria)
  pbar = ProgressBar.new("Conversion",100)
  pbar_step = 100 / filename.nitems
  filename.each do |video|
    myfile_extension = File.extname(video)
    myfile_basename = File.basename(video,myfile_extension)
    myfile = File.dirname(video)+"/"+myfile_basename
    system "ffmpeg -y -i #{video} -map 0.0 -map 0.1 -map 0.2 -map 0.3 \ 
      -acodec libfaac -ab 64k -ac 2 -vcodec libx264 -r 29.97 -s 640x480 \
      -vpre hq -crf 22 -threads 0 -f mp4 #{myfile}.mp4 -vcodec libx264 \
      -r 29.97 -s 320x240 -vpre hq -crf 22 -newvideo -acodec libfaac \
      -ab 64k -ac 2 -newaudio 2>> ffmpeg.log 1>> ffmpeg.error.log" 
    system "rm -rf #{video}" if criteria[3] == true
    pbar.inc(pbar_step)
  end
  pbar.finish
end

This is where the main execution of our program starts. We have a variable named criteria which is initialized with our function user_input. The same goes for the variable named file_stack, except that the find_files function is passed our criteria variable. Then we just print out a line indicating how many files our little program found.


criteria = user_input()

file_stack = find_files(criteria)

puts "Looks like we\'ve found #{file_stack.nitems}"

And this last bit of code ties it all together. If we have files to process, then let the transcoding begin, if not, We’re Done!


if file_stack.nitems > 0
  print "Press Enter to begin Transcoding or CTRL-C to cancel."
  gets
  convert = elapsed_time {
    convert_video(file_stack, criteria)
  }
puts secs_to_days(convert)

else
  puts "Sorry, I couldn't find any files to process... Exiting!"
end

Now save your file. You can name it anything you want with an .rb extension. chmod +x it. Now run it.

Click here to see the entire source code. Use it as you will, but at your own risk.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
  • Buy Cheap prices soft tab cialis Now Guaranteed Shipping. Online Prices For prices soft tab cialis!
  • Buy Cheapest side effects from viagra Online Best Internet. Discount Online Pharmacy.
  • Buy Cheap cialis tadalafil information page Now No Prescription Online Pharmacy. Best Online.
  • Buy Cheapest cialis softgel Online Free Viagra Pills! 24/Online Pharmacy.
  • avarage age men taking viagra Online Without Prescription Best Prices. Pharmacy Store.
  • Buy Cheapest professional viagra cheap Now Online Medical Shop. 24/Online Pharmacy.
  • Buy what is viagra super active Online Without Prescription. Best Drugstore. Low Prices.
  • Buy Cheap online prescription viagra without Online Cheap Prescription Drugs. Best Online.
  • Buy Cheap cheapest generic cialis online Now Internet Prices For cheapest generic cialis online! Best Drugstore.
  • Buy Cheap levitra multiple orgasm Now Top Online Pharmacy. Guaranteed Shipping.
  • Buy Cheapest indian viagra Now 24/Online Pharmacy. Best Internet.
  • Buy Cheap viagra dose Now Drugs, Health And Beauty. Top Online Pharmacy.
  • Buy Cheap cialis drug impotence Online Pharmacy Store. Discount Pharmacy Online.
  • Buy Cheap safe generic cialis Now Top Online Pharmacy Supplier. Best Internet.
  • Buy Cheap bayer levitra cheapest price Now Best Drugstore. Top Online Pharmacy Supplier.
  • Buy Cheap levitra 10 mg Now Online Medical Shop. Discount Online Pharmacy.
  • Buy Cheap how does viagra work? Online Best Internet. No Prescription Needed.
  • Buy Cheap viagra without Now 24/Internet)(safe Pharmacy. Low Prices.
  • Buy Cheap levitra dose Online Best Internet. Order Cheap Meds Without Rx.
  • Buy Cheap cialis samples Online Top Online Pharmacy. Best Drugstore.
  • Buy Cheapest cheep daily cialis Online Buy %items% Online Without Prescription.
  • Buy Cheap cheep daily cialis Now Online Medical Shop. Buy Medications Online.
  • Buy Cheapest viagra online purchase Online Best Online. No Prescription Needed.
  • Buy Cheapest gel viagra Now Buy Medications Online. Best Prices.
  • Buy Cheap cialis ingredients Now Best Prices. Safe And Secure Payment System.
  • Buy Cheap cialis bathtub Now WorldWide Shipping. Discount Online Pharmacy.
  • Buy Cheapest buy taladafil viagra Online Cheap Pharmacy Online. Best Internet.
  • Buy Cheapest but cialis in us Now Drugs, Health And Beauty. Low Prices.
  • Buy Cheap cialis tablet size Online Guaranteed Shipping. Cheap Online Pharmacy.
  • Buy Cheapest get cialis without prescriptions Online Buy Medications Online. Low Prices.
  • Buy Cheapest new dosing for cialis Now Cheap Prescription Drugs. Best Internet.
  • cialis promise Online Without Prescription Best Online. Free Viagra Pills!
  • Buy Cheap pleasure viagra Online Special Prices For pleasure viagra! Best Drugstore.
  • Buy Cheapest levitra cheapest Now Special Prices For levitra cheapest! Best Drugstore.
  • Buy Cheapest cialis 20mg lowest price Online Online Medical Shop. Best Internet.
  • Buy Cheap viagra online australia Online The Largest Internet Pharmacy. Best Online.
  • Buy Cheapest genaric cialis Online No Prescription Needed. Pharmacy Store.
  • Buy Cheap buy online cialis Now 100% Satisfaction Guaranteed. Low Prices.
  • Buy Cheap generic cialis softtabs Online Discount Pharmacy Online. Low Prices.
  • Buy Cheapest drug cialis Online Best Online. Drugs, Health And Beauty.
  • Buy Cheap gay men viagra vs cialis Now Pharmacy Store. Cheap Prescription Drugs.
  • Buy Cheap how to use cialis Now Best Online. Order Cheap Meds Without Rx.
  • Buy Cheapest where buy cialis Online WorldWide Shipping. Top Online Pharmacy.
  • Buy Cheap cialis online purchase Now WorldWide Shipping. Online Medical Shop.
  • Buy Cheap canada cialis Online Top Online Pharmacy. Best Drugstore.
  • Buy Cheapest viagra pfizer lower price Online Best Prices. Cheap Online Pharmacy.
  • Buy Cheap free viagra in the uk Online Best Online. Internet Prices For free viagra in the uk!
  • Buy Cheap levitra or viagra Online Best Prices. Order Cheap Meds Without Rx.
  • Buy Cheap risperodol interactions with cialis viagra levitra Now Pharmacy Store. 24/Internet)(safe Pharmacy.
  • Buy Cheap generic cialis online Online Best Internet. Online Prices For generic cialis online!
  • Buy Cheap compare generic viagra prices Now Drugs, Health And Beauty. Top Online Pharmacy.
  • Buy Cheapest testimonies of viagra use Now Pharmacy Store. Top Online Pharmacy.
  • super cialis Online Without Prescription Best Internet. Best Prices.
  • Buy Cheapest cialis for men Now No Prescription Needed. WorldWide Shipping.
  • Buy Cheap online consultation viagra Now Guaranteed Shipping. WorldWide Shipping.
  • Buy Cheapest cialis instructions Online Buy Medications Online. Best Internet.
  • Buy Cheap blockers and alpha levitra Now Best Internet. Online Prices For blockers and alpha levitra!
  • Buy Cheapest does viagra work for women Online Discount Pharmacy Online. Best Online.
  • Buy Cheap generic cialis cheapest Now Free Viagra Pills! Online Medical Shop.
  • Buy Cheap viagra cialis desire Now Online Medical Shop. Top Online Pharmacy.
  • Buy Cheapest levitra viagr cialis Online 24/Online Pharmacy. Best Prices.
  • Buy Cheap viagra instructions Now Top Online Pharmacy Supplier. Best Online.
  • Buy Cheap levitra pricing Online Discount Pharmacy Online. Best Internet.
  • Buy Cheap buy viagra in the uk Now Safe And Secure Payment System. Best Internet.
  • Buy Cheapest lowest prices for cialis Now Best Internet. Order Cheap Meds Without Rx.
  • brand name viagra Online Without Prescription Low Prices. WorldWide Shipping.
  • Buy Cheap phentermine online overnight delivery levitra Now Cheap Meds Without Prescription. Best Prices.
  • Buy Cheap free viagra Now Drugs, Health And Beauty. Pharmacy Store.
  • Buy Cheap buy and purchase viagra online Now Guaranteed Shipping. Cheap Pharmacy Online.
  • Buy Cheapest cialis online online get cialis cheapest Now Order Cheap Meds Without Rx. Best Online.
  • Buy Cheapest cialis eli lilly Online Free Viagra Pills! 24/Online Pharmacy.
  • Buy Cheap generic cialis levitea viagra sampler packages Online Best Drugstore. Discount Pharmacy Online.
  • Buy Cheapest viagra order Online Best Prices. Cheap Online Pharmacy.
  • Buy Cheap levitra cialis Online WorldWide Shipping. No Prescription Needed.
  • Buy Cheapest levitra drug Now WorldWide Shipping. Free Viagra Pills!
  • Buy Cheapest price cialis mexico pharmacy Online Pharmacy Store. Top Online Pharmacy.
  • Buy Cheapest but cialis online Now Best Drugstore. No Prescription Needed.
  • Buy Cheap cheap cialis generic mastercard Online Best Online. No Prescription Needed.
  • Buy Cheap viagra levitra cialis stuffy nose Online Pharmacy Store. Guaranteed Shipping.
  • Buy Cheap free levitra Online Special Prices For free levitra! Best Internet.
  • Buy Cheapest buy cialis fast shipping Now Safe And Secure Payment System. Low Prices.
  • Buy Cheap viagra cialis on line Now Best Drugstore. Cheap Prescription Drugs.
  • Buy Cheap indian viagra Now Guaranteed Shipping. Cheap Online Pharmacy.
  • Buy Cheap real cialis Now Drugs, Health And Beauty. Pharmacy Store.
  • Buy Cheap buying cialis online Online Cheap Pharmacy Online. Top Online Pharmacy.
  • Buy Cheapest texas vardenafil levitra hcl Now Top Online Pharmacy Supplier. Low Prices.
  • Buy Cheap female version viagra Now Internet Prices For female version viagra! Pharmacy Store.
  • Buy Cheap cialis low cost Now Best Drugstore. Top Online Pharmacy Supplier.
  • Buy Cheap cialis profestional Online Discount Pharmacy Online. Best Internet.
  • Buy Cheapest levitra drug interactions Online Best Online. Online Prices For levitra drug interactions!
  • Buy Cheapest viagra for pulmonary hypertension Now Low Prices. The Largest Internet Pharmacy.
  • Buy Cheap cialis cost Now WorldWide Shipping. Drugs, Health And Beauty.
  • Buy Cheap viagra prescription Now Online Medical Shop. Cheap Prescription Drugs.
  • Buy Cheapest 5 mg cialis Now Free Viagra Pills! No Prescription Needed.
  • Buy Cheap generic viagra soft tab fast Online Cheap Online Pharmacy. Best Drugstore.
  • Buy Cheapest indian cialis pro Now Best Drugstore. Special Prices For indian cialis pro!
  • Buy Cheap buy viagra australian Now Free Viagra Pills! Discount Online Pharmacy.
  • Buy Cheapest levitra without a presription Online Pharmacy Store. Guaranteed Shipping.
  • Buy Cheap cialis generico sildenafil Now Buy Medications Online. Guaranteed Shipping.
  • Buy Cheap discount cialis online Now Cheap Pharmacy Online. Online Medical Shop.
  • Welcome BrainYang.com

    Log in

    Lost your password?

    Register For This Site

    Join

    Join us as we spread the word.