Permalink
Browse files

Refactor IO#each_with_timeout

- Remove unnecessary code and complexity
- More readable variable names
- Avoid requiring win32/process twice
- Idiomatic tabbing (2 space soft tab)
- SIGKILL instead of INT quit ffmpeg process
  • Loading branch information...
1 parent e760d53 commit fbc47de8bf5f89ed430c03b4d4531e78c5b77e13 @dbackeus dbackeus committed Jun 27, 2012
Showing with 40 additions and 57 deletions.
  1. +40 −53 lib/ffmpeg/io_monkey.rb
  2. +0 −4 lib/ffmpeg/transcoder.rb
@@ -1,72 +1,59 @@
-
-
if RUBY_VERSION =~ /1\.8/
- #
- # This is useful when `timeout.rb`, which, on M.R.I 1.8, relies on green threads, does not work consistently.
- #
+ # Useful when `timeout.rb`, which, on M.R.I 1.8, relies on green threads, does not work consistently.
begin
require 'system_timer'
- MyTimer = SystemTimer
+ FFMPEG::Timer = SystemTimer
rescue LoadError
require 'timeout'
- MyTimer = Timeout
+ FFMPEG::Timer = Timeout
end
else
require 'timeout'
- MyTimer = Timeout
+ FFMPEG::Timer = Timeout
end
+require 'win32/process' if RUBY_PLATFORM =~ /(win|w)(32|64)$/
#
# Monkey Patch timeout support into the IO class
#
class IO
- def each_with_timeout(pid, timeout, sep_string=$/)
- q = Queue.new
- th = nil
+ def each_with_timeout(pid, seconds, sep_string=$/)
+ sleeping_queue = Queue.new
+ thread = nil
- timer_set = lambda do |timeout|
- th = new_thread(pid){ to(timeout){ q.pop } }
- end
+ timer_set = lambda do
+ thread = new_thread(pid) { FFMPEG::Timer.timeout(seconds) { sleeping_queue.pop } }
+ end
- timer_cancel = lambda do |timeout|
- th.kill if th rescue nil
- end
+ timer_cancel = lambda do
+ thread.kill if thread rescue nil
+ end
- timer_set[timeout]
- begin
- self.each(sep_string) do |buf|
- timer_cancel[timeout]
- yield buf
- timer_set[timeout]
- end
- ensure
- timer_cancel[timeout]
- end
- end
-
-
- private
-
-
- def new_thread(pid, *a, &b)
- cur = Thread.current
- Thread.new(*a) do |*a|
- begin
- b[*a]
- rescue Exception => e
- cur.raise e
- if RUBY_PLATFORM =~ /(win|w)(32|64)$/
- require 'win32/process'
- Process.kill(1, pid)
- else
- Process.kill('INT', pid)
- end
- end
- end
- end
-
- def to timeout = nil
- MyTimer.timeout(timeout){ yield }
- end
+ timer_set.call
+ each(sep_string) do |buffer|
+ timer_cancel.call
+ yield buffer
+ timer_set.call
+ end
+ ensure
+ timer_cancel.call
+ end
+
+ private
+ def new_thread(pid, &block)
+ current_thread = Thread.current
+ Thread.new do
+ begin
+ block.call
+ rescue Exception => e
+ current_thread.raise e
+ if RUBY_PLATFORM =~ /(win|w)(32|64)$/
+ Process.kill(1, pid)
+ else
+ Process.kill('SIGKILL', pid)
+ end
+ end
+ end
+ end
end
@@ -1,10 +1,6 @@
require 'open3'
require 'shellwords'
-if RUBY_PLATFORM =~ /(win|w)(32|64)$/
- require 'win32/process'
-end
-
module FFMPEG
class Transcoder
@@timeout = 200

0 comments on commit fbc47de

Please sign in to comment.