Difference between revisions of "Engine HTTP API"

From Ace Stream Wiki
Jump to: navigation, search
(Методы API)
(API methods)
 
(22 intermediate revisions by 2 users not shown)
Line 1: Line 1:
==Общее описание==
+
==About==
Начиная с версии 3.1 появилась возможность управлять движком по протоколу HTTP. Для передачи команды движку нужно отправить HTTP GET запрос на http-порт движка. Порт по умолчанию: 6878.
+
Since version 3.1 we implemented API to control app engine via HTTP. To do that, you should send appropriate HTTP GET query to the app engine (default IP:port is 127.0.0.1:6878)
  
==Проверка наличия движка==
+
==Limitations==
При необходимости проверить наличие движка у пользователя необходимо отправить JSONP запрос на адрес <nowiki>http://127.0.0.1:6878/webui/api/service?method=get_version&format=jsonp</nowiki>. Если движок запущен, то выдаст свою версию в ответ на запрос.
+
You can't use HTTP API with AJAX queries from secured (https) pages, because HTTP API is not secured, and such behaviour (http query from https page) will be blocked by browser.
 +
So you must have and serve a dedicated unsecured page on your secured site to work with engine HTTP API.
  
Пример запроса:
+
==Checking local engine availability==
  <nowiki>Запрос:
+
Send JSON query to <nowiki>http://127.0.0.1:6878/webui/api/service?method=get_version&format=jsonp</nowiki>. If app engine is running, then it return version string in JSON format.
 +
 
 +
Some examples:
 +
  <nowiki>
 +
Query:
 
http://127.0.0.1:6878/webui/api/service?method=get_version&format=jsonp&callback=mycallback
 
http://127.0.0.1:6878/webui/api/service?method=get_version&format=jsonp&callback=mycallback
  
Ответ:
+
Response:
 
mycallback({"result": {"code": 3002300, "version": "3.1.0-rc2"}, "error": null});</nowiki>
 
mycallback({"result": {"code": 3002300, "version": "3.1.0-rc2"}, "error": null});</nowiki>
  
Ответ состоит и таких полей:
+
Fields description:
*'''version''' - версия движка в виде строки (например, 3.0.12)
+
*'''version''' - engine version, string ("3.0.12")
*'''code''' - версия движка в виде целого числа (для удобства сравнения версий, например 30012)
+
*'''code''' - engine version, integer (30012)
  
Пример HTML-страницы с кнопкой для проверки движка (JSONP-запросы отправляются с помощью библиотеки jQuery):
+
Simple page with check button (JSONP-queries served by jQuery):
 
  <nowiki><!DOCTYPE html>
 
  <nowiki><!DOCTYPE html>
 
<html>
 
<html>
Line 53: Line 58:
 
</html></nowiki>
 
</html></nowiki>
  
==Методы API==
+
==Using HTTP API on Android==
В описаниях методов <tt>''<engine_address>''</tt> - это ip-адрес движка, <tt>''<engine_port>''</tt> - http-порт движка.
+
HTTP API is a preferred way to integrate engine with other applications on Android.
Все методы принимают такие общие параметры:
 
