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.

1836 lines
64KB

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