#!/usr/bin/perl -w
# id32xspf - create XSPF playlist to stdout from a list of MP3s with ID3v2 tags
# created by scruss on 02007/02/17 - scruss.com

use strict;
use Getopt::Long;
use MP3::Info;
use XML::XSPF;
use XML::XSPF::Track;

my $xspf = XML::XSPF->new;
my @tracks;    # to hold each track object

# some helpful(?) defaults ...
my $title   = 'The Unnamed Tracklist';
my $creator = 'Jabez S. Elkins';
my $urlbase = 'file:///';              # FIXME (maybe) - unlikely to always work

# command line options - can use either long or single character options
GetOptions(
    'title=s'   => \$title,      # -t = playlist title
    'creator=s' => \$creator,    # -c = playlist author
    'urlbase=s' => \$urlbase     # -u = base URL of files - needs trailing /
);

foreach my $file (@ARGV) {

    # NB: uses ID3v2; will fail otherwise.
    my $tag = get_mp3tag( $file, 2 ) or die "No TAG info for $file\n";
    my $info  = get_mp3info($file);      # get file stats (used for length info)
    my $track = XML::XSPF::Track->new;

    # specify file location
    $track->location( $urlbase . $file );

    # fill in as much info from the ID3 tag as XSPF supports
    $track->title( $tag->{TITLE} )        if ( $tag->{TITLE} );
    $track->creator( $tag->{ARTIST} )     if ( $tag->{ARTIST} );
    $track->album( $tag->{ALBUM} )        if ( $tag->{ALBUM} );
    $track->annotation( $tag->{COMMENT} ) if ( $tag->{COMMENT} );

    $track->duration(
        int( 1000 * ( 60 * $info->{MM} + $info->{SS} ) + $info->{MS} ) );

    push @tracks, $track;
}
$xspf->trackList(@tracks);    # specify tracks as contents of array
$xspf->title($title);
$xspf->creator($creator);
print $xspf->toString;        # write out XSPF XML
exit;
