Skip to content

Instantly share code, notes, and snippets.

@mnn
Created January 2, 2022 18:25
Show Gist options
  • Save mnn/d616693a74cae76f15c779a72c4e4661 to your computer and use it in GitHub Desktop.
Save mnn/d616693a74cae76f15c779a72c4e4661 to your computer and use it in GitHub Desktop.

Revisions

  1. mnn created this gist Jan 2, 2022.
    52 changes: 52 additions & 0 deletions auto_vid_conv.raku
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    #!/usr/bin/env raku

    =begin pod
    =NAME auto_vid_conv
    =VERSION 1.0.0
    =head1 DESCRIPTION
    Scans current working directory and converts all unconverted mp4 files to specified resolution (e.g. 240p).
    Converted files are detected by a prefix (e.g. C<240_>).
    Dependencies:
    =item ffmpeg
    =AUTHOR monnef
    =LICENSE GPLv3
    =end pod

    # config
    my $PREFIX = "240_";
    my $RES_HEIGHT = 240;
    my $RES_WIDTH = 428;
    my $RES_BITRATE = "750k";
    my $RES_MIN_BITRATE = "400k";
    my $RES_MAX_BITRATE = "1000k";
    my $BUF_SIZE = "1500k";
    # config END

    say "Starting [auto_vid_conv] by *monnef*.";

    my @files = dir(test => { .IO.f && /:i '.' mp4 $/ }).map({ .IO.path }).sort;
    say "All mp4 files ({ @files.elems }): " ~ @files.map({ .raku }).join(", ");
    my @valid_files = @files.grep({ !/^ $PREFIX/ }).grep({ @files ($PREFIX ~ $_) });
    say "Valid files ({ @valid_files.elems }): " ~ @valid_files.map({ .raku }).join(", ");

    my @files_with_errors;
    for @valid_files.kv -> $i, $f {
    my $new_name = $PREFIX ~ $f;
    say("\n>> Processing file { $i + 1 }/{ @files.elems }: { $f.raku } -> { $new_name.raku }\n");
    my $cmd = "ffmpeg -i \"$f\" -preset slow -codec:a aac -b:a 128k -codec:v libx264 -pix_fmt yuv420p -b:v $RES_BITRATE -minrate $RES_MIN_BITRATE -maxrate $RES_MAX_BITRATE -bufsize $BUF_SIZE -vf \"scale=h={ $RES_WIDTH }:w={ $RES_HEIGHT }:force_original_aspect_ratio=decrease,crop='iw-mod(iw\,2)':'ih-mod(ih\,2)'\" \"$new_name\"";
    say("Running command: $cmd");
    my $res = shell($cmd);
    $res.Bool unless @files_with_errors.push($f);
    say("\n<< end of processing of { $f.raku }\n");
    }

    if @files_with_errors {
    say("Completed run with ERRORS during processing of: " ~ @files_with_errors.map({ .raku }).join(", "));
    exit(1);
    } else {
    say("Finished successfully.");
    }