STB - Dive

    Good day to all.

    I think that many of you have heard about home television, and the proposal to buy a TV decoder (set-top box) in your home so that you can enjoy high-quality TV, buy movies, find out the weather, and do much more without leaving your TV.

    Now I will tell you what it is - this prefix, from the side of the software developer.
    If you are interested, welcome to cat.

    image


    What is a prefix?


    The prefix ( STB, Set-Top Box, box ) is a single-board computer on which the maximum truncated axis from the GNU / Linux family is installed .

    Uname -a command:
    # uname -a
    Linux (none) 3.1.5-1.7 #66 SMP Wed Oct 22 14:40:19 EEST 2014 mips GNU/Linux
    


    Boxes are usually weak.
    Strong representatives (and, accordingly, expensive) may have:

    • RAM - from 300Mb to 1Gb
    • Total space on the console - ~ 250Mb
    • Free space - ~ 5-20Mb (maybe there are more, but these are exactly the numbers that you have to work with)
    • Processor - up to 1.3Ghz (up to two cores)


    Each box has (the list contains only important elements):

    • Ethernet input - needed for IPTV (if IPTV box), integration with services, for connecting to a set-top box
    • HDMI output - no comment
    • Analog output - no comment
    • S / PDIF - No Comments
    • USB inputs are usually one input, but there are boxes that are designed to connect various flash drives and external hard drives at the same time, and therefore can have more inputs. Some boxes even support USB hubs.


    Depending on the task of boxing and some other factors, boxing may have:

    • SIM card entry - some consoles have a 3G module, and through the SIM card the user will be able to access the Internet without an Ethernet cable. In addition, messages from the operator can come to the SIM card, and the platform API allows you to work with SMS messages.
    • Signal input (satellite / cable input) - if the set-top box is satellite or cable, it is necessary for receiving digital broadcasts (in other words, so that you can connect to the streams of TV channels). In addition to broadcasting via cable, service information may come.
    • Entering a smart card - I will describe it a bit below.
    • Connector for Wi-Fi antenna - some boxes can work with Wi-Fi networks.


    Here it may look (pictures from the network, for example):

    image

    image

    What is JavaScript here?


    When a subscriber launches a set-top box at home, he sees a beautiful convenient portal, which he can use using the console from the set-top box.

    This portal is nothing more than a single-page application ( SPA - Single Page Application ) written in JavaScript , and open in the tab of the browser running on the console.

    When we turn on boxing (for nutrition), in the general case, the following happens (I do not describe all the excess):

    1. The axis of the console started
    2. The prefix launches the browser, and opens the HTML file in it


    It has its own characteristics:

    • On some consoles, the configuration file is writable - for example, you can change the path to the HTML file that will open in the browser tab when you start or restart the browser. In general, many settings are used to optimize the process of debugging code, no more.
    • On some consoles, not your portal’s HTML file is launched, but the console’s own portal, in which you use the remote control to enter the address of the file (or the address of your server, which distributes the sources), and then the browser simply opens the link that you entered.


    Added from rule :
    Not all consoles allow you to change the portal page or portal address. For example, Amino on your first page requires you to have special keys for this manufacturer. There are several access levels for this.


    It turns out that almost no skills for developing a portal on the console are needed? It is enough to configure the console, and learn how to deploy your application to it? - This is not entirely true .

    The prefix is ​​a platform with very low performance , and therefore development for the web and for boxing are completely different levels of complexity. That is why almost any coding error makes itself felt - your application will render incorrectly, render with a “ladder”, slow down, refuse to work, “crash” the browser, issue artifacts, erase memory, and much, much more. I will talk about this a bit later.

    Why do I need a prefix?


    • I am a subscriber - I want to hold a plasma on the wall, connect a prefix to it, and watch movies, satellite TV in high quality, find out if there are traffic jams in the morning when I go to work, and not make any effort.
    • I’m a telecom operator - I can sell (or, for example, rent) my set-top boxes to my subscribers, and through it I can sell services (selling films, channel packages, etc.) and make a profit.


    Accordingly, the vast majority of portals on the console are aimed at solving one big problem - on the one hand, create the possibility of selling services (selling movies, watching paid channels and much more), and on the other hand, make the most convenient application integrated with other services (card, mail, social networks, news, SMS, surfing the Internet and more), which allows you to watch TV and solve many other problems in one "box".

    If this is a normal browser, can we really implement all this? TV? Movies? SMS? - we can, because the prefix is ​​not just a box with a browser inside . Each box offers its own JavaScript API.

    JavaScript API prefixes


    In general, the prefix API can be divided into groups:

    • Console player APIs - methods to control playback.
    • API for receiving information about the current stream - subtitles, audio tracks, teletext, more ...
    • API for working with set-top box inputs - checking for HDMI, Ethernet cable, satellite cable, 3G availability, more ...
    • API for checking the availability of the connection - the presence of the Internet in the inserted cable, the presence or quality of a satellite signal, more ...
    • The API for working with the console storage is not on all boxes, but quite often the local browser storage is cleared after the console is restarted, therefore a separate API is used to save data between reboots.
    • API for receiving data - obtaining IP box, MAC address, box model, and more ..
    • Broadcast Network API - Channel Scan, more.
    • Boxing customization API - image enlargement format, aspect ratio, other ..
    • API for working with files and the file system - get the duration of a file, get a list of files on a USB flash drive, find out the video codec, more ...


    This is more than enough to solve most problems.

    How does the user interact with the portal?


    Each console comes with a control panel. Usually it contains buttons for solving basic tasks related to TV:

    • Navigation buttons - “Up”, “Right”, “Down”, “Left”, “Enter”, “Menu”, “Back”.
    • Volume control buttons - “Make it louder”, “Make it quieter”, “Mute”
    • Buttons for switching channels - “Next channel”, “Previous channel”
    • The playback control buttons are “Play”, “Stop”, “Pause”, “Rewind”, “Rewind”, “Start recording”. Depending on the manufacturer, some buttons may be missing or combined.
    • Numeric keypad - numbers and letters drawn on them. Needed to simplify character entry,
    • Colored buttons - for easier interaction with pages. Some logic is hung on these buttons depending on the state of the current page.
    • Switch on switch off
    • Other custom buttons - buttons leading to specific pages of the application, add. navigation control, and more.


    How does the portal interact with the console?

    When developing an application, you need to catch the click of a button and process it. Here, everything is quite simple - pressing a button on the remote control is treated like a regular pressing a keyboard key. One difference - the key codes for each vendor are different.

    Bonus-track - on some boxes, events “keyup” and “keydown” come simultaneously. Therefore, if you want to do the processing of pressing the remote control key (there are such cases), remember the picture of crutches_and_bicycles.jpg

    What we have?


    To summarize a quick summary of this quick introduction:

    • Boxing is a weak Linux machine
    • When you turn on the box, it launches the browser, and therefore the application on the console is a web application in its essence.
    • Work with boxing occurs through SSH or Telnet.
    • Boxing provides an API accessible from a browser for solving a wide range of tasks related to TV, audio / video files, and many others.


    Thus, any set-top box is a platform with low performance, with which you can solve problems one way or another connected with TV. There are all the necessary tools for this platform.

    It sounds good? - sounds great! However, in practice, everything does not sound so good, and now we move on to the more interesting, second part of the article: Notes

    Notes


    I repeat - the prefix is ​​a computer with sawn Linux, and the browser is screwed into an additional API, thanks to which most of the tasks facing the portal on the console become realizable.

    For us, only the second part of this statement is important - box makers finish browsers!

    Various browsers are installed in the boxes, but Opera or browsers on WebKit are most often found. As a result, drunk browsers begin to have a variety of bugs: memory leaks in the most unexpected places, a partially inoperative garbage collector, browser crash as a result of a very ordinary method call, rendering bugs, and much more.

    The notes that are written below are subjective conclusions based on full cones and rakes found.I really hope that they will be useful to you.

    Go..

    DOM operations


    DOM operations are the most difficult operations . On the console, this is very (!) Noticeable (in the literal sense).

    If the number of operations with the DOM is not minimized, then there is a possibility:

    • Get a very unpleasant effect - you will see (literally) how the page is drawn. In fact, this is Composite Layers, which works out very slowly, and therefore the page grid is redrawn with the naked eye (replacing one sector of the grid after another, and not all at once).
    • Spend a lot of time on rendering the page.


    The main problem arising from this is that UX spoils significantly. As a user, I want to press a button and see a page that instantly opens, without a mess of redrawing layers and waiting in 1-3 seconds. If I see this all the time, I’ll get unpleasant sensations from interacting with the portal. First of all, as a user, I want to experience the pleasure of interacting with the application, and think that I spent my money not in vain.

    Digging a little deeper - What exactly needs to be minimized?

    It is necessary to minimize or eliminate:

    • Inserting elements in batches - let's be friends with document.createDocumentFragment ().
    • Changing the style of elements - if it is possible to design the page so that in a particular case (for example, moving elements) you can change the style of one or two elements instead of a whole pack of elements, you need to use it.
    • Layout + redrawing the tree of elements. To understand what is at stake, I will give an example. For example, you have 3 layers (div) located next to each other. If you add the first border to them in 1px, then all layers will be redrawn instead of one. This extra load can be eliminated by designing the page in a different way.
    • Resizing an image - if you take an image 100x100 in size and place it by setting it to 90x90, this will be an extra load on the browser (the browser will compress the image). If you make a catalog with tiles, where each element contains an image, this will be an extra load. If possible, pull images of the size strictly necessary for you from the server, and do not overload the browser with unnecessary actions in this case.
    • Animation . The prefix can allow you to add animation to the application, but only a lightweight animation (scrolling a small list, menu, scrolling text). In other cases, the console will not have enough performance, and the animation will be jerky. You can completely forget about animating large page elements. There are two exceptions - canvas and CSS3 transformations. They work more or less (they do not slow down significantly, but not “60fps.” Let us call it tolerant), but this is an additional complexity in development.


    We summarize. Recipes for working with the DOM:

    • Use document.createDocumentFragment - one operation with the DOM is much more efficient than several (Captain Evidence is with you again).
    • Design a page with the minimum number of DOM modifications when interacting with the page.
    • Use layout with absolutely spaced elements.
    • Do not use images that do not fit your size.
    • Try to eliminate unnecessary load on the browser.
    • Try not to use transparency - this forces the browser to do more calculations.
    • Give up animations, or use canvas.


    CSS


    Without too much water, recipes for optimizing style sheets, and interacting with classes :

    • Try not to use nesting of more than one level - this is the load on the browser. If you make more nesting, when you change the layout, element classes or element styles, the browser will bypass much more nodes in order to generate an element style than with minimal nesting.
    • Do not use heavy selectors.
    • If you need to perform several operations (changing the style of an element) that cannot be combined, do them together, in a row. The browser determines this, and does not redraw (including does not recalculate styles) elements extra n-times.


    As a result, using CSS frameworks (e.g. Bootstrap) is undesirable.

    There is a great solution that gives a powerful performance boost - try to abandon classes, and generate layout with inline styles (style tag). Perhaps there are even plugins for Gulp / Grunt.

    A little about support for CSS properties. Most boxes have WebKit, and much of CSS3 is supported. If you are developing an application not for one box, but for several at once, then I do not recommend using various new “buns”. It is possible that they will work fine on one platform, and bugs will not arrive on the second.

    Add specifics. What is often supported (from CSS3; the list is very incomplete, based on real cases, from memory):

    • border-radius
    • rgba
    • linear gradient
    • text-overflow
    • background-size
    • Transformations
    • Animations
    • opacity
    • box-shadow
    • overflow-x
    • overflow-y
    • line-break
    • word-wrap
    • text-shadow
    • @ font-face
    • box-sizing
    • text-overflow


    Bugs


    In addition to the usual bugs that may arise as a result of incorrectly programmed logic, boxing can quite often lurk in non-obvious places.

    What are the bugs?

    Most often there are bugs related to page rendering: the div’s background was not drawn, the old background did not unload when the element was redrawn, when rendering the transparent border, the browser ignores all the layers below it (the page’s background is visible right away), and many other bugs.

    Bugs in the engine are less common: a call to the native method drops the browser, if the browser drops under special conditions, iteration over the keys of the object occurs in an unsorted form ( maybe not a bug, not a bug: from gibson_dev“That's the whole trick that it is by specification it is, only arrays are sorted, and the for..in construction does not guarantee this”), and other even more rare cases.

    A separate group of bugs is vendor bugs: streams work crookedly, the file system is not read correctly, answers are generated incorrectly when using the API, and much more.

    The moral of the above is to always thoroughly test your solution on all the platforms you support. If your solution works on one platform, then there is no guarantee that it will work on all of your other platforms.

    Memory leaks


    A memory leak on the console may be out of nowhere. Without examples, because there is no universal recipe for getting around this.

    The rule is simple - periodically run your application for memory leaks. If there are leaks, we are looking for where and close the "leak."

    Other


    How is the application usually deployed (during development)?


    There are few ways, and they are all simple. The whole deployment is to copy files from your machine to a folder on the box, or (even easier) to configure the console in such a way that it pulls the sources not from its file system, but from the network (for example, from your local server).

    I wrote about each method (as an instruction), but in order not to clutter up the article, everything is wrapped in a spoiler.

    Hidden text
    Method # 1 - Through a USB flash drive

    1. Putting our app together
    2. Copy the source to the USB flash drive
    3. Вставляем флешку в бокс
    4. Заходим на приставку через telnet или ssh (в зависимости от бокса)
    5. Заменяем исходники в директории, из которой приставка пытается запустить HTML файл (обычно это файл index.html)


    Способ #2 — Выкачиваем исходники со своей машины

    1. Разворачиваем сервер (например, на express'е), который раздает статику из директории в которую собирается ваше приложение
    2. Собираем приложение
    3. Архивируем приложение
    4. Заходим на приставку через telnet или ssh (в зависимости от бокса)
    5. Выкачиваем исходники с нашей машины (wget, curl)
    6. Заменяем исходники в директории, из которой приставка пытается запустить HTML файл (обычно это файл index.html)


    Я думаю что самый лучший способ — способ #3.

    Способ #3 — Без деплоя
    Этот способ будет работать, если вы можете указать приставке откуда ей тянуть HTML файл (почти на всех боксах это возможно).

    1. Разворачиваем сервер (например, на express'е), который раздает статику из директории в которую собирается ваше приложение
    2. Заходим на приставку через telnet или ssh (в зависимости от бокса)
    3. Редактируем конфиг бокса — указываем адрес HTML файла на вашем локальном сервере


    After restarting, the console browser will request a file from your server, and will pull out all the sources (scripts, styles, images, etc.) itself.



    Smart card


    In the boxes there may be a smart card. I am not an expert in this field, so we read about it on Wikipedia .

    In boxing, it can be present in two forms:

    • External card - you need to insert it yourself into a special entrance in the box.
    • An integrated card is wired inside the box, and in fact it is always “inserted” when the box is turned on.


    I won’t write anything else about it - I’m not a specialist, and I understand how it works only at the “touch-feel” level. I don’t want to lie to you by chance.

    Finish


    Boxing (prefix) is an interesting platform, working with which you can gain experience on how to write the most productive applications. Moreover, tons of interesting tasks and bugs when working with this platform will be provided to you with iron.

    If you like hardcore (in the good sense of the word) programming, single-page applications, and are looking for invaluable experience that will come in handy for you, try writing a console application.

    PS The

    article is an introductory one, and no specific features of the boxes of any specific vendors are considered. All in general, just to form an idea of ​​what a prefix is, and give basic information how to start working with it and where to expect complexity.

    When you first hold the console in your hands, it may be completely incomprehensible what it is, and I really hope that this article can serve as a starting point for someone to work with boxes.

    It will be great if there are additions to this article - write in the comments, I will add all the useful information to the text of the article.

    Also popular now: