stringtranslate.com

Протокол обмена сообщениями в реальном времени

Протокол обмена сообщениями в реальном времени ( RTMP ) — это протокол связи для потоковой передачи аудио, видео и данных через Интернет. Первоначально разработанный Macromedia как собственный протокол для потоковой передачи между Flash Player и Flash Communication Server, компания Adobe ( которая приобрела Macromedia) выпустила неполную версию спецификации протокола для публичного использования.

Протокол RTMP имеет несколько вариантов:

  1. Собственно RTMP, «простой» протокол, который работает поверх протокола управления передачей (TCP) и по умолчанию использует номер порта 1935.
  2. RTMPS, который представляет собой RTMP через соединение Transport Layer Security (TLS/SSL).
  3. RTMPE, который зашифрован по протоколу RTMP с использованием собственного механизма безопасности Adobe. Хотя детали реализации являются собственностью компании, в механизме используются стандартные криптографические примитивы. [1]
  4. RTMPT, который инкапсулируется в HTTP- запросы для прохождения межсетевых экранов . RTMPT часто использует запросы открытого текста на TCP- портах 80 и 443 для обхода большей части фильтрации корпоративного трафика. Инкапсулированный сеанс может содержать в себе простые пакеты RTMP, RTMPS или RTMPE.
  5. RTMFP, который представляет собой RTMP через протокол пользовательских датаграмм (UDP) вместо TCP, заменяющий поток фрагментов RTMP. Пакет протоколов Secure Real-Time Media Flow Protocol был разработан Adobe Systems и позволяет конечным пользователям напрямую подключаться и общаться друг с другом (P2P).

Хотя основной мотивацией для RTMP было создание протокола для воспроизведения Flash-видео , он также используется в некоторых других приложениях, таких как Adobe LiveCycle Data Services ES .

Основная операция

RTMP — это протокол на основе TCP, который поддерживает постоянные соединения и обеспечивает связь с малой задержкой. Чтобы обеспечить бесперебойную доставку потоков и передать как можно больше информации, потоки разбиваются на фрагменты, а их размер динамически согласовывается между клиентом и сервером. Иногда его оставляют без изменений; размеры фрагментов по умолчанию составляют 64 байта для аудиоданных и 128 байтов для видеоданных и большинства других типов данных. Затем фрагменты из разных потоков могут чередоваться и мультиплексироваться по одному соединению. Таким образом, при более длинных фрагментах данных протокол несет только однобайтовый заголовок на фрагмент, что приводит к очень небольшим накладным расходам . Однако на практике отдельные фрагменты обычно не чередуются. Вместо этого чередование и мультиплексирование выполняются на уровне пакетов, при этом пакеты RTMP по нескольким различным активным каналам чередуются таким образом, чтобы гарантировать, что каждый канал соответствует своей полосе пропускания, задержке и другим требованиям качества обслуживания. Пакеты, чередующиеся таким образом, рассматриваются как неделимые и не чередуются на уровне фрагментов.

RTMP определяет несколько виртуальных каналов, по которым могут отправляться и получаться пакеты и которые работают независимо друг от друга. Например, есть канал для обработки запросов и ответов RPC, канал для данных видеопотока, канал для данных аудиопотока, канал для внеполосных управляющих сообщений (согласование размера фрагмента и т. д.) и т. д. . Во время типичного сеанса RTMP в любой момент времени одновременно могут быть активны несколько каналов. При кодировании данных RTMP генерируется заголовок пакета. Заголовок пакета, помимо прочего, определяет идентификатор канала, по которому он должен быть отправлен, временную метку его создания (при необходимости) и размер полезной нагрузки пакета. Затем за этим заголовком следует фактическое содержимое полезной нагрузки пакета, который перед отправкой по соединению фрагментируется в соответствии с согласованным на данный момент размером фрагмента. Сам заголовок пакета никогда не фрагментируется, и его размер не учитывается при расчете данных в первом фрагменте пакета. Другими словами, фрагментации подвергается только фактическая полезная нагрузка пакета (медиаданные).

