#!/usr/bin/perl -w

=head1 NAME

mc-encode - use the Media::Convert library to transcode a file from one format to another

=head1 SYNOPSIS

mc-encode --input input.mkv --output output.webm --profile webm --multipass

=cut

use strict;
use warnings;

use Media::Convert;
use Media::Convert::Asset::ProfileFactory;
use Media::Convert::Pipe;
use File::Basename qw/dirname basename/;
use Getopt::Long;
use Data::Dumper;

my $inputname;
my $outputname;
my $acopy = 0;
my $vcopy = 0;
my $multipass = 0;
my $profilename;

=head1 OPTIONS

=head2 B<--input>=FILE

Use C<FILE> as the input file to read video data from. Passed unmodified
to L<ffmpeg(1)>'s C<-i> parameter. No default; required.

=head2 B<--output>=FILE

Use C<FILE> as the output file to write the transcoded video to. Passed
unmodified to L<ffmpeg(1)> as the output file name. Default: the base
name (with whatever comes after the final dot, if anything, removed) of
the input file, supplemented with the default extension for the used
profile.

=head2 B<--acopy>

Enable the C<acopy> option to the L<Media::Convert::Pipe> being used,
which tells ffmpeg that it should not transcode the audio but just copy
it from one container to another, unmodified.

=head2 B<--vcopy>

Enable the C<vcopy> option to the L<Media::Convert::Pipe> being used,
which has the same effect to video that C<--acopy> has to audio.

=head2 B<--multipass>

Enable a 2-pass transcode.

=head2 B<--profile>

Select the profile to be used.

=cut

GetOptions("input=s" => \$inputname,
	   "output=s" => \$outputname,
	   "acopy" => \$acopy,
	   "vcopy" => \$vcopy,
	   "multipass" => \$multipass,
	   "profile=s" => \$profilename)
or die "Error in command line arguments";

die "need input filename!" unless defined($inputname);
die "need profile name!" unless defined($profilename);

sub progress {
	my $perc = shift;
	print "$outputname: $perc\%\r";
}

my $input = Media::Convert->new(url => $inputname);
my $profile = Media::Convert::Asset::ProfileFactory->create($profilename, $input);
if(!defined($outputname)) {
	$outputname = $inputname;
	$outputname =~ s/\.[^\.]*$//g;
	$outputname .= "." . $profile->exten;
}
my $output = Media::Convert->new(url => $outputname, reference => $profile);

$| = 1;

Media::Convert::Pipe->new(inputs => [$input], output => $output, acopy => $acopy, vcopy => $vcopy, multipass => $multipass, progress => \&progress)->run();

print "\n";
