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.

1616 lines
49KB

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