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.

2002 lines
71KB

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