#!/usr/bin/perl -w

use strict;
use POSIX;

my $dir = getcwd();
my ($width, $height, $length);

opendir(DIR, $dir) or die $!;

while (my $file = readdir(DIR)) {
   next unless ($file =~ m/\.mp4$/);

   my @info = `mplayer -benchmark -nosound -quiet -vo null -frames 1 -identify $file`;

   foreach (@info) {
      if (substr($_, 0, 15) eq "ID_VIDEO_WIDTH=") {
         $width = substr($_, 15);
      }
      elsif (substr($_, 0, 16) eq "ID_VIDEO_HEIGHT=") {
         $height = substr($_, 16);
      }
   elsif (substr($_, 0, 10) eq "ID_LENGTH=") {
         $length = substr($_, 10);
      }
   }

   $width = floor($width / 3);
   $height = floor($height / 3);
   my ($tile_x, $tile_y, $frame) = (6, 4, 1);
   my ($position, $files);

   while ($frame < ($tile_x * $tile_y + 1)) {
      $position = $frame * floor($length / ($tile_x * $tile_y));

      system("ffmpeg -ss $position -i $file -vcodec mjpeg -vframes 1 -s $width"."x"."$height -an -f rawvideo -y __$frame.jpg 2> /dev/null");

      $files = $files . " __$frame.jpg";

      $frame += 1;
   }

   system("montage -title \"$file\" -geometry $width"."x"."$height"."+"."1"."+"."1 -tile $tile_x"."x"."$tile_y$files $file.jpg");

   system("rm __*.jpg");
}

closedir(DIR);

