Кодинг для Chromecast. Транслируем видео на телевизор из своего приложения для Android

Overall design principles

Keep the following in mind as you develop your user interface.

Receiver interface:

  • The receiver should not have any interactive elements, only informational
    elements to describe the state of the app, such as paused or playing, or
    error messages. User interaction should only take place on the Cast sender
    (phone, tablet, or Chrome browser), not the Cast receiver (TV).
  • Remember that the video action is happening in the middle of the TV screen,
    and your UI elements should not interfere with the presentation. Place UI
    elements within the lower third of the receiver display, leaving a 10%
    margin from the edges of the screen for possible
  • The UI should use transparency and visual nuance to prevent overpowering the
    content. The experience should not feel like a «computer» UI.
  • When possible, transitions from one screen state to another should be smooth
    and feel cinematic. Rather than abrupt moves from state to state, use
    transitions like fade-in and fade-out. For example, the content-loading
    state lingers on-screen and fades into the media playing experience.

Sender interface:

  • The sender supports user actions and the receiver displays state information.
    For example, if content is paused, the TV should indicate that it is paused,
    while the mobile device indicates it is ready to start playing (for example,
    showing the user a play button).
  • Portrait is the preferred orientation for a sender app on a mobile phone.
    It’s the natural orientation for a phone and the user can control the app
    with just one hand (or thumb). While watching videos is usually best in
    landscape, portrait tends to be easier for the user to control the video on
    the TV. Your sender app should also work well in landscape orientation
    for tablets and laptops.
  • Speed matters. Users need to be able to quickly locate the casting control
    and see content start playing immediately on the large screen. While content
    is loading, provide animated loading indicators and use transitions to help
    make things feel faster.

The easiest way to ensure that your Cast application follows these principles is
to review your user interface with the Cast Design Checklist
and test your Cast applications.

Chromecast

По словам Википедии, Chromecast — цифровой медиаплеер, предназначенный для воспроизведения потокового видео- или аудиоконтента с помощью Wi-Fi из интернета либо из локальной сети. При этом никаких органов управления он не имеет, то есть, в отличие от TV-Stick’ов, требует внешнего управляющего устройства, такого как компьютер или смартфон.

Chromecast «светит» HDMI-разъемом

По определению, основным источником видеоконтента для Chromecast из интернета служит YouTube. Если браузер или официальное мобильное приложение обнаружат в сети работающий Chromecast, в интерфейс будет добавлена соответствующая кнопка, запускающая трансляцию на большой экран. Помимо YouTube, донгл от Google поддерживают такие сервисы, как Twitch, Amediateka, Deezer, и многие другие.

Трансляция с YouTube

Что касается локальных файлов, то самый простой способ воспроизвести что-либо медийное через Chromecast — это перетащить видео- или аудиофайл в окошко браузера Chrome с установленным плагином Google Cast и нажать все ту же заветную кнопочку. И никаких плясок с бубном вокруг DLNA-устройств!

Запуск трансляции из браузера Chrome

У этой простоты, правда, есть и неприятная сторона — Chromecast поддерживает далеко не все кодеки сжатия. Например, видео в контейнерах MKV и MP4 воспроизводится уверенно, тогда как AVI устройство не переваривает. В этом случае потребуется установить транскодер (например, BubbleUPnP Server), конвертирующий видео на лету, или использовать специализированный сервис (например, Videostream). Вообще, «Хакер» уже касался этой темы, разбирая все мыслимые и немыслимые лайфхаки Chromecast, — повторяться не будем, а перейдем непосредственно к нашей теме.

INFO

Если ты не в курсе, Chromecast дешев по сравнению с аналогами: цены на версию 2013 года начинаются с 2000 ₽, а версию 2015 года можно найти за 3000 ₽. На «Авито» цены еще ниже — посмотри, если не боишься связываться с б/у.

Постановка задачи

Итак, допустим, у нас есть внушительная коллекция фильмов (разумеется, не торренты и не мелодрамы с отважными немецкими сантехниками ;), а, скажем, лицензионные… мультики), которую мы хотим через Chromecast посмотреть на большом экране.

Так как Chromecast работает с потоковым видео, нам потребуется поднять локальный сервер на компьютере (подойдет даже такой легковесный, как HTTP File Server). В моем случае ничего настраивать вообще не пришлось: весь видеоконтент хранится на домашнем сетевом диске (NAS) с уже работающим сервером на базе Apache. Будем считать, что этот этап мы успешно прошли и новоиспеченный сервер отдает видео по ссылкам вида:

и так далее (кстати, вместо IP можно использовать сетевое имя).

