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.

2130 lines
72KB

  1. /*
  2. * RTSP/SDP client
  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/base64.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/random_seed.h"
  25. #include "avformat.h"
  26. #include <sys/time.h>
  27. #if HAVE_SYS_SELECT_H
  28. #include <sys/select.h>
  29. #endif
  30. #include <strings.h>
  31. #include "internal.h"
  32. #include "network.h"
  33. #include "os_support.h"
  34. #include "http.h"
  35. #include "rtsp.h"
  36. #include "rtpdec.h"
  37. #include "rdt.h"
  38. #include "rtpdec_formats.h"
  39. //#define DEBUG
  40. //#define DEBUG_RTP_TCP
  41. #if LIBAVFORMAT_VERSION_INT < (53 << 16)
  42. int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
  43. #endif
  44. /* Timeout values for socket select, in ms,
  45. * and read_packet(), in seconds */
  46. #define SELECT_TIMEOUT_MS 100
  47. #define READ_PACKET_TIMEOUT_S 10
  48. #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
  49. #define SDP_MAX_SIZE 16384
  50. #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
  51. static void get_word_until_chars(char *buf, int buf_size,
  52. const char *sep, const char **pp)
  53. {
  54. const char *p;
  55. char *q;
  56. p = *pp;
  57. p += strspn(p, SPACE_CHARS);
  58. q = buf;
  59. while (!strchr(sep, *p) && *p != '\0') {
  60. if ((q - buf) < buf_size - 1)
  61. *q++ = *p;
  62. p++;
  63. }
  64. if (buf_size > 0)
  65. *q = '\0';
  66. *pp = p;
  67. }
  68. static void get_word_sep(char *buf, int buf_size, const char *sep,
  69. const char **pp)
  70. {
  71. if (**pp == '/') (*pp)++;
  72. get_word_until_chars(buf, buf_size, sep, pp);
  73. }
  74. static void get_word(char *buf, int buf_size, const char **pp)
  75. {
  76. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  77. }
  78. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  79. static int sdp_parse_rtpmap(AVFormatContext *s,
  80. AVCodecContext *codec, RTSPStream *rtsp_st,
  81. int payload_type, const char *p)
  82. {
  83. char buf[256];
  84. int i;
  85. AVCodec *c;
  86. const char *c_name;
  87. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  88. * see if we can handle this kind of payload.
  89. * The space should normally not be there but some Real streams or
  90. * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
  91. * have a trailing space. */
  92. get_word_sep(buf, sizeof(buf), "/ ", &p);
  93. if (payload_type >= RTP_PT_PRIVATE) {
  94. RTPDynamicProtocolHandler *handler;
  95. for (handler = RTPFirstDynamicPayloadHandler;
  96. handler; handler = handler->next) {
  97. if (!strcasecmp(buf, handler->enc_name) &&
  98. codec->codec_type == handler->codec_type) {
  99. codec->codec_id = handler->codec_id;
  100. rtsp_st->dynamic_handler = handler;
  101. if (handler->open)
  102. rtsp_st->dynamic_protocol_context = handler->open();
  103. break;
  104. }
  105. }
  106. /* If no dynamic handler was found, check with the list of standard
  107. * allocated types, if such a stream for some reason happens to
  108. * use a private payload type. This isn't handled in rtpdec.c, since
  109. * the format name from the rtpmap line never is passed into rtpdec. */
  110. if (!rtsp_st->dynamic_handler)
  111. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  112. } else {
  113. /* We are in a standard case
  114. * (from http://www.iana.org/assignments/rtp-parameters). */
  115. /* search into AVRtpPayloadTypes[] */
  116. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  117. }
  118. c = avcodec_find_decoder(codec->codec_id);
  119. if (c && c->name)
  120. c_name = c->name;
  121. else
  122. c_name = "(null)";
  123. get_word_sep(buf, sizeof(buf), "/", &p);
  124. i = atoi(buf);
  125. switch (codec->codec_type) {
  126. case AVMEDIA_TYPE_AUDIO:
  127. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  128. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  129. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  130. if (i > 0) {
  131. codec->sample_rate = i;
  132. get_word_sep(buf, sizeof(buf), "/", &p);
  133. i = atoi(buf);
  134. if (i > 0)
  135. codec->channels = i;
  136. // TODO: there is a bug here; if it is a mono stream, and
  137. // less than 22000Hz, faad upconverts to stereo and twice
  138. // the frequency. No problem, but the sample rate is being
  139. // set here by the sdp line. Patch on its way. (rdm)
  140. }
  141. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  142. codec->sample_rate);
  143. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  144. codec->channels);
  145. break;
  146. case AVMEDIA_TYPE_VIDEO:
  147. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  148. break;
  149. default:
  150. break;
  151. }
  152. return 0;
  153. }
  154. /* parse the attribute line from the fmtp a line of an sdp response. This
  155. * is broken out as a function because it is used in rtp_h264.c, which is
  156. * forthcoming. */
  157. int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
  158. char *value, int value_size)
  159. {
  160. *p += strspn(*p, SPACE_CHARS);
  161. if (**p) {
  162. get_word_sep(attr, attr_size, "=", p);
  163. if (**p == '=')
  164. (*p)++;
  165. get_word_sep(value, value_size, ";", p);
  166. if (**p == ';')
  167. (*p)++;
  168. return 1;
  169. }
  170. return 0;
  171. }
  172. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  173. * and end time.
  174. * Used for seeking in the rtp stream.
  175. */
  176. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  177. {
  178. char buf[256];
  179. p += strspn(p, SPACE_CHARS);
  180. if (!av_stristart(p, "npt=", &p))
  181. return;
  182. *start = AV_NOPTS_VALUE;
  183. *end = AV_NOPTS_VALUE;
  184. get_word_sep(buf, sizeof(buf), "-", &p);
  185. *start = parse_date(buf, 1);
  186. if (*p == '-') {
  187. p++;
  188. get_word_sep(buf, sizeof(buf), "-", &p);
  189. *end = parse_date(buf, 1);
  190. }
  191. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  192. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  193. }
  194. static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
  195. {
  196. struct addrinfo hints, *ai = NULL;
  197. memset(&hints, 0, sizeof(hints));
  198. hints.ai_flags = AI_NUMERICHOST;
  199. if (getaddrinfo(buf, NULL, &hints, &ai))
  200. return -1;
  201. memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
  202. freeaddrinfo(ai);
  203. return 0;
  204. }
  205. typedef struct SDPParseState {
  206. /* SDP only */
  207. struct sockaddr_storage default_ip;
  208. int default_ttl;
  209. int skip_media; ///< set if an unknown m= line occurs
  210. } SDPParseState;
  211. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  212. int letter, const char *buf)
  213. {
  214. RTSPState *rt = s->priv_data;
  215. char buf1[64], st_type[64];
  216. const char *p;
  217. enum AVMediaType codec_type;
  218. int payload_type, i;
  219. AVStream *st;
  220. RTSPStream *rtsp_st;
  221. struct sockaddr_storage sdp_ip;
  222. int ttl;
  223. dprintf(s, "sdp: %c='%s'\n", letter, buf);
  224. p = buf;
  225. if (s1->skip_media && letter != 'm')
  226. return;
  227. switch (letter) {
  228. case 'c':
  229. get_word(buf1, sizeof(buf1), &p);
  230. if (strcmp(buf1, "IN") != 0)
  231. return;
  232. get_word(buf1, sizeof(buf1), &p);
  233. if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
  234. return;
  235. get_word_sep(buf1, sizeof(buf1), "/", &p);
  236. if (get_sockaddr(buf1, &sdp_ip))
  237. return;
  238. ttl = 16;
  239. if (*p == '/') {
  240. p++;
  241. get_word_sep(buf1, sizeof(buf1), "/", &p);
  242. ttl = atoi(buf1);
  243. }
  244. if (s->nb_streams == 0) {
  245. s1->default_ip = sdp_ip;
  246. s1->default_ttl = ttl;
  247. } else {
  248. st = s->streams[s->nb_streams - 1];
  249. rtsp_st = st->priv_data;
  250. rtsp_st->sdp_ip = sdp_ip;
  251. rtsp_st->sdp_ttl = ttl;
  252. }
  253. break;
  254. case 's':
  255. av_metadata_set2(&s->metadata, "title", p, 0);
  256. break;
  257. case 'i':
  258. if (s->nb_streams == 0) {
  259. av_metadata_set2(&s->metadata, "comment", p, 0);
  260. break;
  261. }
  262. break;
  263. case 'm':
  264. /* new stream */
  265. s1->skip_media = 0;
  266. get_word(st_type, sizeof(st_type), &p);
  267. if (!strcmp(st_type, "audio")) {
  268. codec_type = AVMEDIA_TYPE_AUDIO;
  269. } else if (!strcmp(st_type, "video")) {
  270. codec_type = AVMEDIA_TYPE_VIDEO;
  271. } else if (!strcmp(st_type, "application")) {
  272. codec_type = AVMEDIA_TYPE_DATA;
  273. } else {
  274. s1->skip_media = 1;
  275. return;
  276. }
  277. rtsp_st = av_mallocz(sizeof(RTSPStream));
  278. if (!rtsp_st)
  279. return;
  280. rtsp_st->stream_index = -1;
  281. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  282. rtsp_st->sdp_ip = s1->default_ip;
  283. rtsp_st->sdp_ttl = s1->default_ttl;
  284. get_word(buf1, sizeof(buf1), &p); /* port */
  285. rtsp_st->sdp_port = atoi(buf1);
  286. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  287. /* XXX: handle list of formats */
  288. get_word(buf1, sizeof(buf1), &p); /* format list */
  289. rtsp_st->sdp_payload_type = atoi(buf1);
  290. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  291. /* no corresponding stream */
  292. } else {
  293. st = av_new_stream(s, 0);
  294. if (!st)
  295. return;
  296. st->priv_data = rtsp_st;
  297. rtsp_st->stream_index = st->index;
  298. st->codec->codec_type = codec_type;
  299. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  300. /* if standard payload type, we can find the codec right now */
  301. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  302. }
  303. }
  304. /* put a default control url */
  305. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  306. sizeof(rtsp_st->control_url));
  307. break;
  308. case 'a':
  309. if (av_strstart(p, "control:", &p)) {
  310. if (s->nb_streams == 0) {
  311. if (!strncmp(p, "rtsp://", 7))
  312. av_strlcpy(rt->control_uri, p,
  313. sizeof(rt->control_uri));
  314. } else {
  315. char proto[32];
  316. /* get the control url */
  317. st = s->streams[s->nb_streams - 1];
  318. rtsp_st = st->priv_data;
  319. /* XXX: may need to add full url resolution */
  320. av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  321. NULL, NULL, 0, p);
  322. if (proto[0] == '\0') {
  323. /* relative control URL */
  324. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  325. av_strlcat(rtsp_st->control_url, "/",
  326. sizeof(rtsp_st->control_url));
  327. av_strlcat(rtsp_st->control_url, p,
  328. sizeof(rtsp_st->control_url));
  329. } else
  330. av_strlcpy(rtsp_st->control_url, p,
  331. sizeof(rtsp_st->control_url));
  332. }
  333. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  334. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  335. get_word(buf1, sizeof(buf1), &p);
  336. payload_type = atoi(buf1);
  337. st = s->streams[s->nb_streams - 1];
  338. rtsp_st = st->priv_data;
  339. sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
  340. } else if (av_strstart(p, "fmtp:", &p) ||
  341. av_strstart(p, "framesize:", &p)) {
  342. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  343. // let dynamic protocol handlers have a stab at the line.
  344. get_word(buf1, sizeof(buf1), &p);
  345. payload_type = atoi(buf1);
  346. for (i = 0; i < s->nb_streams; i++) {
  347. st = s->streams[i];
  348. rtsp_st = st->priv_data;
  349. if (rtsp_st->sdp_payload_type == payload_type &&
  350. rtsp_st->dynamic_handler &&
  351. rtsp_st->dynamic_handler->parse_sdp_a_line)
  352. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  353. rtsp_st->dynamic_protocol_context, buf);
  354. }
  355. } else if (av_strstart(p, "range:", &p)) {
  356. int64_t start, end;
  357. // this is so that seeking on a streamed file can work.
  358. rtsp_parse_range_npt(p, &start, &end);
  359. s->start_time = start;
  360. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  361. s->duration = (end == AV_NOPTS_VALUE) ?
  362. AV_NOPTS_VALUE : end - start;
  363. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  364. if (atoi(p) == 1)
  365. rt->transport = RTSP_TRANSPORT_RDT;
  366. } else {
  367. if (rt->server_type == RTSP_SERVER_WMS)
  368. ff_wms_parse_sdp_a_line(s, p);
  369. if (s->nb_streams > 0) {
  370. if (rt->server_type == RTSP_SERVER_REAL)
  371. ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
  372. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  373. if (rtsp_st->dynamic_handler &&
  374. rtsp_st->dynamic_handler->parse_sdp_a_line)
  375. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  376. s->nb_streams - 1,
  377. rtsp_st->dynamic_protocol_context, buf);
  378. }
  379. }
  380. break;
  381. }
  382. }
  383. static int sdp_parse(AVFormatContext *s, const char *content)
  384. {
  385. const char *p;
  386. int letter;
  387. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  388. * contain long SDP lines containing complete ASF Headers (several
  389. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  390. * "rulebooks" describing their properties. Therefore, the SDP line
  391. * buffer is large.
  392. *
  393. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  394. * in rtpdec_xiph.c. */
  395. char buf[16384], *q;
  396. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  397. memset(s1, 0, sizeof(SDPParseState));
  398. p = content;
  399. for (;;) {
  400. p += strspn(p, SPACE_CHARS);
  401. letter = *p;
  402. if (letter == '\0')
  403. break;
  404. p++;
  405. if (*p != '=')
  406. goto next_line;
  407. p++;
  408. /* get the content */
  409. q = buf;
  410. while (*p != '\n' && *p != '\r' && *p != '\0') {
  411. if ((q - buf) < sizeof(buf) - 1)
  412. *q++ = *p;
  413. p++;
  414. }
  415. *q = '\0';
  416. sdp_parse_line(s, s1, letter, buf);
  417. next_line:
  418. while (*p != '\n' && *p != '\0')
  419. p++;
  420. if (*p == '\n')
  421. p++;
  422. }
  423. return 0;
  424. }
  425. /* close and free RTSP streams */
  426. void ff_rtsp_close_streams(AVFormatContext *s)
  427. {
  428. RTSPState *rt = s->priv_data;
  429. int i;
  430. RTSPStream *rtsp_st;
  431. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  432. rtsp_st = rt->rtsp_streams[i];
  433. if (rtsp_st) {
  434. if (rtsp_st->transport_priv) {
  435. if (s->oformat) {
  436. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  437. av_write_trailer(rtpctx);
  438. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  439. uint8_t *ptr;
  440. url_close_dyn_buf(rtpctx->pb, &ptr);
  441. av_free(ptr);
  442. } else {
  443. url_fclose(rtpctx->pb);
  444. }
  445. av_metadata_free(&rtpctx->streams[0]->metadata);
  446. av_metadata_free(&rtpctx->metadata);
  447. av_free(rtpctx->streams[0]);
  448. av_free(rtpctx);
  449. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  450. ff_rdt_parse_close(rtsp_st->transport_priv);
  451. else
  452. rtp_parse_close(rtsp_st->transport_priv);
  453. }
  454. if (rtsp_st->rtp_handle)
  455. url_close(rtsp_st->rtp_handle);
  456. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  457. rtsp_st->dynamic_handler->close(
  458. rtsp_st->dynamic_protocol_context);
  459. }
  460. }
  461. av_free(rt->rtsp_streams);
  462. if (rt->asf_ctx) {
  463. av_close_input_stream (rt->asf_ctx);
  464. rt->asf_ctx = NULL;
  465. }
  466. av_free(rt->recvbuf);
  467. }
  468. static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
  469. URLContext *handle)
  470. {
  471. RTSPState *rt = s->priv_data;
  472. AVFormatContext *rtpctx;
  473. int ret;
  474. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  475. if (!rtp_format)
  476. return NULL;
  477. /* Allocate an AVFormatContext for each output stream */
  478. rtpctx = avformat_alloc_context();
  479. if (!rtpctx)
  480. return NULL;
  481. rtpctx->oformat = rtp_format;
  482. if (!av_new_stream(rtpctx, 0)) {
  483. av_free(rtpctx);
  484. return NULL;
  485. }
  486. /* Copy the max delay setting; the rtp muxer reads this. */
  487. rtpctx->max_delay = s->max_delay;
  488. /* Copy other stream parameters. */
  489. rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
  490. /* Set the synchronized start time. */
  491. rtpctx->start_time_realtime = rt->start_time;
  492. /* Remove the local codec, link to the original codec
  493. * context instead, to give the rtp muxer access to
  494. * codec parameters. */
  495. av_free(rtpctx->streams[0]->codec);
  496. rtpctx->streams[0]->codec = st->codec;
  497. if (handle) {
  498. url_fdopen(&rtpctx->pb, handle);
  499. } else
  500. url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
  501. ret = av_write_header(rtpctx);
  502. if (ret) {
  503. if (handle) {
  504. url_fclose(rtpctx->pb);
  505. } else {
  506. uint8_t *ptr;
  507. url_close_dyn_buf(rtpctx->pb, &ptr);
  508. av_free(ptr);
  509. }
  510. av_free(rtpctx->streams[0]);
  511. av_free(rtpctx);
  512. return NULL;
  513. }
  514. /* Copy the RTP AVStream timebase back to the original AVStream */
  515. st->time_base = rtpctx->streams[0]->time_base;
  516. return rtpctx;
  517. }
  518. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  519. {
  520. RTSPState *rt = s->priv_data;
  521. AVStream *st = NULL;
  522. /* open the RTP context */
  523. if (rtsp_st->stream_index >= 0)
  524. st = s->streams[rtsp_st->stream_index];
  525. if (!st)
  526. s->ctx_flags |= AVFMTCTX_NOHEADER;
  527. if (s->oformat) {
  528. rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
  529. /* Ownership of rtp_handle is passed to the rtp mux context */
  530. rtsp_st->rtp_handle = NULL;
  531. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  532. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  533. rtsp_st->dynamic_protocol_context,
  534. rtsp_st->dynamic_handler);
  535. else
  536. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  537. rtsp_st->sdp_payload_type);
  538. if (!rtsp_st->transport_priv) {
  539. return AVERROR(ENOMEM);
  540. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  541. if (rtsp_st->dynamic_handler) {
  542. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  543. rtsp_st->dynamic_protocol_context,
  544. rtsp_st->dynamic_handler);
  545. }
  546. }
  547. return 0;
  548. }
  549. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  550. static int rtsp_probe(AVProbeData *p)
  551. {
  552. if (av_strstart(p->filename, "rtsp:", NULL))
  553. return AVPROBE_SCORE_MAX;
  554. return 0;
  555. }
  556. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  557. {
  558. const char *p;
  559. int v;
  560. p = *pp;
  561. p += strspn(p, SPACE_CHARS);
  562. v = strtol(p, (char **)&p, 10);
  563. if (*p == '-') {
  564. p++;
  565. *min_ptr = v;
  566. v = strtol(p, (char **)&p, 10);
  567. *max_ptr = v;
  568. } else {
  569. *min_ptr = v;
  570. *max_ptr = v;
  571. }
  572. *pp = p;
  573. }
  574. /* XXX: only one transport specification is parsed */
  575. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  576. {
  577. char transport_protocol[16];
  578. char profile[16];
  579. char lower_transport[16];
  580. char parameter[16];
  581. RTSPTransportField *th;
  582. char buf[256];
  583. reply->nb_transports = 0;
  584. for (;;) {
  585. p += strspn(p, SPACE_CHARS);
  586. if (*p == '\0')
  587. break;
  588. th = &reply->transports[reply->nb_transports];
  589. get_word_sep(transport_protocol, sizeof(transport_protocol),
  590. "/", &p);
  591. if (!strcasecmp (transport_protocol, "rtp")) {
  592. get_word_sep(profile, sizeof(profile), "/;,", &p);
  593. lower_transport[0] = '\0';
  594. /* rtp/avp/<protocol> */
  595. if (*p == '/') {
  596. get_word_sep(lower_transport, sizeof(lower_transport),
  597. ";,", &p);
  598. }
  599. th->transport = RTSP_TRANSPORT_RTP;
  600. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  601. !strcasecmp (transport_protocol, "x-real-rdt")) {
  602. /* x-pn-tng/<protocol> */
  603. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  604. profile[0] = '\0';
  605. th->transport = RTSP_TRANSPORT_RDT;
  606. }
  607. if (!strcasecmp(lower_transport, "TCP"))
  608. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  609. else
  610. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  611. if (*p == ';')
  612. p++;
  613. /* get each parameter */
  614. while (*p != '\0' && *p != ',') {
  615. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  616. if (!strcmp(parameter, "port")) {
  617. if (*p == '=') {
  618. p++;
  619. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  620. }
  621. } else if (!strcmp(parameter, "client_port")) {
  622. if (*p == '=') {
  623. p++;
  624. rtsp_parse_range(&th->client_port_min,
  625. &th->client_port_max, &p);
  626. }
  627. } else if (!strcmp(parameter, "server_port")) {
  628. if (*p == '=') {
  629. p++;
  630. rtsp_parse_range(&th->server_port_min,
  631. &th->server_port_max, &p);
  632. }
  633. } else if (!strcmp(parameter, "interleaved")) {
  634. if (*p == '=') {
  635. p++;
  636. rtsp_parse_range(&th->interleaved_min,
  637. &th->interleaved_max, &p);
  638. }
  639. } else if (!strcmp(parameter, "multicast")) {
  640. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  641. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  642. } else if (!strcmp(parameter, "ttl")) {
  643. if (*p == '=') {
  644. p++;
  645. th->ttl = strtol(p, (char **)&p, 10);
  646. }
  647. } else if (!strcmp(parameter, "destination")) {
  648. if (*p == '=') {
  649. p++;
  650. get_word_sep(buf, sizeof(buf), ";,", &p);
  651. get_sockaddr(buf, &th->destination);
  652. }
  653. } else if (!strcmp(parameter, "source")) {
  654. if (*p == '=') {
  655. p++;
  656. get_word_sep(buf, sizeof(buf), ";,", &p);
  657. av_strlcpy(th->source, buf, sizeof(th->source));
  658. }
  659. }
  660. while (*p != ';' && *p != '\0' && *p != ',')
  661. p++;
  662. if (*p == ';')
  663. p++;
  664. }
  665. if (*p == ',')
  666. p++;
  667. reply->nb_transports++;
  668. }
  669. }
  670. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  671. HTTPAuthState *auth_state)
  672. {
  673. const char *p;
  674. /* NOTE: we do case independent match for broken servers */
  675. p = buf;
  676. if (av_stristart(p, "Session:", &p)) {
  677. int t;
  678. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  679. if (av_stristart(p, ";timeout=", &p) &&
  680. (t = strtol(p, NULL, 10)) > 0) {
  681. reply->timeout = t;
  682. }
  683. } else if (av_stristart(p, "Content-Length:", &p)) {
  684. reply->content_length = strtol(p, NULL, 10);
  685. } else if (av_stristart(p, "Transport:", &p)) {
  686. rtsp_parse_transport(reply, p);
  687. } else if (av_stristart(p, "CSeq:", &p)) {
  688. reply->seq = strtol(p, NULL, 10);
  689. } else if (av_stristart(p, "Range:", &p)) {
  690. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  691. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  692. p += strspn(p, SPACE_CHARS);
  693. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  694. } else if (av_stristart(p, "Server:", &p)) {
  695. p += strspn(p, SPACE_CHARS);
  696. av_strlcpy(reply->server, p, sizeof(reply->server));
  697. } else if (av_stristart(p, "Notice:", &p) ||
  698. av_stristart(p, "X-Notice:", &p)) {
  699. reply->notice = strtol(p, NULL, 10);
  700. } else if (av_stristart(p, "Location:", &p)) {
  701. p += strspn(p, SPACE_CHARS);
  702. av_strlcpy(reply->location, p , sizeof(reply->location));
  703. } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
  704. p += strspn(p, SPACE_CHARS);
  705. ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
  706. } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
  707. p += strspn(p, SPACE_CHARS);
  708. ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
  709. }
  710. }
  711. /* skip a RTP/TCP interleaved packet */
  712. void ff_rtsp_skip_packet(AVFormatContext *s)
  713. {
  714. RTSPState *rt = s->priv_data;
  715. int ret, len, len1;
  716. uint8_t buf[1024];
  717. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  718. if (ret != 3)
  719. return;
  720. len = AV_RB16(buf + 1);
  721. dprintf(s, "skipping RTP packet len=%d\n", len);
  722. /* skip payload */
  723. while (len > 0) {
  724. len1 = len;
  725. if (len1 > sizeof(buf))
  726. len1 = sizeof(buf);
  727. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  728. if (ret != len1)
  729. return;
  730. len -= len1;
  731. }
  732. }
  733. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  734. unsigned char **content_ptr,
  735. int return_on_interleaved_data)
  736. {
  737. RTSPState *rt = s->priv_data;
  738. char buf[4096], buf1[1024], *q;
  739. unsigned char ch;
  740. const char *p;
  741. int ret, content_length, line_count = 0;
  742. unsigned char *content = NULL;
  743. memset(reply, 0, sizeof(*reply));
  744. /* parse reply (XXX: use buffers) */
  745. rt->last_reply[0] = '\0';
  746. for (;;) {
  747. q = buf;
  748. for (;;) {
  749. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  750. #ifdef DEBUG_RTP_TCP
  751. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  752. #endif
  753. if (ret != 1)
  754. return AVERROR_EOF;
  755. if (ch == '\n')
  756. break;
  757. if (ch == '$') {
  758. /* XXX: only parse it if first char on line ? */
  759. if (return_on_interleaved_data) {
  760. return 1;
  761. } else
  762. ff_rtsp_skip_packet(s);
  763. } else if (ch != '\r') {
  764. if ((q - buf) < sizeof(buf) - 1)
  765. *q++ = ch;
  766. }
  767. }
  768. *q = '\0';
  769. dprintf(s, "line='%s'\n", buf);
  770. /* test if last line */
  771. if (buf[0] == '\0')
  772. break;
  773. p = buf;
  774. if (line_count == 0) {
  775. /* get reply code */
  776. get_word(buf1, sizeof(buf1), &p);
  777. get_word(buf1, sizeof(buf1), &p);
  778. reply->status_code = atoi(buf1);
  779. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  780. } else {
  781. ff_rtsp_parse_line(reply, p, &rt->auth_state);
  782. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  783. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  784. }
  785. line_count++;
  786. }
  787. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  788. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  789. content_length = reply->content_length;
  790. if (content_length > 0) {
  791. /* leave some room for a trailing '\0' (useful for simple parsing) */
  792. content = av_malloc(content_length + 1);
  793. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  794. content[content_length] = '\0';
  795. }
  796. if (content_ptr)
  797. *content_ptr = content;
  798. else
  799. av_free(content);
  800. if (rt->seq != reply->seq) {
  801. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  802. rt->seq, reply->seq);
  803. }
  804. /* EOS */
  805. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  806. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  807. reply->notice == 2306 /* Continuous Feed Terminated */) {
  808. rt->state = RTSP_STATE_IDLE;
  809. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  810. return AVERROR(EIO); /* data or server error */
  811. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  812. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  813. return AVERROR(EPERM);
  814. return 0;
  815. }
  816. int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  817. const char *method, const char *url,
  818. const char *headers,
  819. const unsigned char *send_content,
  820. int send_content_length)
  821. {
  822. RTSPState *rt = s->priv_data;
  823. char buf[4096], *out_buf;
  824. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  825. /* Add in RTSP headers */
  826. out_buf = buf;
  827. rt->seq++;
  828. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  829. if (headers)
  830. av_strlcat(buf, headers, sizeof(buf));
  831. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  832. if (rt->session_id[0] != '\0' && (!headers ||
  833. !strstr(headers, "\nIf-Match:"))) {
  834. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  835. }
  836. if (rt->auth[0]) {
  837. char *str = ff_http_auth_create_response(&rt->auth_state,
  838. rt->auth, url, method);
  839. if (str)
  840. av_strlcat(buf, str, sizeof(buf));
  841. av_free(str);
  842. }
  843. if (send_content_length > 0 && send_content)
  844. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  845. av_strlcat(buf, "\r\n", sizeof(buf));
  846. /* base64 encode rtsp if tunneling */
  847. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  848. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  849. out_buf = base64buf;
  850. }
  851. dprintf(s, "Sending:\n%s--\n", buf);
  852. url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  853. if (send_content_length > 0 && send_content) {
  854. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  855. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  856. "with content data not supported\n");
  857. return AVERROR_PATCHWELCOME;
  858. }
  859. url_write(rt->rtsp_hd_out, send_content, send_content_length);
  860. }
  861. rt->last_cmd_time = av_gettime();
  862. return 0;
  863. }
  864. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  865. const char *url, const char *headers)
  866. {
  867. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  868. }
  869. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  870. const char *headers, RTSPMessageHeader *reply,
  871. unsigned char **content_ptr)
  872. {
  873. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  874. content_ptr, NULL, 0);
  875. }
  876. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  877. const char *method, const char *url,
  878. const char *header,
  879. RTSPMessageHeader *reply,
  880. unsigned char **content_ptr,
  881. const unsigned char *send_content,
  882. int send_content_length)
  883. {
  884. RTSPState *rt = s->priv_data;
  885. HTTPAuthType cur_auth_type;
  886. int ret;
  887. retry:
  888. cur_auth_type = rt->auth_state.auth_type;
  889. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  890. send_content,
  891. send_content_length)))
  892. return ret;
  893. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
  894. return ret;
  895. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  896. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  897. goto retry;
  898. if (reply->status_code > 400){
  899. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  900. method,
  901. reply->status_code,
  902. reply->reason);
  903. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  904. }
  905. return 0;
  906. }
  907. /**
  908. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  909. */
  910. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  911. int lower_transport, const char *real_challenge)
  912. {
  913. RTSPState *rt = s->priv_data;
  914. int rtx, j, i, err, interleave = 0;
  915. RTSPStream *rtsp_st;
  916. RTSPMessageHeader reply1, *reply = &reply1;
  917. char cmd[2048];
  918. const char *trans_pref;
  919. if (rt->transport == RTSP_TRANSPORT_RDT)
  920. trans_pref = "x-pn-tng";
  921. else
  922. trans_pref = "RTP/AVP";
  923. /* default timeout: 1 minute */
  924. rt->timeout = 60;
  925. /* for each stream, make the setup request */
  926. /* XXX: we assume the same server is used for the control of each
  927. * RTSP stream */
  928. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  929. char transport[2048];
  930. /**
  931. * WMS serves all UDP data over a single connection, the RTX, which
  932. * isn't necessarily the first in the SDP but has to be the first
  933. * to be set up, else the second/third SETUP will fail with a 461.
  934. */
  935. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  936. rt->server_type == RTSP_SERVER_WMS) {
  937. if (i == 0) {
  938. /* rtx first */
  939. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  940. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  941. if (len >= 4 &&
  942. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  943. "/rtx"))
  944. break;
  945. }
  946. if (rtx == rt->nb_rtsp_streams)
  947. return -1; /* no RTX found */
  948. rtsp_st = rt->rtsp_streams[rtx];
  949. } else
  950. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  951. } else
  952. rtsp_st = rt->rtsp_streams[i];
  953. /* RTP/UDP */
  954. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  955. char buf[256];
  956. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  957. port = reply->transports[0].client_port_min;
  958. goto have_port;
  959. }
  960. /* first try in specified port range */
  961. if (RTSP_RTP_PORT_MIN != 0) {
  962. while (j <= RTSP_RTP_PORT_MAX) {
  963. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  964. "?localport=%d", j);
  965. /* we will use two ports per rtp stream (rtp and rtcp) */
  966. j += 2;
  967. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  968. goto rtp_opened;
  969. }
  970. }
  971. #if 0
  972. /* then try on any port */
  973. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  974. err = AVERROR_INVALIDDATA;
  975. goto fail;
  976. }
  977. #endif
  978. rtp_opened:
  979. port = rtp_get_local_port(rtsp_st->rtp_handle);
  980. have_port:
  981. snprintf(transport, sizeof(transport) - 1,
  982. "%s/UDP;", trans_pref);
  983. if (rt->server_type != RTSP_SERVER_REAL)
  984. av_strlcat(transport, "unicast;", sizeof(transport));
  985. av_strlcatf(transport, sizeof(transport),
  986. "client_port=%d", port);
  987. if (rt->transport == RTSP_TRANSPORT_RTP &&
  988. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  989. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  990. }
  991. /* RTP/TCP */
  992. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  993. /** For WMS streams, the application streams are only used for
  994. * UDP. When trying to set it up for TCP streams, the server
  995. * will return an error. Therefore, we skip those streams. */
  996. if (rt->server_type == RTSP_SERVER_WMS &&
  997. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  998. AVMEDIA_TYPE_DATA)
  999. continue;
  1000. snprintf(transport, sizeof(transport) - 1,
  1001. "%s/TCP;", trans_pref);
  1002. if (rt->server_type == RTSP_SERVER_WMS)
  1003. av_strlcat(transport, "unicast;", sizeof(transport));
  1004. av_strlcatf(transport, sizeof(transport),
  1005. "interleaved=%d-%d",
  1006. interleave, interleave + 1);
  1007. interleave += 2;
  1008. }
  1009. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1010. snprintf(transport, sizeof(transport) - 1,
  1011. "%s/UDP;multicast", trans_pref);
  1012. }
  1013. if (s->oformat) {
  1014. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1015. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1016. rt->server_type == RTSP_SERVER_WMS)
  1017. av_strlcat(transport, ";mode=play", sizeof(transport));
  1018. snprintf(cmd, sizeof(cmd),
  1019. "Transport: %s\r\n",
  1020. transport);
  1021. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  1022. char real_res[41], real_csum[9];
  1023. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1024. real_challenge);
  1025. av_strlcatf(cmd, sizeof(cmd),
  1026. "If-Match: %s\r\n"
  1027. "RealChallenge2: %s, sd=%s\r\n",
  1028. rt->session_id, real_res, real_csum);
  1029. }
  1030. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1031. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1032. err = 1;
  1033. goto fail;
  1034. } else if (reply->status_code != RTSP_STATUS_OK ||
  1035. reply->nb_transports != 1) {
  1036. err = AVERROR_INVALIDDATA;
  1037. goto fail;
  1038. }
  1039. /* XXX: same protocol for all streams is required */
  1040. if (i > 0) {
  1041. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1042. reply->transports[0].transport != rt->transport) {
  1043. err = AVERROR_INVALIDDATA;
  1044. goto fail;
  1045. }
  1046. } else {
  1047. rt->lower_transport = reply->transports[0].lower_transport;
  1048. rt->transport = reply->transports[0].transport;
  1049. }
  1050. /* close RTP connection if not chosen */
  1051. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1052. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1053. url_close(rtsp_st->rtp_handle);
  1054. rtsp_st->rtp_handle = NULL;
  1055. }
  1056. switch(reply->transports[0].lower_transport) {
  1057. case RTSP_LOWER_TRANSPORT_TCP:
  1058. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1059. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1060. break;
  1061. case RTSP_LOWER_TRANSPORT_UDP: {
  1062. char url[1024];
  1063. /* Use source address if specified */
  1064. if (reply->transports[0].source[0]) {
  1065. ff_url_join(url, sizeof(url), "rtp", NULL,
  1066. reply->transports[0].source,
  1067. reply->transports[0].server_port_min, NULL);
  1068. } else {
  1069. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1070. reply->transports[0].server_port_min, NULL);
  1071. }
  1072. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1073. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1074. err = AVERROR_INVALIDDATA;
  1075. goto fail;
  1076. }
  1077. /* Try to initialize the connection state in a
  1078. * potential NAT router by sending dummy packets.
  1079. * RTP/RTCP dummy packets are used for RDT, too.
  1080. */
  1081. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1082. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1083. break;
  1084. }
  1085. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1086. char url[1024], namebuf[50];
  1087. struct sockaddr_storage addr;
  1088. int port, ttl;
  1089. if (reply->transports[0].destination.ss_family) {
  1090. addr = reply->transports[0].destination;
  1091. port = reply->transports[0].port_min;
  1092. ttl = reply->transports[0].ttl;
  1093. } else {
  1094. addr = rtsp_st->sdp_ip;
  1095. port = rtsp_st->sdp_port;
  1096. ttl = rtsp_st->sdp_ttl;
  1097. }
  1098. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1099. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1100. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1101. port, "?ttl=%d", ttl);
  1102. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1103. err = AVERROR_INVALIDDATA;
  1104. goto fail;
  1105. }
  1106. break;
  1107. }
  1108. }
  1109. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1110. goto fail;
  1111. }
  1112. if (reply->timeout > 0)
  1113. rt->timeout = reply->timeout;
  1114. if (rt->server_type == RTSP_SERVER_REAL)
  1115. rt->need_subscription = 1;
  1116. return 0;
  1117. fail:
  1118. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1119. if (rt->rtsp_streams[i]->rtp_handle) {
  1120. url_close(rt->rtsp_streams[i]->rtp_handle);
  1121. rt->rtsp_streams[i]->rtp_handle = NULL;
  1122. }
  1123. }
  1124. return err;
  1125. }
  1126. static int rtsp_read_play(AVFormatContext *s)
  1127. {
  1128. RTSPState *rt = s->priv_data;
  1129. RTSPMessageHeader reply1, *reply = &reply1;
  1130. int i;
  1131. char cmd[1024];
  1132. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1133. rt->nb_byes = 0;
  1134. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1135. if (rt->state == RTSP_STATE_PAUSED) {
  1136. cmd[0] = 0;
  1137. } else {
  1138. snprintf(cmd, sizeof(cmd),
  1139. "Range: npt=%0.3f-\r\n",
  1140. (double)rt->seek_timestamp / AV_TIME_BASE);
  1141. }
  1142. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  1143. if (reply->status_code != RTSP_STATUS_OK) {
  1144. return -1;
  1145. }
  1146. if (reply->range_start != AV_NOPTS_VALUE &&
  1147. rt->transport == RTSP_TRANSPORT_RTP) {
  1148. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1149. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  1150. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1151. AVStream *st = NULL;
  1152. if (!rtpctx)
  1153. continue;
  1154. if (rtsp_st->stream_index >= 0)
  1155. st = s->streams[rtsp_st->stream_index];
  1156. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  1157. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  1158. if (st)
  1159. rtpctx->range_start_offset = av_rescale_q(reply->range_start,
  1160. AV_TIME_BASE_Q,
  1161. st->time_base);
  1162. }
  1163. }
  1164. }
  1165. rt->state = RTSP_STATE_STREAMING;
  1166. return 0;
  1167. }
  1168. static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  1169. {
  1170. RTSPState *rt = s->priv_data;
  1171. char cmd[1024];
  1172. unsigned char *content = NULL;
  1173. int ret;
  1174. /* describe the stream */
  1175. snprintf(cmd, sizeof(cmd),
  1176. "Accept: application/sdp\r\n");
  1177. if (rt->server_type == RTSP_SERVER_REAL) {
  1178. /**
  1179. * The Require: attribute is needed for proper streaming from
  1180. * Realmedia servers.
  1181. */
  1182. av_strlcat(cmd,
  1183. "Require: com.real.retain-entity-for-setup\r\n",
  1184. sizeof(cmd));
  1185. }
  1186. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  1187. if (!content)
  1188. return AVERROR_INVALIDDATA;
  1189. if (reply->status_code != RTSP_STATUS_OK) {
  1190. av_freep(&content);
  1191. return AVERROR_INVALIDDATA;
  1192. }
  1193. /* now we got the SDP description, we parse it */
  1194. ret = sdp_parse(s, (const char *)content);
  1195. av_freep(&content);
  1196. if (ret < 0)
  1197. return AVERROR_INVALIDDATA;
  1198. return 0;
  1199. }
  1200. static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
  1201. {
  1202. RTSPState *rt = s->priv_data;
  1203. RTSPMessageHeader reply1, *reply = &reply1;
  1204. int i;
  1205. char *sdp;
  1206. AVFormatContext sdp_ctx, *ctx_array[1];
  1207. rt->start_time = av_gettime();
  1208. /* Announce the stream */
  1209. sdp = av_mallocz(SDP_MAX_SIZE);
  1210. if (sdp == NULL)
  1211. return AVERROR(ENOMEM);
  1212. /* We create the SDP based on the RTSP AVFormatContext where we
  1213. * aren't allowed to change the filename field. (We create the SDP
  1214. * based on the RTSP context since the contexts for the RTP streams
  1215. * don't exist yet.) In order to specify a custom URL with the actual
  1216. * peer IP instead of the originally specified hostname, we create
  1217. * a temporary copy of the AVFormatContext, where the custom URL is set.
  1218. *
  1219. * FIXME: Create the SDP without copying the AVFormatContext.
  1220. * This either requires setting up the RTP stream AVFormatContexts
  1221. * already here (complicating things immensely) or getting a more
  1222. * flexible SDP creation interface.
  1223. */
  1224. sdp_ctx = *s;
  1225. ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
  1226. "rtsp", NULL, addr, -1, NULL);
  1227. ctx_array[0] = &sdp_ctx;
  1228. if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
  1229. av_free(sdp);
  1230. return AVERROR_INVALIDDATA;
  1231. }
  1232. av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
  1233. ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
  1234. "Content-Type: application/sdp\r\n",
  1235. reply, NULL, sdp, strlen(sdp));
  1236. av_free(sdp);
  1237. if (reply->status_code != RTSP_STATUS_OK)
  1238. return AVERROR_INVALIDDATA;
  1239. /* Set up the RTSPStreams for each AVStream */
  1240. for (i = 0; i < s->nb_streams; i++) {
  1241. RTSPStream *rtsp_st;
  1242. AVStream *st = s->streams[i];
  1243. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1244. if (!rtsp_st)
  1245. return AVERROR(ENOMEM);
  1246. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1247. st->priv_data = rtsp_st;
  1248. rtsp_st->stream_index = i;
  1249. av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
  1250. /* Note, this must match the relative uri set in the sdp content */
  1251. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1252. "/streamid=%d", i);
  1253. }
  1254. return 0;
  1255. }
  1256. void ff_rtsp_close_connections(AVFormatContext *s)
  1257. {
  1258. RTSPState *rt = s->priv_data;
  1259. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1260. url_close(rt->rtsp_hd);
  1261. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1262. }
  1263. int ff_rtsp_connect(AVFormatContext *s)
  1264. {
  1265. RTSPState *rt = s->priv_data;
  1266. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1267. char *option_list, *option, *filename;
  1268. int port, err, tcp_fd;
  1269. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1270. int lower_transport_mask = 0;
  1271. char real_challenge[64];
  1272. struct sockaddr_storage peer;
  1273. socklen_t peer_len = sizeof(peer);
  1274. if (!ff_network_init())
  1275. return AVERROR(EIO);
  1276. redirect:
  1277. rt->control_transport = RTSP_MODE_PLAIN;
  1278. /* extract hostname and port */
  1279. av_url_split(NULL, 0, auth, sizeof(auth),
  1280. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1281. if (*auth) {
  1282. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1283. }
  1284. if (port < 0)
  1285. port = RTSP_DEFAULT_PORT;
  1286. /* search for options */
  1287. option_list = strrchr(path, '?');
  1288. if (option_list) {
  1289. /* Strip out the RTSP specific options, write out the rest of
  1290. * the options back into the same string. */
  1291. filename = option_list;
  1292. while (option_list) {
  1293. /* move the option pointer */
  1294. option = ++option_list;
  1295. option_list = strchr(option_list, '&');
  1296. if (option_list)
  1297. *option_list = 0;
  1298. /* handle the options */
  1299. if (!strcmp(option, "udp")) {
  1300. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1301. } else if (!strcmp(option, "multicast")) {
  1302. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1303. } else if (!strcmp(option, "tcp")) {
  1304. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1305. } else if(!strcmp(option, "http")) {
  1306. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1307. rt->control_transport = RTSP_MODE_TUNNEL;
  1308. } else {
  1309. /* Write options back into the buffer, using memmove instead
  1310. * of strcpy since the strings may overlap. */
  1311. int len = strlen(option);
  1312. memmove(++filename, option, len);
  1313. filename += len;
  1314. if (option_list) *filename = '&';
  1315. }
  1316. }
  1317. *filename = 0;
  1318. }
  1319. if (!lower_transport_mask)
  1320. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1321. if (s->oformat) {
  1322. /* Only UDP or TCP - UDP multicast isn't supported. */
  1323. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1324. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1325. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1326. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1327. "only UDP and TCP are supported for output.\n");
  1328. err = AVERROR(EINVAL);
  1329. goto fail;
  1330. }
  1331. }
  1332. /* Construct the URI used in request; this is similar to s->filename,
  1333. * but with authentication credentials removed and RTSP specific options
  1334. * stripped out. */
  1335. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1336. host, port, "%s", path);
  1337. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1338. /* set up initial handshake for tunneling */
  1339. char httpname[1024];
  1340. char sessioncookie[17];
  1341. char headers[1024];
  1342. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1343. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1344. av_get_random_seed(), av_get_random_seed());
  1345. /* GET requests */
  1346. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1347. err = AVERROR(EIO);
  1348. goto fail;
  1349. }
  1350. /* generate GET headers */
  1351. snprintf(headers, sizeof(headers),
  1352. "x-sessioncookie: %s\r\n"
  1353. "Accept: application/x-rtsp-tunnelled\r\n"
  1354. "Pragma: no-cache\r\n"
  1355. "Cache-Control: no-cache\r\n",
  1356. sessioncookie);
  1357. ff_http_set_headers(rt->rtsp_hd, headers);
  1358. /* complete the connection */
  1359. if (url_connect(rt->rtsp_hd)) {
  1360. err = AVERROR(EIO);
  1361. goto fail;
  1362. }
  1363. /* POST requests */
  1364. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1365. err = AVERROR(EIO);
  1366. goto fail;
  1367. }
  1368. /* generate POST headers */
  1369. snprintf(headers, sizeof(headers),
  1370. "x-sessioncookie: %s\r\n"
  1371. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1372. "Pragma: no-cache\r\n"
  1373. "Cache-Control: no-cache\r\n"
  1374. "Content-Length: 32767\r\n"
  1375. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1376. sessioncookie);
  1377. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1378. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1379. /* Initialize the authentication state for the POST session. The HTTP
  1380. * protocol implementation doesn't properly handle multi-pass
  1381. * authentication for POST requests, since it would require one of
  1382. * the following:
  1383. * - implementing Expect: 100-continue, which many HTTP servers
  1384. * don't support anyway, even less the RTSP servers that do HTTP
  1385. * tunneling
  1386. * - sending the whole POST data until getting a 401 reply specifying
  1387. * what authentication method to use, then resending all that data
  1388. * - waiting for potential 401 replies directly after sending the
  1389. * POST header (waiting for some unspecified time)
  1390. * Therefore, we copy the full auth state, which works for both basic
  1391. * and digest. (For digest, we would have to synchronize the nonce
  1392. * count variable between the two sessions, if we'd do more requests
  1393. * with the original session, though.)
  1394. */
  1395. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1396. /* complete the connection */
  1397. if (url_connect(rt->rtsp_hd_out)) {
  1398. err = AVERROR(EIO);
  1399. goto fail;
  1400. }
  1401. } else {
  1402. /* open the tcp connection */
  1403. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1404. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1405. err = AVERROR(EIO);
  1406. goto fail;
  1407. }
  1408. rt->rtsp_hd_out = rt->rtsp_hd;
  1409. }
  1410. rt->seq = 0;
  1411. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1412. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1413. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1414. NULL, 0, NI_NUMERICHOST);
  1415. }
  1416. /* request options supported by the server; this also detects server
  1417. * type */
  1418. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1419. cmd[0] = 0;
  1420. if (rt->server_type == RTSP_SERVER_REAL)
  1421. av_strlcat(cmd,
  1422. /**
  1423. * The following entries are required for proper
  1424. * streaming from a Realmedia server. They are
  1425. * interdependent in some way although we currently
  1426. * don't quite understand how. Values were copied
  1427. * from mplayer SVN r23589.
  1428. * @param CompanyID is a 16-byte ID in base64
  1429. * @param ClientChallenge is a 16-byte ID in hex
  1430. */
  1431. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1432. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1433. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1434. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1435. sizeof(cmd));
  1436. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1437. if (reply->status_code != RTSP_STATUS_OK) {
  1438. err = AVERROR_INVALIDDATA;
  1439. goto fail;
  1440. }
  1441. /* detect server type if not standard-compliant RTP */
  1442. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1443. rt->server_type = RTSP_SERVER_REAL;
  1444. continue;
  1445. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1446. rt->server_type = RTSP_SERVER_WMS;
  1447. } else if (rt->server_type == RTSP_SERVER_REAL)
  1448. strcpy(real_challenge, reply->real_challenge);
  1449. break;
  1450. }
  1451. if (s->iformat)
  1452. err = rtsp_setup_input_streams(s, reply);
  1453. else
  1454. err = rtsp_setup_output_streams(s, host);
  1455. if (err)
  1456. goto fail;
  1457. do {
  1458. int lower_transport = ff_log2_tab[lower_transport_mask &
  1459. ~(lower_transport_mask - 1)];
  1460. err = make_setup_request(s, host, port, lower_transport,
  1461. rt->server_type == RTSP_SERVER_REAL ?
  1462. real_challenge : NULL);
  1463. if (err < 0)
  1464. goto fail;
  1465. lower_transport_mask &= ~(1 << lower_transport);
  1466. if (lower_transport_mask == 0 && err == 1) {
  1467. err = FF_NETERROR(EPROTONOSUPPORT);
  1468. goto fail;
  1469. }
  1470. } while (err);
  1471. rt->state = RTSP_STATE_IDLE;
  1472. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1473. return 0;
  1474. fail:
  1475. ff_rtsp_close_streams(s);
  1476. ff_rtsp_close_connections(s);
  1477. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1478. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1479. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1480. reply->status_code,
  1481. s->filename);
  1482. goto redirect;
  1483. }
  1484. ff_network_close();
  1485. return err;
  1486. }
  1487. #endif
  1488. #if CONFIG_RTSP_DEMUXER
  1489. static int rtsp_read_header(AVFormatContext *s,
  1490. AVFormatParameters *ap)
  1491. {
  1492. RTSPState *rt = s->priv_data;
  1493. int ret;
  1494. ret = ff_rtsp_connect(s);
  1495. if (ret)
  1496. return ret;
  1497. rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
  1498. if (!rt->real_setup_cache)
  1499. return AVERROR(ENOMEM);
  1500. rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
  1501. if (ap->initial_pause) {
  1502. /* do not start immediately */
  1503. } else {
  1504. if (rtsp_read_play(s) < 0) {
  1505. ff_rtsp_close_streams(s);
  1506. ff_rtsp_close_connections(s);
  1507. return AVERROR_INVALIDDATA;
  1508. }
  1509. }
  1510. return 0;
  1511. }
  1512. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1513. uint8_t *buf, int buf_size)
  1514. {
  1515. RTSPState *rt = s->priv_data;
  1516. RTSPStream *rtsp_st;
  1517. fd_set rfds;
  1518. int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1519. struct timeval tv;
  1520. for (;;) {
  1521. if (url_interrupt_cb())
  1522. return AVERROR(EINTR);
  1523. FD_ZERO(&rfds);
  1524. if (rt->rtsp_hd) {
  1525. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1526. FD_SET(tcp_fd, &rfds);
  1527. } else {
  1528. fd_max = 0;
  1529. tcp_fd = -1;
  1530. }
  1531. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1532. rtsp_st = rt->rtsp_streams[i];
  1533. if (rtsp_st->rtp_handle) {
  1534. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1535. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1536. if (FFMAX(fd, fd_rtcp) > fd_max)
  1537. fd_max = FFMAX(fd, fd_rtcp);
  1538. FD_SET(fd, &rfds);
  1539. FD_SET(fd_rtcp, &rfds);
  1540. }
  1541. }
  1542. tv.tv_sec = 0;
  1543. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1544. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1545. if (n > 0) {
  1546. timeout_cnt = 0;
  1547. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1548. rtsp_st = rt->rtsp_streams[i];
  1549. if (rtsp_st->rtp_handle) {
  1550. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1551. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1552. if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
  1553. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1554. if (ret > 0) {
  1555. *prtsp_st = rtsp_st;
  1556. return ret;
  1557. }
  1558. }
  1559. }
  1560. }
  1561. #if CONFIG_RTSP_DEMUXER
  1562. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1563. RTSPMessageHeader reply;
  1564. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1565. if (ret < 0)
  1566. return ret;
  1567. /* XXX: parse message */
  1568. if (rt->state != RTSP_STATE_STREAMING)
  1569. return 0;
  1570. }
  1571. #endif
  1572. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1573. return FF_NETERROR(ETIMEDOUT);
  1574. } else if (n < 0 && errno != EINTR)
  1575. return AVERROR(errno);
  1576. }
  1577. }
  1578. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1579. uint8_t *buf, int buf_size)
  1580. {
  1581. RTSPState *rt = s->priv_data;
  1582. int id, len, i, ret;
  1583. RTSPStream *rtsp_st;
  1584. #ifdef DEBUG_RTP_TCP
  1585. dprintf(s, "tcp_read_packet:\n");
  1586. #endif
  1587. redo:
  1588. for (;;) {
  1589. RTSPMessageHeader reply;
  1590. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1591. if (ret < 0)
  1592. return ret;
  1593. if (ret == 1) /* received '$' */
  1594. break;
  1595. /* XXX: parse message */
  1596. if (rt->state != RTSP_STATE_STREAMING)
  1597. return 0;
  1598. }
  1599. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1600. if (ret != 3)
  1601. return -1;
  1602. id = buf[0];
  1603. len = AV_RB16(buf + 1);
  1604. #ifdef DEBUG_RTP_TCP
  1605. dprintf(s, "id=%d len=%d\n", id, len);
  1606. #endif
  1607. if (len > buf_size || len < 12)
  1608. goto redo;
  1609. /* get the data */
  1610. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1611. if (ret != len)
  1612. return -1;
  1613. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1614. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1615. return -1;
  1616. /* find the matching stream */
  1617. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1618. rtsp_st = rt->rtsp_streams[i];
  1619. if (id >= rtsp_st->interleaved_min &&
  1620. id <= rtsp_st->interleaved_max)
  1621. goto found;
  1622. }
  1623. goto redo;
  1624. found:
  1625. *prtsp_st = rtsp_st;
  1626. return len;
  1627. }
  1628. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1629. {
  1630. RTSPState *rt = s->priv_data;
  1631. int ret, len;
  1632. RTSPStream *rtsp_st;
  1633. if (rt->nb_byes == rt->nb_rtsp_streams)
  1634. return AVERROR_EOF;
  1635. /* get next frames from the same RTP packet */
  1636. if (rt->cur_transport_priv) {
  1637. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1638. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1639. } else
  1640. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1641. if (ret == 0) {
  1642. rt->cur_transport_priv = NULL;
  1643. return 0;
  1644. } else if (ret == 1) {
  1645. return 0;
  1646. } else
  1647. rt->cur_transport_priv = NULL;
  1648. }
  1649. /* read next RTP packet */
  1650. redo:
  1651. if (!rt->recvbuf) {
  1652. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1653. if (!rt->recvbuf)
  1654. return AVERROR(ENOMEM);
  1655. }
  1656. switch(rt->lower_transport) {
  1657. default:
  1658. #if CONFIG_RTSP_DEMUXER
  1659. case RTSP_LOWER_TRANSPORT_TCP:
  1660. len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1661. break;
  1662. #endif
  1663. case RTSP_LOWER_TRANSPORT_UDP:
  1664. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1665. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1666. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1667. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1668. break;
  1669. }
  1670. if (len < 0)
  1671. return len;
  1672. if (len == 0)
  1673. return AVERROR_EOF;
  1674. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1675. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1676. } else {
  1677. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1678. if (ret < 0) {
  1679. /* Either bad packet, or a RTCP packet. Check if the
  1680. * first_rtcp_ntp_time field was initialized. */
  1681. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1682. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1683. /* first_rtcp_ntp_time has been initialized for this stream,
  1684. * copy the same value to all other uninitialized streams,
  1685. * in order to map their timestamp origin to the same ntp time
  1686. * as this one. */
  1687. int i;
  1688. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1689. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1690. if (rtpctx2 &&
  1691. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  1692. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1693. }
  1694. }
  1695. if (ret == -RTCP_BYE) {
  1696. rt->nb_byes++;
  1697. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1698. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1699. if (rt->nb_byes == rt->nb_rtsp_streams)
  1700. return AVERROR_EOF;
  1701. }
  1702. }
  1703. }
  1704. if (ret < 0)
  1705. goto redo;
  1706. if (ret == 1)
  1707. /* more packets may follow, so we save the RTP context */
  1708. rt->cur_transport_priv = rtsp_st->transport_priv;
  1709. return ret;
  1710. }
  1711. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1712. {
  1713. RTSPState *rt = s->priv_data;
  1714. int ret;
  1715. RTSPMessageHeader reply1, *reply = &reply1;
  1716. char cmd[1024];
  1717. if (rt->server_type == RTSP_SERVER_REAL) {
  1718. int i;
  1719. for (i = 0; i < s->nb_streams; i++)
  1720. rt->real_setup[i] = s->streams[i]->discard;
  1721. if (!rt->need_subscription) {
  1722. if (memcmp (rt->real_setup, rt->real_setup_cache,
  1723. sizeof(enum AVDiscard) * s->nb_streams)) {
  1724. snprintf(cmd, sizeof(cmd),
  1725. "Unsubscribe: %s\r\n",
  1726. rt->last_subscription);
  1727. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1728. cmd, reply, NULL);
  1729. if (reply->status_code != RTSP_STATUS_OK)
  1730. return AVERROR_INVALIDDATA;
  1731. rt->need_subscription = 1;
  1732. }
  1733. }
  1734. if (rt->need_subscription) {
  1735. int r, rule_nr, first = 1;
  1736. memcpy(rt->real_setup_cache, rt->real_setup,
  1737. sizeof(enum AVDiscard) * s->nb_streams);
  1738. rt->last_subscription[0] = 0;
  1739. snprintf(cmd, sizeof(cmd),
  1740. "Subscribe: ");
  1741. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1742. rule_nr = 0;
  1743. for (r = 0; r < s->nb_streams; r++) {
  1744. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1745. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1746. if (!first)
  1747. av_strlcat(rt->last_subscription, ",",
  1748. sizeof(rt->last_subscription));
  1749. ff_rdt_subscribe_rule(
  1750. rt->last_subscription,
  1751. sizeof(rt->last_subscription), i, rule_nr);
  1752. first = 0;
  1753. }
  1754. rule_nr++;
  1755. }
  1756. }
  1757. }
  1758. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1759. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1760. cmd, reply, NULL);
  1761. if (reply->status_code != RTSP_STATUS_OK)
  1762. return AVERROR_INVALIDDATA;
  1763. rt->need_subscription = 0;
  1764. if (rt->state == RTSP_STATE_STREAMING)
  1765. rtsp_read_play (s);
  1766. }
  1767. }
  1768. ret = rtsp_fetch_packet(s, pkt);
  1769. if (ret < 0)
  1770. return ret;
  1771. /* send dummy request to keep TCP connection alive */
  1772. if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1773. if (rt->server_type == RTSP_SERVER_WMS) {
  1774. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  1775. } else {
  1776. ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
  1777. }
  1778. }
  1779. return 0;
  1780. }
  1781. /* pause the stream */
  1782. static int rtsp_read_pause(AVFormatContext *s)
  1783. {
  1784. RTSPState *rt = s->priv_data;
  1785. RTSPMessageHeader reply1, *reply = &reply1;
  1786. if (rt->state != RTSP_STATE_STREAMING)
  1787. return 0;
  1788. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1789. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  1790. if (reply->status_code != RTSP_STATUS_OK) {
  1791. return -1;
  1792. }
  1793. }
  1794. rt->state = RTSP_STATE_PAUSED;
  1795. return 0;
  1796. }
  1797. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1798. int64_t timestamp, int flags)
  1799. {
  1800. RTSPState *rt = s->priv_data;
  1801. rt->seek_timestamp = av_rescale_q(timestamp,
  1802. s->streams[stream_index]->time_base,
  1803. AV_TIME_BASE_Q);
  1804. switch(rt->state) {
  1805. default:
  1806. case RTSP_STATE_IDLE:
  1807. break;
  1808. case RTSP_STATE_STREAMING:
  1809. if (rtsp_read_pause(s) != 0)
  1810. return -1;
  1811. rt->state = RTSP_STATE_SEEKING;
  1812. if (rtsp_read_play(s) != 0)
  1813. return -1;
  1814. break;
  1815. case RTSP_STATE_PAUSED:
  1816. rt->state = RTSP_STATE_IDLE;
  1817. break;
  1818. }
  1819. return 0;
  1820. }
  1821. static int rtsp_read_close(AVFormatContext *s)
  1822. {
  1823. RTSPState *rt = s->priv_data;
  1824. #if 0
  1825. /* NOTE: it is valid to flush the buffer here */
  1826. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1827. url_fclose(&rt->rtsp_gb);
  1828. }
  1829. #endif
  1830. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  1831. ff_rtsp_close_streams(s);
  1832. ff_rtsp_close_connections(s);
  1833. ff_network_close();
  1834. rt->real_setup = NULL;
  1835. av_freep(&rt->real_setup_cache);
  1836. return 0;
  1837. }
  1838. AVInputFormat rtsp_demuxer = {
  1839. "rtsp",
  1840. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1841. sizeof(RTSPState),
  1842. rtsp_probe,
  1843. rtsp_read_header,
  1844. rtsp_read_packet,
  1845. rtsp_read_close,
  1846. rtsp_read_seek,
  1847. .flags = AVFMT_NOFILE,
  1848. .read_play = rtsp_read_play,
  1849. .read_pause = rtsp_read_pause,
  1850. };
  1851. #endif
  1852. static int sdp_probe(AVProbeData *p1)
  1853. {
  1854. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1855. /* we look for a line beginning "c=IN IP" */
  1856. while (p < p_end && *p != '\0') {
  1857. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1858. av_strstart(p, "c=IN IP", NULL))
  1859. return AVPROBE_SCORE_MAX / 2;
  1860. while (p < p_end - 1 && *p != '\n') p++;
  1861. if (++p >= p_end)
  1862. break;
  1863. if (*p == '\r')
  1864. p++;
  1865. }
  1866. return 0;
  1867. }
  1868. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1869. {
  1870. RTSPState *rt = s->priv_data;
  1871. RTSPStream *rtsp_st;
  1872. int size, i, err;
  1873. char *content;
  1874. char url[1024];
  1875. if (!ff_network_init())
  1876. return AVERROR(EIO);
  1877. /* read the whole sdp file */
  1878. /* XXX: better loading */
  1879. content = av_malloc(SDP_MAX_SIZE);
  1880. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1881. if (size <= 0) {
  1882. av_free(content);
  1883. return AVERROR_INVALIDDATA;
  1884. }
  1885. content[size] ='\0';
  1886. sdp_parse(s, content);
  1887. av_free(content);
  1888. /* open each RTP stream */
  1889. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1890. char namebuf[50];
  1891. rtsp_st = rt->rtsp_streams[i];
  1892. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1893. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1894. ff_url_join(url, sizeof(url), "rtp", NULL,
  1895. namebuf, rtsp_st->sdp_port,
  1896. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1897. rtsp_st->sdp_ttl);
  1898. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1899. err = AVERROR_INVALIDDATA;
  1900. goto fail;
  1901. }
  1902. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1903. goto fail;
  1904. }
  1905. return 0;
  1906. fail:
  1907. ff_rtsp_close_streams(s);
  1908. ff_network_close();
  1909. return err;
  1910. }
  1911. static int sdp_read_close(AVFormatContext *s)
  1912. {
  1913. ff_rtsp_close_streams(s);
  1914. ff_network_close();
  1915. return 0;
  1916. }
  1917. AVInputFormat sdp_demuxer = {
  1918. "sdp",
  1919. NULL_IF_CONFIG_SMALL("SDP"),
  1920. sizeof(RTSPState),
  1921. sdp_probe,
  1922. sdp_read_header,
  1923. rtsp_fetch_packet,
  1924. sdp_read_close,
  1925. };