*'''sid''' - [[#Идентификатор плеера|идентификатор плеера]] (необязательный параметр)
 
*'''id''' - идентификатор контента (content id) (условно обязательный параметр)
 
*'''infohash''' - infohash транспортного файла (.acelive либо .torrent файла)(условно обязательный параметр)
 
*'''url''' - ссылка на транспортный файл (условно обязательный параметр)
 
*'''path''' - путь к транспортному файлу в локальной файловой системе (условно обязательный параметр)
 
  
В запросах на старт воспроизведения обязательно должен присутствовать один из параметров <tt>id</tt>, <tt>infohash</tt>, <tt>url</tt>, <tt>path</tt>.
+
Before sending any requests to engine you should ensure that it is running. This should be done by binding to engine service as described
 +
[[Using_Ace_Stream_as_service_on_Android|here]].
  
===Получение потока в формате HLS===
+
==API methods==
<tt><nowiki>http://<engine_address>:<engine_port>/ace/manifest.m3u8</nowiki></tt>
+
Terms: <tt>''<engine_address>''</tt> - app engine IP address, <tt>''<engine_port>''</tt> - app engine HTTP port.
 +
Common params:
 +
*'''id''' - content id (conditional param)
 +
*'''infohash''' - transport file infohash (.acelive or .torrent file) (conditional param)
 +
*'''url''' - link to transport file (conditional param). Can be used with URL encoded "file://path/" to access local file.
 +
*'''pid''' - [[#Player ID|player id]] (optional, formerly known as '''sid''', since ver. 3.1.29 is obsolete and replaced by '''pid''')
  
В ответ на данную команду движок выдаст HLS плейлист для воспроизведения запрашиваемого контента. В случае ошибки будет возвращен HTTP код 4хх либо 5хх с кратким описанием ошибки.
+
In the query to the app engine at least one of params <tt>id</tt>, <tt>infohash</tt>, <tt>url</tt> must be present.
  
Параметры:
+
===How to get HLS stream===
*'''transcode_audio''' - транскодировать аудио в AAC (параметр принимает значения 0 либо 1)
+
Query: <tt><nowiki>http://<engine_address>:<engine_port>/ace/manifest.m3u8</nowiki></tt>
*'''transcode_mp3''' - не транскодировать MP3 (параметр принимает значения 0 либо 1)
 
*'''preferred_audio_language''' - предпочитаемый язык аудио-дорожки (3-значный код, список [http://xml.coverpages.org/nisoLang3-1994.html здесь])
 
  
Пример:
+
As response app engine should return HLS playlist. If any error occured, then engine return HTTP error code 4хх or 5хх with brief error description.
 +
 
 +
Params:
 +
*'''transcode_audio''' - transcode all audio tracks to AAC, (values: 0 or 1, default 0)
 +
*'''transcode_mp3''' - do not transcode MP3 track(s), (values: 0 or 1, default 0)
 +
*'''transcode_ac3''' - transcode only AC3 track(s), (values: 0 or 1, default 0)
 +
*'''preferred_audio_language''' - three char code of preffered language, full list - http://xml.coverpages.org/nisoLang3-1994.html
 +
 
 +
Example:
 
  <nowiki>http://127.0.0.1:6878/ace/manifest.m3u8?id=dd1e67078381739d14beca697356ab76d49d1a2d</nowiki>
 
  <nowiki>http://127.0.0.1:6878/ace/manifest.m3u8?id=dd1e67078381739d14beca697356ab76d49d1a2d</nowiki>
  
===Получение потока по HTTP===
+
===How to get HTTP stream===
<tt><nowiki>http://<engine_address>:<engine_port>/ace/getstream</nowiki></tt>
+
Query: <tt><nowiki>http://<engine_address>:<engine_port>/ace/getstream</nowiki></tt>
  
В ответ на данную команду движок будет выдавать данные в виде http progressive download. В случае ошибки будет возвращен HTTP код 4хх либо 5хх с кратким описанием ошибки.
+
As response app engine should return stream data as http progressive download. If any error occured, then engine return HTTP error code 4хх or 5хх with brief error description.
  
Пример:
+
Example:
 
  <nowiki>http://127.0.0.1:6878/ace/getstream?id=dd1e67078381739d14beca697356ab76d49d1a2d</nowiki>
 
  <nowiki>http://127.0.0.1:6878/ace/getstream?id=dd1e67078381739d14beca697356ab76d49d1a2d</nowiki>
  
===Запуск HLS-трансляции===
+
===How to play HLS broadcast===
<tt><nowiki>http://<engine_address>:<engine_port>/hls/manifest.m3u8</nowiki></tt>
+
Query: <tt><nowiki>http://<engine_address>:<engine_port>/hls/manifest.m3u8</nowiki></tt>
  
Данная команда позволяет запустить через движок любую HLS-трансляцию. Для запуска достаточно передать движку ссылку на HLS-плейлист (параметр <tt>manifest_url</tt>).
+
You can play via app engine any HLS broadcast, just pass link to the HLS playlist to the engine (<tt>manifest_url</tt> param).
  
Параметры:
+
Params:
*'''manifest_url''' - URL трансляции (ссылка на плейлист HLS-трансляции)
+
*'''manifest_url''' - HLS manifest URL (link to the HLS playlist)
  
Пример:
+
Example:
 
  <nowiki>http://127.0.0.1:6878/hls/manifest.m3u8?manifest_url=http%3A%2F%2Fwin.cdn.bonus-tv.ru%2FTVB7%2Fntv%2Fplaylist.m3u8</nowiki>
 
  <nowiki>http://127.0.0.1:6878/hls/manifest.m3u8?manifest_url=http%3A%2F%2Fwin.cdn.bonus-tv.ru%2FTVB7%2Fntv%2Fplaylist.m3u8</nowiki>
  
Пример HTML-страницы для запуска HLS-трансляции через движок в плеере VideoJS:
+
Simple HTML code for playing HLS broadcast in VideoJS player:
 
  <nowiki><!DOCTYPE html>
 
  <nowiki><!DOCTYPE html>
 
<html>
 
<html>
Line 115: Line 126:
 
</html></nowiki>
 
</html></nowiki>
  
==Получение статистики==
+
==Additional features==
Движок при необходимости может отдавать статистику по текущей сессии воспроизведения (скорость загрузки, кол-во подсоединенных узлов и т.д.)
+
Engine can provide some additional features to control playback session, such as extra commands, session statistics and events polling.
 +
To access such features, you must add this param to playback session options:
 +
<tt>format=json</tt>
  
Для получения статистики необходимо запросить у движка URL статистики при старте воспроизведения. Для этого нужно добавить параметр format=json в запрос на воспроизведение. При наличии данного параметра движок вернет ответ в формате JSON с двумя ссылками:
+
As response app engine should return some links in JSON format:  
*'''playback_url''' - ссылка для воспроизведения (по этой ссылке движок отдаст HLS-манифест либо HTTP-поток)
+
<tt><nowiki>{
*'''stat_url''' - ссылка для получения статистики
+
    "playback_url": playback_url,
 +
    "stat_url: stat_url,
 +
    "command_url": command_url,
 +
    "event_url": event_url,
 +
}</nowiki></tt>
  
Пример:
+
;playback_url
<nowiki>Запрос:
+
:media stream link
http://127.0.0.1:6878/ace/manifest.m3u8?id=dd1e67078381739d14beca697356ab76d49d1a2d&format=json
+
;stat_url
 +
:session statistics link
 +
;command_url
 +
:engine commands link
 +
;event_url
 +
:session events link
  
Ответ:
+
<tt>event_url</tt> will be present in engine response only if query contains param <tt>use_api_events</tt>.
{
+
 
  "stat_url": "http://127.0.0.1:6878/ace/stat/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
+
Via <tt>playback_url</tt> app engine will serve requested media stream. This link should be passed to media player.
  "playback_url": "http://127.0.0.1:6878/ace/m/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6.m3u8"
 
}</nowiki>
 
  
По ссылке <tt>stat_url</tt> движок возвращает ответ в формате JSON с такими полями:
+
===Getting some stats===
*'''status''' - статус сессии воспроизведения:
+
Via <tt>stat_url</tt> link app engine should return JSON-formatted structure:
**''prebuf'' - пребуферизация
+
*'''status''' - playback session status:
**''dl'' - воспроизведение
+
**''prebuf'' - prebuffering
*'''peers''' - кол-во подсоединенных узлов
+
**''dl'' - playback
*'''speed_down''' - скорость скачивания (Кбайт/с)
+
*'''peers''' - number of connected peers
*'''speed_up''' - скорость отдачи (Кбайт/с)
+
*'''speed_down''' - download speed (Kbytes per sec)
*'''downloaded''' - объем скачанных данных (байт)
+
*'''speed_up''' - upload (Kbytes per sec)
*'''uploaded''' - объем отданных данных (байт)
+
*'''downloaded''' - total downloaded (bytes)
*'''total_progress''' - процент загруженных данных от суммарного объема (для VOD); для live всегда 0
+
*'''uploaded''' - total uploaded (bytes)
 +
*'''total_progress''' - download ratio in percentage to media size, valid for VOD only, for live always 0
  
Пример:
+
Example:
  <nowiki>Запрос:
+
  <nowiki>
 +
Query:
 
http://127.0.0.1:6878/ace/stat/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6
 
http://127.0.0.1:6878/ace/stat/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6
  
Ответ:
+
Response:
 
{
 
{
 
   "response": {
 
   "response": {
Line 159: Line 181:
 
   },
 
   },
 
   "error": null
 
   "error": null
 +
}</nowiki>
 +
       
 +
===Sending extra commands to the app engine===
 +
Via <tt>command_url</tt> link you can control playback session.
 +
 +
Command name passed to app engine via <tt>method</tt> param.
 +
For the moment you can use only one command: <tt>stop</tt> - stop playback session.
 +
Its recommended to send "stop" command to the app engine when user stops playback in the media player UI/controls.
 +
 +
Example:
 +
<nowiki>
 +
Query:
 +
http://127.0.0.1:6878/ace/cmd/5410b27fc567c35c8547e3b69b141215ce3a1fd7/ef0609c43e560697329d93dae4571edb?method=stop
 +
 +
Response:
 +
{
 +
    "response": "ok",
 +
    "error": null
 +
}</nowiki>
 +
       
 +
===Getting events from the app engine===
 +
Via <tt>event_url</tt> link you can get events from the app engine, using "long polling" method.
 +
 +
As response app engine should return data in the <tt>response</tt> field (JSON format):
 +
*'''name''' - event name
 +
*'''params''' - object with actual param
 +
 +
In the versions prior to 3003600 <tt>response</tt> field contains "JSON as string" data.
 +
В версиях до 3003600 в поле <tt>response</tt> передается не сам JSON-объект, а его строковое представление.
 +
 +
Example:
 +
<nowiki>
 +
Query:
 +
http://127.0.0.1:6878/ace/event/5410b27fc567c35c8547e3b69b141215ce3a1fd7/ef0609c43e560697329d93dae4571edb
 +
 +
Response (engine version >= 3003600):
 +
{
 +
    "response": {
 +
        "name": "got_codec_info",
 +
        "params: {
 +
            "audio_codec_id": 86018,
 +
            "video_codec_id": 28
 +
        }
 +
    },
 +
    "error": null
 +
}
 +
 +
Response (engine version < 3003600):
 +
{
 +
    "response": "{\"name\": \"got_codec_info\"}, \"params\": {\"audio_codec_id\": 86018, \"video_codec_id\": 28}",
 +
    "error": null
 +
}</nowiki>
 +
 +
 +
When current playback session has stopped, <tt>event_url</tt> response looks like:
 +
<nowiki>{
 +
    "response": null,
 +
    "error": "download stopped"
 +
}</nowiki>
 +
 +
And player should stop sending queries to <tt>event_url</tt>.
 +
 +
====Events list====
 +
;missing_content
 +
:quered fragment cannot be found (HLS playback). Player should fast-forward to keep up with "live" stream.
 +
;got_codec_info
 +
:stream codec data is ready.
 +
:;params:
 +
::video_codec_id - video codec id
 +
::audio_codec_id - audio codec id
 +
:audio/video IDs corresponded to ffmpeg libavcodec, [https://ffmpeg.org/doxygen/trunk/avcodec_8h_source.html full list here]
 +
:this event can be useful, when player do not support such codec(s).
 +
;segmenter_failed
 +
:built-in HLS-segmenter failed to process stream. Player should stop the playback.
 +
;download_stopped
 +
:engine has stopped playback
 +
:;params
 +
::<tt>reason</tt> - stop reason, possible values:
 +
:::<tt>missing_option</tt> - content not free, "paid option" is missing.
 +
::<tt>option</tt> - missing option ID (for <tt>reason=missing_option</tt>)
 +
 +
====Javascript example====
 +
Using [https://jquery.com jQuery] library.
 +
 +
<nowiki>function startEventListener() {
 +
    $.ajax({
 +
        url: url,
 +
        method: "GET",
 +
        dataType: "json",
 +
        cache: false,
 +
        success: function(response) {
 +
            if(response.error) {
 +
                console.log("event listener: got error: " + response.error);
 +
            }
 +
            else {
 +
                var event = response.response;
 +
                if(typeof event !== "object") {
 +
                    event = JSON.parse(event);
 +
                }
 +
                console.log("event listener: got event: name=" + event.name + " params=" + JSON.stringify(params));
 +
               
 +
                // handle event here
 +
                // ...
 +
               
 +
                // listen to the next event (long polling)
 +
                startEventListener(url);
 +
            }
 +
        },
 +
        error: function(xhr, status, error) {
 +
            console.log("event listener error: status=" + status + " error=" + error);
 +
        }
 +
    });
 +
}
 +
 +
// init event listener
 +
startEventListener("http://127.0.0.1:6878/ace/event/5410b27fc567c35c8547e3b69b141215ce3a1fd7/ef0609c43e560697329d93dae4571edb");</nowiki>
 +
 +
==<div id="stop-notifications"></div>Notifications about missing paid option==
 +
In some cases user must have a permit (the paid option) to playback some content. If such permit not granted, then app engine will stop the playback and send a notification to user (by showing some predefined text in the default browser).
 +
This behaviour can be overrided, and then client API will handle user notifications by itself. To do this, engine playback session should be started with <nowiki>use_stop_notifications=1</nowiki> param.
 +
In this case at playback stop app engine will not send notification to user, but send a event to client.
 +
 +
If some permits is not granted, then engine playback can be stopped:
 +
* at the playback start:
 +
<nowiki>Start playback:
 +
http://127.0.0.1:6878/ace/manifest.m3u8?id=c894b23a65d64a0dae2076d2a01ec6bface83b01&format=json&use_stop_notifications=1
 +
{
 +
    "extra_data": {
 +
        "reason": "missing_option",
 +
        "option": "proxyServer"
 +
    },
 +
    "response": null,
 +
    "error": "You need to buy Proxy Server option to continue"
 +
}</nowiki>
 +
 +
* sometime after playback was started:
 +
If playback was stopped after some time, then engine will send a <tt>download_stopped</tt> event:
 +
<nowiki>Start playback:
 +
http://127.0.0.1:6878/ace/manifest.m3u8?id=c894b23a65d64a0dae2076d2a01ec6bface83b01&format=json&use_api_events=1&use_stop_notifications=1
 +
{
 +
    "response": {
 +
        "stat_url": "http://127.0.0.1:6878/ace/stat/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
 +
        "command_url": "http://127.0.0.1:6878/ace/cmd/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
 +
        "event_url": "http://127.0.0.1:6878/ace/event/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
 +
        "playback_url": "http://127.0.0.1:6878/ace/m/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6.m3u8"
 +
    },
 +
    "error": null
 +
}
 +
 +
Wait for event via event_url:
 +
http://127.0.0.1:6878/ace/event/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6
 +
 +
At playback stop response should look like:
 +
{
 +
    "response": {
 +
        "name": "download_stopped",
 +
        "params": {
 +
            "reason": "missing_option",
 +
            "option": "proxyServer"
 +
        }
 +
    },
 +
    "error": null
 
}</nowiki>
 
}</nowiki>
  
==Идентификатор плеера==
+
==Player ID==
Идентификатор плеера - произвольная строка, которая идентифицирует плеер при обращении к движку. В качестве идентификатора лучше всего использовать случайное число.
+
Player ID ('''pid''') - random string, used for player identification during engine connect session.
  
Предназначение идентификатора плеера - дать движку возможность отличать запросы одного плеера от другого. Это связано с таким ограничением - нельзя просматривать одну и ту же live-трансляцию через движок одновременно в двух плеерах. При возникновении такой ситуации результаты непредсказуемы (трансляция может начать идти с перебоями в обоих плеерах). В связи с этим движок перестает отдавать плееру данные по трансляции, если эту же трансляцию запустили в другом плеере, но делает это только в том случае, если может отличить один плеер от другого.
+
"Player ID" purpose - app engine must distinguish one player session from another, as in the current engine implementation user cannot play the same live stream with two (or more) players simultaneously from one engine, and engine will stop to serve requests from one player, when got a new request from another.

Latest revision as of 21:55, 19 April 2018

About

Since version 3.1 we implemented API to control app engine via HTTP. To do that, you should send appropriate HTTP GET query to the app engine (default IP:port is 127.0.0.1:6878)

Limitations

You can't use HTTP API with AJAX queries from secured (https) pages, because HTTP API is not secured, and such behaviour (http query from https page) will be blocked by browser. So you must have and serve a dedicated unsecured page on your secured site to work with engine HTTP API.

Checking local engine availability

Send JSON query to http://127.0.0.1:6878/webui/api/service?method=get_version&format=jsonp. If app engine is running, then it return version string in JSON format.

Some examples:

Query:
http://127.0.0.1:6878/webui/api/service?method=get_version&format=jsonp&callback=mycallback

Response:
mycallback({"result": {"code": 3002300, "version": "3.1.0-rc2"}, "error": null});

Fields description:

  • version - engine version, string ("3.0.12")
  • code - engine version, integer (30012)

Simple page with check button (JSONP-queries served by jQuery):

<!DOCTYPE html>
<html>
    <head>
        <title>Ace Stream - check engine version</title>
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script>
        function checkEngineVersion() {
            $.ajax({
                    method: "GET",
                    url: "http://127.0.0.1:6878/webui/api/service",
                    dataType: "jsonp",
                    data: {
                        method: "get_version",
                        format: "jsonp"
                    },
                    success: function(response) {
                        if(response.error) {
                            console.log("request failed: " + response.error);
                        }
                        else {
                            console.log("version: " + response.result.version);
                            console.log("version_code: " + response.result.code);
                        }
                    },
                    error: function(request, error_string, exception) {
                        console.log("request failed: " + error_string);
                    }
            });
        }
        </script>
    </head>
    <body>
        <button onclick="checkEngineVersion();">Check engine version</button>
    </body>
</html>

Using HTTP API on Android

HTTP API is a preferred way to integrate engine with other applications on Android.

Before sending any requests to engine you should ensure that it is running. This should be done by binding to engine service as described here.

API methods

Terms: <engine_address> - app engine IP address, <engine_port> - app engine HTTP port. Common params:

  • id - content id (conditional param)
  • infohash - transport file infohash (.acelive or .torrent file) (conditional param)
  • url - link to transport file (conditional param). Can be used with URL encoded "file://path/" to access local file.
  • pid - player id (optional, formerly known as sid, since ver. 3.1.29 is obsolete and replaced by pid)

In the query to the app engine at least one of params id, infohash, url must be present.

How to get HLS stream

Query: http://<engine_address>:<engine_port>/ace/manifest.m3u8

As response app engine should return HLS playlist. If any error occured, then engine return HTTP error code 4хх or 5хх with brief error description.

Params:

  • transcode_audio - transcode all audio tracks to AAC, (values: 0 or 1, default 0)
  • transcode_mp3 - do not transcode MP3 track(s), (values: 0 or 1, default 0)
  • transcode_ac3 - transcode only AC3 track(s), (values: 0 or 1, default 0)
  • preferred_audio_language - three char code of preffered language, full list - http://xml.coverpages.org/nisoLang3-1994.html

Example:

http://127.0.0.1:6878/ace/manifest.m3u8?id=dd1e67078381739d14beca697356ab76d49d1a2d

How to get HTTP stream

Query: http://<engine_address>:<engine_port>/ace/getstream

As response app engine should return stream data as http progressive download. If any error occured, then engine return HTTP error code 4хх or 5хх with brief error description.

Example:

http://127.0.0.1:6878/ace/getstream?id=dd1e67078381739d14beca697356ab76d49d1a2d

How to play HLS broadcast

Query: http://<engine_address>:<engine_port>/hls/manifest.m3u8

You can play via app engine any HLS broadcast, just pass link to the HLS playlist to the engine (manifest_url param).

Params:

  • manifest_url - HLS manifest URL (link to the HLS playlist)

Example:

http://127.0.0.1:6878/hls/manifest.m3u8?manifest_url=http%3A%2F%2Fwin.cdn.bonus-tv.ru%2FTVB7%2Fntv%2Fplaylist.m3u8

Simple HTML code for playing HLS broadcast in VideoJS player:

<!DOCTYPE html>
<html>
<head>
<title>HLS example</title>
  <link href="http://vjs.zencdn.net/4.12/video-js.css" rel="stylesheet">
  <script src="http://vjs.zencdn.net/4.12/video.js"></script>
  <script src="https://github.com/videojs/videojs-contrib-media-sources/releases/download/v0.1.0/videojs-media-sources.js"></script>
  <script src="https://github.com/videojs/videojs-contrib-hls/releases/download/v0.11.2/videojs.hls.min.js"></script>
</head>
<body>
  <video id="myvideo" class="video-js vjs-default-skin" controls preload="auto" width="640" height="390" data-setup='{}'>
    <source
      src="http://127.0.0.1:6878/hls/manifest.m3u8?manifest_url=http%3A%2F%2Fwin.cdn.bonus-tv.ru%2FTVB7%2Fntv%2Fplaylist.m3u8"
      type="application/x-mpegurl">
  </video>
</body>
</html>

Additional features

Engine can provide some additional features to control playback session, such as extra commands, session statistics and events polling. To access such features, you must add this param to playback session options:

format=json

As response app engine should return some links in JSON format:

{
    "playback_url": playback_url,
    "stat_url: stat_url,
    "command_url": command_url,
    "event_url": event_url,
}
playback_url
media stream link
stat_url
session statistics link
command_url
engine commands link
event_url
session events link

event_url will be present in engine response only if query contains param use_api_events.

Via playback_url app engine will serve requested media stream. This link should be passed to media player.

Getting some stats

Via stat_url link app engine should return JSON-formatted structure:

  • status - playback session status:
    • prebuf - prebuffering
    • dl - playback
  • peers - number of connected peers
  • speed_down - download speed (Kbytes per sec)
  • speed_up - upload (Kbytes per sec)
  • downloaded - total downloaded (bytes)
  • uploaded - total uploaded (bytes)
  • total_progress - download ratio in percentage to media size, valid for VOD only, for live always 0

Example:

Query:
http://127.0.0.1:6878/ace/stat/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6

Response:
{
  "response": {
    "status": "dl",
    "uploaded": 0,
    "speed_down": 516,
    "speed_up": 0,
    "downloaded": 14155776,
    "peers": 2,
    "total_progress": 0
  },
  "error": null
}
       

Sending extra commands to the app engine

Via command_url link you can control playback session.

Command name passed to app engine via method param. For the moment you can use only one command: stop - stop playback session. Its recommended to send "stop" command to the app engine when user stops playback in the media player UI/controls.

Example:

Query:
http://127.0.0.1:6878/ace/cmd/5410b27fc567c35c8547e3b69b141215ce3a1fd7/ef0609c43e560697329d93dae4571edb?method=stop

Response:
{
    "response": "ok",
    "error": null
}
       

Getting events from the app engine

Via event_url link you can get events from the app engine, using "long polling" method.

As response app engine should return data in the response field (JSON format):

  • name - event name
  • params - object with actual param

In the versions prior to 3003600 response field contains "JSON as string" data. В версиях до 3003600 в поле response передается не сам JSON-объект, а его строковое представление.

Example:

Query:
http://127.0.0.1:6878/ace/event/5410b27fc567c35c8547e3b69b141215ce3a1fd7/ef0609c43e560697329d93dae4571edb

Response (engine version >= 3003600):
{
    "response": {
        "name": "got_codec_info",
        "params: {
            "audio_codec_id": 86018,
            "video_codec_id": 28
        }
    },
    "error": null
}

Response (engine version < 3003600):
{
    "response": "{\"name\": \"got_codec_info\"}, \"params\": {\"audio_codec_id\": 86018, \"video_codec_id\": 28}",
    "error": null
}


When current playback session has stopped, event_url response looks like:

{
    "response": null,
    "error": "download stopped"
}

And player should stop sending queries to event_url.

Events list

missing_content
quered fragment cannot be found (HLS playback). Player should fast-forward to keep up with "live" stream.
got_codec_info
stream codec data is ready.
params
video_codec_id - video codec id
audio_codec_id - audio codec id
audio/video IDs corresponded to ffmpeg libavcodec, full list here
this event can be useful, when player do not support such codec(s).
segmenter_failed
built-in HLS-segmenter failed to process stream. Player should stop the playback.
download_stopped
engine has stopped playback
params
reason - stop reason, possible values:
missing_option - content not free, "paid option" is missing.
option - missing option ID (for reason=missing_option)

Javascript example

Using jQuery library.

function startEventListener() {
    $.ajax({
        url: url,
        method: "GET",
        dataType: "json",
        cache: false,
        success: function(response) {
            if(response.error) {
                console.log("event listener: got error: " + response.error);
            }
            else {
                var event = response.response;
                if(typeof event !== "object") {
                    event = JSON.parse(event);
                }
                console.log("event listener: got event: name=" + event.name + " params=" + JSON.stringify(params));
                
                // handle event here
                // ...
                
                // listen to the next event (long polling)
                startEventListener(url);
            }
        },
        error: function(xhr, status, error) {
            console.log("event listener error: status=" + status + " error=" + error);
        }
    });
}

// init event listener
startEventListener("http://127.0.0.1:6878/ace/event/5410b27fc567c35c8547e3b69b141215ce3a1fd7/ef0609c43e560697329d93dae4571edb");

Notifications about missing paid option

In some cases user must have a permit (the paid option) to playback some content. If such permit not granted, then app engine will stop the playback and send a notification to user (by showing some predefined text in the default browser). This behaviour can be overrided, and then client API will handle user notifications by itself. To do this, engine playback session should be started with use_stop_notifications=1 param. In this case at playback stop app engine will not send notification to user, but send a event to client.

If some permits is not granted, then engine playback can be stopped:

  • at the playback start:
Start playback:
http://127.0.0.1:6878/ace/manifest.m3u8?id=c894b23a65d64a0dae2076d2a01ec6bface83b01&format=json&use_stop_notifications=1
{
    "extra_data": { 
        "reason": "missing_option",
        "option": "proxyServer"
    },
    "response": null,
    "error": "You need to buy Proxy Server option to continue"
}
  • sometime after playback was started:

If playback was stopped after some time, then engine will send a download_stopped event:

Start playback:
http://127.0.0.1:6878/ace/manifest.m3u8?id=c894b23a65d64a0dae2076d2a01ec6bface83b01&format=json&use_api_events=1&use_stop_notifications=1
{
    "response": { 
        "stat_url": "http://127.0.0.1:6878/ace/stat/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
        "command_url": "http://127.0.0.1:6878/ace/cmd/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
        "event_url": "http://127.0.0.1:6878/ace/event/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6",
        "playback_url": "http://127.0.0.1:6878/ace/m/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6.m3u8"
    },
    "error": null
}

Wait for event via event_url:
http://127.0.0.1:6878/ace/event/6d12f958332ef0bd258053ba1afd833ddf9b74f9/f528764d624db129b32c21fbca0cb8d6

At playback stop response should look like:
{
    "response": {
        "name": "download_stopped",
        "params": {
            "reason": "missing_option",
            "option": "proxyServer"
        }
    },
    "error": null
}

Player ID

Player ID (pid) - random string, used for player identification during engine connect session.

"Player ID" purpose - app engine must distinguish one player session from another, as in the current engine implementation user cannot play the same live stream with two (or more) players simultaneously from one engine, and engine will stop to serve requests from one player, when got a new request from another.