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.

2265 lines
82KB

  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. /* Timeout values for socket poll, in ms,
  48. * and read_packet(), in seconds */
  49. #define POLL_TIMEOUT_MS 100
  50. #define READ_PACKET_TIMEOUT_S 10
  51. #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
  52. #define SDP_MAX_SIZE 16384
  53. #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
  54. #define DEFAULT_REORDERING_DELAY 100000
  55. #define OFFSET(x) offsetof(RTSPState, x)
  56. #define DEC AV_OPT_FLAG_DECODING_PARAM
  57. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  58. #define RTSP_FLAG_OPTS(name, longname) \
  59. { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
  60. { "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" }, \
  61. { "listen", "Wait for incoming connections", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_LISTEN}, 0, 0, DEC, "rtsp_flags" }
  62. #define RTSP_MEDIATYPE_OPTS(name, longname) \
  63. { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
  64. { "video", "Video", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
  65. { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
  66. { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
  67. #define RTSP_REORDERING_OPTS() \
  68. { "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 }
  69. const AVOption ff_rtsp_options[] = {
  70. { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  71. FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
  72. { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
  73. { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
  74. { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
  75. { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
  76. { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {.i64 = (1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
  77. RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
  78. RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
  79. { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
  80. { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
  81. { "timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies flag listen", OFFSET(initial_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC },
  82. RTSP_REORDERING_OPTS(),
  83. { NULL },
  84. };
  85. static const AVOption sdp_options[] = {
  86. RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
  87. { "custom_io", "Use custom IO", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_CUSTOM_IO}, 0, 0, DEC, "rtsp_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. if (codec)
  161. codec->codec_id = handler->codec_id;
  162. rtsp_st->dynamic_handler = handler;
  163. if (handler->alloc) {
  164. rtsp_st->dynamic_protocol_context = handler->alloc();
  165. if (!rtsp_st->dynamic_protocol_context)
  166. rtsp_st->dynamic_handler = NULL;
  167. }
  168. }
  169. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  170. static int sdp_parse_rtpmap(AVFormatContext *s,
  171. AVStream *st, RTSPStream *rtsp_st,
  172. int payload_type, const char *p)
  173. {
  174. AVCodecContext *codec = st->codec;
  175. char buf[256];
  176. int i;
  177. AVCodec *c;
  178. const char *c_name;
  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. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  188. }
  189. if (codec->codec_id == AV_CODEC_ID_NONE) {
  190. RTPDynamicProtocolHandler *handler =
  191. ff_rtp_handler_find_by_name(buf, codec->codec_type);
  192. init_rtp_handler(handler, rtsp_st, codec);
  193. /* If no dynamic handler was found, check with the list of standard
  194. * allocated types, if such a stream for some reason happens to
  195. * use a private payload type. This isn't handled in rtpdec.c, since
  196. * the format name from the rtpmap line never is passed into rtpdec. */
  197. if (!rtsp_st->dynamic_handler)
  198. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  199. }
  200. c = avcodec_find_decoder(codec->codec_id);
  201. if (c && c->name)
  202. c_name = c->name;
  203. else
  204. c_name = "(null)";
  205. get_word_sep(buf, sizeof(buf), "/", &p);
  206. i = atoi(buf);
  207. switch (codec->codec_type) {
  208. case AVMEDIA_TYPE_AUDIO:
  209. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  210. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  211. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  212. if (i > 0) {
  213. codec->sample_rate = i;
  214. avpriv_set_pts_info(st, 32, 1, codec->sample_rate);
  215. get_word_sep(buf, sizeof(buf), "/", &p);
  216. i = atoi(buf);
  217. if (i > 0)
  218. codec->channels = i;
  219. }
  220. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  221. codec->sample_rate);
  222. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  223. codec->channels);
  224. break;
  225. case AVMEDIA_TYPE_VIDEO:
  226. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  227. if (i > 0)
  228. avpriv_set_pts_info(st, 32, 1, i);
  229. break;
  230. default:
  231. break;
  232. }
  233. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)
  234. rtsp_st->dynamic_handler->init(s, st->index,
  235. rtsp_st->dynamic_protocol_context);
  236. return 0;
  237. }
  238. /* parse the attribute line from the fmtp a line of an sdp response. This
  239. * is broken out as a function because it is used in rtp_h264.c, which is
  240. * forthcoming. */
  241. int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
  242. char *value, int value_size)
  243. {
  244. *p += strspn(*p, SPACE_CHARS);
  245. if (**p) {
  246. get_word_sep(attr, attr_size, "=", p);
  247. if (**p == '=')
  248. (*p)++;
  249. get_word_sep(value, value_size, ";", p);
  250. if (**p == ';')
  251. (*p)++;
  252. return 1;
  253. }
  254. return 0;
  255. }
  256. typedef struct SDPParseState {
  257. /* SDP only */
  258. struct sockaddr_storage default_ip;
  259. int default_ttl;
  260. int skip_media; ///< set if an unknown m= line occurs
  261. } SDPParseState;
  262. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  263. int letter, const char *buf)
  264. {
  265. RTSPState *rt = s->priv_data;
  266. char buf1[64], st_type[64];
  267. const char *p;
  268. enum AVMediaType codec_type;
  269. int payload_type, i;
  270. AVStream *st;
  271. RTSPStream *rtsp_st;
  272. struct sockaddr_storage sdp_ip;
  273. int ttl;
  274. av_dlog(s, "sdp: %c='%s'\n", letter, buf);
  275. p = buf;
  276. if (s1->skip_media && letter != 'm')
  277. return;
  278. switch (letter) {
  279. case 'c':
  280. get_word(buf1, sizeof(buf1), &p);
  281. if (strcmp(buf1, "IN") != 0)
  282. return;
  283. get_word(buf1, sizeof(buf1), &p);
  284. if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
  285. return;
  286. get_word_sep(buf1, sizeof(buf1), "/", &p);
  287. if (get_sockaddr(buf1, &sdp_ip))
  288. return;
  289. ttl = 16;
  290. if (*p == '/') {
  291. p++;
  292. get_word_sep(buf1, sizeof(buf1), "/", &p);
  293. ttl = atoi(buf1);
  294. }
  295. if (s->nb_streams == 0) {
  296. s1->default_ip = sdp_ip;
  297. s1->default_ttl = ttl;
  298. } else {
  299. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  300. rtsp_st->sdp_ip = sdp_ip;
  301. rtsp_st->sdp_ttl = ttl;
  302. }
  303. break;
  304. case 's':
  305. av_dict_set(&s->metadata, "title", p, 0);
  306. break;
  307. case 'i':
  308. if (s->nb_streams == 0) {
  309. av_dict_set(&s->metadata, "comment", p, 0);
  310. break;
  311. }
  312. break;
  313. case 'm':
  314. /* new stream */
  315. s1->skip_media = 0;
  316. codec_type = AVMEDIA_TYPE_UNKNOWN;
  317. get_word(st_type, sizeof(st_type), &p);
  318. if (!strcmp(st_type, "audio")) {
  319. codec_type = AVMEDIA_TYPE_AUDIO;
  320. } else if (!strcmp(st_type, "video")) {
  321. codec_type = AVMEDIA_TYPE_VIDEO;
  322. } else if (!strcmp(st_type, "application")) {
  323. codec_type = AVMEDIA_TYPE_DATA;
  324. }
  325. if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
  326. s1->skip_media = 1;
  327. return;
  328. }
  329. rtsp_st = av_mallocz(sizeof(RTSPStream));
  330. if (!rtsp_st)
  331. return;
  332. rtsp_st->stream_index = -1;
  333. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  334. rtsp_st->sdp_ip = s1->default_ip;
  335. rtsp_st->sdp_ttl = s1->default_ttl;
  336. get_word(buf1, sizeof(buf1), &p); /* port */
  337. rtsp_st->sdp_port = atoi(buf1);
  338. get_word(buf1, sizeof(buf1), &p); /* protocol */
  339. if (!strcmp(buf1, "udp"))
  340. rt->transport = RTSP_TRANSPORT_RAW;
  341. else if (strstr(buf1, "/AVPF") || strstr(buf1, "/SAVPF"))
  342. rtsp_st->feedback = 1;
  343. /* XXX: handle list of formats */
  344. get_word(buf1, sizeof(buf1), &p); /* format list */
  345. rtsp_st->sdp_payload_type = atoi(buf1);
  346. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  347. /* no corresponding stream */
  348. if (rt->transport == RTSP_TRANSPORT_RAW) {
  349. if (!rt->ts && CONFIG_RTPDEC)
  350. rt->ts = ff_mpegts_parse_open(s);
  351. } else {
  352. RTPDynamicProtocolHandler *handler;
  353. handler = ff_rtp_handler_find_by_id(
  354. rtsp_st->sdp_payload_type, AVMEDIA_TYPE_DATA);
  355. init_rtp_handler(handler, rtsp_st, NULL);
  356. if (handler && handler->init)
  357. handler->init(s, -1, rtsp_st->dynamic_protocol_context);
  358. }
  359. } else if (rt->server_type == RTSP_SERVER_WMS &&
  360. codec_type == AVMEDIA_TYPE_DATA) {
  361. /* RTX stream, a stream that carries all the other actual
  362. * audio/video streams. Don't expose this to the callers. */
  363. } else {
  364. st = avformat_new_stream(s, NULL);
  365. if (!st)
  366. return;
  367. st->id = rt->nb_rtsp_streams - 1;
  368. rtsp_st->stream_index = st->index;
  369. st->codec->codec_type = codec_type;
  370. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  371. RTPDynamicProtocolHandler *handler;
  372. /* if standard payload type, we can find the codec right now */
  373. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  374. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  375. st->codec->sample_rate > 0)
  376. avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
  377. /* Even static payload types may need a custom depacketizer */
  378. handler = ff_rtp_handler_find_by_id(
  379. rtsp_st->sdp_payload_type, st->codec->codec_type);
  380. init_rtp_handler(handler, rtsp_st, st->codec);
  381. if (handler && handler->init)
  382. handler->init(s, st->index,
  383. rtsp_st->dynamic_protocol_context);
  384. }
  385. }
  386. /* put a default control url */
  387. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  388. sizeof(rtsp_st->control_url));
  389. break;
  390. case 'a':
  391. if (av_strstart(p, "control:", &p)) {
  392. if (s->nb_streams == 0) {
  393. if (!strncmp(p, "rtsp://", 7))
  394. av_strlcpy(rt->control_uri, p,
  395. sizeof(rt->control_uri));
  396. } else {
  397. char proto[32];
  398. /* get the control url */
  399. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  400. /* XXX: may need to add full url resolution */
  401. av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  402. NULL, NULL, 0, p);
  403. if (proto[0] == '\0') {
  404. /* relative control URL */
  405. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  406. av_strlcat(rtsp_st->control_url, "/",
  407. sizeof(rtsp_st->control_url));
  408. av_strlcat(rtsp_st->control_url, p,
  409. sizeof(rtsp_st->control_url));
  410. } else
  411. av_strlcpy(rtsp_st->control_url, p,
  412. sizeof(rtsp_st->control_url));
  413. }
  414. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  415. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  416. get_word(buf1, sizeof(buf1), &p);
  417. payload_type = atoi(buf1);
  418. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  419. if (rtsp_st->stream_index >= 0) {
  420. st = s->streams[rtsp_st->stream_index];
  421. sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
  422. }
  423. } else if (av_strstart(p, "fmtp:", &p) ||
  424. av_strstart(p, "framesize:", &p)) {
  425. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  426. // let dynamic protocol handlers have a stab at the line.
  427. get_word(buf1, sizeof(buf1), &p);
  428. payload_type = atoi(buf1);
  429. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  430. rtsp_st = rt->rtsp_streams[i];
  431. if (rtsp_st->sdp_payload_type == payload_type &&
  432. rtsp_st->dynamic_handler &&
  433. rtsp_st->dynamic_handler->parse_sdp_a_line)
  434. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  435. rtsp_st->dynamic_protocol_context, buf);
  436. }
  437. } else if (av_strstart(p, "range:", &p)) {
  438. int64_t start, end;
  439. // this is so that seeking on a streamed file can work.
  440. rtsp_parse_range_npt(p, &start, &end);
  441. s->start_time = start;
  442. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  443. s->duration = (end == AV_NOPTS_VALUE) ?
  444. AV_NOPTS_VALUE : end - start;
  445. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  446. if (atoi(p) == 1)
  447. rt->transport = RTSP_TRANSPORT_RDT;
  448. } else if (av_strstart(p, "SampleRate:integer;", &p) &&
  449. s->nb_streams > 0) {
  450. st = s->streams[s->nb_streams - 1];
  451. st->codec->sample_rate = atoi(p);
  452. } else if (av_strstart(p, "crypto:", &p) && s->nb_streams > 0) {
  453. // RFC 4568
  454. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  455. get_word(buf1, sizeof(buf1), &p); // ignore tag
  456. get_word(rtsp_st->crypto_suite, sizeof(rtsp_st->crypto_suite), &p);
  457. p += strspn(p, SPACE_CHARS);
  458. if (av_strstart(p, "inline:", &p))
  459. get_word(rtsp_st->crypto_params, sizeof(rtsp_st->crypto_params), &p);
  460. } else if (av_strstart(p, "source-filter:", &p) && s->nb_streams > 0) {
  461. get_word(buf1, sizeof(buf1), &p);
  462. if (strcmp(buf1, "incl"))
  463. return;
  464. get_word(buf1, sizeof(buf1), &p);
  465. if (strcmp(buf1, "IN") != 0)
  466. return;
  467. get_word(buf1, sizeof(buf1), &p);
  468. if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
  469. return;
  470. // not checking that the destination address actually matches
  471. get_word(buf1, sizeof(buf1), &p);
  472. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  473. get_word(rtsp_st->source_addr, sizeof(rtsp_st->source_addr), &p);
  474. } else {
  475. if (rt->server_type == RTSP_SERVER_WMS)
  476. ff_wms_parse_sdp_a_line(s, p);
  477. if (s->nb_streams > 0) {
  478. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  479. if (rt->server_type == RTSP_SERVER_REAL)
  480. ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
  481. if (rtsp_st->dynamic_handler &&
  482. rtsp_st->dynamic_handler->parse_sdp_a_line)
  483. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  484. rtsp_st->stream_index,
  485. rtsp_st->dynamic_protocol_context, buf);
  486. }
  487. }
  488. break;
  489. }
  490. }
  491. int ff_sdp_parse(AVFormatContext *s, const char *content)
  492. {
  493. RTSPState *rt = s->priv_data;
  494. const char *p;
  495. int letter;
  496. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  497. * contain long SDP lines containing complete ASF Headers (several
  498. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  499. * "rulebooks" describing their properties. Therefore, the SDP line
  500. * buffer is large.
  501. *
  502. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  503. * in rtpdec_xiph.c. */
  504. char buf[16384], *q;
  505. SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
  506. p = content;
  507. for (;;) {
  508. p += strspn(p, SPACE_CHARS);
  509. letter = *p;
  510. if (letter == '\0')
  511. break;
  512. p++;
  513. if (*p != '=')
  514. goto next_line;
  515. p++;
  516. /* get the content */
  517. q = buf;
  518. while (*p != '\n' && *p != '\r' && *p != '\0') {
  519. if ((q - buf) < sizeof(buf) - 1)
  520. *q++ = *p;
  521. p++;
  522. }
  523. *q = '\0';
  524. sdp_parse_line(s, s1, letter, buf);
  525. next_line:
  526. while (*p != '\n' && *p != '\0')
  527. p++;
  528. if (*p == '\n')
  529. p++;
  530. }
  531. rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
  532. if (!rt->p) return AVERROR(ENOMEM);
  533. return 0;
  534. }
  535. #endif /* CONFIG_RTPDEC */
  536. void ff_rtsp_undo_setup(AVFormatContext *s)
  537. {
  538. RTSPState *rt = s->priv_data;
  539. int i;
  540. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  541. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  542. if (!rtsp_st)
  543. continue;
  544. if (rtsp_st->transport_priv) {
  545. if (s->oformat) {
  546. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  547. av_write_trailer(rtpctx);
  548. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  549. uint8_t *ptr;
  550. avio_close_dyn_buf(rtpctx->pb, &ptr);
  551. av_free(ptr);
  552. } else {
  553. avio_close(rtpctx->pb);
  554. }
  555. avformat_free_context(rtpctx);
  556. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  557. ff_rdt_parse_close(rtsp_st->transport_priv);
  558. else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC)
  559. ff_rtp_parse_close(rtsp_st->transport_priv);
  560. }
  561. rtsp_st->transport_priv = NULL;
  562. if (rtsp_st->rtp_handle)
  563. ffurl_close(rtsp_st->rtp_handle);
  564. rtsp_st->rtp_handle = NULL;
  565. }
  566. }
  567. /* close and free RTSP streams */
  568. void ff_rtsp_close_streams(AVFormatContext *s)
  569. {
  570. RTSPState *rt = s->priv_data;
  571. int i;
  572. RTSPStream *rtsp_st;
  573. ff_rtsp_undo_setup(s);
  574. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  575. rtsp_st = rt->rtsp_streams[i];
  576. if (rtsp_st) {
  577. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  578. rtsp_st->dynamic_handler->free(
  579. rtsp_st->dynamic_protocol_context);
  580. av_free(rtsp_st);
  581. }
  582. }
  583. av_free(rt->rtsp_streams);
  584. if (rt->asf_ctx) {
  585. avformat_close_input(&rt->asf_ctx);
  586. }
  587. if (rt->ts && CONFIG_RTPDEC)
  588. ff_mpegts_parse_close(rt->ts);
  589. av_free(rt->p);
  590. av_free(rt->recvbuf);
  591. }
  592. int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  593. {
  594. RTSPState *rt = s->priv_data;
  595. AVStream *st = NULL;
  596. int reordering_queue_size = rt->reordering_queue_size;
  597. if (reordering_queue_size < 0) {
  598. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
  599. reordering_queue_size = 0;
  600. else
  601. reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
  602. }
  603. /* open the RTP context */
  604. if (rtsp_st->stream_index >= 0)
  605. st = s->streams[rtsp_st->stream_index];
  606. if (!st)
  607. s->ctx_flags |= AVFMTCTX_NOHEADER;
  608. if (s->oformat && CONFIG_RTSP_MUXER) {
  609. int ret = ff_rtp_chain_mux_open(&rtsp_st->transport_priv, s, st,
  610. rtsp_st->rtp_handle,
  611. RTSP_TCP_MAX_PACKET_SIZE,
  612. rtsp_st->stream_index);
  613. /* Ownership of rtp_handle is passed to the rtp mux context */
  614. rtsp_st->rtp_handle = NULL;
  615. if (ret < 0)
  616. return ret;
  617. } else if (rt->transport == RTSP_TRANSPORT_RAW) {
  618. return 0; // Don't need to open any parser here
  619. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  620. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  621. rtsp_st->dynamic_protocol_context,
  622. rtsp_st->dynamic_handler);
  623. else if (CONFIG_RTPDEC)
  624. rtsp_st->transport_priv = ff_rtp_parse_open(s, st,
  625. rtsp_st->sdp_payload_type,
  626. reordering_queue_size);
  627. if (!rtsp_st->transport_priv) {
  628. return AVERROR(ENOMEM);
  629. } else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC) {
  630. if (rtsp_st->dynamic_handler) {
  631. ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  632. rtsp_st->dynamic_protocol_context,
  633. rtsp_st->dynamic_handler);
  634. }
  635. if (rtsp_st->crypto_suite[0])
  636. ff_rtp_parse_set_crypto(rtsp_st->transport_priv,
  637. rtsp_st->crypto_suite,
  638. rtsp_st->crypto_params);
  639. }
  640. return 0;
  641. }
  642. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  643. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  644. {
  645. const char *q;
  646. char *p;
  647. int v;
  648. q = *pp;
  649. q += strspn(q, SPACE_CHARS);
  650. v = strtol(q, &p, 10);
  651. if (*p == '-') {
  652. p++;
  653. *min_ptr = v;
  654. v = strtol(p, &p, 10);
  655. *max_ptr = v;
  656. } else {
  657. *min_ptr = v;
  658. *max_ptr = v;
  659. }
  660. *pp = p;
  661. }
  662. /* XXX: only one transport specification is parsed */
  663. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  664. {
  665. char transport_protocol[16];
  666. char profile[16];
  667. char lower_transport[16];
  668. char parameter[16];
  669. RTSPTransportField *th;
  670. char buf[256];
  671. reply->nb_transports = 0;
  672. for (;;) {
  673. p += strspn(p, SPACE_CHARS);
  674. if (*p == '\0')
  675. break;
  676. th = &reply->transports[reply->nb_transports];
  677. get_word_sep(transport_protocol, sizeof(transport_protocol),
  678. "/", &p);
  679. if (!av_strcasecmp (transport_protocol, "rtp")) {
  680. get_word_sep(profile, sizeof(profile), "/;,", &p);
  681. lower_transport[0] = '\0';
  682. /* rtp/avp/<protocol> */
  683. if (*p == '/') {
  684. get_word_sep(lower_transport, sizeof(lower_transport),
  685. ";,", &p);
  686. }
  687. th->transport = RTSP_TRANSPORT_RTP;
  688. } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
  689. !av_strcasecmp (transport_protocol, "x-real-rdt")) {
  690. /* x-pn-tng/<protocol> */
  691. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  692. profile[0] = '\0';
  693. th->transport = RTSP_TRANSPORT_RDT;
  694. } else if (!av_strcasecmp(transport_protocol, "raw")) {
  695. get_word_sep(profile, sizeof(profile), "/;,", &p);
  696. lower_transport[0] = '\0';
  697. /* raw/raw/<protocol> */
  698. if (*p == '/') {
  699. get_word_sep(lower_transport, sizeof(lower_transport),
  700. ";,", &p);
  701. }
  702. th->transport = RTSP_TRANSPORT_RAW;
  703. }
  704. if (!av_strcasecmp(lower_transport, "TCP"))
  705. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  706. else
  707. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  708. if (*p == ';')
  709. p++;
  710. /* get each parameter */
  711. while (*p != '\0' && *p != ',') {
  712. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  713. if (!strcmp(parameter, "port")) {
  714. if (*p == '=') {
  715. p++;
  716. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  717. }
  718. } else if (!strcmp(parameter, "client_port")) {
  719. if (*p == '=') {
  720. p++;
  721. rtsp_parse_range(&th->client_port_min,
  722. &th->client_port_max, &p);
  723. }
  724. } else if (!strcmp(parameter, "server_port")) {
  725. if (*p == '=') {
  726. p++;
  727. rtsp_parse_range(&th->server_port_min,
  728. &th->server_port_max, &p);
  729. }
  730. } else if (!strcmp(parameter, "interleaved")) {
  731. if (*p == '=') {
  732. p++;
  733. rtsp_parse_range(&th->interleaved_min,
  734. &th->interleaved_max, &p);
  735. }
  736. } else if (!strcmp(parameter, "multicast")) {
  737. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  738. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  739. } else if (!strcmp(parameter, "ttl")) {
  740. if (*p == '=') {
  741. char *end;
  742. p++;
  743. th->ttl = strtol(p, &end, 10);
  744. p = end;
  745. }
  746. } else if (!strcmp(parameter, "destination")) {
  747. if (*p == '=') {
  748. p++;
  749. get_word_sep(buf, sizeof(buf), ";,", &p);
  750. get_sockaddr(buf, &th->destination);
  751. }
  752. } else if (!strcmp(parameter, "source")) {
  753. if (*p == '=') {
  754. p++;
  755. get_word_sep(buf, sizeof(buf), ";,", &p);
  756. av_strlcpy(th->source, buf, sizeof(th->source));
  757. }
  758. } else if (!strcmp(parameter, "mode")) {
  759. if (*p == '=') {
  760. p++;
  761. get_word_sep(buf, sizeof(buf), ";, ", &p);
  762. if (!strcmp(buf, "record") ||
  763. !strcmp(buf, "receive"))
  764. th->mode_record = 1;
  765. }
  766. }
  767. while (*p != ';' && *p != '\0' && *p != ',')
  768. p++;
  769. if (*p == ';')
  770. p++;
  771. }
  772. if (*p == ',')
  773. p++;
  774. reply->nb_transports++;
  775. }
  776. }
  777. static void handle_rtp_info(RTSPState *rt, const char *url,
  778. uint32_t seq, uint32_t rtptime)
  779. {
  780. int i;
  781. if (!rtptime || !url[0])
  782. return;
  783. if (rt->transport != RTSP_TRANSPORT_RTP)
  784. return;
  785. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  786. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  787. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  788. if (!rtpctx)
  789. continue;
  790. if (!strcmp(rtsp_st->control_url, url)) {
  791. rtpctx->base_timestamp = rtptime;
  792. break;
  793. }
  794. }
  795. }
  796. static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
  797. {
  798. int read = 0;
  799. char key[20], value[1024], url[1024] = "";
  800. uint32_t seq = 0, rtptime = 0;
  801. for (;;) {
  802. p += strspn(p, SPACE_CHARS);
  803. if (!*p)
  804. break;
  805. get_word_sep(key, sizeof(key), "=", &p);
  806. if (*p != '=')
  807. break;
  808. p++;
  809. get_word_sep(value, sizeof(value), ";, ", &p);
  810. read++;
  811. if (!strcmp(key, "url"))
  812. av_strlcpy(url, value, sizeof(url));
  813. else if (!strcmp(key, "seq"))
  814. seq = strtoul(value, NULL, 10);
  815. else if (!strcmp(key, "rtptime"))
  816. rtptime = strtoul(value, NULL, 10);
  817. if (*p == ',') {
  818. handle_rtp_info(rt, url, seq, rtptime);
  819. url[0] = '\0';
  820. seq = rtptime = 0;
  821. read = 0;
  822. }
  823. if (*p)
  824. p++;
  825. }
  826. if (read > 0)
  827. handle_rtp_info(rt, url, seq, rtptime);
  828. }
  829. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  830. RTSPState *rt, const char *method)
  831. {
  832. const char *p;
  833. /* NOTE: we do case independent match for broken servers */
  834. p = buf;
  835. if (av_stristart(p, "Session:", &p)) {
  836. int t;
  837. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  838. if (av_stristart(p, ";timeout=", &p) &&
  839. (t = strtol(p, NULL, 10)) > 0) {
  840. reply->timeout = t;
  841. }
  842. } else if (av_stristart(p, "Content-Length:", &p)) {
  843. reply->content_length = strtol(p, NULL, 10);
  844. } else if (av_stristart(p, "Transport:", &p)) {
  845. rtsp_parse_transport(reply, p);
  846. } else if (av_stristart(p, "CSeq:", &p)) {
  847. reply->seq = strtol(p, NULL, 10);
  848. } else if (av_stristart(p, "Range:", &p)) {
  849. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  850. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  851. p += strspn(p, SPACE_CHARS);
  852. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  853. } else if (av_stristart(p, "Server:", &p)) {
  854. p += strspn(p, SPACE_CHARS);
  855. av_strlcpy(reply->server, p, sizeof(reply->server));
  856. } else if (av_stristart(p, "Notice:", &p) ||
  857. av_stristart(p, "X-Notice:", &p)) {
  858. reply->notice = strtol(p, NULL, 10);
  859. } else if (av_stristart(p, "Location:", &p)) {
  860. p += strspn(p, SPACE_CHARS);
  861. av_strlcpy(reply->location, p , sizeof(reply->location));
  862. } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
  863. p += strspn(p, SPACE_CHARS);
  864. ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
  865. } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
  866. p += strspn(p, SPACE_CHARS);
  867. ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
  868. } else if (av_stristart(p, "Content-Base:", &p) && rt) {
  869. p += strspn(p, SPACE_CHARS);
  870. if (method && !strcmp(method, "DESCRIBE"))
  871. av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
  872. } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
  873. p += strspn(p, SPACE_CHARS);
  874. if (method && !strcmp(method, "PLAY"))
  875. rtsp_parse_rtp_info(rt, p);
  876. } else if (av_stristart(p, "Public:", &p) && rt) {
  877. if (strstr(p, "GET_PARAMETER") &&
  878. method && !strcmp(method, "OPTIONS"))
  879. rt->get_parameter_supported = 1;
  880. } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
  881. p += strspn(p, SPACE_CHARS);
  882. rt->accept_dynamic_rate = atoi(p);
  883. } else if (av_stristart(p, "Content-Type:", &p)) {
  884. p += strspn(p, SPACE_CHARS);
  885. av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
  886. }
  887. }
  888. /* skip a RTP/TCP interleaved packet */
  889. void ff_rtsp_skip_packet(AVFormatContext *s)
  890. {
  891. RTSPState *rt = s->priv_data;
  892. int ret, len, len1;
  893. uint8_t buf[1024];
  894. ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
  895. if (ret != 3)
  896. return;
  897. len = AV_RB16(buf + 1);
  898. av_dlog(s, "skipping RTP packet len=%d\n", len);
  899. /* skip payload */
  900. while (len > 0) {
  901. len1 = len;
  902. if (len1 > sizeof(buf))
  903. len1 = sizeof(buf);
  904. ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
  905. if (ret != len1)
  906. return;
  907. len -= len1;
  908. }
  909. }
  910. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  911. unsigned char **content_ptr,
  912. int return_on_interleaved_data, const char *method)
  913. {
  914. RTSPState *rt = s->priv_data;
  915. char buf[4096], buf1[1024], *q;
  916. unsigned char ch;
  917. const char *p;
  918. int ret, content_length, line_count = 0, request = 0;
  919. unsigned char *content = NULL;
  920. start:
  921. line_count = 0;
  922. request = 0;
  923. content = NULL;
  924. memset(reply, 0, sizeof(*reply));
  925. /* parse reply (XXX: use buffers) */
  926. rt->last_reply[0] = '\0';
  927. for (;;) {
  928. q = buf;
  929. for (;;) {
  930. ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
  931. av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  932. if (ret != 1)
  933. return AVERROR_EOF;
  934. if (ch == '\n')
  935. break;
  936. if (ch == '$') {
  937. /* XXX: only parse it if first char on line ? */
  938. if (return_on_interleaved_data) {
  939. return 1;
  940. } else
  941. ff_rtsp_skip_packet(s);
  942. } else if (ch != '\r') {
  943. if ((q - buf) < sizeof(buf) - 1)
  944. *q++ = ch;
  945. }
  946. }
  947. *q = '\0';
  948. av_dlog(s, "line='%s'\n", buf);
  949. /* test if last line */
  950. if (buf[0] == '\0')
  951. break;
  952. p = buf;
  953. if (line_count == 0) {
  954. /* get reply code */
  955. get_word(buf1, sizeof(buf1), &p);
  956. if (!strncmp(buf1, "RTSP/", 5)) {
  957. get_word(buf1, sizeof(buf1), &p);
  958. reply->status_code = atoi(buf1);
  959. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  960. } else {
  961. av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
  962. get_word(buf1, sizeof(buf1), &p); // object
  963. request = 1;
  964. }
  965. } else {
  966. ff_rtsp_parse_line(reply, p, rt, method);
  967. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  968. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  969. }
  970. line_count++;
  971. }
  972. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
  973. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  974. content_length = reply->content_length;
  975. if (content_length > 0) {
  976. /* leave some room for a trailing '\0' (useful for simple parsing) */
  977. content = av_malloc(content_length + 1);
  978. ffurl_read_complete(rt->rtsp_hd, content, content_length);
  979. content[content_length] = '\0';
  980. }
  981. if (content_ptr)
  982. *content_ptr = content;
  983. else
  984. av_free(content);
  985. if (request) {
  986. char buf[1024];
  987. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  988. const char* ptr = buf;
  989. if (!strcmp(reply->reason, "OPTIONS")) {
  990. snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
  991. if (reply->seq)
  992. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
  993. if (reply->session_id[0])
  994. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
  995. reply->session_id);
  996. } else {
  997. snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
  998. }
  999. av_strlcat(buf, "\r\n", sizeof(buf));
  1000. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1001. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  1002. ptr = base64buf;
  1003. }
  1004. ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
  1005. rt->last_cmd_time = av_gettime();
  1006. /* Even if the request from the server had data, it is not the data
  1007. * that the caller wants or expects. The memory could also be leaked
  1008. * if the actual following reply has content data. */
  1009. if (content_ptr)
  1010. av_freep(content_ptr);
  1011. /* If method is set, this is called from ff_rtsp_send_cmd,
  1012. * where a reply to exactly this request is awaited. For
  1013. * callers from within packet receiving, we just want to
  1014. * return to the caller and go back to receiving packets. */
  1015. if (method)
  1016. goto start;
  1017. return 0;
  1018. }
  1019. if (rt->seq != reply->seq) {
  1020. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  1021. rt->seq, reply->seq);
  1022. }
  1023. /* EOS */
  1024. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  1025. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  1026. reply->notice == 2306 /* Continuous Feed Terminated */) {
  1027. rt->state = RTSP_STATE_IDLE;
  1028. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  1029. return AVERROR(EIO); /* data or server error */
  1030. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  1031. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  1032. return AVERROR(EPERM);
  1033. return 0;
  1034. }
  1035. /**
  1036. * Send a command to the RTSP server without waiting for the reply.
  1037. *
  1038. * @param s RTSP (de)muxer context
  1039. * @param method the method for the request
  1040. * @param url the target url for the request
  1041. * @param headers extra header lines to include in the request
  1042. * @param send_content if non-null, the data to send as request body content
  1043. * @param send_content_length the length of the send_content data, or 0 if
  1044. * send_content is null
  1045. *
  1046. * @return zero if success, nonzero otherwise
  1047. */
  1048. static int rtsp_send_cmd_with_content_async(AVFormatContext *s,
  1049. const char *method, const char *url,
  1050. const char *headers,
  1051. const unsigned char *send_content,
  1052. int send_content_length)
  1053. {
  1054. RTSPState *rt = s->priv_data;
  1055. char buf[4096], *out_buf;
  1056. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  1057. /* Add in RTSP headers */
  1058. out_buf = buf;
  1059. rt->seq++;
  1060. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  1061. if (headers)
  1062. av_strlcat(buf, headers, sizeof(buf));
  1063. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  1064. av_strlcatf(buf, sizeof(buf), "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  1065. if (rt->session_id[0] != '\0' && (!headers ||
  1066. !strstr(headers, "\nIf-Match:"))) {
  1067. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  1068. }
  1069. if (rt->auth[0]) {
  1070. char *str = ff_http_auth_create_response(&rt->auth_state,
  1071. rt->auth, url, method);
  1072. if (str)
  1073. av_strlcat(buf, str, sizeof(buf));
  1074. av_free(str);
  1075. }
  1076. if (send_content_length > 0 && send_content)
  1077. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  1078. av_strlcat(buf, "\r\n", sizeof(buf));
  1079. /* base64 encode rtsp if tunneling */
  1080. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1081. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  1082. out_buf = base64buf;
  1083. }
  1084. av_dlog(s, "Sending:\n%s--\n", buf);
  1085. ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  1086. if (send_content_length > 0 && send_content) {
  1087. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1088. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  1089. "with content data not supported\n");
  1090. return AVERROR_PATCHWELCOME;
  1091. }
  1092. ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
  1093. }
  1094. rt->last_cmd_time = av_gettime();
  1095. return 0;
  1096. }
  1097. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  1098. const char *url, const char *headers)
  1099. {
  1100. return rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  1101. }
  1102. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  1103. const char *headers, RTSPMessageHeader *reply,
  1104. unsigned char **content_ptr)
  1105. {
  1106. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  1107. content_ptr, NULL, 0);
  1108. }
  1109. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  1110. const char *method, const char *url,
  1111. const char *header,
  1112. RTSPMessageHeader *reply,
  1113. unsigned char **content_ptr,
  1114. const unsigned char *send_content,
  1115. int send_content_length)
  1116. {
  1117. RTSPState *rt = s->priv_data;
  1118. HTTPAuthType cur_auth_type;
  1119. int ret, attempts = 0;
  1120. retry:
  1121. cur_auth_type = rt->auth_state.auth_type;
  1122. if ((ret = rtsp_send_cmd_with_content_async(s, method, url, header,
  1123. send_content,
  1124. send_content_length)))
  1125. return ret;
  1126. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
  1127. return ret;
  1128. attempts++;
  1129. if (reply->status_code == 401 &&
  1130. (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
  1131. rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
  1132. goto retry;
  1133. if (reply->status_code > 400){
  1134. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  1135. method,
  1136. reply->status_code,
  1137. reply->reason);
  1138. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  1139. }
  1140. return 0;
  1141. }
  1142. int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
  1143. int lower_transport, const char *real_challenge)
  1144. {
  1145. RTSPState *rt = s->priv_data;
  1146. int rtx = 0, j, i, err, interleave = 0, port_off;
  1147. RTSPStream *rtsp_st;
  1148. RTSPMessageHeader reply1, *reply = &reply1;
  1149. char cmd[2048];
  1150. const char *trans_pref;
  1151. if (rt->transport == RTSP_TRANSPORT_RDT)
  1152. trans_pref = "x-pn-tng";
  1153. else if (rt->transport == RTSP_TRANSPORT_RAW)
  1154. trans_pref = "RAW/RAW";
  1155. else
  1156. trans_pref = "RTP/AVP";
  1157. /* default timeout: 1 minute */
  1158. rt->timeout = 60;
  1159. /* for each stream, make the setup request */
  1160. /* XXX: we assume the same server is used for the control of each
  1161. * RTSP stream */
  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, NULL);
  1497. if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
  1498. &s->interrupt_callback, NULL) < 0) {
  1499. err = AVERROR(EIO);
  1500. goto fail;
  1501. }
  1502. rt->rtsp_hd_out = rt->rtsp_hd;
  1503. }
  1504. rt->seq = 0;
  1505. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1506. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1507. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1508. NULL, 0, NI_NUMERICHOST);
  1509. }
  1510. /* request options supported by the server; this also detects server
  1511. * type */
  1512. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1513. cmd[0] = 0;
  1514. if (rt->server_type == RTSP_SERVER_REAL)
  1515. av_strlcat(cmd,
  1516. /*
  1517. * The following entries are required for proper
  1518. * streaming from a Realmedia server. They are
  1519. * interdependent in some way although we currently
  1520. * don't quite understand how. Values were copied
  1521. * from mplayer SVN r23589.
  1522. * ClientChallenge is a 16-byte ID in hex
  1523. * CompanyID is a 16-byte ID in base64
  1524. */
  1525. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1526. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1527. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1528. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1529. sizeof(cmd));
  1530. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1531. if (reply->status_code != RTSP_STATUS_OK) {
  1532. err = AVERROR_INVALIDDATA;
  1533. goto fail;
  1534. }
  1535. /* detect server type if not standard-compliant RTP */
  1536. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1537. rt->server_type = RTSP_SERVER_REAL;
  1538. continue;
  1539. } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
  1540. rt->server_type = RTSP_SERVER_WMS;
  1541. } else if (rt->server_type == RTSP_SERVER_REAL)
  1542. strcpy(real_challenge, reply->real_challenge);
  1543. break;
  1544. }
  1545. if (s->iformat && CONFIG_RTSP_DEMUXER)
  1546. err = ff_rtsp_setup_input_streams(s, reply);
  1547. else if (CONFIG_RTSP_MUXER)
  1548. err = ff_rtsp_setup_output_streams(s, host);
  1549. if (err)
  1550. goto fail;
  1551. do {
  1552. int lower_transport = ff_log2_tab[lower_transport_mask &
  1553. ~(lower_transport_mask - 1)];
  1554. err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
  1555. rt->server_type == RTSP_SERVER_REAL ?
  1556. real_challenge : NULL);
  1557. if (err < 0)
  1558. goto fail;
  1559. lower_transport_mask &= ~(1 << lower_transport);
  1560. if (lower_transport_mask == 0 && err == 1) {
  1561. err = AVERROR(EPROTONOSUPPORT);
  1562. goto fail;
  1563. }
  1564. } while (err);
  1565. rt->lower_transport_mask = lower_transport_mask;
  1566. av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
  1567. rt->state = RTSP_STATE_IDLE;
  1568. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1569. return 0;
  1570. fail:
  1571. ff_rtsp_close_streams(s);
  1572. ff_rtsp_close_connections(s);
  1573. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1574. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1575. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1576. reply->status_code,
  1577. s->filename);
  1578. goto redirect;
  1579. }
  1580. ff_network_close();
  1581. return err;
  1582. }
  1583. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1584. #if CONFIG_RTPDEC
  1585. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1586. uint8_t *buf, int buf_size, int64_t wait_end)
  1587. {
  1588. RTSPState *rt = s->priv_data;
  1589. RTSPStream *rtsp_st;
  1590. int n, i, ret, tcp_fd, timeout_cnt = 0;
  1591. int max_p = 0;
  1592. struct pollfd *p = rt->p;
  1593. int *fds = NULL, fdsnum, fdsidx;
  1594. for (;;) {
  1595. if (ff_check_interrupt(&s->interrupt_callback))
  1596. return AVERROR_EXIT;
  1597. if (wait_end && wait_end - av_gettime() < 0)
  1598. return AVERROR(EAGAIN);
  1599. max_p = 0;
  1600. if (rt->rtsp_hd) {
  1601. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1602. p[max_p].fd = tcp_fd;
  1603. p[max_p++].events = POLLIN;
  1604. } else {
  1605. tcp_fd = -1;
  1606. }
  1607. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1608. rtsp_st = rt->rtsp_streams[i];
  1609. if (rtsp_st->rtp_handle) {
  1610. if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
  1611. &fds, &fdsnum)) {
  1612. av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
  1613. return ret;
  1614. }
  1615. if (fdsnum != 2) {
  1616. av_log(s, AV_LOG_ERROR,
  1617. "Number of fds %d not supported\n", fdsnum);
  1618. return AVERROR_INVALIDDATA;
  1619. }
  1620. for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
  1621. p[max_p].fd = fds[fdsidx];
  1622. p[max_p++].events = POLLIN;
  1623. }
  1624. av_free(fds);
  1625. }
  1626. }
  1627. n = poll(p, max_p, POLL_TIMEOUT_MS);
  1628. if (n > 0) {
  1629. int j = 1 - (tcp_fd == -1);
  1630. timeout_cnt = 0;
  1631. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1632. rtsp_st = rt->rtsp_streams[i];
  1633. if (rtsp_st->rtp_handle) {
  1634. if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
  1635. ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
  1636. if (ret > 0) {
  1637. *prtsp_st = rtsp_st;
  1638. return ret;
  1639. }
  1640. }
  1641. j+=2;
  1642. }
  1643. }
  1644. #if CONFIG_RTSP_DEMUXER
  1645. if (tcp_fd != -1 && p[0].revents & POLLIN) {
  1646. if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
  1647. if (rt->state == RTSP_STATE_STREAMING) {
  1648. if (!ff_rtsp_parse_streaming_commands(s))
  1649. return AVERROR_EOF;
  1650. else
  1651. av_log(s, AV_LOG_WARNING,
  1652. "Unable to answer to TEARDOWN\n");
  1653. } else
  1654. return 0;
  1655. } else {
  1656. RTSPMessageHeader reply;
  1657. ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
  1658. if (ret < 0)
  1659. return ret;
  1660. /* XXX: parse message */
  1661. if (rt->state != RTSP_STATE_STREAMING)
  1662. return 0;
  1663. }
  1664. }
  1665. #endif
  1666. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1667. return AVERROR(ETIMEDOUT);
  1668. } else if (n < 0 && errno != EINTR)
  1669. return AVERROR(errno);
  1670. }
  1671. }
  1672. static int pick_stream(AVFormatContext *s, RTSPStream **rtsp_st,
  1673. const uint8_t *buf, int len)
  1674. {
  1675. RTSPState *rt = s->priv_data;
  1676. int i;
  1677. if (len < 0)
  1678. return len;
  1679. if (rt->nb_rtsp_streams == 1) {
  1680. *rtsp_st = rt->rtsp_streams[0];
  1681. return len;
  1682. }
  1683. if (len >= 8 && rt->transport == RTSP_TRANSPORT_RTP) {
  1684. if (RTP_PT_IS_RTCP(rt->recvbuf[1])) {
  1685. int no_ssrc = 0;
  1686. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1687. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1688. if (!rtpctx)
  1689. continue;
  1690. if (rtpctx->ssrc == AV_RB32(&buf[4])) {
  1691. *rtsp_st = rt->rtsp_streams[i];
  1692. return len;
  1693. }
  1694. if (!rtpctx->ssrc)
  1695. no_ssrc = 1;
  1696. }
  1697. if (no_ssrc) {
  1698. av_log(s, AV_LOG_WARNING,
  1699. "Unable to pick stream for packet - SSRC not known for "
  1700. "all streams\n");
  1701. return AVERROR(EAGAIN);
  1702. }
  1703. } else {
  1704. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1705. if ((buf[1] & 0x7f) == rt->rtsp_streams[i]->sdp_payload_type) {
  1706. *rtsp_st = rt->rtsp_streams[i];
  1707. return len;
  1708. }
  1709. }
  1710. }
  1711. }
  1712. av_log(s, AV_LOG_WARNING, "Unable to pick stream for packet\n");
  1713. return AVERROR(EAGAIN);
  1714. }
  1715. int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1716. {
  1717. RTSPState *rt = s->priv_data;
  1718. int ret, len;
  1719. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1720. int64_t wait_end = 0;
  1721. if (rt->nb_byes == rt->nb_rtsp_streams)
  1722. return AVERROR_EOF;
  1723. /* get next frames from the same RTP packet */
  1724. if (rt->cur_transport_priv) {
  1725. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1726. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1727. } else if (rt->transport == RTSP_TRANSPORT_RTP) {
  1728. ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1729. } else if (rt->ts && CONFIG_RTPDEC) {
  1730. ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);
  1731. if (ret >= 0) {
  1732. rt->recvbuf_pos += ret;
  1733. ret = rt->recvbuf_pos < rt->recvbuf_len;
  1734. }
  1735. } else
  1736. ret = -1;
  1737. if (ret == 0) {
  1738. rt->cur_transport_priv = NULL;
  1739. return 0;
  1740. } else if (ret == 1) {
  1741. return 0;
  1742. } else
  1743. rt->cur_transport_priv = NULL;
  1744. }
  1745. redo:
  1746. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1747. int i;
  1748. int64_t first_queue_time = 0;
  1749. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1750. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1751. int64_t queue_time;
  1752. if (!rtpctx)
  1753. continue;
  1754. queue_time = ff_rtp_queued_packet_time(rtpctx);
  1755. if (queue_time && (queue_time - first_queue_time < 0 ||
  1756. !first_queue_time)) {
  1757. first_queue_time = queue_time;
  1758. first_queue_st = rt->rtsp_streams[i];
  1759. }
  1760. }
  1761. if (first_queue_time) {
  1762. wait_end = first_queue_time + s->max_delay;
  1763. } else {
  1764. wait_end = 0;
  1765. first_queue_st = NULL;
  1766. }
  1767. }
  1768. /* read next RTP packet */
  1769. if (!rt->recvbuf) {
  1770. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1771. if (!rt->recvbuf)
  1772. return AVERROR(ENOMEM);
  1773. }
  1774. switch(rt->lower_transport) {
  1775. default:
  1776. #if CONFIG_RTSP_DEMUXER
  1777. case RTSP_LOWER_TRANSPORT_TCP:
  1778. len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1779. break;
  1780. #endif
  1781. case RTSP_LOWER_TRANSPORT_UDP:
  1782. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1783. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1784. if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1785. ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);
  1786. break;
  1787. case RTSP_LOWER_TRANSPORT_CUSTOM:
  1788. if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&
  1789. wait_end && wait_end < av_gettime())
  1790. len = AVERROR(EAGAIN);
  1791. else
  1792. len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);
  1793. len = pick_stream(s, &rtsp_st, rt->recvbuf, len);
  1794. if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1795. ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, NULL, s->pb, len);
  1796. break;
  1797. }
  1798. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1799. rt->transport == RTSP_TRANSPORT_RTP) {
  1800. rtsp_st = first_queue_st;
  1801. ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1802. goto end;
  1803. }
  1804. if (len < 0)
  1805. return len;
  1806. if (len == 0)
  1807. return AVERROR_EOF;
  1808. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1809. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1810. } else if (rt->transport == RTSP_TRANSPORT_RTP) {
  1811. ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1812. if (rtsp_st->feedback) {
  1813. AVIOContext *pb = NULL;
  1814. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_CUSTOM)
  1815. pb = s->pb;
  1816. ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);
  1817. }
  1818. if (ret < 0) {
  1819. /* Either bad packet, or a RTCP packet. Check if the
  1820. * first_rtcp_ntp_time field was initialized. */
  1821. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1822. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1823. /* first_rtcp_ntp_time has been initialized for this stream,
  1824. * copy the same value to all other uninitialized streams,
  1825. * in order to map their timestamp origin to the same ntp time
  1826. * as this one. */
  1827. int i;
  1828. AVStream *st = NULL;
  1829. if (rtsp_st->stream_index >= 0)
  1830. st = s->streams[rtsp_st->stream_index];
  1831. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1832. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1833. AVStream *st2 = NULL;
  1834. if (rt->rtsp_streams[i]->stream_index >= 0)
  1835. st2 = s->streams[rt->rtsp_streams[i]->stream_index];
  1836. if (rtpctx2 && st && st2 &&
  1837. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  1838. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1839. rtpctx2->rtcp_ts_offset = av_rescale_q(
  1840. rtpctx->rtcp_ts_offset, st->time_base,
  1841. st2->time_base);
  1842. }
  1843. }
  1844. }
  1845. if (ret == -RTCP_BYE) {
  1846. rt->nb_byes++;
  1847. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1848. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1849. if (rt->nb_byes == rt->nb_rtsp_streams)
  1850. return AVERROR_EOF;
  1851. }
  1852. }
  1853. } else if (rt->ts && CONFIG_RTPDEC) {
  1854. ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);
  1855. if (ret >= 0) {
  1856. if (ret < len) {
  1857. rt->recvbuf_len = len;
  1858. rt->recvbuf_pos = ret;
  1859. rt->cur_transport_priv = rt->ts;
  1860. return 1;
  1861. } else {
  1862. ret = 0;
  1863. }
  1864. }
  1865. } else {
  1866. return AVERROR_INVALIDDATA;
  1867. }
  1868. end:
  1869. if (ret < 0)
  1870. goto redo;
  1871. if (ret == 1)
  1872. /* more packets may follow, so we save the RTP context */
  1873. rt->cur_transport_priv = rtsp_st->transport_priv;
  1874. return ret;
  1875. }
  1876. #endif /* CONFIG_RTPDEC */
  1877. #if CONFIG_SDP_DEMUXER
  1878. static int sdp_probe(AVProbeData *p1)
  1879. {
  1880. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1881. /* we look for a line beginning "c=IN IP" */
  1882. while (p < p_end && *p != '\0') {
  1883. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1884. av_strstart(p, "c=IN IP", NULL))
  1885. return AVPROBE_SCORE_EXTENSION;
  1886. while (p < p_end - 1 && *p != '\n') p++;
  1887. if (++p >= p_end)
  1888. break;
  1889. if (*p == '\r')
  1890. p++;
  1891. }
  1892. return 0;
  1893. }
  1894. static int sdp_read_header(AVFormatContext *s)
  1895. {
  1896. RTSPState *rt = s->priv_data;
  1897. RTSPStream *rtsp_st;
  1898. int size, i, err;
  1899. char *content;
  1900. char url[1024];
  1901. if (!ff_network_init())
  1902. return AVERROR(EIO);
  1903. if (s->max_delay < 0) /* Not set by the caller */
  1904. s->max_delay = DEFAULT_REORDERING_DELAY;
  1905. if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)
  1906. rt->lower_transport = RTSP_LOWER_TRANSPORT_CUSTOM;
  1907. /* read the whole sdp file */
  1908. /* XXX: better loading */
  1909. content = av_malloc(SDP_MAX_SIZE);
  1910. size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
  1911. if (size <= 0) {
  1912. av_free(content);
  1913. return AVERROR_INVALIDDATA;
  1914. }
  1915. content[size] ='\0';
  1916. err = ff_sdp_parse(s, content);
  1917. av_free(content);
  1918. if (err) goto fail;
  1919. /* open each RTP stream */
  1920. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1921. char namebuf[50];
  1922. rtsp_st = rt->rtsp_streams[i];
  1923. if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {
  1924. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1925. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1926. ff_url_join(url, sizeof(url), "rtp", NULL,
  1927. namebuf, rtsp_st->sdp_port,
  1928. "?localport=%d&ttl=%d&connect=%d", rtsp_st->sdp_port,
  1929. rtsp_st->sdp_ttl,
  1930. rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0);
  1931. if (rtsp_st->source_addr[0])
  1932. av_strlcatf(url, sizeof(url), "&sources=%s", rtsp_st->source_addr);
  1933. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  1934. &s->interrupt_callback, NULL) < 0) {
  1935. err = AVERROR_INVALIDDATA;
  1936. goto fail;
  1937. }
  1938. }
  1939. if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
  1940. goto fail;
  1941. }
  1942. return 0;
  1943. fail:
  1944. ff_rtsp_close_streams(s);
  1945. ff_network_close();
  1946. return err;
  1947. }
  1948. static int sdp_read_close(AVFormatContext *s)
  1949. {
  1950. ff_rtsp_close_streams(s);
  1951. ff_network_close();
  1952. return 0;
  1953. }
  1954. static const AVClass sdp_demuxer_class = {
  1955. .class_name = "SDP demuxer",
  1956. .item_name = av_default_item_name,
  1957. .option = sdp_options,
  1958. .version = LIBAVUTIL_VERSION_INT,
  1959. };
  1960. AVInputFormat ff_sdp_demuxer = {
  1961. .name = "sdp",
  1962. .long_name = NULL_IF_CONFIG_SMALL("SDP"),
  1963. .priv_data_size = sizeof(RTSPState),
  1964. .read_probe = sdp_probe,
  1965. .read_header = sdp_read_header,
  1966. .read_packet = ff_rtsp_fetch_packet,
  1967. .read_close = sdp_read_close,
  1968. .priv_class = &sdp_demuxer_class,
  1969. };
  1970. #endif /* CONFIG_SDP_DEMUXER */
  1971. #if CONFIG_RTP_DEMUXER
  1972. static int rtp_probe(AVProbeData *p)
  1973. {
  1974. if (av_strstart(p->filename, "rtp:", NULL))
  1975. return AVPROBE_SCORE_MAX;
  1976. return 0;
  1977. }
  1978. static int rtp_read_header(AVFormatContext *s)
  1979. {
  1980. uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];
  1981. char host[500], sdp[500];
  1982. int ret, port;
  1983. URLContext* in = NULL;
  1984. int payload_type;
  1985. AVCodecContext codec = { 0 };
  1986. struct sockaddr_storage addr;
  1987. AVIOContext pb;
  1988. socklen_t addrlen = sizeof(addr);
  1989. RTSPState *rt = s->priv_data;
  1990. if (!ff_network_init())
  1991. return AVERROR(EIO);
  1992. ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
  1993. &s->interrupt_callback, NULL);
  1994. if (ret)
  1995. goto fail;
  1996. while (1) {
  1997. ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
  1998. if (ret == AVERROR(EAGAIN))
  1999. continue;
  2000. if (ret < 0)
  2001. goto fail;
  2002. if (ret < 12) {
  2003. av_log(s, AV_LOG_WARNING, "Received too short packet\n");
  2004. continue;
  2005. }
  2006. if ((recvbuf[0] & 0xc0) != 0x80) {
  2007. av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
  2008. "received\n");
  2009. continue;
  2010. }
  2011. if (RTP_PT_IS_RTCP(recvbuf[1]))
  2012. continue;
  2013. payload_type = recvbuf[1] & 0x7f;
  2014. break;
  2015. }
  2016. getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
  2017. ffurl_close(in);
  2018. in = NULL;
  2019. if (ff_rtp_get_codec_info(&codec, payload_type)) {
  2020. av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
  2021. "without an SDP file describing it\n",
  2022. payload_type);
  2023. goto fail;
  2024. }
  2025. if (codec.codec_type != AVMEDIA_TYPE_DATA) {
  2026. av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
  2027. "properly you need an SDP file "
  2028. "describing it\n");
  2029. }
  2030. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
  2031. NULL, 0, s->filename);
  2032. snprintf(sdp, sizeof(sdp),
  2033. "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
  2034. addr.ss_family == AF_INET ? 4 : 6, host,
  2035. codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
  2036. codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
  2037. port, payload_type);
  2038. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  2039. ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
  2040. s->pb = &pb;
  2041. /* sdp_read_header initializes this again */
  2042. ff_network_close();
  2043. rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
  2044. ret = sdp_read_header(s);
  2045. s->pb = NULL;
  2046. return ret;
  2047. fail:
  2048. if (in)
  2049. ffurl_close(in);
  2050. ff_network_close();
  2051. return ret;
  2052. }
  2053. static const AVClass rtp_demuxer_class = {
  2054. .class_name = "RTP demuxer",
  2055. .item_name = av_default_item_name,
  2056. .option = rtp_options,
  2057. .version = LIBAVUTIL_VERSION_INT,
  2058. };
  2059. AVInputFormat ff_rtp_demuxer = {
  2060. .name = "rtp",
  2061. .long_name = NULL_IF_CONFIG_SMALL("RTP input"),
  2062. .priv_data_size = sizeof(RTSPState),
  2063. .read_probe = rtp_probe,
  2064. .read_header = rtp_read_header,
  2065. .read_packet = ff_rtsp_fetch_packet,
  2066. .read_close = sdp_read_close,
  2067. .flags = AVFMT_NOFILE,
  2068. .priv_class = &rtp_demuxer_class,
  2069. };
  2070. #endif /* CONFIG_RTP_DEMUXER */