> For the complete documentation index, see [llms.txt](https://portal-integracao.intelbras.com.br/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://portal-integracao.intelbras.com.br/cameras-and-gravadores/integracao-api-cftvip-e-mibo/cameras-e-gravadores/apis-rtsp.md).

# APIs RTSP

Integração de streaming via RTSP: URLs realmonitor/playback/arquivo, fluxo MJPG (/cgi-bin/mjpg/video.cgi) e criação de token para RTSP Pull (TokenManager/createToken).

## Dicas & Boas Práticas <a href="#dicas-and-boas-praticas" id="dicas-and-boas-praticas"></a>

* Prefira o modo **Webhook (Push ativo)** sempre que disponível.
* Garanta que os endpoints estejam **acessíveis na internet** e respondam **HTTP 200**.
* Utilize **HTTPS** e **HTTP Digest Authentication** em todas as integrações.
* Trate corretamente **eventos, imagens e payloads JSON** recebidos.
* Monitore o **Heartbeat (KeepAlive)** para validar a disponibilidade do dispositivo.
* Trate exceções, timeouts e reenvio de eventos para garantir estabilidade.

***

### O que é o protocolo RTSP?

**RTSP (Real Time Streaming Protocol)** é um protocolo usado para **controlar transmissões de áudio e vídeo em tempo real**, muito comum em:

* **Câmeras IP (CFTV)**
* **DVRs / NVRs**
* Sistemas de monitoramento
* Players de mídia (VLC, por exemplo)

### Como funciona?

O RTSP **controla a sessão**, enquanto **outros protocolos transportam o vídeo** (normalmente RTP).

1. **Cliente** (**VLC**, app, software de monitoramento)
2. **Servidor RTSP** (câmera ou gravador)
3. Cliente pede o stream
4. Vídeo é enviado via **RTP**
5. Sincronização via **RTCP**

### **Comandos principais :**

Esses comandos são enviados do cliente para o servidor:

* **OPTIONS** → pergunta o que o servidor suporta
* **DESCRIBE** → pede detalhes do stream
* **SETUP** → prepara a transmissão
* **PLAY** → inicia o vídeo
* **PAUSE** → pausa
* **TEARDOWN** → encerra a sessão

***

### Estrutura de uma URL RTSP

**Exemplo:**

```
rtsp://usuario:senha@192.168.1.108:554/cam/realmonitor?channel=1&subtype=0
```

**Explicação:**

| Parte            | Significado       |
| ---------------- | ----------------- |
| rtsp\://         | Protocolo         |
| usuario:senha    | Autenticação      |
| 192.168.1.108    | IP da câmera      |
| 554              | Porta padrão RTSP |
| /cam/realmonitor | Endpoint          |
| channel=1        | Canal             |
| subtype=0        | Main Stream       |

***

### TCP vs UDP&#x20;

| Característica   | UDP                                 | TCP (Interleaved)                     |
| ---------------- | ----------------------------------- | ------------------------------------- |
| Velocidade       | Mais rápido                         | Um pouco mais lento                   |
| Latência         | Menor latência                      | Um pouco mais de latência             |
| Perda de pacotes | Pode perder pacotes                 | Não perde (há reenvio)                |
| Estabilidade     | Menor estabilidade                  | Mais estável                          |
| Firewall / NAT   | Pode exigir liberação de portas RTP | Funciona melhor atrás de firewall/NAT |
| Uso recomendado  | Melhor em rede local                | Recomendado para internet             |

***

### Obter Transmissão Em Tempo Real

**Tópico:** Obtenha APIs de streaming de mídia em tempo real usando o protocolo RTSP.

* Método: `DESCRIBE, SETUP, PLAY, PAUSE, TEARDOWN, ... /cam/realmonitor`

**Exemplo**:

```http
  rtsp://<ip>/cam/realmonitor?channel=1&subtype=0
```

**1) DESCRIBE**

* Obtenha a descrição da mídia executando o comando DESCRIBE

```http
DESCRIBE rtsp://<ip>/cam/realmonitor?channel=1&subtype=0 RTSP/1.0 
CSeq: 1 
User-Agent: LibVLC/3.0.5
```

**Resposta:**

```http
RTSP/1.0 200 OK 
CSeq: 1 
Server: Rtsp Server/3.0 
Content-Base: rtsp://<ip>/cam/realmonitor?channel=1&subtype=0/ 
Content-Length: xxx 
Content-Type: application/sdp 
 

v=0 
o=- 2253484289 2253484289 IN IP4 0.0.0.0 
s=Media Server 
c=IN IP4 0.0.0.0 
t=0 0 
a=control:* 
a=range:npt=now- 
m=video 0 RTP/AVP 98 
a=control:trackID=0 
a=framerate:25.000000 
a=rtpmap:98 H265/90000 
a=recvonly 
```

**2) SETUP**

* Estabeleça um canal de transmissão para cada mídia executando o comando SETUP.

