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.

2005 lines
71KB

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