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.

1996 lines
71KB

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