admin / 02.05.2018

linux — Задержки при записи с камеры rtsp потока — Stack Overflow на русском

Содержание

What are Media Source Extensions?

Media Source Extensions (MSE) is a JS API exposing a set of JS objects that get attached to an HTML media element and allows appending media data to the element from JS. MSE separates fetching/sourcing from playback. Can attach to multiple sources, splice multiple files, shift media in time (allows ad insertion), etc. MSE takes byte-streams (spec supports WebM and ISO BMFF today) to avoid the need for parsing in JS.

Why are we doing this?

  • Started 1-1.5y ago as work on adaptive-streaming/Dash/HLS. Realized we didn’t want to get into manifest parsing, fetching, adaptive algorithms in the browser, and instead move that into JS. Avoids baking in algorithms that have to be supported forever (influenced by experience from other proprietary adaptive implementations). Using MSE, changing buffering algorithm involves pushing new JS, not updating all clients (or supporting their algorithms forever).
  • Fetching happens in JS, enabling transport experimentation. Doesn’t care where media comes from, so , , , etc are all available.
  • Make media more malleable: want to enable splicing/mashup, see what creativity comes out of that. Push the web forward & what people expect to be able to do «just» in a browser.

How does this work w/ ?

object has a collection of s and is associated with a (or ) tag. is parallel to for feeding. s are a timeline abstraction.

Current Status

  • W3C Editor’s Draft, proposed ~5mo ago. Joint proposal by Netflix/Microsoft/Google.
  • Ongoing teleconferences & discussions, clarifying spec bugs, etc.
  • Enabled in Chrome 23 behind an (API is prefixed), with some restrictions (support only WebM & ISO-BMFF, max of 1 audio / 1 video track). Audio & video can come from different s, allowing avoiding re-muxing when adding a language (and avoid extra storage!).
  • Support seamless video codec config changes mid-stream (primarily resolution change) as required by the spec. Causes to change size; use CSS to avoid visual change.
  • Audio config changes are not yet supported.

What’s next?

  • Finish editor’s draft and present to HTML-WG for HTML.next (successor to HTML5), along w/ Encrypted Media Extensions.
  • Currently behind a flag; want to be on by default.
  • Add audio config change support.
  • Add support for multiple tracks of a single type.
  • Add/remove source buffers during playback.
  • Other browser vendors to implement this API. Opera’s started.
  • Web-developer response has been very positive, looking forward to browser support.
  • Open-source command-line tools & a JS validator to show errors as they happen in the byte-stream to help debug apps, instead of an uninformative firing at the tag.
  • Publish more demos.

Discussion

What’s changed since last year?

  • We’ve gone to an object-based API instead of hanging methods on the tag. Create a MediaSource object, then hang s off it. Manipulating objects seems more natural for the logical model.
  • is a new attribute exposing reflecting what’s buffered. Useful for when playback stalls, and for dealing with out-of-memory conditions when data is dropped.
  • allows time-shifting data buffers; supports ad-insertion.

How does the data flow? Some mechanism fetches a buffer (, , etc) and ‘s.

Isn’t that high overhead? (b/c of having to go through JS); can we have a named pipe? Not in the spec today; various approaches being discussed. No clear suggestions yet that work for all cases. Will likely keep but might add mechanisms.

How efficient is going through JS? Pretty efficient. Since the data doesn’t need to be read/written in JS the buffer can be passed efficiently from the network layer to the media layer w/out having to unpack/parse in JS.

eventually represents a single WebM file? No — accepts WebM bytestreams, but they don’t have to all come from the same place. Similar to OGG chaining/concatenation. Appending at a timestamp that’s already buffered truncates the previously-appended data.

Then why do we need multiple s? To support demuxed sources; audio coming from one source going into one , video coming from another source going into the other .

