#!/usr/bin/env perl

use strict;
use warnings;

my $filename = shift;
my $arrayname = shift;
my $track = shift;
my @timestamps;
my @hashes;
my @durations;
my @widths;
my @heights;
my @pixfmts;
my @keyframes;
my $ticks = 1;
my $frames = 0;

if (!defined($filename) || !defined($arrayname) || !defined($track)) {
    print("Usage: gendata [filename] [arrayname] [track] > output.cpp\n");
    exit(0);
}

my $version = "Unknown";

for (`ffmpeg -version 2>&1`) {
    chomp;
    s/^(ffmpeg version .+) Copyright.+/$1/;
    $version = $_;
    last;
}

print("// Autogenerated from $filename by gendata with $version\n\n");
print("#ifndef _FFMS_TEST_".uc($arrayname)."_H\n");
print("#define _FFMS_TEST_".uc($arrayname)."_H\n\n");
print("#include \"data.h\"\n\n");

for (`ffmpeg -i $filename -map $track:0 -f framehash - 2>/dev/null`) {
    if (/^#/) {
        if (!/^#tb/) {
            next;
        }
        chomp;
        s/^#tb \d: //;
        my @tb = split('/');
        $ticks = int($tb[0]);
        next;
    }
    chomp;
    s/\s//g;
    my @fields = split(',');
    push(@hashes, $fields[5]);
    $frames++;
}

for (`ffprobe -show_frames -select_streams $track $filename 2>/dev/null`) {
    chomp;

    if (/^width/) {
        my @w = split('=');
        push(@widths, int($w[1]));
    } elsif (/^height/) {
        my @h = split('=');
        push(@heights, int($h[1]));
    } elsif (/^pix_fmt/) {
        my @p = split('=');
        push(@pixfmts, $p[1]);
    } elsif (/^key_frame/) {
        my @k = split('=');
        push(@keyframes, (int($k[1]) == 1 ? "true" : "false"));
    } elsif (/^pts=/) {
        my @t = split('=');
        push(@timestamps, int($t[1]));
    } elsif (/^duration=/) {
        my @d = split('=');
        push(@durations, int($d[1]));
    } else {
        next;
    }
}

print("const TestFrameData $arrayname\[$frames] = {\n");

for (my $i = 0; $i < $frames; $i++) {
    print("    { $timestamps[$i], $durations[$i], $widths[$i], $heights[$i], \"$pixfmts[$i]\", $keyframes[$i], {");

    my $hash = $hashes[$i];
    $hash =~ s/(..)/ 0x\U$1,/g;
    $hash =~ s/,$//;
    print($hash);

    print(" } }");

    if ($i != $frames - 1) {
        print(",");
    }

    print("\n");
}

print("};\n\n");
print("#endif // _FFMS_TEST_".uc($arrayname)."_H\n");
