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.

2145 lines
77KB

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