#!/usr/bin/perl

#######################################################################
# LiVES photo_still plugin, version 2
# Compiled with Builder version 3.2.0
# autogenerated from script by Salsaman|

# rendered plugins should accept:
# <plugin_name> version (return <plugin_name> version <version>)
# <plugin_name> get_define
# <plugin_name> get_capabilities
# <plugin_name> get_description (e.g. "Edge detect|Edge detecting|1|1|")
# <plugin_name> clear (clean up any plugin generated temp files)
# 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 [<in2_prefix> [<in_prefix>]] <out_prefix> <out_ext> <start> <end>
#  <width> <height> <img_ext> <fps> [<img2_ext> <start2> <handle2>]  <parameters>
# you should create all output frames $out_prefix%08d$out_ext in numerical 
# from start to end inclusive,
# using $in_prefix%08d$in_ext and $in2_prefix%08d$img2_ext as applicable.
# in / out images are in current dir, In2 images can be located in ../handle2 and numbered from 
# Each time calling sig_progress (see smogrify) - writes current frame number to 
# <dir>/.status
# and checking for pause (test for a file of that name in current dir - if present just sleep until deleted)
#
# Any errors - 
# write "error|msg1|msg2|msg3|" to .status
# msgn must not contain "\n", but can be omitted

# 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


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

use POSIX;
setlocale(LC_NUMERIC, "C");

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 )
    # 0x0004 == block mode generator
    # 0x8000 == reserved
    print "32768\n";
    exit 0;
}

if ($command eq "version") {
    print "photo_still version 2 : builder version 3.2.0\n";
    exit 0;
}

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

if ($command eq "get_description") {
    #format here is "Menu entry|Action description|min_frames|number_of_in_channels|"
    # 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 "Photo/still|Photo/still|1|1|\n";
    exit 0;
}


if ($command eq "get_parameters") {
    # "name|label|type|other fields..."
    # eg. print "radius|_radius|num0|1|1|100|";
    # types can be numx, colRGB24, bool, string or string_list
    print "flash|_Flash for|num0|6|0|100|\n";
    print "hold|_Hold for|num0|100|1|10000|\n";
    print "fcol|Flash _colour|colRGB24|255|255|255|\n";
    print "bw|_Black and white camera|bool|1|\n";
    exit 0;
}

if ($command eq "get_param_window") {
    print "layout|p0|\"frames\"|fill||\n";
    print "layout|p2||\n";
    print "layout|p1|\"frames\"|fill||\n";
    exit 0;
}

