You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

978 lines
33KB

  1. /*
  2. * RTSP demuxer
  3. * Copyright (c) 2002 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avstring.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/mathematics.h"
  24. #include "libavutil/random_seed.h"
  25. #include "libavutil/time.h"
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "network.h"
  29. #include "os_support.h"
  30. #include "rtpproto.h"
  31. #include "rtsp.h"
  32. #include "rdt.h"
  33. #include "tls.h"
  34. #include "url.h"
  35. static const struct RTSPStatusMessage {
  36. enum RTSPStatusCode code;
  37. const char *message;
  38. } status_messages[] = {
  39. { RTSP_STATUS_OK, "OK" },
  40. { RTSP_STATUS_METHOD, "Method Not Allowed" },
  41. { RTSP_STATUS_BANDWIDTH, "Not Enough Bandwidth" },
  42. { RTSP_STATUS_SESSION, "Session Not Found" },
  43. { RTSP_STATUS_STATE, "Method Not Valid in This State" },
  44. { RTSP_STATUS_AGGREGATE, "Aggregate operation not allowed" },
  45. { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
  46. { RTSP_STATUS_TRANSPORT, "Unsupported transport" },
  47. { RTSP_STATUS_INTERNAL, "Internal Server Error" },
  48. { RTSP_STATUS_SERVICE, "Service Unavailable" },
  49. { RTSP_STATUS_VERSION, "RTSP Version not supported" },
  50. { 0, "NULL" }
  51. };
  52. static int rtsp_read_close(AVFormatContext *s)
  53. {
  54. RTSPState *rt = s->priv_data;
  55. if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
  56. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  57. ff_rtsp_close_streams(s);
  58. ff_rtsp_close_connections(s);
  59. ff_network_close();
  60. rt->real_setup = NULL;
  61. av_freep(&rt->real_setup_cache);
  62. return 0;
  63. }
  64. static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
  65. int *rbuflen)
  66. {
  67. RTSPState *rt = s->priv_data;
  68. int idx = 0;
  69. int ret = 0;
  70. *rbuflen = 0;
  71. do {
  72. ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
  73. if (ret <= 0)
  74. return ret ? ret : AVERROR_EOF;
  75. if (rbuf[idx] == '\r') {
  76. /* Ignore */
  77. } else if (rbuf[idx] == '\n') {
  78. rbuf[idx] = '\0';
  79. *rbuflen = idx;
  80. return 0;
  81. } else
  82. idx++;
  83. } while (idx < rbufsize);
  84. av_log(s, AV_LOG_ERROR, "Message too long\n");
  85. return AVERROR(EIO);
  86. }
  87. static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
  88. const char *extracontent, uint16_t seq)
  89. {
  90. RTSPState *rt = s->priv_data;
  91. char message[4096];
  92. int index = 0;
  93. while (status_messages[index].code) {
  94. if (status_messages[index].code == code) {
  95. snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
  96. code, status_messages[index].message);
  97. break;
  98. }
  99. index++;
  100. }
  101. if (!status_messages[index].code)
  102. return AVERROR(EINVAL);
  103. av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
  104. av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
  105. if (extracontent)
  106. av_strlcat(message, extracontent, sizeof(message));
  107. av_strlcat(message, "\r\n", sizeof(message));
  108. av_log(s, AV_LOG_TRACE, "Sending response:\n%s", message);
  109. ffurl_write(rt->rtsp_hd_out, message, strlen(message));
  110. return 0;
  111. }
  112. static inline int check_sessionid(AVFormatContext *s,
  113. RTSPMessageHeader *request)
  114. {
  115. RTSPState *rt = s->priv_data;
  116. unsigned char *session_id = rt->session_id;
  117. if (!session_id[0]) {
  118. av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
  119. return 0;
  120. }
  121. if (strcmp(session_id, request->session_id)) {
  122. av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
  123. request->session_id);
  124. rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
  125. return AVERROR_STREAM_NOT_FOUND;
  126. }
  127. return 0;
  128. }
  129. static inline int rtsp_read_request(AVFormatContext *s,
  130. RTSPMessageHeader *request,
  131. const char *method)
  132. {
  133. RTSPState *rt = s->priv_data;
  134. char rbuf[1024];
  135. int rbuflen, ret;
  136. do {
  137. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  138. if (ret)
  139. return ret;
  140. if (rbuflen > 1) {
  141. av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf);
  142. ff_rtsp_parse_line(s, request, rbuf, rt, method);
  143. }
  144. } while (rbuflen > 0);
  145. if (request->seq != rt->seq + 1) {
  146. av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
  147. request->seq);
  148. return AVERROR(EINVAL);
  149. }
  150. if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
  151. ret = check_sessionid(s, request);
  152. if (ret)
  153. return ret;
  154. }
  155. return 0;
  156. }
  157. static int rtsp_read_announce(AVFormatContext *s)
  158. {
  159. RTSPState *rt = s->priv_data;
  160. RTSPMessageHeader request = { 0 };
  161. char sdp[4096];
  162. int ret;
  163. ret = rtsp_read_request(s, &request, "ANNOUNCE");
  164. if (ret)
  165. return ret;
  166. rt->seq++;
  167. if (strcmp(request.content_type, "application/sdp")) {
  168. av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
  169. request.content_type);
  170. rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
  171. return AVERROR_OPTION_NOT_FOUND;
  172. }
  173. if (request.content_length && request.content_length < sizeof(sdp) - 1) {
  174. /* Read SDP */
  175. if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
  176. < request.content_length) {
  177. av_log(s, AV_LOG_ERROR,
  178. "Unable to get complete SDP Description in ANNOUNCE\n");
  179. rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
  180. return AVERROR(EIO);
  181. }
  182. sdp[request.content_length] = '\0';
  183. av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
  184. ret = ff_sdp_parse(s, sdp);
  185. if (ret)
  186. return ret;
  187. rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
  188. return 0;
  189. }
  190. av_log(s, AV_LOG_ERROR,
  191. "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
  192. rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
  193. "Content-Length exceeds buffer size", request.seq);
  194. return AVERROR(EIO);
  195. }
  196. static int rtsp_read_options(AVFormatContext *s)
  197. {
  198. RTSPState *rt = s->priv_data;
  199. RTSPMessageHeader request = { 0 };
  200. int ret = 0;
  201. /* Parsing headers */
  202. ret = rtsp_read_request(s, &request, "OPTIONS");
  203. if (ret)
  204. return ret;
  205. rt->seq++;
  206. /* Send Reply */
  207. rtsp_send_reply(s, RTSP_STATUS_OK,
  208. "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
  209. request.seq);
  210. return 0;
  211. }
  212. static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
  213. {
  214. RTSPState *rt = s->priv_data;
  215. RTSPMessageHeader request = { 0 };
  216. int ret = 0;
  217. char url[1024];
  218. RTSPStream *rtsp_st;
  219. char responseheaders[1024];
  220. int localport = -1;
  221. int transportidx = 0;
  222. int streamid = 0;
  223. ret = rtsp_read_request(s, &request, "SETUP");
  224. if (ret)
  225. return ret;
  226. rt->seq++;
  227. if (!request.nb_transports) {
  228. av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
  229. return AVERROR_INVALIDDATA;
  230. }
  231. for (transportidx = 0; transportidx < request.nb_transports;
  232. transportidx++) {
  233. if (!request.transports[transportidx].mode_record ||
  234. (request.transports[transportidx].lower_transport !=
  235. RTSP_LOWER_TRANSPORT_UDP &&
  236. request.transports[transportidx].lower_transport !=
  237. RTSP_LOWER_TRANSPORT_TCP)) {
  238. av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
  239. " protocol not supported (yet)\n");
  240. return AVERROR_INVALIDDATA;
  241. }
  242. }
  243. if (request.nb_transports > 1)
  244. av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
  245. "using first of all\n");
  246. for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
  247. if (!strcmp(rt->rtsp_streams[streamid]->control_url,
  248. controlurl))
  249. break;
  250. }
  251. if (streamid == rt->nb_rtsp_streams) {
  252. av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
  253. return AVERROR_STREAM_NOT_FOUND;
  254. }
  255. rtsp_st = rt->rtsp_streams[streamid];
  256. localport = rt->rtp_port_min;
  257. if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  258. rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  259. if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
  260. rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
  261. return ret;
  262. }
  263. rtsp_st->interleaved_min = request.transports[0].interleaved_min;
  264. rtsp_st->interleaved_max = request.transports[0].interleaved_max;
  265. snprintf(responseheaders, sizeof(responseheaders), "Transport: "
  266. "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
  267. "\r\n", request.transports[0].interleaved_min,
  268. request.transports[0].interleaved_max);
  269. } else {
  270. do {
  271. AVDictionary *opts = NULL;
  272. char buf[256];
  273. snprintf(buf, sizeof(buf), "%d", rt->buffer_size);
  274. av_dict_set(&opts, "buffer_size", buf, 0);
  275. ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
  276. av_log(s, AV_LOG_TRACE, "Opening: %s", url);
  277. ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  278. &s->interrupt_callback, &opts, rt->protocols, NULL);
  279. av_dict_free(&opts);
  280. if (ret)
  281. localport += 2;
  282. } while (ret || localport > rt->rtp_port_max);
  283. if (localport > rt->rtp_port_max) {
  284. rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
  285. return ret;
  286. }
  287. av_log(s, AV_LOG_TRACE, "Listening on: %d",
  288. ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
  289. if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
  290. rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
  291. return ret;
  292. }
  293. localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  294. snprintf(responseheaders, sizeof(responseheaders), "Transport: "
  295. "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
  296. "client_port=%d-%d;server_port=%d-%d\r\n",
  297. host, request.transports[0].client_port_min,
  298. request.transports[0].client_port_max, localport,
  299. localport + 1);
  300. }
  301. /* Establish sessionid if not previously set */
  302. /* Put this in a function? */
  303. /* RFC 2326: session id must be at least 8 digits */
  304. while (strlen(rt->session_id) < 8)
  305. av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
  306. av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
  307. rt->session_id);
  308. /* Send Reply */
  309. rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
  310. rt->state = RTSP_STATE_PAUSED;
  311. return 0;
  312. }
  313. static int rtsp_read_record(AVFormatContext *s)
  314. {
  315. RTSPState *rt = s->priv_data;
  316. RTSPMessageHeader request = { 0 };
  317. int ret = 0;
  318. char responseheaders[1024];
  319. ret = rtsp_read_request(s, &request, "RECORD");
  320. if (ret)
  321. return ret;
  322. ret = check_sessionid(s, &request);
  323. if (ret)
  324. return ret;
  325. rt->seq++;
  326. snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
  327. rt->session_id);
  328. rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
  329. rt->state = RTSP_STATE_STREAMING;
  330. return 0;
  331. }
  332. static inline int parse_command_line(AVFormatContext *s, const char *line,
  333. int linelen, char *uri, int urisize,
  334. char *method, int methodsize,
  335. enum RTSPMethod *methodcode)
  336. {
  337. RTSPState *rt = s->priv_data;
  338. const char *linept, *searchlinept;
  339. linept = strchr(line, ' ');
  340. if (!linept)
  341. return AVERROR_INVALIDDATA;
  342. if (linept - line > methodsize - 1) {
  343. av_log(s, AV_LOG_ERROR, "Method string too long\n");
  344. return AVERROR(EIO);
  345. }
  346. memcpy(method, line, linept - line);
  347. method[linept - line] = '\0';
  348. linept++;
  349. if (!strcmp(method, "ANNOUNCE"))
  350. *methodcode = ANNOUNCE;
  351. else if (!strcmp(method, "OPTIONS"))
  352. *methodcode = OPTIONS;
  353. else if (!strcmp(method, "RECORD"))
  354. *methodcode = RECORD;
  355. else if (!strcmp(method, "SETUP"))
  356. *methodcode = SETUP;
  357. else if (!strcmp(method, "PAUSE"))
  358. *methodcode = PAUSE;
  359. else if (!strcmp(method, "TEARDOWN"))
  360. *methodcode = TEARDOWN;
  361. else
  362. *methodcode = UNKNOWN;
  363. /* Check method with the state */
  364. if (rt->state == RTSP_STATE_IDLE) {
  365. if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
  366. av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
  367. line);
  368. return AVERROR_PROTOCOL_NOT_FOUND;
  369. }
  370. } else if (rt->state == RTSP_STATE_PAUSED) {
  371. if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
  372. && (*methodcode != SETUP)) {
  373. av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
  374. line);
  375. return AVERROR_PROTOCOL_NOT_FOUND;
  376. }
  377. } else if (rt->state == RTSP_STATE_STREAMING) {
  378. if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
  379. && (*methodcode != TEARDOWN)) {
  380. av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
  381. " %s\n", line);
  382. return AVERROR_PROTOCOL_NOT_FOUND;
  383. }
  384. } else {
  385. av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
  386. return AVERROR_BUG;
  387. }
  388. searchlinept = strchr(linept, ' ');
  389. if (!searchlinept) {
  390. av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
  391. return AVERROR_INVALIDDATA;
  392. }
  393. if (searchlinept - linept > urisize - 1) {
  394. av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
  395. return AVERROR(EIO);
  396. }
  397. memcpy(uri, linept, searchlinept - linept);
  398. uri[searchlinept - linept] = '\0';
  399. if (strcmp(rt->control_uri, uri)) {
  400. char host[128], path[512], auth[128];
  401. int port;
  402. char ctl_host[128], ctl_path[512], ctl_auth[128];
  403. int ctl_port;
  404. av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
  405. path, sizeof(path), uri);
  406. av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
  407. sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
  408. rt->control_uri);
  409. if (strcmp(host, ctl_host))
  410. av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
  411. host, ctl_host);
  412. if (strcmp(path, ctl_path) && *methodcode != SETUP)
  413. av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
  414. " %s\n", path, ctl_path);
  415. if (*methodcode == ANNOUNCE) {
  416. av_log(s, AV_LOG_INFO,
  417. "Updating control URI to %s\n", uri);
  418. av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
  419. }
  420. }
  421. linept = searchlinept + 1;
  422. if (!av_strstart(linept, "RTSP/1.0", NULL)) {
  423. av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
  424. return AVERROR_PROTOCOL_NOT_FOUND;
  425. }
  426. return 0;
  427. }
  428. int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
  429. {
  430. RTSPState *rt = s->priv_data;
  431. unsigned char rbuf[4096];
  432. unsigned char method[10];
  433. char uri[500];
  434. int ret;
  435. int rbuflen = 0;
  436. RTSPMessageHeader request = { 0 };
  437. enum RTSPMethod methodcode;
  438. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  439. if (ret < 0)
  440. return ret;
  441. ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
  442. sizeof(method), &methodcode);
  443. if (ret) {
  444. av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
  445. return ret;
  446. }
  447. ret = rtsp_read_request(s, &request, method);
  448. if (ret)
  449. return ret;
  450. rt->seq++;
  451. if (methodcode == PAUSE) {
  452. rt->state = RTSP_STATE_PAUSED;
  453. ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
  454. // TODO: Missing date header in response
  455. } else if (methodcode == OPTIONS) {
  456. ret = rtsp_send_reply(s, RTSP_STATUS_OK,
  457. "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
  458. "RECORD\r\n", request.seq);
  459. } else if (methodcode == TEARDOWN) {
  460. rt->state = RTSP_STATE_IDLE;
  461. ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
  462. return 0;
  463. }
  464. return ret;
  465. }
  466. static int rtsp_read_play(AVFormatContext *s)
  467. {
  468. RTSPState *rt = s->priv_data;
  469. RTSPMessageHeader reply1, *reply = &reply1;
  470. int i;
  471. char cmd[1024];
  472. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  473. rt->nb_byes = 0;
  474. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  475. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  476. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  477. /* Try to initialize the connection state in a
  478. * potential NAT router by sending dummy packets.
  479. * RTP/RTCP dummy packets are used for RDT, too.
  480. */
  481. if (rtsp_st->rtp_handle &&
  482. !(rt->server_type == RTSP_SERVER_WMS && i > 1))
  483. ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
  484. }
  485. }
  486. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  487. if (rt->transport == RTSP_TRANSPORT_RTP) {
  488. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  489. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  490. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  491. if (!rtpctx)
  492. continue;
  493. ff_rtp_reset_packet_queue(rtpctx);
  494. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  495. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  496. rtpctx->base_timestamp = 0;
  497. rtpctx->timestamp = 0;
  498. rtpctx->unwrapped_timestamp = 0;
  499. rtpctx->rtcp_ts_offset = 0;
  500. }
  501. }
  502. if (rt->state == RTSP_STATE_PAUSED) {
  503. cmd[0] = 0;
  504. } else {
  505. snprintf(cmd, sizeof(cmd),
  506. "Range: npt=%"PRId64".%03"PRId64"-\r\n",
  507. rt->seek_timestamp / AV_TIME_BASE,
  508. rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
  509. }
  510. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  511. if (reply->status_code != RTSP_STATUS_OK) {
  512. return -1;
  513. }
  514. if (rt->transport == RTSP_TRANSPORT_RTP &&
  515. reply->range_start != AV_NOPTS_VALUE) {
  516. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  517. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  518. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  519. AVStream *st = NULL;
  520. if (!rtpctx || rtsp_st->stream_index < 0)
  521. continue;
  522. st = s->streams[rtsp_st->stream_index];
  523. rtpctx->range_start_offset =
  524. av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
  525. st->time_base);
  526. }
  527. }
  528. }
  529. rt->state = RTSP_STATE_STREAMING;
  530. return 0;
  531. }
  532. /* pause the stream */
  533. static int rtsp_read_pause(AVFormatContext *s)
  534. {
  535. RTSPState *rt = s->priv_data;
  536. RTSPMessageHeader reply1, *reply = &reply1;
  537. if (rt->state != RTSP_STATE_STREAMING)
  538. return 0;
  539. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  540. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  541. if (reply->status_code != RTSP_STATUS_OK) {
  542. return -1;
  543. }
  544. }
  545. rt->state = RTSP_STATE_PAUSED;
  546. return 0;
  547. }
  548. int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  549. {
  550. RTSPState *rt = s->priv_data;
  551. char cmd[1024];
  552. unsigned char *content = NULL;
  553. int ret;
  554. /* describe the stream */
  555. snprintf(cmd, sizeof(cmd),
  556. "Accept: application/sdp\r\n");
  557. if (rt->server_type == RTSP_SERVER_REAL) {
  558. /**
  559. * The Require: attribute is needed for proper streaming from
  560. * Realmedia servers.
  561. */
  562. av_strlcat(cmd,
  563. "Require: com.real.retain-entity-for-setup\r\n",
  564. sizeof(cmd));
  565. }
  566. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  567. if (!content)
  568. return AVERROR_INVALIDDATA;
  569. if (reply->status_code != RTSP_STATUS_OK) {
  570. av_freep(&content);
  571. return AVERROR_INVALIDDATA;
  572. }
  573. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
  574. /* now we got the SDP description, we parse it */
  575. ret = ff_sdp_parse(s, (const char *)content);
  576. av_freep(&content);
  577. if (ret < 0)
  578. return ret;
  579. return 0;
  580. }
  581. static int rtsp_listen(AVFormatContext *s)
  582. {
  583. RTSPState *rt = s->priv_data;
  584. char proto[128], host[128], path[512], auth[128];
  585. char uri[500];
  586. int port;
  587. int default_port = RTSP_DEFAULT_PORT;
  588. char tcpname[500];
  589. const char *lower_proto = "tcp";
  590. unsigned char rbuf[4096];
  591. unsigned char method[10];
  592. int rbuflen = 0;
  593. int ret;
  594. enum RTSPMethod methodcode;
  595. if (!rt->protocols) {
  596. rt->protocols = ffurl_get_protocols(s->protocol_whitelist,
  597. s->protocol_blacklist);
  598. if (!rt->protocols)
  599. return AVERROR(ENOMEM);
  600. }
  601. /* extract hostname and port */
  602. av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
  603. &port, path, sizeof(path), s->filename);
  604. /* ff_url_join. No authorization by now (NULL) */
  605. ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
  606. port, "%s", path);
  607. if (!strcmp(proto, "rtsps")) {
  608. lower_proto = "tls";
  609. default_port = RTSPS_DEFAULT_PORT;
  610. }
  611. if (port < 0)
  612. port = default_port;
  613. /* Create TCP connection */
  614. ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
  615. "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
  616. if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
  617. &s->interrupt_callback, NULL, rt->protocols, NULL)) {
  618. av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
  619. return ret;
  620. }
  621. rt->state = RTSP_STATE_IDLE;
  622. rt->rtsp_hd_out = rt->rtsp_hd;
  623. for (;;) { /* Wait for incoming RTSP messages */
  624. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  625. if (ret < 0)
  626. return ret;
  627. ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
  628. sizeof(method), &methodcode);
  629. if (ret) {
  630. av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
  631. return ret;
  632. }
  633. if (methodcode == ANNOUNCE) {
  634. ret = rtsp_read_announce(s);
  635. rt->state = RTSP_STATE_PAUSED;
  636. } else if (methodcode == OPTIONS) {
  637. ret = rtsp_read_options(s);
  638. } else if (methodcode == RECORD) {
  639. ret = rtsp_read_record(s);
  640. if (!ret)
  641. return 0; // We are ready for streaming
  642. } else if (methodcode == SETUP)
  643. ret = rtsp_read_setup(s, host, uri);
  644. if (ret) {
  645. ffurl_close(rt->rtsp_hd);
  646. return AVERROR_INVALIDDATA;
  647. }
  648. }
  649. }
  650. static int rtsp_probe(AVProbeData *p)
  651. {
  652. if (
  653. #if CONFIG_TLS_PROTOCOL
  654. av_strstart(p->filename, "rtsps:", NULL) ||
  655. #endif
  656. av_strstart(p->filename, "rtsp:", NULL))
  657. return AVPROBE_SCORE_MAX;
  658. return 0;
  659. }
  660. static int rtsp_read_header(AVFormatContext *s)
  661. {
  662. RTSPState *rt = s->priv_data;
  663. int ret;
  664. if (rt->initial_timeout > 0)
  665. rt->rtsp_flags |= RTSP_FLAG_LISTEN;
  666. if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
  667. ret = rtsp_listen(s);
  668. if (ret)
  669. return ret;
  670. } else {
  671. ret = ff_rtsp_connect(s);
  672. if (ret)
  673. return ret;
  674. rt->real_setup_cache = !s->nb_streams ? NULL :
  675. av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
  676. if (!rt->real_setup_cache && s->nb_streams)
  677. return AVERROR(ENOMEM);
  678. rt->real_setup = rt->real_setup_cache + s->nb_streams;
  679. if (rt->initial_pause) {
  680. /* do not start immediately */
  681. } else {
  682. if (rtsp_read_play(s) < 0) {
  683. ff_rtsp_close_streams(s);
  684. ff_rtsp_close_connections(s);
  685. return AVERROR_INVALIDDATA;
  686. }
  687. }
  688. }
  689. return 0;
  690. }
  691. int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  692. uint8_t *buf, int buf_size)
  693. {
  694. RTSPState *rt = s->priv_data;
  695. int id, len, i, ret;
  696. RTSPStream *rtsp_st;
  697. av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n");
  698. redo:
  699. for (;;) {
  700. RTSPMessageHeader reply;
  701. ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
  702. if (ret < 0)
  703. return ret;
  704. if (ret == 1) /* received '$' */
  705. break;
  706. /* XXX: parse message */
  707. if (rt->state != RTSP_STATE_STREAMING)
  708. return 0;
  709. }
  710. ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
  711. if (ret != 3)
  712. return -1;
  713. id = buf[0];
  714. len = AV_RB16(buf + 1);
  715. av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len);
  716. if (len > buf_size || len < 12)
  717. goto redo;
  718. /* get the data */
  719. ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
  720. if (ret != len)
  721. return -1;
  722. if (rt->transport == RTSP_TRANSPORT_RDT &&
  723. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  724. return -1;
  725. /* find the matching stream */
  726. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  727. rtsp_st = rt->rtsp_streams[i];
  728. if (id >= rtsp_st->interleaved_min &&
  729. id <= rtsp_st->interleaved_max)
  730. goto found;
  731. }
  732. goto redo;
  733. found:
  734. *prtsp_st = rtsp_st;
  735. return len;
  736. }
  737. static int resetup_tcp(AVFormatContext *s)
  738. {
  739. RTSPState *rt = s->priv_data;
  740. char host[1024];
  741. int port;
  742. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
  743. s->filename);
  744. ff_rtsp_undo_setup(s, 0);
  745. return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
  746. rt->real_challenge);
  747. }
  748. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  749. {
  750. RTSPState *rt = s->priv_data;
  751. int ret;
  752. RTSPMessageHeader reply1, *reply = &reply1;
  753. char cmd[1024];
  754. retry:
  755. if (rt->server_type == RTSP_SERVER_REAL) {
  756. int i;
  757. for (i = 0; i < s->nb_streams; i++)
  758. rt->real_setup[i] = s->streams[i]->discard;
  759. if (!rt->need_subscription) {
  760. if (memcmp (rt->real_setup, rt->real_setup_cache,
  761. sizeof(enum AVDiscard) * s->nb_streams)) {
  762. snprintf(cmd, sizeof(cmd),
  763. "Unsubscribe: %s\r\n",
  764. rt->last_subscription);
  765. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  766. cmd, reply, NULL);
  767. if (reply->status_code != RTSP_STATUS_OK)
  768. return AVERROR_INVALIDDATA;
  769. rt->need_subscription = 1;
  770. }
  771. }
  772. if (rt->need_subscription) {
  773. int r, rule_nr, first = 1;
  774. memcpy(rt->real_setup_cache, rt->real_setup,
  775. sizeof(enum AVDiscard) * s->nb_streams);
  776. rt->last_subscription[0] = 0;
  777. snprintf(cmd, sizeof(cmd),
  778. "Subscribe: ");
  779. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  780. rule_nr = 0;
  781. for (r = 0; r < s->nb_streams; r++) {
  782. if (s->streams[r]->id == i) {
  783. if (s->streams[r]->discard != AVDISCARD_ALL) {
  784. if (!first)
  785. av_strlcat(rt->last_subscription, ",",
  786. sizeof(rt->last_subscription));
  787. ff_rdt_subscribe_rule(
  788. rt->last_subscription,
  789. sizeof(rt->last_subscription), i, rule_nr);
  790. first = 0;
  791. }
  792. rule_nr++;
  793. }
  794. }
  795. }
  796. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  797. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  798. cmd, reply, NULL);
  799. if (reply->status_code != RTSP_STATUS_OK)
  800. return AVERROR_INVALIDDATA;
  801. rt->need_subscription = 0;
  802. if (rt->state == RTSP_STATE_STREAMING)
  803. rtsp_read_play (s);
  804. }
  805. }
  806. ret = ff_rtsp_fetch_packet(s, pkt);
  807. if (ret < 0) {
  808. if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
  809. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  810. rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
  811. RTSPMessageHeader reply1, *reply = &reply1;
  812. av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
  813. if (rtsp_read_pause(s) != 0)
  814. return -1;
  815. // TEARDOWN is required on Real-RTSP, but might make
  816. // other servers close the connection.
  817. if (rt->server_type == RTSP_SERVER_REAL)
  818. ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
  819. reply, NULL);
  820. rt->session_id[0] = '\0';
  821. if (resetup_tcp(s) == 0) {
  822. rt->state = RTSP_STATE_IDLE;
  823. rt->need_subscription = 1;
  824. if (rtsp_read_play(s) != 0)
  825. return -1;
  826. goto retry;
  827. }
  828. }
  829. }
  830. return ret;
  831. }
  832. rt->packets++;
  833. if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
  834. /* send dummy request to keep TCP connection alive */
  835. if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
  836. rt->auth_state.stale) {
  837. if (rt->server_type == RTSP_SERVER_WMS ||
  838. (rt->server_type != RTSP_SERVER_REAL &&
  839. rt->get_parameter_supported)) {
  840. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  841. } else {
  842. ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
  843. }
  844. /* The stale flag should be reset when creating the auth response in
  845. * ff_rtsp_send_cmd_async, but reset it here just in case we never
  846. * called the auth code (if we didn't have any credentials set). */
  847. rt->auth_state.stale = 0;
  848. }
  849. }
  850. return 0;
  851. }
  852. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  853. int64_t timestamp, int flags)
  854. {
  855. RTSPState *rt = s->priv_data;
  856. rt->seek_timestamp = av_rescale_q(timestamp,
  857. s->streams[stream_index]->time_base,
  858. AV_TIME_BASE_Q);
  859. switch(rt->state) {
  860. default:
  861. case RTSP_STATE_IDLE:
  862. break;
  863. case RTSP_STATE_STREAMING:
  864. if (rtsp_read_pause(s) != 0)
  865. return -1;
  866. rt->state = RTSP_STATE_SEEKING;
  867. if (rtsp_read_play(s) != 0)
  868. return -1;
  869. break;
  870. case RTSP_STATE_PAUSED:
  871. rt->state = RTSP_STATE_IDLE;
  872. break;
  873. }
  874. return 0;
  875. }
  876. static const AVClass rtsp_demuxer_class = {
  877. .class_name = "RTSP demuxer",
  878. .item_name = av_default_item_name,
  879. .option = ff_rtsp_options,
  880. .version = LIBAVUTIL_VERSION_INT,
  881. };
  882. AVInputFormat ff_rtsp_demuxer = {
  883. .name = "rtsp",
  884. .long_name = NULL_IF_CONFIG_SMALL("RTSP input"),
  885. .priv_data_size = sizeof(RTSPState),
  886. .read_probe = rtsp_probe,
  887. .read_header = rtsp_read_header,
  888. .read_packet = rtsp_read_packet,
  889. .read_close = rtsp_read_close,
  890. .read_seek = rtsp_read_seek,
  891. .flags = AVFMT_NOFILE,
  892. .read_play = rtsp_read_play,
  893. .read_pause = rtsp_read_pause,
  894. .priv_class = &rtsp_demuxer_class,
  895. };