User Tools

Site Tools


en:tvipjsapi:2

This is an old revision of the document!


Table of Contents

FIXME This page is not fully translated, yet. Please help completing the translation.
(remove this paragraph once the translation is finished)

TVIP JavaScript API #2

Version API #2
Avaliable for firmwares version linux-qt 3.4.0 or higher.

Set-top-boxes TVIP display Web-content using WebKit engine.

JavaScript API in Set-top-boxes Tvip is based on the following main objects:

  • window.TvipStb contains basic methods for operating with hardware;
  • window.TvipPlayer contains methods for control mediaplayer;
  • window.TvipRecorder contains methods for recorder control;
  • window.TvipEvent contains callback methods;

Objects do not require an explicit creation or any initialization and is accessible from any Web-page that is open in STB browser.

The main changes:

  • Support work with the manager of the mount (adding SMB and NFS share).
  • Sleep mode is now controlled via JS API in the portal mode “for the whole system”.
  • Possibility to remap for IR remote all systems commands in the portal mode “for the whole system”.
  • Support HDMI-CEC events.
  • Support events for transition application into background mode.

Description methods of objects JS API

TvipStb

bool addMountPoint(int id, bool temp, int type, String name, Object options);

Add or change mount point with indicated id. If temp equal true, then mount point will be saved after device reload, if false - then mount point will be deleted after reload or application restart.The possible mount points types (type): 1 - SMB, 2 - NFS. Point name at mount system (for example, at pop-up message): name. Parameter options set specific options as object:

SMB:

{
  "address": <address>,
  "folder": <folder>,
  "username": <username>,
  "password": <password>
}

Here, <address> - IP-adress, domain or NetBIOS-server name, <folder> - name of sharing content, <username> и <password> - optional authorization credentials.

NFS:

{
  "address": <address>,
  "folder": <folder>
}

Here, <address> - IP-adress or domain server name, <folder> - full path to sharing catalog.



int getApiVersion();

Returns API version.

String getCurrentLanguageCode();

Returns id of currently active interface language ('en', 'ru').

String getCurrentTimezone();

Return currently time zone (for example, Europe/Moscow).

String getDisplayMode();

Returns current display mode (“1080i”, “1080p”, “720p”, “576i”, etc).

List getDirectoryDirs(String directory);

Returns directory list in a specified directory.

[ "Dir1", "Dir2", "Dir3" ]



List getDirectoryFiles(String directory);

Returns file objects list in a specified directory directory. Object contains file name and file size.

[
  {
    "name": "file1",
    "size": 1234567
  },
  
  {
    "name" : "file2",
    "size" : 44444
  }
]

name -file name, size - file size in bytes.



String getEnvValue(String name);

Get variable from the browser store. If name not found, empty string returns.



String getMainMacAddress();

Returns main MAC address as string. Usually it's Ethernet interface mac.



List getSmbWorkgroups();

Returns windows network workgroup list. Example:

['WORKGOUP', 'MYGROUP']



List getSmbServers(String group);

Perform servers search in specified group network group and returns NetBIOS server names
Example:

['MYPC', 'USER2']



List getSmbServerShares(String server);

Returns names of available network shares by NetBIOS or IP address defined by server parameter. Example:

['shared folder', 'Downloads']



List getStorageValues();

Returns all mounted devises (local and network)

[
 {
   "label": <label>,
   "path" : <ospath>,
   "fstype" : <file_system>,
   "writable": <writable>,
   "status": <status>,
   "size": <size>,
   "free" <free>
 },

]

