top

AllSHare Tutorial for SDK 4.5

Published 2014-10-28 | (Compatible with SDK 3.5,4.5,5.0,5.1 and 2012,2013,2014 models)

This tutorial describes AllShare API usage and includes information about sample widget application working under Samsung SDK 4.5 and 2013 devices.

Note

This tutorial is compatible with Samsung SDK 4.5. If you are using an earlier version, see the AllShare Tutorial for SDK 3.5.

Media providers

MediaProvider

Application can get information about MediaProvider using next attributes:

id
is string with uniq device id, for DLNA devices it is UDN from device description
deviceDomain
is string value of device domain
deviceType
is string value of deviceType e.g. “MEDIAPROVIDER”
iconArray
array of icons info objects
ipAddress
media providers IP address
modelName
media providers model name
name
media providers name, for DLNA devices it is friendly name from device description
isSearchable
boolean flag, true value if media provider supporting Searching
rootFolder
root folder item, is used for browsing

IconArray

IconArray object has next attributes:

depth
icons bits per pixel
height
icons heigth in pixels
width
icons width in pixels
mimeType
icon file mimetype, DOMString
iconUri
icon URL, DOMString

Device discovery

To access get MediaProviders list. Application needs to do next calls.

  1. Create ServiceProvider
  2. Get ServiceProvider object
  3. Get DeviceFinder object from ServiceProvider
  4. Set device discoveryListener to DeviceFinder object. To obtain appear or disappear events.
  5. Access devices list using getDeviceList()

Code example

function serviceProviderCreateSuccessCallback(serviceProvider) {
    alert("serviceProviderCreateSuccessCallback()");
}

function serviceProviderErrorCallback(error, state) {
    alert("serviceProviderErrorCallback() error.name: " + error.name + "  error.message:" +error.message + "  state:" + state);
}

try {
    // need to create ServiceProvider first
    window.webapis.allshare.serviceconnector.createServiceProvider(serviceProviderCreateSuccessCallback, serviceProviderErrorCallback);
} catch(e) {
    // e. WebAPIException
    alert(" exception : " + e.name + "(" + e.code + ") :" + e.message);
}

function showMediaProviderInfo(mediaProvider) {
    alert("mediaProvider.name:" + mediaProvider.name);
    alert("mediaProvider.id:" + mediaProvider.id);
    alert("mediaProvider.ipAddress:" + mediaProvider.ipAddress);
    for (var iconIdx = 0; iconIdx < mediaProvider.iconArray.length; iconIdx++) {
        alert("icon.iconUri:" + mediaProvider.iconArray[iconIdx].iconUri);
    }
}

var serviceProvider = window.webapis.allshare.serviceconnector.getServiceProvider();
if (serviceProvider) {
    var deviceFinder = serviceProvider.getDeviceFinder();
    if (deviceFinder) {
        var deviceDiscoveryCallback = {
            ondeviceadded : function (d) {
                    alert("ondeviceadded: " + d.name);
                    showMediaProviderInfo(d);
                },
             ondeviceremoved : function (d) {
                     alert("ondeviceremoved: " + d.name);
                }
        };

        var listenerId = deviceFinder.addDeviceDiscoveryListener(deviceDiscoveryCallback);

        var deviceType = "MEDIAPROVIDER";
        var mediaProvidersArray = deviceFinder.getDeviceList(deviceType);

        for (var i = 0; i < mediaProvidersArray.length; i++) {
            var mediaProvider = mediaProvidersArray[i];
            showMediaProviderInfo(mediaProvider);
        }
    }
}

Media Items

Item

Item object keeps information about any media items: folders, audio, video, images. Item has next attributes:

itemType
Get item type. Type DOMString. Possible values : “FOLDER”, “AUDIO”, “VIDEO”, “IMAGE”, “UNKNOWN”.
title
Item title. DOMString format.
fileSize
fileSize in bytes. Numeric value.
itemUri
URL pointing to contenst of this item. DOMString format.
mimeType
mimeType of item. DOMString format.
thumbnailUri
URL pointing contents thumbnail. DOMString format.
duration
for audio/video it is media duration in seconds. Numeric format.
date
media creation date. Date object format.
albumTitle
Album title. DOMString format.
artist
Artist name. DOMString format.
genre
Genre. DOMString format.
width
Contents width for video/images. Numeric format.
height
Contents height for video/images. Numeric format.
extension
For media items it included file extension. DOMString format.
subtitleUri
URI of subtitles for video items. DOMString format.
isRootFolder
Boolean format.

To distinguish folder item use next:

Code example

var itemType = item.itemType;
if (itemType == "FOLDER")  {
    // it is folder
}

Example: function printItem()

Next example shows how to access and print media item information.

Code example

function printItem(item) {
    if (item) {
        alert("  albumTitle: " + item.albumTitle);
        alert("  artist: " + item.artist);
        alert("  date: " + item.date);
        alert("  duration: " + item.duration);
        alert("  extension: " + item.extension);
        alert("  fileSize: " + item.fileSize);
        alert("  genre: " + item.genre);
        alert("  location: " + item.location);
        alert("  mimeType: " + item.mimeType);
        alert("  width: " + item.width);
        alert("  height: " + item.height);
        alert("  subtitleUri: " + item.subtitleUri);
        alert("  thumbnailUri: " + item.thumbnailUri);
        alert("  title: " + item.title);
        alert("  itemType: " + item.itemType);
        alert("  itemUri: " + item.itemUri);
        alert("  isRootFolder: " + item.isRootFolder);
        alert("  contentBuildType: " + item.contentBuildType);
    } else {
        alert("item == null");
    }
}

Browsing contents

Contents Navigation: using browse()

To navigate through contents structure similar to computers folders next API exists in MediaProvider object:

rootFolder
attribute, let to access root of folder structure, type of result is Item, with itemType == "FOLDER"
browse()
it is asynchronous function, it obtain callback handlers for success and error cases.

Code example

var browseHelper = {}; // helper object, what will implement browse functionality
browseHelper.resultItems = []; // this variable will keep finded items
browseHelper.showFolderContents = function ()  { // this function executed when folder contents readed fully
    for (i = 0; i &lt; resultItems.length; i++) {
        showMediaItemInfo(resultItems[i]);
    }
}

browseHelper.browseFolder = function (mediaProvider, folderItem) { // this function doing request for all items in folder
    var self = this;

    // this function is callback, it called when items readed
    var mediaProviderSuccessCallback = function (sc_itemList, sc_fEndOfItems, sc_providerId) {
        alert("success callback");
        alert("itemsList.length : " + sc_itemList.length);
        alert("fEndOfItems : " + sc_fEndOfItems);

        // copy result into 'resultItems'
        self.resultItems = self.resultItems.concat(sc_itemList);
        alert("add items into resultItems, new length :" + self.resultItems.length);

        // all items readed
        self.showFolderContents();
    }

    // this function is callback, it called when error happend during items request
    var mediaProviderErrorCallback = function (webAPIError, providerId) {
        alert("webAPIError:" + webAPIError.name + "/" + webAPIError.message);
    }

    self.resultItems = [];
    var startIndex = 0;
    // zero value means read all elements of folder
    var requestCount = 0;

    try {
        mediaProvider.browse(folderItem, startIndex, requestCount, mediaProviderSuccessCallback, mediaProviderErrorCallback);
    } catch(e) {
        alert("browseItems exception:" + e.name + "/" + e.message);
    }
}

// calling part
var mediaProvider = ???;
var folderItem = mediaProvider.rootFolder;
browseHelper.browseFolder(mediaProvider, folderItem);

This code requesting all items located in folder.

Searching contents

Playing contents

Contents playing

Application can access contents of media items through contents URL. For next examples, next html code used:

<html>
    <body>
        <div id="div_id_item">Item viewer</div>
    </body>
</html>

Samsung TV browser included support for html5. Video and Audio playing will use <video> and <audio> tags of html5.

Displaying images

Browser has embedded support for displaying images.

Code example

function showImageViewer (url) {
    var viewerHtml = "<table border=1><tr><td>";
    var url = self.currentItem.getURI();
    if (url) {
        viewerHtml += "<img src=\"" + url + "\"  height=400 width=600>";
    }
    viewerHtml += "</td></tr></table>";
    var element = document.getElementById("div_id_item");
    if (element) {
        element.innerHTML = viewerHtml;
    }
}

Playing audio

Tag <audio> can be used for audio playing.

Code example

function showAudioPlayer(url) {
    var viewerHtml = "";
    var playerId = "playerId";
    var url = self.currentItem.getURI();
    if (url) {
        viewerHtml += "URL : " + url + "<br>";
        viewerHtml += "<audio id=\"" + playerId + "\" src=\"";
        viewerHtml += url + "\" controls=\"controls\"> Browser does not support the audio tag</audio>";
    }
    var element = document.getElementById("div_id_item");
    if (element) {
        element.innerHTML = viewerHtml;
    }
}

Playing video

AVPlay API can be used for video playing.

Code example

function showImage(url) {
    var playerId = PLAYER_ID;
    var videourl = self.currentItem.getURI();


    var playSuccessCB = {
        console.log("playing the video is successfully.");
    };

    function successCB(avplayObj) {
        avplayObj.init();
        avplayObj.open(videourl);
        avplayObj.play(
            playSuccessCB,
            function (error) {
                console.error(error.message);
            },
            5
        );
    }

    function errorCB(error) {
        console.log("Cannot get avplay object : " + error.name);
    }

    try {
        webapis.avplay.getAVPlay(successCB, errorCB);
    } catch (error) {
        console.log(error.name);
    }
}

Sample AllShare widget application

Sample widget view

This is screen shot of Sample widget, in contents browsing mode:

Sample widget in emulator

Files structure

File structure:

  • AllShareApiTest/
    • icon/ - this folder included test application icons
      • icon_af_106.png
      • icon_af_115.png
      • icon_af_85.png
      • icon_af_95.png
    • allshare_api_test.js - sample application
    • allshare_api_test_debug.js - debug messages part are here
    • allshare_api_test.css - styles are here
    • config.xml - it is widget configutation file
    • index.html - main widget file (SmartHub engine loaded it to start widget)

File: config.xml

Contents of config.xml file

<?xml version="1.0" encoding="UTF-8"?>
<widget>
    <ThumbIcon>icon/icon_af_106.png</ThumbIcon>
    <BigThumbIcon>icon/icon_af_115.png</BigThumbIcon>
    <ListIcon>icon/icon_af_85.png</ListIcon>
    <BigListIcon>icon/icon_af_95.png</BigListIcon>

    <category>information</category>
    <autoUpdate>n</autoUpdate>

    <cpname>Samsung</cpname>
    <cpauthjs></cpauthjs>
    <login>n</login>

    <ver>1.3.0.10</ver>
    <mgrver>2.000</mgrver>

    <fullwidget>y</fullwidget>
    <srcctl>y</srcctl>
    <ticker>n</ticker>
    <childlock>n</childlock>
    <audiomute>y</audiomute>
    <videomute>y</videomute>
    <dcont>y</dcont>
    <movie>y</movie>

    <widgetname>AllShare WebAPI 1.3</widgetname>
    <description>AllShare WebAPI 1.3 sample application</description>

    <type>user</type>

    <width>1280</width>
    <height>720</height>

    <author>
        <name>Yevgen</name>
        <email>yevgen@</email>
        <link>http://www.sec.co.kr/</link>
        <organization>Samsung Electronics Co. Ltd.</organization>
    </author>
</widget>

File: index.html

Contents of index.html file

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>SmartHub AllShare test app</title>

        <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/Widget.js"></script>
        <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script>

        <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/webapi/1.0/webapis.js"></script>

        <link type="text/css" rel="stylesheet" href="allshare_api_test.css">
        <script type="text/javascript" language="javascript" src="allshare_api_test_debug.js"></script>
        <script type="text/javascript" language="javascript" src="allshare_api_test.js"></script>
    </head>
    <body onload="astMain.onLoad();">
        <a href="javascript:void(0);" id="anchor" onkeydown="astMain.keyDown();"></a>
        <div><span id="div_id_version_info" class="versionInfo"></span></div>
        <table border=1>
            <tr>
                <td style="vertical-align:text-top;">
                    <div id="div_id_devices_list" style="background-color:#0B0B61;color:#D8D8D8;">div_id_devices_list</div>
                    <div id="div_id_browse_path" style="background-color:#0B615E;color:#D8D8D8;">div_id_browse_path</div>
                    <div id="div_id_browse" style="background-color:#08298A;color:gold;">div_id_browse</div>
                </td>
                <td>
                    <div id="div_id_item"  style="background-color:white;">div_id_item</div>
                    <div id="div_id_keyword" style="background-color:#0B3B17;color:#e8e8e8;">div_id_keyword</div>
                </td>
            </tr>
        </table>
        <div id="div_id_item_info"  style="background-color:#0A2A29;color:#D8D8D8;">div_id_item_info</div>
        <div><span id="div_id_waiting_response" class="waitingResponse"></span><span id="div_id_helper" style="background-color:#088A68;">div_id_helper</span></div>
        <div id="div_id_log"  style="background-color:#3B0B0B;color:#D7DF01;">div_id_log</div>
    </body>
</html>

The index.html consists of next inportant parts:

  • Including widgets objects definitions:

    <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/Widget.js"></script>
    
  • Including definition for TV Keys codes:

    <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script>
    
  • Including implementation of AllShare API:

    <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/webapi/1.0/webapis.js"></script>
    
  • Including javascript code of test application:

    <script type="text/javascript" language="javascript" src="allshare_api_test_debug.js"></script>
    <script type="text/javascript" language="javascript" src="allshare_api_test.js"></script>
    

File: allshare_api_test.js

This file included test application source code.

Features:

  • Getting current list of media providers
  • How to handle mediaprovider adding/removing events
  • Demonstrate browse() function
  • Navigation through folders structure
  • Demonstrate search() function
  • Contents viewer

SDK emulator

It is possible to run test application in Samsung SmartHub SDK 4.5 emulator for 2013 models.

You can download SmartHub SDK from SDK Download page.

If SDK installed using default settings then copy sample application folder AllShareApiTest to: C:\Program Files\Samsung\Samsung TV SDK(4.5)\apps .

Then run 2013 emulator, and open test app in it, using Open App dialog.

How to use

Sample widget shows helper line (it has green background). This line included information about current mode and list of supported keys.

After start, application will show list of available media providers.

Up/Down keys at remote control is used for navigation through media providers list.

Enter/Left key let to choose media provider.

Application will automatically show contents of root folder.

Up/Down/Left/Right keys are used for navigation through contents structure.

Left key in root folder return back to selection of media providers.

Pressing Right/Enter keys on media item will display it.

Notes

Terminology & Acronyms

UPnP Universal Plug and Play
DLNA Digital Living Network Alliance
DMR Device Media Renderer
CP Control Point
DMS Device Media Server

References

  • Samsung API Specification
  • UPnP forum: http://www.upnp.org
  • UPnP device architecture Version 1.0
  • UPnP AV Architecture:0.83 For Universal Plug and Play Version 1.0
  • ContentDirectory:1 Service Template Version 1.01
  • DLNA Alliance: http://www.dlna.org
  • DLNA Guidelines August 2009, Volume 1: Architectures and Protocols
  • DLNA Guidelines August 2009, Volume 2: Media Format Profiles