#!/usr/bin/perl -w
# m4p2mp3 - helper to turn an iTunes protected m4p to an mp3
# you need to have run FairKeys, and have mono and DeDRMS.exe available.
# created by scruss on 02004/12/18
# RCS/CVS: $Id: m4p2mp3,v 1.2 2004/12/19 04:31:46 scruss Exp $

use strict;
use File::Basename;
use File::Copy;
use String::ShellQuote;

# Things you will need to edit:

# where the DeDRMS.exe executable lives:
my $dedrms = '/home/scruss/DeDRMS.exe';

# 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 --preset medium --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 $m4pfile = $ARGV[0];
my $base    = basename( $m4pfile, '.m4p' );
my %faadinfo;

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

# DeDRMS writes files in place, so create a correctly-named copy first
copy( $m4pfile, $m4afile );
system( 'mono', $dedrms, $m4afile );    # decrypt it

# get M4A tag information from faad
my $qm4afile = shell_quote($m4afile);
open( FAADINFO, "faad -i $qm4afile 2>&1 1>/dev/null |" ) or die "$!\n";
while (<FAADINFO>) {
    chomp;
    next unless (/^(\w+):\s+(.*)/);
    $faadinfo{$1} = $2;                 # build a hash of tag-value pairs
}
close(FAADINFO);

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

# fudge iTunes genres to ID3V2 - will need work
$faadinfo{'genre'} =~ s/Spoken Word/Speech/;

# 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\}/$faadinfo{'track'}/g;
$mp3cmd =~ s/\{genre\}/shell_quote($faadinfo{'genre'})/eg;
my ($year) = $faadinfo{'date'} =~ /^(\d{4})/;
$mp3cmd =~ s/\{year\}/$year/eg;
$mp3cmd =~ s/\{wavfile\}/shell_quote($wavfile)/eg;
$mp3cmd =~ s/\{mp3file\}/shell_quote($mp3file)/eg;
system($mp3cmd);    # create the mp3

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

