reactphp / reactphp

Event-driven, non-blocking I/O with PHP.

Home Page:https://reactphp.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

multipart video streaming & only send 1 min of the video

TwelveTitans opened this issue · comments

hey all
I have ran this code and it was successful.

<?php

require __DIR__ . '/../vendor/autoload.php';

use React\Http\Server;
use React\Http\Response;
use React\EventLoop\Factory;
use Psr\Http\Message\ServerRequestInterface;
use function \React\Promise\Stream\unwrapReadable;

$loop = Factory::create();
$filesystem = \React\Filesystem\Filesystem::create($loop);

$server = new Server(function (ServerRequestInterface $request) use ($filesystem) {
    $params = $request->getQueryParams();
    $file = $params['video'] ?? null;

    if ($file === null) {
        return new Response(200, ['Content-Type' => 'text/plain'], 'Video streaming server');
    }

    $filePath = __DIR__ . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . basename($file);

    $file = $filesystem->file($filePath);
    return $file->exists()
        ->then(
            function () use ($file) {
                $stream = unwrapReadable($file->open('r'));
                return new Response(200, ['Content-Type' => 'video/mp4'], $stream);
            },
            function () {
                return new Response(404, ['Content-Type' => 'text/plain'], "This video doesn't exist on server.");
            }
        );
});

$socket = new \React\Socket\Server('127.0.0.1:8003', $loop);
$server->listen($socket);

echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . "\n";
$loop->run();

My Questions:
1: when I forward the video, the html5 player jump to start!?
2: is there any possible way to only send first 1 min of the video and then stop it?

Yes, you'll need to look into the range header for that.

@TwelveTitans Welcome to @reactphp, that's an excellent question!

Like @kelunik said, you'll have to check the Range request header and return an appropriate data chunk using the Content-Range response header. You can take a look at https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests for more details.

I believe this has been answered, so I'm closing this for now. Please come back with more details if this problem persists and we can always reopen this 👍