rtsp_handlers.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. #include "rtsp_handlers.h"
  2. #include <arpa/inet.h>
  3. #include <errno.h>
  4. #include <inttypes.h>
  5. #include <netinet/in.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <strings.h>
  9. #include <sys/socket.h>
  10. #include <unistd.h>
  11. #include "esp_log.h"
  12. #include "esp_mac.h"
  13. #include "esp_netif.h"
  14. #include "freertos/FreeRTOS.h"
  15. #include "freertos/task.h"
  16. #include "sodium.h"
  17. #include "audio_output.h"
  18. #include "audio_receiver.h"
  19. #include "audio_stream.h"
  20. #ifdef CONFIG_BT_A2DP_ENABLE
  21. #include "dac.h"
  22. #endif
  23. #include "dac_njw1195.h"
  24. #include "hap.h"
  25. #include "ntp_clock.h"
  26. #include "ptp_clock.h"
  27. #include "plist.h"
  28. #include "rtsp_fairplay.h"
  29. #include "rtsp_rsa.h"
  30. #include "settings.h"
  31. #include "socket_utils.h"
  32. #include "tlv8.h"
  33. #include "rtsp_events.h"
  34. #include "dacp_client.h"
  35. static const char *TAG = "rtsp_handlers";
  36. // ============================================================================
  37. // Codec Registry
  38. // ============================================================================
  39. // To add a new codec, add an entry to codec_registry[] below.
  40. static void configure_codec(audio_format_t *fmt, const char *name, int64_t sr,
  41. int64_t spf) {
  42. strcpy(fmt->codec, name);
  43. fmt->sample_rate = (int)sr;
  44. fmt->channels = 2;
  45. fmt->bits_per_sample = 16;
  46. fmt->frame_size = (int)spf;
  47. fmt->max_samples_per_frame = (uint32_t)spf;
  48. fmt->sample_size = 16;
  49. fmt->num_channels = 2;
  50. fmt->sample_rate_config = (uint32_t)sr;
  51. }
  52. // Codec registry - add new codecs here
  53. // ct values: 2=ALAC, 4=AAC, 8=AAC-ELD, 64=OPUS (based on AirPlay 2 protocol)
  54. static const rtsp_codec_t codec_registry[] = {
  55. {"ALAC", 2}, {"AAC", 4}, {"AAC-ELD", 8}, {"OPUS", 64}, {NULL, 0}};
  56. bool rtsp_codec_configure(int64_t type_id, audio_format_t *fmt,
  57. int64_t sample_rate, int64_t samples_per_frame) {
  58. for (const rtsp_codec_t *codec = codec_registry; codec->name; codec++) {
  59. if (codec->type_id == type_id) {
  60. configure_codec(fmt, codec->name, sample_rate, samples_per_frame);
  61. ESP_LOGI(TAG, "Configured codec: %s (ct=%lld, sr=%lld, spf=%lld)",
  62. codec->name, (long long)type_id, (long long)sample_rate,
  63. (long long)samples_per_frame);
  64. return true;
  65. }
  66. }
  67. // Default to ALAC if unknown codec type
  68. ESP_LOGW(TAG, "Unknown codec type %lld, defaulting to ALAC",
  69. (long long)type_id);
  70. configure_codec(fmt, "ALAC", sample_rate, samples_per_frame);
  71. return false;
  72. }
  73. // Event port task state
  74. #define EVENT_STACK_SIZE 3072
  75. static int event_client_socket = -1;
  76. static int event_listen_socket = -1;
  77. static TaskHandle_t event_task_handle = NULL;
  78. static volatile bool event_task_should_stop = false;
  79. void rtsp_get_device_id(char *device_id, size_t len) {
  80. uint8_t mac[6];
  81. esp_read_mac(mac, ESP_MAC_WIFI_STA);
  82. snprintf(device_id, len, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1],
  83. mac[2], mac[3], mac[4], mac[5]);
  84. }
  85. static int rtsp_create_udp_socket(uint16_t *port) {
  86. uint16_t bound_port = 0;
  87. int sock = socket_utils_bind_udp(0, 0, 0, &bound_port);
  88. if (sock < 0) {
  89. return -1;
  90. }
  91. if (port) {
  92. *port = bound_port;
  93. }
  94. return sock;
  95. }
  96. static int rtsp_create_event_socket(uint16_t *port) {
  97. uint16_t bound_port = 0;
  98. int sock = socket_utils_bind_tcp_listener(0, 1, false, &bound_port);
  99. if (sock < 0) {
  100. return -1;
  101. }
  102. if (port) {
  103. *port = bound_port;
  104. }
  105. return sock;
  106. }
  107. static void ensure_stream_ports(rtsp_conn_t *conn, bool buffered) {
  108. int temp_socket = 0;
  109. if (!buffered && conn->data_port == 0) {
  110. temp_socket = rtsp_create_udp_socket(&conn->data_port);
  111. if (temp_socket > 0) {
  112. close(temp_socket);
  113. }
  114. }
  115. if (conn->control_port == 0) {
  116. temp_socket = rtsp_create_udp_socket(&conn->control_port);
  117. if (temp_socket > 0) {
  118. close(temp_socket);
  119. }
  120. }
  121. if (conn->timing_port == 0) {
  122. // Allocate a timing port for RTSP response (required by protocol)
  123. // Note: For AirPlay 1, we send timing requests TO the client, not receive
  124. // them
  125. temp_socket = rtsp_create_udp_socket(&conn->timing_port);
  126. if (temp_socket > 0) {
  127. close(temp_socket);
  128. }
  129. }
  130. }
  131. static bool start_ntp_timing_or_fail(int socket, rtsp_conn_t *conn,
  132. const rtsp_request_t *req) {
  133. if (conn->client_timing_port == 0 || conn->client_ip == 0) {
  134. return true;
  135. }
  136. esp_err_t err =
  137. ntp_clock_start_client(conn->client_ip, conn->client_timing_port);
  138. if (err != ESP_OK) {
  139. ESP_LOGE(TAG, "Failed to start NTP timing client: %s",
  140. esp_err_to_name(err));
  141. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  142. NULL, 0);
  143. return false;
  144. }
  145. return true;
  146. }
  147. static bool start_audio_receiver_or_fail(int socket, rtsp_conn_t *conn,
  148. const rtsp_request_t *req,
  149. int64_t stream_type) {
  150. audio_receiver_set_stream_type((audio_stream_type_t)stream_type);
  151. esp_err_t err = audio_receiver_start_stream(
  152. conn->data_port, conn->control_port, conn->buffered_port);
  153. if (err != ESP_OK) {
  154. ESP_LOGE(TAG, "Failed to start audio receiver: %s", esp_err_to_name(err));
  155. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  156. NULL, 0);
  157. return false;
  158. }
  159. return true;
  160. }
  161. // Event port task - handles AirPlay 2 session persistence
  162. static void event_port_task(void *pvParameters) {
  163. int listen_socket = (int)(intptr_t)pvParameters;
  164. event_listen_socket = listen_socket;
  165. while (!event_task_should_stop && listen_socket >= 0) {
  166. fd_set read_fds;
  167. FD_ZERO(&read_fds);
  168. FD_SET(listen_socket, &read_fds);
  169. struct timeval tv = {.tv_sec = 1, .tv_usec = 0};
  170. int ret = select(listen_socket + 1, &read_fds, NULL, NULL, &tv);
  171. if (event_task_should_stop) {
  172. break;
  173. }
  174. if (ret < 0) {
  175. if (errno != EINTR && !event_task_should_stop) {
  176. ESP_LOGE(TAG, "Event port select error: %d", errno);
  177. }
  178. break;
  179. }
  180. if (ret == 0) {
  181. continue;
  182. }
  183. // Check stop flag after select unblocks (shutdown() makes socket readable)
  184. if (event_task_should_stop) {
  185. break;
  186. }
  187. if (FD_ISSET(listen_socket, &read_fds)) {
  188. struct sockaddr_in client_addr;
  189. socklen_t addr_len = sizeof(client_addr);
  190. int client =
  191. accept(listen_socket, (struct sockaddr *)&client_addr, &addr_len);
  192. if (client < 0) {
  193. if (!event_task_should_stop) {
  194. ESP_LOGE(TAG, "Event port accept error: %d", errno);
  195. }
  196. break; // Don't continue - socket is likely invalid
  197. }
  198. if (event_client_socket >= 0) {
  199. close(event_client_socket);
  200. }
  201. event_client_socket = client;
  202. ESP_LOGI(TAG, "Event client connected");
  203. rtsp_events_emit(RTSP_EVENT_CLIENT_CONNECTED, NULL);
  204. // Monitor connection for disconnection
  205. while (event_client_socket >= 0 && !event_task_should_stop) {
  206. fd_set cfds;
  207. FD_ZERO(&cfds);
  208. FD_SET(event_client_socket, &cfds);
  209. struct timeval ctv = {.tv_sec = 1, .tv_usec = 0};
  210. ret = select(event_client_socket + 1, &cfds, NULL, NULL, &ctv);
  211. if (ret < 0) {
  212. break;
  213. }
  214. // Check stop flag after select unblocks
  215. if (event_task_should_stop) {
  216. break;
  217. }
  218. if (ret > 0 && FD_ISSET(event_client_socket, &cfds)) {
  219. char buf[16];
  220. ssize_t n = recv(event_client_socket, buf, sizeof(buf), MSG_PEEK);
  221. if (n <= 0) {
  222. close(event_client_socket);
  223. event_client_socket = -1;
  224. break;
  225. }
  226. }
  227. }
  228. }
  229. }
  230. if (event_client_socket >= 0) {
  231. close(event_client_socket);
  232. event_client_socket = -1;
  233. }
  234. event_listen_socket = -1;
  235. event_task_handle = NULL;
  236. vTaskDelete(NULL);
  237. }
  238. static bool event_port_wait_for_task_stopped(int timeout_ticks) {
  239. while (event_task_handle != NULL && timeout_ticks-- > 0) {
  240. vTaskDelay(pdMS_TO_TICKS(50));
  241. }
  242. return event_task_handle == NULL;
  243. }
  244. esp_err_t rtsp_start_event_port_task(int listen_socket) {
  245. if (event_task_handle != NULL) {
  246. rtsp_stop_event_port_task();
  247. if (!event_port_wait_for_task_stopped(20)) {
  248. ESP_LOGE(TAG, "Previous event port task did not stop");
  249. return ESP_ERR_INVALID_STATE;
  250. }
  251. }
  252. event_task_should_stop = false;
  253. event_listen_socket = -1;
  254. event_task_handle = NULL;
  255. BaseType_t ret =
  256. xTaskCreate(event_port_task, "event_port", EVENT_STACK_SIZE,
  257. (void *)(intptr_t)listen_socket, 5, &event_task_handle);
  258. if (ret != pdPASS) {
  259. event_task_handle = NULL;
  260. ESP_LOGE(TAG, "Failed to create event port task");
  261. return ESP_FAIL;
  262. }
  263. return ESP_OK;
  264. }
  265. int rtsp_event_port_listen_socket(void) {
  266. return event_listen_socket;
  267. }
  268. void rtsp_stop_event_port_task(void) {
  269. if (event_task_handle == NULL) {
  270. return;
  271. }
  272. // Signal task to stop
  273. event_task_should_stop = true;
  274. // Shutdown sockets to unblock select()
  275. if (event_client_socket >= 0) {
  276. shutdown(event_client_socket, SHUT_RDWR);
  277. }
  278. if (event_listen_socket >= 0) {
  279. shutdown(event_listen_socket, SHUT_RDWR);
  280. }
  281. if (!event_port_wait_for_task_stopped(20)) {
  282. ESP_LOGW(TAG, "Event port task did not exit within timeout");
  283. }
  284. }
  285. // Forward declarations of handlers
  286. static void handle_options(int socket, rtsp_conn_t *conn,
  287. const rtsp_request_t *req, const uint8_t *raw,
  288. size_t raw_len);
  289. static void handle_get(int socket, rtsp_conn_t *conn, const rtsp_request_t *req,
  290. const uint8_t *raw, size_t raw_len);
  291. static void handle_post(int socket, rtsp_conn_t *conn,
  292. const rtsp_request_t *req, const uint8_t *raw,
  293. size_t raw_len);
  294. static void handle_announce(int socket, rtsp_conn_t *conn,
  295. const rtsp_request_t *req, const uint8_t *raw,
  296. size_t raw_len);
  297. static void handle_setup(int socket, rtsp_conn_t *conn,
  298. const rtsp_request_t *req, const uint8_t *raw,
  299. size_t raw_len);
  300. static void handle_record(int socket, rtsp_conn_t *conn,
  301. const rtsp_request_t *req, const uint8_t *raw,
  302. size_t raw_len);
  303. static void handle_set_parameter(int socket, rtsp_conn_t *conn,
  304. const rtsp_request_t *req, const uint8_t *raw,
  305. size_t raw_len);
  306. static void handle_get_parameter(int socket, rtsp_conn_t *conn,
  307. const rtsp_request_t *req, const uint8_t *raw,
  308. size_t raw_len);
  309. static void handle_pause(int socket, rtsp_conn_t *conn,
  310. const rtsp_request_t *req, const uint8_t *raw,
  311. size_t raw_len);
  312. static void handle_flush(int socket, rtsp_conn_t *conn,
  313. const rtsp_request_t *req, const uint8_t *raw,
  314. size_t raw_len);
  315. static void handle_flushbuffered(int socket, rtsp_conn_t *conn,
  316. const rtsp_request_t *req, const uint8_t *raw,
  317. size_t raw_len);
  318. static void handle_teardown(int socket, rtsp_conn_t *conn,
  319. const rtsp_request_t *req, const uint8_t *raw,
  320. size_t raw_len);
  321. static void handle_setrateanchortime(int socket, rtsp_conn_t *conn,
  322. const rtsp_request_t *req,
  323. const uint8_t *raw, size_t raw_len);
  324. static void handle_setpeers(int socket, rtsp_conn_t *conn,
  325. const rtsp_request_t *req, const uint8_t *raw,
  326. size_t raw_len);
  327. // Dispatch table
  328. static const rtsp_method_handler_t method_handlers[] = {
  329. {"OPTIONS", handle_options},
  330. {"GET", handle_get},
  331. {"POST", handle_post},
  332. {"ANNOUNCE", handle_announce},
  333. {"SETUP", handle_setup},
  334. {"RECORD", handle_record},
  335. {"SET_PARAMETER", handle_set_parameter},
  336. {"GET_PARAMETER", handle_get_parameter},
  337. {"PAUSE", handle_pause},
  338. {"FLUSH", handle_flush},
  339. {"FLUSHBUFFERED", handle_flushbuffered},
  340. {"TEARDOWN", handle_teardown},
  341. {"SETRATEANCHORTIME", handle_setrateanchortime},
  342. {"SETPEERS", handle_setpeers},
  343. {"SETPEERSX", handle_setpeers},
  344. {NULL, NULL}};
  345. // Parse a named header value from raw RTSP request data (case-insensitive).
  346. // Returns pointer to a static buffer with the trimmed value, or NULL.
  347. static const char *parse_raw_header(const uint8_t *raw, size_t raw_len,
  348. const char *name) {
  349. static char value_buf[64];
  350. if (!raw || !name) {
  351. return NULL;
  352. }
  353. const uint8_t *header_end = rtsp_find_header_end(raw, raw_len);
  354. if (!header_end) {
  355. return NULL;
  356. }
  357. const char *line = (const char *)raw;
  358. const char *end = (const char *)header_end;
  359. size_t name_len = strlen(name);
  360. while (line < end) {
  361. const char *line_end = line;
  362. while (line_end < end && *line_end != '\r' && *line_end != '\n') {
  363. line_end++;
  364. }
  365. if ((size_t)(line_end - line) >= name_len &&
  366. strncasecmp(line, name, name_len) == 0) {
  367. const char *hdr = line + name_len;
  368. // Skip optional whitespace
  369. while (hdr < line_end && (*hdr == ' ' || *hdr == '\t')) {
  370. hdr++;
  371. }
  372. size_t i = 0;
  373. while (i < sizeof(value_buf) - 1 && hdr < line_end) {
  374. value_buf[i] = *hdr;
  375. hdr++;
  376. i++;
  377. }
  378. value_buf[i] = '\0';
  379. return value_buf;
  380. }
  381. line = line_end;
  382. while (line < end && (*line == '\r' || *line == '\n')) {
  383. line++;
  384. }
  385. }
  386. return NULL;
  387. }
  388. static bool request_uses_rtsp(const rtsp_request_t *req) {
  389. return req && strncasecmp(req->protocol, "RTSP/", 5) == 0;
  390. }
  391. int rtsp_dispatch(int socket, rtsp_conn_t *conn, const uint8_t *raw_request,
  392. size_t raw_len) {
  393. rtsp_request_t req;
  394. if (rtsp_request_parse(raw_request, raw_len, &req) < 0) {
  395. ESP_LOGW(TAG, "Failed to parse RTSP request");
  396. return -1;
  397. }
  398. // Extract DACP headers if present (AirPlay 1 only — modern iOS AirPlay 2
  399. // does not send these; it uses MRP for remote control instead).
  400. // parse_raw_header uses a static buffer — copy before calling again.
  401. if (conn->dacp_id[0] == '\0') {
  402. const char *val = parse_raw_header(raw_request, raw_len, "DACP-ID:");
  403. if (val) {
  404. strlcpy(conn->dacp_id, val, sizeof(conn->dacp_id));
  405. ESP_LOGI(TAG, "DACP-ID: %s (from %s)", conn->dacp_id, req.method);
  406. }
  407. }
  408. if (conn->active_remote[0] == '\0') {
  409. const char *val = parse_raw_header(raw_request, raw_len, "Active-Remote:");
  410. if (val) {
  411. strlcpy(conn->active_remote, val, sizeof(conn->active_remote));
  412. ESP_LOGI(TAG, "Active-Remote: %s (from %s)", conn->active_remote,
  413. req.method);
  414. }
  415. }
  416. // Update DACP client session when both identifiers are available
  417. if (conn->dacp_id[0] != '\0' && conn->active_remote[0] != '\0') {
  418. dacp_set_session(conn->dacp_id, conn->active_remote, conn->client_ip);
  419. }
  420. // Find handler in dispatch table
  421. for (const rtsp_method_handler_t *h = method_handlers; h->method; h++) {
  422. if (strcasecmp(req.method, h->method) == 0) {
  423. h->handler(socket, conn, &req, raw_request, raw_len);
  424. return 0;
  425. }
  426. }
  427. ESP_LOGW(TAG, "Unknown method: %s", req.method);
  428. if (request_uses_rtsp(&req)) {
  429. rtsp_send_response(socket, conn, 501, "Not Implemented", req.cseq,
  430. "Content-Type: text/plain\r\n", "Not Implemented", 15);
  431. } else {
  432. rtsp_send_http_response(socket, conn, 501, "Not Implemented", "text/plain",
  433. "Not Implemented", 15);
  434. }
  435. return 0;
  436. }
  437. // ============================================================================
  438. // Handler implementations
  439. // ============================================================================
  440. static void handle_options(int socket, rtsp_conn_t *conn,
  441. const rtsp_request_t *req, const uint8_t *raw,
  442. size_t raw_len) {
  443. const char *public_methods =
  444. "Public: ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, FLUSHBUFFERED, TEARDOWN, "
  445. "OPTIONS, POST, GET, SET_PARAMETER, GET_PARAMETER, SETPEERS, "
  446. "SETRATEANCHORTIME\r\n";
  447. // AirPlay v1: handle Apple-Challenge if present. Triggered by request
  448. // shape, so safe unconditionally — iOS in AirPlay 2 mode does not send
  449. // this header.
  450. const char *challenge = parse_raw_header(raw, raw_len, "Apple-Challenge:");
  451. if (challenge) {
  452. conn->protocol_version = 1;
  453. esp_netif_ip_info_t ip_info;
  454. esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
  455. if (netif && esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
  456. uint8_t mac[6];
  457. esp_read_mac(mac, ESP_MAC_WIFI_STA);
  458. char response_b64[512];
  459. if (rsa_apple_challenge_response(challenge, ip_info.ip.addr, mac,
  460. response_b64,
  461. sizeof(response_b64)) == 0) {
  462. char headers[768];
  463. snprintf(headers, sizeof(headers), "%sApple-Response: %s\r\n",
  464. public_methods, response_b64);
  465. rtsp_send_response(socket, conn, 200, "OK", req->cseq, headers, NULL,
  466. 0);
  467. return;
  468. }
  469. }
  470. ESP_LOGW(TAG, "Failed to build Apple-Challenge response");
  471. }
  472. rtsp_send_response(socket, conn, 200, "OK", req->cseq, public_methods, NULL,
  473. 0);
  474. }
  475. static void handle_get(int socket, rtsp_conn_t *conn, const rtsp_request_t *req,
  476. const uint8_t *raw, size_t raw_len) {
  477. (void)raw;
  478. (void)raw_len;
  479. if (strcmp(req->path, "/info") == 0) {
  480. // Build info response
  481. char device_id[18];
  482. char device_name[65];
  483. rtsp_get_device_id(device_id, sizeof(device_id));
  484. settings_get_device_name(device_name, sizeof(device_name));
  485. const uint8_t *pk = hap_get_public_key();
  486. uint64_t features =
  487. ((uint64_t)AIRPLAY_FEATURES_HI << 32) | AIRPLAY_FEATURES_LO;
  488. #ifdef CONFIG_AIRPLAY_FORCE_V1
  489. int64_t protocol_version = 1;
  490. #else
  491. int64_t protocol_version = 2;
  492. #endif
  493. if (request_uses_rtsp(req)) {
  494. static uint8_t body[1024];
  495. size_t body_len =
  496. bplist_build_info_response(body, sizeof(body), device_id, device_name,
  497. pk, 32, features, protocol_version);
  498. if (body_len == 0) {
  499. ESP_LOGE(TAG, "Failed to build binary /info response");
  500. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  501. NULL, 0);
  502. return;
  503. }
  504. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  505. "Content-Type: application/x-apple-binary-plist\r\n",
  506. (const char *)body, body_len);
  507. return;
  508. }
  509. static char body[4096];
  510. plist_t p;
  511. plist_init(&p, body, sizeof(body));
  512. plist_begin(&p);
  513. plist_dict_begin(&p);
  514. plist_dict_string(&p, "deviceid", device_id);
  515. plist_dict_uint(&p, "features", features);
  516. plist_dict_string(&p, "model", "AudioAccessory5,1");
  517. plist_dict_string(&p, "protovers", "1.1");
  518. plist_dict_string(&p, "srcvers", "377.40.00");
  519. plist_dict_int(&p, "vv", protocol_version);
  520. plist_dict_int(&p, "statusFlags", 4);
  521. plist_dict_data(&p, "pk", pk, 32);
  522. plist_dict_string(&p, "pi", "00000000-0000-0000-0000-000000000000");
  523. plist_dict_string(&p, "name", device_name);
  524. // Audio formats array
  525. plist_dict_array_begin(&p, "audioFormats");
  526. plist_dict_begin(&p);
  527. plist_dict_int(&p, "type", 96);
  528. plist_dict_int(&p, "audioInputFormats", 0x01000000);
  529. plist_dict_int(&p, "audioOutputFormats", 0x01000000);
  530. plist_dict_end(&p);
  531. plist_array_end(&p);
  532. // Audio latencies array
  533. // Both type 96 (realtime/UDP) and type 103 (buffered/TCP) use PTP-based
  534. // anchor timing with internal hardware-latency compensation in
  535. // compute_early_us(). Report 0 so the sender does NOT also adjust its
  536. // anchor — otherwise the hardware pipeline delay is subtracted twice and
  537. // the ESP plays ahead of other speakers. shairport-sync likewise
  538. // reports no audioLatencies at all.
  539. plist_dict_array_begin(&p, "audioLatencies");
  540. plist_dict_begin(&p);
  541. plist_dict_int(&p, "type", 96);
  542. plist_dict_int(&p, "audioType", 0x64);
  543. plist_dict_int(&p, "inputLatencyMicros", 0);
  544. plist_dict_int(&p, "outputLatencyMicros", 0);
  545. plist_dict_end(&p);
  546. plist_dict_begin(&p);
  547. plist_dict_int(&p, "type", 103);
  548. plist_dict_int(&p, "audioType", 0x64);
  549. plist_dict_int(&p, "inputLatencyMicros", 0);
  550. plist_dict_int(&p, "outputLatencyMicros", 0);
  551. plist_dict_end(&p);
  552. plist_array_end(&p);
  553. plist_dict_end(&p);
  554. size_t body_len = plist_end(&p);
  555. rtsp_send_http_response(socket, conn, 200, "OK", "text/x-apple-plist+xml",
  556. body, body_len);
  557. } else {
  558. ESP_LOGW(TAG, "Unknown GET path: %s", req->path);
  559. if (request_uses_rtsp(req)) {
  560. rtsp_send_response(socket, conn, 404, "Not Found", req->cseq,
  561. "Content-Type: text/plain\r\n", "Not Found", 9);
  562. } else {
  563. rtsp_send_http_response(socket, conn, 404, "Not Found", "text/plain",
  564. "Not Found", 9);
  565. }
  566. }
  567. }
  568. static void handle_post(int socket, rtsp_conn_t *conn,
  569. const rtsp_request_t *req, const uint8_t *raw,
  570. size_t raw_len) {
  571. (void)raw;
  572. (void)raw_len;
  573. const uint8_t *body = req->body;
  574. size_t body_len = req->body_len;
  575. if (strstr(req->path, "/pair-setup")) {
  576. conn->protocol_version = 2;
  577. // Create session if needed
  578. if (!conn->hap_session) {
  579. conn->hap_session = hap_session_create();
  580. if (!conn->hap_session) {
  581. ESP_LOGE(TAG, "Failed to create HAP session");
  582. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  583. NULL, 0);
  584. return;
  585. }
  586. }
  587. uint8_t *response = malloc(2048);
  588. if (!response) {
  589. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  590. NULL, 0);
  591. return;
  592. }
  593. size_t response_len = 0;
  594. esp_err_t err = ESP_FAIL;
  595. if (body && body_len > 0) {
  596. size_t state_len;
  597. const uint8_t *state =
  598. tlv8_find(body, body_len, TLV_TYPE_STATE, &state_len);
  599. if (state && state_len == 1) {
  600. switch (state[0]) {
  601. default:
  602. break;
  603. case 1:
  604. err = hap_pair_setup_m1(conn->hap_session, body, body_len, response,
  605. 2048, &response_len);
  606. break;
  607. case 3:
  608. err = hap_pair_setup_m3(conn->hap_session, body, body_len, response,
  609. 2048, &response_len);
  610. break;
  611. case 5:
  612. err = hap_pair_setup_m5(conn->hap_session, body, body_len, response,
  613. 2048, &response_len);
  614. break;
  615. }
  616. }
  617. }
  618. if (err == ESP_OK && response_len > 0) {
  619. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  620. "Content-Type: application/octet-stream\r\n",
  621. (const char *)response, response_len);
  622. if (conn->hap_session && conn->hap_session->pair_setup_state == 4 &&
  623. conn->hap_session->session_established) {
  624. conn->encrypted_mode = true;
  625. }
  626. } else {
  627. ESP_LOGE(TAG, "Pair-setup failed: err=%d", err);
  628. static const uint8_t error_response[] = {0x06, 0x01, 0x02,
  629. 0x07, 0x01, 0x02};
  630. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  631. "Content-Type: application/octet-stream\r\n",
  632. (const char *)error_response, sizeof(error_response));
  633. }
  634. free(response);
  635. } else if (strstr(req->path, "/pair-verify")) {
  636. conn->protocol_version = 2;
  637. if (!conn->hap_session) {
  638. conn->hap_session = hap_session_create();
  639. if (!conn->hap_session) {
  640. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  641. NULL, 0);
  642. return;
  643. }
  644. }
  645. uint8_t *response = malloc(1024);
  646. if (!response) {
  647. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  648. NULL, 0);
  649. return;
  650. }
  651. size_t response_len = 0;
  652. esp_err_t err = ESP_FAIL;
  653. if (body && body_len > 0) {
  654. size_t state_len;
  655. const uint8_t *state =
  656. tlv8_find(body, body_len, TLV_TYPE_STATE, &state_len);
  657. if (state && state_len == 1) {
  658. if (state[0] == 0x01) {
  659. err = hap_pair_verify_m1(conn->hap_session, body, body_len, response,
  660. 1024, &response_len);
  661. } else if (state[0] == 0x03) {
  662. err = hap_pair_verify_m3(conn->hap_session, body, body_len, response,
  663. 1024, &response_len);
  664. // TLV8 pair-verify M3 establishes RTSP channel encryption
  665. if (err == ESP_OK &&
  666. conn->hap_session->pair_verify_state == PAIR_VERIFY_STATE_M4) {
  667. conn->encrypted_mode = true;
  668. ESP_LOGI(TAG, "RTSP encryption enabled (TLV8 pair-verify)");
  669. }
  670. }
  671. } else {
  672. // Raw format - used for audio encryption keys, not RTSP encryption
  673. if (conn->hap_session->pair_verify_state == 0) {
  674. err = hap_pair_verify_m1_raw(conn->hap_session, body, body_len,
  675. response, 1024, &response_len);
  676. } else if (conn->hap_session->pair_verify_state ==
  677. PAIR_VERIFY_STATE_M2) {
  678. err = hap_pair_verify_m3_raw(conn->hap_session, body, body_len,
  679. response, 1024, &response_len);
  680. if (err == ESP_OK) {
  681. ESP_LOGI(TAG, "Raw pair-verify complete (RTSP unencrypted)");
  682. }
  683. }
  684. }
  685. }
  686. if (err == ESP_OK && response_len > 0) {
  687. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  688. "Content-Type: application/octet-stream\r\n",
  689. (const char *)response, response_len);
  690. } else {
  691. ESP_LOGE(TAG, "Pair-verify failed, err=%d", err);
  692. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  693. "Content-Type: application/octet-stream\r\n",
  694. "\x06\x01\x04\x07\x01\x02", 6);
  695. }
  696. free(response);
  697. } else if (strstr(req->path, "/fp-setup")) {
  698. uint8_t *fp_response = NULL;
  699. size_t fp_response_len = 0;
  700. if (body && body_len >= 16) {
  701. if (rtsp_fairplay_handle(body, body_len, &fp_response,
  702. &fp_response_len) == 0) {
  703. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  704. "Content-Type: application/octet-stream\r\n",
  705. (const char *)fp_response, fp_response_len);
  706. free(fp_response);
  707. return;
  708. }
  709. }
  710. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  711. "Content-Type: application/octet-stream\r\n", "\x00", 1);
  712. } else if (strstr(req->path, "/command")) {
  713. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  714. int64_t cmd_type = 0;
  715. if (bplist_find_int(body, body_len, "type", &cmd_type)) {
  716. ESP_LOGI(TAG, "/command type=%lld", (long long)cmd_type);
  717. }
  718. }
  719. rtsp_send_ok(socket, conn, req->cseq);
  720. } else if (strstr(req->path, "/feedback")) {
  721. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  722. int64_t value;
  723. if (bplist_find_int(body, body_len, "networkTimeSecs", &value)) {
  724. ESP_LOGI(TAG, "/feedback has networkTimeSecs=%lld", (long long)value);
  725. }
  726. }
  727. // For buffered audio streams (type 103), send a proper feedback response
  728. // with stream status. This acts as a keepalive to prevent iPhone from
  729. // sending TEARDOWN during extended pause.
  730. if (conn->stream_type == 103) {
  731. uint8_t response[128];
  732. size_t response_len = bplist_build_feedback_response(
  733. response, sizeof(response), conn->stream_type, 44100.0);
  734. if (response_len > 0) {
  735. ESP_LOGD(
  736. TAG,
  737. "/feedback responding with stream status (type=%lld, sr=44100)",
  738. (long long)conn->stream_type);
  739. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  740. "Content-Type: application/x-apple-binary-plist\r\n",
  741. (const char *)response, response_len);
  742. } else {
  743. // Fallback to simple OK if response build fails
  744. rtsp_send_ok(socket, conn, req->cseq);
  745. }
  746. } else {
  747. // For non-buffered streams, simple OK is fine
  748. rtsp_send_ok(socket, conn, req->cseq);
  749. }
  750. } else {
  751. rtsp_send_ok(socket, conn, req->cseq);
  752. }
  753. }
  754. static void parse_sdp(rtsp_conn_t *conn, const char *sdp, size_t len) {
  755. (void)len;
  756. audio_format_t format = {0};
  757. audio_encrypt_t encrypt = {0};
  758. encrypt.type = AUDIO_ENCRYPT_NONE;
  759. format.sample_rate = 44100;
  760. format.channels = 2;
  761. format.bits_per_sample = 16;
  762. format.frame_size = 352;
  763. strcpy(format.codec, "AppleLossless");
  764. const char *rtpmap = strstr(sdp, "a=rtpmap:");
  765. if (rtpmap) {
  766. sscanf(rtpmap, "a=rtpmap:%*d %31s", format.codec);
  767. char *slash = strchr(format.codec, '/');
  768. if (slash) {
  769. *slash = '\0';
  770. int sr = 0;
  771. int ch = 0;
  772. // NOLINTNEXTLINE(bugprone-unchecked-string-to-number-conversion)
  773. if (sscanf(slash + 1, "%d/%d", &sr, &ch) >= 1) {
  774. if (sr > 0) {
  775. format.sample_rate = sr;
  776. }
  777. if (ch > 0) {
  778. format.channels = ch;
  779. }
  780. }
  781. }
  782. }
  783. const char *fmtp = strstr(sdp, "a=fmtp:");
  784. if (fmtp) {
  785. unsigned int frame_len, bit_depth, pb, mb, kb, num_ch, max_run, max_frame,
  786. avg_rate, rate;
  787. unsigned int compat;
  788. // NOLINTNEXTLINE(bugprone-unchecked-string-to-number-conversion)
  789. int matched = sscanf(fmtp, "a=fmtp:%*d %u %u %u %u %u %u %u %u %u %u %u",
  790. &frame_len, &compat, &bit_depth, &pb, &mb, &kb,
  791. &num_ch, &max_run, &max_frame, &avg_rate, &rate);
  792. if (matched >= 7) {
  793. format.max_samples_per_frame = frame_len;
  794. format.sample_size = bit_depth;
  795. format.rice_history_mult = pb;
  796. format.rice_initial_history = mb;
  797. format.rice_limit = kb;
  798. format.num_channels = num_ch;
  799. format.channels = (int)num_ch;
  800. format.bits_per_sample = (int)bit_depth;
  801. if (matched >= 8) {
  802. format.max_run = max_run;
  803. }
  804. if (matched >= 9) {
  805. format.max_coded_frame_size = max_frame;
  806. }
  807. if (matched >= 10) {
  808. format.avg_bit_rate = avg_rate;
  809. }
  810. if (matched >= 11) {
  811. format.sample_rate_config = rate;
  812. format.sample_rate = (int)rate;
  813. }
  814. }
  815. }
  816. if ((strstr(format.codec, "AAC") || strstr(format.codec, "aac") ||
  817. strstr(format.codec, "mpeg4-generic") ||
  818. strstr(format.codec, "MPEG4-GENERIC")) &&
  819. format.max_samples_per_frame == 0) {
  820. format.frame_size = 1024;
  821. format.max_samples_per_frame = 1024;
  822. }
  823. // AirPlay v1: parse RSA-encrypted AES key and IV from SDP. Triggered by
  824. // SDP shape so safe unconditionally — AirPlay 2 uses HAP-derived keys
  825. // and never embeds rsaaeskey in ANNOUNCE.
  826. const char *rsaaeskey = strcasestr(sdp, "rsaaeskey:");
  827. const char *aesiv_str = strcasestr(sdp, "aesiv:");
  828. if (rsaaeskey && aesiv_str) {
  829. conn->protocol_version = 1;
  830. // Extract base64 key (may span multiple lines, concatenate until next
  831. // field or end of SDP). In practice it's a single long base64 line.
  832. rsaaeskey += strlen("rsaaeskey:");
  833. while (*rsaaeskey == ' ' || *rsaaeskey == '\t') {
  834. rsaaeskey++;
  835. }
  836. // Collect key characters (skip whitespace/newlines within base64)
  837. char key_b64[512];
  838. size_t ki = 0;
  839. for (const char *p = rsaaeskey; *p && ki < sizeof(key_b64) - 1; p++) {
  840. if (*p == '\r' || *p == '\n') {
  841. // Check if next non-space char is start of a new SDP field (e.g. "a=")
  842. const char *q = p + 1;
  843. while (*q == '\r' || *q == '\n' || *q == ' ') {
  844. q++;
  845. }
  846. if (*q == 'a' && *(q + 1) == '=') {
  847. break;
  848. }
  849. } else if (*p != ' ' && *p != '\t') {
  850. key_b64[ki++] = *p;
  851. }
  852. }
  853. key_b64[ki] = '\0';
  854. // Extract IV
  855. aesiv_str += strlen("aesiv:");
  856. while (*aesiv_str == ' ' || *aesiv_str == '\t') {
  857. aesiv_str++;
  858. }
  859. char iv_b64[64];
  860. size_t ii = 0;
  861. for (const char *p = aesiv_str;
  862. *p && *p != '\r' && *p != '\n' && ii < sizeof(iv_b64) - 1; p++) {
  863. iv_b64[ii++] = *p;
  864. }
  865. iv_b64[ii] = '\0';
  866. // Decrypt AES key using RSA
  867. uint8_t aes_key[32];
  868. size_t aes_key_len = 0;
  869. if (rsa_decrypt_aes_key(key_b64, aes_key, sizeof(aes_key), &aes_key_len) ==
  870. 0 &&
  871. aes_key_len >= 16) {
  872. encrypt.type = AUDIO_ENCRYPT_AES_CBC;
  873. memcpy(encrypt.key, aes_key, aes_key_len);
  874. encrypt.key_len = aes_key_len;
  875. // Decode IV
  876. size_t iv_len = 0;
  877. if (sodium_base642bin(encrypt.iv, sizeof(encrypt.iv), iv_b64,
  878. strlen(iv_b64), "\r\n \t", &iv_len, NULL,
  879. sodium_base64_VARIANT_ORIGINAL_NO_PADDING) != 0) {
  880. sodium_base642bin(encrypt.iv, sizeof(encrypt.iv), iv_b64,
  881. strlen(iv_b64), "\r\n \t", &iv_len, NULL,
  882. sodium_base64_VARIANT_ORIGINAL);
  883. }
  884. ESP_LOGI(TAG,
  885. "AirPlay v1: AES-CBC encryption configured (key=%zu iv=%zu)",
  886. aes_key_len, iv_len);
  887. }
  888. }
  889. // Update connection state
  890. strlcpy(conn->codec, format.codec, sizeof(conn->codec));
  891. conn->sample_rate = format.sample_rate;
  892. conn->channels = format.channels;
  893. conn->bits_per_sample = format.bits_per_sample;
  894. audio_receiver_set_format(&format);
  895. if (encrypt.type != AUDIO_ENCRYPT_NONE) {
  896. audio_receiver_set_encryption(&encrypt);
  897. }
  898. }
  899. static void handle_announce(int socket, rtsp_conn_t *conn,
  900. const rtsp_request_t *req, const uint8_t *raw,
  901. size_t raw_len) {
  902. (void)raw;
  903. (void)raw_len;
  904. if (req->body && req->body_len > 0) {
  905. parse_sdp(conn, (const char *)req->body, req->body_len);
  906. }
  907. rtsp_send_ok(socket, conn, req->cseq);
  908. }
  909. static void handle_setup(int socket, rtsp_conn_t *conn,
  910. const rtsp_request_t *req, const uint8_t *raw,
  911. size_t raw_len) {
  912. (void)raw_len;
  913. const uint8_t *body = req->body;
  914. size_t body_len = req->body_len;
  915. bool is_bplist =
  916. strstr(req->content_type, "application/x-apple-binary-plist") != NULL;
  917. // Check for streams array
  918. bool request_has_streams = false;
  919. size_t stream_count = 0;
  920. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  921. if (bplist_get_streams_count(body, body_len, &stream_count)) {
  922. request_has_streams = true;
  923. }
  924. }
  925. ESP_LOGI(TAG, "SETUP: has_streams=%d, stream_count=%zu", request_has_streams,
  926. stream_count);
  927. // AirPlay v1 stream SETUP is identified by a Transport header and no bplist
  928. // streams array. Classify it before opening AirPlay 2-only resources.
  929. bool is_v1_transport_setup =
  930. !request_has_streams &&
  931. parse_raw_header(raw, raw_len, "Transport:") != NULL;
  932. if (body && body_len > 0 && is_bplist && request_has_streams) {
  933. conn->protocol_version = 2;
  934. for (size_t i = 0; i < stream_count; i++) {
  935. int64_t stream_type = -1;
  936. size_t ekey_len = 0, eiv_len = 0, shk_len = 0;
  937. if (bplist_get_stream_info(body, body_len, i, &stream_type, &ekey_len,
  938. &eiv_len, &shk_len)) {
  939. if (i == 0) {
  940. conn->stream_type = stream_type;
  941. audio_receiver_set_stream_type((audio_stream_type_t)stream_type);
  942. }
  943. bplist_kv_info_t kv[16];
  944. size_t kv_count = 0;
  945. int64_t codec_type = -1;
  946. int64_t sample_rate = 44100;
  947. int64_t samples_per_frame = 352;
  948. if (bplist_get_stream_kv_info(body, body_len, i, kv, 16, &kv_count)) {
  949. for (size_t k = 0; k < kv_count; k++) {
  950. if (kv[k].value_type == BPLIST_VALUE_INT) {
  951. if (strcmp(kv[k].key, "ct") == 0) {
  952. codec_type = kv[k].int_value;
  953. } else if (strcmp(kv[k].key, "sr") == 0) {
  954. sample_rate = kv[k].int_value;
  955. } else if (strcmp(kv[k].key, "spf") == 0) {
  956. samples_per_frame = kv[k].int_value;
  957. } else if (strcmp(kv[k].key, "controlPort") == 0) {
  958. conn->client_control_port = (uint16_t)kv[k].int_value;
  959. }
  960. }
  961. }
  962. // Use codec registry to configure audio format
  963. audio_format_t format = {0};
  964. rtsp_codec_configure(codec_type, &format, sample_rate,
  965. samples_per_frame);
  966. audio_receiver_set_format(&format);
  967. }
  968. }
  969. }
  970. }
  971. // Process encryption keys
  972. if (body && body_len > 0) {
  973. uint8_t ekey_encrypted[64];
  974. size_t ekey_len = 0;
  975. uint8_t eiv[16];
  976. size_t eiv_len = 0;
  977. uint8_t shk[32];
  978. size_t shk_len = 0;
  979. int64_t crypto_stream_type = conn->stream_type > 0 ? conn->stream_type : 96;
  980. bool has_stream_crypto = bplist_find_stream_crypto(
  981. body, body_len, crypto_stream_type, ekey_encrypted,
  982. sizeof(ekey_encrypted), &ekey_len, eiv, sizeof(eiv), &eiv_len, shk,
  983. sizeof(shk), &shk_len);
  984. if (!has_stream_crypto || (ekey_len == 0 && shk_len == 0)) {
  985. bplist_find_data_deep(body, body_len, "ekey", ekey_encrypted,
  986. sizeof(ekey_encrypted), &ekey_len);
  987. bplist_find_data_deep(body, body_len, "eiv", eiv, sizeof(eiv), &eiv_len);
  988. bplist_find_data_deep(body, body_len, "shk", shk, sizeof(shk), &shk_len);
  989. }
  990. audio_encrypt_t audio_encrypt = {0};
  991. bool encryption_set = false;
  992. if (shk_len >= 16) {
  993. audio_encrypt.type = AUDIO_ENCRYPT_CHACHA20_POLY1305;
  994. memcpy(audio_encrypt.key, shk, shk_len > 32 ? 32 : shk_len);
  995. audio_encrypt.key_len = shk_len > 32 ? 32 : shk_len;
  996. if (eiv_len >= 16) {
  997. memcpy(audio_encrypt.iv, eiv, 16);
  998. }
  999. audio_receiver_set_encryption(&audio_encrypt);
  1000. encryption_set = true;
  1001. } else if (ekey_len > 16 && conn->hap_session &&
  1002. conn->hap_session->session_established) {
  1003. uint8_t nonce[12] = {0};
  1004. uint8_t decrypted_key[32];
  1005. unsigned long long decrypted_len;
  1006. if (crypto_aead_chacha20poly1305_ietf_decrypt(
  1007. decrypted_key, &decrypted_len, NULL, ekey_encrypted, ekey_len,
  1008. NULL, 0, nonce, conn->hap_session->shared_secret) == 0 &&
  1009. decrypted_len >= 16) {
  1010. audio_encrypt.type = AUDIO_ENCRYPT_CHACHA20_POLY1305;
  1011. memcpy(audio_encrypt.key, decrypted_key,
  1012. decrypted_len > 32 ? 32 : decrypted_len);
  1013. audio_encrypt.key_len = decrypted_len > 32 ? 32 : decrypted_len;
  1014. if (eiv_len >= 16) {
  1015. memcpy(audio_encrypt.iv, eiv, 16);
  1016. }
  1017. audio_receiver_set_encryption(&audio_encrypt);
  1018. encryption_set = true;
  1019. }
  1020. }
  1021. if (!encryption_set && conn->hap_session &&
  1022. conn->hap_session->session_established) {
  1023. audio_encrypt.type = AUDIO_ENCRYPT_CHACHA20_POLY1305;
  1024. if (hap_derive_audio_key(conn->hap_session, audio_encrypt.key,
  1025. sizeof(audio_encrypt.key)) == ESP_OK) {
  1026. audio_encrypt.key_len = 32;
  1027. if (eiv_len >= 16) {
  1028. memcpy(audio_encrypt.iv, eiv, 16);
  1029. }
  1030. audio_receiver_set_encryption(&audio_encrypt);
  1031. }
  1032. }
  1033. }
  1034. // Create event port if needed
  1035. if (!is_v1_transport_setup && conn->event_port == 0) {
  1036. conn->event_socket = rtsp_create_event_socket(&conn->event_port);
  1037. if (conn->event_socket >= 0) {
  1038. if (rtsp_start_event_port_task(conn->event_socket) == ESP_OK) {
  1039. ESP_LOGI(TAG, "SETUP: Created event port %u", conn->event_port);
  1040. } else {
  1041. close(conn->event_socket);
  1042. conn->event_socket = -1;
  1043. conn->event_port = 0;
  1044. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  1045. NULL, 0);
  1046. return;
  1047. }
  1048. }
  1049. }
  1050. // Handle initial SETUP vs stream SETUP
  1051. if (!request_has_streams) {
  1052. // AirPlay v1: SETUP has no bplist body — transport info is in the header.
  1053. // Detected by request shape (Transport: header present); AirPlay 2's
  1054. // initial SETUP has neither streams nor a Transport header.
  1055. if (is_v1_transport_setup) {
  1056. ESP_LOGI(TAG, "SETUP: AirPlay v1 stream setup");
  1057. conn->protocol_version = 1;
  1058. int64_t stream_type = 96; // RTP
  1059. conn->stream_type = stream_type;
  1060. // Parse client's control and timing ports from Transport header
  1061. rtsp_parse_transport((const char *)raw, &conn->client_control_port,
  1062. &conn->client_timing_port);
  1063. ESP_LOGI(TAG, "Client ports: control=%u timing=%u",
  1064. conn->client_control_port, conn->client_timing_port);
  1065. if (!start_ntp_timing_or_fail(socket, conn, req)) {
  1066. return;
  1067. }
  1068. ensure_stream_ports(conn, false);
  1069. char transport_response[256];
  1070. snprintf(transport_response, sizeof(transport_response),
  1071. "Transport: RTP/AVP/UDP;unicast;mode=record;"
  1072. "server_port=%d;control_port=%d;timing_port=%d\r\n"
  1073. "Session: 1\r\n",
  1074. conn->data_port, conn->control_port, conn->timing_port);
  1075. rtsp_send_response(socket, conn, 200, "OK", req->cseq, transport_response,
  1076. NULL, 0);
  1077. // Configure audio format — RAOP default is ALAC 44100/352
  1078. audio_format_t format = {0};
  1079. rtsp_codec_configure(2, &format, 44100, 352); // ct=2 is ALAC
  1080. audio_receiver_set_format(&format);
  1081. audio_receiver_set_stream_type((audio_stream_type_t)stream_type);
  1082. // Stop PTP (AirPlay 2 timing) to free socket slots for audio.
  1083. // Audio stream will be started by the subsequent RECORD command.
  1084. ptp_clock_stop();
  1085. conn->stream_active = true;
  1086. return;
  1087. }
  1088. ESP_LOGI(TAG, "SETUP: Initial connection setup (no streams)");
  1089. if (is_bplist) {
  1090. uint8_t plist_body[128];
  1091. size_t plist_len = bplist_build_initial_setup(
  1092. plist_body, sizeof(plist_body), conn->event_port);
  1093. if (plist_len == 0) {
  1094. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  1095. NULL, 0);
  1096. return;
  1097. }
  1098. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  1099. "Content-Type: application/x-apple-binary-plist\r\n",
  1100. (const char *)plist_body, plist_len);
  1101. } else {
  1102. rtsp_send_ok(socket, conn, req->cseq);
  1103. }
  1104. return;
  1105. }
  1106. // Stream SETUP
  1107. int64_t stream_type = conn->stream_type;
  1108. if (stream_type == 0) {
  1109. stream_type = 96;
  1110. }
  1111. ESP_LOGI(TAG, "SETUP: Stream setup, stream_type=%lld",
  1112. (long long)stream_type);
  1113. bool buffered = audio_stream_uses_buffer((audio_stream_type_t)stream_type);
  1114. if (buffered) {
  1115. esp_err_t err = audio_receiver_start_buffered(0);
  1116. if (err != ESP_OK) {
  1117. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  1118. NULL, 0);
  1119. return;
  1120. }
  1121. conn->buffered_port = audio_receiver_get_buffered_port();
  1122. }
  1123. ensure_stream_ports(conn, buffered);
  1124. uint16_t response_data_port =
  1125. buffered ? conn->buffered_port : conn->data_port;
  1126. if (!start_audio_receiver_or_fail(socket, conn, req, stream_type)) {
  1127. return;
  1128. }
  1129. if (is_bplist) {
  1130. uint8_t plist_body[256];
  1131. size_t plist_len = bplist_build_stream_setup(
  1132. plist_body, sizeof(plist_body), stream_type, response_data_port,
  1133. conn->control_port, AP2_AUDIO_BUFFER_SIZE);
  1134. if (plist_len == 0) {
  1135. audio_receiver_stop();
  1136. rtsp_send_response(socket, conn, 500, "Internal Error", req->cseq, NULL,
  1137. NULL, 0);
  1138. return;
  1139. }
  1140. ESP_LOGI(TAG, "SETUP response: type=%lld dataPort=%u controlPort=%u",
  1141. (long long)stream_type, response_data_port, conn->control_port);
  1142. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  1143. "Content-Type: application/x-apple-binary-plist\r\n",
  1144. (const char *)plist_body, plist_len);
  1145. } else {
  1146. // AirPlay 1: Parse client's ports from Transport header
  1147. rtsp_parse_transport((const char *)raw, &conn->client_control_port,
  1148. &conn->client_timing_port);
  1149. ESP_LOGI(TAG, "Client ports: control=%u timing=%u",
  1150. conn->client_control_port, conn->client_timing_port);
  1151. if (!start_ntp_timing_or_fail(socket, conn, req)) {
  1152. audio_receiver_stop();
  1153. return;
  1154. }
  1155. char transport_response[256];
  1156. snprintf(transport_response, sizeof(transport_response),
  1157. "Transport: RTP/AVP/UDP;unicast;mode=record;"
  1158. "server_port=%d;control_port=%d;timing_port=%d\r\n"
  1159. "Session: 1\r\n",
  1160. conn->data_port, conn->control_port, conn->timing_port);
  1161. rtsp_send_response(socket, conn, 200, "OK", req->cseq, transport_response,
  1162. NULL, 0);
  1163. }
  1164. // Enable NACK retransmission if we know the client's control port
  1165. if (conn->client_control_port > 0 && conn->client_ip != 0) {
  1166. audio_receiver_set_client_control(conn->client_ip,
  1167. conn->client_control_port);
  1168. }
  1169. #ifdef CONFIG_BT_A2DP_ENABLE
  1170. // Apply saved AirPlay volume before playback starts — the DAC may have
  1171. // been left at a different level by Bluetooth A2DP.
  1172. dac_set_volume(conn->volume_db);
  1173. #endif
  1174. audio_receiver_set_playing(true);
  1175. conn->stream_paused = false;
  1176. conn->stream_active = true;
  1177. }
  1178. static void handle_record(int socket, rtsp_conn_t *conn,
  1179. const rtsp_request_t *req, const uint8_t *raw,
  1180. size_t raw_len) {
  1181. (void)raw;
  1182. (void)raw_len;
  1183. ESP_LOGI(TAG, "RECORD received - starting playback, stream_paused was %d",
  1184. conn->stream_paused);
  1185. #ifdef CONFIG_BT_A2DP_ENABLE
  1186. // Ensure DAC is at the saved AirPlay volume before any audio plays —
  1187. // Bluetooth A2DP may have left it at a different level.
  1188. dac_set_volume(conn->volume_db);
  1189. #endif
  1190. if (conn->stream_paused) {
  1191. // Resuming from PAUSE: the stream listener is still running and the
  1192. // timing anchor has been preserved. Just re-enable playout; the
  1193. // pause-duration offset in audio_timing will re-align the timestamps.
  1194. ESP_LOGI(TAG, "RECORD: resuming from pause, skipping stream restart");
  1195. audio_receiver_set_playing(true);
  1196. } else {
  1197. // Fresh start or post-teardown reconnect: full stream restart.
  1198. if (!start_audio_receiver_or_fail(socket, conn, req, conn->stream_type)) {
  1199. return;
  1200. }
  1201. if (conn->client_control_port > 0 && conn->client_ip != 0) {
  1202. audio_receiver_set_client_control(conn->client_ip,
  1203. conn->client_control_port);
  1204. }
  1205. audio_receiver_set_playing(true);
  1206. }
  1207. conn->stream_paused = false;
  1208. rtsp_events_emit(RTSP_EVENT_PLAYING, NULL);
  1209. // AirPlay 1 RECORD is always type 96 (realtime/UDP) with NTP sync.
  1210. // Internal timing already compensates for hardware latency, so report 0.
  1211. char headers[128];
  1212. uint32_t latency_samples = 0;
  1213. snprintf(headers, sizeof(headers),
  1214. "Audio-Latency: %" PRIu32 "\r\n"
  1215. "Audio-Jack-Status: connected\r\n",
  1216. latency_samples);
  1217. rtsp_send_response(socket, conn, 200, "OK", req->cseq, headers, NULL, 0);
  1218. }
  1219. // ============================================================================
  1220. // Metadata and Progress Logging Helpers
  1221. // ============================================================================
  1222. /**
  1223. * Format time in seconds as mm:ss string
  1224. * @param seconds Time in seconds
  1225. * @param out Output buffer (at least 8 bytes for "999:59\0")
  1226. * @param out_size Size of output buffer
  1227. */
  1228. static void format_time_mmss(uint32_t seconds, char *out, size_t out_size) {
  1229. uint32_t mins = seconds / 60;
  1230. uint32_t secs = seconds % 60;
  1231. snprintf(out, out_size, "%" PRIu32 ":%02" PRIu32, mins, secs);
  1232. }
  1233. /**
  1234. * Parse DMAP-tagged data and extract metadata into struct
  1235. * DMAP format: 4-byte tag, 4-byte BE length, data
  1236. * Common tags:
  1237. * minm = item name (track title)
  1238. * asar = artist
  1239. * asal = album
  1240. * asgn = genre
  1241. * asai = album id (64-bit)
  1242. */
  1243. static void parse_dmap_metadata(const uint8_t *data, size_t len,
  1244. rtsp_metadata_t *meta) {
  1245. size_t pos = 0;
  1246. while (pos + 8 <= len) {
  1247. // Read 4-byte tag
  1248. char tag[5] = {0};
  1249. memcpy(tag, data + pos, 4);
  1250. pos += 4;
  1251. // Read 4-byte big-endian length
  1252. uint32_t item_len = ((uint32_t)data[pos] << 24) |
  1253. ((uint32_t)data[pos + 1] << 16) |
  1254. ((uint32_t)data[pos + 2] << 8) | data[pos + 3];
  1255. pos += 4;
  1256. if (pos + item_len > len) {
  1257. break; // Malformed
  1258. }
  1259. // Extract known metadata tags
  1260. if (strcmp(tag, "minm") == 0 && item_len > 0) {
  1261. size_t copy_len = item_len < METADATA_STRING_MAX - 1
  1262. ? item_len
  1263. : METADATA_STRING_MAX - 1;
  1264. memcpy(meta->title, data + pos, copy_len);
  1265. meta->title[copy_len] = '\0';
  1266. ESP_LOGI(TAG, " Title = %s", meta->title);
  1267. } else if (strcmp(tag, "asar") == 0 && item_len > 0) {
  1268. size_t copy_len = item_len < METADATA_STRING_MAX - 1
  1269. ? item_len
  1270. : METADATA_STRING_MAX - 1;
  1271. memcpy(meta->artist, data + pos, copy_len);
  1272. meta->artist[copy_len] = '\0';
  1273. ESP_LOGI(TAG, " Artist = %s", meta->artist);
  1274. } else if (strcmp(tag, "asal") == 0 && item_len > 0) {
  1275. size_t copy_len = item_len < METADATA_STRING_MAX - 1
  1276. ? item_len
  1277. : METADATA_STRING_MAX - 1;
  1278. memcpy(meta->album, data + pos, copy_len);
  1279. meta->album[copy_len] = '\0';
  1280. ESP_LOGI(TAG, " Album = %s", meta->album);
  1281. } else if (strcmp(tag, "asgn") == 0 && item_len > 0) {
  1282. size_t copy_len = item_len < METADATA_STRING_MAX - 1
  1283. ? item_len
  1284. : METADATA_STRING_MAX - 1;
  1285. memcpy(meta->genre, data + pos, copy_len);
  1286. meta->genre[copy_len] = '\0';
  1287. ESP_LOGI(TAG, " Genre = %s", meta->genre);
  1288. } else if (strcmp(tag, "mlit") == 0 || strcmp(tag, "cmst") == 0 ||
  1289. strcmp(tag, "mdst") == 0) {
  1290. // Container tags - recurse into them
  1291. parse_dmap_metadata(data + pos, item_len, meta);
  1292. }
  1293. pos += item_len;
  1294. }
  1295. }
  1296. /**
  1297. * Parse progress string and populate metadata fields
  1298. * Progress format: "start/current/end" in RTP timestamp units
  1299. * Sample rate is typically 44100
  1300. */
  1301. static void parse_progress(const char *progress_str, uint32_t sample_rate,
  1302. rtsp_metadata_t *meta) {
  1303. uint64_t start = 0, current = 0, end = 0;
  1304. // NOLINTNEXTLINE(bugprone-unchecked-string-to-number-conversion)
  1305. if (sscanf(progress_str, "%" PRIu64 "/%" PRIu64 "/%" PRIu64, &start, &current,
  1306. &end) == 3) {
  1307. if (sample_rate == 0) {
  1308. sample_rate = 44100; // Default sample rate
  1309. }
  1310. meta->position_secs = (uint32_t)((current - start) / sample_rate);
  1311. meta->duration_secs = (uint32_t)((end - start) / sample_rate);
  1312. char pos_str[16], dur_str[16];
  1313. format_time_mmss(meta->position_secs, pos_str, sizeof(pos_str));
  1314. format_time_mmss(meta->duration_secs, dur_str, sizeof(dur_str));
  1315. ESP_LOGI(TAG,
  1316. "Progress: %s / %s (raw: %" PRIu64 "/%" PRIu64 "/%" PRIu64 ")",
  1317. pos_str, dur_str, start, current, end);
  1318. }
  1319. }
  1320. static void handle_set_parameter(int socket, rtsp_conn_t *conn,
  1321. const rtsp_request_t *req, const uint8_t *raw,
  1322. size_t raw_len) {
  1323. const uint8_t *body = req->body;
  1324. size_t body_len = req->body_len;
  1325. rtsp_event_data_t event_data;
  1326. memset(&event_data, 0, sizeof(event_data));
  1327. bool has_metadata = false;
  1328. // Check for progress header in raw request
  1329. const char *progress_hdr = strstr((const char *)raw, "progress:");
  1330. if (!progress_hdr) {
  1331. progress_hdr = strstr((const char *)raw, "Progress:");
  1332. }
  1333. if (progress_hdr) {
  1334. // Find end of header line
  1335. const char *line_end = strstr(progress_hdr, "\r\n");
  1336. if (line_end) {
  1337. size_t val_start = 9; // Length of "progress:"
  1338. while (progress_hdr[val_start] == ' ') {
  1339. val_start++;
  1340. }
  1341. char progress_val[64];
  1342. size_t val_len = line_end - (progress_hdr + val_start);
  1343. if (val_len < sizeof(progress_val)) {
  1344. memcpy(progress_val, progress_hdr + val_start, val_len);
  1345. progress_val[val_len] = '\0';
  1346. parse_progress(progress_val, 44100, &event_data.metadata);
  1347. has_metadata = true;
  1348. }
  1349. }
  1350. }
  1351. if (strstr(req->content_type, "text/parameters")) {
  1352. if (body) {
  1353. if (strstr((const char *)body, "volume:")) {
  1354. const char *vol = strstr((const char *)body, "volume:");
  1355. if (vol) {
  1356. float volume = strtof(vol + 7, NULL);
  1357. rtsp_conn_set_volume(conn, volume);
  1358. uint8_t pct;
  1359. if (volume <= -30.0f) {
  1360. pct = 0; // 静音(AirPlay -144dB 或 -30dB 以下均认为 0%)
  1361. } else if (volume >= 0.0f) {
  1362. pct = 100;
  1363. } else {
  1364. pct = (uint8_t)(((volume + 30.0f) / 30.0f) * 100.0f + 0.5f);
  1365. }
  1366. dac_njw1195_set_vol_main(pct);
  1367. }
  1368. }
  1369. // Check for progress in body (AirPlay 1 style)
  1370. const char *prog = strstr((const char *)body, "progress:");
  1371. if (prog) {
  1372. prog += 9;
  1373. while (*prog == ' ') {
  1374. prog++;
  1375. }
  1376. parse_progress(prog, 44100, &event_data.metadata);
  1377. has_metadata = true;
  1378. }
  1379. }
  1380. } else if (strstr(req->content_type, "application/x-dmap-tagged")) {
  1381. // DMAP-tagged metadata (AirPlay 1)
  1382. if (body && body_len > 0) {
  1383. ESP_LOGI(TAG, "Received DMAP metadata (%zu bytes)", body_len);
  1384. parse_dmap_metadata(body, body_len, &event_data.metadata);
  1385. has_metadata = true;
  1386. }
  1387. } else if (strstr(req->content_type, "image/jpeg") ||
  1388. strstr(req->content_type, "image/png")) {
  1389. #ifdef CONFIG_ENABLE_AIRPLAY_ARTWORK
  1390. // Artwork - log and flag in metadata
  1391. ESP_LOGI(TAG, "Received artwork: %s (%zu bytes)", req->content_type,
  1392. body_len);
  1393. event_data.metadata.has_artwork = true;
  1394. has_metadata = true;
  1395. #else
  1396. // Artwork reception disabled — ignore it. The md txt record already asks
  1397. // senders not to transmit cover art, but some send it regardless.
  1398. ESP_LOGD(TAG, "Ignoring artwork (%s, %zu bytes): disabled in config",
  1399. req->content_type, body_len);
  1400. #endif
  1401. } else if (strstr(req->content_type, "application/x-apple-binary-plist")) {
  1402. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  1403. int64_t value;
  1404. if (bplist_find_int(body, body_len, "networkTimeSecs", &value)) {
  1405. ESP_LOGI(TAG, "SET_PARAMETER: networkTimeSecs=%lld", (long long)value);
  1406. }
  1407. double rate;
  1408. if (bplist_find_real(body, body_len, "rate", &rate)) {
  1409. ESP_LOGI(TAG, "SET_PARAMETER: rate=%.2f", rate);
  1410. }
  1411. // Try to extract metadata from bplist (AirPlay 2)
  1412. char str_val[METADATA_STRING_MAX];
  1413. if (bplist_find_string(body, body_len, "itemName", str_val,
  1414. sizeof(str_val))) {
  1415. ESP_LOGI(TAG, "Metadata: Title = %s", str_val);
  1416. strlcpy(event_data.metadata.title, str_val, METADATA_STRING_MAX);
  1417. has_metadata = true;
  1418. }
  1419. if (bplist_find_string(body, body_len, "artistName", str_val,
  1420. sizeof(str_val))) {
  1421. ESP_LOGI(TAG, "Metadata: Artist = %s", str_val);
  1422. strlcpy(event_data.metadata.artist, str_val, METADATA_STRING_MAX);
  1423. has_metadata = true;
  1424. }
  1425. if (bplist_find_string(body, body_len, "albumName", str_val,
  1426. sizeof(str_val))) {
  1427. ESP_LOGI(TAG, "Metadata: Album = %s", str_val);
  1428. strlcpy(event_data.metadata.album, str_val, METADATA_STRING_MAX);
  1429. has_metadata = true;
  1430. }
  1431. // Progress info from bplist
  1432. double elapsed = 0, duration = 0;
  1433. if (bplist_find_real(body, body_len, "elapsed", &elapsed)) {
  1434. event_data.metadata.position_secs = (uint32_t)elapsed;
  1435. has_metadata = true;
  1436. char elapsed_str[16];
  1437. format_time_mmss((uint32_t)elapsed, elapsed_str, sizeof(elapsed_str));
  1438. if (bplist_find_real(body, body_len, "duration", &duration)) {
  1439. event_data.metadata.duration_secs = (uint32_t)duration;
  1440. char duration_str[16];
  1441. format_time_mmss((uint32_t)duration, duration_str,
  1442. sizeof(duration_str));
  1443. ESP_LOGI(TAG, "Progress: %s / %s", elapsed_str, duration_str);
  1444. } else {
  1445. ESP_LOGI(TAG, "Progress: %s", elapsed_str);
  1446. }
  1447. }
  1448. }
  1449. }
  1450. if (has_metadata) {
  1451. rtsp_events_emit(RTSP_EVENT_METADATA, &event_data);
  1452. }
  1453. rtsp_send_ok(socket, conn, req->cseq);
  1454. }
  1455. static void handle_get_parameter(int socket, rtsp_conn_t *conn,
  1456. const rtsp_request_t *req, const uint8_t *raw,
  1457. size_t raw_len) {
  1458. (void)raw;
  1459. (void)raw_len;
  1460. if (req->body && req->body_len > 0) {
  1461. if (strstr((const char *)req->body, "volume")) {
  1462. char vol_response[32];
  1463. int vol_len = snprintf(vol_response, sizeof(vol_response),
  1464. "volume: %.2f\r\n", conn->volume_db);
  1465. rtsp_send_response(socket, conn, 200, "OK", req->cseq,
  1466. "Content-Type: text/parameters\r\n", vol_response,
  1467. vol_len);
  1468. return;
  1469. }
  1470. }
  1471. rtsp_send_ok(socket, conn, req->cseq);
  1472. }
  1473. static void handle_pause(int socket, rtsp_conn_t *conn,
  1474. const rtsp_request_t *req, const uint8_t *raw,
  1475. size_t raw_len) {
  1476. (void)raw;
  1477. (void)raw_len;
  1478. ESP_LOGI(TAG, "PAUSE received");
  1479. // Stop the audio consumer but leave the buffer filling. The phone will
  1480. // send a fresh SETRATEANCHORTIME (rate=1) anchor on resume that re-aligns
  1481. // the buffered frames to the correct wall-clock position.
  1482. audio_receiver_pause();
  1483. audio_output_flush();
  1484. conn->stream_paused = true;
  1485. rtsp_send_ok(socket, conn, req->cseq);
  1486. }
  1487. static void handle_flush(int socket, rtsp_conn_t *conn,
  1488. const rtsp_request_t *req, const uint8_t *raw,
  1489. size_t raw_len) {
  1490. (void)raw;
  1491. (void)raw_len;
  1492. // Plain AirPlay 1 FLUSH — always immediate.
  1493. ESP_LOGI(TAG, "FLUSH received");
  1494. audio_receiver_seek_flush();
  1495. audio_output_flush();
  1496. rtsp_send_ok(socket, conn, req->cseq);
  1497. }
  1498. static void handle_flushbuffered(int socket, rtsp_conn_t *conn,
  1499. const rtsp_request_t *req, const uint8_t *raw,
  1500. size_t raw_len) {
  1501. (void)raw;
  1502. (void)raw_len;
  1503. const uint8_t *body = req->body;
  1504. size_t body_len = req->body_len;
  1505. // AirPlay 2 FLUSHBUFFERED carries an optional bplist with:
  1506. // flushFromSeq / flushFromTS — first sequence/timestamp to discard
  1507. // flushUntilSeq / flushUntilTS — last sequence/timestamp to discard
  1508. //
  1509. // If flushFromSeq is absent → immediate flush (stop and discard everything).
  1510. // If flushFromSeq is present → deferred flush: keep playing existing buffered
  1511. // content until flushUntilTS is reached, then discard and start fresh.
  1512. // The phone simultaneously starts streaming the new track, which fills the
  1513. // buffer beyond flushUntilTS; audio_timing_read detects the boundary and
  1514. // triggers the bulk-flush at the right moment.
  1515. bool has_deferred = false;
  1516. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  1517. int64_t flush_from_seq = 0, flush_from_ts = 0;
  1518. int64_t flush_until_seq = 0, flush_until_ts = 0;
  1519. bool got_from_seq =
  1520. bplist_find_int(body, body_len, "flushFromSeq", &flush_from_seq);
  1521. bool got_from_ts =
  1522. bplist_find_int(body, body_len, "flushFromTS", &flush_from_ts);
  1523. bool got_until_seq =
  1524. bplist_find_int(body, body_len, "flushUntilSeq", &flush_until_seq);
  1525. bool got_until_ts =
  1526. bplist_find_int(body, body_len, "flushUntilTS", &flush_until_ts);
  1527. if (got_from_seq && got_from_ts && got_until_seq && got_until_ts) {
  1528. has_deferred = true;
  1529. ESP_LOGI(TAG,
  1530. "FLUSHBUFFERED deferred: fromSeq=%" PRId64 " fromTS=%" PRId64
  1531. " untilSeq=%" PRId64 " untilTS=%" PRId64,
  1532. flush_from_seq, flush_from_ts, flush_until_seq, flush_until_ts);
  1533. // Arm the deferred flush. Do NOT flush the audio output immediately —
  1534. // let it drain naturally to the boundary so the current track finishes.
  1535. audio_receiver_set_deferred_flush((uint32_t)flush_until_ts);
  1536. } else {
  1537. ESP_LOGI(TAG, "FLUSHBUFFERED immediate (missing from/until fields)");
  1538. }
  1539. }
  1540. if (!has_deferred) {
  1541. // Immediate flush: discard everything and reset now.
  1542. audio_receiver_seek_flush();
  1543. audio_output_flush();
  1544. }
  1545. rtsp_send_ok(socket, conn, req->cseq);
  1546. }
  1547. static void handle_teardown(int socket, rtsp_conn_t *conn,
  1548. const rtsp_request_t *req, const uint8_t *raw,
  1549. size_t raw_len) {
  1550. (void)raw;
  1551. (void)raw_len;
  1552. const uint8_t *body = req->body;
  1553. size_t body_len = req->body_len;
  1554. bool has_streams = false;
  1555. size_t stream_count = 0;
  1556. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  1557. if (bplist_get_streams_count(body, body_len, &stream_count)) {
  1558. has_streams = true;
  1559. }
  1560. }
  1561. // TEARDOWN with streams = stream teardown (may be followed by new SETUP)
  1562. // TEARDOWN without streams = full session teardown (disconnect)
  1563. ESP_LOGI(TAG, "TEARDOWN: has_streams=%d stream_count=%zu", has_streams,
  1564. stream_count);
  1565. audio_receiver_stop();
  1566. audio_output_flush();
  1567. // Drop PTP lock + offset history. AirPlay group rejoins reuse the same
  1568. // PTP master clock_id; without this, ptp_clock_set_master_clock_id() on
  1569. // the next session early-returns and reuses stale samples accumulated
  1570. // (or missed) while we were detached from the group.
  1571. ptp_clock_clear();
  1572. conn->stream_active = false;
  1573. conn->stream_paused =
  1574. has_streams; // Keep session ready if only streams torn down
  1575. if (has_streams) {
  1576. // Stream-level teardown — session still open, iOS considers this paused
  1577. rtsp_events_emit(RTSP_EVENT_PAUSED, NULL);
  1578. } else {
  1579. // Full teardown — server cleanup will emit RTSP_EVENT_DISCONNECTED
  1580. // when the TCP connection closes.
  1581. // For v1 sessions, keep the DACP session alive across teardown so the
  1582. // grace period can probe mDNS to differentiate pause from real
  1583. // disconnect. v2 sessions clear immediately.
  1584. if (conn->protocol_version != 1) {
  1585. dacp_clear_session();
  1586. conn->dacp_id[0] = '\0';
  1587. conn->active_remote[0] = '\0';
  1588. }
  1589. ntp_clock_stop();
  1590. conn->timing_port = 0;
  1591. }
  1592. rtsp_send_ok(socket, conn, req->cseq);
  1593. }
  1594. static void handle_setrateanchortime(int socket, rtsp_conn_t *conn,
  1595. const rtsp_request_t *req,
  1596. const uint8_t *raw, size_t raw_len) {
  1597. (void)raw;
  1598. (void)raw_len;
  1599. const uint8_t *body = req->body;
  1600. size_t body_len = req->body_len;
  1601. double rate = 1.0;
  1602. uint64_t clock_id = 0;
  1603. uint64_t network_time_secs = 0;
  1604. uint64_t network_time_frac = 0;
  1605. uint64_t rtp_time = 0;
  1606. if (body && body_len > 0 && body_len >= 8 &&
  1607. memcmp(body, "bplist00", 8) == 0) {
  1608. if (!bplist_find_real(body, body_len, "rate", &rate)) {
  1609. int64_t rate_int;
  1610. if (bplist_find_int(body, body_len, "rate", &rate_int)) {
  1611. rate = (double)rate_int;
  1612. }
  1613. }
  1614. int64_t value;
  1615. if (bplist_find_int(body, body_len, "networkTimeTimelineID", &value)) {
  1616. clock_id = (uint64_t)value;
  1617. }
  1618. if (bplist_find_int(body, body_len, "networkTimeSecs", &value)) {
  1619. network_time_secs = (uint64_t)value;
  1620. }
  1621. if (bplist_find_int(body, body_len, "networkTimeFrac", &value)) {
  1622. network_time_frac = (uint64_t)value;
  1623. }
  1624. if (bplist_find_int(body, body_len, "rtpTime", &value)) {
  1625. rtp_time = (uint64_t)value;
  1626. }
  1627. ESP_LOGI(TAG, "SETRATEANCHORTIME: secs=%llu, rtp=%llu, rate=%.1f",
  1628. (unsigned long long)network_time_secs,
  1629. (unsigned long long)rtp_time, rate);
  1630. if (network_time_secs != 0 && rtp_time != 0) {
  1631. uint64_t frac = network_time_frac >> 32;
  1632. frac = (frac * 1000000000ULL) >> 32;
  1633. uint64_t network_time_ns = network_time_secs * 1000000000ULL + frac;
  1634. audio_receiver_set_anchor_time(clock_id, network_time_ns,
  1635. (uint32_t)rtp_time);
  1636. }
  1637. }
  1638. if (rate == 0.0) {
  1639. ESP_LOGI(TAG, "SETRATEANCHORTIME: rate=0 -> PAUSING");
  1640. conn->stream_paused = true;
  1641. audio_receiver_pause();
  1642. audio_output_flush();
  1643. rtsp_events_emit(RTSP_EVENT_PAUSED, NULL);
  1644. } else {
  1645. ESP_LOGI(TAG, "SETRATEANCHORTIME: rate=%.1f -> RESUMING (was_paused=%d)",
  1646. rate, conn->stream_paused);
  1647. conn->stream_paused = false;
  1648. audio_receiver_set_playing(true);
  1649. rtsp_events_emit(RTSP_EVENT_PLAYING, NULL);
  1650. }
  1651. rtsp_send_ok(socket, conn, req->cseq);
  1652. }
  1653. static void handle_setpeers(int socket, rtsp_conn_t *conn,
  1654. const rtsp_request_t *req, const uint8_t *raw,
  1655. size_t raw_len) {
  1656. (void)raw;
  1657. (void)raw_len;
  1658. const uint8_t *body = req->body;
  1659. size_t body_len = req->body_len;
  1660. ESP_LOGI(TAG, "%s: body_len=%zu", req->method, body_len);
  1661. if (body && body_len >= 8 && memcmp(body, "bplist00", 8) == 0) {
  1662. ESP_LOGI(TAG, "SETPEERS: got bplist");
  1663. }
  1664. // PTP peers changed — the PTP clock will re-lock to the new master on
  1665. // its own. Do NOT reset the audio timing anchor here: the anchor's
  1666. // network_time_ns is in absolute PTP time, and compute_early_us
  1667. // auto-corrects via ptp_clock_get_offset_ns() as PTP re-locks.
  1668. // Resetting mid-stream orphans the pre-buffer (up to ~23 s of audio)
  1669. // with no valid anchor, causing consecutive-early detection to
  1670. // invalidate the anchor and break playback.
  1671. ESP_LOGI(TAG, "SETPEERS: PTP peers changed, clock will re-lock");
  1672. rtsp_send_ok(socket, conn, req->cseq);
  1673. }