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.

1809 lines
59KB

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