Laravel 5 HTTP响应,M4V文件和iOS MPMoviePlayerViewController

时间:2015-05-01 16:50:52

标签: php ios iphone video-streaming laravel-5

我的情况令我难过,所以我正在寻找任何可以得到的帮助。

我有一个iOS应用程序,它使用MPMoviePlayerViewController播放由Laravel 5站点管理的M4V视频文件。

如果直接从Laravel 5 / public文件夹下载视频文件,则视频文件播放效果非常好(在iOS中)。但是,我通常会从Laravel 5的Storage Facade存储和提供视频文件,因为我最终将使用S3和弹性转码器。

这适用于FireFox,包含QuickTime浏览器插件,VLC和其他流媒体视频客户端,但不适用于我们的iOS应用程序。

据我所知,MPMoviePlayerViewController对于如何格式化HTTP响应非常挑剔。我尝试过StreamedResponse,但这似乎没什么帮助。

因此,例如,直接从/ public文件夹中提取文件的以下URL可以在iOS上正常工作:

http://172.16.160.1/video_ae9a7da0efa211e4b115f73708c37d67.m4v

但是,如果我使用Laravel 5从存储器中提取该文件,iOS将无法播放。

http://172.16.160.1/api/getfile/f444b190ef5411e4b7068d1890d109e8/video_ae9a7da0efa211e4b115f73708c37d67.m4v

注意iOS没有提供任何有意义的错误,以帮助调试,但我很肯定它是如何通过Laravel 5进行HTTP响应。

这是我的路线:

Route::get('myapi/getfile/{filename?}', 'APIController@getfile')->where('filename', '(.*)');

这是我的控制器:

    public function getfile($filename)
{
    return $api = API::getfile($filename);
}

这是我的模特:

public static function getfile($filename) {
$file = Storage::disk('local')->get('Files/'.$filename);
return (new Response($file, 200))->header('Content-Type', 'video/mp4');
}

如果我遗漏了任何支持信息,请告诉我,我会发布。我的下一步可能是设置Wireshark测试平台,看看握手是什么样的。

提前感谢您的帮助。 : - )

1 个答案:

答案 0 :(得分:0)

我知道这是一篇老文章,但最终我需要将Laravel中的视频从S3流传输到需要HTTP_RANGE支持的播放器。我把它们放在一起(读了很多线程之后)。它支持您在Laravel中定义的所有disks()。

我使用了下面的类,位于App / Http / Responses。要使用此类,请创建一个执行此操作的方法(这将是您的getFile方法的内容):

$filestream = new \App\Http\Responses\S3FileStream('file_path_and_name_within_bucket', 'disk_bucket_name');
return $filestream->output();

我只是将视频播放器的src指向实现该方法和成功的途径!

S3FileStream.php:     

namespace App\Http\Responses;

use Illuminate\Http\Request;
use Storage;

class S3FileStream
{
    /**
     * @var \League\Flysystem\AwsS3v3\AwsS3Adapter
     */
    private $adapter;

    /**
     * @var \Aws\S3\S3Client
     */
    private $client;

    /**
     * @var file end byte
     */
    private $end;

    /**
     * @var string
     */
    private $filePath;

    /**
     * @var bool storing if request is a range (or a full file)
     */
    private $isRange = false;

    /**
     * @var length of bytes requested
     */
    private $length;

    /**
     * @var
     */
    private $return_headers = [];

    /**
     * @var file size
     */
    private $size;

    /**
     * @var start byte
     */
    private $start;

    /**
     * S3FileStream constructor.
     * @param string $filePath
     * @param string $adapter
     */
    public function __construct(string $filePath, string $adapter = 's3')
    {
        $this->filePath   = $filePath;
        $this->filesystem = Storage::disk($adapter)->getDriver();
        $this->adapter    = Storage::disk($adapter)->getAdapter();
        $this->client     = $this->adapter->getClient();
    }

    /**
     * Output file to client
     */
    public function output()
    {
        return $this->setHeaders()->stream();
    }

    /**
     * Output headers to client
     * @return $this
     */
    protected function setHeaders()
    {
        $object = $this->client->headObject([
            'Bucket' => $this->adapter->getBucket(),
            'Key'    => $this->filePath,
        ]);

        $this->start = 0;
        $this->size  = $object['ContentLength'];
        $this->end   = $this->size - 1;
        //Set headers
        $this->return_headers                        = [];
        $this->return_headers['Last-Modified']       = $object['LastModified'];
        $this->return_headers['Accept-Ranges']       = 'bytes';
        $this->return_headers['Content-Type']        = $object['ContentType'];
        $this->return_headers['Content-Disposition'] = 'attachment; filename=' . basename($this->filePath);

        if (!is_null(request()->server('HTTP_RANGE'))) {
            $c_start = $this->start;
            $c_end   = $this->end;

            [$_, $range] = explode('=', request()->server('HTTP_RANGE'), 2);
            if (strpos($range, ',') !== false) {
                headers('Content-Range: bytes ' . $this->start . '-' . $this->end . '/' . $this->size);
                return response('416 Requested Range Not Satisfiable', 416);
            }
            if ($range == '-') {
                $c_start = $this->size - substr($range, 1);
            } else {
                $range   = explode('-', $range);
                $c_start = $range[0];

                $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $c_end;
            }
            $c_end = ($c_end > $this->end) ? $this->end : $c_end;
            if ($c_start > $c_end || $c_start > $this->size - 1 || $c_end >= $this->size) {
                headers('Content-Range: bytes ' . $this->start . '-' . $this->end . '/' . $this->size);
                return response('416 Requested Range Not Satisfiable', 416);
            }
            $this->start                            = $c_start;
            $this->end                              = $c_end;
            $this->length                           = $this->end - $this->start + 1;
            $this->return_headers['Content-Length'] = $this->length;
            $this->return_headers['Content-Range']  = 'bytes ' . $this->start . '-' . $this->end . '/' . $this->size;
            $this->isRange                          = true;
        } else {
            $this->length                           = $this->size;
            $this->return_headers['Content-Length'] = $this->length;
            unset($this->return_headers['Content-Range']);
            $this->isRange = false;
        }

        return $this;
    }

    /**
     * Stream file to client
     * @throws \Exception
     */
    protected function stream()
    {
        $this->client->registerStreamWrapper();
        // Create a stream context to allow seeking
        $context = stream_context_create([
            's3' => [
                'seekable' => true,
            ],
        ]);
        // Open a stream in read-only mode
        if (!($stream = fopen("s3://{$this->adapter->getBucket()}/{$this->filePath}", 'rb', false, $context))) {
            throw new \Exception('Could not open stream for reading export [' . $this->filePath . ']');
        }
        if (isset($this->start)) {
            fseek($stream, $this->start, SEEK_SET);
        }

        $remaining_bytes = $this->length ?? $this->size;
        $chunk_size      = 1024;

        $video = response()->stream(
            function () use ($stream, $remaining_bytes, $chunk_size) {
                while (!feof($stream) && $remaining_bytes > 0) {
                    echo fread($stream, $chunk_size);
                    $remaining_bytes -= $chunk_size;
                    flush();
                }
                fclose($stream);
            },
            ($this->isRange ? 206 : 200),
            $this->return_headers
        );
        return $video;
    }
}