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.

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