Converting h.265 (HEVC) to h.264 (AVC)

Quick techie entry for anyone using the newer h265 codecs but unable to use them in players. (eg: Torrenting H265 encoded files then trying to play via PLEX and Roku)

Roku and other media players don’t support h.265 and as such any attempt to play h265 encoded files will result in an ‘Unable to play file’ error, so you might be wanting to convert the files to another format such as h.264.  To do this you need ffmpeg, however ffmpeg can be a little difficult to work, especially as it has so many options, so I wrote a little perl script to ‘mass convert’ all files in the current directory if they are h265 encoded to h264 encoding.  It is published here for those on UNIX systems (or those who know how to install Perl on Windows) to make life a little easier:


use strict;
use warnings;

open DIR, "ls -1 |";
while (<DIR>)
        next if ( -d "$_"); # skip directories
        next unless ( -r "$_"); # if it's not readable skip it!
        my $file = $_;
        open PROBE, "ffprobe -show_streams -of csv '$file' 2>/dev/null|" or die ("Unable to launch ffmpeg for $file! ($!)");
        my ($v, $a, $s, @c) = (0,0,0);
        while (<PROBE>)
                my @streaminfo = split(/,/, $_);
                push(@c, $streaminfo[2]) if ($streaminfo[5] eq "video");
                $a++ if ($streaminfo[5] eq "audio");
                $s++ if ($streaminfo[5] eq "subtitle");
        close PROBE;
        $v = scalar @c;
        if (scalar @c eq 1 and $c[0] eq "ansi")
                warn("Text file detected, skipping...\n");
        warn("$file: Video Streams: $v, Audio Streams: $a, Subtitle Streams: $s, Video Codec(s): " . join (", ", @c) . "\n");
        if (scalar @c > 1)
                warn("$file has more than one video stream, bailing!\n");
        if ($c[0] eq "hevc")
                warn("HEVC detected for $file ...converting to AVC...\n");
                system("mkdir -p h265");
                my @params = ("-hide_banner", "-threads 2");
                push(@params, "-map 0") if ($a > 1 or $s > 1 or $v > 1);
                push(@params, "-c:a copy") if ($a);
                push(@params, "-c:s copy") if ($s);
                push(@params, "-c:v libx264 -pix_fmt yuv420p") if ($v);
                if (system("mv '$file' 'h265/$file'"))
                        warn("Error moving $file -> h265/$file\n");
                if (system("ffmpeg -xerror -i 'h265/$file' " . join(" ", @params) . " '$file' 2>/dev/null"))
                        warn("FFMPEG ERROR.  Cannot convert $file restoring original...\n");
                        system("mv 'h265/$file' '$file'");
        } else {
                warn("$file doesn't appear to need converting... Skipping...\n");
close DIR;


Leave a Reply