<?php
include "config.php";

ini_set("default_socket_timeout", 10);

echo "StreamURL: ".$StreamURL."\n";
echo "DiscordWebhook: ".$DiscordWebhook."\n";

$lastOnlineTime = 0;

while(TRUE)
{
    if(($lastOnlineTime + 60) < time())
    {
        $fileName = "output-".md5(time().rand(11111,99999)).".gif";
        $videoFileName = md5(time().rand(11111,99999)).".mp4";

        echo "Checking stream and creating image...\n";
        //system("ffmpeg -i ".$StreamURL." -vframes 1 -q:v 2 -vf scale=535:346 ".$fileName);   
        system('ffmpeg -r 90 -t 4 -i '.$StreamURL.' -vf "fps=10,scale=350:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -loop 0 '.$fileName);

        if(is_file($fileName))
        {
            $lastOnlineTime = time();

            copy($fileName, "tmp/rtmp/".$fileName);
            unlink($fileName);

            $jsonStartMessage = file_get_contents("startMessage.json");
            $jsonEndMessage = file_get_contents("endMessage.json");
 
            $jsonStartMessage = str_replace("%%adresse%%", $StreamURL, $jsonStartMessage);
            $jsonStartMessage = str_replace("%%vorschau%%", "https://files.clatza.dev/tmp/rtmp/".$fileName, $jsonStartMessage);

            $startOptions = [
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/json',
                    'timeout' => 5,
                    'content' => $jsonStartMessage
                ]
            ];

            $endOptions = [
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/json',
                    'timeout' => 5,
                    'content' => $jsonEndMessage
                ]
            ];

            echo "Sending start info to discord...";
            $result = file_get_contents($DiscordWebhook, false, stream_context_create($startOptions));
            echo "done.\n";

            $lastOnlineTime = time();
            system("rtmpdump -r ".$StreamURL." -m 15 -o /dev/null");

            if(($lastOnlineTime + 10) < time())
            {
                echo "Sending end info to discord...";
                $result = file_get_contents($DiscordWebhook, false, stream_context_create($endOptions));
                echo "done.\n";
            }else{
                $lastOnlineTime = $lastOnlineTime + 3600;
            }
        }else{
            echo "ERROR: Image not generated!\n";
        }
    }else{
        echo "Wait for next check ... ( ".(($lastOnlineTime + 60) - time()).")\n";
        sleep(5);
    }
}

?>