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.

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