Skip to content

Instantly share code, notes, and snippets.

@elomatreb
Created January 17, 2018 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elomatreb/0db35c64e8be881c1b4bcf3999c172ff to your computer and use it in GitHub Desktop.
Save elomatreb/0db35c64e8be881c1b4bcf3999c172ff to your computer and use it in GitHub Desktop.
Utility script that can adjust (shift forwards/backwards) the timing of Matroska chapters (given in XML chapter files, obtainable with `mkvextract somefile.mkv chapters out.xml`)
#!/usr/bin/env ruby
require "fileutils"
require "nokogiri"
class Timestamp
def self.parse(raw)
return nil unless raw.match?(/\A\d\d:\d\d:\d\d.\d+\z/)
hours, minutes, seconds = raw.split ":"
ts = 0r
ts += Integer(hours, 10) * 3600
ts += Integer(minutes, 10) * 60
ts += Rational(seconds)
end
def self.format(timestamp)
hours = (timestamp / 3600).floor
minutes = ((timestamp % 3600) / 60).floor
seconds = timestamp % 60
sprintf "%02d:%02d:%012.9f", hours, minutes, seconds
end
end
def usage_and_exit
$stderr.puts "Usage: adjustChapterTimings.rb <amount> [files...]"
exit 1
end
amount = begin
Rational(ARGV.shift)
rescue
usage_and_exit
end
ARGV.select! {|f| File.file? f }
usage_and_exit if ARGV.empty?
ARGV.each do |f|
FileUtils.cp f, "#{f}.orig" # backup
doc = Nokogiri::XML::Document.parse File.read(f)
doc.css("ChapterTimeStart, ChapterTimeEnd").each do |element|
ts = Timestamp.parse element.content
element.content = Timestamp.format(ts + amount)
end
File.write(f, doc.to_xml)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment