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.

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