#!/usr/bin/perl

# Need to add comment tag including normalization level.


use Audio::File;
use Data::Dumper;
use utf8;
use File::Spec;
use strict;
binmode STDOUT, ':utf8';

foreach my $input (@ARGV) {
    my $str = &filestr($input);
    my @exit;

# =tagging
    my $file = Audio::File->new( "$input" );
    my %labelhash = %{$file->tag->all};
    $labelhash{"original_filename"} = $file->name();
    $labelhash{"original_filetype"} = $file->type();
    $labelhash{"genre"} = "Lecture";
    if (! $labelhash{title} ) {
	$labelhash{title} = $str->{basename};
    }
    $labelhash{"original_samplerate"} = $file->audio_properties->sample_rate();
    $labelhash{"original_channels"} = $file->audio_properties->channels();
    $labelhash{"length"} = $file->audio_properties->length();
    $labelhash{"original_bitrate"} = $file->audio_properties->bitrate();
# cut

    # DECODE
    my @playercmd = qw(mplayer -quiet -af pan=1:0.5:0.5,format=s16ne);
    push ( @playercmd, ("-ao", "pcm:file=" . $str->{mwav}, $input) );
    print "Converting $input to speex...\n";
    print "\nDecoder command:\n@playercmd\n\n";
    push(@exit, system(@playercmd));

    # RESAMPLE
    system("rm", $str->{resample});
    push(@exit, system("resample", "-to", "32000", $str->{wav}, $str->{resample}));
    system("rm", $str->{wav});

    # NORMALIZE
    push(@exit, system("normalize-audio", "-a", "-9dBFS", $str->{resample}));

    # ENCODE
    my @encodecmd=qw(nice speexenc --vbr --dtx --denoise);
# =tagging
    foreach my $key (keys %labelhash) {
	if ($labelhash{$key}) {
	    # print "$key: " . $labelhash{$key} . "\n";
	    push(@encodecmd, ("--comment", $key . "=" . $labelhash{$key}));
	}
    }
# =cut
    push(@encodecmd, ($str->{resample}, $str->{spx}) );
    print "Encoder command:\n@encodecmd\n\n";
    push(@exit, system(@encodecmd));
    system("rm", $str->{resample});
    my $sum = 0;
    foreach my $i (@exit) {
	$sum += $i;             #same as: $sum = $sum + $i
    } 
    if (! $sum) {
	print "Successful output: " . $str->{spx} . "\n\n\n";
	system("rm", $input);
    }
    print "=========================\n";
    #sleep 5;
}

# Inputs full filename path, outputs array of:
# full file path, base filename w/o extension, resample temp, normalize temp, spx file
sub filestr {
    my $input = @_[0];
    my %out;
    $out{mplayer} = $input;
    $out{mplayer} =~ s/,/\\,/g; # mplayer input with commas escaped
    my ($volume,$directory,$name) = File::Spec->splitpath($input);
    $out{basename} = $name;
    $out{basename} =~ s/\....$//; # file w/o extension
    $out{wav} = $directory . $out{basename} . ".wav"; # mplayer wav output
    $out{mwav} = $out{wav};
    $out{mwav} =~ s/,/\\,/g; # mplayer output with commas escaped
    $out{resample} = $directory . $out{basename} . "_resampled.wav"; # resampling output
    $out{spx} = $directory . $out{basename} . ".spx"; # speex output
    return \%out;
}