Cast SDK vs. Cast Companion Library

Для работы с Chromecast существует официальный инструмент — Cast SDK, анонсированный Google сразу же после выхода донгла на рынок. SDK включает объемную документацию и изобилует множеством примеров на все случаи тележизни. С другой стороны, инструментарий страдает некоторой «низкоуровневостью» и предполагает написание (копи-пасты, чего уж там) объемного кода взаимодействия с устройством — обнаружение в сети, регистрация, настройка, колбэки и прочее, что несколько выходит за рамки простого воспроизведения медиаконтента на экране телевизора.

К счастью, Google не была бы Google, если бы и здесь не решила облегчить жизнь Android-разработчикам, выпустив вполне удобную обертку в виде библиотеки Cast Companion Library. Говоря избитой фразой, теперь разработчики могут сосредоточиться на написании функциональности приложения, а не обвязки.

Нам Cast Companion Library подходит как нельзя лучше, так что не забудь скачать pdf-мануал и скорее запускай Android Studio.

Sender и Receiver Applications

Приложения для Chromecast бывают двух видов: Sender (передатчики) и Receiver (приемники).

Те, которые работают непосредственно на девайсе, относятся ко второму типу. Обычно они пишутся на связке HTML5/JavaScript и отвечают за графический интерфейс программы на экране ТВ, а также всячески взаимодействуют с передатчиками — обрабатывают управляющие сообщения, обеспечивают обратную связь (характерно для приложений и игр).

Передатчики (Sender Application) настраивают контент для воспроизведения на ТВ посредством ссылок или потокового видео (аудио), формируют очередь, контролируют работу Chromecast. Официально поддерживаются мобильными ОС Android и iOS (Windows Mobile опять «где-то рядом») и платформой Chrome.

Шаг 2. Настраиваем VideoCastManager

Всей логикой взаимодействия с Chromecast занимается специальный класс . Он же отслеживает состояние устройства в сети, дергает колбэки — в общем, сильно упрощает жизнь программисту своим API. Как следует из документации, является почетным синглтоном. Чтобы не зависеть от жизненного цикла активности или фрагмента, имеет смысл инициализировать VideoCastManager в объекте Application, также одиночке:

Класс CastConfiguration определяет конфигурацию работы приложения с Chromecast. В частности:

восстанавливает соединение после разрыва, а — после смены Wi-Fi-сети; включает отладочный режим (требует регистрации устройства — см. врезку); разрешает управление воспроизведением на экране блокировки (без ввода пароля); — то же самое, но в области оповещений.

В последнем случае определяет те органы управления (кнопки), которые пользователь увидит в шторке смартфона. В нашем случае это пауза/воспроизведение () и отключение от девайса (). Всего же определены шесть стандартных действий: Play/Pause, Next, Previous, Fast Forward, Rewind и Disconnect.

Описание остальных свойств и констант можно подсмотреть в исходнике библиотеки на GitHub’е.

Отдельно стоит упомянуть параметр applicationId, передаваемый в конструктор CastConfiguration. Это, как следует из названия, уникальный идентификатор приложения. Получить его можно, отправив СМС на короткий номер Google ;), или посетив небезызвестную консоль разработчика (для справки — ).

Но делать это совсем не обязательно, если приложение использует стандартный проигрыватель (так называемый Default Media Receiver) со стандартным интерфейсом пользователя (примерно как на YouTube). А вот если ты захочешь при воспроизведении лицезреть свой логотип или, например, нарисовать свои скевоморфные кнопочки управления — регистрация обязательна. В нашем случае возможностей стандартного проигрывателя хватает с лихвой, поэтому смело передаем и двигаемся дальше.

Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте

Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score!
Подробнее

Вариант 2. Открой один материал

Заинтересовала статья, но нет возможности стать членом клуба «Xakep.ru»? Тогда этот вариант для тебя!
Обрати внимание: этот способ подходит только для статей, опубликованных более двух месяцев назад.

Я уже участник «Xakep.ru»

Дизайн

Плеер выглядит как небольшой диск (диаметром около 5 см и чуть меньше полутора сантиметров в толщину) с коротким кабелем HDMI (длиной 11 см вместе с разъемом). Сверху корпус выполнен из черного глянцевого пластика с рельефным логотипом Chrome по центру, низ и боковая грань – серый матовый пластик, под цвет HDMI-кабеля.

В разъем вмонтирован небольшой магнит, поэтому в «походном состоянии» он «приклеивается» к низу плеера. Напротив кабеля HDMI на боковой грани можно найти порт micro-USB, рядом с ним – кнопку сброса настроек на заводские установки (кнопка включения у плеера отсутствует).