Doesn’t that require parsing to know how/where to append? Don’t need to do parsing if the media comes alongside a manifest, esp. if it’s in JSON 🙂 Have demo code (JS app and go command-line app) for generating such manifests. In the process of open-sourcing them. Using the manifest a web app can construct s (with Range headers) to pull the just the needed bytes and feed them into s.

This allows pulling audio/video from different sources and get them synchronized. Doesn’t that overlap existing functionality in HTML5 for synchronizing different media elements?

  • Not sure; might not be frame-accurate. Would have to jump through more hoops to do track switching (would be hard to be seamless).
  • Embedded devices also can’t have multiple media pipelines running concurrently, hard to duplicate.
  • Some mobile browsers only allow a single HTML media element to play at a time ( xor , not both).
  • There’s an API for the browser to refuse to create new s for out-of-memory, or other constraints. JS needs to fail gracefully (handle exception).

How would you detect that you don’t have enough data to play? Two mechanisms that can be used:

  • (implemented): can be polled to see what data is in the ; can monitor on a progress event [boo’d down]
  • (not yet implemented): use the readyState to reflect buffered state. i.e. HAVE_{CURRENT_/FUTURE_/META}DATA: when the pipeline is running close to empty or underruns, can switch down the state (and issue events).

Have you considered exposing the manifest as part of the JS interface to support more efficient seeking/caching? Not really; would have to standardize on manifest formats etc. Very different in different media formats.

How small can you chunk media data before things explode? (20ms chunks?) Haven’t really tried; expect to scale depending on JS engine efficiency. Theoretically could use MSE to play a live source with minimal delay; clear that it’ll work with 1-2s of delay, but wondering how small the delay can be driven. Consider a recording API attached to a MediaStream source and piping it to a , allowing transformation in the middle for effects/etc.

OPUS can’t be put in WebM/ISO-BMFF today. What’s the story for OPUS in ? Chrome doesn’t support OPUS yet, so don’t have a plan yet. Should be possible to make it work, just need to figure out how to do it. Everyone’s open to that.

What happens to manifest duration as bytes are fed in? There’s a attribute that can be set, or can fed from an init segment, or data appending can extend duration. Seeking requires duration knowledge.

How does that interact w/ startOffset? Timeline in always starts at 0. For OGG we look at the first page to find the start timestamp, the end to find the duration, and compute offset as the difference. How does that work in MSE? Up to the webapp; JS needs to figure it out. timeOffset can be updated between media segments and things simply work.

DEMO

Prerequisite: Canary build of chrome, enable about:flags: flag, to XHR from local disk.

Video & Audio timelines represent s, and the tracks below are different WebM files for different videos (one audio-only file, a bunch of video-only files). Each video’s slider selects a range of clusters. Drag & drop the selected range from sources into the audio/video s. Can overlap them (adaptive requires smooth stream transition); transition is guaranteed to happen on a keyframe (random access point in the spec) to ensure smoothness, but seeking back into an overlapping segment will show the result of the latest append. Doesn’t allow arbitrary editing except in an I-frame-only stream.

How does it work for audio? Every frame is a keyframe.

For OPUS we do prediction from previous frames, may need to decode several frames before reaching a stable frame. How would that work? Need to talk about it more; probably comes down to the question of how OPUS fits into WebM in the first place.

Going back to duration; if not known it’s updated on the fly. Normally represented as a NaN. What’s up? Mirror HTML; until we know, it’s NaN; once we have metadata it’s like a live stream w/ +inf until we have duration info added either explicitly or from a segment at which point it’s set.

If seek to somewhere ahead of the buffer’s duration what happens? Playback stalls waiting for data to be buffered, at which point playback can resume. When readyState transitions are implemented will move to HAVE_CURRENT_DATA. ATM we just get a ‘stalled’ event. Ditto for seeking to a point where only one has data but not the other.

What about «Save As» / export? Isn’t implemented. Can’t necessarily represent as a single WebM depending on mid-stream config changes, but could implement basic transcoding to allow export.

