#!/usr/bin/perl

#######################################################################
# LiVES sswf plugin v0.6
#
#(c) G. Finch (salsaman) and Alexis Wilke
#
# Released under the GNU GPL 3 or later
# see www.gnu.org for details
#
#version 0.1 by G. Finch (salsaman)
#version 0.2 with feedback from Alexis Wilke
#version 0.3 add audio encoding, allow for non-looping (salsaman)
#version 0.4 use $encoder_command (salsaman)
#version 0.5 remember to clean up tagfile (salsaman)
#version 0.6 use ';' to separate audio rate restrictions (salsaman)
#version 0.7 add experimental support for png, add option for no-looping
#######################################################################

if (!defined($standalone)) {
    my $smogrify;
    if ($^O eq "MSWin32") {
	$smogrify="smogrify";
    }
    else {
	$smogrify=`which smogrify`;
	chomp($smogrify);
    }
    if ($smogrify ne "") {
	require $smogrify;
    }
}
else {
    $command=$ARGV[0];
}


#######################################################################
$tagfile="tags.sswf";


if ($command eq "version") {
    print "sswf encoder plugin v0.7\n";
    exit 0;
}


if ($command eq "init") {
    # perform any initialisation needed
    # On error, print error message and exit 1
    # otherwise exit 0

    if (&location("convert") eq "") {
	print "convert was not found. Please install imagemagick and try again.";
	exit 1;
    }
    
    if (&location("sswf") eq "") {
	print "sswf was not found. Please install it and try again.";
	exit 1;
    }
    
    # end init code
    print "initialised\n";
    exit 0;
}



if ($command eq "get_capabilities") {
    # return capabilities - this is a bitmap field
    # bit 0 - takes extra parameters (using RFX request)
    # bit 1 - unused
    # bit 2 - can encode png
    # bit 3 - not pure perl
    print "5\n";
    exit 0;
}



if ($command eq "get_rfx") {

    # mandatory section
    print "<define>\n";
    print "|1.7\n";
    print "</define>\n";
    
    # mandatory section
    print "<language_code>\n";
    print "0xF0\n";
    print "</language_code>\n";
	
    # optional section
    print "<params>\n";
    print "loop|_Loop the video|bool|1|0\n";
    print "</params>\n";
    
    # optional section
    print "<param_window>\n";
    print "</param_window>\n";
    
    # optional section
    print "<onchange>\n";
    print "</onchange>\n";
    
}








if ($command eq "get_formats") {
   # for each format: -
   # return format_name|display_name|audio_types|restrictions|

   # audio types are: 0 - cannot encode audio, 1 - can encode using
   #  mp3, 2 - can encode using pcm, 3 - can encode using pcm and mp3

   # restrictions: see plugins.c in LiVES

   print "swf|swf (Flash)|2|arate=5512;11025;22050;44100,asigned=signed|swf|\n";
   exit 0;
}



if ($command eq "encode") {
    # encode 
    $encode_command="sswf -c ";

    $err=">/dev/null 2>&1";
    if (defined($DEBUG_ENCODERS)) {
	$err="1>&2";
    }

    $loop=$ARGV[13];

    # make the tag file
    &maketags;

    # call sswf
    $syscom="$encode_command $tagfile -o \"$nfile\" $err";
    if (defined($DEBUG_ENCODERS)) {
	print STDERR "Encode command is: $syscom\n";
    }
    system($syscom);

    # required
    &sig_complete;
    exit 0;
}


if ($command eq "clear") {
    # this is called after "encode"
    # note that encoding could have been stopped at any time

    if (-f $tagfile) {
	unlink $tagfile;
    }

    if ($img_ext eq ".png") {
	for ($i=$start;$i<=$end;$i++) {
	    $name=&mkname($i);
	    unlink "$name.rgb.jpg";
	    unlink "$name.mask.jpg";
	}
    }

    &sig_complete;
    exit 0;
}


