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.

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