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.

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