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.

1748 lines
55KB

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