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.

2053 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 DEFAULT_REORDERING_DELAY 100000
  55. #define OFFSET(x) offsetof(RTSPState, x)
  56. #define DEC AV_OPT_FLAG_DECODING_PARAM
  57. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  58. #define RTSP_FLAG_OPTS(name, longname) \
  59. { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
  60. { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
  61. #define RTSP_MEDIATYPE_OPTS(name, longname) \
  62. { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
  63. { "video", "Video", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
  64. { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
  65. { "data", "Data", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
  66. const AVOption ff_rtsp_options[] = {
  67. { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {0}, 0, 1, DEC },
  68. FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags)
  69. { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
  70. { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
  71. { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
  72. { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
  73. { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {(1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
  74. RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
  75. RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
  76. { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
  77. { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
  78. { NULL },
  79. };
  80. static const AVOption sdp_options[] = {
  81. RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
  82. RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
  83. { NULL },
  84. };
  85. static const AVOption rtp_options[] = {
  86. RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
  87. { NULL },
  88. };
  89. static void get_word_until_chars(char *buf, int buf_size,
  90. const char *sep, const char **pp)
  91. {
  92. const char *p;
  93. char *q;
  94. p = *pp;
  95. p += strspn(p, SPACE_CHARS);
  96. q = buf;
  97. while (!strchr(sep, *p) && *p != '\0') {
  98. if ((q - buf) < buf_size - 1)
  99. *q++ = *p;
  100. p++;
  101. }
  102. if (buf_size > 0)
  103. *q = '\0';
  104. *pp = p;
  105. }
  106. static void get_word_sep(char *buf, int buf_size, const char *sep,
  107. const char **pp)
  108. {
  109. if (**pp == '/') (*pp)++;
  110. get_word_until_chars(buf, buf_size, sep, pp);
  111. }
  112. static void get_word(char *buf, int buf_size, const char **pp)
  113. {
  114. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  115. }
  116. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  117. * and end time.
  118. * Used for seeking in the rtp stream.
  119. */
  120. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  121. {
  122. char buf[256];
  123. p += strspn(p, SPACE_CHARS);
  124. if (!av_stristart(p, "npt=", &p))
  125. return;
  126. *start = AV_NOPTS_VALUE;
  127. *end = AV_NOPTS_VALUE;
  128. get_word_sep(buf, sizeof(buf), "-", &p);
  129. av_parse_time(start, buf, 1);
  130. if (*p == '-') {
  131. p++;
  132. get_word_sep(buf, sizeof(buf), "-", &p);
  133. av_parse_time(end, buf, 1);
  134. }
  135. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  136. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  137. }
  138. static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
  139. {
  140. struct addrinfo hints = { 0 }, *ai = NULL;
  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 = { { 0 } }, *s1 = &sdp_parse_state;
  461. p = content;
  462. for (;;) {
  463. p += strspn(p, SPACE_CHARS);
  464. letter = *p;
  465. if (letter == '\0')
  466. break;
  467. p++;
  468. if (*p != '=')
  469. goto next_line;
  470. p++;
  471. /* get the content */
  472. q = buf;
  473. while (*p != '\n' && *p != '\r' && *p != '\0') {
  474. if ((q - buf) < sizeof(buf) - 1)
  475. *q++ = *p;
  476. p++;
  477. }
  478. *q = '\0';
  479. sdp_parse_line(s, s1, letter, buf);
  480. next_line:
  481. while (*p != '\n' && *p != '\0')
  482. p++;
  483. if (*p == '\n')
  484. p++;
  485. }
  486. rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
  487. if (!rt->p) return AVERROR(ENOMEM);
  488. return 0;
  489. }
  490. #endif /* CONFIG_RTPDEC */
  491. void ff_rtsp_undo_setup(AVFormatContext *s)
  492. {
  493. RTSPState *rt = s->priv_data;
  494. int i;
  495. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  496. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  497. if (!rtsp_st)
  498. continue;
  499. if (rtsp_st->transport_priv) {
  500. if (s->oformat) {
  501. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  502. av_write_trailer(rtpctx);
  503. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  504. uint8_t *ptr;
  505. avio_close_dyn_buf(rtpctx->pb, &ptr);
  506. av_free(ptr);
  507. } else {
  508. avio_close(rtpctx->pb);
  509. }
  510. avformat_free_context(rtpctx);
  511. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  512. ff_rdt_parse_close(rtsp_st->transport_priv);
  513. else if (CONFIG_RTPDEC)
  514. ff_rtp_parse_close(rtsp_st->transport_priv);
  515. }
  516. rtsp_st->transport_priv = NULL;
  517. if (rtsp_st->rtp_handle)
  518. ffurl_close(rtsp_st->rtp_handle);
  519. rtsp_st->rtp_handle = NULL;
  520. }
  521. }
  522. /* close and free RTSP streams */
  523. void ff_rtsp_close_streams(AVFormatContext *s)
  524. {
  525. RTSPState *rt = s->priv_data;
  526. int i;
  527. RTSPStream *rtsp_st;
  528. ff_rtsp_undo_setup(s);
  529. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  530. rtsp_st = rt->rtsp_streams[i];
  531. if (rtsp_st) {
  532. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  533. rtsp_st->dynamic_handler->free(
  534. rtsp_st->dynamic_protocol_context);
  535. av_free(rtsp_st);
  536. }
  537. }
  538. av_free(rt->rtsp_streams);
  539. if (rt->asf_ctx) {
  540. avformat_close_input(&rt->asf_ctx);
  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, request = 0;
  834. unsigned char *content = NULL;
  835. start:
  836. line_count = 0;
  837. request = 0;
  838. content = NULL;
  839. memset(reply, 0, sizeof(*reply));
  840. /* parse reply (XXX: use buffers) */
  841. rt->last_reply[0] = '\0';
  842. for (;;) {
  843. q = buf;
  844. for (;;) {
  845. ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
  846. av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  847. if (ret != 1)
  848. return AVERROR_EOF;
  849. if (ch == '\n')
  850. break;
  851. if (ch == '$') {
  852. /* XXX: only parse it if first char on line ? */
  853. if (return_on_interleaved_data) {
  854. return 1;
  855. } else
  856. ff_rtsp_skip_packet(s);
  857. } else if (ch != '\r') {
  858. if ((q - buf) < sizeof(buf) - 1)
  859. *q++ = ch;
  860. }
  861. }
  862. *q = '\0';
  863. av_dlog(s, "line='%s'\n", buf);
  864. /* test if last line */
  865. if (buf[0] == '\0')
  866. break;
  867. p = buf;
  868. if (line_count == 0) {
  869. /* get reply code */
  870. get_word(buf1, sizeof(buf1), &p);
  871. if (!strncmp(buf1, "RTSP/", 5)) {
  872. get_word(buf1, sizeof(buf1), &p);
  873. reply->status_code = atoi(buf1);
  874. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  875. } else {
  876. av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
  877. get_word(buf1, sizeof(buf1), &p); // object
  878. request = 1;
  879. }
  880. } else {
  881. ff_rtsp_parse_line(reply, p, rt, method);
  882. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  883. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  884. }
  885. line_count++;
  886. }
  887. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
  888. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  889. content_length = reply->content_length;
  890. if (content_length > 0) {
  891. /* leave some room for a trailing '\0' (useful for simple parsing) */
  892. content = av_malloc(content_length + 1);
  893. ffurl_read_complete(rt->rtsp_hd, content, content_length);
  894. content[content_length] = '\0';
  895. }
  896. if (content_ptr)
  897. *content_ptr = content;
  898. else
  899. av_free(content);
  900. if (request) {
  901. char buf[1024];
  902. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  903. const char* ptr = buf;
  904. if (!strcmp(reply->reason, "OPTIONS")) {
  905. snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
  906. if (reply->seq)
  907. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
  908. if (reply->session_id[0])
  909. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
  910. reply->session_id);
  911. } else {
  912. snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
  913. }
  914. av_strlcat(buf, "\r\n", sizeof(buf));
  915. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  916. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  917. ptr = base64buf;
  918. }
  919. ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
  920. rt->last_cmd_time = av_gettime();
  921. /* Even if the request from the server had data, it is not the data
  922. * that the caller wants or expects. The memory could also be leaked
  923. * if the actual following reply has content data. */
  924. if (content_ptr)
  925. av_freep(content_ptr);
  926. /* If method is set, this is called from ff_rtsp_send_cmd,
  927. * where a reply to exactly this request is awaited. For
  928. * callers from within packet receiving, we just want to
  929. * return to the caller and go back to receiving packets. */
  930. if (method)
  931. goto start;
  932. return 0;
  933. }
  934. if (rt->seq != reply->seq) {
  935. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  936. rt->seq, reply->seq);
  937. }
  938. /* EOS */
  939. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  940. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  941. reply->notice == 2306 /* Continuous Feed Terminated */) {
  942. rt->state = RTSP_STATE_IDLE;
  943. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  944. return AVERROR(EIO); /* data or server error */
  945. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  946. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  947. return AVERROR(EPERM);
  948. return 0;
  949. }
  950. /**
  951. * Send a command to the RTSP server without waiting for the reply.
  952. *
  953. * @param s RTSP (de)muxer context
  954. * @param method the method for the request
  955. * @param url the target url for the request
  956. * @param headers extra header lines to include in the request
  957. * @param send_content if non-null, the data to send as request body content
  958. * @param send_content_length the length of the send_content data, or 0 if
  959. * send_content is null
  960. *
  961. * @return zero if success, nonzero otherwise
  962. */
  963. static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  964. const char *method, const char *url,
  965. const char *headers,
  966. const unsigned char *send_content,
  967. int send_content_length)
  968. {
  969. RTSPState *rt = s->priv_data;
  970. char buf[4096], *out_buf;
  971. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  972. /* Add in RTSP headers */
  973. out_buf = buf;
  974. rt->seq++;
  975. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  976. if (headers)
  977. av_strlcat(buf, headers, sizeof(buf));
  978. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  979. if (rt->session_id[0] != '\0' && (!headers ||
  980. !strstr(headers, "\nIf-Match:"))) {
  981. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  982. }
  983. if (rt->auth[0]) {
  984. char *str = ff_http_auth_create_response(&rt->auth_state,
  985. rt->auth, url, method);
  986. if (str)
  987. av_strlcat(buf, str, sizeof(buf));
  988. av_free(str);
  989. }
  990. if (send_content_length > 0 && send_content)
  991. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  992. av_strlcat(buf, "\r\n", sizeof(buf));
  993. /* base64 encode rtsp if tunneling */
  994. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  995. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  996. out_buf = base64buf;
  997. }
  998. av_dlog(s, "Sending:\n%s--\n", buf);
  999. ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  1000. if (send_content_length > 0 && send_content) {
  1001. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1002. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  1003. "with content data not supported\n");
  1004. return AVERROR_PATCHWELCOME;
  1005. }
  1006. ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
  1007. }
  1008. rt->last_cmd_time = av_gettime();
  1009. return 0;
  1010. }
  1011. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  1012. const char *url, const char *headers)
  1013. {
  1014. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  1015. }
  1016. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  1017. const char *headers, RTSPMessageHeader *reply,
  1018. unsigned char **content_ptr)
  1019. {
  1020. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  1021. content_ptr, NULL, 0);
  1022. }
  1023. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  1024. const char *method, const char *url,
  1025. const char *header,
  1026. RTSPMessageHeader *reply,
  1027. unsigned char **content_ptr,
  1028. const unsigned char *send_content,
  1029. int send_content_length)
  1030. {
  1031. RTSPState *rt = s->priv_data;
  1032. HTTPAuthType cur_auth_type;
  1033. int ret, attempts = 0;
  1034. retry:
  1035. cur_auth_type = rt->auth_state.auth_type;
  1036. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  1037. send_content,
  1038. send_content_length)))
  1039. return ret;
  1040. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
  1041. return ret;
  1042. attempts++;
  1043. if (reply->status_code == 401 &&
  1044. (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
  1045. rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
  1046. goto retry;
  1047. if (reply->status_code > 400){
  1048. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  1049. method,
  1050. reply->status_code,
  1051. reply->reason);
  1052. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  1053. }
  1054. return 0;
  1055. }
  1056. int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
  1057. int lower_transport, const char *real_challenge)
  1058. {
  1059. RTSPState *rt = s->priv_data;
  1060. int rtx = 0, j, i, err, interleave = 0, port_off;
  1061. RTSPStream *rtsp_st;
  1062. RTSPMessageHeader reply1, *reply = &reply1;
  1063. char cmd[2048];
  1064. const char *trans_pref;
  1065. if (rt->transport == RTSP_TRANSPORT_RDT)
  1066. trans_pref = "x-pn-tng";
  1067. else
  1068. trans_pref = "RTP/AVP";
  1069. /* default timeout: 1 minute */
  1070. rt->timeout = 60;
  1071. /* Choose a random starting offset within the first half of the
  1072. * port range, to allow for a number of ports to try even if the offset
  1073. * happens to be at the end of the random range. */
  1074. port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
  1075. /* even random offset */
  1076. port_off -= port_off & 0x01;
  1077. for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
  1078. char transport[2048];
  1079. /*
  1080. * WMS serves all UDP data over a single connection, the RTX, which
  1081. * isn't necessarily the first in the SDP but has to be the first
  1082. * to be set up, else the second/third SETUP will fail with a 461.
  1083. */
  1084. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  1085. rt->server_type == RTSP_SERVER_WMS) {
  1086. if (i == 0) {
  1087. /* rtx first */
  1088. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  1089. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  1090. if (len >= 4 &&
  1091. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  1092. "/rtx"))
  1093. break;
  1094. }
  1095. if (rtx == rt->nb_rtsp_streams)
  1096. return -1; /* no RTX found */
  1097. rtsp_st = rt->rtsp_streams[rtx];
  1098. } else
  1099. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  1100. } else
  1101. rtsp_st = rt->rtsp_streams[i];
  1102. /* RTP/UDP */
  1103. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  1104. char buf[256];
  1105. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  1106. port = reply->transports[0].client_port_min;
  1107. goto have_port;
  1108. }
  1109. /* first try in specified port range */
  1110. while (j <= rt->rtp_port_max) {
  1111. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  1112. "?localport=%d", j);
  1113. /* we will use two ports per rtp stream (rtp and rtcp) */
  1114. j += 2;
  1115. if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
  1116. &s->interrupt_callback, NULL))
  1117. goto rtp_opened;
  1118. }
  1119. av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
  1120. err = AVERROR(EIO);
  1121. goto fail;
  1122. rtp_opened:
  1123. port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  1124. have_port:
  1125. snprintf(transport, sizeof(transport) - 1,
  1126. "%s/UDP;", trans_pref);
  1127. if (rt->server_type != RTSP_SERVER_REAL)
  1128. av_strlcat(transport, "unicast;", sizeof(transport));
  1129. av_strlcatf(transport, sizeof(transport),
  1130. "client_port=%d", port);
  1131. if (rt->transport == RTSP_TRANSPORT_RTP &&
  1132. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  1133. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  1134. }
  1135. /* RTP/TCP */
  1136. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1137. /* For WMS streams, the application streams are only used for
  1138. * UDP. When trying to set it up for TCP streams, the server
  1139. * will return an error. Therefore, we skip those streams. */
  1140. if (rt->server_type == RTSP_SERVER_WMS &&
  1141. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  1142. AVMEDIA_TYPE_DATA)
  1143. continue;
  1144. snprintf(transport, sizeof(transport) - 1,
  1145. "%s/TCP;", trans_pref);
  1146. if (rt->transport != RTSP_TRANSPORT_RDT)
  1147. av_strlcat(transport, "unicast;", sizeof(transport));
  1148. av_strlcatf(transport, sizeof(transport),
  1149. "interleaved=%d-%d",
  1150. interleave, interleave + 1);
  1151. interleave += 2;
  1152. }
  1153. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1154. snprintf(transport, sizeof(transport) - 1,
  1155. "%s/UDP;multicast", trans_pref);
  1156. }
  1157. if (s->oformat) {
  1158. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1159. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1160. rt->server_type == RTSP_SERVER_WMS)
  1161. av_strlcat(transport, ";mode=play", sizeof(transport));
  1162. snprintf(cmd, sizeof(cmd),
  1163. "Transport: %s\r\n",
  1164. transport);
  1165. if (rt->accept_dynamic_rate)
  1166. av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
  1167. if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
  1168. char real_res[41], real_csum[9];
  1169. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1170. real_challenge);
  1171. av_strlcatf(cmd, sizeof(cmd),
  1172. "If-Match: %s\r\n"
  1173. "RealChallenge2: %s, sd=%s\r\n",
  1174. rt->session_id, real_res, real_csum);
  1175. }
  1176. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1177. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1178. err = 1;
  1179. goto fail;
  1180. } else if (reply->status_code != RTSP_STATUS_OK ||
  1181. reply->nb_transports != 1) {
  1182. err = AVERROR_INVALIDDATA;
  1183. goto fail;
  1184. }
  1185. /* XXX: same protocol for all streams is required */
  1186. if (i > 0) {
  1187. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1188. reply->transports[0].transport != rt->transport) {
  1189. err = AVERROR_INVALIDDATA;
  1190. goto fail;
  1191. }
  1192. } else {
  1193. rt->lower_transport = reply->transports[0].lower_transport;
  1194. rt->transport = reply->transports[0].transport;
  1195. }
  1196. /* Fail if the server responded with another lower transport mode
  1197. * than what we requested. */
  1198. if (reply->transports[0].lower_transport != lower_transport) {
  1199. av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
  1200. err = AVERROR_INVALIDDATA;
  1201. goto fail;
  1202. }
  1203. switch(reply->transports[0].lower_transport) {
  1204. case RTSP_LOWER_TRANSPORT_TCP:
  1205. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1206. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1207. break;
  1208. case RTSP_LOWER_TRANSPORT_UDP: {
  1209. char url[1024], options[30] = "";
  1210. if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
  1211. av_strlcpy(options, "?connect=1", sizeof(options));
  1212. /* Use source address if specified */
  1213. if (reply->transports[0].source[0]) {
  1214. ff_url_join(url, sizeof(url), "rtp", NULL,
  1215. reply->transports[0].source,
  1216. reply->transports[0].server_port_min, "%s", options);
  1217. } else {
  1218. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1219. reply->transports[0].server_port_min, "%s", options);
  1220. }
  1221. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1222. ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1223. err = AVERROR_INVALIDDATA;
  1224. goto fail;
  1225. }
  1226. /* Try to initialize the connection state in a
  1227. * potential NAT router by sending dummy packets.
  1228. * RTP/RTCP dummy packets are used for RDT, too.
  1229. */
  1230. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
  1231. CONFIG_RTPDEC)
  1232. ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
  1233. break;
  1234. }
  1235. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1236. char url[1024], namebuf[50], optbuf[20] = "";
  1237. struct sockaddr_storage addr;
  1238. int port, ttl;
  1239. if (reply->transports[0].destination.ss_family) {
  1240. addr = reply->transports[0].destination;
  1241. port = reply->transports[0].port_min;
  1242. ttl = reply->transports[0].ttl;
  1243. } else {
  1244. addr = rtsp_st->sdp_ip;
  1245. port = rtsp_st->sdp_port;
  1246. ttl = rtsp_st->sdp_ttl;
  1247. }
  1248. if (ttl > 0)
  1249. snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
  1250. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1251. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1252. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1253. port, "%s", optbuf);
  1254. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  1255. &s->interrupt_callback, NULL) < 0) {
  1256. err = AVERROR_INVALIDDATA;
  1257. goto fail;
  1258. }
  1259. break;
  1260. }
  1261. }
  1262. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1263. goto fail;
  1264. }
  1265. if (reply->timeout > 0)
  1266. rt->timeout = reply->timeout;
  1267. if (rt->server_type == RTSP_SERVER_REAL)
  1268. rt->need_subscription = 1;
  1269. return 0;
  1270. fail:
  1271. ff_rtsp_undo_setup(s);
  1272. return err;
  1273. }
  1274. void ff_rtsp_close_connections(AVFormatContext *s)
  1275. {
  1276. RTSPState *rt = s->priv_data;
  1277. if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
  1278. ffurl_close(rt->rtsp_hd);
  1279. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1280. }
  1281. int ff_rtsp_connect(AVFormatContext *s)
  1282. {
  1283. RTSPState *rt = s->priv_data;
  1284. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1285. int port, err, tcp_fd;
  1286. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1287. int lower_transport_mask = 0;
  1288. char real_challenge[64] = "";
  1289. struct sockaddr_storage peer;
  1290. socklen_t peer_len = sizeof(peer);
  1291. if (rt->rtp_port_max < rt->rtp_port_min) {
  1292. av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
  1293. "than min port %d\n", rt->rtp_port_max,
  1294. rt->rtp_port_min);
  1295. return AVERROR(EINVAL);
  1296. }
  1297. if (!ff_network_init())
  1298. return AVERROR(EIO);
  1299. if (s->max_delay < 0) /* Not set by the caller */
  1300. s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
  1301. rt->control_transport = RTSP_MODE_PLAIN;
  1302. if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
  1303. rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
  1304. rt->control_transport = RTSP_MODE_TUNNEL;
  1305. }
  1306. /* Only pass through valid flags from here */
  1307. rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1308. redirect:
  1309. lower_transport_mask = rt->lower_transport_mask;
  1310. /* extract hostname and port */
  1311. av_url_split(NULL, 0, auth, sizeof(auth),
  1312. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1313. if (*auth) {
  1314. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1315. }
  1316. if (port < 0)
  1317. port = RTSP_DEFAULT_PORT;
  1318. if (!lower_transport_mask)
  1319. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1320. if (s->oformat) {
  1321. /* Only UDP or TCP - UDP multicast isn't supported. */
  1322. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1323. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1324. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1325. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1326. "only UDP and TCP are supported for output.\n");
  1327. err = AVERROR(EINVAL);
  1328. goto fail;
  1329. }
  1330. }
  1331. /* Construct the URI used in request; this is similar to s->filename,
  1332. * but with authentication credentials removed and RTSP specific options
  1333. * stripped out. */
  1334. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1335. host, port, "%s", path);
  1336. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1337. /* set up initial handshake for tunneling */
  1338. char httpname[1024];
  1339. char sessioncookie[17];
  1340. char headers[1024];
  1341. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1342. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1343. av_get_random_seed(), av_get_random_seed());
  1344. /* GET requests */
  1345. if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
  1346. &s->interrupt_callback) < 0) {
  1347. err = AVERROR(EIO);
  1348. goto fail;
  1349. }
  1350. /* generate GET headers */
  1351. snprintf(headers, sizeof(headers),
  1352. "x-sessioncookie: %s\r\n"
  1353. "Accept: application/x-rtsp-tunnelled\r\n"
  1354. "Pragma: no-cache\r\n"
  1355. "Cache-Control: no-cache\r\n",
  1356. sessioncookie);
  1357. av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
  1358. /* complete the connection */
  1359. if (ffurl_connect(rt->rtsp_hd, NULL)) {
  1360. err = AVERROR(EIO);
  1361. goto fail;
  1362. }
  1363. /* POST requests */
  1364. if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
  1365. &s->interrupt_callback) < 0 ) {
  1366. err = AVERROR(EIO);
  1367. goto fail;
  1368. }
  1369. /* generate POST headers */
  1370. snprintf(headers, sizeof(headers),
  1371. "x-sessioncookie: %s\r\n"
  1372. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1373. "Pragma: no-cache\r\n"
  1374. "Cache-Control: no-cache\r\n"
  1375. "Content-Length: 32767\r\n"
  1376. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1377. sessioncookie);
  1378. av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
  1379. av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
  1380. /* Initialize the authentication state for the POST session. The HTTP
  1381. * protocol implementation doesn't properly handle multi-pass
  1382. * authentication for POST requests, since it would require one of
  1383. * the following:
  1384. * - implementing Expect: 100-continue, which many HTTP servers
  1385. * don't support anyway, even less the RTSP servers that do HTTP
  1386. * tunneling
  1387. * - sending the whole POST data until getting a 401 reply specifying
  1388. * what authentication method to use, then resending all that data
  1389. * - waiting for potential 401 replies directly after sending the
  1390. * POST header (waiting for some unspecified time)
  1391. * Therefore, we copy the full auth state, which works for both basic
  1392. * and digest. (For digest, we would have to synchronize the nonce
  1393. * count variable between the two sessions, if we'd do more requests
  1394. * with the original session, though.)
  1395. */
  1396. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1397. /* complete the connection */
  1398. if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
  1399. err = AVERROR(EIO);
  1400. goto fail;
  1401. }
  1402. } else {
  1403. /* open the tcp connection */
  1404. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1405. if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
  1406. &s->interrupt_callback, NULL) < 0) {
  1407. err = AVERROR(EIO);
  1408. goto fail;
  1409. }
  1410. rt->rtsp_hd_out = rt->rtsp_hd;
  1411. }
  1412. rt->seq = 0;
  1413. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1414. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1415. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1416. NULL, 0, NI_NUMERICHOST);
  1417. }
  1418. /* request options supported by the server; this also detects server
  1419. * type */
  1420. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1421. cmd[0] = 0;
  1422. if (rt->server_type == RTSP_SERVER_REAL)
  1423. av_strlcat(cmd,
  1424. /*
  1425. * The following entries are required for proper
  1426. * streaming from a Realmedia server. They are
  1427. * interdependent in some way although we currently
  1428. * don't quite understand how. Values were copied
  1429. * from mplayer SVN r23589.
  1430. * ClientChallenge is a 16-byte ID in hex
  1431. * CompanyID is a 16-byte ID in base64
  1432. */
  1433. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1434. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1435. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1436. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1437. sizeof(cmd));
  1438. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1439. if (reply->status_code != RTSP_STATUS_OK) {
  1440. err = AVERROR_INVALIDDATA;
  1441. goto fail;
  1442. }
  1443. /* detect server type if not standard-compliant RTP */
  1444. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1445. rt->server_type = RTSP_SERVER_REAL;
  1446. continue;
  1447. } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
  1448. rt->server_type = RTSP_SERVER_WMS;
  1449. } else if (rt->server_type == RTSP_SERVER_REAL)
  1450. strcpy(real_challenge, reply->real_challenge);
  1451. break;
  1452. }
  1453. if (s->iformat && CONFIG_RTSP_DEMUXER)
  1454. err = ff_rtsp_setup_input_streams(s, reply);
  1455. else if (CONFIG_RTSP_MUXER)
  1456. err = ff_rtsp_setup_output_streams(s, host);
  1457. if (err)
  1458. goto fail;
  1459. do {
  1460. int lower_transport = ff_log2_tab[lower_transport_mask &
  1461. ~(lower_transport_mask - 1)];
  1462. err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
  1463. rt->server_type == RTSP_SERVER_REAL ?
  1464. real_challenge : NULL);
  1465. if (err < 0)
  1466. goto fail;
  1467. lower_transport_mask &= ~(1 << lower_transport);
  1468. if (lower_transport_mask == 0 && err == 1) {
  1469. err = AVERROR(EPROTONOSUPPORT);
  1470. goto fail;
  1471. }
  1472. } while (err);
  1473. rt->lower_transport_mask = lower_transport_mask;
  1474. av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
  1475. rt->state = RTSP_STATE_IDLE;
  1476. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1477. return 0;
  1478. fail:
  1479. ff_rtsp_close_streams(s);
  1480. ff_rtsp_close_connections(s);
  1481. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1482. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1483. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1484. reply->status_code,
  1485. s->filename);
  1486. goto redirect;
  1487. }
  1488. ff_network_close();
  1489. return err;
  1490. }
  1491. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1492. #if CONFIG_RTPDEC
  1493. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1494. uint8_t *buf, int buf_size, int64_t wait_end)
  1495. {
  1496. RTSPState *rt = s->priv_data;
  1497. RTSPStream *rtsp_st;
  1498. int n, i, ret, tcp_fd, timeout_cnt = 0;
  1499. int max_p = 0;
  1500. struct pollfd *p = rt->p;
  1501. for (;;) {
  1502. if (ff_check_interrupt(&s->interrupt_callback))
  1503. return AVERROR_EXIT;
  1504. if (wait_end && wait_end - av_gettime() < 0)
  1505. return AVERROR(EAGAIN);
  1506. max_p = 0;
  1507. if (rt->rtsp_hd) {
  1508. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1509. p[max_p].fd = tcp_fd;
  1510. p[max_p++].events = POLLIN;
  1511. } else {
  1512. tcp_fd = -1;
  1513. }
  1514. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1515. rtsp_st = rt->rtsp_streams[i];
  1516. if (rtsp_st->rtp_handle) {
  1517. p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
  1518. p[max_p++].events = POLLIN;
  1519. p[max_p].fd = ff_rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1520. p[max_p++].events = POLLIN;
  1521. }
  1522. }
  1523. n = poll(p, max_p, POLL_TIMEOUT_MS);
  1524. if (n > 0) {
  1525. int j = 1 - (tcp_fd == -1);
  1526. timeout_cnt = 0;
  1527. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1528. rtsp_st = rt->rtsp_streams[i];
  1529. if (rtsp_st->rtp_handle) {
  1530. if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
  1531. ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
  1532. if (ret > 0) {
  1533. *prtsp_st = rtsp_st;
  1534. return ret;
  1535. }
  1536. }
  1537. j+=2;
  1538. }
  1539. }
  1540. #if CONFIG_RTSP_DEMUXER
  1541. if (tcp_fd != -1 && p[0].revents & POLLIN) {
  1542. RTSPMessageHeader reply;
  1543. ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
  1544. if (ret < 0)
  1545. return ret;
  1546. /* XXX: parse message */
  1547. if (rt->state != RTSP_STATE_STREAMING)
  1548. return 0;
  1549. }
  1550. #endif
  1551. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1552. return AVERROR(ETIMEDOUT);
  1553. } else if (n < 0 && errno != EINTR)
  1554. return AVERROR(errno);
  1555. }
  1556. }
  1557. int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1558. {
  1559. RTSPState *rt = s->priv_data;
  1560. int ret, len;
  1561. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1562. int64_t wait_end = 0;
  1563. if (rt->nb_byes == rt->nb_rtsp_streams)
  1564. return AVERROR_EOF;
  1565. /* get next frames from the same RTP packet */
  1566. if (rt->cur_transport_priv) {
  1567. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1568. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1569. } else
  1570. ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1571. if (ret == 0) {
  1572. rt->cur_transport_priv = NULL;
  1573. return 0;
  1574. } else if (ret == 1) {
  1575. return 0;
  1576. } else
  1577. rt->cur_transport_priv = NULL;
  1578. }
  1579. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1580. int i;
  1581. int64_t first_queue_time = 0;
  1582. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1583. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1584. int64_t queue_time;
  1585. if (!rtpctx)
  1586. continue;
  1587. queue_time = ff_rtp_queued_packet_time(rtpctx);
  1588. if (queue_time && (queue_time - first_queue_time < 0 ||
  1589. !first_queue_time)) {
  1590. first_queue_time = queue_time;
  1591. first_queue_st = rt->rtsp_streams[i];
  1592. }
  1593. }
  1594. if (first_queue_time)
  1595. wait_end = first_queue_time + s->max_delay;
  1596. }
  1597. /* read next RTP packet */
  1598. redo:
  1599. if (!rt->recvbuf) {
  1600. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1601. if (!rt->recvbuf)
  1602. return AVERROR(ENOMEM);
  1603. }
  1604. switch(rt->lower_transport) {
  1605. default:
  1606. #if CONFIG_RTSP_DEMUXER
  1607. case RTSP_LOWER_TRANSPORT_TCP:
  1608. len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1609. break;
  1610. #endif
  1611. case RTSP_LOWER_TRANSPORT_UDP:
  1612. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1613. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1614. if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1615. ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1616. break;
  1617. }
  1618. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1619. rt->transport == RTSP_TRANSPORT_RTP) {
  1620. rtsp_st = first_queue_st;
  1621. ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1622. goto end;
  1623. }
  1624. if (len < 0)
  1625. return len;
  1626. if (len == 0)
  1627. return AVERROR_EOF;
  1628. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1629. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1630. } else {
  1631. ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1632. if (ret < 0) {
  1633. /* Either bad packet, or a RTCP packet. Check if the
  1634. * first_rtcp_ntp_time field was initialized. */
  1635. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1636. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1637. /* first_rtcp_ntp_time has been initialized for this stream,
  1638. * copy the same value to all other uninitialized streams,
  1639. * in order to map their timestamp origin to the same ntp time
  1640. * as this one. */
  1641. int i;
  1642. AVStream *st = NULL;
  1643. if (rtsp_st->stream_index >= 0)
  1644. st = s->streams[rtsp_st->stream_index];
  1645. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1646. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1647. AVStream *st2 = NULL;
  1648. if (rt->rtsp_streams[i]->stream_index >= 0)
  1649. st2 = s->streams[rt->rtsp_streams[i]->stream_index];
  1650. if (rtpctx2 && st && st2 &&
  1651. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  1652. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1653. rtpctx2->rtcp_ts_offset = av_rescale_q(
  1654. rtpctx->rtcp_ts_offset, st->time_base,
  1655. st2->time_base);
  1656. }
  1657. }
  1658. }
  1659. if (ret == -RTCP_BYE) {
  1660. rt->nb_byes++;
  1661. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1662. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1663. if (rt->nb_byes == rt->nb_rtsp_streams)
  1664. return AVERROR_EOF;
  1665. }
  1666. }
  1667. }
  1668. end:
  1669. if (ret < 0)
  1670. goto redo;
  1671. if (ret == 1)
  1672. /* more packets may follow, so we save the RTP context */
  1673. rt->cur_transport_priv = rtsp_st->transport_priv;
  1674. return ret;
  1675. }
  1676. #endif /* CONFIG_RTPDEC */
  1677. #if CONFIG_SDP_DEMUXER
  1678. static int sdp_probe(AVProbeData *p1)
  1679. {
  1680. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1681. /* we look for a line beginning "c=IN IP" */
  1682. while (p < p_end && *p != '\0') {
  1683. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1684. av_strstart(p, "c=IN IP", NULL))
  1685. return AVPROBE_SCORE_MAX / 2;
  1686. while (p < p_end - 1 && *p != '\n') p++;
  1687. if (++p >= p_end)
  1688. break;
  1689. if (*p == '\r')
  1690. p++;
  1691. }
  1692. return 0;
  1693. }
  1694. static int sdp_read_header(AVFormatContext *s)
  1695. {
  1696. RTSPState *rt = s->priv_data;
  1697. RTSPStream *rtsp_st;
  1698. int size, i, err;
  1699. char *content;
  1700. char url[1024];
  1701. if (!ff_network_init())
  1702. return AVERROR(EIO);
  1703. if (s->max_delay < 0) /* Not set by the caller */
  1704. s->max_delay = DEFAULT_REORDERING_DELAY;
  1705. /* read the whole sdp file */
  1706. /* XXX: better loading */
  1707. content = av_malloc(SDP_MAX_SIZE);
  1708. size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
  1709. if (size <= 0) {
  1710. av_free(content);
  1711. return AVERROR_INVALIDDATA;
  1712. }
  1713. content[size] ='\0';
  1714. err = ff_sdp_parse(s, content);
  1715. av_free(content);
  1716. if (err) goto fail;
  1717. /* open each RTP stream */
  1718. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1719. char namebuf[50];
  1720. rtsp_st = rt->rtsp_streams[i];
  1721. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1722. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1723. ff_url_join(url, sizeof(url), "rtp", NULL,
  1724. namebuf, rtsp_st->sdp_port,
  1725. "?localport=%d&ttl=%d&connect=%d", rtsp_st->sdp_port,
  1726. rtsp_st->sdp_ttl,
  1727. rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0);
  1728. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  1729. &s->interrupt_callback, NULL) < 0) {
  1730. err = AVERROR_INVALIDDATA;
  1731. goto fail;
  1732. }
  1733. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1734. goto fail;
  1735. }
  1736. return 0;
  1737. fail:
  1738. ff_rtsp_close_streams(s);
  1739. ff_network_close();
  1740. return err;
  1741. }
  1742. static int sdp_read_close(AVFormatContext *s)
  1743. {
  1744. ff_rtsp_close_streams(s);
  1745. ff_network_close();
  1746. return 0;
  1747. }
  1748. static const AVClass sdp_demuxer_class = {
  1749. .class_name = "SDP demuxer",
  1750. .item_name = av_default_item_name,
  1751. .option = sdp_options,
  1752. .version = LIBAVUTIL_VERSION_INT,
  1753. };
  1754. AVInputFormat ff_sdp_demuxer = {
  1755. .name = "sdp",
  1756. .long_name = NULL_IF_CONFIG_SMALL("SDP"),
  1757. .priv_data_size = sizeof(RTSPState),
  1758. .read_probe = sdp_probe,
  1759. .read_header = sdp_read_header,
  1760. .read_packet = ff_rtsp_fetch_packet,
  1761. .read_close = sdp_read_close,
  1762. .priv_class = &sdp_demuxer_class,
  1763. };
  1764. #endif /* CONFIG_SDP_DEMUXER */
  1765. #if CONFIG_RTP_DEMUXER
  1766. static int rtp_probe(AVProbeData *p)
  1767. {
  1768. if (av_strstart(p->filename, "rtp:", NULL))
  1769. return AVPROBE_SCORE_MAX;
  1770. return 0;
  1771. }
  1772. static int rtp_read_header(AVFormatContext *s)
  1773. {
  1774. uint8_t recvbuf[1500];
  1775. char host[500], sdp[500];
  1776. int ret, port;
  1777. URLContext* in = NULL;
  1778. int payload_type;
  1779. AVCodecContext codec = { 0 };
  1780. struct sockaddr_storage addr;
  1781. AVIOContext pb;
  1782. socklen_t addrlen = sizeof(addr);
  1783. RTSPState *rt = s->priv_data;
  1784. if (!ff_network_init())
  1785. return AVERROR(EIO);
  1786. ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
  1787. &s->interrupt_callback, NULL);
  1788. if (ret)
  1789. goto fail;
  1790. while (1) {
  1791. ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
  1792. if (ret == AVERROR(EAGAIN))
  1793. continue;
  1794. if (ret < 0)
  1795. goto fail;
  1796. if (ret < 12) {
  1797. av_log(s, AV_LOG_WARNING, "Received too short packet\n");
  1798. continue;
  1799. }
  1800. if ((recvbuf[0] & 0xc0) != 0x80) {
  1801. av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
  1802. "received\n");
  1803. continue;
  1804. }
  1805. if (RTP_PT_IS_RTCP(recvbuf[1]))
  1806. continue;
  1807. payload_type = recvbuf[1] & 0x7f;
  1808. break;
  1809. }
  1810. getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
  1811. ffurl_close(in);
  1812. in = NULL;
  1813. if (ff_rtp_get_codec_info(&codec, payload_type)) {
  1814. av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
  1815. "without an SDP file describing it\n",
  1816. payload_type);
  1817. goto fail;
  1818. }
  1819. if (codec.codec_type != AVMEDIA_TYPE_DATA) {
  1820. av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
  1821. "properly you need an SDP file "
  1822. "describing it\n");
  1823. }
  1824. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
  1825. NULL, 0, s->filename);
  1826. snprintf(sdp, sizeof(sdp),
  1827. "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
  1828. addr.ss_family == AF_INET ? 4 : 6, host,
  1829. codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
  1830. codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
  1831. port, payload_type);
  1832. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  1833. ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
  1834. s->pb = &pb;
  1835. /* sdp_read_header initializes this again */
  1836. ff_network_close();
  1837. rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
  1838. ret = sdp_read_header(s);
  1839. s->pb = NULL;
  1840. return ret;
  1841. fail:
  1842. if (in)
  1843. ffurl_close(in);
  1844. ff_network_close();
  1845. return ret;
  1846. }
  1847. static const AVClass rtp_demuxer_class = {
  1848. .class_name = "RTP demuxer",
  1849. .item_name = av_default_item_name,
  1850. .option = rtp_options,
  1851. .version = LIBAVUTIL_VERSION_INT,
  1852. };
  1853. AVInputFormat ff_rtp_demuxer = {
  1854. .name = "rtp",
  1855. .long_name = NULL_IF_CONFIG_SMALL("RTP input format"),
  1856. .priv_data_size = sizeof(RTSPState),
  1857. .read_probe = rtp_probe,
  1858. .read_header = rtp_read_header,
  1859. .read_packet = ff_rtsp_fetch_packet,
  1860. .read_close = sdp_read_close,
  1861. .flags = AVFMT_NOFILE,
  1862. .priv_class = &rtp_demuxer_class,
  1863. };
  1864. #endif /* CONFIG_RTP_DEMUXER */