#!/usr/bin/perl

# (c) G. Finch (salsaman)

# released under the GNU GPL 3 or later
# see file COPYING or www.gnu.org for details

#######################################################################
# LiVES pdf plugin v1.0

# version 1.0 original - salsaman
# version 1.1 - add support for png, correct requires error text

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

if (!defined($standalone)) {
    my $smogrify=`which smogrify`;
    chomp($smogrify);
    require $smogrify;
}
else {
    $command=$ARGV[0];
}


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


if ($command eq "version") {
    print "pdf encoder plugin v1.1\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("gs") eq "") {
	print "Ghostscript was not found. Please install ghostscript 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 "4\n";
    exit 0;
}



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

   # audio types are: 0 - cannot encode audio, 1 - can encode using
    #  mp3, 2 - can encode using pcm, 3 - can encode using pcm and mp3
    
    print "pdf|pdf|0|none|pdf|\n";
    exit 0;
}



if ($command eq "encode") {
    # encode 
    for ($i=$start;$i<=$end;$i++) {
	$name=&mkname($i);
	`convert $name$img_ext $name.pdf`;
    }
    $syscom="gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=\"$nfile\" *.pdf";

    if (defined($DEBUG_ENCODERS)) {
	print STDERR "Debug: pdf_encoder 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
    chdir $curtmpdir;

    for ($i=$start;$i<=$end;$i++) {
	$name=&mkname($i);
	if (-f "$name.pdf") {
	    unlink "$name.pdf";
	}
    }
    &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 0; # clipped wav, clipped frames
}

