Created
February 28, 2009 23:39
-
-
Save vjt/72151 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# SRT Subtitle fixer v0.5 | |
# Applies a time or id shift to an SRT subtitle file. | |
# | |
# (C) 2008 [email protected] | |
# | |
# Usage: ./fixsrt file.srt <timeshift> [idshift] | |
# - timeshift: time shift in floating point (seconds) | |
# - idshift: subtitle id shift, integer, useful | |
# when cutting unneeded subs. defaults to 0. | |
# | |
# Results are printed to stdout. | |
# | |
$KCODE = 'u' | |
def fixsrt(file, timeshift, idshift) | |
File.read(file).split("\n").map do |line| | |
if line =~ /^(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/ | |
sprintf "%s --> %s", $1.shift_srt_ts(timeshift), $2.shift_srt_ts(timeshift) | |
elsif line =~ /^\d+/ | |
($&.to_i + idshift).to_s | |
else | |
line | |
end | |
end | |
end | |
class String | |
def to_seconds | |
return nil unless self =~ /^(\d{2}):(\d{2}):(\d{2}),(\d{3})/ | |
h, m, s, d = $1, $2, $3, $4 | |
ret = "0.#{d}".to_f | |
ret += s.to_i | |
ret += m.to_i * 60 | |
ret += h.to_i * 3600 | |
ret | |
end | |
def shift_srt_ts(shift) | |
(self.to_seconds + shift).to_srt_ts | |
end | |
end | |
class Float | |
def to_srt_ts | |
h = (self/3600).to_i | |
m = ((self - h*3600)/60).to_i | |
s = (self - h*3600 - m*60).to_i | |
d = ((self - self.to_i) * 1000).to_i | |
sprintf "%02d:%02d:%02d,%03d", h, m, s, d | |
end | |
end | |
if $0 == __FILE__ | |
raise "Usage: #$0 <file> <timeshift> [idshift]" unless ARGV.size > 1 | |
file = ARGV.shift | |
timeshift = ARGV.shift.to_f | |
idshift = ARGV.shift.to_i | |
raise "#{file}: invalid file" unless File.file? file | |
raise "#{timeshift}: invalid timeshift" if timeshift.zero? | |
puts fixsrt(file, timeshift, idshift) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment