live stream video php
Live video streaming from recording files over HTTP based on PHP
I want to organize live streaming from recording files over HTTP based on PHP.
INTRODUCTION: On the streaming server I writing video to local file(local_file.mpg) and when received a request from client then start streaming to it from
$start_byte = filesize(«local_file.mpg»)-10MB; The local_file.mpg is still writing and PHP script continue reading it and flushing.
PROBLEM: I streaming it via HTTP Range with the following headers:
And flushing as follows:
I open it via VLC or FFplay, but it played until the time moment when the stream was requested. This is to be expected, because we determine the size of the file and provide it to requested side. But if we artificially increase a file size, for example
$size = filesize(«local_file.mpg»)+999999999999; it also not help, because video players requesting new data too early when it is not recorded. And also stopped play at the time moment when the stream was requested.
1. Please advice how to correct organize live streaming from recording files over HTTP based on PHP.
2. Is it possible to do it with HTTP RANGE mechanism or I should use another way?
UPDATE: Based on this question I tried the next code:
And it works well via ffplay, but via VLC it played no more then 1 minute and stoped then.
Please advice how to make it work on VLC also?
Live Video Streaming with PHP
I have a PHP/AJAX/MYSQL chat application. I want to add video chatting to my application. How can I create live video streaming to be used for live video conferences/chatting in a PHP application. What are the key-terms I need to know if I wanted to build such a system? Is it a good idea in the first place to use PHP? Is there something I’m not thinking about? What other languages can I use, perhaps in conjunction with PHP?
8 Answers 8
I am not saying that you have to abandon PHP, but you need different technologies here.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you’ll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won’t give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I’m also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
Please note that the below described service is no longer available as it was based on FLV media (Flash)
This project which utilizes the Red5, Flex and PHP for Live Video Streaming and Recording has many features
Stream Live video to the viewers
Record the streams from your cam or other video input devices to the server
Preview the recorded streams and files and thumbnail the frame which you would like to display for the video.
Choose from any resolutions
Can be plugged to any script
Each website user can have a separate Directory for storing their videos and thumbnails use this link http://code.google.com/p/red5-flex-streamer/
PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).
PHP/AJAX/MySQL will not be enough for creating the live video streaming application There is a similar thread here. It primarily suggests using Flex or Silverlight.
For live video conferencing you can’t ignore the need of a streaming server.
If you’re going to build something like this it’s prudent to think about how you’re going to host the video from a very early stage as it will influence how you build the application. Flash/Flex/Silverlight/Windows Media. etc.
There are a lot of «off-the-shelf» ‘servers’ that will run in your environment. Most of these utilize the aforementioned Flex or Silverlight to implement the actual video itself but I’m pretty sure all will run under LAMP/PHP.
The challenges will picking the best software from everything that’s available and getting your hosting-provider to let you stream video (it goes without saying that streaming is heavy on bandwidth).
You can easily build a website as per the requirements. PHP will be there to handle the website development part. All the hosting and normal website development will work just as it is. However, for the streaming part, you will have to choose a good streaming service. Whether it is Red5 or Adobe, you can choose from plenty of services.
Choose a service that provides a dedicated storage to get something done right. If you do not know how to configure the server properly, you can just choose a streaming service. Good services often give a CDN that helps broadcast the stream efficiently. Simply launch your website in PHP and embed the YouTube player in the said web page to get it working.
Same problem/answer here, quoted below
I’m assuming you mean that you want to run your own private video calls, not simply link to Skype calls or similar. You really have 2 options here: host it yourself, or use a hosted solution and integrate it into your product.
Создаем сервер для потокового видео: глава из книги по PHP от нашего разработчика
У нас в Skyeng работают весьма талантливые люди. Вот, например, бэкенд-разработчик Words Сергей Жук написал книгу про событийно-ориентированный PHP на ReactPHP, основанную на публикациях его блога. Книга англоязычная, мы решили перевести одну самодостаточную главу в надежде, что кому-то она сможет пригодиться. Ну и дать скидочную ссылку на всю работу.
В этой главе мы рассмотрим создание элементарного асинхронного сервера для видео-стриминга на ReactPHP Http Component. Это компонент высокого уровня, предоставляющий простой асинхронный интерфейс для обработки входящих соединений и HTTP-запросов.
Для поднятия сервера нам потребуются две вещи:
— инстанс сервера (React\Http\Server) для обработки входящих запросов;
— сокет (React\Socket\Server) для обнаружения входящих соединений.
Для начала давайте сделаем очень простой Hello world сервер, чтобы понять, как все это работает.
Если мы запустим этот скрипт, он будет выполняться бесконечно. Работающий сервер отслеживает входящие запросы. Если мы откроем адрес 127.0.0.1:8000 в нашем браузере, мы увидим строку Hello world. Отлично!
Простой стриминг видео
Давайте теперь попробуем сделать что-нибудь поинтереснее. Конструктор React\Http\Response может принять читаемый поток (инстанс класса ReadableStreamInterface ) в качестве тела ответа, что позволяет нам передавать поток данных непосредственно в тело. Например, мы можем открыть файл bunny.mp4 (его можно скачать с Github) в режиме чтения, создать с ним поток ReadableResourseStream и предоставить этот поток в качестве тела ответа:
Давайте теперь обновим окно браузера и посмотрим потоковое видео:
Супер! Мы сделали стриминговый видео-сервер с помощью нескольких строк кода!
Важно создать инстанс ReadableResourseStream непосредственно в функции обратного вызова сервера. Помните об асинхронности нашего приложения. Если мы создадим поток вне обратного вызова и просто передадим его, никакого стриминга не случится. Почему? Потому что процесс чтения видеофайла и обработка входящих запросов сервера работают асинхронно. Это значит, что пока сервер ждет новые соединения мы также начинаем читать видеофайл.
Поэтому есть вероятность, что к тому моменту, когда на сервер придет первый запрос, мы уже достигнем конца видеофайла, и у нас не будет данных для стриминга. Когда обработчик запроса получит уже закрытый ответный поток, от просто отправит пустое тело ответа, что приведет к пустой странице браузера.
Улучшения
Но здесь есть проблемы. Видите их?
Проверка наличия файла
Прежде чем открыть файл и создать поток, мы должны проверить, существует ли вообще этот файл на сервере. Если нет – возвращаем 404:
Теперь наш сервер не будет падать, если пользователь запросил неверный файл. Мы выдаем правильный ответ:
Определение MIME-типа файла
Ограничение на запрос файлов
Осталась проблема с запросом файлов. Пользователь может задать любой файл на сервере в строке запроса. Например, если код нашего сервера находится в server.php и мы укажем такой запрос в адресной строке браузера: 127.0.0.1:8000/?video=../server.php, то в результате получим следующее:
Теперь тот же запрос выдаст страницу 404. Исправлено!
Рефакторинг
Получается, мы можем здесь выделить два метода:
Метод makeResponseFromFile() также очень прост. Если по указанному пути нет файла, мы сразу же возвращаем ошибку 404. В противном случае мы открываем запрошенный файл, создаем читаемый поток и возвращаем его в теле ответа:
Вот код класса VideoStreaming целиком:
Разумеется, вместо простого обратного вызова обработчика запроса у нас теперь в три раза больше кода, но если этот код будет меняться в будущем, нам будет значительно проще проводить эти изменения и поддерживать наше приложение.
Примеры из этой главы можно найти на GitHub.
У Сергея также есть полезный регулярно обновляемый англоязычный блог.
Наконец, напоминаем, что мы всегда находимся в поиске талантливых разработчиков! Приходите, у нас весело.
ranacseruet / VideoStream.php
This comment has been minimized.
Copy link Quote reply
annopnod commented Jul 15, 2014
$ext = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
switch ($ext)
<
case «mp4»:
header(«Content-Type: video/mp4»);
break;
case «webm»:
header(«Content-Type: video/webm»);
break;
>
This comment has been minimized.
Copy link Quote reply
basicssm commented Oct 17, 2014
I play only 40 second of video?
This comment has been minimized.
Copy link Quote reply
ziggi commented May 31, 2015
Very useful. Thank you.
This comment has been minimized.
Copy link Quote reply
scipper commented Jun 2, 2015
Very nice! solved my problems 🙂
This comment has been minimized.
Copy link Quote reply
dirkx commented Sep 1, 2015
May be an idea to add a if(connection_aborted()) near line 104 or as part of the while().
This comment has been minimized.
Copy link Quote reply
elangodhilipan commented Sep 4, 2015
all type video formats are not supported in this code. so please any body help me for all types of video supported streaming code..
This comment has been minimized.
Copy link Quote reply
NguyenTungs commented Oct 23, 2015
This comment has been minimized.
Copy link Quote reply
sadiq810 commented Dec 28, 2015
This comment has been minimized.
Copy link Quote reply
harish40 commented Feb 1, 2016
How to use the code & where to replace the video path plzz let me know
This comment has been minimized.
Copy link Quote reply
nalmada commented Mar 4, 2016
This comment has been minimized.
Copy link Quote reply
ghost commented Mar 8, 2016
This comment has been minimized.
Copy link Quote reply
Lixus commented Mar 10, 2016
@ranacseruet Thanks for this script! I just noticed that video streaming with this does not work on Android 5 and 6 devices. Any ideas?
This comment has been minimized.
Copy link Quote reply
jadrovski commented Jun 2, 2016
Thank you, very nice solution
This comment has been minimized.
Copy link Quote reply
lynxfg commented Jul 29, 2016
This comment has been minimized.
Copy link Quote reply
inanbayram commented Sep 6, 2016 •
@ranacseruet It’s possible to stream multiple video files in one php script?
$stream1 = new VideoStream($file1);
$stream1->start();
$stream2 = new VideoStream($file2);
$stream2->start();
If I try the following code, the script is just serving the first video file. Of course I removed the exit’s in the class
This comment has been minimized.
Copy link Quote reply
ImSeaWorld commented Oct 8, 2016 •
@annopnod Why are you making an extra variable?
Turn this:
$ext = strtolower(pathinfo($this->path, PATHINFO_EXTENSION)); switch ($ext) < etc etc
Into this:
switch (strtolower(pathinfo($this->path, PATHINFO_EXTENSION))) < etc etc
EDIT: A better way you could do this, is use an array. Line 39 with the Content-Type header can be turned into a «one-liner».
On line 39 or the Content-Type line I replaced-
This: header(«Content-Type: video/mp4»);
With this: header(«Content-Type: «.($this->videoFormats[strtolower(pathinfo($this->path, PATHINFO_EXTENSION))]));
php live streaming
Also use this edition to integrate with any php script or content management system that does not have a turnkey integration, yet.
Supports web based interfaces for broadcasting live video, watching live video, text chat discussions with viewers. More advanced features like access and session duration control, tips for broadcasters can be enabled and integrated as needed.
WebRTC HTML5 plain broadcast and playback is also available. This also uses the relay streaming server, meaning it does not require server grade connection for broadcaster and streams are available across all delivery formats (advanced Flash RTMP interface, plain HTML5 HLS/DASH, plain HTML5 WebRTC ).
Demo for Live Video Streaming Script
Installation Instructions for PHP Live Video Streaming Software
Before installing, make sure your hosting environment meets all requirements.
For enabling transcoding for HTML5 HLS / MPEG DASH playback required for iOS/Android delivery, special requirements apply: latest Wowza and FFMPEG with Flash and HTML5 specific codecs. WebRTC broadcast/playback require specific configuration and SSL certififcate for Wowza SE available with the turnkey complete streaming hosting plans.
Customizing & Integrating Live Video Streaming on your site
HTML5 WebRTC Implementation
WebRTC Publish Features
Solution implements WebRTC for streaming to/from media relay server. This brings compatibility for some HTML5 mobile browsers, to allow streaming directly from site without configuring stand alone encoder apps.
Media server is still required and used as a relay for scalability, reliability and cross protocol stream availability. Relay server also manages sessions and advanced interactions in real time.
Why not use P2P? As standard WebRTC implementations utilize peering networks, there still has to be a nearby node to help distribute the stream to other local hosts. Peering across a global network can be incredibly difficult.
Broadcasters would need server grade connections to live stream to multiple users and using a regular home ADSL connection (that has has higher download and bigger upload) causes real issues.