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.

2093 lines
75KB

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