rtspdec.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. /*
  2. * RTSP demuxer
  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. #include "libavutil/avstring.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/mathematics.h"
  24. #include "libavutil/random_seed.h"
  25. #include "libavutil/time.h"
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "network.h"
  29. #include "os_support.h"
  30. #include "rtsp.h"
  31. #include "rdt.h"
  32. #include "url.h"
  33. static const struct RTSPStatusMessage {
  34. enum RTSPStatusCode code;
  35. const char *message;
  36. } status_messages[] = {
  37. { RTSP_STATUS_OK, "OK" },
  38. { RTSP_STATUS_METHOD, "Method Not Allowed" },
  39. { RTSP_STATUS_BANDWIDTH, "Not Enough Bandwidth" },
  40. { RTSP_STATUS_SESSION, "Session Not Found" },
  41. { RTSP_STATUS_STATE, "Method Not Valid in This State" },
  42. { RTSP_STATUS_AGGREGATE, "Aggregate operation not allowed" },
  43. { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
  44. { RTSP_STATUS_TRANSPORT, "Unsupported transport" },
  45. { RTSP_STATUS_INTERNAL, "Internal Server Error" },
  46. { RTSP_STATUS_SERVICE, "Service Unavailable" },
  47. { RTSP_STATUS_VERSION, "RTSP Version not supported" },
  48. { 0, "NULL" }
  49. };
  50. static int rtsp_read_close(AVFormatContext *s)
  51. {
  52. RTSPState *rt = s->priv_data;
  53. if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
  54. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  55. ff_rtsp_close_streams(s);
  56. ff_rtsp_close_connections(s);
  57. ff_network_close();
  58. rt->real_setup = NULL;
  59. av_freep(&rt->real_setup_cache);
  60. return 0;
  61. }
  62. static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
  63. int *rbuflen)
  64. {
  65. RTSPState *rt = s->priv_data;
  66. int idx = 0;
  67. int ret = 0;
  68. *rbuflen = 0;
  69. do {
  70. ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
  71. if (ret < 0)
  72. return ret;
  73. if (rbuf[idx] == '\r') {
  74. /* Ignore */
  75. } else if (rbuf[idx] == '\n') {
  76. rbuf[idx] = '\0';
  77. *rbuflen = idx;
  78. return 0;
  79. } else
  80. idx++;
  81. } while (idx < rbufsize);
  82. av_log(s, AV_LOG_ERROR, "Message too long\n");
  83. return AVERROR(EIO);
  84. }
  85. static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
  86. const char *extracontent, uint16_t seq)
  87. {
  88. RTSPState *rt = s->priv_data;
  89. char message[4096];
  90. int index = 0;
  91. while (status_messages[index].code) {
  92. if (status_messages[index].code == code) {
  93. snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
  94. code, status_messages[index].message);
  95. break;
  96. }
  97. index++;
  98. }
  99. if (!status_messages[index].code)
  100. return AVERROR(EINVAL);
  101. av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
  102. av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
  103. if (extracontent)
  104. av_strlcat(message, extracontent, sizeof(message));
  105. av_strlcat(message, "\r\n", sizeof(message));
  106. av_dlog(s, "Sending response:\n%s", message);
  107. ffurl_write(rt->rtsp_hd, message, strlen(message));
  108. return 0;
  109. }
  110. static inline int check_sessionid(AVFormatContext *s,
  111. RTSPMessageHeader *request)
  112. {
  113. RTSPState *rt = s->priv_data;
  114. unsigned char *session_id = rt->session_id;
  115. if (!session_id[0]) {
  116. av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
  117. return 0;
  118. }
  119. if (strcmp(session_id, request->session_id)) {
  120. av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
  121. request->session_id);
  122. rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
  123. return AVERROR_STREAM_NOT_FOUND;
  124. }
  125. return 0;
  126. }
  127. static inline int rtsp_read_request(AVFormatContext *s,
  128. RTSPMessageHeader *request,
  129. const char *method)
  130. {
  131. RTSPState *rt = s->priv_data;
  132. char rbuf[1024];
  133. int rbuflen, ret;
  134. do {
  135. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  136. if (ret)
  137. return ret;
  138. if (rbuflen > 1) {
  139. av_dlog(s, "Parsing[%d]: %s\n", rbuflen, rbuf);
  140. ff_rtsp_parse_line(request, rbuf, rt, method);
  141. }
  142. } while (rbuflen > 0);
  143. if (request->seq != rt->seq + 1) {
  144. av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
  145. request->seq);
  146. return AVERROR(EINVAL);
  147. }
  148. if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
  149. ret = check_sessionid(s, request);
  150. if (ret)
  151. return ret;
  152. }
  153. return 0;
  154. }
  155. static int rtsp_read_announce(AVFormatContext *s)
  156. {
  157. RTSPState *rt = s->priv_data;
  158. RTSPMessageHeader request = { 0 };
  159. char sdp[4096];
  160. int ret;
  161. ret = rtsp_read_request(s, &request, "ANNOUNCE");
  162. if (ret)
  163. return ret;
  164. rt->seq++;
  165. if (strcmp(request.content_type, "application/sdp")) {
  166. av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
  167. request.content_type);
  168. rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
  169. return AVERROR_OPTION_NOT_FOUND;
  170. }
  171. if (request.content_length && request.content_length < sizeof(sdp) - 1) {
  172. /* Read SDP */
  173. if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
  174. < request.content_length) {
  175. av_log(s, AV_LOG_ERROR,
  176. "Unable to get complete SDP Description in ANNOUNCE\n");
  177. rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
  178. return AVERROR(EIO);
  179. }
  180. sdp[request.content_length] = '\0';
  181. av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
  182. ret = ff_sdp_parse(s, sdp);
  183. if (ret)
  184. return ret;
  185. rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
  186. return 0;
  187. }
  188. av_log(s, AV_LOG_ERROR,
  189. "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
  190. rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
  191. "Content-Length exceeds buffer size", request.seq);
  192. return AVERROR(EIO);
  193. }
  194. static int rtsp_read_options(AVFormatContext *s)
  195. {
  196. RTSPState *rt = s->priv_data;
  197. RTSPMessageHeader request = { 0 };
  198. int ret = 0;
  199. /* Parsing headers */
  200. ret = rtsp_read_request(s, &request, "OPTIONS");
  201. if (ret)
  202. return ret;
  203. rt->seq++;
  204. /* Send Reply */
  205. rtsp_send_reply(s, RTSP_STATUS_OK,
  206. "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
  207. request.seq);
  208. return 0;
  209. }
  210. static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
  211. {
  212. RTSPState *rt = s->priv_data;
  213. RTSPMessageHeader request = { 0 };
  214. int ret = 0;
  215. char url[1024];
  216. RTSPStream *rtsp_st;
  217. char responseheaders[1024];
  218. int localport = -1;
  219. int transportidx = 0;
  220. int streamid = 0;
  221. ret = rtsp_read_request(s, &request, "SETUP");
  222. if (ret)
  223. return ret;
  224. rt->seq++;
  225. if (!request.nb_transports) {
  226. av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
  227. return AVERROR_INVALIDDATA;
  228. }
  229. for (transportidx = 0; transportidx < request.nb_transports;
  230. transportidx++) {
  231. if (!request.transports[transportidx].mode_record ||
  232. (request.transports[transportidx].lower_transport !=
  233. RTSP_LOWER_TRANSPORT_UDP &&
  234. request.transports[transportidx].lower_transport !=
  235. RTSP_LOWER_TRANSPORT_TCP)) {
  236. av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
  237. " protocol not supported (yet)\n");
  238. return AVERROR_INVALIDDATA;
  239. }
  240. }
  241. if (request.nb_transports > 1)
  242. av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
  243. "using first of all\n");
  244. for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
  245. if (!strcmp(rt->rtsp_streams[streamid]->control_url,
  246. controlurl))
  247. break;
  248. }
  249. if (streamid == rt->nb_rtsp_streams) {
  250. av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
  251. return AVERROR_STREAM_NOT_FOUND;
  252. }
  253. rtsp_st = rt->rtsp_streams[streamid];
  254. localport = rt->rtp_port_min;
  255. if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  256. rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  257. if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
  258. rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
  259. return ret;
  260. }
  261. rtsp_st->interleaved_min = request.transports[0].interleaved_min;
  262. rtsp_st->interleaved_max = request.transports[0].interleaved_max;
  263. snprintf(responseheaders, sizeof(responseheaders), "Transport: "
  264. "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
  265. "\r\n", request.transports[0].interleaved_min,
  266. request.transports[0].interleaved_max);
  267. } else {
  268. do {
  269. ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
  270. av_dlog(s, "Opening: %s", url);
  271. ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  272. &s->interrupt_callback, NULL);
  273. if (ret)
  274. localport += 2;
  275. } while (ret || localport > rt->rtp_port_max);
  276. if (localport > rt->rtp_port_max) {
  277. rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
  278. return ret;
  279. }
  280. av_dlog(s, "Listening on: %d",
  281. ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
  282. if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
  283. rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
  284. return ret;
  285. }
  286. localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  287. snprintf(responseheaders, sizeof(responseheaders), "Transport: "
  288. "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
  289. "client_port=%d-%d;server_port=%d-%d\r\n",
  290. host, request.transports[0].client_port_min,
  291. request.transports[0].client_port_max, localport,
  292. localport + 1);
  293. }
  294. /* Establish sessionid if not previously set */
  295. /* Put this in a function? */
  296. /* RFC 2326: session id must be at least 8 digits */
  297. while (strlen(rt->session_id) < 8)
  298. av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
  299. av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
  300. rt->session_id);
  301. /* Send Reply */
  302. rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
  303. rt->state = RTSP_STATE_PAUSED;
  304. return 0;
  305. }
  306. static int rtsp_read_record(AVFormatContext *s)
  307. {
  308. RTSPState *rt = s->priv_data;
  309. RTSPMessageHeader request = { 0 };
  310. int ret = 0;
  311. char responseheaders[1024];
  312. ret = rtsp_read_request(s, &request, "RECORD");
  313. if (ret)
  314. return ret;
  315. ret = check_sessionid(s, &request);
  316. if (ret)
  317. return ret;
  318. rt->seq++;
  319. snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
  320. rt->session_id);
  321. rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
  322. rt->state = RTSP_STATE_STREAMING;
  323. return 0;
  324. }
  325. static inline int parse_command_line(AVFormatContext *s, const char *line,
  326. int linelen, char *uri, int urisize,
  327. char *method, int methodsize,
  328. enum RTSPMethod *methodcode)
  329. {
  330. RTSPState *rt = s->priv_data;
  331. const char *linept, *searchlinept;
  332. linept = strchr(line, ' ');
  333. if (linept - line > methodsize - 1) {
  334. av_log(s, AV_LOG_ERROR, "Method string too long\n");
  335. return AVERROR(EIO);
  336. }
  337. memcpy(method, line, linept - line);
  338. method[linept - line] = '\0';
  339. linept++;
  340. if (!strcmp(method, "ANNOUNCE"))
  341. *methodcode = ANNOUNCE;
  342. else if (!strcmp(method, "OPTIONS"))
  343. *methodcode = OPTIONS;
  344. else if (!strcmp(method, "RECORD"))
  345. *methodcode = RECORD;
  346. else if (!strcmp(method, "SETUP"))
  347. *methodcode = SETUP;
  348. else if (!strcmp(method, "PAUSE"))
  349. *methodcode = PAUSE;
  350. else if (!strcmp(method, "TEARDOWN"))
  351. *methodcode = TEARDOWN;
  352. else
  353. *methodcode = UNKNOWN;
  354. /* Check method with the state */
  355. if (rt->state == RTSP_STATE_IDLE) {
  356. if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
  357. av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
  358. line);
  359. return AVERROR_PROTOCOL_NOT_FOUND;
  360. }
  361. } else if (rt->state == RTSP_STATE_PAUSED) {
  362. if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
  363. && (*methodcode != SETUP)) {
  364. av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
  365. line);
  366. return AVERROR_PROTOCOL_NOT_FOUND;
  367. }
  368. } else if (rt->state == RTSP_STATE_STREAMING) {
  369. if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
  370. && (*methodcode != TEARDOWN)) {
  371. av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
  372. " %s\n", line);
  373. return AVERROR_PROTOCOL_NOT_FOUND;
  374. }
  375. } else {
  376. av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
  377. return AVERROR_BUG;
  378. }
  379. searchlinept = strchr(linept, ' ');
  380. if (searchlinept == NULL) {
  381. av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
  382. return AVERROR_INVALIDDATA;
  383. }
  384. if (searchlinept - linept > urisize - 1) {
  385. av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
  386. return AVERROR(EIO);
  387. }
  388. memcpy(uri, linept, searchlinept - linept);
  389. uri[searchlinept - linept] = '\0';
  390. if (strcmp(rt->control_uri, uri)) {
  391. char host[128], path[512], auth[128];
  392. int port;
  393. char ctl_host[128], ctl_path[512], ctl_auth[128];
  394. int ctl_port;
  395. av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
  396. path, sizeof(path), uri);
  397. av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
  398. sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
  399. rt->control_uri);
  400. if (strcmp(host, ctl_host))
  401. av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
  402. host, ctl_host);
  403. if (strcmp(path, ctl_path) && *methodcode != SETUP)
  404. av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
  405. " %s\n", path, ctl_path);
  406. if (*methodcode == ANNOUNCE) {
  407. av_log(s, AV_LOG_INFO,
  408. "Updating control URI to %s\n", uri);
  409. strcpy(rt->control_uri, uri);
  410. }
  411. }
  412. linept = searchlinept + 1;
  413. if (!av_strstart(linept, "RTSP/1.0", NULL)) {
  414. av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
  415. return AVERROR_PROTOCOL_NOT_FOUND;
  416. }
  417. return 0;
  418. }
  419. int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
  420. {
  421. RTSPState *rt = s->priv_data;
  422. unsigned char rbuf[4096];
  423. unsigned char method[10];
  424. char uri[500];
  425. int ret;
  426. int rbuflen = 0;
  427. RTSPMessageHeader request = { 0 };
  428. enum RTSPMethod methodcode;
  429. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  430. if (ret < 0)
  431. return ret;
  432. ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
  433. sizeof(method), &methodcode);
  434. if (ret) {
  435. av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
  436. return ret;
  437. }
  438. ret = rtsp_read_request(s, &request, method);
  439. if (ret)
  440. return ret;
  441. rt->seq++;
  442. if (methodcode == PAUSE) {
  443. rt->state = RTSP_STATE_PAUSED;
  444. ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
  445. // TODO: Missing date header in response
  446. } else if (methodcode == OPTIONS) {
  447. ret = rtsp_send_reply(s, RTSP_STATUS_OK,
  448. "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
  449. "RECORD\r\n", request.seq);
  450. } else if (methodcode == TEARDOWN) {
  451. rt->state = RTSP_STATE_IDLE;
  452. ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
  453. return 0;
  454. }
  455. return ret;
  456. }
  457. static int rtsp_read_play(AVFormatContext *s)
  458. {
  459. RTSPState *rt = s->priv_data;
  460. RTSPMessageHeader reply1, *reply = &reply1;
  461. int i;
  462. char cmd[1024];
  463. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  464. rt->nb_byes = 0;
  465. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  466. if (rt->transport == RTSP_TRANSPORT_RTP) {
  467. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  468. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  469. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  470. if (!rtpctx)
  471. continue;
  472. ff_rtp_reset_packet_queue(rtpctx);
  473. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  474. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  475. rtpctx->base_timestamp = 0;
  476. rtpctx->timestamp = 0;
  477. rtpctx->unwrapped_timestamp = 0;
  478. rtpctx->rtcp_ts_offset = 0;
  479. }
  480. }
  481. if (rt->state == RTSP_STATE_PAUSED) {
  482. cmd[0] = 0;
  483. } else {
  484. snprintf(cmd, sizeof(cmd),
  485. "Range: npt=%"PRId64".%03"PRId64"-\r\n",
  486. rt->seek_timestamp / AV_TIME_BASE,
  487. rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
  488. }
  489. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  490. if (reply->status_code != RTSP_STATUS_OK) {
  491. return -1;
  492. }
  493. if (rt->transport == RTSP_TRANSPORT_RTP &&
  494. reply->range_start != AV_NOPTS_VALUE) {
  495. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  496. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  497. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  498. AVStream *st = NULL;
  499. if (!rtpctx || rtsp_st->stream_index < 0)
  500. continue;
  501. st = s->streams[rtsp_st->stream_index];
  502. rtpctx->range_start_offset =
  503. av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
  504. st->time_base);
  505. }
  506. }
  507. }
  508. rt->state = RTSP_STATE_STREAMING;
  509. return 0;
  510. }
  511. /* pause the stream */
  512. static int rtsp_read_pause(AVFormatContext *s)
  513. {
  514. RTSPState *rt = s->priv_data;
  515. RTSPMessageHeader reply1, *reply = &reply1;
  516. if (rt->state != RTSP_STATE_STREAMING)
  517. return 0;
  518. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  519. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  520. if (reply->status_code != RTSP_STATUS_OK) {
  521. return -1;
  522. }
  523. }
  524. rt->state = RTSP_STATE_PAUSED;
  525. return 0;
  526. }
  527. int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  528. {
  529. RTSPState *rt = s->priv_data;
  530. char cmd[1024];
  531. unsigned char *content = NULL;
  532. int ret;
  533. /* describe the stream */
  534. snprintf(cmd, sizeof(cmd),
  535. "Accept: application/sdp\r\n");
  536. if (rt->server_type == RTSP_SERVER_REAL) {
  537. /**
  538. * The Require: attribute is needed for proper streaming from
  539. * Realmedia servers.
  540. */
  541. av_strlcat(cmd,
  542. "Require: com.real.retain-entity-for-setup\r\n",
  543. sizeof(cmd));
  544. }
  545. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  546. if (!content)
  547. return AVERROR_INVALIDDATA;
  548. if (reply->status_code != RTSP_STATUS_OK) {
  549. av_freep(&content);
  550. return AVERROR_INVALIDDATA;
  551. }
  552. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
  553. /* now we got the SDP description, we parse it */
  554. ret = ff_sdp_parse(s, (const char *)content);
  555. av_freep(&content);
  556. if (ret < 0)
  557. return ret;
  558. return 0;
  559. }
  560. static int rtsp_listen(AVFormatContext *s)
  561. {
  562. RTSPState *rt = s->priv_data;
  563. char host[128], path[512], auth[128];
  564. char uri[500];
  565. int port;
  566. char tcpname[500];
  567. unsigned char rbuf[4096];
  568. unsigned char method[10];
  569. int rbuflen = 0;
  570. int ret;
  571. enum RTSPMethod methodcode;
  572. /* extract hostname and port */
  573. av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
  574. path, sizeof(path), s->filename);
  575. /* ff_url_join. No authorization by now (NULL) */
  576. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL, host,
  577. port, "%s", path);
  578. /* Create TCP connection */
  579. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port,
  580. "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
  581. if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
  582. &s->interrupt_callback, NULL)) {
  583. av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
  584. return ret;
  585. }
  586. rt->state = RTSP_STATE_IDLE;
  587. rt->rtsp_hd_out = rt->rtsp_hd;
  588. for (;;) { /* Wait for incoming RTSP messages */
  589. ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
  590. if (ret < 0)
  591. return ret;
  592. ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
  593. sizeof(method), &methodcode);
  594. if (ret) {
  595. av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
  596. return ret;
  597. }
  598. if (methodcode == ANNOUNCE) {
  599. ret = rtsp_read_announce(s);
  600. rt->state = RTSP_STATE_PAUSED;
  601. } else if (methodcode == OPTIONS) {
  602. ret = rtsp_read_options(s);
  603. } else if (methodcode == RECORD) {
  604. ret = rtsp_read_record(s);
  605. if (!ret)
  606. return 0; // We are ready for streaming
  607. } else if (methodcode == SETUP)
  608. ret = rtsp_read_setup(s, host, uri);
  609. if (ret) {
  610. ffurl_close(rt->rtsp_hd);
  611. return AVERROR_INVALIDDATA;
  612. }
  613. }
  614. return 0;
  615. }
  616. static int rtsp_probe(AVProbeData *p)
  617. {
  618. if (av_strstart(p->filename, "rtsp:", NULL))
  619. return AVPROBE_SCORE_MAX;
  620. return 0;
  621. }
  622. static int rtsp_read_header(AVFormatContext *s)
  623. {
  624. RTSPState *rt = s->priv_data;
  625. int ret;
  626. if (rt->initial_timeout > 0)
  627. rt->rtsp_flags |= RTSP_FLAG_LISTEN;
  628. if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
  629. ret = rtsp_listen(s);
  630. if (ret)
  631. return ret;
  632. } else {
  633. ret = ff_rtsp_connect(s);
  634. if (ret)
  635. return ret;
  636. rt->real_setup_cache = !s->nb_streams ? NULL :
  637. av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
  638. if (!rt->real_setup_cache && s->nb_streams)
  639. return AVERROR(ENOMEM);
  640. rt->real_setup = rt->real_setup_cache + s->nb_streams;
  641. if (rt->initial_pause) {
  642. /* do not start immediately */
  643. } else {
  644. if (rtsp_read_play(s) < 0) {
  645. ff_rtsp_close_streams(s);
  646. ff_rtsp_close_connections(s);
  647. return AVERROR_INVALIDDATA;
  648. }
  649. }
  650. }
  651. return 0;
  652. }
  653. int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  654. uint8_t *buf, int buf_size)
  655. {
  656. RTSPState *rt = s->priv_data;
  657. int id, len, i, ret;
  658. RTSPStream *rtsp_st;
  659. av_dlog(s, "tcp_read_packet:\n");
  660. redo:
  661. for (;;) {
  662. RTSPMessageHeader reply;
  663. ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
  664. if (ret < 0)
  665. return ret;
  666. if (ret == 1) /* received '$' */
  667. break;
  668. /* XXX: parse message */
  669. if (rt->state != RTSP_STATE_STREAMING)
  670. return 0;
  671. }
  672. ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
  673. if (ret != 3)
  674. return -1;
  675. id = buf[0];
  676. len = AV_RB16(buf + 1);
  677. av_dlog(s, "id=%d len=%d\n", id, len);
  678. if (len > buf_size || len < 8)
  679. goto redo;
  680. /* get the data */
  681. ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
  682. if (ret != len)
  683. return -1;
  684. if (rt->transport == RTSP_TRANSPORT_RDT &&
  685. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  686. return -1;
  687. /* find the matching stream */
  688. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  689. rtsp_st = rt->rtsp_streams[i];
  690. if (id >= rtsp_st->interleaved_min &&
  691. id <= rtsp_st->interleaved_max)
  692. goto found;
  693. }
  694. goto redo;
  695. found:
  696. *prtsp_st = rtsp_st;
  697. return len;
  698. }
  699. static int resetup_tcp(AVFormatContext *s)
  700. {
  701. RTSPState *rt = s->priv_data;
  702. char host[1024];
  703. int port;
  704. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
  705. s->filename);
  706. ff_rtsp_undo_setup(s);
  707. return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
  708. rt->real_challenge);
  709. }
  710. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  711. {
  712. RTSPState *rt = s->priv_data;
  713. int ret;
  714. RTSPMessageHeader reply1, *reply = &reply1;
  715. char cmd[1024];
  716. retry:
  717. if (rt->server_type == RTSP_SERVER_REAL) {
  718. int i;
  719. for (i = 0; i < s->nb_streams; i++)
  720. rt->real_setup[i] = s->streams[i]->discard;
  721. if (!rt->need_subscription) {
  722. if (memcmp (rt->real_setup, rt->real_setup_cache,
  723. sizeof(enum AVDiscard) * s->nb_streams)) {
  724. snprintf(cmd, sizeof(cmd),
  725. "Unsubscribe: %s\r\n",
  726. rt->last_subscription);
  727. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  728. cmd, reply, NULL);
  729. if (reply->status_code != RTSP_STATUS_OK)
  730. return AVERROR_INVALIDDATA;
  731. rt->need_subscription = 1;
  732. }
  733. }
  734. if (rt->need_subscription) {
  735. int r, rule_nr, first = 1;
  736. memcpy(rt->real_setup_cache, rt->real_setup,
  737. sizeof(enum AVDiscard) * s->nb_streams);
  738. rt->last_subscription[0] = 0;
  739. snprintf(cmd, sizeof(cmd),
  740. "Subscribe: ");
  741. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  742. rule_nr = 0;
  743. for (r = 0; r < s->nb_streams; r++) {
  744. if (s->streams[r]->id == i) {
  745. if (s->streams[r]->discard != AVDISCARD_ALL) {
  746. if (!first)
  747. av_strlcat(rt->last_subscription, ",",
  748. sizeof(rt->last_subscription));
  749. ff_rdt_subscribe_rule(
  750. rt->last_subscription,
  751. sizeof(rt->last_subscription), i, rule_nr);
  752. first = 0;
  753. }
  754. rule_nr++;
  755. }
  756. }
  757. }
  758. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  759. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  760. cmd, reply, NULL);
  761. if (reply->status_code != RTSP_STATUS_OK)
  762. return AVERROR_INVALIDDATA;
  763. rt->need_subscription = 0;
  764. if (rt->state == RTSP_STATE_STREAMING)
  765. rtsp_read_play (s);
  766. }
  767. }
  768. ret = ff_rtsp_fetch_packet(s, pkt);
  769. if (ret < 0) {
  770. if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
  771. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  772. rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
  773. RTSPMessageHeader reply1, *reply = &reply1;
  774. av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
  775. if (rtsp_read_pause(s) != 0)
  776. return -1;
  777. // TEARDOWN is required on Real-RTSP, but might make
  778. // other servers close the connection.
  779. if (rt->server_type == RTSP_SERVER_REAL)
  780. ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
  781. reply, NULL);
  782. rt->session_id[0] = '\0';
  783. if (resetup_tcp(s) == 0) {
  784. rt->state = RTSP_STATE_IDLE;
  785. rt->need_subscription = 1;
  786. if (rtsp_read_play(s) != 0)
  787. return -1;
  788. goto retry;
  789. }
  790. }
  791. }
  792. return ret;
  793. }
  794. rt->packets++;
  795. if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
  796. /* send dummy request to keep TCP connection alive */
  797. if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
  798. rt->auth_state.stale) {
  799. if (rt->server_type == RTSP_SERVER_WMS ||
  800. (rt->server_type != RTSP_SERVER_REAL &&
  801. rt->get_parameter_supported)) {
  802. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  803. } else {
  804. ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
  805. }
  806. /* The stale flag should be reset when creating the auth response in
  807. * ff_rtsp_send_cmd_async, but reset it here just in case we never
  808. * called the auth code (if we didn't have any credentials set). */
  809. rt->auth_state.stale = 0;
  810. }
  811. }
  812. return 0;
  813. }
  814. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  815. int64_t timestamp, int flags)
  816. {
  817. RTSPState *rt = s->priv_data;
  818. rt->seek_timestamp = av_rescale_q(timestamp,
  819. s->streams[stream_index]->time_base,
  820. AV_TIME_BASE_Q);
  821. switch(rt->state) {
  822. default:
  823. case RTSP_STATE_IDLE:
  824. break;
  825. case RTSP_STATE_STREAMING:
  826. if (rtsp_read_pause(s) != 0)
  827. return -1;
  828. rt->state = RTSP_STATE_SEEKING;
  829. if (rtsp_read_play(s) != 0)
  830. return -1;
  831. break;
  832. case RTSP_STATE_PAUSED:
  833. rt->state = RTSP_STATE_IDLE;
  834. break;
  835. }
  836. return 0;
  837. }
  838. static const AVClass rtsp_demuxer_class = {
  839. .class_name = "RTSP demuxer",
  840. .item_name = av_default_item_name,
  841. .option = ff_rtsp_options,
  842. .version = LIBAVUTIL_VERSION_INT,
  843. };
  844. AVInputFormat ff_rtsp_demuxer = {
  845. .name = "rtsp",
  846. .long_name = NULL_IF_CONFIG_SMALL("RTSP input"),
  847. .priv_data_size = sizeof(RTSPState),
  848. .read_probe = rtsp_probe,
  849. .read_header = rtsp_read_header,
  850. .read_packet = rtsp_read_packet,
  851. .read_close = rtsp_read_close,
  852. .read_seek = rtsp_read_seek,
  853. .flags = AVFMT_NOFILE,
  854. .read_play = rtsp_read_play,
  855. .read_pause = rtsp_read_pause,
  856. .priv_class = &rtsp_demuxer_class,
  857. };