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.

2033 lines
72KB

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