FLV (Flash Video) 格式雖漸被淘汰,但存量系統仍需處理。本文解析 FLV 檔案結構,從標頭、Tag 解析取得影片總時長 (毫秒)。
TagHeader (11 bytes) + Data + PreviousTagSize (4 bytes) TagHeader: Type(1) + DataSize(3) + Timestamp(3) + TimestampExtended(1) + StreamID(3)
<?php
class FlvParser
{
private $fp;
private $fileSize;
private $duration = 0; // 毫秒
public function getDuration(string $filePath): int
{
if (!file_exists($filePath) || !is_readable($filePath)) {
throw new InvalidArgumentException("檔案不存在或不可讀: $filePath");
}
$this->fp = fopen($filePath, 'rb');
$this->fileSize = filesize($filePath);
$this->parseHeader();
$this->parseTags();
fclose($this->fp);
return $this->duration;
}
public function getFormattedDuration(string $filePath): string
{
$ms = $this->getDuration($filePath);
return $this->formatDuration($ms);
}
private function parseHeader(): void
{
$header = fread($this->fp, 13); // 9 + 4 (PreviousTagSize0)
if (strlen($header) < 13) {
throw new RuntimeException('檔案過小,非有效 FLV');
}
// Signature: 3 bytes 'FLV'
$signature = substr($header, 0, 3);
if ($signature !== 'FLV') {
throw new RuntimeException('非 FLV 檔案 (Signature: ' . bin2hex($signature) . ')');
}
// Version: 1 byte
$version = ord($header[3]);
// Flags: 1 byte (bit 0: video, bit 2: audio)
$flags = ord($header[4]);
// DataOffset: 4 bytes big-endian
$dataOffset = $this->be2int(substr($header, 5, 4));
// 跳過到第一個 Tag (通常 DataOffset=9,PreviousTagSize0=4,共 13)
fseek($this->fp, $dataOffset, SEEK_SET);
}
private function parseTags(): void
{
while (ftell($this->fp) < $this->fileSize) {
$tagHeader = fread($this->fp, 11);
if (strlen($tagHeader) < 11) break;
$tagType = ord($tagHeader[0]); // 8=audio, 9=video, 18=script
$dataSize = $this->be2int(substr($tagHeader, 1, 3));
$timestamp = $this->be2int(substr($tagHeader, 4, 3));
$timestampExt = ord($tagHeader[7]); // 延伸時間戳 (高 8 位)
$streamId = $this->be2int(substr($tagHeader, 8, 3)); // 應為 0
$fullTimestamp = ($timestampExt << 24) | $timestamp;
// 更新最長時間戳 = 影片長度
if ($fullTimestamp > $this->duration) {
$this->duration = $fullTimestamp;
}
// 跳過 Data + PreviousTagSize
$nextPos = ftell($this->fp) + $dataSize + 4;
if ($nextPos > $this->fileSize) break;
fseek($this->fp, $nextPos, SEEK_SET);
}
}
private function be2int(string $bytes): int
{
$val = 0;
$len = strlen($bytes);
for ($i = 0; $i < $len; $i++) {
$val = ($val << 8) | ord($bytes[$i]);
}
return $val;
}
private function formatDuration(int $ms): string
{
$totalSec = intval($ms / 1000);
$h = intval($totalSec / 3600);
$m = intval(($totalSec % 3600) / 60);
$s = $totalSec % 60;
return sprintf('%02d:%02d:%02d', $h, $m, $s);
}
}
// 使用範例
$parser = new FlvParser();
try {
$durationMs = $parser->getDuration('video.flv');
$formatted = $parser->getFormattedDuration('video.flv');
echo "時長: {$durationMs} ms ({$formatted})";
} catch (Exception $e) {
echo '解析失敗: ' . $e->getMessage();
}
?>
onMetaData 事件,內含 duration 欄位 (秒,浮點數),可作為交叉驗證。
private function parseScriptTag($data)
{
// 簡易 AMF0 解析,尋找 "onMetaData" -> duration
// 實際建議使用 sabre/amf 或專用 FLV 解析庫
if (strpos($data, 'onMetaData') !== false && strpos($data, 'duration') !== false) {
// 正則提取 duration 數值
if (preg_match('/duration.{0,10}(\d+\.?\d*)/', $data, $m)) {
$this->duration = max($this->duration, (int)($m[1] * 1000));
}
}
}
FLV 解析核心在於正確讀取 Big-Endian 整數、遍歷 Tag 找出最大時間戳。本類別輕量無依賴,適合簡單需求;複雜專案建議使用 ffprobe (FFmpeg) 或成熟媒體資訊庫。