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.

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