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.

2034 lines
72KB

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