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.

1673 lines
51KB

  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. RTPDemuxContext *cur_rtp;
  66. int need_subscription;
  67. } RTSPState;
  68. typedef struct RTSPStream {
  69. URLContext *rtp_handle; /* RTP stream handle */
  70. RTPDemuxContext *rtp_ctx; /* RTP 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. rtp_payload_data_t 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. void *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 attrname_map
  253. {
  254. const char *str;
  255. uint16_t type;
  256. uint32_t offset;
  257. } attrname_map_t;
  258. /* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
  259. #define ATTR_NAME_TYPE_INT 0
  260. #define ATTR_NAME_TYPE_STR 1
  261. static attrname_map_t attr_names[]=
  262. {
  263. {"SizeLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, sizelength)},
  264. {"IndexLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexlength)},
  265. {"IndexDeltaLength", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, indexdeltalength)},
  266. {"profile-level-id", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, profile_level_id)},
  267. {"StreamType", ATTR_NAME_TYPE_INT, offsetof(rtp_payload_data_t, streamtype)},
  268. {"mode", ATTR_NAME_TYPE_STR, offsetof(rtp_payload_data_t, mode)},
  269. {NULL, -1, -1},
  270. };
  271. /** parse the attribute line from the fmtp a line of an sdp resonse. This is broken out as a function
  272. * because it is used in rtp_h264.c, which is forthcoming.
  273. */
  274. int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
  275. {
  276. skip_spaces(p);
  277. if(**p)
  278. {
  279. get_word_sep(attr, attr_size, "=", p);
  280. if (**p == '=')
  281. (*p)++;
  282. get_word_sep(value, value_size, ";", p);
  283. if (**p == ';')
  284. (*p)++;
  285. return 1;
  286. }
  287. return 0;
  288. }
  289. /* parse a SDP line and save stream attributes */
  290. static void sdp_parse_fmtp(AVStream *st, const char *p)
  291. {
  292. char attr[256];
  293. char value[4096];
  294. int i;
  295. RTSPStream *rtsp_st = st->priv_data;
  296. AVCodecContext *codec = st->codec;
  297. rtp_payload_data_t *rtp_payload_data = &rtsp_st->rtp_payload_data;
  298. /* loop on each attribute */
  299. while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))
  300. {
  301. /* grab the codec extra_data from the config parameter of the fmtp line */
  302. sdp_parse_fmtp_config(codec, attr, value);
  303. /* Looking for a known attribute */
  304. for (i = 0; attr_names[i].str; ++i) {
  305. if (!strcasecmp(attr, attr_names[i].str)) {
  306. if (attr_names[i].type == ATTR_NAME_TYPE_INT)
  307. *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);
  308. else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
  309. *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);
  310. }
  311. }
  312. }
  313. }
  314. /** Parse a string \p in the form of Range:npt=xx-xx, and determine the start
  315. * and end time.
  316. * Used for seeking in the rtp stream.
  317. */
  318. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  319. {
  320. char buf[256];
  321. skip_spaces(&p);
  322. if (!av_stristart(p, "npt=", &p))
  323. return;
  324. *start = AV_NOPTS_VALUE;
  325. *end = AV_NOPTS_VALUE;
  326. get_word_sep(buf, sizeof(buf), "-", &p);
  327. *start = parse_date(buf, 1);
  328. if (*p == '-') {
  329. p++;
  330. get_word_sep(buf, sizeof(buf), "-", &p);
  331. *end = parse_date(buf, 1);
  332. }
  333. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  334. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  335. }
  336. typedef struct SDPParseState {
  337. /* SDP only */
  338. struct in_addr default_ip;
  339. int default_ttl;
  340. } SDPParseState;
  341. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  342. int letter, const char *buf)
  343. {
  344. RTSPState *rt = s->priv_data;
  345. char buf1[64], st_type[64];
  346. const char *p;
  347. int codec_type, 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(st, 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(st, 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->streams[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. char buf[2048], *q;
  512. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  513. memset(s1, 0, sizeof(SDPParseState));
  514. p = content;
  515. for(;;) {
  516. skip_spaces(&p);
  517. letter = *p;
  518. if (letter == '\0')
  519. break;
  520. p++;
  521. if (*p != '=')
  522. goto next_line;
  523. p++;
  524. /* get the content */
  525. q = buf;
  526. while (*p != '\n' && *p != '\r' && *p != '\0') {
  527. if ((q - buf) < sizeof(buf) - 1)
  528. *q++ = *p;
  529. p++;
  530. }
  531. *q = '\0';
  532. sdp_parse_line(s, s1, letter, buf);
  533. next_line:
  534. while (*p != '\n' && *p != '\0')
  535. p++;
  536. if (*p == '\n')
  537. p++;
  538. }
  539. return 0;
  540. }
  541. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  542. {
  543. const char *p;
  544. int v;
  545. p = *pp;
  546. skip_spaces(&p);
  547. v = strtol(p, (char **)&p, 10);
  548. if (*p == '-') {
  549. p++;
  550. *min_ptr = v;
  551. v = strtol(p, (char **)&p, 10);
  552. *max_ptr = v;
  553. } else {
  554. *min_ptr = v;
  555. *max_ptr = v;
  556. }
  557. *pp = p;
  558. }
  559. /* XXX: only one transport specification is parsed */
  560. static void rtsp_parse_transport(RTSPHeader *reply, const char *p)
  561. {
  562. char transport_protocol[16];
  563. char profile[16];
  564. char lower_transport[16];
  565. char parameter[16];
  566. RTSPTransportField *th;
  567. char buf[256];
  568. reply->nb_transports = 0;
  569. for(;;) {
  570. skip_spaces(&p);
  571. if (*p == '\0')
  572. break;
  573. th = &reply->transports[reply->nb_transports];
  574. get_word_sep(transport_protocol, sizeof(transport_protocol),
  575. "/", &p);
  576. if (*p == '/')
  577. p++;
  578. if (!strcasecmp (transport_protocol, "rtp")) {
  579. get_word_sep(profile, sizeof(profile), "/;,", &p);
  580. lower_transport[0] = '\0';
  581. /* rtp/avp/<protocol> */
  582. if (*p == '/') {
  583. p++;
  584. get_word_sep(lower_transport, sizeof(lower_transport),
  585. ";,", &p);
  586. }
  587. th->transport = RTSP_TRANSPORT_RTP;
  588. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  589. !strcasecmp (transport_protocol, "x-real-rdt")) {
  590. /* x-pn-tng/<protocol> */
  591. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  592. profile[0] = '\0';
  593. th->transport = RTSP_TRANSPORT_RDT;
  594. }
  595. if (!strcasecmp(lower_transport, "TCP"))
  596. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  597. else
  598. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  599. if (*p == ';')
  600. p++;
  601. /* get each parameter */
  602. while (*p != '\0' && *p != ',') {
  603. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  604. if (!strcmp(parameter, "port")) {
  605. if (*p == '=') {
  606. p++;
  607. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  608. }
  609. } else if (!strcmp(parameter, "client_port")) {
  610. if (*p == '=') {
  611. p++;
  612. rtsp_parse_range(&th->client_port_min,
  613. &th->client_port_max, &p);
  614. }
  615. } else if (!strcmp(parameter, "server_port")) {
  616. if (*p == '=') {
  617. p++;
  618. rtsp_parse_range(&th->server_port_min,
  619. &th->server_port_max, &p);
  620. }
  621. } else if (!strcmp(parameter, "interleaved")) {
  622. if (*p == '=') {
  623. p++;
  624. rtsp_parse_range(&th->interleaved_min,
  625. &th->interleaved_max, &p);
  626. }
  627. } else if (!strcmp(parameter, "multicast")) {
  628. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  629. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  630. } else if (!strcmp(parameter, "ttl")) {
  631. if (*p == '=') {
  632. p++;
  633. th->ttl = strtol(p, (char **)&p, 10);
  634. }
  635. } else if (!strcmp(parameter, "destination")) {
  636. struct in_addr ipaddr;
  637. if (*p == '=') {
  638. p++;
  639. get_word_sep(buf, sizeof(buf), ";,", &p);
  640. if (inet_aton(buf, &ipaddr))
  641. th->destination = ntohl(ipaddr.s_addr);
  642. }
  643. }
  644. while (*p != ';' && *p != '\0' && *p != ',')
  645. p++;
  646. if (*p == ';')
  647. p++;
  648. }
  649. if (*p == ',')
  650. p++;
  651. reply->nb_transports++;
  652. }
  653. }
  654. void rtsp_parse_line(RTSPHeader *reply, const char *buf)
  655. {
  656. const char *p;
  657. /* NOTE: we do case independent match for broken servers */
  658. p = buf;
  659. if (av_stristart(p, "Session:", &p)) {
  660. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  661. } else if (av_stristart(p, "Content-Length:", &p)) {
  662. reply->content_length = strtol(p, NULL, 10);
  663. } else if (av_stristart(p, "Transport:", &p)) {
  664. rtsp_parse_transport(reply, p);
  665. } else if (av_stristart(p, "CSeq:", &p)) {
  666. reply->seq = strtol(p, NULL, 10);
  667. } else if (av_stristart(p, "Range:", &p)) {
  668. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  669. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  670. skip_spaces(&p);
  671. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  672. }
  673. }
  674. static int url_readbuf(URLContext *h, unsigned char *buf, int size)
  675. {
  676. int ret, len;
  677. len = 0;
  678. while (len < size) {
  679. ret = url_read(h, buf+len, size-len);
  680. if (ret < 1)
  681. return ret;
  682. len += ret;
  683. }
  684. return len;
  685. }
  686. /* skip a RTP/TCP interleaved packet */
  687. static void rtsp_skip_packet(AVFormatContext *s)
  688. {
  689. RTSPState *rt = s->priv_data;
  690. int ret, len, len1;
  691. uint8_t buf[1024];
  692. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  693. if (ret != 3)
  694. return;
  695. len = AV_RB16(buf + 1);
  696. #ifdef DEBUG
  697. printf("skipping RTP packet len=%d\n", len);
  698. #endif
  699. /* skip payload */
  700. while (len > 0) {
  701. len1 = len;
  702. if (len1 > sizeof(buf))
  703. len1 = sizeof(buf);
  704. ret = url_readbuf(rt->rtsp_hd, buf, len1);
  705. if (ret != len1)
  706. return;
  707. len -= len1;
  708. }
  709. }
  710. static void rtsp_send_cmd(AVFormatContext *s,
  711. const char *cmd, RTSPHeader *reply,
  712. unsigned char **content_ptr)
  713. {
  714. RTSPState *rt = s->priv_data;
  715. char buf[4096], buf1[1024], *q;
  716. unsigned char ch;
  717. const char *p;
  718. int content_length, line_count;
  719. unsigned char *content = NULL;
  720. memset(reply, 0, sizeof(RTSPHeader));
  721. rt->seq++;
  722. av_strlcpy(buf, cmd, sizeof(buf));
  723. snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
  724. av_strlcat(buf, buf1, sizeof(buf));
  725. if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
  726. snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
  727. av_strlcat(buf, buf1, sizeof(buf));
  728. }
  729. av_strlcat(buf, "\r\n", sizeof(buf));
  730. #ifdef DEBUG
  731. printf("Sending:\n%s--\n", buf);
  732. #endif
  733. url_write(rt->rtsp_hd, buf, strlen(buf));
  734. /* parse reply (XXX: use buffers) */
  735. line_count = 0;
  736. rt->last_reply[0] = '\0';
  737. for(;;) {
  738. q = buf;
  739. for(;;) {
  740. if (url_readbuf(rt->rtsp_hd, &ch, 1) != 1)
  741. break;
  742. if (ch == '\n')
  743. break;
  744. if (ch == '$') {
  745. /* XXX: only parse it if first char on line ? */
  746. rtsp_skip_packet(s);
  747. } else if (ch != '\r') {
  748. if ((q - buf) < sizeof(buf) - 1)
  749. *q++ = ch;
  750. }
  751. }
  752. *q = '\0';
  753. #ifdef DEBUG
  754. printf("line='%s'\n", buf);
  755. #endif
  756. /* test if last line */
  757. if (buf[0] == '\0')
  758. break;
  759. p = buf;
  760. if (line_count == 0) {
  761. /* get reply code */
  762. get_word(buf1, sizeof(buf1), &p);
  763. get_word(buf1, sizeof(buf1), &p);
  764. reply->status_code = atoi(buf1);
  765. } else {
  766. rtsp_parse_line(reply, p);
  767. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  768. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  769. }
  770. line_count++;
  771. }
  772. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  773. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  774. content_length = reply->content_length;
  775. if (content_length > 0) {
  776. /* leave some room for a trailing '\0' (useful for simple parsing) */
  777. content = av_malloc(content_length + 1);
  778. (void)url_readbuf(rt->rtsp_hd, content, content_length);
  779. content[content_length] = '\0';
  780. }
  781. if (content_ptr)
  782. *content_ptr = content;
  783. else
  784. av_free(content);
  785. }
  786. /* close and free RTSP streams */
  787. static void rtsp_close_streams(RTSPState *rt)
  788. {
  789. int i;
  790. RTSPStream *rtsp_st;
  791. for(i=0;i<rt->nb_rtsp_streams;i++) {
  792. rtsp_st = rt->rtsp_streams[i];
  793. if (rtsp_st) {
  794. if (rtsp_st->rtp_ctx)
  795. rtp_parse_close(rtsp_st->rtp_ctx);
  796. if (rtsp_st->rtp_handle)
  797. url_close(rtsp_st->rtp_handle);
  798. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  799. rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
  800. }
  801. }
  802. av_free(rt->rtsp_streams);
  803. }
  804. static int
  805. rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  806. {
  807. AVStream *st = NULL;
  808. /* open the RTP context */
  809. if (rtsp_st->stream_index >= 0)
  810. st = s->streams[rtsp_st->stream_index];
  811. if (!st)
  812. s->ctx_flags |= AVFMTCTX_NOHEADER;
  813. rtsp_st->rtp_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle, rtsp_st->sdp_payload_type, &rtsp_st->rtp_payload_data);
  814. if (!rtsp_st->rtp_ctx) {
  815. return AVERROR(ENOMEM);
  816. } else {
  817. if(rtsp_st->dynamic_handler) {
  818. rtsp_st->rtp_ctx->dynamic_protocol_context= rtsp_st->dynamic_protocol_context;
  819. rtsp_st->rtp_ctx->parse_packet= rtsp_st->dynamic_handler->parse_packet;
  820. }
  821. }
  822. return 0;
  823. }
  824. /**
  825. * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
  826. */
  827. static int
  828. make_setup_request (AVFormatContext *s, const char *host, int port,
  829. int lower_transport, const char *real_challenge)
  830. {
  831. RTSPState *rt = s->priv_data;
  832. int j, i, err;
  833. RTSPStream *rtsp_st;
  834. RTSPHeader reply1, *reply = &reply1;
  835. char cmd[2048];
  836. const char *trans_pref;
  837. if (rt->transport == RTSP_TRANSPORT_RDT)
  838. trans_pref = "x-pn-tng";
  839. else
  840. trans_pref = "RTP/AVP";
  841. /* for each stream, make the setup request */
  842. /* XXX: we assume the same server is used for the control of each
  843. RTSP stream */
  844. for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  845. char transport[2048];
  846. rtsp_st = rt->rtsp_streams[i];
  847. /* RTP/UDP */
  848. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  849. char buf[256];
  850. /* first try in specified port range */
  851. if (RTSP_RTP_PORT_MIN != 0) {
  852. while(j <= RTSP_RTP_PORT_MAX) {
  853. snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
  854. j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
  855. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
  856. goto rtp_opened;
  857. }
  858. }
  859. }
  860. /* then try on any port
  861. ** if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  862. ** err = AVERROR_INVALIDDATA;
  863. ** goto fail;
  864. ** }
  865. */
  866. rtp_opened:
  867. port = rtp_get_local_port(rtsp_st->rtp_handle);
  868. snprintf(transport, sizeof(transport) - 1,
  869. "%s/UDP;", trans_pref);
  870. if (rt->server_type != RTSP_SERVER_REAL)
  871. av_strlcat(transport, "unicast;", sizeof(transport));
  872. av_strlcatf(transport, sizeof(transport),
  873. "client_port=%d", port);
  874. if (rt->transport == RTSP_TRANSPORT_RTP)
  875. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  876. }
  877. /* RTP/TCP */
  878. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  879. snprintf(transport, sizeof(transport) - 1,
  880. "%s/TCP", trans_pref);
  881. }
  882. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  883. snprintf(transport, sizeof(transport) - 1,
  884. "%s/UDP;multicast", trans_pref);
  885. }
  886. if (rt->server_type == RTSP_SERVER_REAL)
  887. av_strlcat(transport, ";mode=play", sizeof(transport));
  888. snprintf(cmd, sizeof(cmd),
  889. "SETUP %s RTSP/1.0\r\n"
  890. "Transport: %s\r\n",
  891. rtsp_st->control_url, transport);
  892. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  893. char real_res[41], real_csum[9];
  894. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  895. real_challenge);
  896. av_strlcatf(cmd, sizeof(cmd),
  897. "If-Match: %s\r\n"
  898. "RealChallenge2: %s, sd=%s\r\n",
  899. rt->session_id, real_res, real_csum);
  900. }
  901. rtsp_send_cmd(s, cmd, reply, NULL);
  902. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  903. err = 1;
  904. goto fail;
  905. } else if (reply->status_code != RTSP_STATUS_OK ||
  906. reply->nb_transports != 1) {
  907. err = AVERROR_INVALIDDATA;
  908. goto fail;
  909. }
  910. /* XXX: same protocol for all streams is required */
  911. if (i > 0) {
  912. if (reply->transports[0].lower_transport != rt->lower_transport ||
  913. reply->transports[0].transport != rt->transport) {
  914. err = AVERROR_INVALIDDATA;
  915. goto fail;
  916. }
  917. } else {
  918. rt->lower_transport = reply->transports[0].lower_transport;
  919. rt->transport = reply->transports[0].transport;
  920. }
  921. /* close RTP connection if not choosen */
  922. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  923. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  924. url_close(rtsp_st->rtp_handle);
  925. rtsp_st->rtp_handle = NULL;
  926. }
  927. switch(reply->transports[0].lower_transport) {
  928. case RTSP_LOWER_TRANSPORT_TCP:
  929. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  930. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  931. break;
  932. case RTSP_LOWER_TRANSPORT_UDP:
  933. {
  934. char url[1024];
  935. /* XXX: also use address if specified */
  936. snprintf(url, sizeof(url), "rtp://%s:%d",
  937. host, reply->transports[0].server_port_min);
  938. if (rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  939. err = AVERROR_INVALIDDATA;
  940. goto fail;
  941. }
  942. }
  943. break;
  944. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  945. {
  946. char url[1024];
  947. struct in_addr in;
  948. in.s_addr = htonl(reply->transports[0].destination);
  949. snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
  950. inet_ntoa(in),
  951. reply->transports[0].port_min,
  952. reply->transports[0].ttl);
  953. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  954. err = AVERROR_INVALIDDATA;
  955. goto fail;
  956. }
  957. }
  958. break;
  959. }
  960. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  961. goto fail;
  962. }
  963. if (rt->server_type == RTSP_SERVER_REAL)
  964. rt->need_subscription = 1;
  965. return 0;
  966. fail:
  967. for (i=0; i<rt->nb_rtsp_streams; i++) {
  968. if (rt->rtsp_streams[i]->rtp_handle) {
  969. url_close(rt->rtsp_streams[i]->rtp_handle);
  970. rt->rtsp_streams[i]->rtp_handle = NULL;
  971. }
  972. }
  973. return err;
  974. }
  975. static int rtsp_read_header(AVFormatContext *s,
  976. AVFormatParameters *ap)
  977. {
  978. RTSPState *rt = s->priv_data;
  979. char host[1024], path[1024], tcpname[1024], cmd[2048], *option_list, *option;
  980. URLContext *rtsp_hd;
  981. int port, ret, err;
  982. RTSPHeader reply1, *reply = &reply1;
  983. unsigned char *content = NULL;
  984. int lower_transport_mask = 0;
  985. char real_challenge[64];
  986. /* extract hostname and port */
  987. url_split(NULL, 0, NULL, 0,
  988. host, sizeof(host), &port, path, sizeof(path), s->filename);
  989. if (port < 0)
  990. port = RTSP_DEFAULT_PORT;
  991. /* search for options */
  992. option_list = strchr(path, '?');
  993. if (option_list) {
  994. /* remove the options from the path */
  995. *option_list++ = 0;
  996. while(option_list) {
  997. /* move the option pointer */
  998. option = option_list;
  999. option_list = strchr(option_list, '&');
  1000. if (option_list)
  1001. *(option_list++) = 0;
  1002. /* handle the options */
  1003. if (strcmp(option, "udp") == 0)
  1004. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
  1005. else if (strcmp(option, "multicast") == 0)
  1006. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1007. else if (strcmp(option, "tcp") == 0)
  1008. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
  1009. }
  1010. }
  1011. if (!lower_transport_mask)
  1012. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_LAST) - 1;
  1013. /* open the tcp connexion */
  1014. snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
  1015. if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0)
  1016. return AVERROR(EIO);
  1017. rt->rtsp_hd = rtsp_hd;
  1018. rt->seq = 0;
  1019. /* request options supported by the server; this also detects server type */
  1020. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1021. snprintf(cmd, sizeof(cmd),
  1022. "OPTIONS %s RTSP/1.0\r\n", s->filename);
  1023. if (rt->server_type == RTSP_SERVER_REAL)
  1024. av_strlcat(cmd,
  1025. /**
  1026. * The following entries are required for proper
  1027. * streaming from a Realmedia server. They are
  1028. * interdependent in some way although we currently
  1029. * don't quite understand how. Values were copied
  1030. * from mplayer SVN r23589.
  1031. * @param CompanyID is a 16-byte ID in base64
  1032. * @param ClientChallenge is a 16-byte ID in hex
  1033. */
  1034. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1035. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1036. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1037. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1038. sizeof(cmd));
  1039. rtsp_send_cmd(s, cmd, reply, NULL);
  1040. if (reply->status_code != RTSP_STATUS_OK) {
  1041. err = AVERROR_INVALIDDATA;
  1042. goto fail;
  1043. }
  1044. /* detect server type if not standard-compliant RTP */
  1045. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1046. rt->server_type = RTSP_SERVER_REAL;
  1047. continue;
  1048. } else if (rt->server_type == RTSP_SERVER_REAL) {
  1049. strcpy(real_challenge, reply->real_challenge);
  1050. }
  1051. break;
  1052. }
  1053. /* describe the stream */
  1054. snprintf(cmd, sizeof(cmd),
  1055. "DESCRIBE %s RTSP/1.0\r\n"
  1056. "Accept: application/sdp\r\n",
  1057. s->filename);
  1058. if (rt->server_type == RTSP_SERVER_REAL) {
  1059. /**
  1060. * The Require: attribute is needed for proper streaming from
  1061. * Realmedia servers.
  1062. */
  1063. av_strlcat(cmd,
  1064. "Require: com.real.retain-entity-for-setup\r\n",
  1065. sizeof(cmd));
  1066. }
  1067. rtsp_send_cmd(s, cmd, reply, &content);
  1068. if (!content) {
  1069. err = AVERROR_INVALIDDATA;
  1070. goto fail;
  1071. }
  1072. if (reply->status_code != RTSP_STATUS_OK) {
  1073. err = AVERROR_INVALIDDATA;
  1074. goto fail;
  1075. }
  1076. /* now we got the SDP description, we parse it */
  1077. ret = sdp_parse(s, (const char *)content);
  1078. av_freep(&content);
  1079. if (ret < 0) {
  1080. err = AVERROR_INVALIDDATA;
  1081. goto fail;
  1082. }
  1083. do {
  1084. int lower_transport = ff_log2_tab[lower_transport_mask & ~(lower_transport_mask - 1)];
  1085. err = make_setup_request(s, host, port, lower_transport,
  1086. rt->server_type == RTSP_SERVER_REAL ?
  1087. real_challenge : NULL);
  1088. if (err < 0)
  1089. goto fail;
  1090. lower_transport_mask &= ~(1 << lower_transport);
  1091. if (lower_transport_mask == 0 && err == 1) {
  1092. err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
  1093. goto fail;
  1094. }
  1095. } while (err);
  1096. rt->state = RTSP_STATE_IDLE;
  1097. rt->seek_timestamp = 0; /* default is to start stream at position
  1098. zero */
  1099. if (ap->initial_pause) {
  1100. /* do not start immediately */
  1101. } else {
  1102. if (rtsp_read_play(s) < 0) {
  1103. err = AVERROR_INVALIDDATA;
  1104. goto fail;
  1105. }
  1106. }
  1107. return 0;
  1108. fail:
  1109. rtsp_close_streams(rt);
  1110. av_freep(&content);
  1111. url_close(rt->rtsp_hd);
  1112. return err;
  1113. }
  1114. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1115. uint8_t *buf, int buf_size)
  1116. {
  1117. RTSPState *rt = s->priv_data;
  1118. int id, len, i, ret;
  1119. RTSPStream *rtsp_st;
  1120. #ifdef DEBUG_RTP_TCP
  1121. printf("tcp_read_packet:\n");
  1122. #endif
  1123. redo:
  1124. for(;;) {
  1125. ret = url_readbuf(rt->rtsp_hd, buf, 1);
  1126. #ifdef DEBUG_RTP_TCP
  1127. printf("ret=%d c=%02x [%c]\n", ret, buf[0], buf[0]);
  1128. #endif
  1129. if (ret != 1)
  1130. return -1;
  1131. if (buf[0] == '$')
  1132. break;
  1133. }
  1134. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  1135. if (ret != 3)
  1136. return -1;
  1137. id = buf[0];
  1138. len = AV_RB16(buf + 1);
  1139. #ifdef DEBUG_RTP_TCP
  1140. printf("id=%d len=%d\n", id, len);
  1141. #endif
  1142. if (len > buf_size || len < 12)
  1143. goto redo;
  1144. /* get the data */
  1145. ret = url_readbuf(rt->rtsp_hd, buf, len);
  1146. if (ret != len)
  1147. return -1;
  1148. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1149. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL) < 0)
  1150. return -1;
  1151. /* find the matching stream */
  1152. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1153. rtsp_st = rt->rtsp_streams[i];
  1154. if (id >= rtsp_st->interleaved_min &&
  1155. id <= rtsp_st->interleaved_max)
  1156. goto found;
  1157. }
  1158. goto redo;
  1159. found:
  1160. *prtsp_st = rtsp_st;
  1161. return len;
  1162. }
  1163. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1164. uint8_t *buf, int buf_size)
  1165. {
  1166. RTSPState *rt = s->priv_data;
  1167. RTSPStream *rtsp_st;
  1168. fd_set rfds;
  1169. int fd1, fd2, fd_max, n, i, ret;
  1170. struct timeval tv;
  1171. for(;;) {
  1172. if (url_interrupt_cb())
  1173. return AVERROR(EINTR);
  1174. FD_ZERO(&rfds);
  1175. fd_max = -1;
  1176. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1177. rtsp_st = rt->rtsp_streams[i];
  1178. /* currently, we cannot probe RTCP handle because of blocking restrictions */
  1179. rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
  1180. if (fd1 > fd_max)
  1181. fd_max = fd1;
  1182. FD_SET(fd1, &rfds);
  1183. }
  1184. tv.tv_sec = 0;
  1185. tv.tv_usec = 100 * 1000;
  1186. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1187. if (n > 0) {
  1188. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1189. rtsp_st = rt->rtsp_streams[i];
  1190. rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
  1191. if (FD_ISSET(fd1, &rfds)) {
  1192. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1193. if (ret > 0) {
  1194. *prtsp_st = rtsp_st;
  1195. return ret;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. static int rtsp_read_packet(AVFormatContext *s,
  1203. AVPacket *pkt)
  1204. {
  1205. RTSPState *rt = s->priv_data;
  1206. RTSPStream *rtsp_st;
  1207. int ret, len;
  1208. uint8_t buf[RTP_MAX_PACKET_LENGTH];
  1209. if (rt->server_type == RTSP_SERVER_REAL && rt->need_subscription) {
  1210. int i;
  1211. RTSPHeader reply1, *reply = &reply1;
  1212. char cmd[1024];
  1213. snprintf(cmd, sizeof(cmd),
  1214. "SET_PARAMETER %s RTSP/1.0\r\n"
  1215. "Subscribe: ",
  1216. s->filename);
  1217. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1218. if (i != 0) av_strlcat(cmd, ",", sizeof(cmd));
  1219. ff_rdt_subscribe_rule(cmd, sizeof(cmd), i, 0);
  1220. if (rt->transport == RTSP_TRANSPORT_RDT)
  1221. ff_rdt_subscribe_rule2(
  1222. rt->rtsp_streams[i]->rtp_ctx,
  1223. cmd, sizeof(cmd), i, 0);
  1224. }
  1225. av_strlcat(cmd, "\r\n", sizeof(cmd));
  1226. rtsp_send_cmd(s, cmd, reply, NULL);
  1227. if (reply->status_code != RTSP_STATUS_OK)
  1228. return AVERROR_INVALIDDATA;
  1229. rt->need_subscription = 0;
  1230. if (rt->state == RTSP_STATE_PLAYING)
  1231. rtsp_read_play (s);
  1232. }
  1233. /* get next frames from the same RTP packet */
  1234. if (rt->cur_rtp) {
  1235. if (rt->transport == RTSP_TRANSPORT_RDT)
  1236. ret = ff_rdt_parse_packet(rt->cur_rtp, pkt, NULL, 0);
  1237. else
  1238. ret = rtp_parse_packet(rt->cur_rtp, pkt, NULL, 0);
  1239. if (ret == 0) {
  1240. rt->cur_rtp = NULL;
  1241. return 0;
  1242. } else if (ret == 1) {
  1243. return 0;
  1244. } else {
  1245. rt->cur_rtp = NULL;
  1246. }
  1247. }
  1248. /* read next RTP packet */
  1249. redo:
  1250. switch(rt->lower_transport) {
  1251. default:
  1252. case RTSP_LOWER_TRANSPORT_TCP:
  1253. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1254. break;
  1255. case RTSP_LOWER_TRANSPORT_UDP:
  1256. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1257. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1258. if (len >=0 && rtsp_st->rtp_ctx)
  1259. rtp_check_and_send_back_rr(rtsp_st->rtp_ctx, len);
  1260. break;
  1261. }
  1262. if (len < 0)
  1263. return len;
  1264. if (rt->transport == RTSP_TRANSPORT_RDT)
  1265. ret = ff_rdt_parse_packet(rtsp_st->rtp_ctx, pkt, buf, len);
  1266. else
  1267. ret = rtp_parse_packet(rtsp_st->rtp_ctx, pkt, buf, len);
  1268. if (ret < 0)
  1269. goto redo;
  1270. if (ret == 1) {
  1271. /* more packets may follow, so we save the RTP context */
  1272. rt->cur_rtp = rtsp_st->rtp_ctx;
  1273. }
  1274. return 0;
  1275. }
  1276. static int rtsp_read_play(AVFormatContext *s)
  1277. {
  1278. RTSPState *rt = s->priv_data;
  1279. RTSPHeader reply1, *reply = &reply1;
  1280. char cmd[1024];
  1281. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1282. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1283. if (rt->state == RTSP_STATE_PAUSED) {
  1284. snprintf(cmd, sizeof(cmd),
  1285. "PLAY %s RTSP/1.0\r\n",
  1286. s->filename);
  1287. } else {
  1288. snprintf(cmd, sizeof(cmd),
  1289. "PLAY %s RTSP/1.0\r\n"
  1290. "Range: npt=%0.3f-\r\n",
  1291. s->filename,
  1292. (double)rt->seek_timestamp / AV_TIME_BASE);
  1293. }
  1294. rtsp_send_cmd(s, cmd, reply, NULL);
  1295. if (reply->status_code != RTSP_STATUS_OK) {
  1296. return -1;
  1297. }
  1298. }
  1299. rt->state = RTSP_STATE_PLAYING;
  1300. return 0;
  1301. }
  1302. /* pause the stream */
  1303. static int rtsp_read_pause(AVFormatContext *s)
  1304. {
  1305. RTSPState *rt = s->priv_data;
  1306. RTSPHeader reply1, *reply = &reply1;
  1307. char cmd[1024];
  1308. rt = s->priv_data;
  1309. if (rt->state != RTSP_STATE_PLAYING)
  1310. return 0;
  1311. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1312. snprintf(cmd, sizeof(cmd),
  1313. "PAUSE %s RTSP/1.0\r\n",
  1314. s->filename);
  1315. rtsp_send_cmd(s, cmd, reply, NULL);
  1316. if (reply->status_code != RTSP_STATUS_OK) {
  1317. return -1;
  1318. }
  1319. }
  1320. rt->state = RTSP_STATE_PAUSED;
  1321. return 0;
  1322. }
  1323. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1324. int64_t timestamp, int flags)
  1325. {
  1326. RTSPState *rt = s->priv_data;
  1327. rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
  1328. switch(rt->state) {
  1329. default:
  1330. case RTSP_STATE_IDLE:
  1331. break;
  1332. case RTSP_STATE_PLAYING:
  1333. if (rtsp_read_play(s) != 0)
  1334. return -1;
  1335. break;
  1336. case RTSP_STATE_PAUSED:
  1337. rt->state = RTSP_STATE_IDLE;
  1338. break;
  1339. }
  1340. return 0;
  1341. }
  1342. static int rtsp_read_close(AVFormatContext *s)
  1343. {
  1344. RTSPState *rt = s->priv_data;
  1345. RTSPHeader reply1, *reply = &reply1;
  1346. char cmd[1024];
  1347. #if 0
  1348. /* NOTE: it is valid to flush the buffer here */
  1349. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1350. url_fclose(&rt->rtsp_gb);
  1351. }
  1352. #endif
  1353. snprintf(cmd, sizeof(cmd),
  1354. "TEARDOWN %s RTSP/1.0\r\n",
  1355. s->filename);
  1356. rtsp_send_cmd(s, cmd, reply, NULL);
  1357. rtsp_close_streams(rt);
  1358. url_close(rt->rtsp_hd);
  1359. return 0;
  1360. }
  1361. #ifdef CONFIG_RTSP_DEMUXER
  1362. AVInputFormat rtsp_demuxer = {
  1363. "rtsp",
  1364. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1365. sizeof(RTSPState),
  1366. rtsp_probe,
  1367. rtsp_read_header,
  1368. rtsp_read_packet,
  1369. rtsp_read_close,
  1370. rtsp_read_seek,
  1371. .flags = AVFMT_NOFILE,
  1372. .read_play = rtsp_read_play,
  1373. .read_pause = rtsp_read_pause,
  1374. };
  1375. #endif
  1376. static int sdp_probe(AVProbeData *p1)
  1377. {
  1378. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1379. /* we look for a line beginning "c=IN IP4" */
  1380. while (p < p_end && *p != '\0') {
  1381. if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
  1382. return AVPROBE_SCORE_MAX / 2;
  1383. while(p < p_end - 1 && *p != '\n') p++;
  1384. if (++p >= p_end)
  1385. break;
  1386. if (*p == '\r')
  1387. p++;
  1388. }
  1389. return 0;
  1390. }
  1391. #define SDP_MAX_SIZE 8192
  1392. static int sdp_read_header(AVFormatContext *s,
  1393. AVFormatParameters *ap)
  1394. {
  1395. RTSPState *rt = s->priv_data;
  1396. RTSPStream *rtsp_st;
  1397. int size, i, err;
  1398. char *content;
  1399. char url[1024];
  1400. /* read the whole sdp file */
  1401. /* XXX: better loading */
  1402. content = av_malloc(SDP_MAX_SIZE);
  1403. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1404. if (size <= 0) {
  1405. av_free(content);
  1406. return AVERROR_INVALIDDATA;
  1407. }
  1408. content[size] ='\0';
  1409. sdp_parse(s, content);
  1410. av_free(content);
  1411. /* open each RTP stream */
  1412. for(i=0;i<rt->nb_rtsp_streams;i++) {
  1413. rtsp_st = rt->rtsp_streams[i];
  1414. snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
  1415. inet_ntoa(rtsp_st->sdp_ip),
  1416. rtsp_st->sdp_port,
  1417. rtsp_st->sdp_port,
  1418. rtsp_st->sdp_ttl);
  1419. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1420. err = AVERROR_INVALIDDATA;
  1421. goto fail;
  1422. }
  1423. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1424. goto fail;
  1425. }
  1426. return 0;
  1427. fail:
  1428. rtsp_close_streams(rt);
  1429. return err;
  1430. }
  1431. static int sdp_read_packet(AVFormatContext *s,
  1432. AVPacket *pkt)
  1433. {
  1434. return rtsp_read_packet(s, pkt);
  1435. }
  1436. static int sdp_read_close(AVFormatContext *s)
  1437. {
  1438. RTSPState *rt = s->priv_data;
  1439. rtsp_close_streams(rt);
  1440. return 0;
  1441. }
  1442. #ifdef CONFIG_SDP_DEMUXER
  1443. AVInputFormat sdp_demuxer = {
  1444. "sdp",
  1445. NULL_IF_CONFIG_SMALL("SDP"),
  1446. sizeof(RTSPState),
  1447. sdp_probe,
  1448. sdp_read_header,
  1449. sdp_read_packet,
  1450. sdp_read_close,
  1451. };
  1452. #endif
  1453. #ifdef CONFIG_REDIR_DEMUXER
  1454. /* dummy redirector format (used directly in av_open_input_file now) */
  1455. static int redir_probe(AVProbeData *pd)
  1456. {
  1457. const char *p;
  1458. p = pd->buf;
  1459. while (redir_isspace(*p))
  1460. p++;
  1461. if (av_strstart(p, "http://", NULL) ||
  1462. av_strstart(p, "rtsp://", NULL))
  1463. return AVPROBE_SCORE_MAX;
  1464. return 0;
  1465. }
  1466. static int redir_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1467. {
  1468. char buf[4096], *q;
  1469. int c;
  1470. AVFormatContext *ic = NULL;
  1471. ByteIOContext *f = s->pb;
  1472. /* parse each URL and try to open it */
  1473. c = url_fgetc(f);
  1474. while (c != URL_EOF) {
  1475. /* skip spaces */
  1476. for(;;) {
  1477. if (!redir_isspace(c))
  1478. break;
  1479. c = url_fgetc(f);
  1480. }
  1481. if (c == URL_EOF)
  1482. break;
  1483. /* record url */
  1484. q = buf;
  1485. for(;;) {
  1486. if (c == URL_EOF || redir_isspace(c))
  1487. break;
  1488. if ((q - buf) < sizeof(buf) - 1)
  1489. *q++ = c;
  1490. c = url_fgetc(f);
  1491. }
  1492. *q = '\0';
  1493. //printf("URL='%s'\n", buf);
  1494. /* try to open the media file */
  1495. if (av_open_input_file(&ic, buf, NULL, 0, NULL) == 0)
  1496. break;
  1497. }
  1498. if (!ic)
  1499. return AVERROR(EIO);
  1500. *s = *ic;
  1501. url_fclose(f);
  1502. return 0;
  1503. }
  1504. AVInputFormat redir_demuxer = {
  1505. "redir",
  1506. NULL_IF_CONFIG_SMALL("Redirector format"),
  1507. 0,
  1508. redir_probe,
  1509. redir_read_header,
  1510. NULL,
  1511. NULL,
  1512. };
  1513. #endif