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.

976 lines
33KB

  1. /*
  2. * RTSP demuxer
  3. * Copyright (c) 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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(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);
  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. av_log(s, AV_LOG_ERROR, "Error parsing method string\n");
  342. return AVERROR_INVALIDDATA;
  343. }
  344. if (linept - line > methodsize - 1) {
  345. av_log(s, AV_LOG_ERROR, "Method string too long\n");
  346. return AVERROR(EIO);
  347. }
  348. memcpy(method, line, linept - line);
  349. method[linept - line] = '\0';
  350. linept++;
  351. if (!strcmp(method, "ANNOUNCE"))
  352. *methodcode = ANNOUNCE;
  353. else if (!strcmp(method, "OPTIONS"))
  354. *methodcode = OPTIONS;
  355. else if (!strcmp(method, "RECORD"))
  356. *methodcode = RECORD;
  357. else if (!strcmp(method, "SETUP"))
  358. *methodcode = SETUP;
  359. else if (!strcmp(method, "PAUSE"))
  360. *methodcode = PAUSE;
  361. else if (!strcmp(method, "TEARDOWN"))
  362. *methodcode = TEARDOWN;
  363. else
  364. *methodcode = UNKNOWN;
  365. /* Check method with the state */
  366. if (rt->state == RTSP_STATE_IDLE) {
  367. if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
  368. av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
  369. line);
  370. return AVERROR_PROTOCOL_NOT_FOUND;
  371. }
  372. } else if (rt->state == RTSP_STATE_PAUSED) {
  373. if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
  374. && (*methodcode != SETUP)) {
  375. av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
  376. line);
  377. return AVERROR_PROTOCOL_NOT_FOUND;
  378. }
  379. } else if (rt->state == RTSP_STATE_STREAMING) {
  380. if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
  381. && (*methodcode != TEARDOWN)) {
  382. av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
  383. " %s\n", line);
  384. return AVERROR_PROTOCOL_NOT_FOUND;
  385. }
  386. } else {
  387. av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
  388. return AVERROR_BUG;
  389. }
  390. searchlinept = strchr(linept, ' ');
  391. if (!searchlinept) {
  392. av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
  393. return AVERROR_INVALIDDATA;
  394. }
  395. if (searchlinept - linept > urisize - 1) {
  396. av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
  397. return AVERROR(EIO);
  398. }
  399. memcpy(uri, linept, searchlinept - linept);
  400. uri[searchlinept - linept] = '\0';
  401. if (strcmp(rt->control_uri, uri)) {
  402. char host[128], path[512], auth[128];
  403. int port;
  404. char ctl_host[128], ctl_path[512], ctl_auth[128];
  405. int ctl_port;
  406. av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
  407. path, sizeof(path), uri);
  408. av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
  409. sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
  410. rt->control_uri);
  411. if (strcmp(host, ctl_host))
  412. av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
  413. host, ctl_host);
  414. if (strcmp(path, ctl_path) && *methodcode != SETUP)
  415. av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
  416. " %s\n", path, ctl_path);
  417. if (*methodcode == ANNOUNCE) {
  418. av_log(s, AV_LOG_INFO,
  419. "Updating control URI to %s\n", uri);
  420. av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
  421. }
  422. }
  423. linept = searchlinept + 1;
  424. if (!av_strstart(linept, "RTSP/1.0", NULL)) {
  425. av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
  426. return AVERROR_PROTOCOL_NOT_FOUND;
  427. }
  428. return 0;
  429. }
  430. int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
  431. {
  432. RTSPState *rt = s->priv_data;
  433. unsigned char rbuf[4096];
  434. unsigned char method[10];
  435. char uri[500];
  436. int ret;
  437. int rbuflen = 0;
  438. RTSPMessageHeader request = { 0 };
  439. enum RTSPMethod methodcode;
  440. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  441. if (ret < 0)
  442. return ret;
  443. ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
  444. sizeof(method), &methodcode);
  445. if (ret) {
  446. av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
  447. return ret;
  448. }
  449. ret = rtsp_read_request(s, &request, method);
  450. if (ret)
  451. return ret;
  452. rt->seq++;
  453. if (methodcode == PAUSE) {
  454. rt->state = RTSP_STATE_PAUSED;
  455. ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
  456. // TODO: Missing date header in response
  457. } else if (methodcode == OPTIONS) {
  458. ret = rtsp_send_reply(s, RTSP_STATUS_OK,
  459. "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
  460. "RECORD\r\n", request.seq);
  461. } else if (methodcode == TEARDOWN) {
  462. rt->state = RTSP_STATE_IDLE;
  463. ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
  464. return 0;
  465. }
  466. return ret;
  467. }
  468. static int rtsp_read_play(AVFormatContext *s)
  469. {
  470. RTSPState *rt = s->priv_data;
  471. RTSPMessageHeader reply1, *reply = &reply1;
  472. int i;
  473. char cmd[1024];
  474. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  475. rt->nb_byes = 0;
  476. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  477. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  478. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  479. /* Try to initialize the connection state in a
  480. * potential NAT router by sending dummy packets.
  481. * RTP/RTCP dummy packets are used for RDT, too.
  482. */
  483. if (rtsp_st->rtp_handle &&
  484. !(rt->server_type == RTSP_SERVER_WMS && i > 1))
  485. ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
  486. }
  487. }
  488. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  489. if (rt->transport == RTSP_TRANSPORT_RTP) {
  490. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  491. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  492. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  493. if (!rtpctx)
  494. continue;
  495. ff_rtp_reset_packet_queue(rtpctx);
  496. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  497. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  498. rtpctx->base_timestamp = 0;
  499. rtpctx->timestamp = 0;
  500. rtpctx->unwrapped_timestamp = 0;
  501. rtpctx->rtcp_ts_offset = 0;
  502. }
  503. }
  504. if (rt->state == RTSP_STATE_PAUSED) {
  505. cmd[0] = 0;
  506. } else {
  507. snprintf(cmd, sizeof(cmd),
  508. "Range: npt=%"PRId64".%03"PRId64"-\r\n",
  509. rt->seek_timestamp / AV_TIME_BASE,
  510. rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
  511. }
  512. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  513. if (reply->status_code != RTSP_STATUS_OK) {
  514. return ff_rtsp_averror(reply->status_code, -1);
  515. }
  516. if (rt->transport == RTSP_TRANSPORT_RTP &&
  517. reply->range_start != AV_NOPTS_VALUE) {
  518. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  519. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  520. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  521. AVStream *st = NULL;
  522. if (!rtpctx || rtsp_st->stream_index < 0)
  523. continue;
  524. st = s->streams[rtsp_st->stream_index];
  525. rtpctx->range_start_offset =
  526. av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
  527. st->time_base);
  528. }
  529. }
  530. }
  531. rt->state = RTSP_STATE_STREAMING;
  532. return 0;
  533. }
  534. /* pause the stream */
  535. static int rtsp_read_pause(AVFormatContext *s)
  536. {
  537. RTSPState *rt = s->priv_data;
  538. RTSPMessageHeader reply1, *reply = &reply1;
  539. if (rt->state != RTSP_STATE_STREAMING)
  540. return 0;
  541. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  542. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  543. if (reply->status_code != RTSP_STATUS_OK) {
  544. return ff_rtsp_averror(reply->status_code, -1);
  545. }
  546. }
  547. rt->state = RTSP_STATE_PAUSED;
  548. return 0;
  549. }
  550. int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  551. {
  552. RTSPState *rt = s->priv_data;
  553. char cmd[1024];
  554. unsigned char *content = NULL;
  555. int ret;
  556. /* describe the stream */
  557. snprintf(cmd, sizeof(cmd),
  558. "Accept: application/sdp\r\n");
  559. if (rt->server_type == RTSP_SERVER_REAL) {
  560. /**
  561. * The Require: attribute is needed for proper streaming from
  562. * Realmedia servers.
  563. */
  564. av_strlcat(cmd,
  565. "Require: com.real.retain-entity-for-setup\r\n",
  566. sizeof(cmd));
  567. }
  568. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  569. if (reply->status_code != RTSP_STATUS_OK) {
  570. av_freep(&content);
  571. return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
  572. }
  573. if (!content)
  574. return AVERROR_INVALIDDATA;
  575. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
  576. /* now we got the SDP description, we parse it */
  577. ret = ff_sdp_parse(s, (const char *)content);
  578. av_freep(&content);
  579. if (ret < 0)
  580. return ret;
  581. return 0;
  582. }
  583. static int rtsp_listen(AVFormatContext *s)
  584. {
  585. RTSPState *rt = s->priv_data;
  586. char proto[128], host[128], path[512], auth[128];
  587. char uri[500];
  588. int port;
  589. int default_port = RTSP_DEFAULT_PORT;
  590. char tcpname[500];
  591. const char *lower_proto = "tcp";
  592. unsigned char rbuf[4096];
  593. unsigned char method[10];
  594. int rbuflen = 0;
  595. int ret;
  596. enum RTSPMethod methodcode;
  597. /* extract hostname and port */
  598. av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
  599. &port, path, sizeof(path), s->filename);
  600. /* ff_url_join. No authorization by now (NULL) */
  601. ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
  602. port, "%s", path);
  603. if (!strcmp(proto, "rtsps")) {
  604. lower_proto = "tls";
  605. default_port = RTSPS_DEFAULT_PORT;
  606. }
  607. if (port < 0)
  608. port = default_port;
  609. /* Create TCP connection */
  610. ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
  611. "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
  612. if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
  613. &s->interrupt_callback, NULL)) {
  614. av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
  615. return ret;
  616. }
  617. rt->state = RTSP_STATE_IDLE;
  618. rt->rtsp_hd_out = rt->rtsp_hd;
  619. for (;;) { /* Wait for incoming RTSP messages */
  620. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  621. if (ret < 0)
  622. return ret;
  623. ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
  624. sizeof(method), &methodcode);
  625. if (ret) {
  626. av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
  627. return ret;
  628. }
  629. if (methodcode == ANNOUNCE) {
  630. ret = rtsp_read_announce(s);
  631. rt->state = RTSP_STATE_PAUSED;
  632. } else if (methodcode == OPTIONS) {
  633. ret = rtsp_read_options(s);
  634. } else if (methodcode == RECORD) {
  635. ret = rtsp_read_record(s);
  636. if (!ret)
  637. return 0; // We are ready for streaming
  638. } else if (methodcode == SETUP)
  639. ret = rtsp_read_setup(s, host, uri);
  640. if (ret) {
  641. ffurl_close(rt->rtsp_hd);
  642. return AVERROR_INVALIDDATA;
  643. }
  644. }
  645. return 0;
  646. }
  647. static int rtsp_probe(AVProbeData *p)
  648. {
  649. if (
  650. #if CONFIG_TLS_PROTOCOL
  651. av_strstart(p->filename, "rtsps:", NULL) ||
  652. #endif
  653. av_strstart(p->filename, "rtsp:", NULL))
  654. return AVPROBE_SCORE_MAX;
  655. return 0;
  656. }
  657. static int rtsp_read_header(AVFormatContext *s)
  658. {
  659. RTSPState *rt = s->priv_data;
  660. int ret;
  661. if (rt->initial_timeout > 0)
  662. rt->rtsp_flags |= RTSP_FLAG_LISTEN;
  663. if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
  664. ret = rtsp_listen(s);
  665. if (ret)
  666. return ret;
  667. } else {
  668. ret = ff_rtsp_connect(s);
  669. if (ret)
  670. return ret;
  671. rt->real_setup_cache = !s->nb_streams ? NULL :
  672. av_mallocz_array(s->nb_streams, 2 * sizeof(*rt->real_setup_cache));
  673. if (!rt->real_setup_cache && s->nb_streams)
  674. return AVERROR(ENOMEM);
  675. rt->real_setup = rt->real_setup_cache + s->nb_streams;
  676. if (rt->initial_pause) {
  677. /* do not start immediately */
  678. } else {
  679. if ((ret = rtsp_read_play(s)) < 0) {
  680. ff_rtsp_close_streams(s);
  681. ff_rtsp_close_connections(s);
  682. return ret;
  683. }
  684. }
  685. }
  686. return 0;
  687. }
  688. int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  689. uint8_t *buf, int buf_size)
  690. {
  691. RTSPState *rt = s->priv_data;
  692. int id, len, i, ret;
  693. RTSPStream *rtsp_st;
  694. av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n");
  695. redo:
  696. for (;;) {
  697. RTSPMessageHeader reply;
  698. ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
  699. if (ret < 0)
  700. return ret;
  701. if (ret == 1) /* received '$' */
  702. break;
  703. /* XXX: parse message */
  704. if (rt->state != RTSP_STATE_STREAMING)
  705. return 0;
  706. }
  707. ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
  708. if (ret != 3)
  709. return -1;
  710. id = buf[0];
  711. len = AV_RB16(buf + 1);
  712. av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len);
  713. if (len > buf_size || len < 8)
  714. goto redo;
  715. /* get the data */
  716. ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
  717. if (ret != len)
  718. return -1;
  719. if (rt->transport == RTSP_TRANSPORT_RDT &&
  720. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  721. return -1;
  722. /* find the matching stream */
  723. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  724. rtsp_st = rt->rtsp_streams[i];
  725. if (id >= rtsp_st->interleaved_min &&
  726. id <= rtsp_st->interleaved_max)
  727. goto found;
  728. }
  729. goto redo;
  730. found:
  731. *prtsp_st = rtsp_st;
  732. return len;
  733. }
  734. static int resetup_tcp(AVFormatContext *s)
  735. {
  736. RTSPState *rt = s->priv_data;
  737. char host[1024];
  738. int port;
  739. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
  740. s->filename);
  741. ff_rtsp_undo_setup(s, 0);
  742. return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
  743. rt->real_challenge);
  744. }
  745. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  746. {
  747. RTSPState *rt = s->priv_data;
  748. int ret;
  749. RTSPMessageHeader reply1, *reply = &reply1;
  750. char cmd[1024];
  751. retry:
  752. if (rt->server_type == RTSP_SERVER_REAL) {
  753. int i;
  754. for (i = 0; i < s->nb_streams; i++)
  755. rt->real_setup[i] = s->streams[i]->discard;
  756. if (!rt->need_subscription) {
  757. if (memcmp (rt->real_setup, rt->real_setup_cache,
  758. sizeof(enum AVDiscard) * s->nb_streams)) {
  759. snprintf(cmd, sizeof(cmd),
  760. "Unsubscribe: %s\r\n",
  761. rt->last_subscription);
  762. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  763. cmd, reply, NULL);
  764. if (reply->status_code != RTSP_STATUS_OK)
  765. return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
  766. rt->need_subscription = 1;
  767. }
  768. }
  769. if (rt->need_subscription) {
  770. int r, rule_nr, first = 1;
  771. memcpy(rt->real_setup_cache, rt->real_setup,
  772. sizeof(enum AVDiscard) * s->nb_streams);
  773. rt->last_subscription[0] = 0;
  774. snprintf(cmd, sizeof(cmd),
  775. "Subscribe: ");
  776. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  777. rule_nr = 0;
  778. for (r = 0; r < s->nb_streams; r++) {
  779. if (s->streams[r]->id == i) {
  780. if (s->streams[r]->discard != AVDISCARD_ALL) {
  781. if (!first)
  782. av_strlcat(rt->last_subscription, ",",
  783. sizeof(rt->last_subscription));
  784. ff_rdt_subscribe_rule(
  785. rt->last_subscription,
  786. sizeof(rt->last_subscription), i, rule_nr);
  787. first = 0;
  788. }
  789. rule_nr++;
  790. }
  791. }
  792. }
  793. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  794. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  795. cmd, reply, NULL);
  796. if (reply->status_code != RTSP_STATUS_OK)
  797. return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
  798. rt->need_subscription = 0;
  799. if (rt->state == RTSP_STATE_STREAMING)
  800. rtsp_read_play (s);
  801. }
  802. }
  803. ret = ff_rtsp_fetch_packet(s, pkt);
  804. if (ret < 0) {
  805. if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
  806. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  807. rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
  808. RTSPMessageHeader reply1, *reply = &reply1;
  809. av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
  810. if (rtsp_read_pause(s) != 0)
  811. return -1;
  812. // TEARDOWN is required on Real-RTSP, but might make
  813. // other servers close the connection.
  814. if (rt->server_type == RTSP_SERVER_REAL)
  815. ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
  816. reply, NULL);
  817. rt->session_id[0] = '\0';
  818. if (resetup_tcp(s) == 0) {
  819. rt->state = RTSP_STATE_IDLE;
  820. rt->need_subscription = 1;
  821. if (rtsp_read_play(s) != 0)
  822. return -1;
  823. goto retry;
  824. }
  825. }
  826. }
  827. return ret;
  828. }
  829. rt->packets++;
  830. if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
  831. /* send dummy request to keep TCP connection alive */
  832. if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
  833. rt->auth_state.stale) {
  834. if (rt->server_type == RTSP_SERVER_WMS ||
  835. (rt->server_type != RTSP_SERVER_REAL &&
  836. rt->get_parameter_supported)) {
  837. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  838. } else {
  839. ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
  840. }
  841. /* The stale flag should be reset when creating the auth response in
  842. * ff_rtsp_send_cmd_async, but reset it here just in case we never
  843. * called the auth code (if we didn't have any credentials set). */
  844. rt->auth_state.stale = 0;
  845. }
  846. }
  847. return 0;
  848. }
  849. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  850. int64_t timestamp, int flags)
  851. {
  852. RTSPState *rt = s->priv_data;
  853. int ret;
  854. rt->seek_timestamp = av_rescale_q(timestamp,
  855. s->streams[stream_index]->time_base,
  856. AV_TIME_BASE_Q);
  857. switch(rt->state) {
  858. default:
  859. case RTSP_STATE_IDLE:
  860. break;
  861. case RTSP_STATE_STREAMING:
  862. if ((ret = rtsp_read_pause(s)) != 0)
  863. return ret;
  864. rt->state = RTSP_STATE_SEEKING;
  865. if ((ret = rtsp_read_play(s)) != 0)
  866. return ret;
  867. break;
  868. case RTSP_STATE_PAUSED:
  869. rt->state = RTSP_STATE_IDLE;
  870. break;
  871. }
  872. return 0;
  873. }
  874. static const AVClass rtsp_demuxer_class = {
  875. .class_name = "RTSP demuxer",
  876. .item_name = av_default_item_name,
  877. .option = ff_rtsp_options,
  878. .version = LIBAVUTIL_VERSION_INT,
  879. };
  880. AVInputFormat ff_rtsp_demuxer = {
  881. .name = "rtsp",
  882. .long_name = NULL_IF_CONFIG_SMALL("RTSP input"),
  883. .priv_data_size = sizeof(RTSPState),
  884. .read_probe = rtsp_probe,
  885. .read_header = rtsp_read_header,
  886. .read_packet = rtsp_read_packet,
  887. .read_close = rtsp_read_close,
  888. .read_seek = rtsp_read_seek,
  889. .flags = AVFMT_NOFILE,
  890. .read_play = rtsp_read_play,
  891. .read_pause = rtsp_read_pause,
  892. .priv_class = &rtsp_demuxer_class,
  893. };