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:
2026-10-08 14:12:48 +03:30
parent 00278119b6
commit 72a2d714ab
13 changed files with 1398 additions and 175 deletions
+2 -2
View File
@@ -1,3 +1,3 @@
idf_component_register(SRCS "main.c" "esp32_s3_cam_ovxxxx.c" "camera.c" "audio.c" "wifi.c"
idf_component_register(SRCS "main.c" "esp32_s3_cam_ovxxxx.c" "camera.c" "audio.c" "wifi.c" "cam_stream.c" "cam_auth.c"
PRIV_INCLUDE_DIRS .
REQUIRES nvs_flash esp32-camera esp_io_expander custom_io_expander_ch32v003 esp_jpeg)
REQUIRES nvs_flash esp32-camera esp_io_expander custom_io_expander_ch32v003 esp_jpeg esp_http_server esp_timer lwip)
+59 -5
View File
@@ -4,9 +4,18 @@
#include "driver/i2s_std.h"
#include "esp_codec_dev.h"
#include "esp_codec_dev_defaults.h"
#include "audio.h"
#include "cam_stream.h"
#include "board.h"
#define I2S_MCLK GPIO_NUM_10
#define I2S_BCLK GPIO_NUM_11
#define I2S_WS GPIO_NUM_12
#define I2S_DOUT GPIO_NUM_14 // ESP -> ES8311 DSDIN
#define I2S_DIN GPIO_NUM_13 // ES7210 SDOUT -> ESP
#define SR 16000
#define MIC_BOOST 4 // software gain, raise if still quiet
static StreamBufferHandle_t s_play_sb; // mono 16-bit PCM from the browser
static esp_codec_dev_handle_t spk_dev, mic_dev;
@@ -18,22 +27,51 @@ static i2s_chan_handle_t rx_chan = NULL;
static StreamBufferHandle_t s_mic_sb;
static volatile bool s_mic_on = false;
#define MIC_BOOST 4
// void mic_task(void *arg)
// {
// static int16_t st[512]; // 256 stereo frames
// static int16_t mono[256];
// while (1) {
// if (esp_codec_dev_read(mic_dev, st, sizeof(st)) != ESP_CODEC_DEV_OK) {
// vTaskDelay(pdMS_TO_TICKS(10));
// continue;
// }
// if (!s_mic_on) continue; // nobody listening, just drain
// long eL = 0, eR = 0;
// for (int i = 0; i < 256; i++) { eL += abs(st[2*i]); eR += abs(st[2*i+1]); }
// int useRight = eR > eL;
// for (int i = 0; i < 256; i++) {
// int v = (useRight ? st[2*i+1] : st[2*i]) * MIC_BOOST;
// if (v > 32767) v = 32767;
// if (v < -32768) v = -32768;
// mono[i] = (int16_t)v;
// }
// xStreamBufferSend(s_mic_sb, mono, sizeof(mono), 0); // drops if full
// }
// }
void mic_task(void *arg)
{
static int16_t st[512]; // 256 stereo frames
static int16_t mono[256];
long aL = 0, aR = 0;
int useRight = 0;
while (1) {
if (esp_codec_dev_read(mic_dev, st, sizeof(st)) != ESP_CODEC_DEV_OK) {
vTaskDelay(pdMS_TO_TICKS(10));
continue;
}
if (!s_mic_on) continue; // nobody listening, just drain
if (!s_mic_on && !cam_audio_wanted()) continue; // nobody listening
long eL = 0, eR = 0;
for (int i = 0; i < 256; i++) { eL += abs(st[2*i]); eR += abs(st[2*i+1]); }
int useRight = eR > eL;
aL += (eL - aL) / 16; // smoothed level per channel
aR += (eR - aR) / 16;
if (!useRight && aR > 2 * aL) useRight = 1; // switch only on a clear difference
else if (useRight && aL > 2 * aR) useRight = 0;
for (int i = 0; i < 256; i++) {
int v = (useRight ? st[2*i+1] : st[2*i]) * MIC_BOOST;
@@ -41,7 +79,10 @@ void mic_task(void *arg)
if (v < -32768) v = -32768;
mono[i] = (int16_t)v;
}
xStreamBufferSend(s_mic_sb, mono, sizeof(mono), 0); // drops if full
if (s_mic_on && xStreamBufferSpacesAvailable(s_mic_sb) >= sizeof(mono))
xStreamBufferSend(s_mic_sb, mono, sizeof(mono), 0);
cam_audio_push(mono, 256); // RTSP sessions
}
}
@@ -58,6 +99,12 @@ static void play_task(void *arg)
esp_codec_dev_write(spk_dev, st, n * 4);
}
}
void rtsp_speaker_sink(const int16_t *pcm, size_t samples)
{
size_t bytes = samples * sizeof(int16_t);
if (xStreamBufferSpacesAvailable(s_play_sb) >= bytes)
xStreamBufferSend(s_play_sb, pcm, bytes, 0); // full: drop, keeps delay bounded
}
esp_err_t audio_init(i2c_master_bus_handle_t bus)
{
@@ -147,6 +194,8 @@ static const uint8_t WAV_HDR[44] = {
static esp_err_t mic_handler(httpd_req_t *req)
{
static int16_t buf[256];
if (!cam_http_check(req)) return ESP_OK;
cors(req);
httpd_resp_set_type(req, "audio/wav");
xStreamBufferReset(s_mic_sb);
@@ -169,6 +218,9 @@ static esp_err_t mic_handler(httpd_req_t *req)
static esp_err_t spk_handler(httpd_req_t *req)
{
static uint8_t body[4096];
if (!cam_http_check(req)) return ESP_FAIL;;
cors(req);
size_t total = req->content_len;
if (total == 0 || total > sizeof(body)) {
@@ -193,6 +245,8 @@ static esp_err_t spk_handler(httpd_req_t *req)
static esp_err_t vol_handler(httpd_req_t *req)
{
char q[32], val[8];
if (!cam_http_check(req)) return ESP_OK;
cors(req);
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
httpd_query_key_value(q, "v", val, sizeof(val)) == ESP_OK) {
-10
View File
@@ -1,10 +0,0 @@
#include "esp_http_server.h"
#define I2S_MCLK GPIO_NUM_10
#define I2S_BCLK GPIO_NUM_11
#define I2S_WS GPIO_NUM_12
#define I2S_DOUT GPIO_NUM_14 // ESP -> ES8311 DSDIN
#define I2S_DIN GPIO_NUM_13 // ES7210 SDOUT -> ESP
#define SR 16000
#define MIC_BOOST 4 // software gain, raise if still quiet
+3 -1
View File
@@ -7,6 +7,7 @@
#include <esp_log.h>
#include <esp_system.h>
#include "esp_http_server.h"
#include "cam_auth.h"
// support IDF 5.x
#ifndef portTICK_RATE_MS
@@ -26,4 +27,5 @@ void start_wifi_and_server(void);
void start_audio_server(void);
void start_camera_server(void);
void wifi_start_provisioning_if_needed(void);
bool wifi_wait_connected(uint32_t timeout_ms);
bool wifi_wait_connected(uint32_t timeout_ms);
void rtsp_speaker_sink(const int16_t *pcm, size_t samples);
+296
View File
@@ -0,0 +1,296 @@
/*
* cam_auth.c
* - tiny self-contained MD5 (no mbedTLS dependency, works on every ESP-IDF version)
* - RTSP Digest authentication (RFC 2069 style, no qop: what ffmpeg, VLC and go2rtc speak)
* - HTTP check: "Authorization: Basic" header or "?key=" query parameter
*/
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <strings.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_random.h"
#include "cam_auth.h"
static const char *TAG = "AUTH";
static bool s_enabled = false;
static char s_user[48];
static char s_pass[64];
static char s_ha1[33]; /* md5(user:realm:pass), computed once */
/* ================================================================== */
/* MD5 (RFC 1321) */
/* ================================================================== */
typedef struct {
uint32_t a, b, c, d;
uint64_t bytes;
uint8_t buf[64];
} md5_ctx;
static const uint32_t MD5_K[64] = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
};
static const uint8_t MD5_S[64] = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
};
#define ROL32(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
static void md5_block(md5_ctx *c, const uint8_t *p)
{
uint32_t M[16];
for (int i = 0; i < 16; i++)
M[i] = (uint32_t)p[4 * i] | ((uint32_t)p[4 * i + 1] << 8) |
((uint32_t)p[4 * i + 2] << 16) | ((uint32_t)p[4 * i + 3] << 24);
uint32_t A = c->a, B = c->b, C = c->c, D = c->d;
for (int i = 0; i < 64; i++) {
uint32_t F;
int g;
if (i < 16) { F = (B & C) | (~B & D); g = i; }
else if (i < 32) { F = (D & B) | (~D & C); g = (5 * i + 1) & 15; }
else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) & 15; }
else { F = C ^ (B | ~D); g = (7 * i) & 15; }
F = F + A + MD5_K[i] + M[g];
A = D;
D = C;
C = B;
B = B + ROL32(F, MD5_S[i]);
}
c->a += A; c->b += B; c->c += C; c->d += D;
}
static void md5_init(md5_ctx *c)
{
c->a = 0x67452301; c->b = 0xefcdab89; c->c = 0x98badcfe; c->d = 0x10325476;
c->bytes = 0;
}
static void md5_update(md5_ctx *c, const void *data, size_t n)
{
const uint8_t *p = data;
size_t have = (size_t)(c->bytes & 63);
c->bytes += n;
if (have) {
size_t take = 64 - have;
if (take > n) take = n;
memcpy(c->buf + have, p, take);
p += take;
n -= take;
if (have + take == 64) md5_block(c, c->buf);
else return;
}
while (n >= 64) { md5_block(c, p); p += 64; n -= 64; }
if (n) memcpy(c->buf, p, n);
}
static void md5_final(md5_ctx *c, uint8_t out[16])
{
uint64_t bits = c->bytes * 8;
static const uint8_t pad[64] = { 0x80 };
size_t have = (size_t)(c->bytes & 63);
size_t padlen = (have < 56) ? (56 - have) : (120 - have);
md5_update(c, pad, padlen);
uint8_t len[8];
for (int i = 0; i < 8; i++) len[i] = (uint8_t)(bits >> (8 * i));
md5_update(c, len, 8);
uint32_t v[4] = { c->a, c->b, c->c, c->d };
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++) out[4 * i + j] = (uint8_t)(v[i] >> (8 * j));
}
/* md5 of a string, as 32 lowercase hex characters + NUL */
static void md5_hex(const char *s, char out[33])
{
md5_ctx c;
uint8_t d[16];
md5_init(&c);
md5_update(&c, s, strlen(s));
md5_final(&c, d);
for (int i = 0; i < 16; i++) sprintf(out + 2 * i, "%02x", d[i]);
}
/* ================================================================== */
/* Helpers */
/* ================================================================== */
static bool ct_eq(const char *a, const char *b) /* constant-time string compare */
{
size_t la = strlen(a), lb = strlen(b);
unsigned d = (unsigned)(la ^ lb);
size_t n = la < lb ? la : lb;
for (size_t i = 0; i < n; i++) d |= (unsigned char)a[i] ^ (unsigned char)b[i];
return d == 0;
}
static int b64_val(char c)
{
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
static size_t b64_decode(const char *in, uint8_t *out, size_t outmax)
{
size_t n = 0;
uint32_t acc = 0;
int bits = 0;
for (; *in && *in != '='; in++) {
int v = b64_val(*in);
if (v < 0) return 0;
acc = (acc << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
if (n >= outmax) return 0;
out[n++] = (uint8_t)(acc >> bits);
}
}
return n;
}
/* ================================================================== */
/* Public API */
/* ================================================================== */
void cam_auth_init(const char *user, const char *pass)
{
s_enabled = (user && *user);
if (!s_enabled) {
ESP_LOGW(TAG, "Authentication DISABLED");
return;
}
snprintf(s_user, sizeof(s_user), "%s", user);
snprintf(s_pass, sizeof(s_pass), "%s", pass ? pass : "");
char tmp[160];
snprintf(tmp, sizeof(tmp), "%s:%s:%s", s_user, CAM_AUTH_REALM, s_pass);
md5_hex(tmp, s_ha1);
ESP_LOGI(TAG, "Authentication enabled for user \"%s\"", s_user);
}
bool cam_auth_enabled(void)
{
return s_enabled;
}
/* ---------------- HTTP ---------------- */
bool cam_http_check(httpd_req_t *req)
{
if (!s_enabled) return true;
bool ok = false;
/* 1) Authorization: Basic base64(user:pass) (Home Assistant, NVRs, browsers' login box) */
size_t hl = httpd_req_get_hdr_value_len(req, "Authorization");
if (hl > 6 && hl < 200) {
char h[200];
if (httpd_req_get_hdr_value_str(req, "Authorization", h, sizeof(h)) == ESP_OK &&
strncasecmp(h, "Basic ", 6) == 0) {
uint8_t dec[130];
size_t dl = b64_decode(h + 6, dec, sizeof(dec) - 1);
if (dl > 0) {
dec[dl] = 0;
char want[120];
snprintf(want, sizeof(want), "%s:%s", s_user, s_pass);
ok = ct_eq((const char *)dec, want);
}
}
}
/* 2) ?key=<password> (web pages: works for <img>, fetch() without CORS preflight) */
if (!ok) {
char q[160], v[80];
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
httpd_query_key_value(q, "key", v, sizeof(v)) == ESP_OK) {
ok = ct_eq(v, s_pass);
}
}
if (!ok) {
ESP_LOGW(TAG, "HTTP request refused: %s", req->uri);
vTaskDelay(pdMS_TO_TICKS(300)); /* slows down password guessing */
httpd_resp_set_status(req, "401 Unauthorized");
httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"" CAM_AUTH_REALM "\"");
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
httpd_resp_set_type(req, "text/plain");
httpd_resp_send(req, "Unauthorized", HTTPD_RESP_USE_STRLEN);
}
return ok;
}
/* ---------------- RTSP Digest ---------------- */
void cam_rtsp_make_nonce(char out[33])
{
for (int i = 0; i < 4; i++) sprintf(out + 8 * i, "%08x", (unsigned)esp_random());
out[32] = 0;
}
/* value of key="..." (or key=value) inside a Digest parameter list */
static bool dig_field(const char *s, const char *key, char *out, size_t n)
{
size_t kl = strlen(key);
for (const char *p = s; *p; p++) {
if ((p == s || p[-1] == ' ' || p[-1] == ',') &&
strncasecmp(p, key, kl) == 0 && p[kl] == '=') {
p += kl + 1;
size_t i = 0;
if (*p == '"') {
p++;
while (*p && *p != '"' && i < n - 1) out[i++] = *p++;
} else {
while (*p && *p != ',' && *p != ' ' && *p != '\r' && *p != '\n' && i < n - 1) out[i++] = *p++;
}
out[i] = 0;
return true;
}
}
return false;
}
bool cam_rtsp_digest_ok(const char *method, const char *authz, const char *nonce)
{
if (!s_enabled) return true;
if (!authz || strncasecmp(authz, "Digest ", 7) != 0) return false;
const char *params = authz + 7;
char user[48], realm[48], n[48], uri[200], resp[48];
if (!dig_field(params, "username", user, sizeof(user)) ||
!dig_field(params, "realm", realm, sizeof(realm)) ||
!dig_field(params, "nonce", n, sizeof(n)) ||
!dig_field(params, "uri", uri, sizeof(uri)) ||
!dig_field(params, "response", resp, sizeof(resp))) return false;
if (!ct_eq(user, s_user) || !ct_eq(realm, CAM_AUTH_REALM) || !ct_eq(n, nonce)) return false;
char tmp[320], ha2[33], expect[33];
snprintf(tmp, sizeof(tmp), "%s:%s", method, uri); /* HA2 uses the real method */
md5_hex(tmp, ha2);
snprintf(tmp, sizeof(tmp), "%s:%s:%s", s_ha1, nonce, ha2);
md5_hex(tmp, expect);
return ct_eq(resp, expect);
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <stdbool.h>
#include "esp_http_server.h"
#define CAM_AUTH_REALM "ESP32-Cam"
/* Set the single account used by every service (RTSP, /pic, /stream, /mic, /spk, /vol).
* user NULL or "" disables authentication completely.
* Use letters and digits only in the password, it also travels inside URLs. */
void cam_auth_init(const char *user, const char *pass);
bool cam_auth_enabled(void);
/* ---------- HTTP ----------
* Accepts either "Authorization: Basic ..." or "?key=<password>" in the URL.
* On failure it sends 401 itself and returns false, so a handler does:
* if (!cam_http_check(req)) return ESP_OK; */
bool cam_http_check(httpd_req_t *req);
/* ---------- RTSP (Digest, MD5, no qop) ---------- */
void cam_rtsp_make_nonce(char out[33]);
bool cam_rtsp_digest_ok(const char *method, const char *authz_header_value, const char *nonce);
+919
View File
@@ -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;
}
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
/* ---------- Shared JPEG feed ----------
* One task captures + converts to JPEG, only while at least one viewer exists. */
esp_err_t cam_feed_start(void); /* call after esp_camera_init() */
void cam_feed_viewer_add(uint32_t *seq); /* register a viewer, *seq = "last seen" marker */
void cam_feed_viewer_remove(void);
/* Copies the newest frame (newer than *seq) into *buf (realloc'd, size in *cap).
* Returns JPEG length, or 0 on timeout. Caller frees *buf when done. */
size_t cam_feed_wait(uint8_t **buf, size_t *cap, uint32_t *seq, uint32_t timeout_ms);
/* ---------- Audio feed for RTSP ----------
* The mic task calls cam_audio_push() with every block of mono 16 kHz / 16-bit PCM,
* but only needs to do the work while cam_audio_wanted() is true. */
bool cam_audio_wanted(void);
void cam_audio_push(const int16_t *pcm, size_t samples);
/* ---------- Back channel (client -> speaker) ----------
* Register a function that plays mono 16 kHz / 16-bit PCM on the speaker.
* Call before rtsp_server_start(). Without it the back channel is not offered. */
typedef void (*cam_speaker_sink_t)(const int16_t *pcm16k_mono, size_t samples);
void rtsp_set_speaker_sink(cam_speaker_sink_t fn);
/* ---------- RTSP server (port 554, TCP-interleaved) ----------
* Video: RTP/JPEG (MJPEG). Audio: G.711 / L16, see RTSP_AUDIO_FORMAT in cam_stream.c */
esp_err_t rtsp_server_start(void);
#ifdef __cplusplus
}
#endif
+48 -70
View File
@@ -3,6 +3,7 @@
#include "esp_camera.h"
#include "camera_pinout.h"
#include "esp32_s3_cam_ovxxxx.h"
#include "cam_stream.h"
#include "board.h"
#if defined CONFIG_CAMERA_AF_SUPPORT
@@ -106,82 +107,59 @@ static void maybe_init_autofocus(void)
#endif
#endif
esp_err_t capture_handler(httpd_req_t *req) {
camera_fb_t *fb = esp_camera_fb_get();
if (!fb) {
ESP_LOGE(TAG, "Camera capture failed");
esp_err_t capture_handler(httpd_req_t *req)
{
uint8_t *jpg = NULL;
size_t cap = 0;
uint32_t seq;
if (!cam_http_check(req)) return ESP_OK;
cam_feed_viewer_add(&seq);
size_t n = cam_feed_wait(&jpg, &cap, &seq, 3000);
cam_feed_viewer_remove();
if (!n) {
free(jpg);
httpd_resp_send_500(req);
return ESP_FAIL;
}
uint8_t *jpeg_buf = NULL;
size_t jpeg_len = 0;
bool jpeg_converted = frame2jpg(fb, 50, &jpeg_buf, &jpeg_len);
esp_camera_fb_return(fb);
if (!jpeg_converted) {
ESP_LOGE(TAG, "JPEG compression failed");
httpd_resp_send_500(req);
return ESP_FAIL;
}
httpd_resp_set_type(req, "image/jpeg");
httpd_resp_send(req, (const char *)jpeg_buf, jpeg_len);
free(jpeg_buf);
return ESP_OK;
esp_err_t r = httpd_resp_send(req, (const char *)jpg, n);
free(jpg);
return r;
}
esp_err_t stream_handler(httpd_req_t *req) {
camera_fb_t * fb = NULL;
esp_err_t res = ESP_OK;
size_t _jpg_buf_len = 0;
uint8_t * _jpg_buf = NULL;
char * part_buf[64];
esp_err_t stream_handler(httpd_req_t *req)
{
uint8_t *jpg = NULL;
size_t cap = 0;
uint32_t seq;
int idle = 0;
char part[64];
res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
if (res != ESP_OK) {
return res;
}
while(true) {
fb = esp_camera_fb_get();
if (!fb) {
ESP_LOGE(TAG, "Camera capture failed");
res = ESP_FAIL;
break;
}
bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
esp_camera_fb_return(fb);
if (!jpeg_converted) {
ESP_LOGE(TAG, "JPEG compression failed");
res = ESP_FAIL;
break;
}
if (res == ESP_OK) {
res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
}
if (res == ESP_OK) {
size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
}
if (res == ESP_OK) {
res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
}
free(_jpg_buf);
_jpg_buf = NULL;
if (res != ESP_OK) {
break;
}
vTaskDelay(1);
if (!cam_http_check(req)) return ESP_OK;
esp_err_t res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
if (res != ESP_OK) return res;
cam_feed_viewer_add(&seq);
while (1) {
size_t n = cam_feed_wait(&jpg, &cap, &seq, 2000);
if (!n) {
if (++idle >= 5) { res = ESP_FAIL; break; } // no frames for 10 s: give up
continue;
}
idle = 0;
res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
if (res == ESP_OK) {
size_t hl = snprintf(part, sizeof(part), _STREAM_PART, (unsigned)n);
res = httpd_resp_send_chunk(req, part, hl);
}
if (res == ESP_OK) res = httpd_resp_send_chunk(req, (const char *)jpg, n);
if (res != ESP_OK) break; // browser left
}
cam_feed_viewer_remove();
free(jpg);
return res;
}
}
-1
View File
@@ -8,7 +8,6 @@ static const char *TAG = "BSP_BOARD";
static esp_io_expander_handle_t io_expander = NULL;
static i2c_master_bus_handle_t i2c_bus_handle = NULL;
// تعریف قطعی پین‌های I2C طبق شماتیک برای جلوگیری از خطای ماکروها
#define ACTUAL_I2C_SDA 8
#define ACTUAL_I2C_SCL 7
-4
View File
@@ -6,24 +6,20 @@
#include "esp_camera.h"
#include "custom_io_expander_ch32v003.h"
// --- پین‌های I2C ---
#define BSP_I2C_NUM 0
#define BSP_I2C_SCL (GPIO_NUM_7)
#define BSP_I2C_SDA (GPIO_NUM_8)
// --- آدرس اکسپندر ---
#define BSP_IO_EXPANDER_I2C_ADDRESS_CH32V003 (CUSTOM_IO_EXPANDER_I2C_CH32V003_ADDRESS)
#ifdef __cplusplus
extern "C" {
#endif
// --- توابع I2C ---
esp_err_t bsp_i2c_init(void);
esp_err_t bsp_i2c_deinit(void);
i2c_master_bus_handle_t bsp_i2c_get_handle(void);
// --- توابع IO Expander ---
esp_err_t bsp_io_expander_init(void);
esp_io_expander_handle_t bsp_get_io_expander_handle(void);
uint16_t bsp_get_io_expander_adc(void);
+8 -2
View File
@@ -1,6 +1,10 @@
#include "driver/i2c_master.h"
#include "board.h"
#include "esp32_s3_cam_ovxxxx.h"
#include "cam_stream.h"
#define CAM_USER "admin"
#define CAM_PASS "ChangeThis123"
void app_main(void)
{
@@ -15,17 +19,19 @@ void app_main(void)
#endif
ESP_ERROR_CHECK(audio_init(bsp_i2c_get_handle()));
ESP_ERROR_CHECK(cam_feed_start());
wifi_start_provisioning_if_needed(); // station mode, or the captive portal if no credentials
while (!wifi_wait_connected(5000)) {
ESP_LOGI("Main", "Waiting for Wi-Fi (or setup portal)...");
}
cam_auth_init(CAM_USER, CAM_PASS);
start_camera_server(); // port 80: /pic, /stream
xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL);
start_audio_server(); // ports 81 and 82: /mic, /spk, /vol
rtsp_set_speaker_sink(rtsp_speaker_sink);
rtsp_server_start();
while (1) vTaskDelay(pdMS_TO_TICKS(1000));
#endif
}
+1 -80
View File
@@ -1,82 +1,3 @@
// #include "sdkconfig.h"
// #include <esp_log.h>
// #include <esp_system.h>
// #include "esp_http_server.h"
// #include <nvs_flash.h>
// #include <sys/param.h>
// #include <string.h>
// #include "freertos/FreeRTOS.h"
// #include "freertos/task.h"
// #include "esp_wifi.h"
// #include "nvs_flash.h"
// #include "esp_netif.h"
// #include "esp_http_server.h"
// #include "lwip/sockets.h"
// #include <netinet/tcp.h>
// #include "board.h"
// static const char *TAG = "WIFI:";
// static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
// if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
// esp_wifi_connect();
// } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
// ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying...");
// esp_wifi_connect();
// } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
// ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
// ESP_LOGI(TAG, "SUCCESS! Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
// }
// }
// void start_wifi_and_server(void) {
// esp_err_t ret = nvs_flash_init();
// if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
// nvs_flash_erase();
// nvs_flash_init();
// }
// esp_netif_init();
// esp_event_loop_create_default();
// esp_netif_create_default_wifi_sta();
// wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
// esp_wifi_init(&cfg);
// wifi_config_t wifi_config = {
// .sta = {
// .ssid = "viratak-lte",
// .password = "mydlinkviratak",
// },
// };
// esp_wifi_set_mode(WIFI_MODE_STA);
// esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
// esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL);
// esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL);
// esp_wifi_start();
// esp_wifi_set_ps(WIFI_PS_NONE);
// esp_wifi_connect();
// httpd_config_t config = HTTPD_DEFAULT_CONFIG();
// httpd_handle_t server = NULL;
// if (httpd_start(&server, &config) == ESP_OK) {
// httpd_uri_t uri_capture = {
// .uri = "/pic",
// .method = HTTP_GET,
// .handler = capture_handler,
// .user_ctx = NULL
// };
// httpd_register_uri_handler(server, &uri_capture);
// httpd_uri_t uri_stream = {
// .uri = "/stream",
// .method = HTTP_GET,
// .handler = stream_handler,
// .user_ctx = NULL
// };
// httpd_register_uri_handler(server, &uri_stream);
// }
// }
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
@@ -301,7 +222,7 @@ static void start_portal_webserver(void)
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 80;
config.stack_size = 8192;
config.lru_purge_enable = true; /* phones open many short connections */
config.lru_purge_enable = true;
if (httpd_start(&s_portal_server, &config) != ESP_OK) {
ESP_LOGE(TAG, "Portal HTTP server failed to start");