#!/usr/bin/perl -w
#
# a script to plit a subtitle file into two files, split at a certain time.
#
# Chunis Deng (chunchengfh@gmail.com)
#
use strict;
use warnings;
# substract two times
# sub_time("35:25", "29:44") or sub_time("21:35:25", "12:29:44")
# sub_time("2:34:45", "37:22") will fail
sub sub_time {
my ($x, $y) = @_;
my ($i, @x, @y);
@x = split /:/, $x;
@y = split /:/, $y;
die "Error! '$x' and '$y' have different time format.\n" if $#x != $#y;
for($i=0; $i<=$#x; $i++){
$x[$i] -= $y[$i];
}
for($i=$#x; $i>0; $i--){
if($x[$i] < 0){
$x[$i] += 60;
$x[$i-1] -= 1;
}
}
#join ":", @x;
sprintf "%02d:%02d:%02d", @x;
}
# test sub_time()
# my $m = "03:25:07";
# my $n = "01:38:56";
# my $s = sub_time($m, $n);
# print "$m - $n = $s\n";
my ($file, $ct, $n, $is_part1);
$n = 1; # messages count flag
$is_part1 = 1; # $is_part1 == 1 means we haven't reach to the second part yet
$#ARGV >= 1 || die "Usage:\n\t$0 subtitle_file substract_time\n";
$file = shift @ARGV;
$ct = shift @ARGV;
my ($file_a, $file_b);
$file =~ /([^.]*)(\.?.*)/;
$file_a = $1 . "-a" . $2;
$file_b = $1 . "-b" . $2;
open FILE, "<", $file
or die "open subtitle file '$file' failed: $!";
open F1, ">", $file_a
or die "open subtitle file '$file' failed: $!";
open F2, ">", $file_b
or die "open subtitle file '$file' failed: $!";
print F2 "1\n";
while(my $line = <FILE>){
chomp $line;
if($line =~ /^(\d+)$/){
if($is_part1){ # we are still in the 1st part
$n = $1;
} else { # we reach to the 2nd part now
$line = $1 - $n + 1;
}
} elsif($line eq ""){
1;
} elsif($line =~ /--/){
my ($t1, $t2) = (split /[, ]/, $line)[0, 3];
$t1 = sub_time($t1, $ct);
$t2 = sub_time($t2, $ct);
if($t1 =~ /^\d/){ # $t1 is later than $ct now(the 2nd argument)
$is_part1 = 0;
$line =~ s/^.*(,.* )[\d:]+(,.*)$/$t1$1$t2$2/;
}
}
if($is_part1){
print F1 "$line\n";
} else {
print F2 "$line\n";
}
}
|