if ($command eq "finalise") {
    # do any finalising code

    # ...

    # end finalising code
    print "finalised\n";
    exit 0;
}


###### subroutines #######




sub get_format_request {
    # return the code for how we would like audio and video delivered
    # this is a bitmap field composed of:
    # bit 0 - unset=raw pcm audio; set=pcm audio with wav header
    # bit 1 - unset=all audio; set=clipped audio
    # bit 2 - unset=all frames; set=frames for selection only

    return 3; # clipped pcm wav, all frames
}



sub maketags {

    open OUT,"> $tagfile";
    select (OUT);

    # default stuff
    print "// encoding=\"utf-8\"\n";
    print "fill style \"fill_image\" {\n";
    print "type: \"clipped\";\n";
    print "  matrix {\n";
    print "     scale: 20.0, 20.0;\n";
    print "	    };\n";
    print "img: img;\n";
    print "};\n";
    print "edges \"img_rect\" { w + 2, 0; 0, h + 2; -w - 2, 0; 0, -h - 2; };\n";
    print "rectangle \"rect_frame\" { -1, -1, w + 1, h + 1 };\n";

    # define images
    for ($i=$start;$i<=$end;$i++) {
	# pad to %8d
	$name=&mkname($i);
	$newname="jpg".&mkname($i-$start+1);

	if ($img_ext eq ".png") {
	    `convert $name.png -quality 100 $name.rgb.jpg`;
	    `convert $name.png -alpha Extract -quality 100 $name.mask.jpg`;
	}

	print $newname."_width = $hsize;\n";
	print $newname."_height = $vsize;\n";

	if ($img_ext eq ".png") {
	    print "image \"$newname"."_img\" { jpeg: \"$name.rgb.jpg\", \"$name.mask.jpg\"; quality: 1.0 };\n";
	}
	else {
	    print "image \"$newname"."_img\" { jpeg: \"$name.jpg\"; quality: 1.0 };\n";
	}
	print "    shape \"$newname"."\" {\n";
	print "	w = $newname"."_width; h = $newname"."_height; img = $newname"."_img;\n";
	print "	rect_frame;\n";
	print "	fill_image;\n";
	print "	img_rect;\n";
	print "};\n";
    }

    #define audio
    if (-f $audiofile) {
	print "    sound \"sswf_audio\" {";
	print "	     \"$audiofile\";";
	print "      format: \"uncompressed\";";
	print "    };";
    }

    # create the sequence
    print " sequence \"main\" {\n";
    print "	frame_rate = $fps;\n";
    print "	rectangle \"screen\" { 0, 0, $hsize, $vsize };\n";
    print "	set background color { 255,255,255 };\n";

    ## set comments etc.
    print "    do action {";
    print "	    action \"push data\" {";
    print "		  string: \"/:title\";";
    print "		  string: \"$title\";";
    print "           string: \"/:author\";";
    print "		  string: \"$author\";";
    print "		  string: \"/:comment\";";
    print "		  string: \"$comment\";";
    print "		      };";
    print "	        action \"set variable\";";
    print "	        action \"set variable\";";
    print "	        action \"set variable\";";
    print "	    };";

    for ($i=1;$i<=($end-$start+1);$i++) {
	$newname="jpg".&mkname($i);
	print "	$newname"."_img;\n";
	print "     $newname;\n";
	print "	place object {\n";
	print "	  depth: $i;\n";
	print "	    obj: $newname;\n";
	print "	};\n";
	print "	show frame;\n";

	# start playing the audio right after showing frame 1
	if ($i==1&& -f $audiofile) {
	    print "	    sswf_audio;";
	    print "	    sound info {";
	    print "	      id: sswf_audio;";
	    print "	    };";
	}
    }
    if (defined ($loop)&&$loop==0) {
	print "    do action { action \"stop\"; };";
    }
    print "};\n";

    select (STDOUT);
    close OUT;
}
