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.

2161 lines
78KB

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