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.

2264 lines
83KB

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