На более высоком уровне RTMP инкапсулирует аудиопотоки MP3 или AAC и видео-мультимедийные потоки FLV1 и может выполнять удаленные вызовы процедур (RPC) с использованием формата сообщения действия . Любые необходимые службы RPC выполняются асинхронно с использованием единой модели запроса/ответа клиент/сервер, поэтому связь в реальном времени не требуется. [ нужны разъяснения ] [2] [3]

Шифрование

Сеансы RTMP могут быть зашифрованы одним из двух методов:

HTTP-туннелирование

В режиме RTMP Tunneled (RTMPT) данные RTMP инкапсулируются и обмениваются через HTTP , а сообщения от клиента (в данном случае медиаплеера) адресуются на порт 80 (по умолчанию для HTTP) на сервере.

Хотя сообщения в RTMPT больше, чем эквивалентные нетуннелируемые сообщения RTMP из-за заголовков HTTP, RTMPT может облегчить использование RTMP в сценариях, где в противном случае использование нетуннелируемого RTMP было бы невозможно, например, когда клиент находится позади брандмауэр , который блокирует исходящий трафик, отличный от HTTP и HTTPS.

Протокол работает, отправляя команды через URL-адрес POST и сообщения AMF через тело POST. Примером является

POST/open/1 HTTP/1.1

для открытия соединения.

Спецификация и патентная лицензия

Adobe выпустила спецификацию протокола версии 1.0 от 21 декабря 2012 года. [4] На целевой веб-странице, ведущей к этой спецификации, отмечается: «Чтобы принести пользу клиентам, которые хотят защитить свой контент, открытая спецификация RTMP не включает уникальную технологию Adobe безопасные меры RTMP». [5]

Документ, сопровождающий спецификацию Adobe, предоставляет «неисключительную, безвозмездную, непередаваемую, не подлежащую сублицензированию, персональную, всемирную» патентную лицензию на все реализации протокола с двумя ограничениями: первое запрещает использование для перехвата потоковых данных («любая технология который перехватывает потоковое видео, аудио и/или данные для хранения на любом устройстве или носителе»), а другой запрещает обход «технологических мер по защите аудио, видео и/или данных, включая любые меры безопасности Adobe RTMP». . [6]

Патенты и связанные с ними судебные разбирательства

Стефан Рихтер, автор нескольких книг по Flash , отметил в 2008 году, что, хотя Adobe неясно, какие патенты применимы к RTMP, патент США 7 246 356, по-видимому, является одним из них. [2]

В 2011 году Adobe подала в суд на Wowza Media Systems, заявив, среди прочего, о нарушении их патентов RTMP. [7] [8] [9] В 2015 году Adobe и Wowza объявили, что иски были урегулированы и отклонены с предубеждением. [10]

Структура пакета

Схема пакетов RTMP

Пакеты передаются через TCP-соединение, которое сначала устанавливается между клиентом и сервером. Они содержат заголовок и тело, которое в случае команд подключения и управления кодируется с использованием формата сообщения действия (AMF). Заголовок разделен на базовый заголовок (показанный на диаграмме как отдельный от остальных) и заголовок фрагмента сообщения . Базовый заголовок является единственной постоянной частью пакета и обычно состоит из одного составного байта, где два старших бита — это тип фрагмента ( fmt в спецификации), а остальные образуют идентификатор потока. В зависимости от значения первого некоторые поля заголовка сообщения могут быть опущены, а их значение получено из предыдущих пакетов, тогда как в зависимости от значения последнего базовый заголовок может быть расширен одним или двумя дополнительными байтами (как в случай диаграммы, имеющей всего три байта (c)). Если значение остальных шести бит базового заголовка (BH) (наименее значимого) равно 0, тогда BH составляет два байта и представляет идентификатор потока от 64 до 319 (64+255); если значение равно 1, то BH составляет три байта (последние два байта закодированы как 16-битный Little Endian) и представляет собой идентификатор потока от 64 до 65599 (64+65535); если значение равно 2, то BH составляет один байт и зарезервирован для сообщений и команд управления протоколом низкого уровня. Заголовок сообщения фрагмента содержит метаданные, такие как размер сообщения (измеряется в байтах), дельта метки времени и тип сообщения . Это последнее значение представляет собой один байт и определяет, является ли пакет аудио, видео, командой или пакетом RTMP «низкого уровня», например RTMP Ping.

