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.

2015 lines
71KB

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