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.

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