Object fields:
label - Resource name(label) visible to user;
path - mount point
fstype - FS type (e.g. vfat, ntfs, ext2, ext3, nfs, cifs;
writable - write access (“1” - yes, “0” - no);
status - mount point status (“0” - need mount, “1” - mount in progress, “2” - mount successfully, “3” - mount error, “4” - umount in progress, “5” - unmounted, “6” - umount error),
size - FS size,
free - Available free space.



bool hasDirectory(String osPath);

Returns true, if directory osPath exists. Otherwise returns false.



bool hasFile(String osPath);

Returns true, if file (not directory) with defined name osPath exists, false otherwise.



void launchPreferences();

Launch system preferences Tvip.



void logDebug(String message);

Output debugging message to terminal(Linux) or logcat(Android).



void rebootSystem();

Reboot system.



void removeMountPoint(int id);

Remove mount point from mount manager. id - Mount point identifier



void setColorKey(int color);

Setup UI color that could be consider as transparent for video layer. color in RGB model.



void setCustomHeader(String header, String value);

Define HTTP-header for browser. header - header name, value - header value. If value is empty, previously defined header will be purged.



void setEnvValue(String name, String value);

Save variable in browsers persistent storage. All variables are available for all browser pages.



void setDirectoryListFilters(String filters);

Setup filename filter for getDirectoryFiles and getDirectoryDirs. | Will be count as delimiter.
? and * applicable as well.
e.g. *.avi|*.mp3



void setPassKeyKeyboard(bool enabled);

If enabled=true, Cursor key press(on remote) event will be pass to Java Script directly, instead of default virtual keyboard handler.



void setPassKeyMenu(bool enabled);

If enabled==true, Remote “Menu” button press event will be pass to JS, instead of Tvip menu call.



void setPassKeySysInfo(bool enabled);

If enabled==true, remote press “S.INFO” event will be passed to JS, instead of Tvip system info call.



void setPassKeySettings(bool enabled);

If enabled==true, remote press “Settings” will be passed to JS, instead of Tvip settings menu call.



void setStandBy(bool enabled);

Switch STB in sleep mode (enabled==true) or return it to operation mode (enabled==false).

void showVirtualKeyboard(bool show);

Virtual keyboard show (show=true) or hide (show=false).



void reset();

Reset settings:
transparent color;
HTTP-header;
file filter.

TvipPlayer

void reset();

Reset playback. If we don't need playback after page change this routine should be called.



void playUrl (String url, String mode);

Starts playback defined URL(local path also welcome).

Parameter mode can be:

vod - URL contains VOD-file (with final length specified);

live - URL contains live TV-stream (Timeshift and DVR are welcome);

Examples:

playUrl ("udp://239.1.1.1", "live"); // Start play multicast-stream;
playUrl ("http://domain.tv/movies/movie.mkv", ""); // Start play file via http;
playUrl ("http://domain.tv/hls/playlist.m3u8", ""); // Start play HLS-video;



void setVideoWindow(int x, int y, int w, int x, boolean onTop);

Sets up video window size. Position seting up according current video out mode.

If w = 0 и h = 0, Full screen mode used.

If onTop = true, video window drows above UI.



void stop();

Stops playback if any.



void pause();

sets playback on pause.



void unpause();

Continue playback.



void seek(int position);

Set playback position in milliseconds. Keep in mind that beginning of playback is minPosition see below



int getCurrentPositionMsec();

Returns current playback position.



int getMinPositionMsec();

Returns minimal playback position (e.g. content beginning)



int getMaxPositionMsec();

Returns maximum playback position (e.g. content ends).



void setVolume();

Sets volume level from 0 to 100



int getVolume();

Returns current volume level from 0 to 100



void setMute(bool mute);

Turns off (mute=true) or turns on (mute=false) sound.



bool getMute();

Returns true, if muted, otherwise false;



String getContainerType();

Returns the type of container being played (e.g. mpegts, avi, matroska)



int getStreamsCount();

Returns content being played media streams count (audio, video, subtitles etc)



Object getStreamInfo(int index);

Returns an object with media stream info

{
  "type": <videotype>,
  "id": <id>,
  "codec": <codec>,
  "lang" : <lang>
}

Here:
videotype - media stream type;
“v” - video,
“a” - audio,
“s” - subtitles;
id - PID;
codec - codec name;
lang - Audio stream ISO 639 language code.



int getCurrentVideoStreamIndex();

Returns currently played video stream index.



int getCurrentAudioStreamIndex();

Возвращает номер потока с аудио-дорожкой, проигрываемой в данный момент.



void setCurrentAudioStreamIndex(int index);

Устанавливает номер активной аудио-дорожки (index).



void setAspectRatio (String ratio)

Устанавливает режим aspect ratio. На данный момент поддерживаются значения: “box” - Оригинал, “full” - На весь экран, “zoom” - Увеличенный.



TvipRecorder

String addRecord(String name, String url, String path, String start, String end);

Добавляет новое задание на запись эфира.
Здесь: name - произвольное имя записи, url - URL потока (поддерживаются потоки в формате MPEGTS через UDP, RTP и HTTP, path - локальный путь для записи, start и end - время начала и окончания записи в UNIX TIMESTAMP либо в формате “YYYYMMDDTHHmmss”.
Возвращает уникальный идентификатор созданного задания.



bool cancelRecord(String id, bool removeFile);

Удаляет задание на запись с уникальным идентификатором id. Если removeFile=true, удаляется также записанный на диск поток. Возвращает true в случае успешного удаления.



void updateStartEndTime(String id, String start, String end);

Меняет время начала и/или окончания записи с уникальным идентификатором id. Если требуется поменять только одно из значений, то второе - пустая строка. Формат start и end см. в описании addRecord.



List getRecordIds();

Возвращает список уникальных идентификаторов заданий, которые добавлены в настоящий момент.



Object getRecord(id);

Возвращает объект с параметрами записи с уникальным идентификатором id.

{
  "id": <id>,
  "name": <name>,
  "startTime": <start>,
  "endTime" : <end>,
  "url" : <url>,
  "status" : <status>
}

Здесь: <id>, <name>, <start>, <end> - соответствуют параметром метода addRecord; <status> - статус записи: “waiting” - ожидает запись, “recording” - запись в процессе, “finished” - запись завершена, “error” - произошла ошибка.



TvipEvent

TvipEvent consist of Callback functions, which may be overloaded for events capturing.

onPlayerStateChange(int oldState, int newState);

Calls on mediaplayer playback status change. oldState - previous player status, newState - new player status.

Player possible status:

  • 1 - Retrieving new URL;
  • 2 - получение метаданных;
  • 3 - Metadata received;
  • 4 - Decoders preparation;
  • 5 - Playback;
  • 6 - End of content;
  • 7 - Stopping playback;
  • 8 - Playback stopped;
  • 9 - Playback on hold;
  • 10 - Seek new position is in progress;
  • 11 - Error occured;

onSystemEvent(String codename, Object args);

On system event.
Examples codename:

  • “mounted” - External storage connected and ready to use (args[“label”] - device label).
  • “unmounted” - External storage is gone (args[“label”] - device label).
  • “onpause” - Web-app window goes to background (eg, active Home or Settings screen).
  • “onresume” - Web-app window become active (Calls on application resume).
  • “cec_sleep” - HDMI connected TV turns OFF.
  • “cec_wake” - HDMI connected TV turns ON.
en/tvipjsapi/2.1443540141.txt.gz · Last modified: 2015/09/29 18:22 by Alexi