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.

2070 lines
74KB

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