Wednesday, October 6, 2010

Perl script to adjust the timeline of subtitles for BBC iPlayer downloads

#!/usr/bin/perl -w
#Perl script to adjust the synchronization of subtitles for BBC iPlayer downloads
#Usage: change the $inf and $offset before running the script.
#Output: this script will generate an adjusted subtitle file with a suffix .new#
#Author: Wong
#
use strict;

my $inf='b00vcrt0_live.xml'; #subtitle file name

my $offset=7; # Time in subtitle file delayed in seconds compared to the video.

open (FI,$inf) || die "Cannot open $inf\n";
open(FO,">$inf.new") || die "Cannot create $inf.new\n";
while(<FI>){
if(/(.*<p begin=\")([\d\:\.]+)(\"\s+end=\")([\d\:\.]+)(\">.*)/){
my $b=num2timestr(timestr2num($2)-$offset);
my $e=num2timestr(timestr2num($4)-$offset);
print FO "$1$b$3$e$5\n";
}else{
print FO $_;
}
}
close(FI);
close(FO);
print "Program done.\n";

sub timestr2num{
my ($s)=@_;
if($s=~/(\d+)\:(\d+)\:([\d\.]+)/){
return $1*3600+$2*60+$3;
}
else{
die "Un-recognize time format: $s\n";
}
}
sub num2timestr{
my ($s)=@_;
my $h=int($s/3600);
$s=$s%3600;
my $m=int($s/60);
$s=$s%60;
return ("$h:$m:$s");
}