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.

2142 lines
77KB

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