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.

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