<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';
global $pdo;

echo "<h1>视频格式检查</h1>";

$stmt = $pdo->prepare("SELECT video_id, video_name, storage_path, file_name, duration, is_active FROM video_assets WHERE video_type='opening' ORDER BY created_at DESC LIMIT 5;");
$stmt->execute();
$videos = $stmt->fetchAll(PDO::FETCH_ASSOC);

$isSecure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
$scheme = $isSecure ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$scriptDir = dirname(dirname($_SERVER['PHP_SELF']));
$scriptDir = str_replace('\\', '/', $scriptDir);
if ($scriptDir === '/' || $scriptDir === '\\') {
    $scriptDir = '';
}
$baseUrl = $scheme . '://' . $host . $scriptDir;

echo "<h2>当前站点信息</h2>";
echo "<p>HTTP_HOST: " . $host . "</p>";
echo "<p>Base URL: " . $baseUrl . "</p>";

echo "<table border='1' cellpadding='10'>";
echo "<tr><th>名称</th><th>时长</th><th>文件大小</th><th>MIME类型</th><th>文件头</th><th>测试播放</th></tr>";

foreach ($videos as $video) {
    $filePath = __DIR__ . '/' . $video['storage_path'] . $video['file_name'];
    $fileExists = file_exists($filePath);
    
    $mime = '未知';
    $fileHeader = '未知';
    $fileSize = '0';
    
    if ($fileExists) {
        $fileSize = filesize($filePath);
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($filePath);
        
        $handle = fopen($filePath, 'rb');
        if ($handle) {
            $fileHeader = bin2hex(fread($handle, 16));
            fclose($handle);
        }
        
        $relativeUrl = $video['storage_path'] . $video['file_name'];
        $playUrl = $baseUrl . '/' . $relativeUrl;
    }
    
    echo "<tr>";
    echo "<td>" . $video['video_name'] . "</td>";
    echo "<td>" . $video['duration'] . "秒</td>";
    echo "<td>" . ($fileSize > 0 ? round($fileSize / 1024 / 1024, 1) . 'MB' : '0') . "</td>";
    echo "<td>" . $mime . "</td>";
    echo "<td>" . $fileHeader . "</td>";
    echo "<td>";
    if ($fileExists) {
        echo "<a href='" . $playUrl . "' target='_blank'>直接访问</a><br>";
        echo "<video width='300' controls>";
        echo "<source src='" . $relativeUrl . "' type='video/mp4'>";
        echo "浏览器不支持";
        echo "</video>";
    } else {
        echo "<span style='color:red'>文件不存在</span>";
    }
    echo "</td>";
    echo "</tr>";
}

echo "</table>";

echo "<h2>常见问题排查</h2>";
echo "<h3>1. 视频编码检查</h3>";
echo "<p>浏览器支持的视频编码：</p>";
echo "<ul>";
echo "<li><strong>H.264 + AAC</strong> (MP4容器) - 所有浏览器支持</li>";
echo "<li><strong>VP8/VP9 + Opus</strong> (WebM容器) - Chrome/Firefox支持</li>";
echo "<li><strong>H.265/HEVC</strong> - 仅Safari和部分浏览器支持</li>";
echo "</ul>";

echo "<h3>2. 文件头检查</h3>";
echo "<p>MP4文件的文件头通常以：0000001866747970 开头</p>";
echo "<p>如果文件头不是这样，可能是文件损坏或编码问题</p>";

echo "<h3>3. 如果视频无法播放</h3>";
echo "<ul>";
echo "<li>尝试用其他播放器（如VLC）打开视频文件，确认文件是否完整</li>";
echo "<li>检查视频编码是否为H.264（推荐使用MediaInfo工具）</li>";
echo "<li>尝试转换视频格式：使用ffmpeg转换为H.264编码</li>";
echo "</ul>";
?>
