#!/usr/bin/perl

#######################################################################
# LiVES noisify plugin v0.1

# rendered plugins should accept:
# <plugin_name> version (return <plugin_name> version <version>)
# <plugin_name> get_capabilities
# <plugin_name> get_description (e.g. "Edge detect|Edge detecting|1|1|")
# and optionally any of: 
# <plugin_name> get_parameters
# <plugin_name> get_param_window
# <plugin_name> get_onchange
# <plugin_name> onchange_<when> (for any triggers, e.g. onchange_init)
#
# they must accept:
# <plugin_name> process <parameters>

# You should not skip any frames, if a frame is not changed you must do:
# `cp $in $out`
#
# for *non-Perl* plugins, LiVES will call:
# <plugin_name> process "<dir>" <in_ext> <out_ext> <start> <end>
#  <width> <height> <parameters>
# first you should chdir to <dir>
# then you should create all output frames %8d$out_ext in numerical 
# from start to end inclusive,
# each time calling sig_progress (see smogrify) - writes current frame number to 
# <dir>/.status
# and checking for pause
#
# Any errors should be transmitted as in sig_error - 
# write "error|msg1|msg2|msg3|" to <dir>/.status
# msgn must not contain "\n", but can be omitted

# output frames should be named %8d$out_ext in the same directory
# after processing, you should leave no gaps in out frames, you should not resize
# or change the palette from RGB24 (LiVES will check and autocorrect this soon)

# Also you must implement your own: &sig_error and &sig_progress


#######################################################################

my $command=$ARGV[0];

if ($command eq "get_capabilities") {
    # capabilities is a bitmap field
    # 0x0001 == slow (hint to GUI)
    # 0x0002 == may resize (all frames to  x )
    # 0x8000 == reserved
    print "32769\n";
    exit 0;
}

if ($command eq "version") {
    print "noisify version 0.3 : builder version 0.9.5\n";
    exit 0;
}

if ($command eq "get_description") {
    #format here is "Menu entry|Action description|min_frames|script_file_name|"
    # min_frames==-1 indicates a special "no processing" effect. This allows more
    #general parameter windows which are not really effects (e.g. frame_calculator)
    print "Noisify|Adjusting noise on|1|1||\n";
    exit 0;
}


if ($command eq "get_parameters") {
    # "name|group|type|default|min|max|"
    # eg. print "Radius|0|num0|1|1|100|";
    # types can be numx,colRGB24,bool,string or string_list
    print "Add noise|1|bool|1|\n";
    print "Reduce noise|1|bool|0|\n";
    print "|2|bool|0|\n";
    print "every|0|num0|1|1|10000|\n";
    print "Noise type|0|string_list|Impulse|Uniform|Gaussian|Multiplicative|Impulse|Laplacian|Poisson|\n";
    print "Reduction radius|0|num0|1|1|10000|\n";
    print "|0|bool|0|\n";
    print "every|0|num0|1|1|10000|\n";
    print "|2|bool|1|\n";
    print "Constant noise level|0|num0|1|1|50|\n";
    exit 0;
}

if ($command eq "get_param_window") {
    print "layout|p1|fill|p5||\n";
    print "layout|p9|p10||\n";
    print "layout|p3|\"Increase noise\"|p4|\"frame(s)\"||\n";
    print "layout|hseparator||\n";
    print "layout|p2|fill|p6||\n";
    print "layout|p7|\"Decrease noise\"|p8|\"frame(s)\"||\n";
    exit 0;
}

if ($command eq "get_onchange") {
    print "init|\n";
    exit 0;
}

#######################################################

if ($command eq "process") {

# in case of error, you should do:
# &sig_error("msg1","msg2","msg3","msg4"); [ msg's are optional, but must not
# contain newlines (\n) ]

    $livesexitcode=1;
    $SIG{'HUP'}="dopost";

##### check requirements first #######
    if (&location("convert") eq "") {
      &sig_error("You must install 'convert' before you can use this effect.");
    }

###### handle parameters #############
# autogenerated from get_parameters

    unless (defined($ARGV[1])) {
      $p1=1;
    }
    else {
      $p1=$ARGV[1];
    }
    unless (defined($ARGV[2])) {
      $p2=0;
    }
    else {
      $p2=$ARGV[2];
    }
    unless (defined($ARGV[3])) {
      $p3=0;
    }
    else {
      $p3=$ARGV[3];
    }
    unless (defined($ARGV[4])) {
      $p4=1;
    }
    else {
      $p4=$ARGV[4];
    }
    unless (defined($ARGV[5])) {
      $p5="Impulse";
    }
    else {
      $p5=$ARGV[5];
    }
    unless (defined($ARGV[6])) {
      $p6=1;
    }
    else {
      $p6=$ARGV[6];
    }
    unless (defined($ARGV[7])) {
      $p7=0;
    }
    else {
      $p7=$ARGV[7];
    }
    unless (defined($ARGV[8])) {
      $p8=1;
    }
    else {
      $p8=$ARGV[8];
    }
    unless (defined($ARGV[9])) {
      $p9=1;
    }
    else {
      $p9=$ARGV[9];
    }
    unless (defined($ARGV[10])) {
      $p10=1;
    }
    else {
      $p10=$ARGV[10];
    }
    $p1=~(~$p1);
    $p2=~(~$p2);
    $p3=~(~$p3);
    $p4=int($p4*1+.5)/1;
    if ($p4<1) {
       &sig_error("every must be >= 1");
    }
    if ($p4>10000) {
       &sig_error("every must be <= 10000");
    }
    $p6=int($p6*1+.5)/1;
    if ($p6<1) {
       &sig_error("Reduction radius must be >= 1");
    }
    if ($p6>10000) {
       &sig_error("Reduction radius must be <= 10000");
    }
    $p7=~(~$p7);
    $p8=int($p8*1+.5)/1;
    if ($p8<1) {
       &sig_error("every must be >= 1");
    }
    if ($p8>10000) {
       &sig_error("every must be <= 10000");
    }
    $p9=~(~$p9);
    $p10=int($p10*1+.5)/1;
    if ($p10<1) {
       &sig_error("Constant noise level must be >= 1");
    }
    if ($p10>50) {
       &sig_error("Constant noise level must be <= 50");
    }

    $noise="noise";
    if ($p1) {
       $pre="+";
       $ntype="$p5";
    }
    elsif ($p2) {
       $pre="-";
       $ntype="$p6";
    }
    $param=" $pre$noise $ntype ";
    $nstep=1;
    $fstep=1;
    if ($p3) {
       $nadd="$p4";
    }
    elsif ($p7) {
       $nadd="$p7";
    }
    else {
       $nadd=1;
    }
    if ($p9) {
       $cnl="$p10";
    }
    else {
       $cnl=1;
    }

################# loop through frames #################
    for ($frame=$start;$frame<=$end;$frame++) {
	# sig progress will update the progress bar from $start->$end
	&sig_progress($frame);
	$name=&mkname($frame);
	$in="$name$img_ext";
	$out="$name.mgk";

##################### the all-important bit #######################

        if ($p3||$p7) {
           if ($nstep==$fstep) {
              if ($nstep <= 50) {
                 $totnoise=$param x $nstep;
              }
              else {
                  $totnoise=$param x 50;
              }
              $nstep+=$nadd;
           }
        }
        else {
           $totnoise=$param x $cnl;
        }
        `$convert_command $in $totnoise $out`;
        $fstep++;

###################################################################
        if (! -f $out) {
            print "Warning: effect plugin noisify skipped frame $frame !";
            `cp $in $out`;
        }
    }
    $livesexitcode=0;
    &dopost;
    return 1;
}



########## Post loop code ############
sub dopost {
    if ($livesexitcode) {
        exit $livesexitcode;
    }
}

########## Triggers ############

if ($command eq "onchange_init") {
    $p1=@ARGV[1];
    $p2=@ARGV[2];
    $p3=@ARGV[3];
    $p4=@ARGV[4];
    $p4_min=@ARGV[5];
    $p4_max=@ARGV[6];
    $p5=@ARGV[7];
    $p6=@ARGV[8];
    $p6_min=@ARGV[9];
    $p6_max=@ARGV[10];
    $p7=@ARGV[11];
    $p8=@ARGV[12];
    $p8_min=@ARGV[13];
    $p8_max=@ARGV[14];
    $p9=@ARGV[15];
    $p10=@ARGV[16];
    $p10_min=@ARGV[17];
    $p10_max=@ARGV[18];
    $width=@ARGV[19];
    $height=@ARGV[20];
    $start=@ARGV[21];
    $end=@ARGV[22];
    $last=@ARGV[23];
    $length=$end-$start+1;

    $p9=1;
    $p5=~ s/\"/\\\"/g;

    print "$p1 $p2 $p3 $p4 $p4_min $p4_max \"$p5\" $p6 $p6_min $p6_max $p7 $p8 $p8_min $p8_max $p9 $p10 $p10_min $p10_max ";
    exit 0;
}
