#! /usr/bin/perl -w
# aup2ass - time subtitles using Audacity
# catwell <catwell@archlinux.us> 2007
# Released under the WTFPL: http://sam.zoy.org/wtfpl/

# To time, open your audio track in Audacity and use a marker for each subtitle.
# You can create a marker with ctrl+b.
# To convert, use perl aup2ass.pl file.aup.

 ########
 # VARS #
 ########

my $head = '[Script Info]
Title: 
Original Script: 
Original Translation: 
Original Editing: 
Original Timing: 
Synch Point: 
Script Updated By: 
Update Details: 
ScriptType: v4.00+
Collisions: Normal
PlayResX: 640
PlayResY: 480
PlayDepth: 0
Timer: 100.0000
WrapStyle: 0

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,25,&H00FFFFFF,&H00000000,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,20,20,30,0

[Events]
Format: Layer, Start, End, Style, Actor, MarginL, MarginR, MarginV, Effect, Text
';

 ########
 # SUBS #
 ########

sub d2
{
 my $i = "00".shift;
 my $j = chop($i);
 $i = chop($i);
 return "$i$j"
}

sub cf
{
 my $in = shift;
 my @t = localtime($in);
 my ($h,$m,$s,$c) = ($t[2]-1,d2($t[1]),d2($t[0]),d2(int(100*($in-int($in))+.5)/100));
 return "$h:$m:$s.$c"
}

 ########
 # MAIN #
 ########

my $aup = $ARGV[0];
my $ass = $aup;
substr($ass,-4,4,'.ass');
my $lnum = 1;

open(AUP,'<',$aup);
my @aup = <AUP> ;
close(AUP);
open(ASS,'>',$ass);
open(ASS,'>>',$ass);
print ASS $head;

foreach $line (@aup)
{
 my ($td,$tf);
 if ($line =~ m/<label t=/)
 {
  ($td,$tf) = ($line =~ /<label t="(\d+.\d+)" t1="(\d+.\d+)" /);
  ($td,$tf) = (cf($td),cf($tf));
  print ASS "Dialogue: 0,$td,$tf,Default,,0000,0000,0000,,$lnum\n";
  $lnum=$lnum+1;
 }
}
close(ASS);
$lnum = $lnum-1;
print "$lnum lines processed, all done.\n";