Если вам нужно записывать видео с камеры, у которое есть rtsp-поток, вам сюда.
В моем случае использовалась камера Ubiquiti Aircam mini.

Windows Media Player HTML5 Extension for Chrome

RTSP-потоков у не несколько:

rtsp://192.168.1.1:554/live/ch00_0 — Full resolution
rtsp://192.168.1.1:554/live/ch01_0 — Half resolution
rtsp://192.168.1.1:554/live/ch02_0 — Quarter resolution
rtsp://192.168.1.1:554/live/ch03_0 — Small preview

Будем использовать rtsp://192.168.1.1:554/live/ch00_0.

Установим нужный софт (ffmpeg и OpenRTSP)

# cd /usr/ports/multimedia/ffmpeg
# make install clean
# cd /usr/ports/net/liveMedia
# make install clean

Чтобы записать видео с камеры, воспользуемся командой:

# openRTSP -v -t rtsp://192.168.1.1:554/live/ch00_0 | ffmpeg -i — -y -r 20 -s hd720 -b 1000k -vcodec mpeg4 -f avi test.avi

Опции ffmpeg:
-y — перезаписать существующий файл
-r — fps
-s — размер видео (в man ffmpeg доступны остальные)
-b — битрейт видео
-vcodec — кодек
-f — формат
-i записать в файл

Если хочется вести трансляцию с rtsp-потока, то ffserver в помощь.

Запись опубликована автором MishLen в рубрике ПО (FreeBSD) с метками ffmpeg, openrtsp, rtsp. Добавьте в закладки постоянную ссылку.

Как проверить возможность трансляции RTSP потока с IP камеры в различных Web-браузерах

Проверим отображение RTSP-видеопотока в браузерах Chrome, Firefox, Safari на десктопах с ОС Windows, Mac OS X, Linux и мобильных устройствах под управлением Android и iOS

 Загрузить       Купить      

 

Проверяем RTSP-поток в VLC

Чтобы быстро убедиться в том, что RTSP-поток доступен и отдает видео, открываем его в VLC-плеере. Если поток воспроизводится корректно, переходим к тестированию web-интерфейса. RTSP URL вы можете получить в панели управления IP-камерой или использовать какой-нибудь публично доступный RTSP-видеопоток, например этот: rtsp://b1.dnsdojo.com:1935/live/sys3.stream

 

Тестируем RTSP-WebRTC поток в браузерах Google Chrome и Mozilla Firefox

Убеждаемся в том, что тот же самый RTSP-поток воспроизводится на обычной HTML-странице в браузерах Chrome и Firefox.

1.

Загружаем демо-интерфейс по адресу wcs5-eu.flashphoner.com, меню ‘Demo / Streaming Min’. Это минимальный HTML5 web-интерфейс, который использует WebRTC-технологию для отображения RTSP-видеопотока в браузерах Chrome и Firefox.

2. Устанавливаем соединение с Web Call Server

3.

media source extensions

Вписываем адрес RTSP камеры и запускаем воспроизведение потока:

В результате успешно проверили воспроизведение RTSP-потока в браузере Google Chrome. Аналогичный тест можно провести с браузерами Firefox и Opera на тех десктопных и мобильных платформах, которые поддерживают технологию WebRTC в браузерах.

 

Тестируем RTSP-Websocket поток в браузере Safari под iOS и Mac OS X

Браузеры на iOS устройствах не поддерживают технологию WebRTC. По этой причине используется отдельный плеер ‘WS Player Min’, который забирает поток по протоколу Websocket и воспроизводит в HTML5-Canvas элементе браузера.

 1. Также как и в случае с Chrome нужно открыть страницу демо-интерфеса, но выбрать другой пункт меню:

2. После этого установить соединение с Web Call Server

3. Вписать заранее известный адрес RTSP трансляции и воспроизвести видеопоток:

Таким образом выше продемонстрированна возможность просматривать переконвертированный с помощью Web Call Server RTSP трафик на большинстве из распространенных Web браузеров, в том числе на наиболее популярных мобильных платформах.