Такое решение оказывается более удобным при подключении плеера к телевизору по сравнению с HDMI-стиком, в виде которого был выполнен первый Chromecast.

Considerations

Due to hardware and resource limitations, there are certain restrictions placed
on Chromecast-enabled applications:

  • The Cast device is a low-power device with memory, CPU and GPU
    limitations, so the receiver application should be as lightweight as
    possible.
  • Given the nature of the Cast interaction model, tabs, windows or popups
    cannot be created in the receiver app, nor can the receiver app directly
    accept user input, such as taps or swipes. For example, the receiver app
    can display a pause button, but cannot receive a user’s tap —
    instead, the user must tap on the sender’s pause button.
    In this way, all actions on the application must be triggered
    from a sender application.

    The Cast receiver is a Chrome browser optimized for video playback. As such,
    WebGL and Chrome Native Client (NaCL) are not currently supported, nor are
    Chrome extensions.

  • Cast supports a single concurrent media stream playback in the
    and tags, or multiple audio tracks using the
    WebAudio API. Only one video element may be active in the DOM at any time.
    Additionally, video compositing, manipulation, transformations, rotations or
    zooming are not supported.

Аппаратная платформа

В «хромкасте» второго поколения используется новый чип Marvell Armada 1500 Mini Plus 88DE3006 (в предыдущей модели — Marvell Armada 1500 Mini 88DE3005-A1). В его основе лежит двухъядерный процессор ARM Cortex-A7, быстродействие которого, по заявлению производителя чипа, в 2.5 раза выше, чем у предшественника (одноядерного ARM Cortex-A9). За беспроводную связь отвечает Marvell Avastar 88W8887, добавивший в Chromecast поддержку Wi-Fi 802.11ac. Объем оперативной памяти остался неизменным – ее по-прежнему 512 МБ. А вот размер внутреннего хранилища значительно уменьшился – с 2 ГБ до всего лишь 256 МБ. В плеере используется пассивное охлаждение, поэтому он абсолютно бесшумен в работе; корпус при этом нагревается весьма умеренно.

Common namespace data structures

A superset of data structures used by all media namespace artifacts is defined in a common namespace.

Image

This is the description of an image, including a small amount of metadata to allow the sender application a choice of images, depending on how it will render them.

The height and width are optional on only one item in an array of Images. For example, if there is a single item returned, then they are optional; if there are two items returned, one item must specify a height and width, but the sender may choose to go with the «default» option if it does not like the one passed with specific parameters.

Name Type Description
url URI URI for the image
height integer optional Height of the image
width integer optional Width of the image

Volume

The media stream volume. Used for fade-in/fade-out effects on the media stream. (Note: system
volume is changed using the sender APIs.) Stream volume must not be used in conjunction with
the volume slider or volume buttons to control the device volume. At least one of the following
params must be passed to change the stream volume.

Name Type Description
level double optional Current stream volume level as a value between 0.0 and 1.0 where 1.0 is the maximum volume.
muted boolean optional Whether the Cast device is muted, independent of the volume level

Постановка задачи

Итак, допустим, у нас есть внушительная коллекция фильмов (разумеется, не торренты и не мелодрамы с отважными немецкими сантехниками ;), а, скажем, лицензионные… мультики), которую мы хотим через Chromecast посмотреть на большом экране.

Так как Chromecast работает с потоковым видео, нам потребуется поднять локальный сервер на компьютере (подойдет даже такой легковесный, как HTTP File Server). В моем случае ничего настраивать вообще не пришлось: весь видеоконтент хранится на домашнем сетевом диске (NAS) с уже работающим сервером на базе Apache. Будем считать, что этот этап мы успешно прошли и новоиспеченный сервер отдает видео по ссылкам вида:

и так далее (кстати, вместо IP можно использовать сетевое имя).

Check your Chrome version

  • In your Chrome browser URL bar enter chrome:chrome.
  • In your Chrome browser:
    • On a PC, click More  Help  About Google Chrome.
    • On a Mac, click More   Help  About Google Chrome.
    • On a Chrome OS computer, click More   Help  About Chrome OS.

If your version is below 53, install any updates and click Relaunch to restart your browser.

Teachers and students: If your Chrome device is locked to a lower version, contact your administrator.

Administrators: Ensure that you are not .

Administrators: Enable Cast 

By default, Cast is enabled. If it’s not, you can enable it:

  1. Sign in to the Google Admin console.
  2. From the dashboard, click Device management.
  3. Under Device Settings, click Chrome management.
  4. Click User settings.
  5. Under Content, scroll down to Cast.
  6. At Allow users to Cast from Chrome, click Down Allow user to Cast.
  7. Click Save.