```http
SETUP rtsp://<ip>/cam/realmonitor?channel=1&subtype=0/trackID=0 RTSP/1.0 
CSeq: 2 
User-Agent: LibVLC/3.0.5 
Transport: RTP/AVP;unicast;client_port=63088-63089 
```

**Resposta:**

```http
RTSP/1.0 200 OK 
CSeq: 2 
Server: Rtsp Server/3.0 
Session: 1546116282447;timeout=60 
Transport: RTP/AVP/UDP;unicast;client_port=63088-63089;server_port=24764-24765;ssrc=71B0AFDC
```

**3) PLAY**

* Execute o comando de reprodução para tocar a mídia e receber e enviar dados RTP e RTCP através do socket UDP estabelecido no passo 2.

```http
PLAY rtsp://<ip>/cam/realmonitor?channel=1&subtype=0/ RTSP/1.0 
CSeq: 3 
User-Agent: LibVLC/3.0.5 
Session: 1546116282447 
Range: npt=0.000- 
```

**Resposta:**

```http
RTSP/1.0 200 OK 
CSeq: 3 
Server: Rtsp Server/3.0 
Session: 1546116282447 
Range: npt=0.000- 
RTP-Info: url=trackID=0;seq=45020;rtptime=1907404764
```

**4) TEARDOWN**

* Execute o comando TEARDOWN para parar de reproduzir a mídia e então desative o socket UDP.

```http
TEARDOWN rtsp://<ip>/cam/realmonitor?channel=1&subtype=0/ RTSP/1.0 
CSeq: 4 
User-Agent: LibVLC/3.0.5 
Session: 1546116282447 
```

**Resposta:**

```http
RTSP/1.0 200 OK 
CSeq: 4 
Server: Rtsp Server/3.0 
Session: 1546116282447
```

### Obter Fluxo de Reprodução

**Tópico:** Obtenha o fluxo de reprodução

* Método: `DESCRIBE, SETUP, PLAY, PAUSE, TEARDOWN, ... /cam/playback`

**Exemplo**:

```http
rtsp://<ip>/cam/playback?channel=1&starttime=2012_09_15_12_37_05&endtime=2012_
09_15_18_34_14
```

{% hint style="warning" %}
Garantir formato correto de timestamp (YYYY-MM-DD HH:MM:SS)
{% endhint %}

### Obter Fluxo de Arquivo

**Tópico:** Obtenha o fluxo do arquivo

* Método: `DESCRIBE, SETUP, PLAY, PAUSE, TEARDOWN, ... rtsp://:[port]/<caminho para o arquivo>`

**Exemplo**:

```http
rtsp://<ip>//mnt/sd/2015-09-16/001/dav/20/20.32.08-20.32.28[M][0@0][0].dav
```

### Obter Stream MJPG&#x20;

**Tópico:** Obtenha um fluxo de vídeo codificado em mjpg.

* Método: `GET /cgi-bin/mjpg/video.cgi`

**Exemplo**:

```http
http://<ip>/cgi-bin/mjpg/video.cgi?channel=1&subtype=0 
```

**Resposta:**

```http
HTTP/1.1 200 OK 
Server: Device/1.0 
Content-Type: multipart/x-mixed-replace; boundary=<boundary> 
 --<boundary> 
Content-Type: image/jpeg 
Content-Length:<image size> 
 
<JPEG image data> --<boundary> 
Content-Type: image/jpeg 
Content-Length:<image size> 
 
<JPEG image data> --<boundary
```

### Criar RTSP Pull e Token de Autenticação

**Tópico:** Criar RTSP Pull e Token de autentocação

* Método: `POST /cgi-bin/api/TokenManager/createToken`

**Exemplo de request**:

```powershell
{ 
"Channel": 0
}
```

**Resposta:**

```http
{ 
"Token": "AwDSEci0j4EUW6pUz5bcQ0yK8_Rbq0vaUsUwqQKmFoUpuMJjOxy9kgcV6BlCty8U" 
} 
```

***

### Recomendações Técnicas Avançadas

#### Transporte

* Prefira **TCP (interleaved)** em:
  * Redes instáveis
  * Ambientes NAT
  * Firewalls restritivos
* Use **UDP** apenas em redes locais controladas.

#### Segurança

* Nunca exponha RTSP diretamente na internet.
* Utilize:
  * VPN
  * Reverse Proxy seguro
  * Firewall com IP allowlist
* Desative credenciais padrão.
* Monitore tentativas de brute force.

#### Ferramentas de Teste

* Postman e Insomnia não são adequados para:
  * RTSP
  * RTP
  * MJPEG persistente
  * Webhook contínuo

Ferramentas recomendadas:

* VLC
* FFmpeg
* Wireshark (análise de pacotes)

***

Notas finais:

* Ferramentas como **Postman** e **Insomnia não são compatíveis** com esse modelo
* A correta implementação destas diretrizes assegura:
  * **Estabilidade da conexão**
  * **Entrega confiável dos eventos**
  * **Desempenho adequado da integração**

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://portal-integracao.intelbras.com.br/cameras-and-gravadores/integracao-api-cftvip-e-mibo/cameras-e-gravadores/apis-rtsp.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