Ниже показан пример, зафиксированный, когда флэш-клиент выполняет следующий код:

поток вар : NetStream = новый NetStream ( connectionObject );    

это создаст следующий чанк:

Пакет начинается с базового заголовка , состоящего из одного байта (0x03), где два старших бита (b 00 000011) определяют тип заголовка фрагмента, равный 0, а остальные (b00 000011 ) определяют идентификатор потока фрагмента, равный 3. Четыре возможных значения типа заголовка и их значение:

The last type (b11) is always used in the case of aggregate messages where, in the example above, the second message will start with an id of 0xC3 (b11000011) and would mean that all Message Header fields should be derived from the message with a stream Id of 3 (which would be the message right above it). The six least significant bits that form the Stream ID can take values between 3 and 63. Some values have special meaning, like 1 that stands for an extended ID format, in which case there will be two bytes following that. A value of two is for low level messages such as Ping and Set Client Bandwidth.

The next bytes of the RTMP Header (including the values in the example packet above) are decoded as follows:

The Message Type ID byte defines whether the packet contains audio/video data, a remote object or a command. Some possible values for are:

Following the header, 0x02 denotes a string of size 0x000C and values 0x63 0x72 ... 0x6D ("createStream" command). Following that we have a 0x00 (number) which is the transaction id of value 2.0. The last byte is 0x05 (null) which means there are no arguments.

Invoke Message Structure (0x14, 0x11)

Some of the message types shown above, such as Ping and Set Client/Server Bandwidth, are considered low level RTMP protocol messages which do not use the AMF encoding format. Command messages on the other hand, whether AMF0 (Message Type of 0x14) or AMF3 (0x11), use the format and have the general form shown below:

(String) <Command Name>(Number) <Transaction Id>(Mixed) <Argument> ex. Null, String, Object: {key1:value1, key2:value2 ... }

The transaction id is used for commands that can have a reply. The value can be either a string like in the example above or one or more objects, each composed of a set of key/value pairs where the keys are always encoded as strings while the values can be any AMF data type, including complex types like arrays.

Control Message Structure (0x04)

Control messages are not AMF encoded. They start with a stream Id of 0x02 which implies a full (type 0) header and have a message type of 0x04. The header is followed by six bytes, which are interpreted as such:

The first two bytes of the message body define the Ping Type, which can apparently[11] take six possible values.

Pong is the name for a reply to a Ping, with the values used as seen above.

ServerBw/ClientBw Message Structure (0x05, 0x06)

This relates to messages that have to do with the client up-stream and server down-stream bit-rate. The body is composed of four bytes showing the bandwidth value, with a possible extension of one byte which sets the Limit Type. This can have one of three possible values which can be: hard, soft or dynamic (either soft or hard).

Set Chunk Size (0x01)

The value received in the four bytes of the body. A default value of 128 bytes exists, and the message is sent only when a change is wanted.

Protocol

RTMP Handshake Diagram

Handshake

After establishing a TCP connection, an RTMP connection is established first, performing a handshake through the exchange of three packets from each side (also referred to as Chunks in the official documentation). These are referred in the official spec as C0-2 for the client sent packets and S0-2 for the server side respectively and are not to be confused with RTMP packets that can be exchanged only after the handshake is complete. These packets have a structure of their own and C1 contains a field setting the "epoch" timestamp, but since this can be set to zero, as is done in third party implementations, the packet can be simplified. The client initialises the connection by sending the C0 packet with a constant value of 0x03 representing the current protocol version. It follows straight with C1 without waiting for S0 to be received first which contains 1536 bytes, with the first four representing the epoch timestamp, the second four all being 0, and the rest being random (and which can be set to 0 in third party implementations). C2 and S2 are an echo of S1 and C1 respectively, except with the second four bytes being the time the respective message was received (instead of 0). After C2 and S2 are received, the handshake is considered complete.

Connect

At this point, the client, and server can negotiate a connection by exchanging AMF encoded messages. These include key value pairs which relate to variables that are needed for a connection to be established. An example message from the client is:

(Invoke) "connect"(Transaction ID) 1.0(Object1) { app: "sample", flashVer: "MAC 10,2,153,2", swfUrl: null, tcUrl: "rtmpt://127.0.0.1/sample ", fpad: false, capabilities: 9947.75 , audioCodecs: 3191, videoCodecs: 252, videoFunction: 1 , pageUrl: null, objectEncoding: 3.0 }

The Flash Media Server and other implementations uses the concept of an "app" to conceptually define a container for audio/video and other content, implemented as a folder on the server root which contains the media files to be streamed. The first variable contains the name of this app as "sample" which is the name provided by the Wowza Server for their testing. The flashVer string is the same as returned by the Action-script getversion() function. The audioCodec and videoCodec are encoded as doubles and their meaning can be found in the original spec. The same is true for the videoFunction variable, which in this case is the self-explanatory SUPPORT_VID_CLIENT_SEEK constant. Of special interest is the objectEncoding which will define whether the rest of the communication will make use of the extended AMF3 format or not. As version 3 is the current default, the flash client has to be told explicitly in Action-script code to use AMF0 if that is requested. The server then replies with a ServerBW, a ClientBW and a SetPacketSize message sequence, finally followed by an Invoke, with an example message.

(Invoke) "_result"(transaction ID) 1.0(Object1) { fmsVer: "FMS/3,5,5,2004", capabilities: 31.0, mode: 1.0 }(Object2) { level: "status", code: "NetConnection.Connect.Success", description: "Connection succeeded", data: (array) { version: "3,5,5,2004" }, clientId: 1728724019, objectEncoding: 3.0 }

Some values above are serialised into properties of a generic Action-script Object, which is then passed to the NetConnection event listener. The clientId will establish a number for the session to be started by the connection. Object encoding must match the value previously set.

Play video

To start a video stream, the client sends a "createStream" invocation followed by a ping message, followed by a "play" invocation with the file name as argument. The server will then reply with a series of "onStatus" commands followed by the video data as encapsulated within RTMP messages.

After a connection is established, media is sent by encapsulating the content of FLV tags into RTMP messages of type 8 and 9 for audio and video, respectively.

HTTP tunneling (RTMPT)

This refers to the HTTP tunneled version of the protocol. It communicates over port 80 and passes the AMF data inside HTTP POST request and responses. The sequence for connection is as follows:

POST /fcs/ident2 HTTP/1.1Content-Type: application/x-fcs\r\nHTTP/1.0 404 Not Found
POST /open/1 HTTP/1.1Content-Type: application/x-fcs\r\nHTTP/1.1 200 OKContent-Type: application/x-fcs\r\n 1728724019

The first request has an /fcs/ident2 path, and the correct reply is a 404 Not Found error. The client then sends an /open/1 request where the server must reply with a 200 ok appending a random number that will be used as the session identifier for the said communication. In this example, 1728724019 is returned in the response body.

POST /idle/1728724019/0 HTTP/1.1HTTP/1.1 200 OK 0x01

From now on, the /idle/<session id>/<sequence #> is a polling request where the session id has been generated and returned from the server and the sequence is just a number that increments by one for every request. The appropriate response is a 200 OK, with an integer returned in the body signifying the interval time. AMF data is sent through /send/<session id>/<sequence #>

Software implementations

RTMP is implemented at these three stages:

rtmpdump