Administrators: Pre-install the Google Cast for Education extension for teachers

  1. Sign in to the Google Admin console.
  2. From the dashboard, click Device management.
  3. Under Device Settings, click Chrome management.
  4. Click User settings.
  5. Select the organizational unit that will use Google Cast for Education.

    Tip: If you want everyone in an organizational unit to have access, select the top-level unit. Otherwise, select a department in that organizational unit.

  6. Go to Apps and Extensions Force installed Apps and Extensions, and click Manage force-installed apps.
  7. Click Chrome Web Store and search for «Google Cast for Education». Or, search for the ID:  «bnmgbcehmiinmmlmepibeeflglhbhlea».
  8. Next to the extension, click Add.
  9. Click Save.

Teachers: Set up Cast for Education

Make sure your Chrome browser is , and that you are signed in with your G Suite for Education account.

Name your receiver

The first time you open Cast for Education, you’re asked to name your receiver—that’s your computer. When students request to share their screens with you, they’ll see the name you gave your computer.

Once you set up Cast for Education, your settings are saved on that device.

  1. To open the extension, click Google Cast for Education . Don’t see the extension? Click Menu or More Cast.
  2. Under Receiver name, enter a name for your cast extension, such as Room 301. Click Save.
  3. Click Share .
  4. To invite your students to cast, enter the name of a Classroom class or individual student email address and click Add.
  5. Select a level of access for each student or class:
    • Can present—Students can cast to your screen anytime you have the extension open.
    • Can request—Students can request to cast. You need to approve or deny each request.
    • Note: Students that aren’t on the list won’t see the extension in their Chrome toolbar.
  6. Click Close.

Accept a request to cast

To start accepting casts from your students, open the Cast for Education extension on your computer. While the extension is open, you can cast or anyone you’ve shared the extension with can request to cast or can present if you permitted casting without a request.

Casts appear in your Cast for Education extension on the teacher device connected to the projector.

Students: Cast to your teacher’s screen

Make sure your device is updated and that you’re signed in with your G Suite for Education account.

  1. In your Chrome toolbar, click Cast . If there is no Cast icon in your Chrome toolbar, click Menu or More Cast.
  2. Click the name of your teacher’s cast extension, such as Room 301.
  3. (Optional) To switch between casting your whole screen and your current tab, click Cast to and make a selection.

Your screen casts to the Cast for Education extension on the teacher’s computer.

Brand guidelines

The following Chromecast brand guidelines are for app developers and focus on
the additional requirements you must comply with to describe your app in text.
If you are looking for brand guidelines for Cast devices, please fill out
this form to access device-specific
guidelines.

You can let others know that your app works with Chromecast built-in by using
the term «Chromecast-enabled». However, please be sure that your app complies
with the Cast SDK Additional Developer Terms of Service
and the Design Checklist, and that your
use of «Chromecast-enabled» complies with our branding guidelines.

You can similarly use a as long as your
app or device complies with our badging guidelines. Google reserves the right to
request that you modify or cease your use of the badge if it does not comply
with the brand guidelines.

Using «Chromecast» in text

  • When describing an app (not a hardware product) as being Cast-enabled, use
    the phrase «Chromecast-enabled». For example: «This app is Chromecast-enabled».
  • When describing a Cast compatible third-party hardware product, use
    «Chromecast built-in TV», «Chromecast built-in Speaker» or just «Chromecast
    built-in».
  • When written in text, «Chromecast» should be capitalized, and «built-in»
    should be lowercased.
  • In any marketing asset that uses «Chromecast» in text or the badge/logo, you
    must include the following legal attribution: Chromecast is a trademark of
    Google LLC.
  • Do not put Chromecast in the title of the app (such as XYZ Chromecast App).

Chromecast-enabled app messaging

You can promote your app as follows:

  • «XYZ is a Chromecast-enabled app which lets you stream your favorite
    entertainment from your mobile device to your TV.»
  • «The XYZ app is now available for TVs with Chromecast built-in.»
  • «The XYZ app is now available for all Chromecast products including
    Chromecast, Chromecast Audio, and TVs and speakers with Chromecast built-in.»
  • «The XYZ app is Chromecast-enabled, allowing you to enjoy all your favorite
    shows/movies/music/games on your TV with Chromecast built-in.»
  • «The XYZ app now has Chromecast support, allowing users to stream content
    from their phone to their TV with Chromecast built-in.»

Chromecast badge

