<?php
/**
 * stream_proxy.php
 * Controla el proceso ffmpeg que transcodifica el stream RTSP a HLS.
 * Acciones: ?action=start|stop|status
 */

// ---- Configuracion -------------------------------------------------------
define('RTSP_URL',  'rtsp://Vanaeph:Tykun.2026@192.168.0.116:554/video');
define('HLS_DIR',   '/tmp/hls');
define('PID_FILE',  '/tmp/hls/stream.pid');
define('LOG_FILE',  '/tmp/hls/ffmpeg.log');
define('M3U8_FILE', '/tmp/hls/stream.m3u8');
// --------------------------------------------------------------------------

header('Content-Type: application/json');
header('Cache-Control: no-cache');

$action = isset($_GET['action']) ? trim($_GET['action']) : 'status';

switch ($action) {
    case 'start':
        echo json_encode(startStream());
        break;
    case 'stop':
        echo json_encode(stopStream());
        break;
    case 'status':
    default:
        echo json_encode(getStatus());
        break;
}

// ---------- helpers --------------------------------------------------------

function findFfmpegPid(): ?int {
    // pgrep -x matches only processes named exactly 'ffmpeg'
    $out = trim(shell_exec('pgrep -x ffmpeg 2>/dev/null | head -1'));
    return ($out && is_numeric($out)) ? (int)$out : null;
}

function isAlive(int $pid): bool {
    return file_exists('/proc/' . $pid);
}

function getStatus(): array {
    $pid = findFfmpegPid();
    if ($pid) {
        return ['status' => 'running', 'pid' => $pid, 'rtsp_url' => RTSP_URL];
    }
    return ['status' => 'stopped', 'pid' => null, 'rtsp_url' => RTSP_URL];
}

function killAllFfmpeg(): void {
    shell_exec('pkill -TERM -x ffmpeg 2>/dev/null');
    sleep(1);
    shell_exec('pkill -KILL -x ffmpeg 2>/dev/null');
    @unlink(PID_FILE);
}

function startStream(): array {
    // Asegurar que el directorio HLS existe
    if (!is_dir(HLS_DIR)) {
        mkdir(HLS_DIR, 0777, true);
    }

    // Si ya hay un ffmpeg corriendo, retornar su PID
    $pid = findFfmpegPid();
    if ($pid) {
        return ['status' => 'already_running', 'pid' => $pid, 'rtsp_url' => RTSP_URL];
    }

    // Limpiar PID y segmentos anteriores
    @unlink(PID_FILE);
    foreach (glob(HLS_DIR . '/*.ts') as $f) @unlink($f);
    @unlink(M3U8_FILE);

    // Lanzar en background con doble fork para desconectar de PHP/Apache
    $launchCmd = 'nohup /usr/bin/ffmpeg -rtsp_transport tcp'
        . ' -i ' . escapeshellarg(RTSP_URL)
        . ' -c:v copy -tag:v hvc1'
        . ' -f hls -hls_time 2 -hls_list_size 5 -hls_flags delete_segments'
        . ' ' . escapeshellarg(M3U8_FILE)
        . ' >' . LOG_FILE . ' 2>&1 &';
    shell_exec('/bin/sh -c ' . escapeshellarg($launchCmd) . ' </dev/null >/dev/null 2>&1');

    // Breve espera para que el proceso arranque (250ms)
    usleep(250000);
    $pid = findFfmpegPid();

    if ($pid) {
        file_put_contents(PID_FILE, $pid);
        return ['status' => 'started', 'pid' => $pid, 'rtsp_url' => RTSP_URL];
    }

    // Revisar log si fallo
    $log = file_exists(LOG_FILE) ? file_get_contents(LOG_FILE) : '';
    return ['status' => 'error', 'message' => 'No se pudo iniciar ffmpeg', 'log' => substr($log, -500), 'rtsp_url' => RTSP_URL];
}

function stopStream(): array {
    killAllFfmpeg();
    return ['status' => 'stopped', 'pid' => null];
}
