Skip to content

Instantly share code, notes, and snippets.

@RomanHargrave
Created August 28, 2020 01:30
Show Gist options
  • Select an option

  • Save RomanHargrave/a5f657894c1194787981c2ac0a57d255 to your computer and use it in GitHub Desktop.

Select an option

Save RomanHargrave/a5f657894c1194787981c2ac0a57d255 to your computer and use it in GitHub Desktop.
#!/usr/bin/rakudo
sub MAIN(
Int :$threads = 1, #= Number of parallel flac encoders to run
*@files #= List of files to process
) {
# limit threads to n <= files
my $threads_eff = $threads > @files.elems ?? @files.elems !! $threads;
my $load = floor(@files.elems / $threads_eff);
my @workloads;
for 0..($threads_eff - 1) {
@workloads.push(splice(@files, 0, $load));
}
@workloads.tail.append(@files);
my @workers = @workloads.map: -> $load {
Thread.start(
name => "FLAC encoder process",
sub {
for @$load {
my $abspath = $_.IO.resolve;
my $dir = $abspath.IO.dirname;
my $basename = $abspath.IO.basename;
my $out_name = "$dir/.__recompress__$basename";
if ($out_name.IO.e) {
unlink $out_name orelse warn "Could not unlink existing temporary file $out_name";
}
my @cmd = ('flac', '-s', '-8', $abspath, '-o', $out_name);
say @cmd;
my $result = run @cmd;
if ($result.exitcode == 0 and $out_name.IO.e) {
move $out_name, $abspath;
} else {
warn "Recompress failed for $_";
}
}
}
);
};
.finish for @workers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment