#!/usr/bin/env perl
# pile of crap mp3 to ogg converter script. written as a quick n dirty replacement for
# other tools that couldn't cope with a 20,000 + list of mp3s to convert
# also doubles as a way to convert to ogg and copy tracks in proper order for my dodgy
# mp3 player which will only order play by file creation time, the bugger.
#
# the script doesn't actually trancode the music itself, it just calls mpg321 and oggenc
# so you'll need them to be installed. alter $mpgenc and $oggenc to taste. $qual is also
# used for setting the oggenc quality.

use File::Copy;

sub usage {
  print "\nUsage:\t\t$0 <source dir> <output dir>\n\n";
}

sub coder {
  my $workdir = shift;
  my $outdir = shift;
  opendir(DIR, $workdir) or &warn("Cannot open directory $workdir - $!");
  my @contents = sort readdir(DIR); # sorting the DIR for my arsey mp3 player that orders by creation time
  close(DIR);
  foreach(@contents) {
    next if ((/^\.$/) || (/^\.\.$/));
    if ((-f "$workdir/$_") && (/\.mp3$/i)) {
      my $newfile = $_;
      $newfile =~ s/\.mp3/\.ogg/i;
      if (! -e "$workdir/$newfile") {
        &info("encoding $workdir/$_ to $outdir/$newfile");
        `$mpgenc -s "$workdir/$_" | $oggenc -q$qual -o "$outdir/$newfile" -r -`
      } else {
        &warn("failed to encode $workdir/$_ to $outdir/$newfile, dest exists");
      }
    }
    if (-d "$workdir/$_") {
      &info("found directory $_ processing");
      &coder("$workdir/$_","$outdir/$_");
    }
  }
}

sub warn {
  my $warning = shift;
  print time()." WARNING: $warning\n";
}

sub info {
  my $info = shift;
  print time()." INFO: $info\n";
}
sub deslash {
  my $dir = shift;
  if ($dir =~ m/\/$/) {
    $dir =~ s/\/$//;
  }
  return($dir);
}
if ($#ARGV != 1) {
  &usage();
  exit(1);
}

my $tld = &deslash(shift); #remove trailing slashes if they are given
my $destdir = &deslash(shift);
#remove trailing slashes if they are given

local ($oggenc, $mpgenc) = ("/usr/bin/oggenc", "/usr/bin/mpg321"); #set executables
if ((! -e $oggenc) || (! -e $mpgenc)) {
  &warn("one or more of required executables not found");
}
local $qual = 0; #set ogg quality
&info("Running with options:\tsource directory=$tld dest dir=$destdir");
&coder($tld,$destdir);
&info("All done... exiting");
exit(0);




HOME