Следующим шагом будет добавление HTML5 RTSP-плеера на ваш собственный веб-сайт. Процесс добавления подробно описан в соседнем разделе Внедрение

 

Видеоролики с описанием процесса тестирования RTSP-WebRTC и RTSP-Websocket плеера

RTSP-WebRTC плеер для Chrome и Firefox

RTSP-Websocket плеер для iOS Safari

 

x

Эта страница скорее всего устарела

Посетите актуальную страницу тестирования RTSP-HTML5 трансляции

ПерейтиНет, остаюсь здесь

Загрузить Web Call Server 5

Системные требования: Linux x86_64, 1 core CPU, 1 Gb RAM, Java

    Загрузить WCS5   

Установка:

  1. wget http://flashphoner.com/download-wcs5-server.tar.gz
  2. Распаковать и установить с помощью скрипта ‘install.sh’
  3. Запустить сервер с помощью команды ‘service webcallserver start’
  4. Открыть веб-интерфейс https://host:8888 и активировать вашу лицензию

 

Если вы используете серверы Amazon EC2, то скачивать ничего не нужно.

WCS5 на Amazon EC2

 

Web Call Server 5 — Триал

30-дневная ознакомительная лицензия предоставляется один раз частному лицу или организации. Пожалуйста используйте ваш корпоративный e-mail при заполнении формы.

Ваш поток работает? Проверьте его доступность потока бесплатно.

Tweet

Проверьте любой поток бесплатно прямо сейчас

Проверка делается из распределённой сети контрольных точек, каждая из которых представляет собой сервер с Nimble Streamer, настроенным на проверку потоков.
Поддерживаются протоколы HLS, HDS, Smooth, RTSP, RTMP, Icecast, Shoutcast и DASH с SSL/TLS для HLS, RTMP и RTSP.

Тестовый плеер HTML5

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

Результаты появятся ниже.

Для повышения уровня отказоустойчивости и масштабирования HTTP вещания можно использовать Nimble Streamer в качестве ретрансляционного edge-сервера, а также в качестве origin-сервера для живого вещания.

Action Amsterdam, Netherlands San Francisco, USA New York, USA Singapore, Asia Frankfurt, Germany Toronto, Canada
Validate URL
Validate protocol
Resolve server name
Connect to server
Send stream request
Get stream info
Get full stream info
Parse stream info
Check for redirect
Check stream availability

Media Source Extensions™

HTML5 RTSP плеер

Воспроизведение RTSP видеопотоков в браузере и мобильных приложениях с использованием WebRTC и Websocket технологий

Трансляция и воспроизведение RTSP потока в браузерах без установки дополнительного ПО и плагинов прямо на HTML-странице. Воспроизведение RTSP в мобильных приложениях для iOS и Android.

Использование технологий HTML5, WebRTC и Websockets для воспроизведения RTSP аудио и видео потоков в реальном времени с минимальной задержкой.

Web Call Server — это серверное программное обеспечение, которое конвертирует RTSP поток в формат, понятный web-браузеру и мобильному приложению. Использование технологий WebRTC и Websockets обеспечивает минимальную задержку, по сравнению с существующими решениями, такими, как HLS.

 

Спецификация

Видеопоток захватывается с RTSP-источника (см. Источники RTSP), отдающего аудио и видео в поддерживаемых кодеках (см. RTSP кодеки). Далее видеопоток трансформируется на стороне сервера для воспроизведения в браузерах и мобильных устройствах (см. Воспроизведение RTSP). В браузерах и мобильных устройствах воспроизведение происходит по перечисленным технологиям (см. Технологии воспроизведения).

Источники RTSP

  • IP камеры
  • Медиасерверы
  • Системы наблюдения
  • Конференц-серверы

Воспроизведение RTSP

  • Chrome
  • Firefox
  • Opera
  • Safari, Mac OS
  • Safari, iOS
  • IE
  • Edge
  • iOS SDK
  • Android SDK

