#!/usr/bin/perl -w
# m4p2mp3 - helper to turn an m4a to an mp3
# needs lame for genre checking

use strict;
use File::Basename;
use File::Copy;
use String::ShellQuote;
use Data::Dumper::Simple;

# Things you will need to edit:

# your MP3 encoder of choice. Use the following tokens:
#
# {wavfile}  input wav file name
# {mp3file}  output mp3 file name
#
# and for optional ID3 tagging:
#
# {title}
# {artist}
# {album}
# {trackno}
# {genre}
# {year}
my $mp3cmd =
'lame -V2 --add-id3v2 --tt {title} --ta {artist} --tl {album} --tn {trackno} --tg {genre} --ty {year} {wavfile} {mp3file}';

#
# You probably don't need to edit anything south of here
#

my $m4afile = $ARGV[0];
my $base = basename( $m4afile, '.m4a' );
my %faadinfo;
$faadinfo{'genre'}   = '';    # default
$faadinfo{'year'}    = '';    # default
$faadinfo{'trackno'} = 1;     # default
$faadinfo{'title'}   = '';    # default
$faadinfo{'artist'}  = '';    # default
$faadinfo{'album'}   = '';    # default

# create output file names
my $wavfile = join( '.', $base, 'wav' );
my $mp3file = join( '.', $base, 'mp3' );

# get M4A tag information from faad
my $xfaadinfo = `faad -i "$m4afile" 2>&1 1>/dev/null`;
my @fi = split( "\n", $xfaadinfo );
foreach (@fi) {
    chomp;
    next unless (/^(\w+):\s+(.*)/);
    print '## ', $_, "\n";
    $faadinfo{$1} = $2;    # build a hash of tag-value pairs
}

# print Dumper(%faadinfo);
# decode the file to WAV
system( 'faad', '-o', $wavfile, $m4afile );

# fudge iTunes genres to ID3V2
my %genres;
open( GENRE, "lame --genre-list |" ) or die "$!\n";
while (<GENRE>) {
    chomp;
    s/^ *//;
    my ( $number, $genre ) = split( ' ', $_, 2 );
    $genres{$genre} = $number;
}
close(GENRE);
if ( exists( $genres{ $faadinfo{'genre'} } ) ) {
    $faadinfo{'genre'} = $genres{ $faadinfo{'genre'} };    # convert to numeric
}
else {
    $faadinfo{'genre'} = $genres{'Other'};                 # just give in ...
}

# insert tokens into mp3 encoder command string
$mp3cmd =~ s/\{title\}/shell_quote($faadinfo{'title'})/eg;
$mp3cmd =~ s/\{artist\}/shell_quote($faadinfo{'artist'})/eg;
$mp3cmd =~ s/\{album\}/shell_quote($faadinfo{'album'})/eg;
$mp3cmd =~ s/\{trackno\}/shell_quote($faadinfo{'track'})/eg;
$mp3cmd =~ s/\{genre\}/shell_quote($faadinfo{'genre'})/eg;
my ($year) = $faadinfo{'date'} =~ /(\d{4})/;
$mp3cmd =~ s/\{year\}/shell_quote($year)/eg;
$mp3cmd =~ s/\{wavfile\}/shell_quote($wavfile)/eg;
$mp3cmd =~ s/\{mp3file\}/shell_quote($mp3file)/eg;
print '%%% ', $mp3cmd, "\n";
system($mp3cmd);    # create the mp3

# clean up temporary files
unlink($wavfile);
exit;

