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 viagra vs cialis vs levitra Now Best Drugstore. 100% Satisfaction Guaranteed.
  • Buy Cheapest ampicillin side effects Online Low Prices. Pharmacy At The Best Price!
  • Buy Cheapest propecia on line Online Best Prices. Discount Online Pharmacy.
  • Buy narcotic pain killers Without Prescription Doctor. Best Prices. Best Online.
  • Buying Cheap effects of ultram. Offshore Rx, Best Prices. Online Medical Shop.
  • Buy Cheapest what does tramadol look like Now Cheap Pharmacy Online. WorldWide Shipping.
  • Buy Cheap xanax warnings Now 24/Online Pharmacy. Cheap Pharmacy Online.
  • Buy Cheapest zithromax 500 mg Now Best Drugstore. Cheap Online Pharmacy.
  • Buying Cheapest levitra use instructions. Mexican Pharmacy, Good Prices. Best Prices.
  • Buy Cheap vitamin stores online Now Drugs, Health And Beauty. Online Medical Shop.
  • Buy Cheap low cost phentermine no prescription Online Drugs, Health And Beauty. Pharmacy Store.
  • Buy Cheapest cialis fast shipping Now Pharmacy Store. Cheap Pharmacy Online.
  • Buy Cheapest finasteride proscar Online Pharmacy Store. Online Medical Shop.
  • Buy Cheap buy generic cialis overnight delivery Online Top Online Pharmacy. Best Drugstore.
  • Buy Cheapest safest weight loss pill Now Pharmacy Store. Guaranteed Shipping.
  • Buy Cheap clonazepam fedex Now Best Internet. Special Prices For clonazepam fedex!
  • Buy Cheap sildenafil cheapest Now Internet Prices For sildenafil cheapest! Best Prices.
  • Buy Cheap generic cialis in stock Now Best Internet. 100% Satisfaction Guaranteed.
  • Buy pharmacy no prescription Online Without Prescription. Best Internet. Best Prices.
  • Buy Cheap nexium interactions Online Drugs, Health And Beauty. Best Internet.
  • Buy Cheap viagra vs cialis Now Cheap Prescription Drugs. Online Medical Shop.
  • Buy Cheap xanax street value Now 24/Online Pharmacy. Cheap Online Pharmacy.
  • Buy Cheap can women take cialis Now 24/Online Pharmacy. Cheap Pharmacy Online.
  • Buy Cheapest pain management speciality pharmacy Online Best Drugstore. Buy Medications Online.
  • Buy Cheapest accutane buy Online Discount Drugs At Best Online Drugstore.
  • Buy Cheapest fda diet pill Now Special Prices For fda diet pill! Pharmacy Store.
  • Buy Cheapest depression meds Now Best Internet. Buy Medications Online.
  • Buy Cheap ordering diet medications Online Buy Medications Online. Best Online.
  • Buy Cheapest cheap revatio Now Guaranteed Shipping. Free Viagra Pills!
  • Buy Cheap male weight loss supplements Online Cheap Online Pharmacy. Pharmacy Store.
  • Buy Cheap pinworm remedy Now Best Internet. Discount Online Pharmacy.
  • Buy Cheap zyban how to use Online Pharmacy Store. Cheap Online Pharmacy.
  • Buy Cheapest generic cialis online pharmacy Now Best Drugstore. Guaranteed Shipping.
  • Buy Cheap discount drugs online Online Order Cheap Meds Without Rx. Low Prices.
  • Buy Cheap cheap online plavix Now Low Prices. All Medications Are Certificated!
  • Buying Cheapest viagra fedex. Offshore Pharmacy, Best Prices. Low Prices.
  • Buy Cheapest cialis mail order Now No Prescription Needed. Best Internet.
  • Buying Cheap valium addiction. Mexican Pharmacy, Best Prices. Pharmacy Store.
  • Buy Cheapest medicine without prescription Online Guaranteed Shipping. Pharmacy Store.
  • Buy Cheap non prescription ambien Now No Prescription Online Pharmacy. Best Online.
  • Buy Cheap walmart pharmacies Online Best Online. Order Cheap Meds Without Rx.
  • Buy xanax sold online Without Prescription Doctor. Best Internet. Low Prices.
  • Buy Cheap viagra generic cheap Online WorldWide Shipping. Cheap Pharmacy Online.
  • Buy Cheap viagra cialis vs Now Best Internet. Discount Pharmacy Online.
  • internet pharmacies no prescription Online Without Prescription Best Online. WorldWide Shipping.
  • Buy Cheapest real phentermine Now Low Prices. Top Online Pharmacy Supplier.
  • Buy Cheap cialis generic Now Low Prices. 24/Internet)(safe Pharmacy.
  • Buy Cheap buy tetracycline Online Guaranteed Shipping. Cheap Pharmacy Online.
  • Buy Cheapest buy ambien cr Now WorldWide Shipping. Guaranteed Shipping.
  • Buying Cheapest cialis long term effects. Mexican Pharmacy, Good Prices. Best Online.
  • Buy Cheapest prescription diet med Online Pharmacy Store. No Prescription Needed.
  • Buy Cheapest lorazepam online no prescription Now Special Prices For lorazepam online no prescription! Best Prices.
  • Buy Cheapest levitra onlines Online Low Prices. No Prescription Needed.
  • Buy Cheapest generic lexapro Now No Prescription Needed. Free Viagra Pills!
  • Buy Cheapest levitra result Now Special Prices For levitra result! Best Online.
  • Buy Cheapest non prescription anti anxiety drugs Now Discount Pharmacy Online. Best Prices.
  • Buy Cheapest women's viagra Now Best Online. The Largest Internet Pharmacy.
  • Buy Cheap erectile dysfunction cialis Now Safe And Secure Payment System. Best Internet.
  • Buy Cheap fda levaquin Now Low Prices. Top Online Pharmacy Supplier.
  • Buy Cheap clomid instructions Online Online Prices For clomid instructions! Best Prices.
  • Buy Cheapest maximum cialis dose Now Special Prices For maximum cialis dose! Best Drugstore.
  • Buy Cheap india pharmacy Now Free Viagra Pills! Internet Prices For india pharmacy!
  • Buy Cheap amoxicillin dosages Online Low Prices. Safe And Secure Payment System.
  • Buy Cheapest generic sleep aids Now Drugs, Health And Beauty. Best Prices.
  • Buy Cheapest non-prescription diet pills Online 24/Online Pharmacy. Best Online.
  • Buy Cheap overseas phentermine Now Top Online Pharmacy. Discount Online Pharmacy.
  • Buy Cheap woman's viagra Online Drugs, Health And Beauty. Best Drugstore.
  • Buy Cheapest online licensed pharmacy Online Top Online Pharmacy. Free Viagra Pills!
  • Buy Cheapest new drugs for depression Now 100% Satisfaction Guaranteed. Low Prices.
  • Buy Cheap doxycycline uses Now Best Drugstore. Discount Online Pharmacy.
  • Buy Cheap no rx cheap appetite suppressants Online Cheap Pharmacy Online. Pharmacy Store.
  • Buy Cheap how to get pain medication Online Online Medical Shop. Cheap Pharmacy Online.
  • Buy Cheap pharmacy discounts Online Pharmacy Store. Guaranteed Shipping.
  • Buy Cheapest codeine syrup Online Best Prices. 24/Online Pharmacy.
  • Buy Cheap rate weight loss products Now Discount Online Pharmacy. Guaranteed Shipping.
  • Buy Cheap pain medications generic side effects Now Online Medical Shop. Free Viagra Pills!
  • Buy Cheap tramadol generic Now Guaranteed Shipping. Online Medical Shop.
  • Buy Cheap ultram withdrawals Online 24/Online Pharmacy. Best Internet.
  • Buy Cheap online pain meds no prescription Now Discount Pharmacy Online. Guaranteed Shipping.
  • Buy Cheap cialis effect on blood pressure Now Drug Store Without A Prescription. Low Prices.
  • Buy Cheap ultram 50mg Online Best Online. Order Cheap Meds Without Rx.
  • Buy Cheapest order valtrex Online Best Internet. Top Online Pharmacy.
  • Buy Cheapest mexico phentermine Now Discount Online Pharmacy. Best Internet.
  • Buy Cheap top ten diet pills Online Best Online. Special Prices For top ten diet pills!
  • Buy prescription pain management drugs Online Without Prescription. Low Prices. Pharmacy Store.
  • Buy Cheap valium online Now Best Drugstore. Top Online Pharmacy Supplier.
  • Buy Cheapest pain med online no prescriptions Now Guaranteed Shipping. 24/Online Pharmacy.
  • Buying Cheap tramadol best buy. Worldwide Rx, Good Prices. WorldWide Shipping.
  • Buy Cheapest pharmacy diazepam Now Free Viagra Pills! 24/Online Pharmacy.
  • Buy Cheap on line sleep aids Online Pharmacy Store. Cheap Prescription Drugs.
  • Buy Cheapest viagra prices australia Now Best Internet. No Prescription Needed.
  • Buy Cheap cheap valium generic Now Top Online Pharmacy. Discount Pharmacy Online.
  • Buy Cheap tramadol hci Online Discount Online Pharmacy. Best Prices.
  • Buy Cheapest how to write a prescription cialis Now Free Viagra Pills! WorldWide Shipping.
  • Buy Cheap viagra half price pharmacy Online Internet Prices For viagra half price pharmacy! Best Internet.
  • Buy Cheapest testosterone booster Online Buy Medications Online. Best Prices.
  • Buy Cheap canada drug store Now Cheap Pharmacy Online. WorldWide Shipping.
  • Buy Cheapest generic levitra cheap Online Free Viagra Pills! Online Medical Shop.
  • Buy Cheapest diet pill Now Cheap Pharmacy Online. Free Viagra Pills!
  • Buy Cheap online drug store Online Low Prices. Drugs, Health And Beauty.
  • Howdy, BrainYang.com

    Log in

    Lost your password?

    Register For This Site

    Join

    Join us as we spread the word.