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.

2162 lines
74KB

  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. AVFormatContext *rtpctx;
  472. int ret;
  473. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  474. if (!rtp_format)
  475. return NULL;
  476. /* Allocate an AVFormatContext for each output stream */
  477. rtpctx = avformat_alloc_context();
  478. if (!rtpctx)
  479. return NULL;
  480. rtpctx->oformat = rtp_format;
  481. if (!av_new_stream(rtpctx, 0)) {
  482. av_free(rtpctx);
  483. return NULL;
  484. }
  485. /* Copy the max delay setting; the rtp muxer reads this. */
  486. rtpctx->max_delay = s->max_delay;
  487. /* Copy other stream parameters. */
  488. rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
  489. /* Set the synchronized start time. */
  490. rtpctx->start_time_realtime = s->start_time_realtime;
  491. /* Remove the local codec, link to the original codec
  492. * context instead, to give the rtp muxer access to
  493. * codec parameters. */
  494. av_free(rtpctx->streams[0]->codec);
  495. rtpctx->streams[0]->codec = st->codec;
  496. if (handle) {
  497. url_fdopen(&rtpctx->pb, handle);
  498. } else
  499. url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
  500. ret = av_write_header(rtpctx);
  501. if (ret) {
  502. if (handle) {
  503. url_fclose(rtpctx->pb);
  504. } else {
  505. uint8_t *ptr;
  506. url_close_dyn_buf(rtpctx->pb, &ptr);
  507. av_free(ptr);
  508. }
  509. av_free(rtpctx->streams[0]);
  510. av_free(rtpctx);
  511. return NULL;
  512. }
  513. /* Copy the RTP AVStream timebase back to the original AVStream */
  514. st->time_base = rtpctx->streams[0]->time_base;
  515. return rtpctx;
  516. }
  517. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  518. {
  519. RTSPState *rt = s->priv_data;
  520. AVStream *st = NULL;
  521. /* open the RTP context */
  522. if (rtsp_st->stream_index >= 0)
  523. st = s->streams[rtsp_st->stream_index];
  524. if (!st)
  525. s->ctx_flags |= AVFMTCTX_NOHEADER;
  526. if (s->oformat) {
  527. rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
  528. /* Ownership of rtp_handle is passed to the rtp mux context */
  529. rtsp_st->rtp_handle = NULL;
  530. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  531. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  532. rtsp_st->dynamic_protocol_context,
  533. rtsp_st->dynamic_handler);
  534. else
  535. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  536. rtsp_st->sdp_payload_type,
  537. (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
  538. ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
  539. if (!rtsp_st->transport_priv) {
  540. return AVERROR(ENOMEM);
  541. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  542. if (rtsp_st->dynamic_handler) {
  543. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  544. rtsp_st->dynamic_protocol_context,
  545. rtsp_st->dynamic_handler);
  546. }
  547. }
  548. return 0;
  549. }
  550. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  551. static int rtsp_probe(AVProbeData *p)
  552. {
  553. if (av_strstart(p->filename, "rtsp:", NULL))
  554. return AVPROBE_SCORE_MAX;
  555. return 0;
  556. }
  557. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  558. {
  559. const char *p;
  560. int v;
  561. p = *pp;
  562. p += strspn(p, SPACE_CHARS);
  563. v = strtol(p, (char **)&p, 10);
  564. if (*p == '-') {
  565. p++;
  566. *min_ptr = v;
  567. v = strtol(p, (char **)&p, 10);
  568. *max_ptr = v;
  569. } else {
  570. *min_ptr = v;
  571. *max_ptr = v;
  572. }
  573. *pp = p;
  574. }
  575. /* XXX: only one transport specification is parsed */
  576. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  577. {
  578. char transport_protocol[16];
  579. char profile[16];
  580. char lower_transport[16];
  581. char parameter[16];
  582. RTSPTransportField *th;
  583. char buf[256];
  584. reply->nb_transports = 0;
  585. for (;;) {
  586. p += strspn(p, SPACE_CHARS);
  587. if (*p == '\0')
  588. break;
  589. th = &reply->transports[reply->nb_transports];
  590. get_word_sep(transport_protocol, sizeof(transport_protocol),
  591. "/", &p);
  592. if (!strcasecmp (transport_protocol, "rtp")) {
  593. get_word_sep(profile, sizeof(profile), "/;,", &p);
  594. lower_transport[0] = '\0';
  595. /* rtp/avp/<protocol> */
  596. if (*p == '/') {
  597. get_word_sep(lower_transport, sizeof(lower_transport),
  598. ";,", &p);
  599. }
  600. th->transport = RTSP_TRANSPORT_RTP;
  601. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  602. !strcasecmp (transport_protocol, "x-real-rdt")) {
  603. /* x-pn-tng/<protocol> */
  604. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  605. profile[0] = '\0';
  606. th->transport = RTSP_TRANSPORT_RDT;
  607. }
  608. if (!strcasecmp(lower_transport, "TCP"))
  609. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  610. else
  611. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  612. if (*p == ';')
  613. p++;
  614. /* get each parameter */
  615. while (*p != '\0' && *p != ',') {
  616. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  617. if (!strcmp(parameter, "port")) {
  618. if (*p == '=') {
  619. p++;
  620. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  621. }
  622. } else if (!strcmp(parameter, "client_port")) {
  623. if (*p == '=') {
  624. p++;
  625. rtsp_parse_range(&th->client_port_min,
  626. &th->client_port_max, &p);
  627. }
  628. } else if (!strcmp(parameter, "server_port")) {
  629. if (*p == '=') {
  630. p++;
  631. rtsp_parse_range(&th->server_port_min,
  632. &th->server_port_max, &p);
  633. }
  634. } else if (!strcmp(parameter, "interleaved")) {
  635. if (*p == '=') {
  636. p++;
  637. rtsp_parse_range(&th->interleaved_min,
  638. &th->interleaved_max, &p);
  639. }
  640. } else if (!strcmp(parameter, "multicast")) {
  641. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  642. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  643. } else if (!strcmp(parameter, "ttl")) {
  644. if (*p == '=') {
  645. p++;
  646. th->ttl = strtol(p, (char **)&p, 10);
  647. }
  648. } else if (!strcmp(parameter, "destination")) {
  649. if (*p == '=') {
  650. p++;
  651. get_word_sep(buf, sizeof(buf), ";,", &p);
  652. get_sockaddr(buf, &th->destination);
  653. }
  654. } else if (!strcmp(parameter, "source")) {
  655. if (*p == '=') {
  656. p++;
  657. get_word_sep(buf, sizeof(buf), ";,", &p);
  658. av_strlcpy(th->source, buf, sizeof(th->source));
  659. }
  660. }
  661. while (*p != ';' && *p != '\0' && *p != ',')
  662. p++;
  663. if (*p == ';')
  664. p++;
  665. }
  666. if (*p == ',')
  667. p++;
  668. reply->nb_transports++;
  669. }
  670. }
  671. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  672. HTTPAuthState *auth_state)
  673. {
  674. const char *p;
  675. /* NOTE: we do case independent match for broken servers */
  676. p = buf;
  677. if (av_stristart(p, "Session:", &p)) {
  678. int t;
  679. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  680. if (av_stristart(p, ";timeout=", &p) &&
  681. (t = strtol(p, NULL, 10)) > 0) {
  682. reply->timeout = t;
  683. }
  684. } else if (av_stristart(p, "Content-Length:", &p)) {
  685. reply->content_length = strtol(p, NULL, 10);
  686. } else if (av_stristart(p, "Transport:", &p)) {
  687. rtsp_parse_transport(reply, p);
  688. } else if (av_stristart(p, "CSeq:", &p)) {
  689. reply->seq = strtol(p, NULL, 10);
  690. } else if (av_stristart(p, "Range:", &p)) {
  691. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  692. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  693. p += strspn(p, SPACE_CHARS);
  694. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  695. } else if (av_stristart(p, "Server:", &p)) {
  696. p += strspn(p, SPACE_CHARS);
  697. av_strlcpy(reply->server, p, sizeof(reply->server));
  698. } else if (av_stristart(p, "Notice:", &p) ||
  699. av_stristart(p, "X-Notice:", &p)) {
  700. reply->notice = strtol(p, NULL, 10);
  701. } else if (av_stristart(p, "Location:", &p)) {
  702. p += strspn(p, SPACE_CHARS);
  703. av_strlcpy(reply->location, p , sizeof(reply->location));
  704. } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
  705. p += strspn(p, SPACE_CHARS);
  706. ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
  707. } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
  708. p += strspn(p, SPACE_CHARS);
  709. ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
  710. }
  711. }
  712. /* skip a RTP/TCP interleaved packet */
  713. void ff_rtsp_skip_packet(AVFormatContext *s)
  714. {
  715. RTSPState *rt = s->priv_data;
  716. int ret, len, len1;
  717. uint8_t buf[1024];
  718. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  719. if (ret != 3)
  720. return;
  721. len = AV_RB16(buf + 1);
  722. dprintf(s, "skipping RTP packet len=%d\n", len);
  723. /* skip payload */
  724. while (len > 0) {
  725. len1 = len;
  726. if (len1 > sizeof(buf))
  727. len1 = sizeof(buf);
  728. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  729. if (ret != len1)
  730. return;
  731. len -= len1;
  732. }
  733. }
  734. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  735. unsigned char **content_ptr,
  736. int return_on_interleaved_data)
  737. {
  738. RTSPState *rt = s->priv_data;
  739. char buf[4096], buf1[1024], *q;
  740. unsigned char ch;
  741. const char *p;
  742. int ret, content_length, line_count = 0;
  743. unsigned char *content = NULL;
  744. memset(reply, 0, sizeof(*reply));
  745. /* parse reply (XXX: use buffers) */
  746. rt->last_reply[0] = '\0';
  747. for (;;) {
  748. q = buf;
  749. for (;;) {
  750. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  751. #ifdef DEBUG_RTP_TCP
  752. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  753. #endif
  754. if (ret != 1)
  755. return AVERROR_EOF;
  756. if (ch == '\n')
  757. break;
  758. if (ch == '$') {
  759. /* XXX: only parse it if first char on line ? */
  760. if (return_on_interleaved_data) {
  761. return 1;
  762. } else
  763. ff_rtsp_skip_packet(s);
  764. } else if (ch != '\r') {
  765. if ((q - buf) < sizeof(buf) - 1)
  766. *q++ = ch;
  767. }
  768. }
  769. *q = '\0';
  770. dprintf(s, "line='%s'\n", buf);
  771. /* test if last line */
  772. if (buf[0] == '\0')
  773. break;
  774. p = buf;
  775. if (line_count == 0) {
  776. /* get reply code */
  777. get_word(buf1, sizeof(buf1), &p);
  778. get_word(buf1, sizeof(buf1), &p);
  779. reply->status_code = atoi(buf1);
  780. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  781. } else {
  782. ff_rtsp_parse_line(reply, p, &rt->auth_state);
  783. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  784. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  785. }
  786. line_count++;
  787. }
  788. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  789. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  790. content_length = reply->content_length;
  791. if (content_length > 0) {
  792. /* leave some room for a trailing '\0' (useful for simple parsing) */
  793. content = av_malloc(content_length + 1);
  794. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  795. content[content_length] = '\0';
  796. }
  797. if (content_ptr)
  798. *content_ptr = content;
  799. else
  800. av_free(content);
  801. if (rt->seq != reply->seq) {
  802. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  803. rt->seq, reply->seq);
  804. }
  805. /* EOS */
  806. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  807. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  808. reply->notice == 2306 /* Continuous Feed Terminated */) {
  809. rt->state = RTSP_STATE_IDLE;
  810. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  811. return AVERROR(EIO); /* data or server error */
  812. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  813. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  814. return AVERROR(EPERM);
  815. return 0;
  816. }
  817. int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  818. const char *method, const char *url,
  819. const char *headers,
  820. const unsigned char *send_content,
  821. int send_content_length)
  822. {
  823. RTSPState *rt = s->priv_data;
  824. char buf[4096], *out_buf;
  825. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  826. /* Add in RTSP headers */
  827. out_buf = buf;
  828. rt->seq++;
  829. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  830. if (headers)
  831. av_strlcat(buf, headers, sizeof(buf));
  832. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  833. if (rt->session_id[0] != '\0' && (!headers ||
  834. !strstr(headers, "\nIf-Match:"))) {
  835. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  836. }
  837. if (rt->auth[0]) {
  838. char *str = ff_http_auth_create_response(&rt->auth_state,
  839. rt->auth, url, method);
  840. if (str)
  841. av_strlcat(buf, str, sizeof(buf));
  842. av_free(str);
  843. }
  844. if (send_content_length > 0 && send_content)
  845. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  846. av_strlcat(buf, "\r\n", sizeof(buf));
  847. /* base64 encode rtsp if tunneling */
  848. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  849. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  850. out_buf = base64buf;
  851. }
  852. dprintf(s, "Sending:\n%s--\n", buf);
  853. url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  854. if (send_content_length > 0 && send_content) {
  855. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  856. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  857. "with content data not supported\n");
  858. return AVERROR_PATCHWELCOME;
  859. }
  860. url_write(rt->rtsp_hd_out, send_content, send_content_length);
  861. }
  862. rt->last_cmd_time = av_gettime();
  863. return 0;
  864. }
  865. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  866. const char *url, const char *headers)
  867. {
  868. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  869. }
  870. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  871. const char *headers, RTSPMessageHeader *reply,
  872. unsigned char **content_ptr)
  873. {
  874. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  875. content_ptr, NULL, 0);
  876. }
  877. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  878. const char *method, const char *url,
  879. const char *header,
  880. RTSPMessageHeader *reply,
  881. unsigned char **content_ptr,
  882. const unsigned char *send_content,
  883. int send_content_length)
  884. {
  885. RTSPState *rt = s->priv_data;
  886. HTTPAuthType cur_auth_type;
  887. int ret;
  888. retry:
  889. cur_auth_type = rt->auth_state.auth_type;
  890. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  891. send_content,
  892. send_content_length)))
  893. return ret;
  894. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
  895. return ret;
  896. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  897. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  898. goto retry;
  899. if (reply->status_code > 400){
  900. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  901. method,
  902. reply->status_code,
  903. reply->reason);
  904. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  905. }
  906. return 0;
  907. }
  908. /**
  909. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  910. */
  911. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  912. int lower_transport, const char *real_challenge)
  913. {
  914. RTSPState *rt = s->priv_data;
  915. int rtx, j, i, err, interleave = 0;
  916. RTSPStream *rtsp_st;
  917. RTSPMessageHeader reply1, *reply = &reply1;
  918. char cmd[2048];
  919. const char *trans_pref;
  920. if (rt->transport == RTSP_TRANSPORT_RDT)
  921. trans_pref = "x-pn-tng";
  922. else
  923. trans_pref = "RTP/AVP";
  924. /* default timeout: 1 minute */
  925. rt->timeout = 60;
  926. /* for each stream, make the setup request */
  927. /* XXX: we assume the same server is used for the control of each
  928. * RTSP stream */
  929. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  930. char transport[2048];
  931. /**
  932. * WMS serves all UDP data over a single connection, the RTX, which
  933. * isn't necessarily the first in the SDP but has to be the first
  934. * to be set up, else the second/third SETUP will fail with a 461.
  935. */
  936. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  937. rt->server_type == RTSP_SERVER_WMS) {
  938. if (i == 0) {
  939. /* rtx first */
  940. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  941. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  942. if (len >= 4 &&
  943. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  944. "/rtx"))
  945. break;
  946. }
  947. if (rtx == rt->nb_rtsp_streams)
  948. return -1; /* no RTX found */
  949. rtsp_st = rt->rtsp_streams[rtx];
  950. } else
  951. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  952. } else
  953. rtsp_st = rt->rtsp_streams[i];
  954. /* RTP/UDP */
  955. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  956. char buf[256];
  957. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  958. port = reply->transports[0].client_port_min;
  959. goto have_port;
  960. }
  961. /* first try in specified port range */
  962. if (RTSP_RTP_PORT_MIN != 0) {
  963. while (j <= RTSP_RTP_PORT_MAX) {
  964. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  965. "?localport=%d", j);
  966. /* we will use two ports per rtp stream (rtp and rtcp) */
  967. j += 2;
  968. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  969. goto rtp_opened;
  970. }
  971. }
  972. #if 0
  973. /* then try on any port */
  974. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  975. err = AVERROR_INVALIDDATA;
  976. goto fail;
  977. }
  978. #endif
  979. rtp_opened:
  980. port = rtp_get_local_port(rtsp_st->rtp_handle);
  981. have_port:
  982. snprintf(transport, sizeof(transport) - 1,
  983. "%s/UDP;", trans_pref);
  984. if (rt->server_type != RTSP_SERVER_REAL)
  985. av_strlcat(transport, "unicast;", sizeof(transport));
  986. av_strlcatf(transport, sizeof(transport),
  987. "client_port=%d", port);
  988. if (rt->transport == RTSP_TRANSPORT_RTP &&
  989. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  990. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  991. }
  992. /* RTP/TCP */
  993. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  994. /** For WMS streams, the application streams are only used for
  995. * UDP. When trying to set it up for TCP streams, the server
  996. * will return an error. Therefore, we skip those streams. */
  997. if (rt->server_type == RTSP_SERVER_WMS &&
  998. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  999. AVMEDIA_TYPE_DATA)
  1000. continue;
  1001. snprintf(transport, sizeof(transport) - 1,
  1002. "%s/TCP;", trans_pref);
  1003. if (rt->server_type == RTSP_SERVER_WMS)
  1004. av_strlcat(transport, "unicast;", sizeof(transport));
  1005. av_strlcatf(transport, sizeof(transport),
  1006. "interleaved=%d-%d",
  1007. interleave, interleave + 1);
  1008. interleave += 2;
  1009. }
  1010. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1011. snprintf(transport, sizeof(transport) - 1,
  1012. "%s/UDP;multicast", trans_pref);
  1013. }
  1014. if (s->oformat) {
  1015. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1016. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1017. rt->server_type == RTSP_SERVER_WMS)
  1018. av_strlcat(transport, ";mode=play", sizeof(transport));
  1019. snprintf(cmd, sizeof(cmd),
  1020. "Transport: %s\r\n",
  1021. transport);
  1022. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  1023. char real_res[41], real_csum[9];
  1024. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1025. real_challenge);
  1026. av_strlcatf(cmd, sizeof(cmd),
  1027. "If-Match: %s\r\n"
  1028. "RealChallenge2: %s, sd=%s\r\n",
  1029. rt->session_id, real_res, real_csum);
  1030. }
  1031. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1032. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1033. err = 1;
  1034. goto fail;
  1035. } else if (reply->status_code != RTSP_STATUS_OK ||
  1036. reply->nb_transports != 1) {
  1037. err = AVERROR_INVALIDDATA;
  1038. goto fail;
  1039. }
  1040. /* XXX: same protocol for all streams is required */
  1041. if (i > 0) {
  1042. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1043. reply->transports[0].transport != rt->transport) {
  1044. err = AVERROR_INVALIDDATA;
  1045. goto fail;
  1046. }
  1047. } else {
  1048. rt->lower_transport = reply->transports[0].lower_transport;
  1049. rt->transport = reply->transports[0].transport;
  1050. }
  1051. /* close RTP connection if not chosen */
  1052. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1053. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1054. url_close(rtsp_st->rtp_handle);
  1055. rtsp_st->rtp_handle = NULL;
  1056. }
  1057. switch(reply->transports[0].lower_transport) {
  1058. case RTSP_LOWER_TRANSPORT_TCP:
  1059. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1060. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1061. break;
  1062. case RTSP_LOWER_TRANSPORT_UDP: {
  1063. char url[1024];
  1064. /* Use source address if specified */
  1065. if (reply->transports[0].source[0]) {
  1066. ff_url_join(url, sizeof(url), "rtp", NULL,
  1067. reply->transports[0].source,
  1068. reply->transports[0].server_port_min, NULL);
  1069. } else {
  1070. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1071. reply->transports[0].server_port_min, NULL);
  1072. }
  1073. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1074. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1075. err = AVERROR_INVALIDDATA;
  1076. goto fail;
  1077. }
  1078. /* Try to initialize the connection state in a
  1079. * potential NAT router by sending dummy packets.
  1080. * RTP/RTCP dummy packets are used for RDT, too.
  1081. */
  1082. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1083. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1084. break;
  1085. }
  1086. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1087. char url[1024], namebuf[50];
  1088. struct sockaddr_storage addr;
  1089. int port, ttl;
  1090. if (reply->transports[0].destination.ss_family) {
  1091. addr = reply->transports[0].destination;
  1092. port = reply->transports[0].port_min;
  1093. ttl = reply->transports[0].ttl;
  1094. } else {
  1095. addr = rtsp_st->sdp_ip;
  1096. port = rtsp_st->sdp_port;
  1097. ttl = rtsp_st->sdp_ttl;
  1098. }
  1099. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1100. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1101. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1102. port, "?ttl=%d", ttl);
  1103. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1104. err = AVERROR_INVALIDDATA;
  1105. goto fail;
  1106. }
  1107. break;
  1108. }
  1109. }
  1110. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1111. goto fail;
  1112. }
  1113. if (reply->timeout > 0)
  1114. rt->timeout = reply->timeout;
  1115. if (rt->server_type == RTSP_SERVER_REAL)
  1116. rt->need_subscription = 1;
  1117. return 0;
  1118. fail:
  1119. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1120. if (rt->rtsp_streams[i]->rtp_handle) {
  1121. url_close(rt->rtsp_streams[i]->rtp_handle);
  1122. rt->rtsp_streams[i]->rtp_handle = NULL;
  1123. }
  1124. }
  1125. return err;
  1126. }
  1127. static int rtsp_read_play(AVFormatContext *s)
  1128. {
  1129. RTSPState *rt = s->priv_data;
  1130. RTSPMessageHeader reply1, *reply = &reply1;
  1131. int i;
  1132. char cmd[1024];
  1133. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1134. rt->nb_byes = 0;
  1135. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1136. if (rt->state == RTSP_STATE_PAUSED) {
  1137. cmd[0] = 0;
  1138. } else {
  1139. snprintf(cmd, sizeof(cmd),
  1140. "Range: npt=%0.3f-\r\n",
  1141. (double)rt->seek_timestamp / AV_TIME_BASE);
  1142. }
  1143. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  1144. if (reply->status_code != RTSP_STATUS_OK) {
  1145. return -1;
  1146. }
  1147. if (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. ff_rtp_reset_packet_queue(rtpctx);
  1157. if (reply->range_start != AV_NOPTS_VALUE) {
  1158. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  1159. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  1160. if (st)
  1161. rtpctx->range_start_offset =
  1162. av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
  1163. st->time_base);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. rt->state = RTSP_STATE_STREAMING;
  1169. return 0;
  1170. }
  1171. static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  1172. {
  1173. RTSPState *rt = s->priv_data;
  1174. char cmd[1024];
  1175. unsigned char *content = NULL;
  1176. int ret;
  1177. /* describe the stream */
  1178. snprintf(cmd, sizeof(cmd),
  1179. "Accept: application/sdp\r\n");
  1180. if (rt->server_type == RTSP_SERVER_REAL) {
  1181. /**
  1182. * The Require: attribute is needed for proper streaming from
  1183. * Realmedia servers.
  1184. */
  1185. av_strlcat(cmd,
  1186. "Require: com.real.retain-entity-for-setup\r\n",
  1187. sizeof(cmd));
  1188. }
  1189. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  1190. if (!content)
  1191. return AVERROR_INVALIDDATA;
  1192. if (reply->status_code != RTSP_STATUS_OK) {
  1193. av_freep(&content);
  1194. return AVERROR_INVALIDDATA;
  1195. }
  1196. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
  1197. /* now we got the SDP description, we parse it */
  1198. ret = sdp_parse(s, (const char *)content);
  1199. av_freep(&content);
  1200. if (ret < 0)
  1201. return AVERROR_INVALIDDATA;
  1202. return 0;
  1203. }
  1204. static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
  1205. {
  1206. RTSPState *rt = s->priv_data;
  1207. RTSPMessageHeader reply1, *reply = &reply1;
  1208. int i;
  1209. char *sdp;
  1210. AVFormatContext sdp_ctx, *ctx_array[1];
  1211. s->start_time_realtime = av_gettime();
  1212. /* Announce the stream */
  1213. sdp = av_mallocz(SDP_MAX_SIZE);
  1214. if (sdp == NULL)
  1215. return AVERROR(ENOMEM);
  1216. /* We create the SDP based on the RTSP AVFormatContext where we
  1217. * aren't allowed to change the filename field. (We create the SDP
  1218. * based on the RTSP context since the contexts for the RTP streams
  1219. * don't exist yet.) In order to specify a custom URL with the actual
  1220. * peer IP instead of the originally specified hostname, we create
  1221. * a temporary copy of the AVFormatContext, where the custom URL is set.
  1222. *
  1223. * FIXME: Create the SDP without copying the AVFormatContext.
  1224. * This either requires setting up the RTP stream AVFormatContexts
  1225. * already here (complicating things immensely) or getting a more
  1226. * flexible SDP creation interface.
  1227. */
  1228. sdp_ctx = *s;
  1229. ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
  1230. "rtsp", NULL, addr, -1, NULL);
  1231. ctx_array[0] = &sdp_ctx;
  1232. if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
  1233. av_free(sdp);
  1234. return AVERROR_INVALIDDATA;
  1235. }
  1236. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  1237. ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
  1238. "Content-Type: application/sdp\r\n",
  1239. reply, NULL, sdp, strlen(sdp));
  1240. av_free(sdp);
  1241. if (reply->status_code != RTSP_STATUS_OK)
  1242. return AVERROR_INVALIDDATA;
  1243. /* Set up the RTSPStreams for each AVStream */
  1244. for (i = 0; i < s->nb_streams; i++) {
  1245. RTSPStream *rtsp_st;
  1246. AVStream *st = s->streams[i];
  1247. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1248. if (!rtsp_st)
  1249. return AVERROR(ENOMEM);
  1250. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1251. st->priv_data = rtsp_st;
  1252. rtsp_st->stream_index = i;
  1253. av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
  1254. /* Note, this must match the relative uri set in the sdp content */
  1255. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1256. "/streamid=%d", i);
  1257. }
  1258. return 0;
  1259. }
  1260. void ff_rtsp_close_connections(AVFormatContext *s)
  1261. {
  1262. RTSPState *rt = s->priv_data;
  1263. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1264. url_close(rt->rtsp_hd);
  1265. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1266. }
  1267. int ff_rtsp_connect(AVFormatContext *s)
  1268. {
  1269. RTSPState *rt = s->priv_data;
  1270. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1271. char *option_list, *option, *filename;
  1272. int port, err, tcp_fd;
  1273. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1274. int lower_transport_mask = 0;
  1275. char real_challenge[64];
  1276. struct sockaddr_storage peer;
  1277. socklen_t peer_len = sizeof(peer);
  1278. if (!ff_network_init())
  1279. return AVERROR(EIO);
  1280. redirect:
  1281. rt->control_transport = RTSP_MODE_PLAIN;
  1282. /* extract hostname and port */
  1283. av_url_split(NULL, 0, auth, sizeof(auth),
  1284. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1285. if (*auth) {
  1286. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1287. }
  1288. if (port < 0)
  1289. port = RTSP_DEFAULT_PORT;
  1290. /* search for options */
  1291. option_list = strrchr(path, '?');
  1292. if (option_list) {
  1293. /* Strip out the RTSP specific options, write out the rest of
  1294. * the options back into the same string. */
  1295. filename = option_list;
  1296. while (option_list) {
  1297. /* move the option pointer */
  1298. option = ++option_list;
  1299. option_list = strchr(option_list, '&');
  1300. if (option_list)
  1301. *option_list = 0;
  1302. /* handle the options */
  1303. if (!strcmp(option, "udp")) {
  1304. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1305. } else if (!strcmp(option, "multicast")) {
  1306. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1307. } else if (!strcmp(option, "tcp")) {
  1308. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1309. } else if(!strcmp(option, "http")) {
  1310. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1311. rt->control_transport = RTSP_MODE_TUNNEL;
  1312. } else {
  1313. /* Write options back into the buffer, using memmove instead
  1314. * of strcpy since the strings may overlap. */
  1315. int len = strlen(option);
  1316. memmove(++filename, option, len);
  1317. filename += len;
  1318. if (option_list) *filename = '&';
  1319. }
  1320. }
  1321. *filename = 0;
  1322. }
  1323. if (!lower_transport_mask)
  1324. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1325. if (s->oformat) {
  1326. /* Only UDP or TCP - UDP multicast isn't supported. */
  1327. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1328. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1329. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1330. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1331. "only UDP and TCP are supported for output.\n");
  1332. err = AVERROR(EINVAL);
  1333. goto fail;
  1334. }
  1335. }
  1336. /* Construct the URI used in request; this is similar to s->filename,
  1337. * but with authentication credentials removed and RTSP specific options
  1338. * stripped out. */
  1339. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1340. host, port, "%s", path);
  1341. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1342. /* set up initial handshake for tunneling */
  1343. char httpname[1024];
  1344. char sessioncookie[17];
  1345. char headers[1024];
  1346. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1347. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1348. av_get_random_seed(), av_get_random_seed());
  1349. /* GET requests */
  1350. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1351. err = AVERROR(EIO);
  1352. goto fail;
  1353. }
  1354. /* generate GET headers */
  1355. snprintf(headers, sizeof(headers),
  1356. "x-sessioncookie: %s\r\n"
  1357. "Accept: application/x-rtsp-tunnelled\r\n"
  1358. "Pragma: no-cache\r\n"
  1359. "Cache-Control: no-cache\r\n",
  1360. sessioncookie);
  1361. ff_http_set_headers(rt->rtsp_hd, headers);
  1362. /* complete the connection */
  1363. if (url_connect(rt->rtsp_hd)) {
  1364. err = AVERROR(EIO);
  1365. goto fail;
  1366. }
  1367. /* POST requests */
  1368. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1369. err = AVERROR(EIO);
  1370. goto fail;
  1371. }
  1372. /* generate POST headers */
  1373. snprintf(headers, sizeof(headers),
  1374. "x-sessioncookie: %s\r\n"
  1375. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1376. "Pragma: no-cache\r\n"
  1377. "Cache-Control: no-cache\r\n"
  1378. "Content-Length: 32767\r\n"
  1379. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1380. sessioncookie);
  1381. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1382. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1383. /* Initialize the authentication state for the POST session. The HTTP
  1384. * protocol implementation doesn't properly handle multi-pass
  1385. * authentication for POST requests, since it would require one of
  1386. * the following:
  1387. * - implementing Expect: 100-continue, which many HTTP servers
  1388. * don't support anyway, even less the RTSP servers that do HTTP
  1389. * tunneling
  1390. * - sending the whole POST data until getting a 401 reply specifying
  1391. * what authentication method to use, then resending all that data
  1392. * - waiting for potential 401 replies directly after sending the
  1393. * POST header (waiting for some unspecified time)
  1394. * Therefore, we copy the full auth state, which works for both basic
  1395. * and digest. (For digest, we would have to synchronize the nonce
  1396. * count variable between the two sessions, if we'd do more requests
  1397. * with the original session, though.)
  1398. */
  1399. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1400. /* complete the connection */
  1401. if (url_connect(rt->rtsp_hd_out)) {
  1402. err = AVERROR(EIO);
  1403. goto fail;
  1404. }
  1405. } else {
  1406. /* open the tcp connection */
  1407. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1408. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1409. err = AVERROR(EIO);
  1410. goto fail;
  1411. }
  1412. rt->rtsp_hd_out = rt->rtsp_hd;
  1413. }
  1414. rt->seq = 0;
  1415. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1416. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1417. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1418. NULL, 0, NI_NUMERICHOST);
  1419. }
  1420. /* request options supported by the server; this also detects server
  1421. * type */
  1422. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1423. cmd[0] = 0;
  1424. if (rt->server_type == RTSP_SERVER_REAL)
  1425. av_strlcat(cmd,
  1426. /**
  1427. * The following entries are required for proper
  1428. * streaming from a Realmedia server. They are
  1429. * interdependent in some way although we currently
  1430. * don't quite understand how. Values were copied
  1431. * from mplayer SVN r23589.
  1432. * @param CompanyID is a 16-byte ID in base64
  1433. * @param ClientChallenge is a 16-byte ID in hex
  1434. */
  1435. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1436. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1437. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1438. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1439. sizeof(cmd));
  1440. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1441. if (reply->status_code != RTSP_STATUS_OK) {
  1442. err = AVERROR_INVALIDDATA;
  1443. goto fail;
  1444. }
  1445. /* detect server type if not standard-compliant RTP */
  1446. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1447. rt->server_type = RTSP_SERVER_REAL;
  1448. continue;
  1449. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1450. rt->server_type = RTSP_SERVER_WMS;
  1451. } else if (rt->server_type == RTSP_SERVER_REAL)
  1452. strcpy(real_challenge, reply->real_challenge);
  1453. break;
  1454. }
  1455. if (s->iformat)
  1456. err = rtsp_setup_input_streams(s, reply);
  1457. else
  1458. err = rtsp_setup_output_streams(s, host);
  1459. if (err)
  1460. goto fail;
  1461. do {
  1462. int lower_transport = ff_log2_tab[lower_transport_mask &
  1463. ~(lower_transport_mask - 1)];
  1464. err = make_setup_request(s, host, port, lower_transport,
  1465. rt->server_type == RTSP_SERVER_REAL ?
  1466. real_challenge : NULL);
  1467. if (err < 0)
  1468. goto fail;
  1469. lower_transport_mask &= ~(1 << lower_transport);
  1470. if (lower_transport_mask == 0 && err == 1) {
  1471. err = FF_NETERROR(EPROTONOSUPPORT);
  1472. goto fail;
  1473. }
  1474. } while (err);
  1475. rt->state = RTSP_STATE_IDLE;
  1476. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1477. return 0;
  1478. fail:
  1479. ff_rtsp_close_streams(s);
  1480. ff_rtsp_close_connections(s);
  1481. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1482. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1483. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1484. reply->status_code,
  1485. s->filename);
  1486. goto redirect;
  1487. }
  1488. ff_network_close();
  1489. return err;
  1490. }
  1491. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1492. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1493. uint8_t *buf, int buf_size, int64_t wait_end)
  1494. {
  1495. RTSPState *rt = s->priv_data;
  1496. RTSPStream *rtsp_st;
  1497. fd_set rfds;
  1498. int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1499. struct timeval tv;
  1500. for (;;) {
  1501. if (url_interrupt_cb())
  1502. return AVERROR(EINTR);
  1503. if (wait_end && wait_end - av_gettime() < 0)
  1504. return AVERROR(EAGAIN);
  1505. FD_ZERO(&rfds);
  1506. if (rt->rtsp_hd) {
  1507. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1508. FD_SET(tcp_fd, &rfds);
  1509. } else {
  1510. fd_max = 0;
  1511. tcp_fd = -1;
  1512. }
  1513. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1514. rtsp_st = rt->rtsp_streams[i];
  1515. if (rtsp_st->rtp_handle) {
  1516. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1517. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1518. if (FFMAX(fd, fd_rtcp) > fd_max)
  1519. fd_max = FFMAX(fd, fd_rtcp);
  1520. FD_SET(fd, &rfds);
  1521. FD_SET(fd_rtcp, &rfds);
  1522. }
  1523. }
  1524. tv.tv_sec = 0;
  1525. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1526. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1527. if (n > 0) {
  1528. timeout_cnt = 0;
  1529. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1530. rtsp_st = rt->rtsp_streams[i];
  1531. if (rtsp_st->rtp_handle) {
  1532. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1533. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1534. if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
  1535. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1536. if (ret > 0) {
  1537. *prtsp_st = rtsp_st;
  1538. return ret;
  1539. }
  1540. }
  1541. }
  1542. }
  1543. #if CONFIG_RTSP_DEMUXER
  1544. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1545. RTSPMessageHeader reply;
  1546. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1547. if (ret < 0)
  1548. return ret;
  1549. /* XXX: parse message */
  1550. if (rt->state != RTSP_STATE_STREAMING)
  1551. return 0;
  1552. }
  1553. #endif
  1554. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1555. return FF_NETERROR(ETIMEDOUT);
  1556. } else if (n < 0 && errno != EINTR)
  1557. return AVERROR(errno);
  1558. }
  1559. }
  1560. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1561. uint8_t *buf, int buf_size);
  1562. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1563. {
  1564. RTSPState *rt = s->priv_data;
  1565. int ret, len;
  1566. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1567. int64_t wait_end = 0;
  1568. if (rt->nb_byes == rt->nb_rtsp_streams)
  1569. return AVERROR_EOF;
  1570. /* get next frames from the same RTP packet */
  1571. if (rt->cur_transport_priv) {
  1572. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1573. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1574. } else
  1575. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1576. if (ret == 0) {
  1577. rt->cur_transport_priv = NULL;
  1578. return 0;
  1579. } else if (ret == 1) {
  1580. return 0;
  1581. } else
  1582. rt->cur_transport_priv = NULL;
  1583. }
  1584. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1585. int i;
  1586. int64_t first_queue_time = 0;
  1587. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1588. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1589. int64_t queue_time = ff_rtp_queued_packet_time(rtpctx);
  1590. if (queue_time && (queue_time - first_queue_time < 0 ||
  1591. !first_queue_time)) {
  1592. first_queue_time = queue_time;
  1593. first_queue_st = rt->rtsp_streams[i];
  1594. }
  1595. }
  1596. if (first_queue_time)
  1597. wait_end = first_queue_time + s->max_delay;
  1598. }
  1599. /* read next RTP packet */
  1600. redo:
  1601. if (!rt->recvbuf) {
  1602. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1603. if (!rt->recvbuf)
  1604. return AVERROR(ENOMEM);
  1605. }
  1606. switch(rt->lower_transport) {
  1607. default:
  1608. #if CONFIG_RTSP_DEMUXER
  1609. case RTSP_LOWER_TRANSPORT_TCP:
  1610. len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1611. break;
  1612. #endif
  1613. case RTSP_LOWER_TRANSPORT_UDP:
  1614. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1615. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1616. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1617. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1618. break;
  1619. }
  1620. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1621. rt->transport == RTSP_TRANSPORT_RTP) {
  1622. rtsp_st = first_queue_st;
  1623. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1624. goto end;
  1625. }
  1626. if (len < 0)
  1627. return len;
  1628. if (len == 0)
  1629. return AVERROR_EOF;
  1630. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1631. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1632. } else {
  1633. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1634. if (ret < 0) {
  1635. /* Either bad packet, or a RTCP packet. Check if the
  1636. * first_rtcp_ntp_time field was initialized. */
  1637. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1638. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1639. /* first_rtcp_ntp_time has been initialized for this stream,
  1640. * copy the same value to all other uninitialized streams,
  1641. * in order to map their timestamp origin to the same ntp time
  1642. * as this one. */
  1643. int i;
  1644. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1645. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1646. if (rtpctx2 &&
  1647. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  1648. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1649. }
  1650. }
  1651. if (ret == -RTCP_BYE) {
  1652. rt->nb_byes++;
  1653. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1654. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1655. if (rt->nb_byes == rt->nb_rtsp_streams)
  1656. return AVERROR_EOF;
  1657. }
  1658. }
  1659. }
  1660. end:
  1661. if (ret < 0)
  1662. goto redo;
  1663. if (ret == 1)
  1664. /* more packets may follow, so we save the RTP context */
  1665. rt->cur_transport_priv = rtsp_st->transport_priv;
  1666. return ret;
  1667. }
  1668. #if CONFIG_RTSP_DEMUXER
  1669. static int rtsp_read_header(AVFormatContext *s,
  1670. AVFormatParameters *ap)
  1671. {
  1672. RTSPState *rt = s->priv_data;
  1673. int ret;
  1674. ret = ff_rtsp_connect(s);
  1675. if (ret)
  1676. return ret;
  1677. rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
  1678. if (!rt->real_setup_cache)
  1679. return AVERROR(ENOMEM);
  1680. rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);
  1681. if (ap->initial_pause) {
  1682. /* do not start immediately */
  1683. } else {
  1684. if (rtsp_read_play(s) < 0) {
  1685. ff_rtsp_close_streams(s);
  1686. ff_rtsp_close_connections(s);
  1687. return AVERROR_INVALIDDATA;
  1688. }
  1689. }
  1690. return 0;
  1691. }
  1692. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1693. uint8_t *buf, int buf_size)
  1694. {
  1695. RTSPState *rt = s->priv_data;
  1696. int id, len, i, ret;
  1697. RTSPStream *rtsp_st;
  1698. #ifdef DEBUG_RTP_TCP
  1699. dprintf(s, "tcp_read_packet:\n");
  1700. #endif
  1701. redo:
  1702. for (;;) {
  1703. RTSPMessageHeader reply;
  1704. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1705. if (ret < 0)
  1706. return ret;
  1707. if (ret == 1) /* received '$' */
  1708. break;
  1709. /* XXX: parse message */
  1710. if (rt->state != RTSP_STATE_STREAMING)
  1711. return 0;
  1712. }
  1713. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1714. if (ret != 3)
  1715. return -1;
  1716. id = buf[0];
  1717. len = AV_RB16(buf + 1);
  1718. #ifdef DEBUG_RTP_TCP
  1719. dprintf(s, "id=%d len=%d\n", id, len);
  1720. #endif
  1721. if (len > buf_size || len < 12)
  1722. goto redo;
  1723. /* get the data */
  1724. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1725. if (ret != len)
  1726. return -1;
  1727. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1728. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1729. return -1;
  1730. /* find the matching stream */
  1731. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1732. rtsp_st = rt->rtsp_streams[i];
  1733. if (id >= rtsp_st->interleaved_min &&
  1734. id <= rtsp_st->interleaved_max)
  1735. goto found;
  1736. }
  1737. goto redo;
  1738. found:
  1739. *prtsp_st = rtsp_st;
  1740. return len;
  1741. }
  1742. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1743. {
  1744. RTSPState *rt = s->priv_data;
  1745. int ret;
  1746. RTSPMessageHeader reply1, *reply = &reply1;
  1747. char cmd[1024];
  1748. if (rt->server_type == RTSP_SERVER_REAL) {
  1749. int i;
  1750. for (i = 0; i < s->nb_streams; i++)
  1751. rt->real_setup[i] = s->streams[i]->discard;
  1752. if (!rt->need_subscription) {
  1753. if (memcmp (rt->real_setup, rt->real_setup_cache,
  1754. sizeof(enum AVDiscard) * s->nb_streams)) {
  1755. snprintf(cmd, sizeof(cmd),
  1756. "Unsubscribe: %s\r\n",
  1757. rt->last_subscription);
  1758. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1759. cmd, reply, NULL);
  1760. if (reply->status_code != RTSP_STATUS_OK)
  1761. return AVERROR_INVALIDDATA;
  1762. rt->need_subscription = 1;
  1763. }
  1764. }
  1765. if (rt->need_subscription) {
  1766. int r, rule_nr, first = 1;
  1767. memcpy(rt->real_setup_cache, rt->real_setup,
  1768. sizeof(enum AVDiscard) * s->nb_streams);
  1769. rt->last_subscription[0] = 0;
  1770. snprintf(cmd, sizeof(cmd),
  1771. "Subscribe: ");
  1772. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1773. rule_nr = 0;
  1774. for (r = 0; r < s->nb_streams; r++) {
  1775. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1776. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1777. if (!first)
  1778. av_strlcat(rt->last_subscription, ",",
  1779. sizeof(rt->last_subscription));
  1780. ff_rdt_subscribe_rule(
  1781. rt->last_subscription,
  1782. sizeof(rt->last_subscription), i, rule_nr);
  1783. first = 0;
  1784. }
  1785. rule_nr++;
  1786. }
  1787. }
  1788. }
  1789. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1790. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1791. cmd, reply, NULL);
  1792. if (reply->status_code != RTSP_STATUS_OK)
  1793. return AVERROR_INVALIDDATA;
  1794. rt->need_subscription = 0;
  1795. if (rt->state == RTSP_STATE_STREAMING)
  1796. rtsp_read_play (s);
  1797. }
  1798. }
  1799. ret = rtsp_fetch_packet(s, pkt);
  1800. if (ret < 0)
  1801. return ret;
  1802. /* send dummy request to keep TCP connection alive */
  1803. if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1804. if (rt->server_type == RTSP_SERVER_WMS) {
  1805. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  1806. } else {
  1807. ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
  1808. }
  1809. }
  1810. return 0;
  1811. }
  1812. /* pause the stream */
  1813. static int rtsp_read_pause(AVFormatContext *s)
  1814. {
  1815. RTSPState *rt = s->priv_data;
  1816. RTSPMessageHeader reply1, *reply = &reply1;
  1817. if (rt->state != RTSP_STATE_STREAMING)
  1818. return 0;
  1819. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1820. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  1821. if (reply->status_code != RTSP_STATUS_OK) {
  1822. return -1;
  1823. }
  1824. }
  1825. rt->state = RTSP_STATE_PAUSED;
  1826. return 0;
  1827. }
  1828. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1829. int64_t timestamp, int flags)
  1830. {
  1831. RTSPState *rt = s->priv_data;
  1832. rt->seek_timestamp = av_rescale_q(timestamp,
  1833. s->streams[stream_index]->time_base,
  1834. AV_TIME_BASE_Q);
  1835. switch(rt->state) {
  1836. default:
  1837. case RTSP_STATE_IDLE:
  1838. break;
  1839. case RTSP_STATE_STREAMING:
  1840. if (rtsp_read_pause(s) != 0)
  1841. return -1;
  1842. rt->state = RTSP_STATE_SEEKING;
  1843. if (rtsp_read_play(s) != 0)
  1844. return -1;
  1845. break;
  1846. case RTSP_STATE_PAUSED:
  1847. rt->state = RTSP_STATE_IDLE;
  1848. break;
  1849. }
  1850. return 0;
  1851. }
  1852. static int rtsp_read_close(AVFormatContext *s)
  1853. {
  1854. RTSPState *rt = s->priv_data;
  1855. #if 0
  1856. /* NOTE: it is valid to flush the buffer here */
  1857. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1858. url_fclose(&rt->rtsp_gb);
  1859. }
  1860. #endif
  1861. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  1862. ff_rtsp_close_streams(s);
  1863. ff_rtsp_close_connections(s);
  1864. ff_network_close();
  1865. rt->real_setup = NULL;
  1866. av_freep(&rt->real_setup_cache);
  1867. return 0;
  1868. }
  1869. AVInputFormat rtsp_demuxer = {
  1870. "rtsp",
  1871. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1872. sizeof(RTSPState),
  1873. rtsp_probe,
  1874. rtsp_read_header,
  1875. rtsp_read_packet,
  1876. rtsp_read_close,
  1877. rtsp_read_seek,
  1878. .flags = AVFMT_NOFILE,
  1879. .read_play = rtsp_read_play,
  1880. .read_pause = rtsp_read_pause,
  1881. };
  1882. #endif /* CONFIG_RTSP_DEMUXER */
  1883. static int sdp_probe(AVProbeData *p1)
  1884. {
  1885. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1886. /* we look for a line beginning "c=IN IP" */
  1887. while (p < p_end && *p != '\0') {
  1888. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1889. av_strstart(p, "c=IN IP", NULL))
  1890. return AVPROBE_SCORE_MAX / 2;
  1891. while (p < p_end - 1 && *p != '\n') p++;
  1892. if (++p >= p_end)
  1893. break;
  1894. if (*p == '\r')
  1895. p++;
  1896. }
  1897. return 0;
  1898. }
  1899. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1900. {
  1901. RTSPState *rt = s->priv_data;
  1902. RTSPStream *rtsp_st;
  1903. int size, i, err;
  1904. char *content;
  1905. char url[1024];
  1906. if (!ff_network_init())
  1907. return AVERROR(EIO);
  1908. /* read the whole sdp file */
  1909. /* XXX: better loading */
  1910. content = av_malloc(SDP_MAX_SIZE);
  1911. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1912. if (size <= 0) {
  1913. av_free(content);
  1914. return AVERROR_INVALIDDATA;
  1915. }
  1916. content[size] ='\0';
  1917. sdp_parse(s, content);
  1918. av_free(content);
  1919. /* open each RTP stream */
  1920. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1921. char namebuf[50];
  1922. rtsp_st = rt->rtsp_streams[i];
  1923. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1924. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1925. ff_url_join(url, sizeof(url), "rtp", NULL,
  1926. namebuf, rtsp_st->sdp_port,
  1927. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1928. rtsp_st->sdp_ttl);
  1929. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1930. err = AVERROR_INVALIDDATA;
  1931. goto fail;
  1932. }
  1933. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1934. goto fail;
  1935. }
  1936. return 0;
  1937. fail:
  1938. ff_rtsp_close_streams(s);
  1939. ff_network_close();
  1940. return err;
  1941. }
  1942. static int sdp_read_close(AVFormatContext *s)
  1943. {
  1944. ff_rtsp_close_streams(s);
  1945. ff_network_close();
  1946. return 0;
  1947. }
  1948. AVInputFormat sdp_demuxer = {
  1949. "sdp",
  1950. NULL_IF_CONFIG_SMALL("SDP"),
  1951. sizeof(RTSPState),
  1952. sdp_probe,
  1953. sdp_read_header,
  1954. rtsp_fetch_packet,
  1955. sdp_read_close,
  1956. };