PHP 实现大文件视频推流
/** * 视频推流 * 返回视频流 */ function bofang(){ set_time_limit(0); ini_set('max_execution_time', 0);//秒为单位,自己根据需要定义 ini_set("memory_limit",-1); $moviePath = FCPATH.'movie'.DIRECTORY_SEPARATOR; $filename = $moviePath.'afanda.mkv'; // 视频地址 $file = new \SplFileObject($filename, 'rb'); $size = $file->getSize(); // File size $length = $size; // Content length $start = 0; // Start byte $end = $size - 1; // End byte header('Content-type: audio/mp4'); header("Accept-Ranges: 0-$length"); // $_SERVER['HTTP_RANGE'] = 'bytes=0-'; // 会发生2次请求,会携带断点缓存需要加载的视频流 0- 表示从头加载文件尾,8G文件读取会卡 if (isset($_SERVER['HTTP_RANGE'])) { $c_start = $start; $c_end = $end; list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); if (strpos($range, ',') !== false) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header("Content-Range: bytes $start-$end/$size"); exit; } if ($range == '-') { $c_start = $size - substr($range, 1); }else{ $range = explode('-', $range); $c_start = $range[0]; $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size; } $c_end = ($c_end > $end) ? $end : $c_end; if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header("Content-Range: bytes $start-$end/$size"); exit; } $start = $c_start; $end = $c_end; $length = $end - $start + 1; $file->fseek($start); header('HTTP/1.1 206 Partial Content'); } header("Content-Range: bytes $start-$end/$size"); header("Content-Length: ".$length); $buffer = 1024 * 8; $strNum = 1024*10; // 如果8G 读取 8kb,估计会循环上百万次,就会陷入无限等待中... while(!$file->eof() && $start <= $end) { $strNum--; if( $strNum <= 0 ) break; //if( $start >= $end ) //$buffer=0; echo $file->fread($buffer); $file->next(); // ob_flush(); $file->fflush(); } //关闭文件对象 $file = null; exit(); }
最近项目要做源视频(MP4 MKV)加密,然后播放的时候需要解密,然后要接口推流给客户端。
视频是可以做加密处理的,原理是修改header 头,随机加密替换字节流,解密就是反过来,把密文解密替换回去。