rtsp.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  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. return 0;
  874. }
  875. /**
  876. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  877. */
  878. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  879. int lower_transport, const char *real_challenge)
  880. {
  881. RTSPState *rt = s->priv_data;
  882. int rtx, j, i, err, interleave = 0;
  883. RTSPStream *rtsp_st;
  884. RTSPMessageHeader reply1, *reply = &reply1;
  885. char cmd[2048];
  886. const char *trans_pref;
  887. if (rt->transport == RTSP_TRANSPORT_RDT)
  888. trans_pref = "x-pn-tng";
  889. else
  890. trans_pref = "RTP/AVP";
  891. /* default timeout: 1 minute */
  892. rt->timeout = 60;
  893. /* for each stream, make the setup request */
  894. /* XXX: we assume the same server is used for the control of each
  895. * RTSP stream */
  896. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  897. char transport[2048];
  898. /**
  899. * WMS serves all UDP data over a single connection, the RTX, which
  900. * isn't necessarily the first in the SDP but has to be the first
  901. * to be set up, else the second/third SETUP will fail with a 461.
  902. */
  903. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  904. rt->server_type == RTSP_SERVER_WMS) {
  905. if (i == 0) {
  906. /* rtx first */
  907. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  908. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  909. if (len >= 4 &&
  910. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  911. "/rtx"))
  912. break;
  913. }
  914. if (rtx == rt->nb_rtsp_streams)
  915. return -1; /* no RTX found */
  916. rtsp_st = rt->rtsp_streams[rtx];
  917. } else
  918. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  919. } else
  920. rtsp_st = rt->rtsp_streams[i];
  921. /* RTP/UDP */
  922. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  923. char buf[256];
  924. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  925. port = reply->transports[0].client_port_min;
  926. goto have_port;
  927. }
  928. /* first try in specified port range */
  929. if (RTSP_RTP_PORT_MIN != 0) {
  930. while (j <= RTSP_RTP_PORT_MAX) {
  931. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  932. "?localport=%d", j);
  933. /* we will use two ports per rtp stream (rtp and rtcp) */
  934. j += 2;
  935. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  936. goto rtp_opened;
  937. }
  938. }
  939. #if 0
  940. /* then try on any port */
  941. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  942. err = AVERROR_INVALIDDATA;
  943. goto fail;
  944. }
  945. #endif
  946. rtp_opened:
  947. port = rtp_get_local_port(rtsp_st->rtp_handle);
  948. have_port:
  949. snprintf(transport, sizeof(transport) - 1,
  950. "%s/UDP;", trans_pref);
  951. if (rt->server_type != RTSP_SERVER_REAL)
  952. av_strlcat(transport, "unicast;", sizeof(transport));
  953. av_strlcatf(transport, sizeof(transport),
  954. "client_port=%d", port);
  955. if (rt->transport == RTSP_TRANSPORT_RTP &&
  956. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  957. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  958. }
  959. /* RTP/TCP */
  960. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  961. /** For WMS streams, the application streams are only used for
  962. * UDP. When trying to set it up for TCP streams, the server
  963. * will return an error. Therefore, we skip those streams. */
  964. if (rt->server_type == RTSP_SERVER_WMS &&
  965. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  966. AVMEDIA_TYPE_DATA)
  967. continue;
  968. snprintf(transport, sizeof(transport) - 1,
  969. "%s/TCP;", trans_pref);
  970. if (rt->server_type == RTSP_SERVER_WMS)
  971. av_strlcat(transport, "unicast;", sizeof(transport));
  972. av_strlcatf(transport, sizeof(transport),
  973. "interleaved=%d-%d",
  974. interleave, interleave + 1);
  975. interleave += 2;
  976. }
  977. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  978. snprintf(transport, sizeof(transport) - 1,
  979. "%s/UDP;multicast", trans_pref);
  980. }
  981. if (s->oformat) {
  982. av_strlcat(transport, ";mode=receive", sizeof(transport));
  983. } else if (rt->server_type == RTSP_SERVER_REAL ||
  984. rt->server_type == RTSP_SERVER_WMS)
  985. av_strlcat(transport, ";mode=play", sizeof(transport));
  986. snprintf(cmd, sizeof(cmd),
  987. "Transport: %s\r\n",
  988. transport);
  989. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  990. char real_res[41], real_csum[9];
  991. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  992. real_challenge);
  993. av_strlcatf(cmd, sizeof(cmd),
  994. "If-Match: %s\r\n"
  995. "RealChallenge2: %s, sd=%s\r\n",
  996. rt->session_id, real_res, real_csum);
  997. }
  998. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  999. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1000. err = 1;
  1001. goto fail;
  1002. } else if (reply->status_code != RTSP_STATUS_OK ||
  1003. reply->nb_transports != 1) {
  1004. err = AVERROR_INVALIDDATA;
  1005. goto fail;
  1006. }
  1007. /* XXX: same protocol for all streams is required */
  1008. if (i > 0) {
  1009. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1010. reply->transports[0].transport != rt->transport) {
  1011. err = AVERROR_INVALIDDATA;
  1012. goto fail;
  1013. }
  1014. } else {
  1015. rt->lower_transport = reply->transports[0].lower_transport;
  1016. rt->transport = reply->transports[0].transport;
  1017. }
  1018. /* close RTP connection if not choosen */
  1019. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1020. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1021. url_close(rtsp_st->rtp_handle);
  1022. rtsp_st->rtp_handle = NULL;
  1023. }
  1024. switch(reply->transports[0].lower_transport) {
  1025. case RTSP_LOWER_TRANSPORT_TCP:
  1026. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1027. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1028. break;
  1029. case RTSP_LOWER_TRANSPORT_UDP: {
  1030. char url[1024];
  1031. /* XXX: also use address if specified */
  1032. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1033. reply->transports[0].server_port_min, NULL);
  1034. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1035. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1036. err = AVERROR_INVALIDDATA;
  1037. goto fail;
  1038. }
  1039. /* Try to initialize the connection state in a
  1040. * potential NAT router by sending dummy packets.
  1041. * RTP/RTCP dummy packets are used for RDT, too.
  1042. */
  1043. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1044. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1045. break;
  1046. }
  1047. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1048. char url[1024];
  1049. struct in_addr in;
  1050. int port, ttl;
  1051. if (reply->transports[0].destination) {
  1052. in.s_addr = htonl(reply->transports[0].destination);
  1053. port = reply->transports[0].port_min;
  1054. ttl = reply->transports[0].ttl;
  1055. } else {
  1056. in = rtsp_st->sdp_ip;
  1057. port = rtsp_st->sdp_port;
  1058. ttl = rtsp_st->sdp_ttl;
  1059. }
  1060. ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
  1061. port, "?ttl=%d", ttl);
  1062. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1063. err = AVERROR_INVALIDDATA;
  1064. goto fail;
  1065. }
  1066. break;
  1067. }
  1068. }
  1069. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1070. goto fail;
  1071. }
  1072. if (reply->timeout > 0)
  1073. rt->timeout = reply->timeout;
  1074. if (rt->server_type == RTSP_SERVER_REAL)
  1075. rt->need_subscription = 1;
  1076. return 0;
  1077. fail:
  1078. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1079. if (rt->rtsp_streams[i]->rtp_handle) {
  1080. url_close(rt->rtsp_streams[i]->rtp_handle);
  1081. rt->rtsp_streams[i]->rtp_handle = NULL;
  1082. }
  1083. }
  1084. return err;
  1085. }
  1086. static int rtsp_read_play(AVFormatContext *s)
  1087. {
  1088. RTSPState *rt = s->priv_data;
  1089. RTSPMessageHeader reply1, *reply = &reply1;
  1090. int i;
  1091. char cmd[1024];
  1092. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1093. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1094. if (rt->state == RTSP_STATE_PAUSED) {
  1095. cmd[0] = 0;
  1096. } else {
  1097. snprintf(cmd, sizeof(cmd),
  1098. "Range: npt=%0.3f-\r\n",
  1099. (double)rt->seek_timestamp / AV_TIME_BASE);
  1100. }
  1101. ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
  1102. if (reply->status_code != RTSP_STATUS_OK) {
  1103. return -1;
  1104. }
  1105. if (reply->range_start != AV_NOPTS_VALUE &&
  1106. rt->transport == RTSP_TRANSPORT_RTP) {
  1107. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1108. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  1109. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1110. AVStream *st = NULL;
  1111. if (!rtpctx)
  1112. continue;
  1113. if (rtsp_st->stream_index >= 0)
  1114. st = s->streams[rtsp_st->stream_index];
  1115. rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  1116. rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  1117. if (st)
  1118. rtpctx->range_start_offset = av_rescale_q(reply->range_start,
  1119. AV_TIME_BASE_Q,
  1120. st->time_base);
  1121. }
  1122. }
  1123. }
  1124. rt->state = RTSP_STATE_STREAMING;
  1125. return 0;
  1126. }
  1127. static int rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
  1128. {
  1129. RTSPState *rt = s->priv_data;
  1130. char cmd[1024];
  1131. unsigned char *content = NULL;
  1132. int ret;
  1133. /* describe the stream */
  1134. snprintf(cmd, sizeof(cmd),
  1135. "Accept: application/sdp\r\n");
  1136. if (rt->server_type == RTSP_SERVER_REAL) {
  1137. /**
  1138. * The Require: attribute is needed for proper streaming from
  1139. * Realmedia servers.
  1140. */
  1141. av_strlcat(cmd,
  1142. "Require: com.real.retain-entity-for-setup\r\n",
  1143. sizeof(cmd));
  1144. }
  1145. ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
  1146. if (!content)
  1147. return AVERROR_INVALIDDATA;
  1148. if (reply->status_code != RTSP_STATUS_OK) {
  1149. av_freep(&content);
  1150. return AVERROR_INVALIDDATA;
  1151. }
  1152. /* now we got the SDP description, we parse it */
  1153. ret = sdp_parse(s, (const char *)content);
  1154. av_freep(&content);
  1155. if (ret < 0)
  1156. return AVERROR_INVALIDDATA;
  1157. return 0;
  1158. }
  1159. static int rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
  1160. {
  1161. RTSPState *rt = s->priv_data;
  1162. RTSPMessageHeader reply1, *reply = &reply1;
  1163. int i;
  1164. char *sdp;
  1165. AVFormatContext sdp_ctx, *ctx_array[1];
  1166. rt->start_time = av_gettime();
  1167. /* Announce the stream */
  1168. sdp = av_mallocz(8192);
  1169. if (sdp == NULL)
  1170. return AVERROR(ENOMEM);
  1171. /* We create the SDP based on the RTSP AVFormatContext where we
  1172. * aren't allowed to change the filename field. (We create the SDP
  1173. * based on the RTSP context since the contexts for the RTP streams
  1174. * don't exist yet.) In order to specify a custom URL with the actual
  1175. * peer IP instead of the originally specified hostname, we create
  1176. * a temporary copy of the AVFormatContext, where the custom URL is set.
  1177. *
  1178. * FIXME: Create the SDP without copying the AVFormatContext.
  1179. * This either requires setting up the RTP stream AVFormatContexts
  1180. * already here (complicating things immensely) or getting a more
  1181. * flexible SDP creation interface.
  1182. */
  1183. sdp_ctx = *s;
  1184. ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
  1185. "rtsp", NULL, addr, -1, NULL);
  1186. ctx_array[0] = &sdp_ctx;
  1187. if (avf_sdp_create(ctx_array, 1, sdp, 8192)) {
  1188. av_free(sdp);
  1189. return AVERROR_INVALIDDATA;
  1190. }
  1191. av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
  1192. ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
  1193. "Content-Type: application/sdp\r\n",
  1194. reply, NULL, sdp, strlen(sdp));
  1195. av_free(sdp);
  1196. if (reply->status_code != RTSP_STATUS_OK)
  1197. return AVERROR_INVALIDDATA;
  1198. /* Set up the RTSPStreams for each AVStream */
  1199. for (i = 0; i < s->nb_streams; i++) {
  1200. RTSPStream *rtsp_st;
  1201. AVStream *st = s->streams[i];
  1202. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1203. if (!rtsp_st)
  1204. return AVERROR(ENOMEM);
  1205. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1206. st->priv_data = rtsp_st;
  1207. rtsp_st->stream_index = i;
  1208. av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
  1209. /* Note, this must match the relative uri set in the sdp content */
  1210. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1211. "/streamid=%d", i);
  1212. }
  1213. return 0;
  1214. }
  1215. void ff_rtsp_close_connections(AVFormatContext *s)
  1216. {
  1217. RTSPState *rt = s->priv_data;
  1218. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1219. url_close(rt->rtsp_hd);
  1220. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1221. }
  1222. int ff_rtsp_connect(AVFormatContext *s)
  1223. {
  1224. RTSPState *rt = s->priv_data;
  1225. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1226. char *option_list, *option, *filename;
  1227. int port, err, tcp_fd;
  1228. RTSPMessageHeader reply1 = {}, *reply = &reply1;
  1229. int lower_transport_mask = 0;
  1230. char real_challenge[64];
  1231. struct sockaddr_storage peer;
  1232. socklen_t peer_len = sizeof(peer);
  1233. if (!ff_network_init())
  1234. return AVERROR(EIO);
  1235. redirect:
  1236. rt->control_transport = RTSP_MODE_PLAIN;
  1237. /* extract hostname and port */
  1238. av_url_split(NULL, 0, auth, sizeof(auth),
  1239. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1240. if (*auth) {
  1241. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1242. }
  1243. if (port < 0)
  1244. port = RTSP_DEFAULT_PORT;
  1245. /* search for options */
  1246. option_list = strrchr(path, '?');
  1247. if (option_list) {
  1248. /* Strip out the RTSP specific options, write out the rest of
  1249. * the options back into the same string. */
  1250. filename = option_list;
  1251. while (option_list) {
  1252. /* move the option pointer */
  1253. option = ++option_list;
  1254. option_list = strchr(option_list, '&');
  1255. if (option_list)
  1256. *option_list = 0;
  1257. /* handle the options */
  1258. if (!strcmp(option, "udp")) {
  1259. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1260. } else if (!strcmp(option, "multicast")) {
  1261. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1262. } else if (!strcmp(option, "tcp")) {
  1263. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1264. } else if(!strcmp(option, "http")) {
  1265. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1266. rt->control_transport = RTSP_MODE_TUNNEL;
  1267. } else {
  1268. /* Write options back into the buffer, using memmove instead
  1269. * of strcpy since the strings may overlap. */
  1270. int len = strlen(option);
  1271. memmove(++filename, option, len);
  1272. filename += len;
  1273. if (option_list) *filename = '&';
  1274. }
  1275. }
  1276. *filename = 0;
  1277. }
  1278. if (!lower_transport_mask)
  1279. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1280. if (s->oformat) {
  1281. /* Only UDP or TCP - UDP multicast isn't supported. */
  1282. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1283. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1284. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1285. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1286. "only UDP and TCP are supported for output.\n");
  1287. err = AVERROR(EINVAL);
  1288. goto fail;
  1289. }
  1290. }
  1291. /* Construct the URI used in request; this is similar to s->filename,
  1292. * but with authentication credentials removed and RTSP specific options
  1293. * stripped out. */
  1294. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1295. host, port, "%s", path);
  1296. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1297. /* set up initial handshake for tunneling */
  1298. char httpname[1024];
  1299. char sessioncookie[17];
  1300. char headers[1024];
  1301. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1302. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1303. av_get_random_seed(), av_get_random_seed());
  1304. /* GET requests */
  1305. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1306. err = AVERROR(EIO);
  1307. goto fail;
  1308. }
  1309. /* generate GET headers */
  1310. snprintf(headers, sizeof(headers),
  1311. "x-sessioncookie: %s\r\n"
  1312. "Accept: application/x-rtsp-tunnelled\r\n"
  1313. "Pragma: no-cache\r\n"
  1314. "Cache-Control: no-cache\r\n",
  1315. sessioncookie);
  1316. ff_http_set_headers(rt->rtsp_hd, headers);
  1317. /* complete the connection */
  1318. if (url_connect(rt->rtsp_hd)) {
  1319. err = AVERROR(EIO);
  1320. goto fail;
  1321. }
  1322. /* POST requests */
  1323. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1324. err = AVERROR(EIO);
  1325. goto fail;
  1326. }
  1327. /* generate POST headers */
  1328. snprintf(headers, sizeof(headers),
  1329. "x-sessioncookie: %s\r\n"
  1330. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1331. "Pragma: no-cache\r\n"
  1332. "Cache-Control: no-cache\r\n"
  1333. "Content-Length: 32767\r\n"
  1334. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1335. sessioncookie);
  1336. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1337. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1338. /* Initialize the authentication state for the POST session. The HTTP
  1339. * protocol implementation doesn't properly handle multi-pass
  1340. * authentication for POST requests, since it would require one of
  1341. * the following:
  1342. * - implementing Expect: 100-continue, which many HTTP servers
  1343. * don't support anyway, even less the RTSP servers that do HTTP
  1344. * tunneling
  1345. * - sending the whole POST data until getting a 401 reply specifying
  1346. * what authentication method to use, then resending all that data
  1347. * - waiting for potential 401 replies directly after sending the
  1348. * POST header (waiting for some unspecified time)
  1349. * Therefore, we copy the full auth state, which works for both basic
  1350. * and digest. (For digest, we would have to synchronize the nonce
  1351. * count variable between the two sessions, if we'd do more requests
  1352. * with the original session, though.)
  1353. */
  1354. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1355. /* complete the connection */
  1356. if (url_connect(rt->rtsp_hd_out)) {
  1357. err = AVERROR(EIO);
  1358. goto fail;
  1359. }
  1360. } else {
  1361. /* open the tcp connection */
  1362. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1363. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1364. err = AVERROR(EIO);
  1365. goto fail;
  1366. }
  1367. rt->rtsp_hd_out = rt->rtsp_hd;
  1368. }
  1369. rt->seq = 0;
  1370. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1371. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1372. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1373. NULL, 0, NI_NUMERICHOST);
  1374. }
  1375. /* request options supported by the server; this also detects server
  1376. * type */
  1377. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1378. cmd[0] = 0;
  1379. if (rt->server_type == RTSP_SERVER_REAL)
  1380. av_strlcat(cmd,
  1381. /**
  1382. * The following entries are required for proper
  1383. * streaming from a Realmedia server. They are
  1384. * interdependent in some way although we currently
  1385. * don't quite understand how. Values were copied
  1386. * from mplayer SVN r23589.
  1387. * @param CompanyID is a 16-byte ID in base64
  1388. * @param ClientChallenge is a 16-byte ID in hex
  1389. */
  1390. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1391. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1392. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1393. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1394. sizeof(cmd));
  1395. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1396. if (reply->status_code != RTSP_STATUS_OK) {
  1397. err = AVERROR_INVALIDDATA;
  1398. goto fail;
  1399. }
  1400. /* detect server type if not standard-compliant RTP */
  1401. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1402. rt->server_type = RTSP_SERVER_REAL;
  1403. continue;
  1404. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1405. rt->server_type = RTSP_SERVER_WMS;
  1406. } else if (rt->server_type == RTSP_SERVER_REAL)
  1407. strcpy(real_challenge, reply->real_challenge);
  1408. break;
  1409. }
  1410. if (s->iformat)
  1411. err = rtsp_setup_input_streams(s, reply);
  1412. else
  1413. err = rtsp_setup_output_streams(s, host);
  1414. if (err)
  1415. goto fail;
  1416. do {
  1417. int lower_transport = ff_log2_tab[lower_transport_mask &
  1418. ~(lower_transport_mask - 1)];
  1419. err = make_setup_request(s, host, port, lower_transport,
  1420. rt->server_type == RTSP_SERVER_REAL ?
  1421. real_challenge : NULL);
  1422. if (err < 0)
  1423. goto fail;
  1424. lower_transport_mask &= ~(1 << lower_transport);
  1425. if (lower_transport_mask == 0 && err == 1) {
  1426. err = FF_NETERROR(EPROTONOSUPPORT);
  1427. goto fail;
  1428. }
  1429. } while (err);
  1430. rt->state = RTSP_STATE_IDLE;
  1431. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1432. return 0;
  1433. fail:
  1434. ff_rtsp_close_streams(s);
  1435. ff_rtsp_close_connections(s);
  1436. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1437. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1438. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1439. reply->status_code,
  1440. s->filename);
  1441. goto redirect;
  1442. }
  1443. ff_network_close();
  1444. return err;
  1445. }
  1446. #endif
  1447. #if CONFIG_RTSP_DEMUXER
  1448. static int rtsp_read_header(AVFormatContext *s,
  1449. AVFormatParameters *ap)
  1450. {
  1451. int ret;
  1452. ret = ff_rtsp_connect(s);
  1453. if (ret)
  1454. return ret;
  1455. if (ap->initial_pause) {
  1456. /* do not start immediately */
  1457. } else {
  1458. if (rtsp_read_play(s) < 0) {
  1459. ff_rtsp_close_streams(s);
  1460. ff_rtsp_close_connections(s);
  1461. return AVERROR_INVALIDDATA;
  1462. }
  1463. }
  1464. return 0;
  1465. }
  1466. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1467. uint8_t *buf, int buf_size)
  1468. {
  1469. RTSPState *rt = s->priv_data;
  1470. RTSPStream *rtsp_st;
  1471. fd_set rfds;
  1472. int fd, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1473. struct timeval tv;
  1474. for (;;) {
  1475. if (url_interrupt_cb())
  1476. return AVERROR(EINTR);
  1477. FD_ZERO(&rfds);
  1478. if (rt->rtsp_hd) {
  1479. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1480. FD_SET(tcp_fd, &rfds);
  1481. } else {
  1482. fd_max = 0;
  1483. tcp_fd = -1;
  1484. }
  1485. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1486. rtsp_st = rt->rtsp_streams[i];
  1487. if (rtsp_st->rtp_handle) {
  1488. /* currently, we cannot probe RTCP handle because of
  1489. * blocking restrictions */
  1490. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1491. if (fd > fd_max)
  1492. fd_max = fd;
  1493. FD_SET(fd, &rfds);
  1494. }
  1495. }
  1496. tv.tv_sec = 0;
  1497. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1498. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1499. if (n > 0) {
  1500. timeout_cnt = 0;
  1501. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1502. rtsp_st = rt->rtsp_streams[i];
  1503. if (rtsp_st->rtp_handle) {
  1504. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1505. if (FD_ISSET(fd, &rfds)) {
  1506. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1507. if (ret > 0) {
  1508. *prtsp_st = rtsp_st;
  1509. return ret;
  1510. }
  1511. }
  1512. }
  1513. }
  1514. #if CONFIG_RTSP_DEMUXER
  1515. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1516. RTSPMessageHeader reply;
  1517. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1518. if (ret < 0)
  1519. return ret;
  1520. /* XXX: parse message */
  1521. if (rt->state != RTSP_STATE_STREAMING)
  1522. return 0;
  1523. }
  1524. #endif
  1525. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1526. return FF_NETERROR(ETIMEDOUT);
  1527. } else if (n < 0 && errno != EINTR)
  1528. return AVERROR(errno);
  1529. }
  1530. }
  1531. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1532. uint8_t *buf, int buf_size)
  1533. {
  1534. RTSPState *rt = s->priv_data;
  1535. int id, len, i, ret;
  1536. RTSPStream *rtsp_st;
  1537. #ifdef DEBUG_RTP_TCP
  1538. dprintf(s, "tcp_read_packet:\n");
  1539. #endif
  1540. redo:
  1541. for (;;) {
  1542. RTSPMessageHeader reply;
  1543. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1544. if (ret == -1)
  1545. return -1;
  1546. if (ret == 1) /* received '$' */
  1547. break;
  1548. /* XXX: parse message */
  1549. if (rt->state != RTSP_STATE_STREAMING)
  1550. return 0;
  1551. }
  1552. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1553. if (ret != 3)
  1554. return -1;
  1555. id = buf[0];
  1556. len = AV_RB16(buf + 1);
  1557. #ifdef DEBUG_RTP_TCP
  1558. dprintf(s, "id=%d len=%d\n", id, len);
  1559. #endif
  1560. if (len > buf_size || len < 12)
  1561. goto redo;
  1562. /* get the data */
  1563. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1564. if (ret != len)
  1565. return -1;
  1566. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1567. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1568. return -1;
  1569. /* find the matching stream */
  1570. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1571. rtsp_st = rt->rtsp_streams[i];
  1572. if (id >= rtsp_st->interleaved_min &&
  1573. id <= rtsp_st->interleaved_max)
  1574. goto found;
  1575. }
  1576. goto redo;
  1577. found:
  1578. *prtsp_st = rtsp_st;
  1579. return len;
  1580. }
  1581. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1582. {
  1583. RTSPState *rt = s->priv_data;
  1584. int ret, len;
  1585. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1586. RTSPStream *rtsp_st;
  1587. /* get next frames from the same RTP packet */
  1588. if (rt->cur_transport_priv) {
  1589. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1590. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1591. } else
  1592. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1593. if (ret == 0) {
  1594. rt->cur_transport_priv = NULL;
  1595. return 0;
  1596. } else if (ret == 1) {
  1597. return 0;
  1598. } else
  1599. rt->cur_transport_priv = NULL;
  1600. }
  1601. /* read next RTP packet */
  1602. redo:
  1603. switch(rt->lower_transport) {
  1604. default:
  1605. #if CONFIG_RTSP_DEMUXER
  1606. case RTSP_LOWER_TRANSPORT_TCP:
  1607. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1608. break;
  1609. #endif
  1610. case RTSP_LOWER_TRANSPORT_UDP:
  1611. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1612. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1613. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1614. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1615. break;
  1616. }
  1617. if (len < 0)
  1618. return len;
  1619. if (len == 0)
  1620. return AVERROR_EOF;
  1621. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1622. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1623. } else {
  1624. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1625. if (ret < 0) {
  1626. /* Either bad packet, or a RTCP packet. Check if the
  1627. * first_rtcp_ntp_time field was initialized. */
  1628. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1629. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1630. /* first_rtcp_ntp_time has been initialized for this stream,
  1631. * copy the same value to all other uninitialized streams,
  1632. * in order to map their timestamp origin to the same ntp time
  1633. * as this one. */
  1634. int i;
  1635. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1636. RTPDemuxContext *rtpctx2 = rtsp_st->transport_priv;
  1637. if (rtpctx2 &&
  1638. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  1639. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1640. }
  1641. }
  1642. }
  1643. }
  1644. if (ret < 0)
  1645. goto redo;
  1646. if (ret == 1)
  1647. /* more packets may follow, so we save the RTP context */
  1648. rt->cur_transport_priv = rtsp_st->transport_priv;
  1649. return ret;
  1650. }
  1651. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1652. {
  1653. RTSPState *rt = s->priv_data;
  1654. int ret;
  1655. RTSPMessageHeader reply1, *reply = &reply1;
  1656. char cmd[1024];
  1657. if (rt->server_type == RTSP_SERVER_REAL) {
  1658. int i;
  1659. enum AVDiscard cache[MAX_STREAMS];
  1660. for (i = 0; i < s->nb_streams; i++)
  1661. cache[i] = s->streams[i]->discard;
  1662. if (!rt->need_subscription) {
  1663. if (memcmp (cache, rt->real_setup_cache,
  1664. sizeof(enum AVDiscard) * s->nb_streams)) {
  1665. snprintf(cmd, sizeof(cmd),
  1666. "Unsubscribe: %s\r\n",
  1667. rt->last_subscription);
  1668. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1669. cmd, reply, NULL);
  1670. if (reply->status_code != RTSP_STATUS_OK)
  1671. return AVERROR_INVALIDDATA;
  1672. rt->need_subscription = 1;
  1673. }
  1674. }
  1675. if (rt->need_subscription) {
  1676. int r, rule_nr, first = 1;
  1677. memcpy(rt->real_setup_cache, cache,
  1678. sizeof(enum AVDiscard) * s->nb_streams);
  1679. rt->last_subscription[0] = 0;
  1680. snprintf(cmd, sizeof(cmd),
  1681. "Subscribe: ");
  1682. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1683. rule_nr = 0;
  1684. for (r = 0; r < s->nb_streams; r++) {
  1685. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1686. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1687. if (!first)
  1688. av_strlcat(rt->last_subscription, ",",
  1689. sizeof(rt->last_subscription));
  1690. ff_rdt_subscribe_rule(
  1691. rt->last_subscription,
  1692. sizeof(rt->last_subscription), i, rule_nr);
  1693. first = 0;
  1694. }
  1695. rule_nr++;
  1696. }
  1697. }
  1698. }
  1699. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1700. ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
  1701. cmd, reply, NULL);
  1702. if (reply->status_code != RTSP_STATUS_OK)
  1703. return AVERROR_INVALIDDATA;
  1704. rt->need_subscription = 0;
  1705. if (rt->state == RTSP_STATE_STREAMING)
  1706. rtsp_read_play (s);
  1707. }
  1708. }
  1709. ret = rtsp_fetch_packet(s, pkt);
  1710. if (ret < 0)
  1711. return ret;
  1712. /* send dummy request to keep TCP connection alive */
  1713. if ((rt->server_type == RTSP_SERVER_WMS ||
  1714. rt->server_type == RTSP_SERVER_REAL) &&
  1715. (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1716. if (rt->server_type == RTSP_SERVER_WMS) {
  1717. ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
  1718. } else {
  1719. ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
  1720. }
  1721. }
  1722. return 0;
  1723. }
  1724. /* pause the stream */
  1725. static int rtsp_read_pause(AVFormatContext *s)
  1726. {
  1727. RTSPState *rt = s->priv_data;
  1728. RTSPMessageHeader reply1, *reply = &reply1;
  1729. if (rt->state != RTSP_STATE_STREAMING)
  1730. return 0;
  1731. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1732. ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
  1733. if (reply->status_code != RTSP_STATUS_OK) {
  1734. return -1;
  1735. }
  1736. }
  1737. rt->state = RTSP_STATE_PAUSED;
  1738. return 0;
  1739. }
  1740. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1741. int64_t timestamp, int flags)
  1742. {
  1743. RTSPState *rt = s->priv_data;
  1744. rt->seek_timestamp = av_rescale_q(timestamp,
  1745. s->streams[stream_index]->time_base,
  1746. AV_TIME_BASE_Q);
  1747. switch(rt->state) {
  1748. default:
  1749. case RTSP_STATE_IDLE:
  1750. break;
  1751. case RTSP_STATE_STREAMING:
  1752. if (rtsp_read_pause(s) != 0)
  1753. return -1;
  1754. rt->state = RTSP_STATE_SEEKING;
  1755. if (rtsp_read_play(s) != 0)
  1756. return -1;
  1757. break;
  1758. case RTSP_STATE_PAUSED:
  1759. rt->state = RTSP_STATE_IDLE;
  1760. break;
  1761. }
  1762. return 0;
  1763. }
  1764. static int rtsp_read_close(AVFormatContext *s)
  1765. {
  1766. RTSPState *rt = s->priv_data;
  1767. #if 0
  1768. /* NOTE: it is valid to flush the buffer here */
  1769. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1770. url_fclose(&rt->rtsp_gb);
  1771. }
  1772. #endif
  1773. ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
  1774. ff_rtsp_close_streams(s);
  1775. ff_rtsp_close_connections(s);
  1776. ff_network_close();
  1777. return 0;
  1778. }
  1779. AVInputFormat rtsp_demuxer = {
  1780. "rtsp",
  1781. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1782. sizeof(RTSPState),
  1783. rtsp_probe,
  1784. rtsp_read_header,
  1785. rtsp_read_packet,
  1786. rtsp_read_close,
  1787. rtsp_read_seek,
  1788. .flags = AVFMT_NOFILE,
  1789. .read_play = rtsp_read_play,
  1790. .read_pause = rtsp_read_pause,
  1791. };
  1792. #endif
  1793. static int sdp_probe(AVProbeData *p1)
  1794. {
  1795. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1796. /* we look for a line beginning "c=IN IP4" */
  1797. while (p < p_end && *p != '\0') {
  1798. if (p + sizeof("c=IN IP4") - 1 < p_end &&
  1799. av_strstart(p, "c=IN IP4", NULL))
  1800. return AVPROBE_SCORE_MAX / 2;
  1801. while (p < p_end - 1 && *p != '\n') p++;
  1802. if (++p >= p_end)
  1803. break;
  1804. if (*p == '\r')
  1805. p++;
  1806. }
  1807. return 0;
  1808. }
  1809. #define SDP_MAX_SIZE 8192
  1810. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1811. {
  1812. RTSPState *rt = s->priv_data;
  1813. RTSPStream *rtsp_st;
  1814. int size, i, err;
  1815. char *content;
  1816. char url[1024];
  1817. if (!ff_network_init())
  1818. return AVERROR(EIO);
  1819. /* read the whole sdp file */
  1820. /* XXX: better loading */
  1821. content = av_malloc(SDP_MAX_SIZE);
  1822. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1823. if (size <= 0) {
  1824. av_free(content);
  1825. return AVERROR_INVALIDDATA;
  1826. }
  1827. content[size] ='\0';
  1828. sdp_parse(s, content);
  1829. av_free(content);
  1830. /* open each RTP stream */
  1831. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1832. rtsp_st = rt->rtsp_streams[i];
  1833. ff_url_join(url, sizeof(url), "rtp", NULL,
  1834. inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
  1835. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1836. rtsp_st->sdp_ttl);
  1837. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1838. err = AVERROR_INVALIDDATA;
  1839. goto fail;
  1840. }
  1841. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1842. goto fail;
  1843. }
  1844. return 0;
  1845. fail:
  1846. ff_rtsp_close_streams(s);
  1847. ff_network_close();
  1848. return err;
  1849. }
  1850. static int sdp_read_close(AVFormatContext *s)
  1851. {
  1852. ff_rtsp_close_streams(s);
  1853. ff_network_close();
  1854. return 0;
  1855. }
  1856. AVInputFormat sdp_demuxer = {
  1857. "sdp",
  1858. NULL_IF_CONFIG_SMALL("SDP"),
  1859. sizeof(RTSPState),
  1860. sdp_probe,
  1861. sdp_read_header,
  1862. rtsp_fetch_packet,
  1863. sdp_read_close,
  1864. };