The open-source RTMP client command-line tool rtmpdump is designed to play back or save to disk the full RTMP stream, including the RTMPE protocol Adobe uses for encryption. RTMPdump runs on Linux, Android, Solaris, Mac OS X, and most other Unix-derived operating systems, as well as Microsoft Windows. Originally supporting all versions of 32-bit Windows including Windows 98, from version 2.2 the software will run only on Windows XP and above (although earlier versions remain fully functional).

Packages of the rtmpdump suite of software are available in the major open-source repositories (Linux distributions). These include the front-end apps "rtmpdump", "rtmpsrv" and "rtmpsuck."

Development of RTMPdump was restarted in October 2009, outside the United States, at the MPlayer site.[12] The current version features greatly improved functionality, and has been rewritten to take advantage of the benefits of the C programming language. In particular, the main functionality was built into a library (librtmp) which can easily be used by other applications. The RTMPdump developers have also written support for librtmp for MPlayer, FFmpeg, XBMC, cURL, VLC and a number of other open source software projects. Use of librtmp provides these projects with full support of RTMP in all its variants without any additional development effort.

FLVstreamer

FLVstreamer is a fork of RTMPdump, without the code, which Adobe claims violates the DMCA in the USA. This was developed as a response to Adobe's attempt in 2008 to suppress RTMPdump. FLVstreamer is an RTMP client that will save a stream of audio or video content from any RTMP server to disk, if encryption (RTMPE) is not enabled on the stream.

Enhanced RTMP

Flash video container in RTMP is limited to H264 codec in most implementations. For this reason, The Veovera Software Organization, including Adobe, Google and Veriskope published the enhanced RTMP specification,[13] which adds support for VP9, H265 and AV1 codecs in the Flash Video container FLV.

Implementations

See also

References

  1. ^ "RTMPE". Adobe Flash Lite 4 Help. Adobe. Retrieved 29 December 2013.
  2. ^ a b "TheRealTimeWeb.com: Adobe Patents RTMP". therealtimeweb.com.
  3. ^ "Using RPC services in Flex Data Services 2". Archived from the original on 3 April 2007. Retrieved 16 April 2007. {{cite journal}}: Cite journal requires |journal= (help)
  4. ^ H. Parmar, M. Thornburgh (eds.) Adobe’s Real Time Messaging Protocol, Adobe, 21 December 2012
  5. ^ "Real-Time Messaging Protocol (RTMP) specification". Archived from the original on 21 August 2014. Retrieved 8 May 2014.
  6. ^ RTMP Specification License, Published April 2009
  7. ^ Schumacher-Rasmussen, Eric (27 May 2011). "Wowza Denies Adobe's Allegations of Patent Infringement". streamingmedia.com.
  8. ^ Lawler, Ryan (31 May 2011). "Wowza Fires Back at Adobe in Flash Patent Suit". gigaom.com.
  9. ^ "ADOBE SYSTEMS INCORPORATE - No. C 11-2243 CW. - 20120907565 - Leagle.com". leagle.com.
  10. ^ Wowza Media Systems and Adobe Systems Settle Patent Cases http://www.wowza.com/news/wowza-media-systems-and-adobe-systems-settle-patent-cases
  11. ^ The Red5 Project (2009) Ping. Available from: http://trac.red5.org/wiki/Real_Time_Messaging_Protocol/Documentation/Tutorials/Ping. Accessed at: 25 December 2011
  12. ^ "Updates:2009-11-01". Retrieved 1 November 2009.
  13. ^ Lozben, Slavik (2 February 2024). "Enhancing RTMP, FLV With Additional Video Codecs And HDR Support". GitHub. Retrieved 1 April 2024.
  14. ^ "Support HEVC VP9 AV1 codec in enhanced flv format". GitHub. 2 February 2024. Retrieved 1 April 2024.
  15. ^ "Enable AV1, HEVC via RTMP to YouTube". GitHub. 25 March 2023. Retrieved 1 April 2024.
  16. ^ "Introducing the Enhanced Broadcasting Beta". GitHub. 8 January 2024. Retrieved 1 April 2024.

External links