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.

2049 lines
73KB

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