rtsp.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  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. #include "libavutil/base64.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/random_seed.h"
  25. #include "avformat.h"
  26. #include <sys/time.h>
  27. #if HAVE_SYS_SELECT_H
  28. #include <sys/select.h>
  29. #endif
  30. #include <strings.h>
  31. #include "internal.h"
  32. #include "network.h"
  33. #include "os_support.h"
  34. #include "http.h"
  35. #include "rtsp.h"
  36. #include "rtpdec.h"
  37. #include "rdt.h"
  38. #include "rtpdec_asf.h"
  39. //#define DEBUG
  40. //#define DEBUG_RTP_TCP
  41. #if LIBAVFORMAT_VERSION_INT < (53 << 16)
  42. int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
  43. #endif
  44. /* Timeout values for socket select, in ms,
  45. * and read_packet(), in seconds */
  46. #define SELECT_TIMEOUT_MS 100
  47. #define READ_PACKET_TIMEOUT_S 10
  48. #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
  49. static void get_word_until_chars(char *buf, int buf_size,
  50. const char *sep, const char **pp)
  51. {
  52. const char *p;
  53. char *q;
  54. p = *pp;
  55. p += strspn(p, SPACE_CHARS);
  56. q = buf;
  57. while (!strchr(sep, *p) && *p != '\0') {
  58. if ((q - buf) < buf_size - 1)
  59. *q++ = *p;
  60. p++;
  61. }
  62. if (buf_size > 0)
  63. *q = '\0';
  64. *pp = p;
  65. }
  66. static void get_word_sep(char *buf, int buf_size, const char *sep,
  67. const char **pp)
  68. {
  69. if (**pp == '/') (*pp)++;
  70. get_word_until_chars(buf, buf_size, sep, pp);
  71. }
  72. static void get_word(char *buf, int buf_size, const char **pp)
  73. {
  74. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  75. }
  76. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  77. static int sdp_parse_rtpmap(AVFormatContext *s,
  78. AVCodecContext *codec, RTSPStream *rtsp_st,
  79. int payload_type, const char *p)
  80. {
  81. char buf[256];
  82. int i;
  83. AVCodec *c;
  84. const char *c_name;
  85. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  86. * see if we can handle this kind of payload.
  87. * The space should normally not be there but some Real streams or
  88. * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
  89. * have a trailing space. */
  90. get_word_sep(buf, sizeof(buf), "/ ", &p);
  91. if (payload_type >= RTP_PT_PRIVATE) {
  92. RTPDynamicProtocolHandler *handler;
  93. for (handler = RTPFirstDynamicPayloadHandler;
  94. handler; handler = handler->next) {
  95. if (!strcasecmp(buf, handler->enc_name) &&
  96. codec->codec_type == handler->codec_type) {
  97. codec->codec_id = handler->codec_id;
  98. rtsp_st->dynamic_handler = handler;
  99. if (handler->open)
  100. rtsp_st->dynamic_protocol_context = handler->open();
  101. break;
  102. }
  103. }
  104. } else {
  105. /* We are in a standard case
  106. * (from http://www.iana.org/assignments/rtp-parameters). */
  107. /* search into AVRtpPayloadTypes[] */
  108. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  109. }
  110. c = avcodec_find_decoder(codec->codec_id);
  111. if (c && c->name)
  112. c_name = c->name;
  113. else
  114. c_name = "(null)";
  115. get_word_sep(buf, sizeof(buf), "/", &p);
  116. i = atoi(buf);
  117. switch (codec->codec_type) {
  118. case AVMEDIA_TYPE_AUDIO:
  119. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  120. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  121. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  122. if (i > 0) {
  123. codec->sample_rate = i;
  124. get_word_sep(buf, sizeof(buf), "/", &p);
  125. i = atoi(buf);
  126. if (i > 0)
  127. codec->channels = i;
  128. // TODO: there is a bug here; if it is a mono stream, and
  129. // less than 22000Hz, faad upconverts to stereo and twice
  130. // the frequency. No problem, but the sample rate is being
  131. // set here by the sdp line. Patch on its way. (rdm)
  132. }
  133. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  134. codec->sample_rate);
  135. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  136. codec->channels);
  137. break;
  138. case AVMEDIA_TYPE_VIDEO:
  139. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  140. break;
  141. default:
  142. break;
  143. }
  144. return 0;
  145. }
  146. /* parse the attribute line from the fmtp a line of an sdp response. This
  147. * is broken out as a function because it is used in rtp_h264.c, which is
  148. * forthcoming. */
  149. int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
  150. char *value, int value_size)
  151. {
  152. *p += strspn(*p, SPACE_CHARS);
  153. if (**p) {
  154. get_word_sep(attr, attr_size, "=", p);
  155. if (**p == '=')
  156. (*p)++;
  157. get_word_sep(value, value_size, ";", p);
  158. if (**p == ';')
  159. (*p)++;
  160. return 1;
  161. }
  162. return 0;
  163. }
  164. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  165. * and end time.
  166. * Used for seeking in the rtp stream.
  167. */
  168. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  169. {
  170. char buf[256];
  171. p += strspn(p, SPACE_CHARS);
  172. if (!av_stristart(p, "npt=", &p))
  173. return;
  174. *start = AV_NOPTS_VALUE;
  175. *end = AV_NOPTS_VALUE;
  176. get_word_sep(buf, sizeof(buf), "-", &p);
  177. *start = parse_date(buf, 1);
  178. if (*p == '-') {
  179. p++;
  180. get_word_sep(buf, sizeof(buf), "-", &p);
  181. *end = parse_date(buf, 1);
  182. }
  183. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  184. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  185. }
  186. typedef struct SDPParseState {
  187. /* SDP only */
  188. struct in_addr default_ip;
  189. int default_ttl;
  190. int skip_media; ///< set if an unknown m= line occurs
  191. } SDPParseState;
  192. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  193. int letter, const char *buf)
  194. {
  195. RTSPState *rt = s->priv_data;
  196. char buf1[64], st_type[64];
  197. const char *p;
  198. enum AVMediaType codec_type;
  199. int payload_type, i;
  200. AVStream *st;
  201. RTSPStream *rtsp_st;
  202. struct in_addr sdp_ip;
  203. int ttl;
  204. dprintf(s, "sdp: %c='%s'\n", letter, buf);
  205. p = buf;
  206. if (s1->skip_media && letter != 'm')
  207. return;
  208. switch (letter) {
  209. case 'c':
  210. get_word(buf1, sizeof(buf1), &p);
  211. if (strcmp(buf1, "IN") != 0)
  212. return;
  213. get_word(buf1, sizeof(buf1), &p);
  214. if (strcmp(buf1, "IP4") != 0)
  215. return;
  216. get_word_sep(buf1, sizeof(buf1), "/", &p);
  217. if (ff_inet_aton(buf1, &sdp_ip) == 0)
  218. return;
  219. ttl = 16;
  220. if (*p == '/') {
  221. p++;
  222. get_word_sep(buf1, sizeof(buf1), "/", &p);
  223. ttl = atoi(buf1);
  224. }
  225. if (s->nb_streams == 0) {
  226. s1->default_ip = sdp_ip;
  227. s1->default_ttl = ttl;
  228. } else {
  229. st = s->streams[s->nb_streams - 1];
  230. rtsp_st = st->priv_data;
  231. rtsp_st->sdp_ip = sdp_ip;
  232. rtsp_st->sdp_ttl = ttl;
  233. }
  234. break;
  235. case 's':
  236. av_metadata_set2(&s->metadata, "title", p, 0);
  237. break;
  238. case 'i':
  239. if (s->nb_streams == 0) {
  240. av_metadata_set2(&s->metadata, "comment", p, 0);
  241. break;
  242. }
  243. break;
  244. case 'm':
  245. /* new stream */
  246. s1->skip_media = 0;
  247. get_word(st_type, sizeof(st_type), &p);
  248. if (!strcmp(st_type, "audio")) {
  249. codec_type = AVMEDIA_TYPE_AUDIO;
  250. } else if (!strcmp(st_type, "video")) {
  251. codec_type = AVMEDIA_TYPE_VIDEO;
  252. } else if (!strcmp(st_type, "application")) {
  253. codec_type = AVMEDIA_TYPE_DATA;
  254. } else {
  255. s1->skip_media = 1;
  256. return;
  257. }
  258. rtsp_st = av_mallocz(sizeof(RTSPStream));
  259. if (!rtsp_st)
  260. return;
  261. rtsp_st->stream_index = -1;
  262. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  263. rtsp_st->sdp_ip = s1->default_ip;
  264. rtsp_st->sdp_ttl = s1->default_ttl;
  265. get_word(buf1, sizeof(buf1), &p); /* port */
  266. rtsp_st->sdp_port = atoi(buf1);
  267. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  268. /* XXX: handle list of formats */
  269. get_word(buf1, sizeof(buf1), &p); /* format list */
  270. rtsp_st->sdp_payload_type = atoi(buf1);
  271. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  272. /* no corresponding stream */
  273. } else {
  274. st = av_new_stream(s, 0);
  275. if (!st)
  276. return;
  277. st->priv_data = rtsp_st;
  278. rtsp_st->stream_index = st->index;
  279. st->codec->codec_type = codec_type;
  280. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  281. /* if standard payload type, we can find the codec right now */
  282. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  283. }
  284. }
  285. /* put a default control url */
  286. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  287. sizeof(rtsp_st->control_url));
  288. break;
  289. case 'a':
  290. if (av_strstart(p, "control:", &p)) {
  291. if (s->nb_streams == 0) {
  292. if (!strncmp(p, "rtsp://", 7))
  293. av_strlcpy(rt->control_uri, p,
  294. sizeof(rt->control_uri));
  295. } else {
  296. char proto[32];
  297. /* get the control url */
  298. st = s->streams[s->nb_streams - 1];
  299. rtsp_st = st->priv_data;
  300. /* XXX: may need to add full url resolution */
  301. av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  302. NULL, NULL, 0, p);
  303. if (proto[0] == '\0') {
  304. /* relative control URL */
  305. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  306. av_strlcat(rtsp_st->control_url, "/",
  307. sizeof(rtsp_st->control_url));
  308. av_strlcat(rtsp_st->control_url, p,
  309. sizeof(rtsp_st->control_url));
  310. } else
  311. av_strlcpy(rtsp_st->control_url, p,
  312. sizeof(rtsp_st->control_url));
  313. }
  314. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  315. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  316. get_word(buf1, sizeof(buf1), &p);
  317. payload_type = atoi(buf1);
  318. st = s->streams[s->nb_streams - 1];
  319. rtsp_st = st->priv_data;
  320. sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
  321. } else if (av_strstart(p, "fmtp:", &p) ||
  322. av_strstart(p, "framesize:", &p)) {
  323. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  324. // let dynamic protocol handlers have a stab at the line.
  325. get_word(buf1, sizeof(buf1), &p);
  326. payload_type = atoi(buf1);
  327. for (i = 0; i < s->nb_streams; i++) {
  328. st = s->streams[i];
  329. rtsp_st = st->priv_data;
  330. if (rtsp_st->sdp_payload_type == payload_type &&
  331. rtsp_st->dynamic_handler &&
  332. rtsp_st->dynamic_handler->parse_sdp_a_line)
  333. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  334. rtsp_st->dynamic_protocol_context, buf);
  335. }
  336. } else if (av_strstart(p, "range:", &p)) {
  337. int64_t start, end;
  338. // this is so that seeking on a streamed file can work.
  339. rtsp_parse_range_npt(p, &start, &end);
  340. s->start_time = start;
  341. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  342. s->duration = (end == AV_NOPTS_VALUE) ?
  343. AV_NOPTS_VALUE : end - start;
  344. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  345. if (atoi(p) == 1)
  346. rt->transport = RTSP_TRANSPORT_RDT;
  347. } else {
  348. if (rt->server_type == RTSP_SERVER_WMS)
  349. ff_wms_parse_sdp_a_line(s, p);
  350. if (s->nb_streams > 0) {
  351. if (rt->server_type == RTSP_SERVER_REAL)
  352. ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
  353. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  354. if (rtsp_st->dynamic_handler &&
  355. rtsp_st->dynamic_handler->parse_sdp_a_line)
  356. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  357. s->nb_streams - 1,
  358. rtsp_st->dynamic_protocol_context, buf);
  359. }
  360. }
  361. break;
  362. }
  363. }
  364. static int sdp_parse(AVFormatContext *s, const char *content)
  365. {
  366. const char *p;
  367. int letter;
  368. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  369. * contain long SDP lines containing complete ASF Headers (several
  370. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  371. * "rulebooks" describing their properties. Therefore, the SDP line
  372. * buffer is large.
  373. *
  374. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  375. * in rtpdec_xiph.c. */
  376. char buf[16384], *q;
  377. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  378. memset(s1, 0, sizeof(SDPParseState));
  379. p = content;
  380. for (;;) {
  381. p += strspn(p, SPACE_CHARS);
  382. letter = *p;
  383. if (letter == '\0')
  384. break;
  385. p++;
  386. if (*p != '=')
  387. goto next_line;
  388. p++;
  389. /* get the content */
  390. q = buf;
  391. while (*p != '\n' && *p != '\r' && *p != '\0') {
  392. if ((q - buf) < sizeof(buf) - 1)
  393. *q++ = *p;
  394. p++;
  395. }
  396. *q = '\0';
  397. sdp_parse_line(s, s1, letter, buf);
  398. next_line:
  399. while (*p != '\n' && *p != '\0')
  400. p++;
  401. if (*p == '\n')
  402. p++;
  403. }
  404. return 0;
  405. }
  406. /* close and free RTSP streams */
  407. void ff_rtsp_close_streams(AVFormatContext *s)
  408. {
  409. RTSPState *rt = s->priv_data;
  410. int i;
  411. RTSPStream *rtsp_st;
  412. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  413. rtsp_st = rt->rtsp_streams[i];
  414. if (rtsp_st) {
  415. if (rtsp_st->transport_priv) {
  416. if (s->oformat) {
  417. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  418. av_write_trailer(rtpctx);
  419. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  420. uint8_t *ptr;
  421. url_close_dyn_buf(rtpctx->pb, &ptr);
  422. av_free(ptr);
  423. } else {
  424. url_fclose(rtpctx->pb);
  425. }
  426. av_metadata_free(&rtpctx->streams[0]->metadata);
  427. av_metadata_free(&rtpctx->metadata);
  428. av_free(rtpctx->streams[0]);
  429. av_free(rtpctx);
  430. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  431. ff_rdt_parse_close(rtsp_st->transport_priv);
  432. else
  433. rtp_parse_close(rtsp_st->transport_priv);
  434. }
  435. if (rtsp_st->rtp_handle)
  436. url_close(rtsp_st->rtp_handle);
  437. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  438. rtsp_st->dynamic_handler->close(
  439. rtsp_st->dynamic_protocol_context);
  440. }
  441. }
  442. av_free(rt->rtsp_streams);
  443. if (rt->asf_ctx) {
  444. av_close_input_stream (rt->asf_ctx);
  445. rt->asf_ctx = NULL;
  446. }
  447. }
  448. static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st,
  449. URLContext *handle)
  450. {
  451. RTSPState *rt = s->priv_data;
  452. AVFormatContext *rtpctx;
  453. int ret;
  454. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  455. if (!rtp_format)
  456. return NULL;
  457. /* Allocate an AVFormatContext for each output stream */
  458. rtpctx = avformat_alloc_context();
  459. if (!rtpctx)
  460. return NULL;
  461. rtpctx->oformat = rtp_format;
  462. if (!av_new_stream(rtpctx, 0)) {
  463. av_free(rtpctx);
  464. return NULL;
  465. }
  466. /* Copy the max delay setting; the rtp muxer reads this. */
  467. rtpctx->max_delay = s->max_delay;
  468. /* Copy other stream parameters. */
  469. rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
  470. /* Set the synchronized start time. */
  471. rtpctx->start_time_realtime = rt->start_time;
  472. /* Remove the local codec, link to the original codec
  473. * context instead, to give the rtp muxer access to
  474. * codec parameters. */
  475. av_free(rtpctx->streams[0]->codec);
  476. rtpctx->streams[0]->codec = st->codec;
  477. if (handle) {
  478. url_fdopen(&rtpctx->pb, handle);
  479. } else
  480. url_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
  481. ret = av_write_header(rtpctx);
  482. if (ret) {
  483. if (handle) {
  484. url_fclose(rtpctx->pb);
  485. } else {
  486. uint8_t *ptr;
  487. url_close_dyn_buf(rtpctx->pb, &ptr);
  488. av_free(ptr);
  489. }
  490. av_free(rtpctx->streams[0]);
  491. av_free(rtpctx);
  492. return NULL;
  493. }
  494. /* Copy the RTP AVStream timebase back to the original AVStream */
  495. st->time_base = rtpctx->streams[0]->time_base;
  496. return rtpctx;
  497. }
  498. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  499. {
  500. RTSPState *rt = s->priv_data;
  501. AVStream *st = NULL;
  502. /* open the RTP context */
  503. if (rtsp_st->stream_index >= 0)
  504. st = s->streams[rtsp_st->stream_index];
  505. if (!st)
  506. s->ctx_flags |= AVFMTCTX_NOHEADER;
  507. if (s->oformat) {
  508. rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
  509. /* Ownership of rtp_handle is passed to the rtp mux context */
  510. rtsp_st->rtp_handle = NULL;
  511. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  512. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  513. rtsp_st->dynamic_protocol_context,
  514. rtsp_st->dynamic_handler);
  515. else
  516. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  517. rtsp_st->sdp_payload_type);
  518. if (!rtsp_st->transport_priv) {
  519. return AVERROR(ENOMEM);
  520. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  521. if (rtsp_st->dynamic_handler) {
  522. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  523. rtsp_st->dynamic_protocol_context,
  524. rtsp_st->dynamic_handler);
  525. }
  526. }
  527. return 0;
  528. }
  529. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  530. static int rtsp_probe(AVProbeData *p)
  531. {
  532. if (av_strstart(p->filename, "rtsp:", NULL))
  533. return AVPROBE_SCORE_MAX;
  534. return 0;
  535. }
  536. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  537. {
  538. const char *p;
  539. int v;
  540. p = *pp;
  541. p += strspn(p, SPACE_CHARS);
  542. v = strtol(p, (char **)&p, 10);
  543. if (*p == '-') {
  544. p++;
  545. *min_ptr = v;
  546. v = strtol(p, (char **)&p, 10);
  547. *max_ptr = v;
  548. } else {
  549. *min_ptr = v;
  550. *max_ptr = v;
  551. }
  552. *pp = p;
  553. }
  554. /* XXX: only one transport specification is parsed */
  555. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  556. {
  557. char transport_protocol[16];
  558. char profile[16];
  559. char lower_transport[16];
  560. char parameter[16];
  561. RTSPTransportField *th;
  562. char buf[256];
  563. reply->nb_transports = 0;
  564. for (;;) {
  565. p += strspn(p, SPACE_CHARS);
  566. if (*p == '\0')
  567. break;
  568. th = &reply->transports[reply->nb_transports];
  569. get_word_sep(transport_protocol, sizeof(transport_protocol),
  570. "/", &p);
  571. if (!strcasecmp (transport_protocol, "rtp")) {
  572. get_word_sep(profile, sizeof(profile), "/;,", &p);
  573. lower_transport[0] = '\0';
  574. /* rtp/avp/<protocol> */
  575. if (*p == '/') {
  576. get_word_sep(lower_transport, sizeof(lower_transport),
  577. ";,", &p);
  578. }
  579. th->transport = RTSP_TRANSPORT_RTP;
  580. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  581. !strcasecmp (transport_protocol, "x-real-rdt")) {
  582. /* x-pn-tng/<protocol> */
  583. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  584. profile[0] = '\0';
  585. th->transport = RTSP_TRANSPORT_RDT;
  586. }
  587. if (!strcasecmp(lower_transport, "TCP"))
  588. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  589. else
  590. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  591. if (*p == ';')
  592. p++;
  593. /* get each parameter */
  594. while (*p != '\0' && *p != ',') {
  595. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  596. if (!strcmp(parameter, "port")) {
  597. if (*p == '=') {
  598. p++;
  599. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  600. }
  601. } else if (!strcmp(parameter, "client_port")) {
  602. if (*p == '=') {
  603. p++;
  604. rtsp_parse_range(&th->client_port_min,
  605. &th->client_port_max, &p);
  606. }
  607. } else if (!strcmp(parameter, "server_port")) {
  608. if (*p == '=') {
  609. p++;
  610. rtsp_parse_range(&th->server_port_min,
  611. &th->server_port_max, &p);
  612. }
  613. } else if (!strcmp(parameter, "interleaved")) {
  614. if (*p == '=') {
  615. p++;
  616. rtsp_parse_range(&th->interleaved_min,
  617. &th->interleaved_max, &p);
  618. }
  619. } else if (!strcmp(parameter, "multicast")) {
  620. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  621. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  622. } else if (!strcmp(parameter, "ttl")) {
  623. if (*p == '=') {
  624. p++;
  625. th->ttl = strtol(p, (char **)&p, 10);
  626. }
  627. } else if (!strcmp(parameter, "destination")) {
  628. struct in_addr ipaddr;
  629. if (*p == '=') {
  630. p++;
  631. get_word_sep(buf, sizeof(buf), ";,", &p);
  632. if (ff_inet_aton(buf, &ipaddr))
  633. th->destination = ntohl(ipaddr.s_addr);
  634. }
  635. }
  636. while (*p != ';' && *p != '\0' && *p != ',')
  637. p++;
  638. if (*p == ';')
  639. p++;
  640. }
  641. if (*p == ',')
  642. p++;
  643. reply->nb_transports++;
  644. }
  645. }
  646. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  647. HTTPAuthState *auth_state)
  648. {
  649. const char *p;
  650. /* NOTE: we do case independent match for broken servers */
  651. p = buf;
  652. if (av_stristart(p, "Session:", &p)) {
  653. int t;
  654. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  655. if (av_stristart(p, ";timeout=", &p) &&
  656. (t = strtol(p, NULL, 10)) > 0) {
  657. reply->timeout = t;
  658. }
  659. } else if (av_stristart(p, "Content-Length:", &p)) {
  660. reply->content_length = strtol(p, NULL, 10);
  661. } else if (av_stristart(p, "Transport:", &p)) {
  662. rtsp_parse_transport(reply, p);
  663. } else if (av_stristart(p, "CSeq:", &p)) {
  664. reply->seq = strtol(p, NULL, 10);
  665. } else if (av_stristart(p, "Range:", &p)) {
  666. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  667. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  668. p += strspn(p, SPACE_CHARS);
  669. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  670. } else if (av_stristart(p, "Server:", &p)) {
  671. p += strspn(p, SPACE_CHARS);
  672. av_strlcpy(reply->server, p, sizeof(reply->server));
  673. } else if (av_stristart(p, "Notice:", &p) ||
  674. av_stristart(p, "X-Notice:", &p)) {
  675. reply->notice = strtol(p, NULL, 10);
  676. } else if (av_stristart(p, "Location:", &p)) {
  677. p += strspn(p, SPACE_CHARS);
  678. av_strlcpy(reply->location, p , sizeof(reply->location));
  679. } else if (av_stristart(p, "WWW-Authenticate:", &p) && auth_state) {
  680. p += strspn(p, SPACE_CHARS);
  681. ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
  682. } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
  683. p += strspn(p, SPACE_CHARS);
  684. ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
  685. }
  686. }
  687. /* skip a RTP/TCP interleaved packet */
  688. void ff_rtsp_skip_packet(AVFormatContext *s)
  689. {
  690. RTSPState *rt = s->priv_data;
  691. int ret, len, len1;
  692. uint8_t buf[1024];
  693. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  694. if (ret != 3)
  695. return;
  696. len = AV_RB16(buf + 1);
  697. dprintf(s, "skipping RTP packet len=%d\n", len);
  698. /* skip payload */
  699. while (len > 0) {
  700. len1 = len;
  701. if (len1 > sizeof(buf))
  702. len1 = sizeof(buf);
  703. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  704. if (ret != len1)
  705. return;
  706. len -= len1;
  707. }
  708. }
  709. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  710. unsigned char **content_ptr,
  711. int return_on_interleaved_data)
  712. {
  713. RTSPState *rt = s->priv_data;
  714. char buf[4096], buf1[1024], *q;
  715. unsigned char ch;
  716. const char *p;
  717. int ret, content_length, line_count = 0;
  718. unsigned char *content = NULL;
  719. memset(reply, 0, sizeof(*reply));
  720. /* parse reply (XXX: use buffers) */
  721. rt->last_reply[0] = '\0';
  722. for (;;) {
  723. q = buf;
  724. for (;;) {
  725. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  726. #ifdef DEBUG_RTP_TCP
  727. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  728. #endif
  729. if (ret != 1)
  730. return -1;
  731. if (ch == '\n')
  732. break;
  733. if (ch == '$') {
  734. /* XXX: only parse it if first char on line ? */
  735. if (return_on_interleaved_data) {
  736. return 1;
  737. } else
  738. ff_rtsp_skip_packet(s);
  739. } else if (ch != '\r') {
  740. if ((q - buf) < sizeof(buf) - 1)
  741. *q++ = ch;
  742. }
  743. }
  744. *q = '\0';
  745. dprintf(s, "line='%s'\n", buf);
  746. /* test if last line */
  747. if (buf[0] == '\0')
  748. break;
  749. p = buf;
  750. if (line_count == 0) {
  751. /* get reply code */
  752. get_word(buf1, sizeof(buf1), &p);
  753. get_word(buf1, sizeof(buf1), &p);
  754. reply->status_code = atoi(buf1);
  755. } else {
  756. ff_rtsp_parse_line(reply, p, &rt->auth_state);
  757. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  758. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  759. }
  760. line_count++;
  761. }
  762. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  763. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  764. content_length = reply->content_length;
  765. if (content_length > 0) {
  766. /* leave some room for a trailing '\0' (useful for simple parsing) */
  767. content = av_malloc(content_length + 1);
  768. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  769. content[content_length] = '\0';
  770. }
  771. if (content_ptr)
  772. *content_ptr = content;
  773. else
  774. av_free(content);
  775. if (rt->seq != reply->seq) {
  776. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  777. rt->seq, reply->seq);
  778. }
  779. /* EOS */
  780. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  781. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  782. reply->notice == 2306 /* Continuous Feed Terminated */) {
  783. rt->state = RTSP_STATE_IDLE;
  784. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  785. return AVERROR(EIO); /* data or server error */
  786. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  787. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  788. return AVERROR(EPERM);
  789. return 0;
  790. }
  791. int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  792. const char *method, const char *url,
  793. const char *headers,
  794. const unsigned char *send_content,
  795. int send_content_length)
  796. {
  797. RTSPState *rt = s->priv_data;
  798. char buf[4096], *out_buf;
  799. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  800. /* Add in RTSP headers */
  801. out_buf = buf;
  802. rt->seq++;
  803. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  804. if (headers)
  805. av_strlcat(buf, headers, sizeof(buf));
  806. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  807. if (rt->session_id[0] != '\0' && (!headers ||
  808. !strstr(headers, "\nIf-Match:"))) {
  809. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  810. }
  811. if (rt->auth[0]) {
  812. char *str = ff_http_auth_create_response(&rt->auth_state,
  813. rt->auth, url, method);
  814. if (str)
  815. av_strlcat(buf, str, sizeof(buf));
  816. av_free(str);
  817. }
  818. if (send_content_length > 0 && send_content)
  819. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  820. av_strlcat(buf, "\r\n", sizeof(buf));
  821. /* base64 encode rtsp if tunneling */
  822. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  823. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  824. out_buf = base64buf;
  825. }
  826. dprintf(s, "Sending:\n%s--\n", buf);
  827. url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  828. if (send_content_length > 0 && send_content) {
  829. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  830. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  831. "with content data not supported\n");
  832. return AVERROR_PATCHWELCOME;
  833. }
  834. url_write(rt->rtsp_hd_out, send_content, send_content_length);
  835. }
  836. rt->last_cmd_time = av_gettime();
  837. return 0;
  838. }
  839. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  840. const char *url, const char *headers)
  841. {
  842. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  843. }
  844. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  845. const char *headers, RTSPMessageHeader *reply,
  846. unsigned char **content_ptr)
  847. {
  848. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  849. content_ptr, NULL, 0);
  850. }
  851. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  852. const char *method, const char *url,
  853. const char *header,
  854. RTSPMessageHeader *reply,
  855. unsigned char **content_ptr,
  856. const unsigned char *send_content,
  857. int send_content_length)
  858. {
  859. RTSPState *rt = s->priv_data;
  860. HTTPAuthType cur_auth_type;
  861. int ret;
  862. retry:
  863. cur_auth_type = rt->auth_state.auth_type;
  864. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  865. send_content,
  866. send_content_length)))
  867. return ret;
  868. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
  869. return ret;
  870. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  871. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  872. goto retry;
  873. if (reply->status_code > 400){
  874. av_log(s, AV_LOG_ERROR, "method %s failed, %d\n",
  875. method,
  876. reply->status_code);
  877. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  878. }
  879. return 0;
  880. }
  881. /**
  882. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  883. */
  884. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  885. int lower_transport, const char *real_challenge)
  886. {
  887. RTSPState *rt = s->priv_data;
  888. int rtx, j, i, err, interleave = 0;
  889. RTSPStream *rtsp_st;
  890. RTSPMessageHeader reply1, *reply = &reply1;
  891. char cmd[2048];
  892. const char *trans_pref;
  893. if (rt->transport == RTSP_TRANSPORT_RDT)
  894. trans_pref = "x-pn-tng";
  895. else
  896. trans_pref = "RTP/AVP";
  897. /* default timeout: 1 minute */
  898. rt->timeout = 60;
  899. /* for each stream, make the setup request */
  900. /* XXX: we assume the same server is used for the control of each
  901. * RTSP stream */
  902. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  903. char transport[2048];
  904. /**
  905. * WMS serves all UDP data over a single connection, the RTX, which
  906. * isn't necessarily the first in the SDP but has to be the first
  907. * to be set up, else the second/third SETUP will fail with a 461.
  908. */
  909. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  910. rt->server_type == RTSP_SERVER_WMS) {
  911. if (i == 0) {
  912. /* rtx first */
  913. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  914. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  915. if (len >= 4 &&
  916. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  917. "/rtx"))
  918. break;
  919. }
  920. if (rtx == rt->nb_rtsp_streams)
  921. return -1; /* no RTX found */
  922. rtsp_st = rt->rtsp_streams[rtx];
  923. } else
  924. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  925. } else
  926. rtsp_st = rt->rtsp_streams[i];
  927. /* RTP/UDP */
  928. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  929. char buf[256];
  930. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  931. port = reply->transports[0].client_port_min;
  932. goto have_port;
  933. }
  934. /* first try in specified port range */
  935. if (RTSP_RTP_PORT_MIN != 0) {
  936. while (j <= RTSP_RTP_PORT_MAX) {
  937. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  938. "?localport=%d", j);
  939. /* we will use two ports per rtp stream (rtp and rtcp) */
  940. j += 2;
  941. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  942. goto rtp_opened;
  943. }
  944. }
  945. #if 0
  946. /* then try on any port */
  947. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  948. err = AVERROR_INVALIDDATA;
  949. goto fail;
  950. }
  951. #endif
  952. rtp_opened:
  953. port = rtp_get_local_port(rtsp_st->rtp_handle);
  954. have_port:
  955. snprintf(transport, sizeof(transport) - 1,
  956. "%s/UDP;", trans_pref);
  957. if (rt->server_type != RTSP_SERVER_REAL)
  958. av_strlcat(transport, "unicast;", sizeof(transport));
  959. av_strlcatf(transport, sizeof(transport),
  960. "client_port=%d", port);
  961. if (rt->transport == RTSP_TRANSPORT_RTP &&
  962. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  963. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  964. }
  965. /* RTP/TCP */
  966. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  967. /** For WMS streams, the application streams are only used for
  968. * UDP. When trying to set it up for TCP streams, the server
  969. * will return an error. Therefore, we skip those streams. */
  970. if (rt->server_type == RTSP_SERVER_WMS &&
  971. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  972. AVMEDIA_TYPE_DATA)
  973. continue;
  974. snprintf(transport, sizeof(transport) - 1,
  975. "%s/TCP;", trans_pref);
  976. if (rt->server_type == RTSP_SERVER_WMS)
  977. av_strlcat(transport, "unicast;", sizeof(transport));
  978. av_strlcatf(transport, sizeof(transport),
  979. "interleaved=%d-%d",
  980. interleave, interleave + 1);
  981. interleave += 2;
  982. }
  983. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  984. snprintf(transport, sizeof(transport) - 1,
  985. "%s/UDP;multicast", trans_pref);
  986. }
  987. if (s->oformat) {
  988. av_strlcat(transport, ";mode=receive", sizeof(transport));
  989. } else if (rt->server_type == RTSP_SERVER_REAL ||
  990. rt->server_type == RTSP_SERVER_WMS)
  991. av_strlcat(transport, ";mode=play", sizeof(transport));
  992. snprintf(cmd, sizeof(cmd),
  993. "Transport: %s\r\n",
  994. transport);
  995. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  996. char real_res[41], real_csum[9];
  997. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  998. real_challenge);
  999. av_strlcatf(cmd, sizeof(cmd),
  1000. "If-Match: %s\r\n"
  1001. "RealChallenge2: %s, sd=%s\r\n",
  1002. rt->session_id, real_res, real_csum);
  1003. }
  1004. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1005. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1006. err = 1;
  1007. goto fail;
  1008. } else if (reply->status_code != RTSP_STATUS_OK ||
  1009. reply->nb_transports != 1) {
  1010. err = AVERROR_INVALIDDATA;
  1011. goto fail;
  1012. }
  1013. /* XXX: same protocol for all streams is required */
  1014. if (i > 0) {
  1015. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1016. reply->transports[0].transport != rt->transport) {
  1017. err = AVERROR_INVALIDDATA;
  1018. goto fail;
  1019. }
  1020. } else {
  1021. rt->lower_transport = reply->transports[0].lower_transport;
  1022. rt->transport = reply->transports[0].transport;
  1023. }
  1024. /* close RTP connection if not choosen */
  1025. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1026. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1027. url_close(rtsp_st->rtp_handle);
  1028. rtsp_st->rtp_handle = NULL;
  1029. }
  1030. switch(reply->transports[0].lower_transport) {
  1031. case RTSP_LOWER_TRANSPORT_TCP:
  1032. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1033. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1034. break;
  1035. case RTSP_LOWER_TRANSPORT_UDP: {
  1036. char url[1024];
  1037. /* XXX: also use address if specified */
  1038. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1039. reply->transports[0].server_port_min, NULL);
  1040. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1041. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1042. err = AVERROR_INVALIDDATA;
  1043. goto fail;
  1044. }
  1045. /* Try to initialize the connection state in a
  1046. * potential NAT router by sending dummy packets.
  1047. * RTP/RTCP dummy packets are used for RDT, too.
  1048. */
  1049. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1050. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1051. break;
  1052. }
  1053. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1054. char url[1024];
  1055. struct in_addr in;
  1056. int port, ttl;
  1057. if (reply->transports[0].destination) {
  1058. in.s_addr = htonl(reply->transports[0].destination);
  1059. port = reply->transports[0].port_min;
  1060. ttl = reply->transports[0].ttl;
  1061. } else {
  1062. in = rtsp_st->sdp_ip;
  1063. port = rtsp_st->sdp_port;
  1064. ttl = rtsp_st->sdp_ttl;
  1065. }
  1066. ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
  1067. port, "?ttl=%d", ttl);
  1068. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1069. err = AVERROR_INVALIDDATA;
  1070. goto fail;
  1071. }
  1072. break;
  1073. }
  1074. }
  1075. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1076. goto fail;
  1077. }
  1078. if (reply->timeout > 0)
  1079. rt->timeout = reply->timeout;
  1080. if (rt->server_type == RTSP_SERVER_REAL)
  1081. rt->need_subscription = 1;
  1082. return 0;
  1083. fail:
  1084. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1085. if (rt->rtsp_streams[i]->rtp_handle) {
  1086. url_close(rt->rtsp_streams[i]->rtp_handle);
  1087. rt->rtsp_streams[i]->rtp_handle = NULL;
  1088. }
  1089. }
  1090. return err;
  1091. }
  1092. static int rtsp_read_play(AVFormatContext *s)
  1093. {
  1094. RTSPState *rt = s->priv_data;
  1095. RTSPMessageHeader reply1, *reply = &reply1;
  1096. int i;
  1097. char cmd[1024];
  1098. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1099. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1100. if (rt->state == RTSP_STATE_PAUSED) {
  1101. cmd[0] = 0;
  1102. } else {
  1103. snprintf(cmd, sizeof(cmd),
  1104. "Range: npt=%0.3f-\r\n",
  1105. (double)rt->seek_timestamp / AV_TIME_BASE);
  1106. }
  1107. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  1108. if (reply->status_code != RTSP_STATUS_OK) {
  1109. return -1;
  1110. }
  1111. if (reply->range_start != AV_NOPTS_VALUE &&
  1112. rt->transport == RTSP_TRANSPORT_RTP) {
  1113. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1114. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  1115. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1116. AVStream *st = NULL;
  1117. if (!rtpctx)
  1118. continue;
  1119. if (rtsp_st->stream_index >= 0)
  1120. st = s->streams[rtsp_st->stream_index];
  1121. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  1122. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  1123. if (st)
  1124. rtpctx->range_start_offset = av_rescale_q(reply->range_start,
  1125. AV_TIME_BASE_Q,
  1126. st->time_base);
  1127. }
  1128. }
  1129. }
  1130. rt->state = RTSP_STATE_STREAMING;
  1131. return 0;
  1132. }
  1133. static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  1134. {
  1135. RTSPState *rt = s->priv_data;
  1136. char cmd[1024];
  1137. unsigned char *content = NULL;
  1138. int ret;
  1139. /* describe the stream */
  1140. snprintf(cmd, sizeof(cmd),
  1141. "Accept: application/sdp\r\n");
  1142. if (rt->server_type == RTSP_SERVER_REAL) {
  1143. /**
  1144. * The Require: attribute is needed for proper streaming from
  1145. * Realmedia servers.
  1146. */
  1147. av_strlcat(cmd,
  1148. "Require: com.real.retain-entity-for-setup\r\n",
  1149. sizeof(cmd));
  1150. }
  1151. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  1152. if (!content)
  1153. return AVERROR_INVALIDDATA;
  1154. if (reply->status_code != RTSP_STATUS_OK) {
  1155. av_freep(&content);
  1156. return AVERROR_INVALIDDATA;
  1157. }
  1158. /* now we got the SDP description, we parse it */
  1159. ret = sdp_parse(s, (const char *)content);
  1160. av_freep(&content);
  1161. if (ret < 0)
  1162. return AVERROR_INVALIDDATA;
  1163. return 0;
  1164. }
  1165. static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
  1166. {
  1167. RTSPState *rt = s->priv_data;
  1168. RTSPMessageHeader reply1, *reply = &reply1;
  1169. int i;
  1170. char *sdp;
  1171. AVFormatContext sdp_ctx, *ctx_array[1];
  1172. rt->start_time = av_gettime();
  1173. /* Announce the stream */
  1174. sdp = av_mallocz(8192);
  1175. if (sdp == NULL)
  1176. return AVERROR(ENOMEM);
  1177. /* We create the SDP based on the RTSP AVFormatContext where we
  1178. * aren't allowed to change the filename field. (We create the SDP
  1179. * based on the RTSP context since the contexts for the RTP streams
  1180. * don't exist yet.) In order to specify a custom URL with the actual
  1181. * peer IP instead of the originally specified hostname, we create
  1182. * a temporary copy of the AVFormatContext, where the custom URL is set.
  1183. *
  1184. * FIXME: Create the SDP without copying the AVFormatContext.
  1185. * This either requires setting up the RTP stream AVFormatContexts
  1186. * already here (complicating things immensely) or getting a more
  1187. * flexible SDP creation interface.
  1188. */
  1189. sdp_ctx = *s;
  1190. ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
  1191. "rtsp", NULL, addr, -1, NULL);
  1192. ctx_array[0] = &sdp_ctx;
  1193. if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
  1194. av_free(sdp);
  1195. return AVERROR_INVALIDDATA;
  1196. }
  1197. av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
  1198. ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
  1199. "Content-Type: application/sdp\r\n",
  1200. reply, NULL, sdp, strlen(sdp));
  1201. av_free(sdp);
  1202. if (reply->status_code != RTSP_STATUS_OK)
  1203. return AVERROR_INVALIDDATA;
  1204. /* Set up the RTSPStreams for each AVStream */
  1205. for (i = 0; i < s->nb_streams; i++) {
  1206. RTSPStream *rtsp_st;
  1207. AVStream *st = s->streams[i];
  1208. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1209. if (!rtsp_st)
  1210. return AVERROR(ENOMEM);
  1211. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1212. st->priv_data = rtsp_st;
  1213. rtsp_st->stream_index = i;
  1214. av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
  1215. /* Note, this must match the relative uri set in the sdp content */
  1216. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1217. "/streamid=%d", i);
  1218. }
  1219. return 0;
  1220. }
  1221. void ff_rtsp_close_connections(AVFormatContext *s)
  1222. {
  1223. RTSPState *rt = s->priv_data;
  1224. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1225. url_close(rt->rtsp_hd);
  1226. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1227. }
  1228. int ff_rtsp_connect(AVFormatContext *s)
  1229. {
  1230. RTSPState *rt = s->priv_data;
  1231. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1232. char *option_list, *option, *filename;
  1233. int port, err, tcp_fd;
  1234. RTSPMessageHeader reply1 = {}, *reply = &reply1;
  1235. int lower_transport_mask = 0;
  1236. char real_challenge[64];
  1237. struct sockaddr_storage peer;
  1238. socklen_t peer_len = sizeof(peer);
  1239. if (!ff_network_init())
  1240. return AVERROR(EIO);
  1241. redirect:
  1242. rt->control_transport = RTSP_MODE_PLAIN;
  1243. /* extract hostname and port */
  1244. av_url_split(NULL, 0, auth, sizeof(auth),
  1245. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1246. if (*auth) {
  1247. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1248. }
  1249. if (port < 0)
  1250. port = RTSP_DEFAULT_PORT;
  1251. /* search for options */
  1252. option_list = strrchr(path, '?');
  1253. if (option_list) {
  1254. /* Strip out the RTSP specific options, write out the rest of
  1255. * the options back into the same string. */
  1256. filename = option_list;
  1257. while (option_list) {
  1258. /* move the option pointer */
  1259. option = ++option_list;
  1260. option_list = strchr(option_list, '&');
  1261. if (option_list)
  1262. *option_list = 0;
  1263. /* handle the options */
  1264. if (!strcmp(option, "udp")) {
  1265. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1266. } else if (!strcmp(option, "multicast")) {
  1267. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1268. } else if (!strcmp(option, "tcp")) {
  1269. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1270. } else if(!strcmp(option, "http")) {
  1271. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1272. rt->control_transport = RTSP_MODE_TUNNEL;
  1273. } else {
  1274. /* Write options back into the buffer, using memmove instead
  1275. * of strcpy since the strings may overlap. */
  1276. int len = strlen(option);
  1277. memmove(++filename, option, len);
  1278. filename += len;
  1279. if (option_list) *filename = '&';
  1280. }
  1281. }
  1282. *filename = 0;
  1283. }
  1284. if (!lower_transport_mask)
  1285. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1286. if (s->oformat) {
  1287. /* Only UDP or TCP - UDP multicast isn't supported. */
  1288. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1289. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1290. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1291. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1292. "only UDP and TCP are supported for output.\n");
  1293. err = AVERROR(EINVAL);
  1294. goto fail;
  1295. }
  1296. }
  1297. /* Construct the URI used in request; this is similar to s->filename,
  1298. * but with authentication credentials removed and RTSP specific options
  1299. * stripped out. */
  1300. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1301. host, port, "%s", path);
  1302. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1303. /* set up initial handshake for tunneling */
  1304. char httpname[1024];
  1305. char sessioncookie[17];
  1306. char headers[1024];
  1307. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1308. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1309. av_get_random_seed(), av_get_random_seed());
  1310. /* GET requests */
  1311. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1312. err = AVERROR(EIO);
  1313. goto fail;
  1314. }
  1315. /* generate GET headers */
  1316. snprintf(headers, sizeof(headers),
  1317. "x-sessioncookie: %s\r\n"
  1318. "Accept: application/x-rtsp-tunnelled\r\n"
  1319. "Pragma: no-cache\r\n"
  1320. "Cache-Control: no-cache\r\n",
  1321. sessioncookie);
  1322. ff_http_set_headers(rt->rtsp_hd, headers);
  1323. /* complete the connection */
  1324. if (url_connect(rt->rtsp_hd)) {
  1325. err = AVERROR(EIO);
  1326. goto fail;
  1327. }
  1328. /* POST requests */
  1329. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1330. err = AVERROR(EIO);
  1331. goto fail;
  1332. }
  1333. /* generate POST headers */
  1334. snprintf(headers, sizeof(headers),
  1335. "x-sessioncookie: %s\r\n"
  1336. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1337. "Pragma: no-cache\r\n"
  1338. "Cache-Control: no-cache\r\n"
  1339. "Content-Length: 32767\r\n"
  1340. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1341. sessioncookie);
  1342. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1343. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1344. /* Initialize the authentication state for the POST session. The HTTP
  1345. * protocol implementation doesn't properly handle multi-pass
  1346. * authentication for POST requests, since it would require one of
  1347. * the following:
  1348. * - implementing Expect: 100-continue, which many HTTP servers
  1349. * don't support anyway, even less the RTSP servers that do HTTP
  1350. * tunneling
  1351. * - sending the whole POST data until getting a 401 reply specifying
  1352. * what authentication method to use, then resending all that data
  1353. * - waiting for potential 401 replies directly after sending the
  1354. * POST header (waiting for some unspecified time)
  1355. * Therefore, we copy the full auth state, which works for both basic
  1356. * and digest. (For digest, we would have to synchronize the nonce
  1357. * count variable between the two sessions, if we'd do more requests
  1358. * with the original session, though.)
  1359. */
  1360. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1361. /* complete the connection */
  1362. if (url_connect(rt->rtsp_hd_out)) {
  1363. err = AVERROR(EIO);
  1364. goto fail;
  1365. }
  1366. } else {
  1367. /* open the tcp connection */
  1368. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1369. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1370. err = AVERROR(EIO);
  1371. goto fail;
  1372. }
  1373. rt->rtsp_hd_out = rt->rtsp_hd;
  1374. }
  1375. rt->seq = 0;
  1376. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1377. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1378. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1379. NULL, 0, NI_NUMERICHOST);
  1380. }
  1381. /* request options supported by the server; this also detects server
  1382. * type */
  1383. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1384. cmd[0] = 0;
  1385. if (rt->server_type == RTSP_SERVER_REAL)
  1386. av_strlcat(cmd,
  1387. /**
  1388. * The following entries are required for proper
  1389. * streaming from a Realmedia server. They are
  1390. * interdependent in some way although we currently
  1391. * don't quite understand how. Values were copied
  1392. * from mplayer SVN r23589.
  1393. * @param CompanyID is a 16-byte ID in base64
  1394. * @param ClientChallenge is a 16-byte ID in hex
  1395. */
  1396. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1397. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1398. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1399. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1400. sizeof(cmd));
  1401. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1402. if (reply->status_code != RTSP_STATUS_OK) {
  1403. err = AVERROR_INVALIDDATA;
  1404. goto fail;
  1405. }
  1406. /* detect server type if not standard-compliant RTP */
  1407. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1408. rt->server_type = RTSP_SERVER_REAL;
  1409. continue;
  1410. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1411. rt->server_type = RTSP_SERVER_WMS;
  1412. } else if (rt->server_type == RTSP_SERVER_REAL)
  1413. strcpy(real_challenge, reply->real_challenge);
  1414. break;
  1415. }
  1416. if (s->iformat)
  1417. err = rtsp_setup_input_streams(s, reply);
  1418. else
  1419. err = rtsp_setup_output_streams(s, host);
  1420. if (err)
  1421. goto fail;
  1422. do {
  1423. int lower_transport = ff_log2_tab[lower_transport_mask &
  1424. ~(lower_transport_mask - 1)];
  1425. err = make_setup_request(s, host, port, lower_transport,
  1426. rt->server_type == RTSP_SERVER_REAL ?
  1427. real_challenge : NULL);
  1428. if (err < 0)
  1429. goto fail;
  1430. lower_transport_mask &= ~(1 << lower_transport);
  1431. if (lower_transport_mask == 0 && err == 1) {
  1432. err = FF_NETERROR(EPROTONOSUPPORT);
  1433. goto fail;
  1434. }
  1435. } while (err);
  1436. rt->state = RTSP_STATE_IDLE;
  1437. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1438. return 0;
  1439. fail:
  1440. ff_rtsp_close_streams(s);
  1441. ff_rtsp_close_connections(s);
  1442. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1443. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1444. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1445. reply->status_code,
  1446. s->filename);
  1447. goto redirect;
  1448. }
  1449. ff_network_close();
  1450. return err;
  1451. }
  1452. #endif
  1453. #if CONFIG_RTSP_DEMUXER
  1454. static int rtsp_read_header(AVFormatContext *s,
  1455. AVFormatParameters *ap)
  1456. {
  1457. int ret;
  1458. ret = ff_rtsp_connect(s);
  1459. if (ret)
  1460. return ret;
  1461. if (ap->initial_pause) {
  1462. /* do not start immediately */
  1463. } else {
  1464. if (rtsp_read_play(s) < 0) {
  1465. ff_rtsp_close_streams(s);
  1466. ff_rtsp_close_connections(s);
  1467. return AVERROR_INVALIDDATA;
  1468. }
  1469. }
  1470. return 0;
  1471. }
  1472. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1473. uint8_t *buf, int buf_size)
  1474. {
  1475. RTSPState *rt = s->priv_data;
  1476. RTSPStream *rtsp_st;
  1477. fd_set rfds;
  1478. int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1479. struct timeval tv;
  1480. for (;;) {
  1481. if (url_interrupt_cb())
  1482. return AVERROR(EINTR);
  1483. FD_ZERO(&rfds);
  1484. if (rt->rtsp_hd) {
  1485. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1486. FD_SET(tcp_fd, &rfds);
  1487. } else {
  1488. fd_max = 0;
  1489. tcp_fd = -1;
  1490. }
  1491. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1492. rtsp_st = rt->rtsp_streams[i];
  1493. if (rtsp_st->rtp_handle) {
  1494. /* currently, we cannot probe RTCP handle because of
  1495. * blocking restrictions */
  1496. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1497. if (fd > fd_max)
  1498. fd_max = fd;
  1499. FD_SET(fd, &rfds);
  1500. }
  1501. }
  1502. tv.tv_sec = 0;
  1503. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1504. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1505. if (n > 0) {
  1506. timeout_cnt = 0;
  1507. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1508. rtsp_st = rt->rtsp_streams[i];
  1509. if (rtsp_st->rtp_handle) {
  1510. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1511. if (FD_ISSET(fd, &rfds)) {
  1512. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1513. if (ret > 0) {
  1514. *prtsp_st = rtsp_st;
  1515. return ret;
  1516. }
  1517. }
  1518. }
  1519. }
  1520. #if CONFIG_RTSP_DEMUXER
  1521. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1522. RTSPMessageHeader reply;
  1523. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1524. if (ret < 0)
  1525. return ret;
  1526. /* XXX: parse message */
  1527. if (rt->state != RTSP_STATE_STREAMING)
  1528. return 0;
  1529. }
  1530. #endif
  1531. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1532. return FF_NETERROR(ETIMEDOUT);
  1533. } else if (n < 0 && errno != EINTR)
  1534. return AVERROR(errno);
  1535. }
  1536. }
  1537. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1538. uint8_t *buf, int buf_size)
  1539. {
  1540. RTSPState *rt = s->priv_data;
  1541. int id, len, i, ret;
  1542. RTSPStream *rtsp_st;
  1543. #ifdef DEBUG_RTP_TCP
  1544. dprintf(s, "tcp_read_packet:\n");
  1545. #endif
  1546. redo:
  1547. for (;;) {
  1548. RTSPMessageHeader reply;
  1549. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1550. if (ret == -1)
  1551. return -1;
  1552. if (ret == 1) /* received '$' */
  1553. break;
  1554. /* XXX: parse message */
  1555. if (rt->state != RTSP_STATE_STREAMING)
  1556. return 0;
  1557. }
  1558. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1559. if (ret != 3)
  1560. return -1;
  1561. id = buf[0];
  1562. len = AV_RB16(buf + 1);
  1563. #ifdef DEBUG_RTP_TCP
  1564. dprintf(s, "id=%d len=%d\n", id, len);
  1565. #endif
  1566. if (len > buf_size || len < 12)
  1567. goto redo;
  1568. /* get the data */
  1569. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1570. if (ret != len)
  1571. return -1;
  1572. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1573. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1574. return -1;
  1575. /* find the matching stream */
  1576. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1577. rtsp_st = rt->rtsp_streams[i];
  1578. if (id >= rtsp_st->interleaved_min &&
  1579. id <= rtsp_st->interleaved_max)
  1580. goto found;
  1581. }
  1582. goto redo;
  1583. found:
  1584. *prtsp_st = rtsp_st;
  1585. return len;
  1586. }
  1587. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1588. {
  1589. RTSPState *rt = s->priv_data;
  1590. int ret, len;
  1591. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1592. RTSPStream *rtsp_st;
  1593. /* get next frames from the same RTP packet */
  1594. if (rt->cur_transport_priv) {
  1595. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1596. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1597. } else
  1598. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1599. if (ret == 0) {
  1600. rt->cur_transport_priv = NULL;
  1601. return 0;
  1602. } else if (ret == 1) {
  1603. return 0;
  1604. } else
  1605. rt->cur_transport_priv = NULL;
  1606. }
  1607. /* read next RTP packet */
  1608. redo:
  1609. switch(rt->lower_transport) {
  1610. default:
  1611. #if CONFIG_RTSP_DEMUXER
  1612. case RTSP_LOWER_TRANSPORT_TCP:
  1613. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1614. break;
  1615. #endif
  1616. case RTSP_LOWER_TRANSPORT_UDP:
  1617. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1618. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1619. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1620. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1621. break;
  1622. }
  1623. if (len < 0)
  1624. return len;
  1625. if (len == 0)
  1626. return AVERROR_EOF;
  1627. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1628. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1629. } else {
  1630. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1631. if (ret < 0) {
  1632. /* Either bad packet, or a RTCP packet. Check if the
  1633. * first_rtcp_ntp_time field was initialized. */
  1634. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1635. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1636. /* first_rtcp_ntp_time has been initialized for this stream,
  1637. * copy the same value to all other uninitialized streams,
  1638. * in order to map their timestamp origin to the same ntp time
  1639. * as this one. */
  1640. int i;
  1641. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1642. RTPDemuxContext *rtpctx2 = rtsp_st->transport_priv;
  1643. if (rtpctx2 &&
  1644. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  1645. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1646. }
  1647. }
  1648. }
  1649. }
  1650. if (ret < 0)
  1651. goto redo;
  1652. if (ret == 1)
  1653. /* more packets may follow, so we save the RTP context */
  1654. rt->cur_transport_priv = rtsp_st->transport_priv;
  1655. return ret;
  1656. }
  1657. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1658. {
  1659. RTSPState *rt = s->priv_data;
  1660. int ret;
  1661. RTSPMessageHeader reply1, *reply = &reply1;
  1662. char cmd[1024];
  1663. if (rt->server_type == RTSP_SERVER_REAL) {
  1664. int i;
  1665. enum AVDiscard cache[MAX_STREAMS];
  1666. for (i = 0; i < s->nb_streams; i++)
  1667. cache[i] = s->streams[i]->discard;
  1668. if (!rt->need_subscription) {
  1669. if (memcmp (cache, rt->real_setup_cache,
  1670. sizeof(enum AVDiscard) * s->nb_streams)) {
  1671. snprintf(cmd, sizeof(cmd),
  1672. "Unsubscribe: %s\r\n",
  1673. rt->last_subscription);
  1674. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1675. cmd, reply, NULL);
  1676. if (reply->status_code != RTSP_STATUS_OK)
  1677. return AVERROR_INVALIDDATA;
  1678. rt->need_subscription = 1;
  1679. }
  1680. }
  1681. if (rt->need_subscription) {
  1682. int r, rule_nr, first = 1;
  1683. memcpy(rt->real_setup_cache, cache,
  1684. sizeof(enum AVDiscard) * s->nb_streams);
  1685. rt->last_subscription[0] = 0;
  1686. snprintf(cmd, sizeof(cmd),
  1687. "Subscribe: ");
  1688. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1689. rule_nr = 0;
  1690. for (r = 0; r < s->nb_streams; r++) {
  1691. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1692. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1693. if (!first)
  1694. av_strlcat(rt->last_subscription, ",",
  1695. sizeof(rt->last_subscription));
  1696. ff_rdt_subscribe_rule(
  1697. rt->last_subscription,
  1698. sizeof(rt->last_subscription), i, rule_nr);
  1699. first = 0;
  1700. }
  1701. rule_nr++;
  1702. }
  1703. }
  1704. }
  1705. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1706. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1707. cmd, reply, NULL);
  1708. if (reply->status_code != RTSP_STATUS_OK)
  1709. return AVERROR_INVALIDDATA;
  1710. rt->need_subscription = 0;
  1711. if (rt->state == RTSP_STATE_STREAMING)
  1712. rtsp_read_play (s);
  1713. }
  1714. }
  1715. ret = rtsp_fetch_packet(s, pkt);
  1716. if (ret < 0)
  1717. return ret;
  1718. /* send dummy request to keep TCP connection alive */
  1719. if ((rt->server_type == RTSP_SERVER_WMS ||
  1720. rt->server_type == RTSP_SERVER_REAL) &&
  1721. (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1722. if (rt->server_type == RTSP_SERVER_WMS) {
  1723. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  1724. } else {
  1725. ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
  1726. }
  1727. }
  1728. return 0;
  1729. }
  1730. /* pause the stream */
  1731. static int rtsp_read_pause(AVFormatContext *s)
  1732. {
  1733. RTSPState *rt = s->priv_data;
  1734. RTSPMessageHeader reply1, *reply = &reply1;
  1735. if (rt->state != RTSP_STATE_STREAMING)
  1736. return 0;
  1737. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1738. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  1739. if (reply->status_code != RTSP_STATUS_OK) {
  1740. return -1;
  1741. }
  1742. }
  1743. rt->state = RTSP_STATE_PAUSED;
  1744. return 0;
  1745. }
  1746. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1747. int64_t timestamp, int flags)
  1748. {
  1749. RTSPState *rt = s->priv_data;
  1750. rt->seek_timestamp = av_rescale_q(timestamp,
  1751. s->streams[stream_index]->time_base,
  1752. AV_TIME_BASE_Q);
  1753. switch(rt->state) {
  1754. default:
  1755. case RTSP_STATE_IDLE:
  1756. break;
  1757. case RTSP_STATE_STREAMING:
  1758. if (rtsp_read_pause(s) != 0)
  1759. return -1;
  1760. rt->state = RTSP_STATE_SEEKING;
  1761. if (rtsp_read_play(s) != 0)
  1762. return -1;
  1763. break;
  1764. case RTSP_STATE_PAUSED:
  1765. rt->state = RTSP_STATE_IDLE;
  1766. break;
  1767. }
  1768. return 0;
  1769. }
  1770. static int rtsp_read_close(AVFormatContext *s)
  1771. {
  1772. RTSPState *rt = s->priv_data;
  1773. #if 0
  1774. /* NOTE: it is valid to flush the buffer here */
  1775. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1776. url_fclose(&rt->rtsp_gb);
  1777. }
  1778. #endif
  1779. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  1780. ff_rtsp_close_streams(s);
  1781. ff_rtsp_close_connections(s);
  1782. ff_network_close();
  1783. return 0;
  1784. }
  1785. AVInputFormat rtsp_demuxer = {
  1786. "rtsp",
  1787. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1788. sizeof(RTSPState),
  1789. rtsp_probe,
  1790. rtsp_read_header,
  1791. rtsp_read_packet,
  1792. rtsp_read_close,
  1793. rtsp_read_seek,
  1794. .flags = AVFMT_NOFILE,
  1795. .read_play = rtsp_read_play,
  1796. .read_pause = rtsp_read_pause,
  1797. };
  1798. #endif
  1799. static int sdp_probe(AVProbeData *p1)
  1800. {
  1801. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1802. /* we look for a line beginning "c=IN IP4" */
  1803. while (p < p_end && *p != '\0') {
  1804. if (p + sizeof("c=IN IP4") - 1 < p_end &&
  1805. av_strstart(p, "c=IN IP4", NULL))
  1806. return AVPROBE_SCORE_MAX / 2;
  1807. while (p < p_end - 1 && *p != '\n') p++;
  1808. if (++p >= p_end)
  1809. break;
  1810. if (*p == '\r')
  1811. p++;
  1812. }
  1813. return 0;
  1814. }
  1815. #define SDP_MAX_SIZE 8192
  1816. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1817. {
  1818. RTSPState *rt = s->priv_data;
  1819. RTSPStream *rtsp_st;
  1820. int size, i, err;
  1821. char *content;
  1822. char url[1024];
  1823. if (!ff_network_init())
  1824. return AVERROR(EIO);
  1825. /* read the whole sdp file */
  1826. /* XXX: better loading */
  1827. content = av_malloc(SDP_MAX_SIZE);
  1828. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1829. if (size <= 0) {
  1830. av_free(content);
  1831. return AVERROR_INVALIDDATA;
  1832. }
  1833. content[size] ='\0';
  1834. sdp_parse(s, content);
  1835. av_free(content);
  1836. /* open each RTP stream */
  1837. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1838. rtsp_st = rt->rtsp_streams[i];
  1839. ff_url_join(url, sizeof(url), "rtp", NULL,
  1840. inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
  1841. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1842. rtsp_st->sdp_ttl);
  1843. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1844. err = AVERROR_INVALIDDATA;
  1845. goto fail;
  1846. }
  1847. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1848. goto fail;
  1849. }
  1850. return 0;
  1851. fail:
  1852. ff_rtsp_close_streams(s);
  1853. ff_network_close();
  1854. return err;
  1855. }
  1856. static int sdp_read_close(AVFormatContext *s)
  1857. {
  1858. ff_rtsp_close_streams(s);
  1859. ff_network_close();
  1860. return 0;
  1861. }
  1862. AVInputFormat sdp_demuxer = {
  1863. "sdp",
  1864. NULL_IF_CONFIG_SMALL("SDP"),
  1865. sizeof(RTSPState),
  1866. sdp_probe,
  1867. sdp_read_header,
  1868. rtsp_fetch_packet,
  1869. sdp_read_close,
  1870. };