<?php
setlocale(LC_CTYPE, "pl_PL.UTF-8", "en_US.UTF-8", "C.UTF-8");
require_once 'functions.php';
checkAuth();

// Zwalnia sesję, abyś mógł otwierać inne karty
session_write_close();

$cfg = cfg();
$folderKey = $_GET['folder'] ?? '';
$subPath = $_GET['path'] ?? '';
$fileName = $_GET['file'] ?? '';
$start = isset($_GET['start']) ? floatval($_GET['start']) : 0;

if (!isset($cfg['allowedFolders'][$folderKey])) die('Odmowa dostępu.');
$basePath = '/mnt/mega' . $cfg['allowedFolders'][$folderKey];
$filePath = rtrim($basePath . '/' . $subPath, '/') . '/' . $fileName;

if (!file_exists($filePath)) die('Plik nie istnieje.');

header("Content-Type: video/mp4");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
header("X-Accel-Buffering: no");

while (ob_get_level()) ob_end_clean();
ignore_user_abort(true);

$startParam = $start > 0 ? "-ss " . escapeshellarg($start) : "";

$logFile = __DIR__ . '/data/ffmpeg_error.log';

$cmd = "/usr/bin/ffmpeg -hide_banner -loglevel warning $startParam -i " . escapeshellarg($filePath) . " -map 0:v:0 -map 0:a:0? -c:v libx264 -pix_fmt yuv420p -preset ultrafast -crf 28 -maxrate 3000k -bufsize 6000k -c:a aac -b:a 128k -threads 2 -f mp4 -movflags frag_keyframe+empty_moov+default_base_moof pipe:1";

$descriptorspec = [
    0 => ["pipe", "r"],
    1 => ["pipe", "w"],
    2 => ["file", $logFile, "w"]
];

$process = proc_open($cmd, $descriptorspec, $pipes);

if (is_resource($process)) {
    fclose($pipes[0]);

    while (!feof($pipes[1])) {
        $data = fread($pipes[1], 8192);
        if ($data === false || strlen($data) === 0) break;
        echo $data;
        @ob_flush();
        flush();
        
        if (connection_aborted()) break;
    }
    
    fclose($pipes[1]);
    proc_terminate($process, 9);
    proc_close($process);
}
?>
