Last active
August 26, 2026 15:06
-
-
Save gugod/d30249db790a16cc7cf0549a5c22bcd2 to your computer and use it in GitHub Desktop.
Shift timestamps in a srt file. Output to STDOUT.
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 perl | |
| use v5.42; | |
| main($ARGV[0], $ARGV[1] // 0); | |
| exit; | |
| sub main ($fn, $shiftAmountMs) { | |
| open (my $fh, '<', $fn) | |
| or die $!; | |
| my $nn = qr/[0-9][0-9]/; | |
| my $nnn = qr/[0-9][0-9][0-9]/; | |
| while (<$fh>) { | |
| chomp; | |
| if (/^($nn):($nn):($nn),($nnn) --> ($nn):($nn):($nn),($nnn)$/) { | |
| $_ = timeShiftedLine($shiftAmountMs, [$1,$2,$3,$4], [$5,$6,$7,$8]); | |
| } | |
| say; | |
| } | |
| return 0; | |
| } | |
| sub timeShiftedLine ($shiftAmountMs, $t1, $t2) { | |
| ts(timeShifted($shiftAmountMs, $t1)) . " --> " . ts(timeShifted($shiftAmountMs, $t2)) | |
| } | |
| sub ts ($t) { | |
| sprintf('%02d:%02d:%02d,%03d', $t->[0], $t->[1], $t->[2], $t->[3]); | |
| } | |
| sub timeShifted ($shiftAmountMs, $t) { | |
| my @t2 = @$t; | |
| my $carry; | |
| ($carry, $t2[3]) = addDigits($t2[3], $shiftAmountMs, 1000); | |
| ($carry, $t2[2]) = addDigits($t2[2], $carry, 60); | |
| ($carry, $t2[1]) = addDigits($t2[1], $carry, 60); | |
| $t2[0] += $carry; | |
| return \@t2; | |
| } | |
| sub addDigits($n, $increment, $size) { | |
| my $carry = 0; | |
| $n += $increment; | |
| if ($n < 0) { | |
| $carry = -1 * int( -1*$n / $size); | |
| $n = -1*$n % $size; | |
| } else { | |
| $carry = int($n / $size); | |
| $n = $n % $size; | |
| } | |
| return ($carry, $n); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment