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.

999 lines
34KB

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