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.

1691 lines
52KB

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