RTSP-кодеки

  • H.264
  • VP8
  • AAC
  • G.711
  • Speex

Технологии воспроизведения

 

Схема доставки RTSP-видеопотока на браузеры и мобильные приложения

Web Call Server подключается к IP-камере либо серверу потокового видео по протоколу RTSP, получает аудио и видео трафик, конвертирует этот трафик в совместимый с браузерами формат, и далее раздает потоковое видео на HTML5-страницы пользователей и на мобильные приложения для iOS и Android.

Пошаговая схема RTSP-трансляции на HTML5-браузер или мобильное приложение

Браузер подключается к серверу по протоколу Websocket и запрашивает RTSP-видеопоток. С этого начинается трансляция.

  1. Браузер запрашивает RTSP-поток
  2. Web Call Server подключается к IP-камере и запрашивает требуемый браузером RTSP-поток
  3. IP-камера отправляет аудио и видео трафик внутри RTSP-соединения
  4. Web Call Server конвертирует трафик в WebRTC или Websockets и передает браузеру на воспроизведение

 

 

RTSP HTML5 player в WebRTC браузере
Google Chrome

На скриншоте ниже показан пример работы плеера в браузере Chrome через WebRTC

 

RTSP HTML5 Player — демо

Посетите наш демо-сервер чтобы проверить работу плеера в действии

Тестировать

 

 

Загрузить Web Call Server 5

Системные требования: Linux x86_64, 1 core CPU, 1 Gb RAM, Java

    Загрузить WCS5   

Установка:

  1. wget http://flashphoner.com/download-wcs5-server.tar.gz
  2. Распаковать и установить с помощью скрипта ‘install.sh’
  3. Запустить сервер с помощью команды ‘service webcallserver start’
  4. Открыть веб-интерфейс https://host:8888 и активировать вашу лицензию

 

Если вы используете серверы Amazon EC2, то скачивать ничего не нужно.

WCS5 на Amazon EC2

 

Web Call Server 5 — Триал

30-дневная ознакомительная лицензия предоставляется один раз частному лицу или организации. Пожалуйста используйте ваш корпоративный e-mail при заполнении формы.

 

Статьи по теме

iOS Safari 11 теперь умеет WebRTC

Встраиваем WebRTC плеер для живых трансляций на сайт

7 способов транслировать RTSP на страницу

Браузерная WebRTC трансляция с RTSP IP-камеры с низкой задержкой

Unofficial news and tips about Google

протокол для управления (запуска, постановки на паузу и остановки) мультимедийным контентом. Например, с его помощью можно получить видео и звук с камеры и, с последующей конвертацией, транслировать их на веб-сервер. Расшифровывается как real time streaming protocol (потоковый протокол реального времени).

Захват аудио/видео по RTSP можно осуществить при помощи следующих популярных программ-клиентов:

  • Windows Media Player.
  • VLC Player.
  • Winamp.
  • QuickTime.
  • Skype.

По умолчанию, RTSP работает на сетевом порту 554.

Пример ссылки на поток для камеры:
rtsp://admin:12345@192.168.0.24:554/Streaming/Channels/1
Где admin и 12345 — логин и пароль для подключения к камере; 192.168.0.24 — IP-адрес камеры; /Streaming/Channels/1 — URL до потока. Данная ссылка приведена только для примера, в зависимости от производителя и модели, они могут сильно различаться. Правильную ссылку нужно смотреть в документации к оборудованию.

RTSP похож на протокол HTTP, за исключением следующих моментов:

  1. Сервер RTSP способен управлять состоянием подключения.
  2. В случае с RTSP, сервер, как и клиент, тоже может генерировать запросы.
  3. В RTSP возможна передача данных вне основной полосы.

Подробнее об RTSP на Википедии

FILED UNDER : IT

Submit a Comment

Must be required * marked fields.

:*
:*