if ($command eq "get_onchange") {
    print "init|\n";
    print "0|\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) ]

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

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

    unless (defined($ARGV[1])) {
      $p0 = 6;
    }
    else {
      $p0 = $ARGV[1];
    }
    unless (defined($ARGV[2])) {
      $p1 = 100;
    }
    else {
      $p1 = $ARGV[2];
    }
    unless (defined($ARGV[3])) {
      $p2 = 255;
    }
    else {
      $p2 = $ARGV[3];
    }
    unless (defined($ARGV[4])) {
      $p3 = 1;
    }
    else {
      $p3 = $ARGV[4];
    }
    $! = 0;
    if ($p0 >= 0) {
        $p0 = int(POSIX::strtod($p0) * 1 + .5) / 1;
    } else {
        $p0 = int(POSIX::strtod($p0) * 1 - .5) / 1;
    }
    if ($p0 < 0) {
       &sig_error("flash must be >= 0");
       exit 1;
    }
    if ($p0 > 100) {
       &sig_error("flash must be <= 100");
       exit 1;
    }
    $! = 0;
    if ($p1 >= 0) {
        $p1 = int(POSIX::strtod($p1) * 1 + .5) / 1;
    } else {
        $p1 = int(POSIX::strtod($p1) * 1 - .5) / 1;
    }
    if ($p1 < 1) {
       &sig_error("hold must be >= 1");
       exit 1;
    }
    if ($p1 > 10000) {
       &sig_error("hold must be <= 10000");
       exit 1;
    }
    $p3 = ~(~$p3);
    $p2 = int($p2);
    if ($p2 > 0xFFFFFF || $p2 < 0) {
        &sig_error("Invalid colour for fcol.");
        exit 1;
    }
    $p2_red = int($p2 / 65536);
    $p2 -= $p2_red * 65536;
    $p2_green = int($p2 / 256);
    $p2 -= $p2_green * 256;
    $p2_blue = $p2;
    if ($img_ext eq ".png") {
        $img_prefix = "PNG32:";
    } else {
        $img_prefix = "";
    }

    if ($out_ext eq ".png") {
        $out_prefix = "PNG32:";
    } else {
        $out_prefix="";
    }

    #make flash frame
    $cstring=&RGB24_to_string($p2_red,$p2_green,$p2_blue);
    system("$convert_command -size $width!x$height! xc:$cstring $img_prefix"."flash$img_ext");
    
    $has_store=0;
    
    #bit of a cheat for faster finishing
    $end=$start+$p0+$p1-1;

    if ($start == 0) {$start = 1;}


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

        if (!defined($end) || $end == 0) {
            print STDERR "WARNING: generator plugin did not set $end !";
            &sig_error("Generator plugin did not set $end.");
        }
        $out = "$name$out_ext";

        # wait for front end to create 
        while (! -s $in) {
            sleep 1;
        }

        `flock $in true`;
##################### the all-important bit #######################

        $i=$frame-$start;
        
        if ($p1&&!$has_store) {
        	$has_store=1;
        	if ($p3) {
        		system("$convert_command $img_prefix$in -modulate 100,0,100 $img_prefix"."store$img_ext");
        	}
        	else {
        		`cp $in store$img_ext`;
        	}
        }
        
        #################
        
        if ($i<$p0) {
         # replace frame with flash frame
        	`cp flash$img_ext $out`;
        }
        elsif ($i<$p0+$p1) {
        	# replace with stored frame
        	`cp store$img_ext $out`;
        }
        else {
        	`cp $in $out`;
        }

###################################################################
        for (my $i = 0; $i < 5; $i++) {
            if (! -s $out) {
                sleep 1;
            }
        }

        if (! -s $out) {
            print STDERR "Warning: effect plugin photo_still skipped frame $frame !\n";
            return 1;
        }

        &sig_progress($frame);

        if ($p2_red > 255) {
            $p2_red = 255;
        }
        elsif ($p2_red < 0) {
            $p2_red = 0;
        }
        if ($p2_green > 255) {
            $p2_green = 255;
        }
        elsif ($p2_green < 0) {
            $p2_green = 0;
        }
        if ($p2_blue > 255) {
            $p2_blue = 255;
        }
        elsif ($p2_blue < 0) {
            $p2_blue = 0;
        }
        }
    return 1;
}



########## Post loop code ############
if ($command eq "clear") {
    $start = $ARGV[1];
    $end = $ARGV[2];
    $img_ext = $ARGV[3];

    unlink <"store$img_ext" "flash$img_ext">;
    exit 0;
}

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

if ($command eq "onchange_0") {
    $p0 = @ARGV[1];
    $p0_min = @ARGV[2];
    $p0_max = @ARGV[3];
    $p1 = @ARGV[4];
    $p1_min = @ARGV[5];
    $p1_max = @ARGV[6];
    $p2_red = @ARGV[7];
    $p2_green = @ARGV[8];
    $p2_blue = @ARGV[9];
    $p3 = @ARGV[10];
    $width = @ARGV[11];
    $height = @ARGV[12];
    $start = @ARGV[13];
    $end = @ARGV[14];
    $last = @ARGV[15];
    $length = $end - $start + 1;

    $p1_max=$length-$p0;

    print "$p0 $p0_min $p0_max $p1 $p1_min $p1_max $p2_red $p2_green $p2_blue $p3 ";
    exit 0;
}

if ($command eq "onchange_init") {
    $p0 = @ARGV[1];
    $p0_min = @ARGV[2];
    $p0_max = @ARGV[3];
    $p1 = @ARGV[4];
    $p1_min = @ARGV[5];
    $p1_max = @ARGV[6];
    $p2_red = @ARGV[7];
    $p2_green = @ARGV[8];
    $p2_blue = @ARGV[9];
    $p3 = @ARGV[10];
    $width = @ARGV[11];
    $height = @ARGV[12];
    $start = @ARGV[13];
    $end = @ARGV[14];
    $last = @ARGV[15];
    $length = $end - $start + 1;

    $p0_max=$length-1;$p1=$p1_max=$length-$p0;if ($p1_max<$p1_min) {$p1=$p1_max=$p1_min;}

    print "$p0 $p0_min $p0_max $p1 $p1_min $p1_max $p2_red $p2_green $p2_blue $p3 ";
    exit 0;
}
