Add : RTSP audio/video with back channel, and auth
- cam_stream: shared JPEG feed for /pic, /stream and RTSP; RTSP server (port 554, TCP) with MJPEG video, G.711 mic audio and an ONVIF-style back channel to the speaker - cam_auth: RTSP Digest login and HTTP Basic / ?key= check on all endpoints - Mic task feeds HTTP and RTSP with a sticky channel choice
This commit is contained in:
@@ -0,0 +1,919 @@
|
||||
/*
|
||||
* cam_stream.c
|
||||
* - shared JPEG feed (one capture/encode task for all viewers)
|
||||
* - audio hub: mic blocks are distributed to every RTSP session
|
||||
* - RTSP server, TCP-interleaved only
|
||||
* track0: video, RTP/JPEG (RFC 2435)
|
||||
* track1: audio, G.711 A-law / mu-law (8 kHz) or L16 (16 kHz), see RTSP_AUDIO_FORMAT
|
||||
* Access: Digest login on RTSP (cam_auth.c), same account as the HTTP endpoints.
|
||||
* track2: ONVIF-style back channel (client -> board, G.711), only offered when the
|
||||
* client asks for it with "Require: www.onvif.org/ver20/backchannel"
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <stdbool.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/stream_buffer.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_camera.h"
|
||||
#include "img_converters.h"
|
||||
#include "lwip/sockets.h"
|
||||
#include <netinet/tcp.h>
|
||||
#include "cam_stream.h"
|
||||
#include "cam_auth.h"
|
||||
|
||||
static const char *TAG = "CAMSTREAM";
|
||||
|
||||
#define CAM_JPEG_QUALITY 70 /* frame2jpg quality, higher = better/larger */
|
||||
#define RTSP_PORT 554
|
||||
#define RTSP_MAX_SESSIONS 2
|
||||
#define RTSP_RX_SIZE 2048
|
||||
#define RTP_MAX_PAYLOAD 1400 /* JPEG payload bytes per RTP packet */
|
||||
#define RTP_PKT_SIZE (4 + 12 + 8 + 132 + RTP_MAX_PAYLOAD)
|
||||
|
||||
/* ---- RTSP audio format ----------------------------------------------------
|
||||
* RTSP_AUDIO_PCMA : G.711 A-law, 8 kHz (static payload type 8, Europe/most NVRs)
|
||||
* RTSP_AUDIO_PCMU : G.711 mu-law, 8 kHz (static payload type 0, US/Japan)
|
||||
* RTSP_AUDIO_L16 : raw 16-bit PCM, 16 kHz (dynamic type 97, wideband quality,
|
||||
* supported by ffmpeg/VLC/go2rtc/Frigate, but not by every NVR)
|
||||
* G.711 is telephone quality (about 300-3400 Hz). L16 keeps the full 16 kHz mic signal. */
|
||||
#define RTSP_AUDIO_PCMA 0
|
||||
#define RTSP_AUDIO_PCMU 1
|
||||
#define RTSP_AUDIO_L16 2
|
||||
#define RTSP_AUDIO_FORMAT RTSP_AUDIO_PCMA
|
||||
|
||||
#if RTSP_AUDIO_FORMAT == RTSP_AUDIO_PCMA
|
||||
#define AUDIO_PT 8
|
||||
#define AUDIO_PT_STR "8"
|
||||
#define AUDIO_RTPMAP "a=rtpmap:8 PCMA/8000\r\n"
|
||||
#elif RTSP_AUDIO_FORMAT == RTSP_AUDIO_PCMU
|
||||
#define AUDIO_PT 0
|
||||
#define AUDIO_PT_STR "0"
|
||||
#define AUDIO_RTPMAP "a=rtpmap:0 PCMU/8000\r\n"
|
||||
#else
|
||||
#define AUDIO_PT 97
|
||||
#define AUDIO_PT_STR "97"
|
||||
#define AUDIO_RTPMAP "a=rtpmap:97 L16/16000/1\r\n"
|
||||
#endif
|
||||
|
||||
#define AUDIO_IN_SAMPLES 320 /* 20 ms of 16 kHz mic audio per RTP packet */
|
||||
#define AUDIO_SB_SIZE 6144 /* per-session queue, ~190 ms at 16 kHz/16-bit */
|
||||
#define AUDIO_PKT_SIZE (4 + 12 + AUDIO_IN_SAMPLES * 2)
|
||||
|
||||
/* ================================================================== */
|
||||
/* Shared JPEG feed */
|
||||
/* ================================================================== */
|
||||
static SemaphoreHandle_t s_jpg_mutex = NULL;
|
||||
static SemaphoreHandle_t s_audio_mutex = NULL;
|
||||
static SemaphoreHandle_t s_spk_mutex = NULL;
|
||||
static uint8_t *s_jpg_buf = NULL;
|
||||
static size_t s_jpg_len = 0;
|
||||
static uint32_t s_jpg_seq = 0;
|
||||
static volatile int s_viewers = 0;
|
||||
|
||||
static void feed_task(void *arg)
|
||||
{
|
||||
while (1) {
|
||||
if (s_viewers <= 0) { /* nobody watching: stay idle */
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
continue;
|
||||
}
|
||||
camera_fb_t *fb = esp_camera_fb_get();
|
||||
if (!fb) {
|
||||
ESP_LOGE(TAG, "Camera capture failed");
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
continue;
|
||||
}
|
||||
uint8_t *j = NULL;
|
||||
size_t jl = 0;
|
||||
bool ok = frame2jpg(fb, CAM_JPEG_QUALITY, &j, &jl);
|
||||
esp_camera_fb_return(fb);
|
||||
if (!ok || !j) {
|
||||
ESP_LOGE(TAG, "JPEG compression failed");
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
continue;
|
||||
}
|
||||
|
||||
xSemaphoreTake(s_jpg_mutex, portMAX_DELAY);
|
||||
uint8_t *old = s_jpg_buf;
|
||||
s_jpg_buf = j;
|
||||
s_jpg_len = jl;
|
||||
s_jpg_seq++;
|
||||
xSemaphoreGive(s_jpg_mutex);
|
||||
free(old);
|
||||
|
||||
vTaskDelay(1); /* let other tasks run */
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t cam_feed_start(void)
|
||||
{
|
||||
if (s_jpg_mutex) return ESP_OK;
|
||||
s_jpg_mutex = xSemaphoreCreateMutex();
|
||||
s_audio_mutex = xSemaphoreCreateMutex();
|
||||
s_spk_mutex = xSemaphoreCreateMutex();
|
||||
if (!s_jpg_mutex || !s_audio_mutex || !s_spk_mutex) return ESP_ERR_NO_MEM;
|
||||
if (xTaskCreate(feed_task, "jpeg_feed", 8192, NULL, 5, NULL) != pdPASS) return ESP_ERR_NO_MEM;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void cam_feed_viewer_add(uint32_t *seq)
|
||||
{
|
||||
xSemaphoreTake(s_jpg_mutex, portMAX_DELAY);
|
||||
*seq = s_jpg_seq; /* skip any stale frame, wait for a fresh one */
|
||||
xSemaphoreGive(s_jpg_mutex);
|
||||
__atomic_fetch_add(&s_viewers, 1, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
|
||||
void cam_feed_viewer_remove(void)
|
||||
{
|
||||
__atomic_fetch_sub(&s_viewers, 1, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
|
||||
size_t cam_feed_wait(uint8_t **buf, size_t *cap, uint32_t *seq, uint32_t timeout_ms)
|
||||
{
|
||||
TickType_t start = xTaskGetTickCount();
|
||||
while (1) {
|
||||
xSemaphoreTake(s_jpg_mutex, portMAX_DELAY);
|
||||
if (s_jpg_buf && s_jpg_seq != *seq) {
|
||||
size_t n = s_jpg_len;
|
||||
if (n > *cap) {
|
||||
uint8_t *nb = realloc(*buf, n + 4096);
|
||||
if (!nb) {
|
||||
xSemaphoreGive(s_jpg_mutex);
|
||||
return 0;
|
||||
}
|
||||
*buf = nb;
|
||||
*cap = n + 4096;
|
||||
}
|
||||
memcpy(*buf, s_jpg_buf, n);
|
||||
*seq = s_jpg_seq;
|
||||
xSemaphoreGive(s_jpg_mutex);
|
||||
return n;
|
||||
}
|
||||
xSemaphoreGive(s_jpg_mutex);
|
||||
|
||||
if ((xTaskGetTickCount() - start) >= pdMS_TO_TICKS(timeout_ms)) return 0;
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== */
|
||||
/* Audio hub: every RTSP session gets its own queue of mic samples */
|
||||
/* ================================================================== */
|
||||
static StreamBufferHandle_t s_audio_sb[RTSP_MAX_SESSIONS];
|
||||
static volatile int s_audio_subs = 0;
|
||||
|
||||
static StreamBufferHandle_t audio_subscribe(void)
|
||||
{
|
||||
StreamBufferHandle_t sb = xStreamBufferCreate(AUDIO_SB_SIZE, 1);
|
||||
if (!sb) return NULL;
|
||||
|
||||
bool placed = false;
|
||||
xSemaphoreTake(s_audio_mutex, portMAX_DELAY);
|
||||
for (int i = 0; i < RTSP_MAX_SESSIONS; i++) {
|
||||
if (!s_audio_sb[i]) { s_audio_sb[i] = sb; placed = true; break; }
|
||||
}
|
||||
xSemaphoreGive(s_audio_mutex);
|
||||
|
||||
if (!placed) {
|
||||
vStreamBufferDelete(sb);
|
||||
return NULL;
|
||||
}
|
||||
__atomic_fetch_add(&s_audio_subs, 1, __ATOMIC_SEQ_CST);
|
||||
return sb;
|
||||
}
|
||||
|
||||
static void audio_unsubscribe(StreamBufferHandle_t sb)
|
||||
{
|
||||
xSemaphoreTake(s_audio_mutex, portMAX_DELAY);
|
||||
for (int i = 0; i < RTSP_MAX_SESSIONS; i++)
|
||||
if (s_audio_sb[i] == sb) s_audio_sb[i] = NULL;
|
||||
xSemaphoreGive(s_audio_mutex);
|
||||
__atomic_fetch_sub(&s_audio_subs, 1, __ATOMIC_SEQ_CST);
|
||||
vStreamBufferDelete(sb);
|
||||
}
|
||||
|
||||
bool cam_audio_wanted(void)
|
||||
{
|
||||
return s_audio_subs > 0;
|
||||
}
|
||||
|
||||
void cam_audio_push(const int16_t *pcm, size_t samples)
|
||||
{
|
||||
if (!s_audio_mutex || s_audio_subs <= 0) return;
|
||||
size_t bytes = samples * sizeof(int16_t);
|
||||
|
||||
xSemaphoreTake(s_audio_mutex, portMAX_DELAY);
|
||||
for (int i = 0; i < RTSP_MAX_SESSIONS; i++) {
|
||||
StreamBufferHandle_t sb = s_audio_sb[i];
|
||||
/* whole blocks only: a partial write would shift the byte alignment of the samples */
|
||||
if (sb && xStreamBufferSpacesAvailable(sb) >= bytes)
|
||||
xStreamBufferSend(sb, pcm, bytes, 0);
|
||||
}
|
||||
xSemaphoreGive(s_audio_mutex);
|
||||
}
|
||||
|
||||
/* ---------- G.711 encoders ---------- */
|
||||
static __attribute__((unused)) uint8_t lin2ulaw(int16_t pcm16)
|
||||
{
|
||||
const int BIAS = 0x84, CLIP = 32635;
|
||||
int v = pcm16;
|
||||
int sign = (v >> 8) & 0x80;
|
||||
if (sign) v = -v;
|
||||
if (v > CLIP) v = CLIP;
|
||||
v += BIAS;
|
||||
int exp = 7;
|
||||
for (int mask = 0x4000; (v & mask) == 0 && exp > 0; exp--, mask >>= 1) {}
|
||||
int mant = (v >> (exp + 3)) & 0x0F;
|
||||
return (uint8_t)~(sign | (exp << 4) | mant);
|
||||
}
|
||||
|
||||
static __attribute__((unused)) uint8_t lin2alaw(int16_t pcm16)
|
||||
{
|
||||
static const int seg_end[8] = {0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF};
|
||||
int v = pcm16 >> 3; /* 13-bit */
|
||||
int mask;
|
||||
if (v >= 0) {
|
||||
mask = 0xD5;
|
||||
} else {
|
||||
mask = 0x55;
|
||||
v = -v - 1;
|
||||
}
|
||||
int seg = 8;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
if (v <= seg_end[i]) { seg = i; break; }
|
||||
}
|
||||
if (seg >= 8) return (uint8_t)(0x7F ^ mask);
|
||||
int aval = seg << 4;
|
||||
aval |= (seg < 2) ? ((v >> 1) & 0x0F) : ((v >> seg) & 0x0F);
|
||||
return (uint8_t)(aval ^ mask);
|
||||
}
|
||||
|
||||
/* ---------- G.711 decoders (back channel) ---------- */
|
||||
static int16_t alaw2lin(uint8_t a)
|
||||
{
|
||||
a ^= 0x55;
|
||||
int t = (a & 0x0F) << 4;
|
||||
int seg = (a & 0x70) >> 4;
|
||||
switch (seg) {
|
||||
case 0: t += 8; break;
|
||||
case 1: t += 0x108; break;
|
||||
default: t += 0x108; t <<= (seg - 1); break;
|
||||
}
|
||||
return (int16_t)((a & 0x80) ? t : -t);
|
||||
}
|
||||
|
||||
static int16_t ulaw2lin(uint8_t u)
|
||||
{
|
||||
u = (uint8_t)~u;
|
||||
int t = ((u & 0x0F) << 3) + 0x84;
|
||||
t <<= (u & 0x70) >> 4;
|
||||
return (int16_t)((u & 0x80) ? (0x84 - t) : (t - 0x84));
|
||||
}
|
||||
|
||||
/* ---------- Speaker sink: where back-channel audio goes ---------- */
|
||||
static cam_speaker_sink_t s_spk_sink = NULL;
|
||||
|
||||
void rtsp_set_speaker_sink(cam_speaker_sink_t fn)
|
||||
{
|
||||
s_spk_sink = fn;
|
||||
}
|
||||
|
||||
/* ================================================================== */
|
||||
/* JPEG parsing for RTP/JPEG (RFC 2435) */
|
||||
/* ================================================================== */
|
||||
typedef struct {
|
||||
const uint8_t *scan; /* entropy-coded data after the SOS header */
|
||||
size_t scan_len;
|
||||
uint8_t type; /* 0 = 4:2:2, 1 = 4:2:0 */
|
||||
uint8_t w8, h8; /* size in 8-pixel units */
|
||||
uint8_t y_samp; /* luma sampling byte, for diagnostics */
|
||||
uint8_t qt[2][64];
|
||||
bool have_qt[2];
|
||||
} jpg_info_t;
|
||||
|
||||
static bool jpeg_parse(const uint8_t *b, size_t n, jpg_info_t *o)
|
||||
{
|
||||
memset(o, 0, sizeof(*o));
|
||||
if (n < 4 || b[0] != 0xFF || b[1] != 0xD8) return false;
|
||||
|
||||
size_t i = 2;
|
||||
bool sof = false, sos = false;
|
||||
|
||||
while (!sos && i + 4 <= n) {
|
||||
if (b[i] != 0xFF) return false;
|
||||
uint8_t m = b[i + 1];
|
||||
if (m == 0xFF) { i++; continue; } /* fill byte */
|
||||
if (m == 0x01 || (m >= 0xD0 && m <= 0xD8)) { i += 2; continue; }
|
||||
|
||||
size_t seg = ((size_t)b[i + 2] << 8) | b[i + 3];
|
||||
if (seg < 2 || i + 2 + seg > n) return false;
|
||||
const uint8_t *p = b + i + 4;
|
||||
size_t plen = seg - 2;
|
||||
|
||||
switch (m) {
|
||||
case 0xDB: { /* DQT */
|
||||
size_t k = 0;
|
||||
while (k < plen) {
|
||||
uint8_t pq = p[k] >> 4, tq = p[k] & 0x0F;
|
||||
k++;
|
||||
if (pq != 0 || tq > 1 || k + 64 > plen) return false;
|
||||
memcpy(o->qt[tq], &p[k], 64);
|
||||
o->have_qt[tq] = true;
|
||||
k += 64;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 0xC0: { /* SOF0 baseline */
|
||||
if (plen < 15 || p[0] != 8 || p[5] != 3) return false;
|
||||
uint16_t h = (p[1] << 8) | p[2];
|
||||
uint16_t w = (p[3] << 8) | p[4];
|
||||
o->y_samp = p[7];
|
||||
if (p[10] != 0x11 || p[13] != 0x11) return false;
|
||||
if (p[7] == 0x21) o->type = 0;
|
||||
else if (p[7] == 0x22) o->type = 1;
|
||||
else return false;
|
||||
if (w == 0 || h == 0 || w > 2040 || h > 2040) return false;
|
||||
o->w8 = (w + 7) / 8;
|
||||
o->h8 = (h + 7) / 8;
|
||||
sof = true;
|
||||
break;
|
||||
}
|
||||
case 0xC1: case 0xC2: /* extended / progressive */
|
||||
return false;
|
||||
case 0xDD: /* DRI */
|
||||
if (plen >= 2 && (p[0] | p[1])) return false; /* restart markers unsupported */
|
||||
break;
|
||||
case 0xDA: /* SOS */
|
||||
o->scan = b + i + 2 + seg;
|
||||
o->scan_len = n - (i + 2 + seg);
|
||||
sos = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
i += 2 + seg;
|
||||
}
|
||||
|
||||
if (!sos || !sof || !o->have_qt[0] || !o->have_qt[1]) return false;
|
||||
if (o->scan_len >= 2 && o->scan[o->scan_len - 2] == 0xFF && o->scan[o->scan_len - 1] == 0xD9)
|
||||
o->scan_len -= 2; /* strip EOI */
|
||||
return o->scan_len > 0;
|
||||
}
|
||||
|
||||
/* ================================================================== */
|
||||
/* RTSP */
|
||||
/* ================================================================== */
|
||||
typedef struct {
|
||||
int fd;
|
||||
bool has_v, has_a, has_b; /* tracks the client set up (b = back channel) */
|
||||
bool onvif; /* client asked for the ONVIF back channel */
|
||||
bool playing, viewer, warned;
|
||||
uint8_t ch_v, ch_a, ch_b; /* interleaved RTP channels */
|
||||
int16_t bc_prev; /* last decoded back-channel sample (interpolation) */
|
||||
bool bc_logged;
|
||||
bool authed; /* Digest login succeeded on this connection */
|
||||
int auth_fail;
|
||||
char nonce[33];
|
||||
uint16_t seq_v, seq_a;
|
||||
uint32_t ssrc_v, ssrc_a, ts_a;
|
||||
uint32_t session_id;
|
||||
uint32_t last_seq; /* shared-feed marker */
|
||||
StreamBufferHandle_t asb; /* this session's audio queue */
|
||||
uint8_t *apkt; /* audio packet scratch buffer */
|
||||
int16_t a_hist[6]; /* FIR history for the 16k -> 8k decimator */
|
||||
} rtsp_sess_t;
|
||||
|
||||
static volatile int s_rtsp_sessions = 0;
|
||||
|
||||
static bool send_all(int fd, const uint8_t *d, size_t n)
|
||||
{
|
||||
while (n) {
|
||||
int r = send(fd, d, n, 0);
|
||||
if (r <= 0) return false;
|
||||
d += r;
|
||||
n -= r;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void rtp_header(uint8_t *rtp, uint8_t pt, bool marker, uint16_t seq, uint32_t ts, uint32_t ssrc)
|
||||
{
|
||||
rtp[0] = 0x80;
|
||||
rtp[1] = pt | (marker ? 0x80 : 0);
|
||||
rtp[2] = seq >> 8; rtp[3] = seq & 0xFF;
|
||||
rtp[4] = ts >> 24; rtp[5] = ts >> 16; rtp[6] = ts >> 8; rtp[7] = ts;
|
||||
rtp[8] = ssrc >> 24; rtp[9] = ssrc >> 16; rtp[10] = ssrc >> 8; rtp[11] = ssrc;
|
||||
}
|
||||
|
||||
#if RTSP_AUDIO_FORMAT != RTSP_AUDIO_L16
|
||||
/* 16 kHz -> 8 kHz with a 7-tap half-band low-pass [-1 0 9 16 9 0 -1]/32 (320 in, 160 out) */
|
||||
static void downsample_2x(rtsp_sess_t *s, const int16_t *in, int16_t *out)
|
||||
{
|
||||
int16_t x[6 + AUDIO_IN_SAMPLES];
|
||||
memcpy(x, s->a_hist, sizeof(s->a_hist));
|
||||
memcpy(x + 6, in, AUDIO_IN_SAMPLES * sizeof(int16_t));
|
||||
for (int i = 0; i < AUDIO_IN_SAMPLES / 2; i++) {
|
||||
const int16_t *p = &x[2 * i];
|
||||
int acc = (-p[0] + 9 * p[2] + 16 * p[3] + 9 * p[4] - p[6]) >> 5;
|
||||
if (acc > 32767) acc = 32767;
|
||||
if (acc < -32768) acc = -32768;
|
||||
out[i] = (int16_t)acc;
|
||||
}
|
||||
memcpy(s->a_hist, &x[AUDIO_IN_SAMPLES], sizeof(s->a_hist));
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Sends every complete 20 ms audio block that is waiting in this session's queue */
|
||||
static bool audio_pump(rtsp_sess_t *s)
|
||||
{
|
||||
int16_t in[AUDIO_IN_SAMPLES];
|
||||
|
||||
while (xStreamBufferBytesAvailable(s->asb) >= sizeof(in)) {
|
||||
xStreamBufferReceive(s->asb, in, sizeof(in), 0);
|
||||
|
||||
uint8_t *pl = s->apkt + 4 + 12;
|
||||
size_t plen;
|
||||
uint32_t samples;
|
||||
|
||||
#if RTSP_AUDIO_FORMAT == RTSP_AUDIO_L16
|
||||
for (int i = 0; i < AUDIO_IN_SAMPLES; i++) { /* network byte order */
|
||||
pl[2 * i] = (uint8_t)(in[i] >> 8);
|
||||
pl[2 * i + 1] = (uint8_t)(in[i] & 0xFF);
|
||||
}
|
||||
plen = AUDIO_IN_SAMPLES * 2;
|
||||
samples = AUDIO_IN_SAMPLES;
|
||||
#else
|
||||
int16_t d[AUDIO_IN_SAMPLES / 2];
|
||||
downsample_2x(s, in, d);
|
||||
for (int i = 0; i < AUDIO_IN_SAMPLES / 2; i++) {
|
||||
#if RTSP_AUDIO_FORMAT == RTSP_AUDIO_PCMA
|
||||
pl[i] = lin2alaw(d[i]);
|
||||
#else
|
||||
pl[i] = lin2ulaw(d[i]);
|
||||
#endif
|
||||
}
|
||||
plen = AUDIO_IN_SAMPLES / 2;
|
||||
samples = AUDIO_IN_SAMPLES / 2;
|
||||
#endif
|
||||
|
||||
rtp_header(s->apkt + 4, AUDIO_PT, false, s->seq_a++, s->ts_a, s->ssrc_a);
|
||||
s->ts_a += samples;
|
||||
|
||||
size_t rl = 12 + plen;
|
||||
s->apkt[0] = '$';
|
||||
s->apkt[1] = s->ch_a;
|
||||
s->apkt[2] = rl >> 8;
|
||||
s->apkt[3] = rl & 0xFF;
|
||||
if (!send_all(s->fd, s->apkt, 4 + rl)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Back channel: RTP/G.711 from the client -> 16 kHz PCM -> speaker sink */
|
||||
static void backchannel_rx(rtsp_sess_t *s, const uint8_t *p, size_t n)
|
||||
{
|
||||
if (!s_spk_sink || n < 12 || (p[0] >> 6) != 2) return;
|
||||
|
||||
size_t off = 12 + 4 * (size_t)(p[0] & 0x0F); /* CSRC list */
|
||||
if (p[0] & 0x10) { /* header extension */
|
||||
if (n < off + 4) return;
|
||||
off += 4 + 4 * (((size_t)p[off + 2] << 8) | p[off + 3]);
|
||||
}
|
||||
size_t end = n;
|
||||
if (p[0] & 0x20) { /* padding */
|
||||
size_t pad = p[n - 1];
|
||||
if (pad > end) return;
|
||||
end -= pad;
|
||||
}
|
||||
if (off >= end) return;
|
||||
|
||||
uint8_t pt = p[1] & 0x7F;
|
||||
if (pt != 0 && pt != 8) return; /* PCMU / PCMA only */
|
||||
if (!s->bc_logged) {
|
||||
ESP_LOGI(TAG, "Back channel audio received: payload type %u, %u bytes/packet",
|
||||
(unsigned)pt, (unsigned)(end - off));
|
||||
s->bc_logged = true;
|
||||
}
|
||||
|
||||
p += off;
|
||||
size_t cnt = end - off;
|
||||
int16_t out[2 * 160];
|
||||
|
||||
xSemaphoreTake(s_spk_mutex, portMAX_DELAY); /* one talker at a time */
|
||||
while (cnt) {
|
||||
size_t c = cnt > 160 ? 160 : cnt;
|
||||
for (size_t i = 0; i < c; i++) {
|
||||
int16_t cur = (pt == 8) ? alaw2lin(p[i]) : ulaw2lin(p[i]);
|
||||
out[2 * i] = (int16_t)((s->bc_prev + cur) / 2); /* 8 kHz -> 16 kHz, linear interpolation */
|
||||
out[2 * i + 1] = cur;
|
||||
s->bc_prev = cur;
|
||||
}
|
||||
s_spk_sink(out, 2 * c);
|
||||
p += c;
|
||||
cnt -= c;
|
||||
}
|
||||
xSemaphoreGive(s_spk_mutex);
|
||||
}
|
||||
|
||||
static void rtsp_reply(int fd, int code, const char *text, int cseq, const char *extra, const char *body)
|
||||
{
|
||||
char hdr[640];
|
||||
size_t blen = body ? strlen(body) : 0;
|
||||
int n = snprintf(hdr, sizeof(hdr), "RTSP/1.0 %d %s\r\nCSeq: %d\r\nServer: ESP32-Cam\r\n%s",
|
||||
code, text, cseq, extra ? extra : "");
|
||||
if (n < 0 || n >= (int)sizeof(hdr) - 40) return;
|
||||
if (blen) n += snprintf(hdr + n, sizeof(hdr) - n, "Content-Length: %u\r\n", (unsigned)blen);
|
||||
n += snprintf(hdr + n, sizeof(hdr) - n, "\r\n");
|
||||
send_all(fd, (const uint8_t *)hdr, n);
|
||||
if (blen) send_all(fd, (const uint8_t *)body, blen);
|
||||
}
|
||||
|
||||
/* returns pointer to the header value inside req, or NULL */
|
||||
static const char *hdr_value(const char *req, const char *name)
|
||||
{
|
||||
size_t nl = strlen(name);
|
||||
const char *p = strstr(req, "\r\n");
|
||||
while (p) {
|
||||
p += 2;
|
||||
if (strncasecmp(p, name, nl) == 0 && p[nl] == ':') {
|
||||
p += nl + 1;
|
||||
while (*p == ' ') p++;
|
||||
return p;
|
||||
}
|
||||
p = strstr(p, "\r\n");
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static bool hdr_copy(const char *req, const char *name, char *out, size_t outlen)
|
||||
{
|
||||
const char *v = hdr_value(req, name);
|
||||
if (!v) return false;
|
||||
size_t i = 0;
|
||||
while (v[i] && v[i] != '\r' && v[i] != '\n' && i < outlen - 1) { out[i] = v[i]; i++; }
|
||||
out[i] = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Returns false when the session must end (TEARDOWN) */
|
||||
static bool rtsp_handle(rtsp_sess_t *s, const char *req)
|
||||
{
|
||||
char method[16] = {0}, url[200] = {0};
|
||||
if (sscanf(req, "%15s %199s", method, url) < 1) return true;
|
||||
|
||||
char tmp[32];
|
||||
int cseq = 0;
|
||||
if (hdr_copy(req, "CSeq", tmp, sizeof(tmp))) cseq = atoi(tmp);
|
||||
|
||||
char sess_hdr[48];
|
||||
snprintf(sess_hdr, sizeof(sess_hdr), "Session: %08X\r\n", (unsigned)s->session_id);
|
||||
|
||||
ESP_LOGI(TAG, "RTSP %s %s", method, url);
|
||||
|
||||
/* Digest login. OPTIONS stays open, as most cameras do. Once a connection has logged in,
|
||||
* later requests on it are accepted (some clients only send the header on DESCRIBE). */
|
||||
if (cam_auth_enabled() && !s->authed && strcmp(method, "OPTIONS") != 0) {
|
||||
char authz[400];
|
||||
bool had = hdr_copy(req, "Authorization", authz, sizeof(authz));
|
||||
if (had && cam_rtsp_digest_ok(method, authz, s->nonce)) {
|
||||
s->authed = true;
|
||||
} else {
|
||||
char wa[120];
|
||||
snprintf(wa, sizeof(wa), "WWW-Authenticate: Digest realm=\"%s\", nonce=\"%s\"\r\n",
|
||||
CAM_AUTH_REALM, s->nonce);
|
||||
if (had) { /* wrong credentials, not just the first challenge */
|
||||
s->auth_fail++;
|
||||
ESP_LOGW(TAG, "RTSP authentication failed (%d/5)", s->auth_fail);
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
}
|
||||
rtsp_reply(s->fd, 401, "Unauthorized", cseq, wa, NULL);
|
||||
return s->auth_fail < 5; /* drop the connection after 5 bad tries */
|
||||
}
|
||||
}
|
||||
|
||||
if (!strcmp(method, "OPTIONS")) {
|
||||
rtsp_reply(s->fd, 200, "OK", cseq,
|
||||
"Public: OPTIONS, DESCRIBE, SETUP, PLAY, TEARDOWN, GET_PARAMETER\r\n", NULL);
|
||||
|
||||
} else if (!strcmp(method, "DESCRIBE")) {
|
||||
char ip[16] = "0.0.0.0";
|
||||
struct sockaddr_in la;
|
||||
socklen_t ll = sizeof(la);
|
||||
if (getsockname(s->fd, (struct sockaddr *)&la, &ll) == 0)
|
||||
inet_ntoa_r(la.sin_addr, ip, sizeof(ip));
|
||||
|
||||
/* ONVIF back channel is offered only to clients that ask for it */
|
||||
char rq[96] = {0};
|
||||
bool want_bc = s_spk_sink && hdr_copy(req, "Require", rq, sizeof(rq)) &&
|
||||
strstr(rq, "www.onvif.org/ver20/backchannel");
|
||||
s->onvif = want_bc;
|
||||
const char *dir = want_bc ? "a=recvonly\r\n" : "";
|
||||
|
||||
char sdp[720];
|
||||
int sl = snprintf(sdp, sizeof(sdp),
|
||||
"v=0\r\no=- 0 0 IN IP4 %s\r\ns=ESP32 Camera\r\nc=IN IP4 0.0.0.0\r\nt=0 0\r\n"
|
||||
"m=video 0 RTP/AVP 26\r\na=control:track0\r\n%s"
|
||||
"m=audio 0 RTP/AVP " AUDIO_PT_STR "\r\n" AUDIO_RTPMAP "a=control:track1\r\n%s",
|
||||
ip, dir, dir);
|
||||
if (want_bc && sl > 0 && sl < (int)sizeof(sdp))
|
||||
snprintf(sdp + sl, sizeof(sdp) - sl,
|
||||
"m=audio 0 RTP/AVP 0 8\r\na=control:track2\r\n"
|
||||
"a=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=sendonly\r\n");
|
||||
|
||||
char extra[300];
|
||||
size_t ul = strlen(url);
|
||||
snprintf(extra, sizeof(extra), "Content-Base: %s%s\r\nContent-Type: application/sdp\r\n",
|
||||
url, (ul && url[ul - 1] == '/') ? "" : "/");
|
||||
rtsp_reply(s->fd, 200, "OK", cseq, extra, sdp);
|
||||
|
||||
} else if (!strcmp(method, "SETUP")) {
|
||||
char tr[160];
|
||||
if (!hdr_copy(req, "Transport", tr, sizeof(tr)) || !strstr(tr, "RTP/AVP/TCP")) {
|
||||
/* UDP requested: refuse, clients (ffmpeg, VLC) then retry with TCP */
|
||||
rtsp_reply(s->fd, 461, "Unsupported Transport", cseq, NULL, NULL);
|
||||
return true;
|
||||
}
|
||||
bool is_bc = (strstr(url, "track2") != NULL);
|
||||
bool is_audio = !is_bc && (strstr(url, "track1") != NULL);
|
||||
|
||||
int c0 = -1, c1 = -1;
|
||||
const char *il = strstr(tr, "interleaved=");
|
||||
if (il) sscanf(il + 12, "%d-%d", &c0, &c1);
|
||||
if (c0 < 0 || c0 > 253) c0 = is_bc ? 4 : (is_audio ? 2 : 0);
|
||||
if (c1 < 0) c1 = c0 + 1;
|
||||
|
||||
if (is_bc) {
|
||||
if (!s_spk_sink) {
|
||||
rtsp_reply(s->fd, 404, "Not Found", cseq, NULL, NULL);
|
||||
return true;
|
||||
}
|
||||
s->ch_b = (uint8_t)c0;
|
||||
s->has_b = true;
|
||||
} else if (is_audio) {
|
||||
s->ch_a = (uint8_t)c0;
|
||||
s->has_a = true;
|
||||
} else {
|
||||
s->ch_v = (uint8_t)c0;
|
||||
s->has_v = true;
|
||||
}
|
||||
|
||||
char extra[160];
|
||||
snprintf(extra, sizeof(extra),
|
||||
"Transport: RTP/AVP/TCP;unicast;interleaved=%d-%d\r\nSession: %08X;timeout=60\r\n",
|
||||
c0, c1, (unsigned)s->session_id);
|
||||
rtsp_reply(s->fd, 200, "OK", cseq, extra, NULL);
|
||||
|
||||
} else if (!strcmp(method, "PLAY")) {
|
||||
if (!s->has_v && !s->has_a && !s->has_b) {
|
||||
rtsp_reply(s->fd, 455, "Method Not Valid In This State", cseq, NULL, NULL);
|
||||
return true;
|
||||
}
|
||||
if (!s->playing) {
|
||||
if (s->has_v) {
|
||||
cam_feed_viewer_add(&s->last_seq);
|
||||
s->viewer = true;
|
||||
}
|
||||
if (s->has_a) {
|
||||
s->asb = audio_subscribe();
|
||||
if (!s->asb) ESP_LOGW(TAG, "No audio queue available, sending video only");
|
||||
}
|
||||
s->playing = true;
|
||||
}
|
||||
char extra[96];
|
||||
snprintf(extra, sizeof(extra), "%sRange: npt=0.000-\r\n", sess_hdr);
|
||||
rtsp_reply(s->fd, 200, "OK", cseq, extra, NULL);
|
||||
|
||||
} else if (!strcmp(method, "TEARDOWN")) {
|
||||
rtsp_reply(s->fd, 200, "OK", cseq, sess_hdr, NULL);
|
||||
return false;
|
||||
|
||||
} else if (!strcmp(method, "GET_PARAMETER") || !strcmp(method, "SET_PARAMETER")) {
|
||||
rtsp_reply(s->fd, 200, "OK", cseq, sess_hdr, NULL);
|
||||
|
||||
} else {
|
||||
rtsp_reply(s->fd, 405, "Method Not Allowed", cseq, NULL, NULL);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Parses everything buffered from the client: RTSP requests and interleaved RTCP ($ frames) */
|
||||
static bool rtsp_process_rx(rtsp_sess_t *s, char *rx, size_t *rx_len)
|
||||
{
|
||||
while (*rx_len > 0) {
|
||||
if (rx[0] == '$') { /* interleaved frame from client (RTCP) */
|
||||
if (*rx_len < 4) break;
|
||||
size_t fl = 4 + (((uint8_t)rx[2] << 8) | (uint8_t)rx[3]);
|
||||
if (fl > RTSP_RX_SIZE) return false;
|
||||
if (*rx_len < fl) break;
|
||||
if (s->has_b && s->playing && (uint8_t)rx[1] == s->ch_b)
|
||||
backchannel_rx(s, (const uint8_t *)rx + 4, fl - 4);
|
||||
memmove(rx, rx + fl, *rx_len - fl);
|
||||
*rx_len -= fl;
|
||||
continue;
|
||||
}
|
||||
|
||||
rx[*rx_len] = 0;
|
||||
char *end = strstr(rx, "\r\n\r\n");
|
||||
if (!end) {
|
||||
if (*rx_len >= RTSP_RX_SIZE) return false; /* garbage / too long */
|
||||
break;
|
||||
}
|
||||
size_t rl = (size_t)(end - rx) + 4;
|
||||
char saved = rx[rl];
|
||||
rx[rl] = 0;
|
||||
bool keep = rtsp_handle(s, rx);
|
||||
rx[rl] = saved;
|
||||
memmove(rx, rx + rl, *rx_len - rl);
|
||||
*rx_len -= rl;
|
||||
if (!keep) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Sends one JPEG frame as RTP/JPEG packets; audio is interleaved between the video packets */
|
||||
static bool rtp_send_jpeg(rtsp_sess_t *s, const uint8_t *jpg, size_t n, uint8_t *pkt)
|
||||
{
|
||||
jpg_info_t ji;
|
||||
if (!jpeg_parse(jpg, n, &ji)) {
|
||||
if (!s->warned) {
|
||||
ESP_LOGE(TAG, "JPEG not RTP-compatible (luma sampling 0x%02X); frames are skipped", ji.y_samp);
|
||||
s->warned = true;
|
||||
}
|
||||
return true; /* skip frame, keep the session */
|
||||
}
|
||||
|
||||
uint32_t ts = (uint32_t)((esp_timer_get_time() * 9) / 100); /* 90 kHz clock */
|
||||
size_t off = 0;
|
||||
|
||||
while (off < ji.scan_len) {
|
||||
bool first = (off == 0);
|
||||
size_t room = RTP_MAX_PAYLOAD - 8 - (first ? 132 : 0);
|
||||
size_t chunk = ji.scan_len - off;
|
||||
if (chunk > room) chunk = room;
|
||||
bool last = (off + chunk >= ji.scan_len);
|
||||
|
||||
uint8_t *rtp = pkt + 4;
|
||||
rtp_header(rtp, 26, last, s->seq_v++, ts, s->ssrc_v);
|
||||
|
||||
uint8_t *q = rtp + 12;
|
||||
q[0] = 0; /* type-specific */
|
||||
q[1] = off >> 16; q[2] = off >> 8; q[3] = off; /* fragment offset */
|
||||
q[4] = ji.type;
|
||||
q[5] = 255; /* Q=255: tables sent in-band */
|
||||
q[6] = ji.w8;
|
||||
q[7] = ji.h8;
|
||||
q += 8;
|
||||
|
||||
if (first) { /* quantization table header */
|
||||
q[0] = 0; q[1] = 0; q[2] = 0; q[3] = 128;
|
||||
memcpy(q + 4, ji.qt[0], 64);
|
||||
memcpy(q + 68, ji.qt[1], 64);
|
||||
q += 132;
|
||||
}
|
||||
|
||||
memcpy(q, ji.scan + off, chunk);
|
||||
q += chunk;
|
||||
|
||||
size_t plen = (size_t)(q - rtp);
|
||||
pkt[0] = '$';
|
||||
pkt[1] = s->ch_v;
|
||||
pkt[2] = plen >> 8;
|
||||
pkt[3] = plen & 0xFF;
|
||||
|
||||
if (!send_all(s->fd, pkt, 4 + plen)) return false;
|
||||
off += chunk;
|
||||
|
||||
if (s->asb && !audio_pump(s)) return false; /* keep audio flowing during a big frame */
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void rtsp_session_task(void *arg)
|
||||
{
|
||||
int fd = (int)(intptr_t)arg;
|
||||
rtsp_sess_t s = {0};
|
||||
s.fd = fd;
|
||||
s.ssrc_v = esp_random();
|
||||
s.ssrc_a = esp_random();
|
||||
s.seq_v = (uint16_t)esp_random();
|
||||
s.seq_a = (uint16_t)esp_random();
|
||||
s.ts_a = esp_random();
|
||||
s.session_id = esp_random();
|
||||
cam_rtsp_make_nonce(s.nonce);
|
||||
|
||||
char *rx = malloc(RTSP_RX_SIZE + 1);
|
||||
uint8_t *pkt = malloc(RTP_PKT_SIZE);
|
||||
s.apkt = malloc(AUDIO_PKT_SIZE);
|
||||
uint8_t *jpg = NULL;
|
||||
size_t jcap = 0, rx_len = 0;
|
||||
|
||||
if (rx && pkt && s.apkt) {
|
||||
int one = 1;
|
||||
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
|
||||
struct timeval rt = { .tv_sec = 0, .tv_usec = 10000 };
|
||||
struct timeval st = { .tv_sec = 3, .tv_usec = 0 };
|
||||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &rt, sizeof(rt));
|
||||
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &st, sizeof(st));
|
||||
|
||||
TickType_t last_rx = xTaskGetTickCount();
|
||||
|
||||
while (1) {
|
||||
if (s.playing) {
|
||||
if (s.viewer) {
|
||||
size_t n = cam_feed_wait(&jpg, &jcap, &s.last_seq, 0);
|
||||
if (n && !rtp_send_jpeg(&s, jpg, n, pkt)) break; /* client gone or too slow */
|
||||
}
|
||||
if (s.asb && !audio_pump(&s)) break;
|
||||
}
|
||||
|
||||
int r = recv(fd, rx + rx_len, RTSP_RX_SIZE - rx_len, 0);
|
||||
if (r > 0) {
|
||||
rx_len += r;
|
||||
last_rx = xTaskGetTickCount();
|
||||
if (!rtsp_process_rx(&s, rx, &rx_len)) break;
|
||||
} else if (r == 0) {
|
||||
break; /* client closed */
|
||||
} else if (errno != EAGAIN && errno != EWOULDBLOCK) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!s.playing && (xTaskGetTickCount() - last_rx) > pdMS_TO_TICKS(60000)) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (s.viewer) cam_feed_viewer_remove();
|
||||
if (s.asb) audio_unsubscribe(s.asb);
|
||||
free(jpg);
|
||||
free(rx);
|
||||
free(pkt);
|
||||
free(s.apkt);
|
||||
close(fd);
|
||||
__atomic_fetch_sub(&s_rtsp_sessions, 1, __ATOMIC_SEQ_CST);
|
||||
ESP_LOGI(TAG, "RTSP session closed");
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
static void rtsp_server_task(void *arg)
|
||||
{
|
||||
int ls = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
|
||||
if (ls < 0) {
|
||||
ESP_LOGE(TAG, "RTSP: socket failed");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
int one = 1;
|
||||
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
|
||||
struct sockaddr_in addr = {0};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
addr.sin_port = htons(RTSP_PORT);
|
||||
|
||||
if (bind(ls, (struct sockaddr *)&addr, sizeof(addr)) < 0 || listen(ls, 2) < 0) {
|
||||
ESP_LOGE(TAG, "RTSP: bind/listen failed");
|
||||
close(ls);
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
ESP_LOGI(TAG, "RTSP server listening on port %d (rtsp://<ip>:%d/mjpeg/1)", RTSP_PORT, RTSP_PORT);
|
||||
|
||||
while (1) {
|
||||
struct sockaddr_in ca;
|
||||
socklen_t cl = sizeof(ca);
|
||||
int fd = accept(ls, (struct sockaddr *)&ca, &cl);
|
||||
if (fd < 0) {
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (s_rtsp_sessions >= RTSP_MAX_SESSIONS) {
|
||||
static const char busy[] = "RTSP/1.0 503 Service Unavailable\r\n\r\n";
|
||||
send(fd, busy, sizeof(busy) - 1, 0);
|
||||
close(fd);
|
||||
continue;
|
||||
}
|
||||
|
||||
__atomic_fetch_add(&s_rtsp_sessions, 1, __ATOMIC_SEQ_CST);
|
||||
ESP_LOGI(TAG, "RTSP client %s", inet_ntoa(ca.sin_addr));
|
||||
if (xTaskCreate(rtsp_session_task, "rtsp_sess", 8192, (void *)(intptr_t)fd, 5, NULL) != pdPASS) {
|
||||
__atomic_fetch_sub(&s_rtsp_sessions, 1, __ATOMIC_SEQ_CST);
|
||||
close(fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t rtsp_server_start(void)
|
||||
{
|
||||
if (!s_jpg_mutex) return ESP_ERR_INVALID_STATE; /* cam_feed_start() first */
|
||||
return (xTaskCreate(rtsp_server_task, "rtsp_srv", 4096, NULL, 5, NULL) == pdPASS)
|
||||
? ESP_OK : ESP_ERR_NO_MEM;
|
||||
}
|
||||
Reference in New Issue
Block a user