You can use the «Chromecast» badges on your website, app store listing,
marketing materials and promotional materials to display compatibility with
devices that use the Cast protocol.

  • Do not modify the color, proportions, spacing or any other aspect of the
    badge image.
  • When used alongside logos for other ingredient technologies (for example,
    Bluetooth, Spotify Connect, AirPlay, etc.), the Chromecast badge must be of
    equal or greater size.
  • Don’t make the badge the primary element on your page.
  • Keep some distance between the badge and other logos and icons on your page.
  • When used on white, light, or medium-toned background, use a black badge.
  • When used on a black or dark-toned background, use the white badge.
  • Don’t use the badge on a page that contains or displays adult content,
    promotes gambling, promotes violence, contains hate speech, involves the sale of
    tobacco or alcohol to persons under twenty-one years of age, violates other
    applicable laws or regulations or is otherwise objectionable.

Badge linking

When used online, the Chromecast badge must link to one of the following:

  • Google’s list of Chromecast-enabled apps and products, currently at
    g.co/castapps.
  • A list of products published by you.
  • A specific product detail page published by you.
  • A list of apps published by you.
  • A specific app detail page published by you, on Google Play, or in the Apple
    App Store.

Download Chromecast badge assets

The download bundle includes Portable Network Graphics (.png), Adobe
Illustrator (.ai), and Enapsulated Postscript (.eps) formats.

chromecast_built_in_badges.zip

Preview Chromecast badges

Blue logo and white text on black background

White logo and white text on black background

Blue logo and gray text on white background

Messages from receiver to sender

The receiver sends two types of messages:

  • Errors: Unicast messages sent when there is an error response to a sender request.
  • Status: Broadcast messages.
    • Consequence of a sender-initiated action. Will contain the requestId of the request that caused the change.
    • Spontaneous: For example, due to a change triggered by the receiver application. The RequestId will be 0.

Error: Invalid Player State

Sent when the request by the sender can not be fulfilled because the player is not in a valid state. For example, if the application has not created a media element yet.

Name Type Description
requestId integer ID of the request that generated this error
type string INVALID_PLAYER_STATE (only value)
customData object optional Application-specific blob of data defined by the receiver application

Error: Load Failed

Sent when the load request failed. The player state will be IDLE.

Name Type Description
requestId integer ID of the request that generated this error
type string LOAD_FAILED (only value)
customData object optional Application-specific blob of data defined by the receiver application

Error: Load Cancelled

Sent when the load request was cancelled (a second load request was received).

Name Type Description
requestId integer ID of the request that generated this error
type string LOAD_CANCELLED (only value)
customData object optional Application-specific blob of data defined by the receiver application

Error: Invalid Request

Sent when the request is invalid (an unknown request type, for example).

Name Type Description
requestId integer ID of the request that generated this error
type string INVALID_REQUEST (only value)
reason Enum (string)

Values:

  • INVALID_COMMAND  The command is not supported
  • DUPLICATE_REQUESTID  The request ID is not unique (the receiver is processing a request with the same ID)
customData object optional Application-specific blob of data defined by the receiver application

Media status

Sent after a state change or after a media status request. Only the MediaStatus objects that changed or were requested will be sent.

Name Type Description
requestId integer ID used to correlate this status response with the request that originated it or 0 if the status message is spontaneous (not triggered by a sender request). Sender applications will generate unique request IDs by selecting a random number and continuously increasing it (they will not use 0).
type string MEDIA_STATUS (only value)
status [] Array of Media Status objects. NOTE: the media element in MediaStatus will only be returned if it has changed.
customData object optional Application-specific blob of data defined by the receiver application

Как подключать и настраивать приставки

Подсоединяются и настраиваются HDMI-донглы просто. Все образцы, помимо Audio, подключать нужно следующим образом.

  1. Соедините кабель HDMI с соответствующим портом на телевизоре.
  2. Обычно все модели питаются от телевизора и не требуют розетки, но устройство Ultra – исключение. Здесь даже в комплекте идет адаптер, так что перед началом работы подсоедините блок через microUSB-порт.
  3. Через 5-10 секунд телевизор обнаружит подключение, после этого необходимо подключиться к сети Вай-Фай. В случае с Ультра можно использовать кабель интернета.
  4. Установите на смартфон или айфон мобильное приложение Google Home.

Далее на экране будут высвечиваться подсказки, по которым можно подстроить приставку под себя.

Сhromecast умеет транслировать на телевизор не только содержимое экрана смартфона, он сопрягается и с ПК. На компьютер устанавливается браузер Хром, а в нем расширение Google Cast. В итоге пользователь получает трансляцию работы в браузере на экран телевизора.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector