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.

1826 lines
63KB

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