<?php
if(isset($_GET['url']) && isset($_GET['quality'])) {
    $url = $_GET['url'];
    $quality = $_GET['quality'];
    header('Content-Type: application/octet-stream');
    // Adjust this according to what file type you have in the ffmpeg section
    header('Content-Disposition: attachment; filename="output.mp4"');


    // Special website-specific URL handling:
    // YouTube
    if (strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false) {
        $ytDlpCmd = "/usr/local/bin/yt-dlp -q -f b -g $url";
        $ytDlpProcess = popen($ytDlpCmd, 'r');
        $newUrl = trim(fread($ytDlpProcess, 2048));
        pclose($ytDlpProcess);

        $url = $newUrl;
    }
    // TikTok
    if (strpos($url, 'vm.tiktok.com') !== false || strpos($url, 'vm.tiktxk.com') !== false) {
        if (preg_match('/vm\.tiktxk\.com\/([^\/]+)/', $url, $matches)) {
            $extractedString = $matches[1];
        }
        if (preg_match('/vm\.tiktok\.com\/([^\/]+)/', $url, $matches)) {
            $extractedString = $matches[1];
        }
        echo "$extractedString";
        $newUrl = "https://vm.tiktxk.com/" . $extractedString;
        $output = shell_exec("curl -A 'Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)' $newUrl");
        echo "$output";
        preg_match('/<meta property="og:video" content="([^"]+)"/', $output, $matches);
        if (isset($matches[1])) {
            $url = $matches[1];
        } else {
            echo "No TikTok metadata present. Invalid URL?";
            exit();
        }
    }

    // ffmpeg commands (adjust for different type of stream)
    if ($quality === 'low') {
        $cmd = "ffmpeg -re -i \"$url\" -movflags frag_keyframe+empty_moov -f mp4 -vf scale=320:240 -b:v 200K -c:v libx264 -profile:v high -preset medium -c:a libmp3lame -strict -1 -b:a 48K -";
    } elseif ($quality === 'mid') {
        $cmd = "ffmpeg -re -i \"$url\" -movflags frag_keyframe+empty_moov -f mp4 -vf scale=640:480 -b:v 500K -c:v libx264 -profile:v high -preset medium -c:a libmp3lame -strict -1 -b:a 96K -";
    } elseif ($quality === 'high') {
        $cmd = "ffmpeg -re -i \"$url\" -movflags frag_keyframe+empty_moov -f mp4 -vf scale=800:600 -b:v 800K -c:v libx264 -profile:v high -preset medium -c:a libmp3lame -strict -1 -b:a 128K -";
    } elseif ($quality === 'dbg') {
        echo "$url";
        exit();
    } else {
        echo "Invalid quality parameter provided.";
        exit();
    }

    // The part where it does the actual streaming
    $descriptors = [
        0 => ['pipe', 'r'], // STDIN
        1 => ['pipe', 'w'], // STDOUT
        2 => ['pipe', 'w']  // STDERR
    ];
    $process = proc_open($cmd, $descriptors, $pipes);

    if (is_resource($process)) {
        while ($data = fread($pipes[1], 1024)) {
            echo $data;
            ob_flush();
            flush();
        }
    }

    // Check if the process is still running and kill it if needed
    $status = proc_get_status($process);
    if ($status['running']) {
        proc_terminate($process);
    }
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
} else {
    // Error catching if user doesnt provide URL parameter
    echo "Please provide both URL and quality parameters.";
}
?>
